{
  "version": 3,
  "sources": ["../../../libs/helper-gib/src/constants.mts", "../../../libs/helper-gib/src/helpers/utils-helper.mts", "../../../libs/ts-gib/src/helper.mts", "../../../libs/ts-gib/src/V1/sha256v1.mts", "../../../libs/ts-gib/src/V1/types.mts", "../../../libs/ts-gib/src/V1/constants.mts", "../../../libs/ts-gib/src/V1/transforms/transform-helper.mts", "../../../libs/ts-gib/src/V1/transforms/fork.mts", "../../../libs/ts-gib/src/V1/transforms/mut8.mts", "../../../libs/ts-gib/src/V1/transforms/rel8.mts", "../../../libs/ts-gib/src/V1/v1-helper.mts", "../../../libs/ts-gib/src/V1/validate-helper.mts", "../../../libs/ts-gib/src/V1/factory.mts", "../../../libs/core-gib/src/core-constants.mts", "../../../libs/core-gib/src/common/other/other-types.mts", "../../../libs/core-gib/src/witness/robbot/robbot-constants.mts", "../../../libs/core-gib/src/witness/space/space-constants.mts", "../../../libs/core-gib/src/common/root/root-constants.mts", "../../../libs/core-gib/src/common/tag/tag-constants.mts", "../../../libs/core-gib/src/common/other/other-constants.mts", "../../../libs/core-gib/src/common/other/ibgib-constants.mts", "../../../libs/core-gib/src/witness/app/app-constants.mts", "../../../libs/core-gib/src/witness/space/bootstrap/bootstrap-constants.mts", "../../../libs/encrypt-gib/src/types.mts", "../../../libs/encrypt-gib/src/helper.mts", "../../../libs/encrypt-gib/src/constants.mts", "../../../libs/encrypt-gib/src/common/encrypt-decrypt-common.mts", "../../../libs/encrypt-gib/src/stream-mode/encrypt-from-hex-stream-mode.mts", "../../../libs/encrypt-gib/src/stream-mode/decrypt-to-hex-stream-mode.mts", "../../../libs/encrypt-gib/src/stream-mode/decrypt-stream-mode.mts", "../../../libs/encrypt-gib/src/stream-mode/encrypt-stream-mode.mts", "../../../libs/encrypt-gib/src/block-mode/encrypt-from-hex-block-mode.mts", "../../../libs/encrypt-gib/src/block-mode/decrypt-to-hex-block-mode.mts", "../../../libs/encrypt-gib/src/block-mode/decrypt-block-mode.mts", "../../../libs/encrypt-gib/src/block-mode/encrypt-block-mode.mts", "../../../libs/encrypt-gib/src/encrypt-decrypt.mts", "../../../libs/core-gib/src/common/encrypt/encrypt-constants.mts", "../../../libs/core-gib/src/witness/space/space-types.mts", "../../../libs/core-gib/src/common/form/form-helper.mts", "../../../libs/core-gib/src/witness/witness-form-builder.mts", "../../../libs/core-gib/src/witness/app/app-helper.mts", "../../../libs/core-gib/src/witness/app/chat-app/chat-app-types.mts", "../../../libs/core-gib/src/witness/app/raw-app/raw-app-types.mts", "../../../libs/core-gib/src/witness/app/todo-app/todo-app-types.mts", "../../../libs/core-gib/src/witness/space/bootstrap/bootstrap-helper.mts", "../../../libs/core-gib/src/common/meta-stone/meta-stone-constants.mts", "../../../libs/core-gib/src/common/meta-stone/meta-stone-helper.mts", "../../../libs/core-gib/src/witness/witness-constants.mts", "../../../libs/core-gib/src/witness/space/space-helper.mts", "../../../libs/core-gib/src/common/other/ibgib-helper.mts", "../src/constants.mts", "../../../libs/core-gib/src/common/other/other-helper.web.mts", "../../../libs/core-gib/src/common/import-export/import-export-constants.mts", "../../../libs/core-gib/src/common/import-export/import-export-helper.web.mts", "../../../libs/web-gib/src/constants.mts", "../../../libs/web-gib/src/storage/storage-helpers.web.mts", "../../../libs/web-gib/src/ui/ui-constants.mts", "../../../libs/web-gib/src/ui/ui-helpers.mts", "../../../libs/web-gib/src/helpers.mts", "../../../libs/web-gib/src/helpers.web.mts", "../../../libs/web-gib/src/ui/component/ibgib-component-service.mts", "../src/common/app-constants.mts", "../src/ui/shell/shell-constants.mts", "../src/components/canvas/canvas.html", "../src/components/canvas/canvas.css", "../src/styles.css", "../src/root.css", "../../../libs/core-gib/src/common/other/graph-helper.mts", "../../../libs/core-gib/src/timeline/timeline-api.mts", "../../../libs/core-gib/src/common/comment/comment-constants.mts", "../../../libs/core-gib/src/common/comment/comment-helper.mts", "../../../libs/web-gib/src/witness/agent/agent-constants.mts", "../../../libs/web-gib/src/api/commands/command-constants.mts", "../../../libs/web-gib/src/api/api-index.mts", "../../../libs/web-gib/src/api/commands/command-service-v1.mts", "../../../libs/web-gib/src/api/api-constants.mts", "../../../libs/core-gib/src/common/tag/tag-helper.mts", "../../../libs/web-gib/src/witness/agent/agents-service-v1.mts", "../../../libs/web-gib/src/witness/agent/gemini/gemini-constants.mts", "../../../libs/web-gib/src/witness/agent/agent-types.mts", "../../../libs/web-gib/node_modules/@google/genai/src/_base_url.ts", "../../../libs/web-gib/node_modules/@google/genai/src/_common.ts", "../../../libs/web-gib/node_modules/@google/genai/src/_base_transformers.ts", "../../../libs/web-gib/node_modules/@google/genai/src/converters/_operations_converters.ts", "../../../libs/web-gib/node_modules/@google/genai/src/types.ts", "../../../libs/web-gib/node_modules/@google/genai/src/_transformers.ts", "../../../libs/web-gib/node_modules/@google/genai/src/converters/_batches_converters.ts", "../../../libs/web-gib/node_modules/@google/genai/src/pagers.ts", "../../../libs/web-gib/node_modules/@google/genai/src/batches.ts", "../../../libs/web-gib/node_modules/@google/genai/src/converters/_caches_converters.ts", "../../../libs/web-gib/node_modules/@google/genai/src/caches.ts", "../../../libs/web-gib/node_modules/@google/genai/src/chats.ts", "../../../libs/web-gib/node_modules/@google/genai/src/errors.ts", "../../../libs/web-gib/node_modules/@google/genai/src/converters/_files_converters.ts", "../../../libs/web-gib/node_modules/@google/genai/src/files.ts", "../../../libs/web-gib/node_modules/@google/genai/src/converters/_live_converters.ts", "../../../libs/web-gib/node_modules/@google/genai/src/converters/_models_converters.ts", "../../../libs/web-gib/node_modules/@google/genai/src/converters/_filesearchstores_converters.ts", "../../../libs/web-gib/node_modules/@google/genai/src/_api_client.ts", "../../../libs/web-gib/node_modules/@google/genai/src/mcp/_mcp.ts", "../../../libs/web-gib/node_modules/@google/genai/src/music.ts", "../../../libs/web-gib/node_modules/@google/genai/src/live.ts", "../../../libs/web-gib/node_modules/@google/genai/src/_afc.ts", "../../../libs/web-gib/node_modules/@google/genai/src/models.ts", "../../../libs/web-gib/node_modules/@google/genai/src/operations.ts", "../../../libs/web-gib/node_modules/@google/genai/src/converters/_tokens_converters.ts", "../../../libs/web-gib/node_modules/@google/genai/src/tokens.ts", "../../../libs/web-gib/node_modules/@google/genai/src/converters/_documents_converters.ts", "../../../libs/web-gib/node_modules/@google/genai/src/documents.ts", "../../../libs/web-gib/node_modules/@google/genai/src/filesearchstores.ts", "../../../libs/web-gib/node_modules/@google/genai/src/interactions/internal/utils/uuid.ts", "../../../libs/web-gib/node_modules/@google/genai/src/interactions/internal/errors.ts", "../../../libs/web-gib/node_modules/@google/genai/src/interactions/core/error.ts", "../../../libs/web-gib/node_modules/@google/genai/src/interactions/internal/utils/values.ts", "../../../libs/web-gib/node_modules/@google/genai/src/interactions/internal/utils/sleep.ts", "../../../libs/web-gib/node_modules/@google/genai/src/interactions/version.ts", "../../../libs/web-gib/node_modules/@google/genai/src/interactions/internal/detect-platform.ts", "../../../libs/web-gib/node_modules/@google/genai/src/interactions/internal/shims.ts", "../../../libs/web-gib/node_modules/@google/genai/src/interactions/internal/request-options.ts", "../../../libs/web-gib/node_modules/@google/genai/src/interactions/internal/uploads.ts", "../../../libs/web-gib/node_modules/@google/genai/src/interactions/internal/to-file.ts", "../../../libs/web-gib/node_modules/@google/genai/src/interactions/core/resource.ts", "../../../libs/web-gib/node_modules/@google/genai/src/interactions/internal/utils/path.ts", "../../../libs/web-gib/node_modules/@google/genai/src/interactions/resources/interactions.ts", "../../../libs/web-gib/node_modules/@google/genai/src/interactions/internal/utils/bytes.ts", "../../../libs/web-gib/node_modules/@google/genai/src/interactions/internal/decoders/line.ts", "../../../libs/web-gib/node_modules/@google/genai/src/interactions/internal/utils/log.ts", "../../../libs/web-gib/node_modules/@google/genai/src/interactions/core/streaming.ts", "../../../libs/web-gib/node_modules/@google/genai/src/interactions/internal/parse.ts", "../../../libs/web-gib/node_modules/@google/genai/src/interactions/core/api-promise.ts", "../../../libs/web-gib/node_modules/@google/genai/src/interactions/internal/headers.ts", "../../../libs/web-gib/node_modules/@google/genai/src/interactions/internal/utils/env.ts", "../../../libs/web-gib/node_modules/@google/genai/src/interactions/client.ts", "../../../libs/web-gib/node_modules/@google/genai/src/converters/_tunings_converters.ts", "../../../libs/web-gib/node_modules/@google/genai/src/tunings.ts", "../../../libs/web-gib/node_modules/@google/genai/src/web/_browser_downloader.ts", "../../../libs/web-gib/node_modules/@google/genai/src/cross/_cross_uploader.ts", "../../../libs/web-gib/node_modules/@google/genai/src/web/_browser_uploader.ts", "../../../libs/web-gib/node_modules/@google/genai/src/web/_browser_websocket.ts", "../../../libs/web-gib/node_modules/@google/genai/src/web/_web_auth.ts", "../../../libs/web-gib/node_modules/@google/genai/src/web/web_client.ts", "../../../libs/web-gib/src/witness/agent/gemini/gemini-helpers.mts", "../../../libs/web-gib/src/witness/agent/function-info/function-info-one-file.mts", "../../../libs/core-gib/src/witness/light-witness-base-v1.mts", "../../../libs/core-gib/src/common/error/error-constants.mts", "../../../libs/core-gib/src/common/error/error-helper.mts", "../../../libs/core-gib/src/witness/anonymous-fn/anonymous-fn-constants.mts", "../../../libs/core-gib/src/witness/anonymous-fn/anonymous-fn-helper.mts", "../../../libs/core-gib/src/witness/anonymous-fn/anonymous-fn-v1.mts", "../../../libs/core-gib/src/common/pubsub/observer/observer-helper.mts", "../../../libs/core-gib/src/witness/witness-base-v1.mts", "../../../libs/core-gib/src/witness/witness-with-context/witness-with-context-base-v1.mts", "../../../libs/core-gib/src/common/pubsub/subject/subject-constants.mts", "../../../libs/core-gib/src/common/pubsub/observable/observable-constants.mts", "../../../libs/core-gib/src/common/pubsub/observable/observable-types.mts", "../../../libs/core-gib/src/common/pubsub/observer/observer-types.mts", "../../../libs/core-gib/src/common/pubsub/subject/subject-types.mts", "../../../libs/core-gib/src/witness/witness-helper.mts", "../../../libs/core-gib/src/witness/factory/witness-factory-base.mts", "../../../libs/core-gib/src/witness/factory/dynamic-form-factory-base.mts", "../../../libs/core-gib/src/common/pubsub/subscription/subscription-constants.mts", "../../../libs/core-gib/src/common/pubsub/subscription/subscription-types.mts", "../../../libs/core-gib/src/common/pubsub/observable/observable-helper.mts", "../../../libs/core-gib/src/common/pubsub/subscription/subscription-v1.mts", "../../../libs/core-gib/src/common/pubsub/subscription/subscription-helper.mts", "../../../libs/core-gib/src/common/pubsub/observable/observable-event/observable-event-constants.mts", "../../../libs/core-gib/src/common/pubsub/observable/observable-event/observable-event-helper.mts", "../../../libs/core-gib/src/common/pubsub/observable/observable-base-v1.mts", "../../../libs/core-gib/src/common/pubsub/subject/subject-v1.mts", "../../../libs/core-gib/src/common/pubsub/subject/subject-helper.mts", "../../../libs/web-gib/src/witness/live-proxy-ibgib/live-proxy-ibgib-one-file.mts", "../../../libs/web-gib/src/witness/agent/agent-one-file.mts", "../../../libs/web-gib/src/witness/agent/gemini/agent-witness-gemini-v1.mts", "../../../libs/web-gib/src/witness/agent/gemini/gemini-agent-factory.mts", "../../../libs/web-gib/src/witness/agent/agent-helpers.mts", "../../../libs/web-gib/src/api/commands/chat/tell-user.mts", "../../../libs/web-gib/src/common/settings/settings-constants.mts", "../../../libs/web-gib/src/common/settings/settings-helpers.mts", "../../../libs/web-gib/src/ui/component/ibgib-dynamic-component-bases.mts", "../src/render/render-constants.mts", "../src/render/render-service-v1.mts", "../src/api/commands/renderable/path-command/path-command-types.mts", "../src/api/commands/renderable/renderable-constants.mts", "../src/api/commands/renderable/renderable-create.mts", "../../../libs/web-gib/src/api/commands/command-helpers.mts", "../src/api/commands/renderable/renderable-destroy.mts", "../src/api/commands/renderable/renderable-get-all.mts", "../src/api/commands/renderable/renderable-get.mts", "../src/api/commands/renderable/renderable-update.mts", "../src/api/commands/renderable/renderable-index.mts", "../../../libs/web-gib/src/agent-texts/common-agent-texts.mts", "../src/agent-texts/common-agent-texts.mts", "../src/agent-texts/canvas-agent-texts.mts", "../../../libs/web-gib/src/app-bootstrap/init-orchestration.mts", "../src/AUTO-GENERATED-version.mts", "../src/helpers.web.mts", "../src/components/canvas/canvas-component-one-file.mts", "../src/components/projects/projects.html", "../src/components/projects/projects.css", "../../../libs/web-gib/src/common/project/project-constants.mts", "../../../libs/web-gib/src/common/project/project-helper.mts", "../../../libs/web-gib/src/common/project/project-types.mts", "../../../libs/web-gib/src/api/commands/chat/get-context-info.mts", "../../../libs/web-gib/src/api/commands/chat/hello-world.mts", "../../../libs/web-gib/src/api/commands/chat/chat-index.mts", "../../../libs/web-gib/src/api/commands/ibgib/get-ibgibs.mts", "../../../libs/web-gib/src/api/commands/ibgib/mut8-ibgib.mts", "../../../libs/web-gib/src/api/commands/ibgib/ibgib-index.mts", "../../../libs/web-gib/src/api/commands/text/text-edit.mts", "../../../libs/web-gib/src/api/commands/text/text-index.mts", "../../../libs/web-gib/src/api/commands/ui/update-css-variables.mts", "../../../libs/web-gib/src/common/project/project-agent-functions.mts", "../src/agent-texts/project-agent-texts.mts", "../src/components/projects/project/project.html", "../src/components/projects/project/project.css", "../src/components/common/raw/raw.html", "../src/components/common/raw/raw.css", "../src/components/common/raw/raw-component-one-file.mts", "../src/components/common/text-editor/text-editor.html", "../src/components/common/text-editor/text-editor.css", "../src/components/common/text-editor/text-editor-component-one-file.mts", "../src/agent-texts/project-child-text-agent-texts.mts", "../src/common/minigame/typing/typing-constants.mts", "../src/common/minigame/minigame-constants.mts", "../src/common/minigame/minigame-types.mts", "../src/common/text-analysis/analysis-engine-constants.mts", "../src/common/text-analysis/analysis-engine.mts", "../src/common/text-analysis/corpus-analyzer.mts", "../src/common/minigame/typing/sentence-helper.mts", "../src/common/minigame/typing/typing-helper.mts", "../src/common/minigame/minigame-helper.mts", "../src/components/minigame/minigame.html", "../src/components/minigame/minigame.css", "../src/components/minigame/typing/typing.html", "../src/components/minigame/typing/typing.css", "../src/api/commands/minigame/minigame-builder-validate-and-ready.mts", "../src/api/commands/minigame/minigame-builder-edit-stimuli.mts", "../src/components/minigame/typing/typing-component-one-file.mts", "../src/common/minigame/metronome.mts", "../src/components/minigame/minigame-component-one-file.mts", "../src/agent-texts/minigame-agent-texts.mts", "../src/api/commands/minigame/minigame-builder-start.mts", "../src/components/projects/project/project-component-one-file.mts", "../src/agent-texts/projects-agent-texts.mts", "../src/components/projects/projects-component-one-file.mts", "../src/components/common/breadcrumb/breadcrumb.html", "../src/components/common/breadcrumb/breadcrumb.css", "../src/components/common/breadcrumb/breadcrumb-component-one-file.mts", "../src/components/common/input/input.html", "../src/components/common/input/input.css", "../../../libs/helper-gib/src/rcli/rcli-constants.mts", "../../../libs/encrypt-gib/src/rcli/rcli-constants.mts", "../src/witness/app/blank-canvas/blank-canvas-constants.mts", "../src/components/common/input/input-component-one-file.mts", "../src/components/chronologys/chronologys.html", "../src/components/chronologys/chronologys.css", "../src/components/common/chronology/chronology.html", "../src/components/common/chronology/chronology.css", "../src/components/common/chronology/chronology-component-one-file.mts", "../src/components/chronologys/chronologys-component-one-file.mts", "../src/components/projects/projects-explorer/projects-explorer.html", "../src/components/projects/projects-explorer/projects-explorer.css", "../src/components/common/explorer-item/explorer-item.html", "../src/components/common/explorer-item/explorer-item.css", "../src/components/common/explorer-item/explorer-item-component-one-file.mts", "../src/components/projects/projects-explorer/projects-explorer-component-one-file.mts", "../src/components/web1/about/about.html", "../src/components/web1/web1-common.css", "../src/components/web1/about/about.css", "../../../libs/web-gib/src/api/commands/ui/ui-index.mts", "../../../libs/web-gib/src/witness/agent/agent-one-file.app.mts", "../src/components/web1/web1-component-base-one-file.mts", "../src/components/web1/about/web1-about-component-one-file.mts", "../src/components/web1/blog/blog.html", "../src/components/web1/blog/blog.css", "../src/components/web1/blog/web1-blog-component-one-file.mts", "../src/components/web1/contact/contact.html", "../src/components/web1/contact/contact.css", "../src/components/web1/contact/web1-contact-component-one-file.mts", "../src/components/web1/faq/faq.html", "../src/components/web1/faq/faq.css", "../src/components/web1/faq/web1-faq-component-one-file.mts", "../src/components/web1/funding/funding.html", "../src/components/web1/funding/funding.css", "../src/components/web1/funding/web1-funding-component-one-file.mts", "../src/components/web1/home/home.html", "../src/components/web1/home/home.css", "../src/components/web1/home/web1-home-component-one-file.mts", "../src/components/web1/links/links.html", "../src/components/web1/links/links.css", "../src/components/web1/links/web1-links-component-one-file.mts", "../src/components/web1/challenges/challenges.html", "../src/components/web1/challenges/challenges.css", "../src/components/web1/challenges/web1-challenges-component-one-file.mts", "../src/components/web1/about-projects/about-projects.html", "../src/components/web1/about-projects/about-projects.css", "../src/components/web1/about-projects/web1-about-projects-component-one-file.mts", "../src/components/web1/web1-constants.mts", "../src/ui/shell/app-shell-service.mts", "../src/ui/router/router-one-file.mts"],
  "sourcesContent": ["\n/**\n * @internal\n * Used internally for logging.\n */\nexport const HELPER_LOG_A_LOT = false;\n\nexport const DEFAULT_UUID = undefined;\nexport const UUID_REGEXP = /^[a-zA-Z0-9_\\-.]{1,256}$/;\n\n/**\n * regular expression for a classname.\n *\n * Used in witnesses atm.\n */\nexport const CLASSNAME_REGEXP = /^[a-zA-Z0-9_]{1,255}$/;\n\n/**\n * capture groups for expected (in various places). will return `null` if\n * does not have an id section like `(E: abcdef32chars)`.\n */\nexport const ERROR_MSG_WITH_ID_CAPTURE_GROUPS_REGEXP = /^(\\[.+\\])?\\s?(\\(UNEXPECTED\\)|\\(unexpected\\))?(.+)(\\([EIWeiw]: [a-fA-F\\d]{32}\\))(\\(UNEXPECTED\\)|\\(unexpected\\))?$/;\nexport const ERROR_MSG_LOCATION_ONLY_REGEXP = /^(\\[.+\\]).+$/;\n\n/**\n * RegExp for a hexadecimal string of length 32\n */\nexport const HEXADECIMAL_HASH_STRING_REGEXP_32 = /^[0-9a-fA-F]{32}$/;\n/**\n * RegExp for a hexadecimal string of length 64\n */\nexport const HEXADECIMAL_HASH_STRING_REGEXP_64 = /^[0-9a-fA-F]{64}$/;\n\n/**\n * When you have a comma-delimited list of word characters and maybe some specials.\n *\n * @see {@link COMMA_DELIMITED_SIMPLE_STRINGS_REGEXP_DESCRIPTION}\n */\nexport const COMMA_DELIMITED_SIMPLE_STRINGS_REGEXP = /^[\\w\\-]+(,?[\\w+\\-])*$/;\n/**\n * Human-readable description to {@link COMMA_DELIMITED_SIMPLE_STRINGS_REGEXP}\n *\n * It is meant to be used with validation errors helper.\n *\n * **WARNING** obviously this can get out of sync.\n */\nexport const COMMA_DELIMITED_SIMPLE_STRINGS_REGEXP_DESCRIPTION = 'text must only be comma-delimited, no-spaces simple words like \"comment,link,pic,x,under_score,hyphens-ok-too\"';\n\n/**\n * When expressing ibgib data paths, this will be used as the delimiter\n * to indicate a sub-object.\n *\n * # notes\n *\n * This should be used with the understanding that having overly-complex data\n * maps is an indication that the ibgib may possibly be better designed as\n * multiple ibgibs linked via their rel8ns.\n *\n * That said, I think it will be common for grouping settings, especially\n * mapping from external sources (API, SDK, etc.).\n */\nexport const DEFAULT_DATA_PATH_DELIMITER = '/';\n\n/**\n * If a string has only non-alphanumerics, this may be returned when getting a safer substring.\n */\nexport const ONLY_HAS_NON_ALPHANUMERICS = '_nonalphanumerics_';\n", "import { DEFAULT_DATA_PATH_DELIMITER, HELPER_LOG_A_LOT, ONLY_HAS_NON_ALPHANUMERICS } from \"../constants.mjs\";\n\nconst logalot = HELPER_LOG_A_LOT || false;\n\nlet crypto: any = globalThis.crypto;\nlet { subtle } = crypto;\n\nexport type HashAlgorithm = 'SHA-256' | 'SHA-512';\nexport const HashAlgorithm: { [key: string]: HashAlgorithm } = {\n    'sha_256': 'SHA-256' as HashAlgorithm,\n    'sha_512': 'SHA-512' as HashAlgorithm,\n}\n\nexport function clone(obj: any) {\n    return JSON.parse(JSON.stringify(obj));\n}\nexport function getTimestamp(date?: Date) {\n    return (date ?? new Date()).toUTCString();\n}\n\n/**\n * Simple hash function.\n *\n * NOTE:\n *   This is not used for ibGib.gib values (ATOW)\n *   but rather as a helper function for generating random UUIDs.\n *\n * @param s string to hash\n * @param algorithm to use, currently only 'SHA-256'\n */\nexport async function hash({\n    s,\n    algorithm = 'SHA-256',\n}: {\n    s: string,\n    algorithm?: HashAlgorithm,\n}): Promise<string> {\n    if (!s) { return ''; }\n\n    try {\n        const validAlgorithms = Object.values(HashAlgorithm);\n        if (!validAlgorithms.includes(algorithm)) {\n            throw new Error(`Only ${validAlgorithms} implemented (E: 73cb52cd4d7f70c3415fdf695ba6ba23)`);\n        }\n        const msgUint8 = new TextEncoder().encode(s);\n        const buffer = await subtle.digest(algorithm, msgUint8);\n        const asArray = Array.from(new Uint8Array(buffer));\n        return asArray.map(b => b.toString(16).padStart(2, '0')).join('');\n    } catch (error) {\n        console.error(extractErrorMsg(error.message));\n        throw error;\n        // return ''; // why had I decided to return an empty string on error?\n    }\n}\n\n/**\n * Simple func to generate UUID (sha-256 hash basically).\n *\n * @param seedSize size of seed for UUID generation\n */\nexport async function getUUID(seedSize = 64): Promise<string> {\n    let uuid: string = '';\n    if (seedSize < 32) { throw new Error(`Seed size must be at least 32`); }\n    if (!globalThis.crypto) { throw new Error(`Cannot create UUID, as unknown crypto library version. If using node.js, v19+ is required. (E: c02cee3fd8a94f678d3f4ebe9dc49797)`); }\n\n    const values = crypto.getRandomValues(new Uint8Array(16));\n    uuid = await hash({ s: values.join('') });\n\n    if (!uuid) { throw new Error(`Did not create UUID...hmm...`); }\n\n    return uuid;\n}\n\n/**\n * Syntactic sugar for JSON.stringify(obj, null, 2);\n *\n * @param obj to pretty stringify\n */\nexport function pretty(obj: any): string {\n    return JSON.stringify(obj, null, 2);\n}\n\n/**\n * Just delays given number of ms.\n *\n * @param ms milliseconds to delay\n */\nexport async function delay(ms: number): Promise<void> {\n    return new Promise<void>(resolve => {\n        setTimeout(() => {\n            resolve();\n        }, ms);\n    });\n}\n\n/**\n * extracts the error message from an error object/string/falsy arg.\n *\n * ## notes\n *\n * * some libs throw errors, some throw just strings.\n * * who knows what else it could be.\n *\n * ## todo\n *\n * * extract inner errors/causes if we ever use this function extensively.\n *\n * @param error the error object in the catch area of the try..catch block.\n * @returns error.message if it's a string, error itself if it's a string, or canned error messages if it's falsy or none of the above.\n */\nexport function extractErrorMsg(error: any): string {\n    if (!error && error !== 0) {\n        return '[error is falsy]';\n    } else if (typeof error === 'string') {\n        return error;\n    } else if (typeof error.message === 'string') {\n        return error.message;\n    } else if (typeof error === 'number') {\n        return JSON.stringify(error);\n    } else if (!!error.error) {\n        // the caller has used the \"wrong\" signature type\n        console.warn(`[${extractErrorMsg.name}] this fn takes the raw error object. no destructure required. change your call from extractErrorMsg({error}) to extractErrorMsg(error). (W: ea49af5fd76d4b80a55a108d73a3e9b4)`);\n        return extractErrorMsg(error.error);\n    } else {\n        return `[error is not a string and error.message is not a string. typeof error: ${typeof error} (E: d5a7723ca59646838308bc9e53a43134)]`;\n    }\n}\n\nexport function groupBy<TItem>({\n    items,\n    keyFn,\n}: {\n    items: TItem[],\n    keyFn: (x: TItem) => string,\n}): { [key: string]: TItem[] } {\n    const lc = `[${groupBy.name}]`;\n    try {\n        const result: { [key: string]: TItem[] } = {};\n        for (let i = 0; i < items.length; i++) {\n            const item = items[i];\n            const key = keyFn(item);\n            result[key] = [...(result[key] ?? []), item];\n        }\n        return result;\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    }\n}\n\n\n/**\n * Just trying to centralize and standardize regular expressions here...\n */\nexport function getRegExp({\n    min,\n    max,\n    chars,\n    noSpaces,\n}: {\n    min?: number,\n    max?: number,\n    chars?: string,\n    noSpaces?: boolean,\n}): RegExp {\n    min = min ?? 1;\n    max = max ?? 999999999999;\n    chars = chars ?? '';\n\n    return noSpaces ?\n        new RegExp(`^[\\\\w${chars}]{${min},${max}}$`) :\n        new RegExp(`^[\\\\w\\\\s${chars}]{${min},${max}}$`);\n}\n\n/**\n * syntactic sugar for `(new Date()).getTime().toString()`\n * @returns ticks string\n */\nexport function getTimestampInTicks(timestamp?: string): string {\n    let date: Date;\n    if (timestamp) {\n        date = new Date(timestamp);\n        if (date.toString() === \"Invalid Date\") {\n            throw new Error(`invalid date created by timestamp (${timestamp}) (E: cbd6aeefe00708184e276ea3c2532b22)`);\n        }\n    } else {\n        date = new Date();\n    }\n    return date.getTime().toString();\n}\n\n/**\n * ## requires\n * at least either `startDate` or one of the intervals to be truthy.\n *\n * ## thanks\n *\n * https://stackoverflow.com/questions/8609261/how-to-determine-one-year-from-now-in-javascript\n *\n * ## tested manually eek\n```\nconsole.log(new Date().toUTCString());\n// Mon, 14 Feb 2022 14:19:32 GMT\nconsole.log(getExpirationUTCString({years: 1}));\n// Tue, 14 Feb 2023 14:19:32 GMT\nconsole.log(getExpirationUTCString({months: 13}));\n// Tue, 14 Mar 2023 13:19:32 GMT\nconsole.log(getExpirationUTCString({days: 365}));\n// Tue, 14 Feb 2023 14:19:32 GMT\nconsole.log(getExpirationUTCString({days: 45}));\n// Thu, 31 Mar 2022 13:19:32 GMT\nconsole.log(getExpirationUTCString({years: 1, days: 45, hours: 25, seconds: 70}));\n// Sat, 01 Apr 2023 14:20:42 GMT\nconsole.log(getExpirationUTCString({days: 10, hours: 10, seconds: 10}));\n// Fri, 25 Feb 2022 00:19:42 GMT\nconsole.log(getExpirationUTCString({years: 1, days: 45, hours: 25, seconds: 70}));\n// Sat, 01 Apr 2023 14:20:42 GMT\nconsole.log(getExpirationUTCString({years: 1, days: 45, hours: 25, seconds: 35}));\n// Sat, 01 Apr 2023 14:20:07 GMT\n```\n */\nexport function getExpirationUTCString({\n    startDate,\n    years,\n    months,\n    days,\n    hours,\n    seconds,\n}: {\n    startDate?: Date,\n    years?: number,\n    months?: number,\n    days?: number,\n    hours?: number,\n    seconds?: number,\n}): string {\n    const lc = `[${getExpirationUTCString.name}]`;\n    try {\n        return addTimeToDate({\n            startDate, years, months, days, hours, seconds,\n        }).toUTCString();\n    } catch (error) {\n        console.log(`${lc} ${error.message}`);\n        throw error;\n    }\n}\n\nexport function addTimeToDate({\n    startDate,\n    years,\n    months,\n    days,\n    hours,\n    seconds,\n}: {\n    startDate?: Date,\n    years?: number,\n    months?: number,\n    days?: number,\n    hours?: number,\n    seconds?: number,\n}): Date {\n    const lc = `[${addTimeToDate.name}]`;\n    try {\n        if (!startDate && !years && !months && !days && !hours && !seconds) {\n            // throw here because otherwise we would return an expiration\n            // timestamp string with now as the expiration, which doesn't make\n            // sense.\n            throw new Error(`either startDate or a time interval required. (E: 30248f8b306f443ab036fa8c313c50d8)`);\n        }\n\n        // don't want to mutate the incoming date\n        startDate = startDate ?\n            new Date(startDate) :\n            new Date(); // default to now\n\n        /** incoming years/months/days/hours/seconds to add to start date */\n        let intervalToAdd: number;\n        /** start date + interval in ticks, before assigning to Date obj */\n        let newDateTicks: number;\n\n        if (years) {\n            intervalToAdd = startDate.getFullYear() + years;\n            newDateTicks = startDate.setFullYear(intervalToAdd);\n            // call recursively for other interval args (if any)\n            return addTimeToDate({\n                startDate: new Date(newDateTicks),\n                months, days, hours, seconds, // all but years (just set)\n            })\n        } else if (months) {\n            intervalToAdd = startDate.getMonth() + months;\n            newDateTicks = startDate.setMonth(intervalToAdd);\n            // call recursively for other interval args (if any)\n            return addTimeToDate({\n                startDate: new Date(newDateTicks),\n                years, days, hours, seconds, // all but months (just set)\n            })\n        } else if (days) {\n            intervalToAdd = startDate.getDate() + days;\n            newDateTicks = startDate.setDate(intervalToAdd);\n            // call recursively for other interval args (if any)\n            return addTimeToDate({\n                startDate: new Date(newDateTicks),\n                years, months, hours, seconds, // all but days (just set)\n            })\n        } else if (hours) {\n            intervalToAdd = startDate.getHours() + hours;\n            newDateTicks = startDate.setHours(intervalToAdd);\n            // call recursively for other interval args (if any)\n            return addTimeToDate({\n                startDate: new Date(newDateTicks),\n                years, months, days, seconds, // all but hours (just set)\n            })\n        } else if (seconds) {\n            intervalToAdd = startDate.getSeconds() + seconds;\n            newDateTicks = startDate.setSeconds(intervalToAdd);\n            // call recursively for other interval args (if any)\n            return addTimeToDate({\n                startDate: new Date(newDateTicks),\n                years, months, days, hours, // all but seconds (just set)\n            })\n        } else {\n            // we've called our function recursively and all intervals args\n            // falsy now, so startDate is the output date.\n            return startDate;\n        }\n    } catch (error) {\n        console.log(`${lc} ${error.message}`);\n        throw error;\n    }\n}\n\nexport function isExpired({\n    expirationTimestampUTC,\n}: {\n    expirationTimestampUTC: string,\n}): boolean {\n    const lc = `[${isExpired.name}]`;\n    try {\n        if (!expirationTimestampUTC) { throw new Error(`expirationTimestampUTC required (E: 5eeb1e29f93d64f70c71a8112080a222)`); }\n\n        let expirationDate = new Date(expirationTimestampUTC);\n        if (expirationDate.toUTCString() === \"Invalid Date\") { throw new Error(`invalid expirationTimestampUTC: ${expirationTimestampUTC} (E: 66a1a165bcf1f9336fe78856ab777822)`); }\n\n        const now = new Date();\n        const expired = expirationDate < now;\n        return expired;\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    }\n}\n\n/**\n * Creates a new array that is a unique set of incoming `arr`.\n * @param arr array to make unique\n * @returns new array with unique items\n */\nexport function unique<T>(arr: T[]): T[] {\n    return Array.from(new Set<T>(arr));\n}\n\n// export function getExt(path: string): { filename: string, ext: string } {\n//     const pathPieces = path.split('/');\n//     const fullFilename = pathPieces[pathPieces.length-1];\n//     if (fullFilename.includes('.') && !fullFilename.endsWith('.')) {\n//         const lastDotIndex = fullFilename.lastIndexOf('.');\n//         return {\n//             filename: fullFilename.slice(0, lastDotIndex),\n//             ext: fullFilename.slice(lastDotIndex+1),\n//         };\n//     } else {\n//         return {filename: fullFilename, ext: \"\"}\n//     }\n// }\n\nexport function patchObject({\n    obj,\n    value,\n    path,\n    pathDelimiter,\n    logalot,\n}: {\n    obj: Object,\n    value: any,\n    path: string,\n    pathDelimiter?: string,\n    logalot?: number | boolean,\n}): void {\n    const lc = `[${patchObject.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting...`); }\n        if (!obj) { throw new Error(`obj required (E: 6a9dd32a361476e80b1bf7b91ec50522)`); }\n        if (typeof obj !== 'object') { throw new Error(`obj must be type 'object' (E: 66fdc289b32c06492bd95f5d266e6a22)`); }\n        if (!path) { throw new Error(`path required (at the very least should be the key in the root obj.) (E: fc779e7794ead8a0b44e5f2e776b0e22)`); }\n\n        /** atow defaults to a forward slash, but could be a dot or who knows */\n        pathDelimiter = pathDelimiter || DEFAULT_DATA_PATH_DELIMITER;\n\n        /**\n         * the target starts off at the object level itself, but we will\n         * traverse the given path, updating the targetObj as we go.\n         */\n        let targetObj: { [key: string | number]: any } = obj;\n        const pathPieces = path.split(pathDelimiter).filter(x => !!x);\n\n        /** the last one is the key into the final targetObj with value */\n        const key = pathPieces.pop()!;\n\n        // ensure each intermediate path exists and is an object\n        pathPieces.forEach(piece => {\n            let currentValue = targetObj[piece];\n            if (currentValue) {\n                if (typeof currentValue !== 'object') { throw new Error(`invalid path into object. Each step along the path must be typeof === 'object', but typeof targetObj[\"${piece}\"] === ${typeof currentValue}. (value: ${currentValue})  (E: 38cf29c5f624a40b4b56502c2ec39d22)`); }\n            } else {\n                // if not exist, create it\n                targetObj[piece] = {};\n            }\n\n            // update targetObj ref\n            targetObj = targetObj[piece];\n        });\n\n        // reached target depth, so finally set the value\n        targetObj[key] = value;\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport async function getIdPool({\n    n,\n}: {\n    n: number,\n}): Promise<string[]> {\n    const lc = `[${getIdPool.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting...`); }\n        let result: string[] = [];\n        for (let i = 0; i < n; i++) {\n            const id = await getUUID();\n            result.push(id.substring(0, 16));\n        }\n        return result;\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport function getSaferSubstring({\n    text,\n    length,\n    keepLiterals = ['-'],\n    replaceMap,\n}: {\n    text: string;\n    length?: number,\n    /**\n     * list of strings that you want to keep in the resultant string verbatim (without alteration).\n     *\n     * ## driving use case\n     *\n     * I want user comments that start with a question mark (?) to signify a\n     * request to a robbot, e.g. \"?start someAddr^gib\" or whatever. So I want to\n     * keep the question mark.  I thought of an encoding mapping, like ? =>\n     * \"__qstmark__\" but it's easier just to keep it, as this function was\n     * originally intended to just nerf text in general because there was no\n     * reason not to. well now there is a reason.\n     *\n     * I'm adding in a couple other characters in common use for whenever I get around\n     * to making those mean something in the app (#, @)\n     */\n    keepLiterals?: string[],\n    /**\n     *\n     */\n    replaceMap?: { [s: string]: string },\n}): string {\n    const lc = `[${getSaferSubstring.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 27437e312e5aa621adfebb84e059c822)`); }\n        if (!text) { throw new Error(`text required (E: 87e0493613c8b30dfade83e1d2862a22)`); }\n\n        let saferText: string = text;\n\n        // before stripping \"unsafe\" characters, replace all instances of\n        // keepLiterals with a temporary token if applicable\n        let tokenToKeepMap: { [token: string]: string } = {};\n        keepLiterals = keepLiterals ?? [];\n        for (let i = 0; i < keepLiterals.length; i++) {\n            const keep = keepLiterals[i];\n            let tmpToken: string;\n            do {\n                tmpToken = pickRandom_Letters({ count: 10 });\n            } while (tmpToken.includes(keep) || keep.includes(tmpToken) || text.includes(tmpToken));\n\n            // replace instances of keep literals with our token\n            if (saferText.includes(keep)) {\n                tokenToKeepMap[tmpToken] = keep;\n                while (saferText.includes(keep)) {\n                    saferText = saferText.replace(keep, tmpToken);\n                }\n            }\n        }\n\n        if (replaceMap && Object.keys(replaceMap).length > 0) {\n            for (let i = 0; i < Object.keys(replaceMap).length; i++) {\n                const toReplace = Object.keys(replaceMap)[i];\n                const replaceWith = replaceMap[toReplace];\n                while (saferText.includes(toReplace)) {\n                    saferText = saferText.replace(toReplace, replaceWith);\n                }\n            }\n        }\n\n        // now remove every non-alphanumeric\n        saferText = saferText.replace(/\\W/g, '');\n\n        // before checking length, put back in our keep literals (if any)\n        const tokens = Object.keys(tokenToKeepMap);\n        for (let i = 0; i < tokens.length; i++) {\n            const token = tokens[i];\n            while (saferText.includes(token)) {\n                saferText = saferText.replace(token, tokenToKeepMap[token]);\n            }\n        }\n\n        // trim the text to length if specified\n        if (length && length > 0) {\n            // debugger;\n            // let resText: string;\n\n            if (saferText.length > length) {\n                if (logalot) { console.log(`${lc} curtailing length (I: d7a28e05daa5979c7686b4c1cf519b23)`); }\n                saferText = saferText.substring(0, length);\n            }\n        }\n\n        // replace if text only has characters/nonalphanumerics (\"unsafe\").\n        if (saferText.length === 0) { saferText = ONLY_HAS_NON_ALPHANUMERICS; }\n\n        return saferText;\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * picks a random item from an array\n */\nexport function pickRandom<T extends any>({ x }: { x: T[] }): T | undefined {\n    if ((x ?? []).length === 0) { return undefined; /* <<<< returns early */ }\n    let randomIndex = Math.floor(Math.random() * x.length);\n    return x[randomIndex];\n}\n\n/**\n * NOT strong crypto!\n *\n * returns `count` number of letters concatenated into a string.\n */\nexport function pickRandom_Letters({ count }: { count: number }): string {\n    const lc = `${pickRandom_Letters.name}]`;\n    try {\n        if (!Number.isInteger(count)) { throw new Error(`count required to be a number. (E: c0a21d884ebd9afc4b2e8025207e0522)`); }\n        let result: string = \"\";\n        for (let i = 0; i < count; i++) {\n            result += pickRandom({ x: 'a b c d e f g h i j k l m n o p q r s t u v w x y z'.split(' ') });\n        }\n        if (result.length !== count) { throw new Error(`${lc} (UNEXPECTED) result.length !== count ? (E: 9bec4ec8f78610d8055e565415392a22)`); }\n        return result;\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * creates a text selection of the entire element's text.\n *\n * ty https://stackoverflow.com/questions/985272/selecting-text-in-an-element-akin-to-highlighting-with-your-mouse\n *\n * @param el element whose text we're selecting\n */\nexport function selectElementText(el: HTMLElement): void {\n    const lc = `[${selectElementText.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 0971989c737e5b846894357f671ab322)`); }\n        if (((document as any).body).createTextRange) {\n            const range = ((document as any).body).createTextRange();\n            range.moveToElementText(el);\n            range.select();\n        } else if (window.getSelection) {\n            const selection = window.getSelection();\n            if (selection) {\n                selection.removeAllRanges();\n                const range = document.createRange();\n                range.selectNodeContents(el);\n                selection.addRange(range);\n            } else {\n                throw new Error(`(UNEXPECTED) window.getSelection() returned false? (E: 722b2d3084ed43fe8da22d889ddb52b8)`);\n            }\n        } else {\n            throw new Error(`(UNEXPECTED) cannot select element text? (E: 163a1dd811b4f4bc22dd6823db859322)`);\n        }\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * replaces an individual character at a position.\n *\n * ## driving use case\n *\n * part of functionality to replace entire words with underscores (_'s) for blanking out\n * stimulations in wordy robbot.\n *\n * @returns string with replaced characters\n */\nexport function replaceCharAt({\n    s,\n    pos,\n    newChar,\n}: {\n    s: string,\n    pos: number,\n    newChar: string,\n}): string {\n    const chars = s.split('');\n    chars[pos] = newChar;\n    return chars.join('');\n}\n\n/**\n * Apparently it's a pain to determine if a keyboard event is hitting the\n * \"enter\" key across platforms.\n *\n * @link https://bugs.chromium.org/p/chromium/issues/detail?id=79407\n * @link https://stackoverflow.com/questions/3883543/javascript-different-keycodes-on-different-browsers\n *\n * @returns true if the event is the user pressing the \"Enter\" key, else false\n */\nexport function isKeyboardEvent_Enter(event: KeyboardEvent): boolean {\n    const isEnter = event.key === 'Enter' || event.code === 'Enter';\n    // event.keyCode === 10 || event.keyCode === 13 ||\n    // event.charCode === 10 || event.charCode === 13;\n    return isEnter;\n}\n\n/**\n * https://github.com/ionic-team/capacitor/issues/1564\n *\n * Still doesn't work...hmm\n */\nexport function getFileReaderHack(): FileReader {\n    const lc = `[${getFileReaderHack.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: d03faf53dd5f1cd1014f2f0e01058b22)`); }\n        const fileReader = new FileReader();\n        const zoneOriginalInstance = (fileReader as any)[\"__zone_symbol__originalInstance\"];\n        return zoneOriginalInstance || fileReader;\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * checks for mouse/trackball presence and infers keyboard when one is detected.\n *\n * ## aside\n *\n * It's amazing this isn't in an API...\n *\n * @returns true if by magical inference there is probably* a keyboard\n */\nexport function weHaveAPhysicalKeyboardProbably(): boolean {\n    const lc = `${weHaveAPhysicalKeyboardProbably.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 70a952db8e1f23263ba98607def6f422)`); }\n        const hasHover = window?.matchMedia?.('(hover:hover)').matches;\n        const hasPointerFine = window?.matchMedia?.('(pointer:fine)').matches;\n        return hasHover && hasPointerFine;\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * Check for either a physical keyboard or a relatively large window\n *\n * ## notes\n *\n * Such a long silly name because it's silly we don't have a better way of\n * detecting this with an official API.\n *\n * @returns true if we think that we're running on mobile\n */\nexport function weAreRunningOnMobileProbably(): boolean {\n    const lc = `${weAreRunningOnMobileProbably.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 5fd8deba6cb8cd40633c69371df95f22)`); }\n        const keyboard = weHaveAPhysicalKeyboardProbably();\n        const isMightyLargeForMobile = window.innerWidth > 810;\n        return keyboard || isMightyLargeForMobile;\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * Combines two maps/arrays into a single one with some very basic, naive merge rules:\n *\n * 1. If a key exists in only one map, then it will be included in the output map.\n * 2. If a key exists in both maps and the type is array or map, then these will be recursively merged.\n * 3. If a key exists in both maps but is not an array or map, the dominant map's value wins.\n *\n * ## future\n *\n * In the future, if we want to keep these kinds of things around and be more\n * specific about mergers, we can always rel8 a merge strategy ibgib to be\n * referred to when performing merger.\n */\nexport function mergeMapsOrArrays_Naive<T extends {} | any[]>({\n    dominant,\n    recessive,\n}: {\n    /**\n     * when two keys are not arrays or maps themselves, this one's value is\n     * chosen for output.\n     */\n    dominant: T,\n    /**\n     * when two keys are not arrays or maps themselves, this one's value is NOT\n     * chosen for output.\n     */\n    recessive: T,\n}): T {\n    const lc = `[${mergeMapsOrArrays_Naive.name}]`;\n    try {\n        if (Array.isArray(dominant) && Array.isArray(recessive)) {\n            // arrays\n            const output: any[] = clone(dominant) as any[];\n            let warned = false;\n            (recessive as []).forEach((recessiveItem: any) => {\n                if (typeof (recessiveItem) === 'string') {\n                    if (!output.includes(recessiveItem)) { output.push(recessiveItem); }\n                } else {\n                    if (!warned) {\n                        console.warn(`${lc} merging arrays of non-string elements. (W: d8ab113064834abc8eb5fe6c4cf87ba3)`);\n                        warned = true;\n                    }\n                    // we'll check the stringified version of recessive item against\n                    // the stringified dominant item.\n                    const xString = JSON.stringify(recessiveItem);\n                    if (!output.some(o => JSON.stringify(o) === xString)) {\n                        output.push(recessiveItem);\n                    }\n                }\n            });\n            return (output as T);\n        } else if (typeof (dominant) === 'object' && typeof (recessive) === 'object') {\n            // maps\n            const output: { [key: string]: any } = { ...recessive };\n            const dominantKeys: string[] = Object.keys(dominant);\n            const recessiveKeys: string[] = Object.keys(recessive);\n            dominantKeys.forEach((key: string) => {\n                if (recessiveKeys.includes(key)) {\n\n                    // naive merge for key that exists in both dominant & recessive\n                    if (Array.isArray((dominant as any)[key]) && Array.isArray((recessive as any)[key])) {\n                        // recursive call if both arrays\n                        output[key] = mergeMapsOrArrays_Naive<any[]>({\n                            dominant: (dominant as any)[key],\n                            recessive: (recessive as any)[key],\n                        });\n                    } else if (\n                        !!(dominant as any)[key] && !Array.isArray((dominant as any)[key]) && typeof ((dominant as any)[key]) === 'object' &&\n                        !!(recessive as any)[key] && !!Array.isArray((recessive as any)[key]) && typeof ((recessive as any)[key]) === 'object'\n                    ) {\n                        // recursive call if both objects\n                        output[key] = mergeMapsOrArrays_Naive<{}>({\n                            dominant: (dominant as any)[key],\n                            recessive: (recessive as any)[key],\n                        });\n                    } else {\n                        (output as any)[key] = (dominant as any)[key];\n                    }\n                } else {\n                    output[key] = (dominant as any)[key];\n                }\n            });\n\n            return output as T;\n        } else {\n            // ? unknown matching of dominant and recessive\n            console.warn(`${lc} unknown values or value types do not match. Both should either be an array or map. Dominant one wins categorically without any merging. (W: 3690ea19b81a4b89b98c1940637df62c)`);\n            return (dominant as T);\n        }\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    }\n};\n", "import { Ib, Gib, IbGib, IbGibAddr, IbAndGib } from './types.mjs';\n\n\n/**\n * Gets the ib^gib address from the given ib and gib or\n * from the ibGib object.\n *\n * Need to refactor to getIbGibAddr\n */\nexport function getIbGibAddr({\n    ib, gib, ibGib, delimiter = '^'\n}: {\n    ib?: Ib,\n    gib?: Gib,\n    ibGib?: IbGib,\n    delimiter?: string\n}): IbGibAddr {\n    ib = ib || ibGib?.ib || '';\n    gib = gib || ibGib?.gib || '';\n    return ib + delimiter + gib;\n}\n\n/**\n * Get the ib and gib fields from an ibGib object or ibGibAddr\n * with the given `delimiter`.\n */\nexport function getIbAndGib({\n    ibGib,\n    ibGibAddr,\n    delimiter = '^'\n}: {\n    ibGibAddr?: IbGibAddr,\n    ibGib?: IbGib,\n    delimiter?: string\n}): IbAndGib {\n    const lc = '[getIbAndGib]';\n    if (!ibGibAddr) {\n        if (ibGib) {\n            ibGibAddr = getIbGibAddr({ ibGib });\n        } else {\n            throw new Error(`${lc} We need either an address or an ibGib object`);\n        }\n    }\n    if (!ibGibAddr) { throw new Error(`${lc} Couldn't get ibGibAddr. ibGib invalid?`); }\n\n    if (!delimiter) { delimiter = '^'; }\n\n    const pieces = ibGibAddr.split(delimiter);\n    if (pieces.length === 2) {\n        // normal v1 case, e.g. 'ib^gib' or 'tag home^ABC123'\n        return { ib: pieces[0], gib: pieces[1] };\n    } else if (pieces.length === 1 && ibGibAddr.endsWith(delimiter)) {\n        // normal v1 primitive, e.g. '7^' or 'name^'\n        return { ib: pieces[0], gib: '' };\n    } else if (pieces.length === 1 && ibGibAddr.startsWith(delimiter)) {\n        // only gib/hash is provided like maybe a binary file\n        // e.g. ^ABC123 or ^XYZ456 or ^some_gib_that_isnt_a_hash\n        return { ib: '', gib: pieces[0] };\n    } else if (pieces.length === 2 && pieces[0] === '' && pieces[1] === '') {\n        // edge case of address is only the delimiter.\n        // So it's the primitive for that delimiter\n        return { ib: delimiter, gib: '' };\n        // } else if (pieces.length === 0 ) {\n        // ibGibAddr is falsy, so would have thrown earlier in this function\n        // I'm just noting this case for intent ATOW\n    } else {\n        console.warn(`${lc} multiple delimiters found in ibGibAddr. Considering last delimiter as the demarcation of gib hash`);\n        // e.g. 'ib^ABC123^gib'\n        // ib: 'ib^ABC123'\n        // gib: 'gib'\n        return {\n            ib: pieces.slice(0, pieces.length - 1).join(delimiter),\n            gib: pieces.slice(pieces.length - 1)[0],\n        }\n    }\n}\n\n\n/**\n * Normalizes an object/value for consistent hashing.\n * - Recursively processes objects and arrays.\n * - For objects:\n *   - Sorts keys alphabetically.\n *   - Removes properties whose values are `undefined`.\n *   - Keeps properties whose values are `null`.\n * - For arrays:\n *   - Preserves element order.\n *   - Recursively normalizes each element.\n * - Primitives (strings, numbers, booleans) and `null` are returned as is.\n *\n * @param value The value to normalize.\n * @returns The normalized value.\n *\n * This has been adjusted due to conversation with Gemini and working on python\n * port.  The main thing here is that we normalize array members, but not the\n * array itself. This way the array's order is preserved, but any object members\n * are themselves normalized.\n */\nexport function toNormalizedForHashing(value: any): any {\n    // Handle null, primitives (string, number, boolean) directly.\n    // `undefined` at the top level will be handled by the caller or become part of an object/array.\n    if (value === null || typeof value !== 'object') {\n        return value;\n    }\n\n    // Handle Arrays: recursively normalize elements, preserve order\n    if (Array.isArray(value)) {\n        return value.map(element => toNormalizedForHashing(element));\n    }\n\n    // Handle Objects (plain objects)\n    const normalizedObject: { [key: string]: any } = {};\n    const sortedKeys = Object.keys(value).sort();\n\n    for (const key of sortedKeys) {\n        const propertyValue = value[key];\n        if (propertyValue !== undefined) { // CRITICAL: Only omit if value is undefined\n            normalizedObject[key] = toNormalizedForHashing(propertyValue);\n        }\n        // If propertyValue is undefined, it's omitted from normalizedObject.\n        // If propertyValue is null, it's included.\n    }\n    return normalizedObject;\n}\n", "import { extractErrorMsg } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { IbGib_V1, IbGibData_V1, IbGibRel8ns_V1 } from \"./types.mjs\";\nimport { Ib } from \"../types.mjs\";\n\nlet crypto: any = globalThis.crypto;\nlet { subtle } = crypto;\n\n/**\n * Performs the gib hash like V1\n *\n * I have it all in one function for smallest, most independent version possible.\n *\n * #thanks https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest\n * #thanks https://stackoverflow.com/questions/49129643/how-do-i-merge-an-array-of-uint8arrays\n * #thanks https://stackoverflow.com/a/49129872/3897838 (answer to above)\n *\n * @param ibGib ibGib for which to calculate the gib\n */\nexport function sha256v1_old(ibGib: IbGib_V1, salt: string = \"\"): Promise<string> {\n    // console.log('func_gib_sha256v1 executed');\n    if (!salt) { salt = \"\"; }\n    let hashToHex = async (message: string | undefined) => {\n        if (!message) { return \"\"; }\n        const msgUint8 = new TextEncoder().encode(message);\n        const buffer = await subtle.digest('SHA-256', msgUint8);\n        const asArray = Array.from(new Uint8Array(buffer));\n        // return hashAsHex\n        return asArray.map(b => b.toString(16).padStart(2, '0')).join('');\n    };\n    let hashToHex_Uint8Array = async (salt: string, msgUint8: Uint8Array) => {\n        let tohashUint8Array: Uint8Array;\n        if (salt) {\n            const msgUint8_salt = new TextEncoder().encode(salt);\n            tohashUint8Array = new Uint8Array(msgUint8_salt.length + msgUint8.length);\n            tohashUint8Array.set(msgUint8_salt);\n            tohashUint8Array.set(msgUint8, msgUint8_salt.length);\n        } else {\n            tohashUint8Array = msgUint8;\n        }\n        const hashAsBuffer = await subtle.digest('SHA-256', tohashUint8Array);\n        const hashAsArray = Array.from(new Uint8Array(hashAsBuffer));\n        // return hashAsHex\n        return hashAsArray.map(b => b.toString(16).padStart(2, '0')).join('');\n    };\n    let hashFields;\n    if (salt) {\n        hashFields = async (ib: Ib, data: IbGibData_V1 | undefined, rel8ns: IbGibRel8ns_V1 | undefined) => {\n            const hasRel8ns =\n                Object.keys(rel8ns || {}).length > 0 &&\n                Object.keys(rel8ns || {}).some(k => rel8ns![k] && rel8ns![k]!.length > 0);\n            let hasData = !!data;\n            if (hasData) {\n                if (typeof data === 'string') {\n                    hasData = (data as string).length > 0;\n                } else if (data instanceof Uint8Array) {\n                    hasData = true;\n                } else if (typeof data === 'object') {\n                    hasData = Object.keys((data) || {}).length > 0;\n                } else {\n                    hasData = true;\n                }\n            }\n            const ibHash = (await hashToHex(salt + ib)).toUpperCase();\n            // empty, null, undefined all treated the same at this level.\n            const rel8nsHash: string = hasRel8ns ? (await hashToHex(salt + JSON.stringify(rel8ns))).toUpperCase() : \"\";\n            // empty, null, undefined all treated the same at this level (though not farther down in data)\n\n            // change this for binaries (Uint8Array data)\n            // const dataHash: string = hasData ? (await hashToHex(salt + JSON.stringify(data))).toUpperCase() : \"\";\n            let dataHash: string = \"\";\n            if (hasData) {\n                if (data instanceof Uint8Array) {\n                    dataHash = (await hashToHex_Uint8Array(salt, data)).toUpperCase();\n                } else {\n                    dataHash = (await hashToHex(salt + JSON.stringify(data))).toUpperCase();\n                }\n            }\n\n            // if the ibgib has no rel8ns or data, the hash should be just of the ib itself.\n            const allHash = hasRel8ns || hasData ?\n                (await hashToHex(salt + ibHash + rel8nsHash + dataHash)).toUpperCase() :\n                (await hashToHex(salt + ibHash)).toUpperCase();\n            return allHash;\n        };\n    } else {\n        hashFields = async (ib: Ib, data: IbGibData_V1 | undefined, rel8ns: IbGibRel8ns_V1 | undefined) => {\n            const hasRel8ns =\n                Object.keys(rel8ns || {}).length > 0 &&\n                Object.keys(rel8ns || {}).some(k => rel8ns![k] && rel8ns![k]!.length > 0);\n            // const hasData = Object.keys((data) || {}).length > 0;\n            let hasData = !!data;\n            if (hasData) {\n                if (typeof data === 'string') {\n                    hasData = (data as string).length > 0;\n                } else if (data instanceof Uint8Array) {\n                    hasData = true;\n                } else if (typeof data === 'object') {\n                    hasData = Object.keys((data) || {}).length > 0;\n                } else {\n                    hasData = true;\n                }\n            }\n            const ibHash = (await hashToHex(ib)).toUpperCase();\n            // empty, null, undefined all treated the same at this level.\n            const rel8nsHash: string = hasRel8ns ? (await hashToHex(JSON.stringify(rel8ns))).toUpperCase() : \"\";\n            // empty, null, undefined all treated the same at this level (though not farther down in data)\n            // const dataHash: string = hasData ? (await hashToHex(JSON.stringify(data))).toUpperCase() : \"\";\n            let dataHash: string = \"\";\n            if (hasData) {\n                if (data instanceof Uint8Array) {\n                    dataHash = (await hashToHex_Uint8Array('', data)).toUpperCase();\n                } else {\n                    dataHash = (await hashToHex(JSON.stringify(data))).toUpperCase();\n                }\n            }\n            // if the ibgib has no rel8ns or data, the hash should be just of the ib itself.\n            const allHash = hasRel8ns || hasData ?\n                (await hashToHex(ibHash + rel8nsHash + dataHash)).toUpperCase() :\n                (await hashToHex(ibHash)).toUpperCase();\n            return allHash;\n        }\n    }\n    return hashFields(ibGib.ib, ibGib?.data, ibGib?.rel8ns);\n}\n\nexport function sha256v1(ibGib: IbGib_V1, salt: string = \"\"): Promise<string> {\n    // console.log('func_gib_sha256v1 executed');\n    if (!salt) { salt = \"\"; }\n    let hashToHex = async (message: string | undefined) => {\n        if (!message) { return \"\"; }\n        const msgUint8 = new TextEncoder().encode(message);\n        const buffer = await subtle.digest('SHA-256', msgUint8);\n        const asArray = Array.from(new Uint8Array(buffer));\n        // return hashAsHex\n        return asArray.map(b => b.toString(16).padStart(2, '0')).join('');\n    };\n    let hashToHex_Uint8Array = async (salt: string, msgUint8: Uint8Array) => {\n        let tohashUint8Array: Uint8Array;\n        if (salt) {\n            const msgUint8_salt = new TextEncoder().encode(salt);\n            tohashUint8Array = new Uint8Array(msgUint8_salt.length + msgUint8.length);\n            tohashUint8Array.set(msgUint8_salt);\n            tohashUint8Array.set(msgUint8, msgUint8_salt.length);\n        } else {\n            tohashUint8Array = msgUint8;\n        }\n        const hashAsBuffer = await subtle.digest('SHA-256', tohashUint8Array);\n        const hashAsArray = Array.from(new Uint8Array(hashAsBuffer));\n        // return hashAsHex\n        return hashAsArray.map(b => b.toString(16).padStart(2, '0')).join('');\n    };\n\n    /**\n     * THIS IS DUPLICATED CODE IN THE RESPEC FILE. ANY CHANGES HERE MUST\n     * MANUALLY BE CHANGED IN THE RESPEC FILE!!!\n     *\n     * Normalizes an object/value for consistent hashing.\n     * - Recursively processes objects and arrays.\n     * - For objects:\n     *   - Sorts keys alphabetically.\n     *   - Removes properties whose values are `undefined`.\n     *   - Keeps properties whose values are `null`.\n     * - For arrays:\n     *   - Preserves element order.\n     *   - Recursively normalizes each element.\n     * - Primitives (strings, numbers, booleans) and `null` are returned as is.\n     *\n     * THIS IS DUPLICATED CODE IN THE RESPEC FILE. ANY CHANGES HERE MUST\n     * MANUALLY BE CHANGED IN THE RESPEC FILE!!!\n     *\n     * @param value The value to normalize.\n     * @returns The normalized value.\n     */\n    const toNormalizedForHashing = (value: any) => {\n        // Handle null, primitives (string, number, boolean) directly.\n        // `undefined` at the top level will be handled by the caller or become part of an object/array.\n        if (value === null || typeof value !== 'object') {\n            return value;\n        }\n\n        // Handle Arrays: recursively normalize elements, preserve order\n        if (Array.isArray(value)) {\n            return value.map(element => toNormalizedForHashing(element));\n        }\n\n        // Handle Objects (plain objects)\n        const normalizedObject: { [key: string]: any } = {};\n        const sortedKeys = Object.keys(value).sort();\n\n        for (const key of sortedKeys) {\n            const propertyValue = value[key];\n            if (propertyValue !== undefined) { // CRITICAL: Only omit if value is undefined\n                normalizedObject[key] = toNormalizedForHashing(propertyValue);\n            }\n            // If propertyValue is undefined, it's omitted from normalizedObject.\n            // If propertyValue is null, it's included.\n        }\n        return normalizedObject;\n\n        // if (!obj) {\n        //     return obj; /* <<<< returns early */\n        // } else if (typeof obj === 'string' || Array.isArray(obj)) {\n        //     return obj.concat(); /* <<<< returns early */\n        // } else if (typeof obj !== 'object') {\n        //     // Return non-objects as is, we don't know how to concat/copy it...hmm...\n        //     return obj;  /* <<<< returns early */\n        // }\n\n        // // we have an object. we will create a new object and populate it.\n        // const normalized = {};\n\n        // // sort keys alphabetically\n        // // NOTE: this does NOT mutate obj as Object.keys produces a new array\n        // const keys = Object.keys(obj).sort();\n\n        // for (const key of keys) {\n        //     const value = obj[key];\n        //     if (value !== undefined) {\n        //         // Recursively normalize if the value is an object\n        //         normalized[key] = (typeof value === 'object' && value !== null) ? toNormalizedForHashing(value) : value;\n        //     }\n        // }\n        // return normalized;\n    }\n\n\n    let hashFields;\n    if (salt) {\n        hashFields = async (ib: Ib, data: IbGibData_V1 | undefined, rel8ns: IbGibRel8ns_V1 | undefined) => {\n            const hasRel8ns =\n                Object.keys(rel8ns || {}).length > 0 &&\n                Object.keys(rel8ns || {}).some(k => rel8ns![k] && rel8ns![k]!.length > 0);\n            let hasData = !!data;\n            if (hasData) {\n                if (typeof data === 'string') {\n                    hasData = (data as string).length > 0;\n                } else if (data instanceof Uint8Array) {\n                    hasData = true;\n                } else if (typeof data === 'object') {\n                    hasData = Object.keys((data) || {}).length > 0;\n                } else {\n                    hasData = true;\n                }\n            }\n            const ibHash = (await hashToHex(salt + ib)).toUpperCase();\n            // empty, null, undefined all treated the same at this level.\n            const rel8nsHash: string = hasRel8ns ? (await hashToHex(salt + JSON.stringify(toNormalizedForHashing(rel8ns)))).toUpperCase() : \"\";\n            // empty, null, undefined all treated the same at this level (though not farther down in data)\n\n            // change this for binaries (Uint8Array data)\n            // const dataHash: string = hasData ? (await hashToHex(salt + JSON.stringify(data))).toUpperCase() : \"\";\n            let dataHash: string = \"\";\n            if (hasData) {\n                if (data instanceof Uint8Array) {\n                    dataHash = (await hashToHex_Uint8Array(salt, data)).toUpperCase();\n                } else {\n                    dataHash = (await hashToHex(salt + JSON.stringify(toNormalizedForHashing(data)))).toUpperCase();\n                }\n            }\n\n            // if the ibgib has no rel8ns or data, the hash should be just of the ib itself.\n            const allHash = hasRel8ns || hasData ?\n                (await hashToHex(salt + ibHash + rel8nsHash + dataHash)).toUpperCase() :\n                (await hashToHex(salt + ibHash)).toUpperCase();\n            return allHash;\n        };\n    } else {\n        hashFields = async (ib: Ib, data: IbGibData_V1 | undefined, rel8ns: IbGibRel8ns_V1 | undefined) => {\n            const hasRel8ns =\n                Object.keys(rel8ns || {}).length > 0 &&\n                Object.keys(rel8ns || {}).some(k => rel8ns![k] && rel8ns![k]!.length > 0);\n            // const hasData = Object.keys((data) || {}).length > 0;\n            let hasData = !!data;\n            if (hasData) {\n                if (typeof data === 'string') {\n                    hasData = (data as string).length > 0;\n                } else if (data instanceof Uint8Array) {\n                    hasData = true;\n                } else if (typeof data === 'object') {\n                    hasData = Object.keys((data) || {}).length > 0;\n                } else {\n                    hasData = true;\n                }\n            }\n            const ibHash = (await hashToHex(ib)).toUpperCase();\n            // empty, null, undefined all treated the same at this level.\n            const rel8nsHash: string = hasRel8ns ? (await hashToHex(JSON.stringify(toNormalizedForHashing(rel8ns)))).toUpperCase() : \"\";\n            // empty, null, undefined all treated the same at this level (though not farther down in data)\n            // const dataHash: string = hasData ? (await hashToHex(JSON.stringify(data))).toUpperCase() : \"\";\n            let dataHash: string = \"\";\n            if (hasData) {\n                if (data instanceof Uint8Array) {\n                    dataHash = (await hashToHex_Uint8Array('', data)).toUpperCase();\n                } else {\n                    dataHash = (await hashToHex(JSON.stringify(toNormalizedForHashing(data)))).toUpperCase();\n                }\n            }\n            // if the ibgib has no rel8ns or data, the hash should be just of the ib itself.\n            const allHash = hasRel8ns || hasData ?\n                (await hashToHex(ibHash + rel8nsHash + dataHash)).toUpperCase() :\n                (await hashToHex(ibHash)).toUpperCase();\n            return allHash;\n        }\n    }\n    return hashFields(ibGib.ib, ibGib?.data, ibGib?.rel8ns); // conditional nav ibGib?.data and ibGib?.rel8ns\n}\n\n/**\n * I have one large-ish sha256 function for gibbing purposes\n * (dream where metabootstrapping is better)\n * this is just testing a function that is internal to the sha256v1 func.\n * terrible as can be duplicated, but simple for now.\n */\nexport async function hashToHexCopy(\n    message: string | undefined\n): Promise<string | undefined> {\n    if (!message) { return \"\"; }\n    try {\n        const msgUint8 = new TextEncoder().encode(message);\n        const buffer = await subtle.digest('SHA-256', msgUint8);\n        const asArray = Array.from(new Uint8Array(buffer));\n        return asArray.map(b => b.toString(16).padStart(2, '0')).join('');\n    } catch (e) {\n        console.error(extractErrorMsg(e.message));\n        return undefined;\n    }\n};\n", "/**\n * The core of the simplicity of the ibGib protocol is that you are\n * taking two (or more) ibGibs and producing other ibGibs.\n *\n * There are three primary functions: mut8, rel8, fork\n *\n * These are actually different aspects of the single function of\n * relationship and time, either:\n *   1) Creating a 'new' timeline, or...\n *   2) Extending an existing one.\n *\n * Mut8 is intrinsic, rel8 is extrinsic, fork is a new timeline.\n * Mut8 changes a timeline, rel8 changes a timeline's link(s),\n * fork creates a new timeline.\n */\nimport {\n    IbGibRel8ns, IbGibAddr, IbGibWithDataAndRel8ns, Gib,\n} from '../types.mjs';\n\n/**\n * Need to see if I can remove this...\n */\nexport declare type IbGibData_V1 = {\n    [key: string]: any;\n    /**\n     * if true, this is the very first ibgib in a timeline.\n     *\n     * in the future, it is possible that there will be multiple temporal\n     * junction points and that this may be true for multiple ibgibs in a\n     * timeline. but atow (02/2024) and the foreseeable future, this should only\n     * be true for the very first ibgib.\n     *\n     */\n    isTjp?: boolean;\n    /**\n     * special property meant to track evolution count. So when a transform is\n     * applied to a punctiliar ibgib, this value is incremented if that ibgib\n     * has a temporal junction point (tjp).\n     */\n    n?: number;\n    /**\n     * the timestamp that the ibgib was created/evolved.  to get the\n     * milliseconds, get/set {@link timestampMs}\n     */\n    timestamp?: string;\n    /**\n     * the ms component of {@link timestamp}\n     */\n    timestampMs?: number;\n    /**\n     * if given, this is the unique identification for the ibgib. note that\n     * there is often a good use case for this when linking multiple ibgibs\n     * together in some operation. but usually this is a convenience property.\n     * most actual identification should often be done with the ib^gib address,\n     * either the tjp or punctiliar address depending on use case.\n     */\n    uuid?: string;\n};\n\n/**\n * Convenience enum to avoid spelling mistakes. (optional)\n */\nexport enum Rel8n {\n    past = 'past',\n    ancestor = 'ancestor',\n    dna = 'dna',\n    identity = 'identity',\n    tjp = 'tjp',\n    secret = 'secret',\n    encryption = 'encryption',\n}\n/**\n * shape of named edges (hard links) to other ibgibs which forms a dependency\n * graph (DAG) in V1.\n *\n * Note that all rel8ns are open-ended, because this is how rel8ns actually\n * exist. For example, consider that any relationship conceived nowadays in CS\n * as one-to-one, actually can be thought of as many-to-many when considering\n * multiple timelines.\n */\nexport interface IbGibRel8ns_V1 extends IbGibRel8ns {\n    /**\n     * when an ibgib is evolved, this is a rel8n to pointer(s) in the ibgib\n     * timeline's history.\n     *\n     * depending on use case, this could only be a single pointer to the most\n     * recent past (like a linked list or blockchain), or it could be the entire\n     * history from inception of the ibgib.\n     * @optional\n     */\n    [Rel8n.past]?: IbGibAddr[];\n    /**\n     * associate the owner/producer of the ibgib. not in use atow (02/2024), so\n     * this may change or be yagni. the keystone structure will solve this.\n     * @optional\n     */\n    [Rel8n.identity]?: IbGibAddr[];\n    /**\n     * when an ibgib is forked, this is the parent.\n     * @optional\n     */\n    [Rel8n.ancestor]?: IbGibAddr[];\n    /**\n     * points to the dna that are the history of applied transforms that got the\n     * ibgib to its current state.\n     * @optional\n     */\n    [Rel8n.dna]?: IbGibAddr[];\n    /**\n     * temporal junction point of the ibgib.\n     *\n     * this is set if either uuid or timestamp tjp setting is used when the most\n     * recent transform was applied.\n     * @optional\n     */\n    [Rel8n.tjp]?: IbGibAddr[];\n    /**\n     * if there is any encryption related to this ibgib, most likely for\n     * enciphering one or more properties in the ibgib's `ib` and/or `data`\n     * properties, the associated secret(s) can be linked here.\n     * @optional\n     */\n    [Rel8n.secret]?: IbGibAddr[];\n    /**\n     * if there is any encryption related to this ibgib, most likely for\n     * enciphering one or more properties in the ibgib's `ib` and/or `data`\n     * properties, the encryption ibgibs (which hold encryption details like\n     * encryption algorithm + parameterization) can be linked here.\n     * @optional\n     */\n    [Rel8n.encryption]?: IbGibAddr[];\n}\n/**\n * combined shape of the overall v1 ibgib. it has an ib, gib, data, and rel8ns.  */\nexport interface IbGib_V1<TData = IbGibData_V1, TRel8ns extends IbGibRel8ns_V1 = IbGibRel8ns_V1>\n    extends IbGibWithDataAndRel8ns<TData, TRel8ns> {\n}\n\nexport interface GibInfo {\n    /**\n     * Hash for this ibgib frame in time.\n     */\n    punctiliarHash?: string;\n    /**\n     * The gib for this ibgib's most recent tjp.\n     *\n     * ## notes\n     *\n     * ATOW, only one tjp expected really, though I've been coding\n     * with the possibility of having multiple tjp's similar to\n     * checkpoints.\n     */\n    tjpGib?: Gib;\n    /**\n     * If\n     */\n    piecesCount?: number;\n    /**\n     * If a delimiter is used in this gib, this is the delimiter.\n     *\n     * ## notes\n     *\n     * ATOW, the caller already knows the delimiter. But I'm thinking that\n     * I may be persisting this at some point and it would be good to include.\n     */\n    delimiter?: string;\n    /**\n     * True the gib is just 'gib' (GIB constant), else falsy.\n     */\n    isPrimitive?: boolean;\n}\n", "import { IbGib_V1 } from './types.mjs';\n\n/**\n * This is essentially an alias of the string literal `'ib'`\n */\nexport const IB = 'ib';\n/**\n * This is essentially an alias of the string literal `'gib'`\n *\n * When you have a primitive ibgib, this should be the `ibGib.gib` value, as\n * there is no hashing metadata for primitives.\n */\nexport const GIB = 'gib';\n/**\n * This is the root ibgib from which all ibgib are ultimately forked.\n * It has 0 and infinite data, 0 and infinite rel8ns. Its ib and gib\n * are simply 'ib' and 'gib'.\n */\nexport const ROOT: IbGib_V1 = { ib: IB, gib: GIB, }\n/**\n * The default delimiter is the caret (^) symbol. This is derived from\n * taking an ib^gib address and turning it into an ibGib object (note\n * the capitalized \"G\").\n */\nexport const IBGIB_DELIMITER = '^';\n/**\n * Gib is often just a single hash for a single ib^gib record.\n * But if the ibgib has a tjp, which implies a timeline (\"stream\"\n * in some senses), then we will include the tjp gib hash alongside the\n * individual punctilear ibgib frame.\n *\n * ATOW this has the default schema of\n *\n * @example \"comment abc^TJPHASH123\", \"comment abc^TJPHASH123.THISRECORDHASH456\"\n */\nexport const GIB_DELIMITER = '.';\n/**\n * This is the address of the ROOT ibgib with the default delimiter (caret ^).\n */\nexport const ROOT_ADDR = 'ib^gib'; // `${IB}${IBGIB_DELIMITER}${GIB}`;\n/**\n * Some rel8ns should not be able to be renamed or removed, as these have\n * \"special\" semantic meaning in the low-level graphing protocol.\n *\n * ## notes\n *\n * * Of course, this can be forged or tinkered with, and that ultimately is what\n *   consensus would be utilized for.\n * * protocols built on top of this may also have reserved rel8n/data key names\n */\nexport const FORBIDDEN_ADD_RENAME_REMOVE_REL8N_NAMES = ['past', 'ancestor', 'dna', 'tjp'];\n\nexport const IB_MAX_LENGTH_DEFAULT = 155;\n\n/**\n * Defaults to word characters, space, tab, hyphen, and other\n * non-slash (path navigating) chars.\n *\n * Does not allow new lines or other whitespace, only tabs and spaces.\n *\n * ## atow\n *\n * `^[\\\\w\\\\t\\\\-|=+.&%\\$#@!~\\` \\\\[\\\\]\\\\(\\\\)\\\\{\\\\}]{1,${IB_MAX_LENGTH_DEFAULT}}$`\n */\nexport const IB_REGEXP_DEFAULT = new RegExp(`^[\\\\w\\\\t\\\\-|=+.&%\\$#@!~\\` \\\\[\\\\]\\\\(\\\\)\\\\{\\\\}]{1,${IB_MAX_LENGTH_DEFAULT}}$`);", "import { clone, extractErrorMsg, } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { TransformOpts, IbGib, Gib, IbGibAddr, } from \"../../types.mjs\";\nimport { getIbGibAddr, getIbAndGib, } from \"../../helper.mjs\";\nimport { sha256v1, } from \"../sha256v1.mjs\";\nimport { GibInfo, IbGib_V1, } from \"../types.mjs\";\nimport { IBGIB_DELIMITER, GIB, GIB_DELIMITER } from \"../constants.mjs\";\n\nexport async function buildDna<TSrc extends IbGib_V1, TOpts extends TransformOpts<TSrc>>(\n    opts: TOpts,\n): Promise<IbGib_V1> {\n    const transformData: TOpts = clone(opts);\n    let lc = `[${buildDna.name}]`;\n\n    // remove references to the srcAddr, as this will be captured\n    // by the ibGib's `past` rel8n. This way, we can reapply dna\n    // to different src's more easily, as well as have less unique dna\n    if (transformData.srcAddr) { delete transformData.srcAddr; }\n\n    // remove all references to actual objects in this, we just\n    // want the data. ATOW, src is a reference to the src object\n    // and we only want the srcAddr\n    delete transformData.src;\n\n    // dna is never timestamped or uniquely identified hmm...\n    // or rel8d to anything...hmmm\n    // so much dna, best to minimize though of course we dont\n    // want to prematurely optimize...but there's a looooot of dna.\n    // best to share/reuse as much as possible.\n    const result: IbGib_V1 = {\n        ib: transformData.type!,\n        data: transformData,\n        rel8ns: {\n            ancestor: [\n                `${transformData.type!.toString()}${IBGIB_DELIMITER}${GIB}` // e.g. fork^gib\n            ]\n        }\n    };\n\n    result.gib = await sha256v1(result);\n\n    return result;\n}\n\nexport function isDna({ ibGib }: { ibGib: IbGib }): boolean {\n    const lc = `[${isDna.name}]`;\n    try {\n        if (!ibGib) { throw new Error(`ibGib required.`); }\n\n        // console.log(`${lc} ibGib: ${pretty(ibGib)}`);\n\n        // ancestor is known transform is the best way for v1 ATOW\n        const knownTransformPrimitiveAddrs =\n            ['fork', 'mut8', 'rel8', 'plan'].map(x => `${x}^${GIB}`); // plan from prev versions\n        const hasTransformAncestor =\n            ((ibGib as any).rel8ns) &&\n            ((ibGib as any).rel8ns.ancestor) &&\n            (Array.isArray((ibGib as any).rel8ns.ancestor)) &&\n            ((((ibGib as any).rel8ns.ancestor) as any) as any).\n                some((x: any) => knownTransformPrimitiveAddrs.includes(x));\n\n        return hasTransformAncestor || false;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    }\n}\n\nexport function isPrimitive({ ibGib, gib }: { ibGib?: IbGib_V1, gib?: Gib }): boolean {\n    if (ibGib) {\n        return isPrimitive({ gib: ibGib.gib });\n    } else if (gib) {\n        return gib === GIB;\n    } else {\n        // falsy gib means it's primitive or a programming error...hmm\n        return true;\n    }\n}\n\n/**\n * Generates the gib of a given `ibGib` depending on\n * @returns gib - either bare hash for those with no tjp; or tjp-scoped hash; or 'gib' for primitives\n */\nexport async function getGib({\n    ibGib,\n    hasTjp,\n    tjpAddr,\n    gibDelimiter,\n    isPrimitive,\n    hashAlgorithm,\n}: {\n    /**\n     * We'll take the `ib`, `data`, and `rel8ns` from this\n     */\n    ibGib: IbGib_V1,\n    /**\n     * If true, then we'll treat this as having a tjp.\n     * If falsy, then we'll check the internals of the ibGib to see if it has a tjp.\n     */\n    hasTjp?: boolean;\n    /**\n     * @deprecated\n     *\n     * IGNORED\n     *\n     * This is now always searched for in the ibGib itself.\n     */\n    tjpAddr?: IbGibAddr,\n    /**\n     * What to use as the delimiter for the `gib`.\n     *\n     * @default GIB_DELIMITER\n     *\n     * ## notes\n     *\n     * This is not the same thing necessarily as the ib^gib delimiter.\n     * In fact the default gibDelimiter ATOW ('.') is different than the\n     * default ib^gib delimiter ('^').\n     */\n    gibDelimiter?: string,\n    /**\n     * If this is primitive, then the `gib` is always GIB (\"gib\" string literal).\n     */\n    isPrimitive?: boolean,\n    /**\n     * Hash algorithm to use when calculating the gib hash of the ibgib datum.\n     *\n     * ## notes\n     *\n     * * I'm just including this now to show where we will expand when working with\n     *   multiple hash algorithms. For now though, in all of V1, we use 'SHA-256'\n     *   when calculating the gib hashes. This is why I'm hard-coding the type\n     *   here instead of using this lib's `HashAlgorithm` type.\n     *   * This param is actually ignored ATOW.\n     * * In my current consuming use case (ionic-gib), though,\n     *   I am indeed using SHA-512 when encrypting using encrypt-gib. I only note\n     *   this in case someone sees \"SHA-512\" code somewhere and is confused.\n     */\n    hashAlgorithm?: 'SHA-256',\n}): Promise<string> {\n    const lc = `[${getGib.name}]`;\n    try {\n        if (!ibGib) { throw new Error(`ibGib required. (E: 17d073226b9d42fd841e5a94b065ef21)`); }\n        if (isPrimitive) { return GIB; }\n        const ibGibHash = await sha256v1(ibGib, '');\n        const rel8ns = ibGib.rel8ns ?? {};\n        const data = ibGib.data ?? {};\n        gibDelimiter = gibDelimiter || GIB_DELIMITER;\n        if (!hasTjp) { hasTjp = (rel8ns.tjp ?? []).length > 0 || data.isTjp || false; }\n        if (hasTjp) {\n            let tjpAddrGib: string | undefined;\n            if (rel8ns.tjp) {\n                if (rel8ns.tjp.length === 1) {\n                    if (rel8ns.tjp[0]) { // checking for empty string\n                        tjpAddr = rel8ns.tjp[0];\n                    } else {\n                        throw new Error(`rel8ns.tjp[0] is falsy. (E: ed879d2b039543f8b1902e8b7b5a5a7b)`);\n                    }\n                } else if (rel8ns.tjp.length > 1) {\n                    if (rel8ns.tjp[rel8ns.tjp.length - 1]) {\n                        console.warn(`${lc} found more than one tjp addr...only expecting 1 ATOW. (W: 10ed43f716e743e0afd1954f1ab46789)`);\n                        tjpAddr = rel8ns.tjp[rel8ns.tjp.length - 1];\n                    } else {\n                        throw new Error(`multiple tjp addrs, and the last (most recent) one is falsy. (E: bc835dc89be24075bba8b2b6616ea069)`);\n                    }\n                } else {\n                    // empty rel8ns.tjp array?\n                    throw new Error(`hasTjp is true but rel8ns.tjp is empty array. (E: d08b2f9e86494814b5e7d7b4602b2ab7)`);\n                }\n            } else if (data.isTjp) {\n                // the ibGib itself is the tjp\n                tjpAddr = getIbGibAddr({ ib: ibGib.ib, gib: ibGibHash });\n            } else {\n                throw new Error(`hasTjp is true, but both ibGib.rel8ns.tjp and ibGib.data.isTjp are falsy. (E: 4e246897e52044789594d853bb5b66ee)`)\n            }\n            tjpAddrGib = tjpAddr ? getIbAndGib({ ibGibAddr: tjpAddr }).gib : undefined;\n\n            if (tjpAddrGib) {\n                // if the ibGib IS the tjp, then the gib is only the hash\n\n                // if the ibGib is NOT the tjp, then the gib is the hash plus\n                // tjpGib. note in the future, if multiple tjps are going, then\n                // tjpAddrGib itself may have another delim inside it, so we\n                // will end up with a gib with multiple delimiters.\n                return data.isTjp ? ibGibHash : `${ibGibHash}${GIB_DELIMITER}${tjpAddrGib}`;\n            } else {\n                throw new Error(`hasTjp is true but could not find tjpAddrGib. (E: 1863df626b754744a1d431a683cb0ba0)`);\n            }\n        } else {\n            // no tjp, so gib is just the hash\n            return ibGibHash;\n        }\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    }\n\n}\n\n/**\n * Parses gib (either via `gib` param or `ibGibAddr.gib`) and returns information\n * about it.\n *\n * @returns Information about the given `gib` (or `gib` extracted from `ibGibAddr`)\n */\nexport function getGibInfo({\n    ibGibAddr,\n    gib,\n    gibDelimiter,\n}: {\n    /**\n     * If given, will extract `gib` from this.\n     */\n    ibGibAddr?: IbGibAddr,\n    /**\n     * `gib` to analyze.\n     */\n    gib?: Gib,\n    /**\n     * Delimiter among pieces of gib, if applicable.\n     *\n     * @default GIB_DELIMITER (ATOW '.')\n     *\n     * ## notes\n     *\n     * Some `gib` values will include tjp information, while others\n     * are just the hash.\n     */\n    gibDelimiter?: string,\n}): GibInfo {\n    const lc = `[${getGibInfo.name}]`;\n    try {\n        if (!ibGibAddr && !gib) { throw new Error(`Either ibGibAddr or gib required. (E: 25e3dcbe63cd44909032df12af9df75e)`); }\n        gib = gib || getIbAndGib({ ibGibAddr }).gib;\n\n        if (gib === GIB) { return { isPrimitive: true } }\n\n        gibDelimiter = gibDelimiter ?? GIB_DELIMITER;\n\n        if (gib.includes(gibDelimiter)) {\n            const pieces = gib.split(gibDelimiter);\n            if (pieces.some(p => p === '')) { throw new Error(`unexpected gib that contains gibDelimiter (${gibDelimiter}) but has at least one piece with empty string. (E: 75a94280045541009ee68182d12d3449)`); }\n\n            const piecesCount = pieces.length;\n            if (piecesCount > 2) { console.warn(`${lc} gib only expected to have two pieces ATOW. re-examine please. (W: aa4283ac5a5747a386a69966ecdad39d)`); }\n\n            const punctiliarHashPiece = pieces.splice(0, 1);\n            return {\n                punctiliarHash: punctiliarHashPiece[0],\n                tjpGib: pieces.join(gibDelimiter), // after splice, piece/s is/are tjp\n                piecesCount,\n                delimiter: gibDelimiter,\n            }\n        } else {\n            return {\n                punctiliarHash: gib,\n                piecesCount: 1,\n                delimiter: gibDelimiter,\n            }\n        }\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    }\n}\n", "import { getIbGibAddr } from '../../helper.mjs';\nimport { clone, getUUID, getTimestamp, } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';\nimport { sha256v1 } from '../sha256v1.mjs';\nimport { IbGib_V1, IbGibData_V1, IbGibRel8ns_V1, Rel8n } from '../types.mjs';\nimport { TransformOpts_Fork, TransformResult } from '../../types.mjs';\nimport { IBGIB_DELIMITER, ROOT_ADDR } from '../constants.mjs';\nimport { buildDna } from './transform-helper.mjs';\n\n/**\n * Original-ish V1 transform behavior.\n * Going to create an ibGib containing the fork data.\n * Apply that fork and create a resulting ibGib.\n *\n * Takes the src ibGib, clears its past and adds a link to\n * the src via the 'ancestor' rel8n.\n *\n * NOTE:\n *   This is NOT going to do the plan^gib stuff ATM.\n *   Also this does NOT add any identity information ATM.\n */\nexport async function fork(opts: TransformOpts_Fork<IbGib_V1>): Promise<TransformResult<IbGib_V1>> {\n    const {\n        noTimestamp, dna,\n        linkedRel8ns,\n        destIb, uuid, tjp,\n        cloneRel8ns, cloneData,\n        type = 'fork',\n    } = opts;\n    let src = opts.src;\n\n    const lc = '[fork_v1]';\n    // #region validation\n    if (type !== 'fork') { throw new Error(`${lc} not a fork transform.`); }\n    if (!opts.type) { opts.type = 'fork' }\n\n    if (!src) { throw new Error(`${lc} src required to fork.`); }\n    if (!src!.ib) { throw new Error(`${lc} src.ib required.`); }\n    // destIb is not required, as it just reuses src.ib\n    if (destIb && destIb.includes(IBGIB_DELIMITER)) {\n        throw new Error(`${lc} destIb can't contain (hardcoded) delimiter right now.`);\n    }\n    if (!src!.gib) { throw new Error(`${lc} src.gib required.`); }\n\n    // #endregion\n\n    // we want to forget `src` proper very quickly because it may have other\n    // non-IbGib properties that are not relevant to our transform.\n    let dto: IbGib_V1 = { ib: src.ib, gib: src.gib, };\n    if (src.data && Object.keys(src.data).length > 0) { dto.data = src.data; }\n    if (src.rel8ns && Object.keys(src.rel8ns).length > 0) { dto.rel8ns = src.rel8ns; }\n    src = dto;\n\n    const srcAddr = getIbGibAddr({ ib: src!.ib, gib: src.gib });\n    opts.srcAddr = srcAddr;\n\n    const rel8ns: IbGibRel8ns_V1 =\n        cloneRel8ns && src.rel8ns && Object.keys(src.rel8ns).length > 0 ?\n            clone(src.rel8ns) :\n            {};\n    delete rel8ns.past;\n    const data: any = cloneData && src?.data ? clone(src!.data) : {};\n    if (opts.nCounter) { data.n = 0; }\n    const ancestor = linkedRel8ns?.includes(Rel8n.ancestor) ?\n        [srcAddr] :\n        (rel8ns.ancestor || []).concat([srcAddr]);\n    rel8ns.ancestor = ancestor;\n\n    // remove tjp if exists in rel8ns\n    if (rel8ns.tjp) { delete rel8ns.tjp; }\n\n    const newIbGib = clone(src) as IbGib_V1<IbGibData_V1>;\n    if (noTimestamp && tjp?.timestamp) {\n        throw new Error(`${lc} both noTimestamp and tjp.timestamp selected.`);\n    }\n    if (!noTimestamp || tjp?.timestamp) {\n        const date = new Date();\n        data.timestamp = getTimestamp(date);\n        data.timestampMs = date.getMilliseconds();\n    }\n    if (tjp?.uuid || uuid) { data.uuid = await getUUID(); }\n    if (tjp?.uuid || tjp?.timestamp) {\n        data.isTjp = true;\n    } else {\n        if (data.isTjp) { delete data.isTjp; }\n    }\n\n    newIbGib.ib = destIb || 'ib';\n    // rel8ns ignored if forking from the root ib^gib\n    if (srcAddr !== ROOT_ADDR) { newIbGib.rel8ns = rel8ns; }\n    if (Object.keys(data).length > 0) { newIbGib.data = data; }\n\n    let transformDna: IbGib_V1 | null = null;\n    if (dna) {\n        transformDna = await buildDna(opts);\n        const dnaAddr = getIbGibAddr({ ibGib: transformDna });\n        rel8ns.dna = linkedRel8ns?.includes(Rel8n.dna) ?\n            rel8ns.dna = [dnaAddr] :\n            rel8ns.dna = (rel8ns.dna || []).concat(dnaAddr);\n    }\n\n    newIbGib.gib = await sha256v1(newIbGib, '');\n\n    const result: TransformResult<IbGib_V1> = { newIbGib };\n    if (transformDna) { result.dnas = [transformDna!] }\n    return result;\n}\n", "import { getIbGibAddr } from '../../helper.mjs';\nimport { clone, getTimestamp, } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';\nimport { IbGib_V1, IbGibData_V1, IbGibRel8ns_V1, Rel8n } from '../types.mjs';\nimport { TransformOpts_Mut8, TransformResult } from '../../types.mjs';\nimport { IBGIB_DELIMITER, } from '../constants.mjs';\nimport { buildDna, isPrimitive, getGib } from './transform-helper.mjs';\n\n/**\n * Original-ish V1 transform behavior.\n * Going to create a new ibGib which mut8s internal data (or the ib) from the src ibgib.\n *\n * Takes the immutable src ibGib record, applies a mutation to its internal (intrinsic)\n * `data` field, creates a new ibGib with the new intrinsic data.\n *\n * ### remember, ibgib basic structure\n *\n * Remember, the ibGib has the following basic structure (here represented in JSON):\n * {\n *   ib: 'some ib, can be a simple name, or other metadata, up to very complex metadata.',\n *   gib: 'ABC123', // hash of the other three fields of our JSON data structure\n *   rel8ns: {\n *      'link name': [ 'other ibgib^ABC345', 'yo^456789' ],\n *      'called an edge in other jargon': [ 'ib^gib' ],\n *      'past': ['ib^gib']\n *      ...\n *   },\n *   data: {\n *     'intrinsic data': 'intrinsic value',\n *     'copied each datum': 'so should be relatively small in practice',\n *     'can...': {\n *       '...also be objects if you really': ['want']\n *      }\n *   }\n * }\n *\n * So this transform is primarily concerned with that `data` property (though we can mut8 the ib also).\n * If it's really anything complex, most likely it would be better to do\n * another ibGib and link to it via the `rel8ns` (in the same way that in OOP it\n * is good to have single responsibility for class architecture).\n *\n * ### what we can do with mutations\n *\n * We can mutate the `ib` value. So if we need to change metadata (e.g. a 'rename'), we can.\n * This has implications for updating pointer refs and the tjp, but that's more advanced.\n *\n * We can also mutate the intrinsic `data` property, which is basically a JS object style of\n * key/value store.\n *\n * ### notes\n *   * This is NOT going to do the plan^gib stuff ATM.\n *   * This does NOT add any identity information ATM.\n *\n */\nexport async function mut8<TNewData = any>(\n    opts: TransformOpts_Mut8<IbGib_V1, TNewData>\n): Promise<TransformResult<IbGib_V1>> {\n    const {\n        noTimestamp, dna, linkedRel8ns,\n        dataToRename, dataToRemove, dataToAddOrPatch,\n        mut8Ib,\n        type = 'mut8'\n    } = opts;\n    let src = opts.src;\n    const lc = '[mut8_v1]';\n    // #region validation\n\n    if (type !== 'mut8') { throw new Error(`${lc} not a mut8 transform.`); }\n    if (!opts.type) { opts.type = 'mut8' }\n\n    if (!src) { throw new Error(`${lc} src required to mut8.`); }\n    if (!src!.ib) { throw new Error(`${lc} src.ib required.`); }\n    if (src!.ib!.includes(IBGIB_DELIMITER)) {\n        throw new Error(`${lc} ib can't contain hardcoded delimiter (${IBGIB_DELIMITER}) right now.`);\n    }\n    if (!src!.gib) { throw new Error(`${lc} src.gib required.`); }\n\n    if (!mut8Ib && !dataToRename && !dataToRemove && !dataToAddOrPatch) {\n        throw new Error(`${lc} gotta provide either a mut8Ib or some data to change.`);\n    }\n\n    const srcAddr = getIbGibAddr({ ib: src!.ib, gib: src.gib });\n    if (opts.srcAddr && srcAddr !== opts.srcAddr) { throw new Error(`${lc} srcAddr from src does not equal opts.srcAddr`); }\n    opts.srcAddr = srcAddr;\n\n    // const srcIsPrimitive = src.gib === GIB || !src.gib;\n    // if (srcIsPrimitive) { throw new Error(`${lc} cannot mutate primitive ibgib`); }\n    if (isPrimitive({ ibGib: src })) { throw new Error(`${lc} cannot mutate primitive ibgib`); }\n\n    // #endregion\n\n    // we want to forget `src` proper very quickly because it may have other\n    // non-IbGib properties that are not relevant to our transform.\n    let dto: IbGib_V1 = { ib: src.ib, gib: src.gib, };\n    if (src.data && Object.keys(src.data).length > 0) { dto.data = src.data; }\n    if (src.rel8ns && Object.keys(src.rel8ns).length > 0) { dto.rel8ns = src.rel8ns; }\n    src = dto;\n\n    const newIbGib = clone(src) as IbGib_V1<IbGibData_V1>;\n\n    const srcRel8ns = src.rel8ns ? src.rel8ns : {};\n    const rel8ns: IbGibRel8ns_V1 = clone(srcRel8ns);\n    rel8ns.past = linkedRel8ns?.includes(Rel8n.past) ?\n        [srcAddr] :\n        (rel8ns.past || []).concat([srcAddr]);\n\n    let data: any = src?.data ? clone(src!.data) : {};\n    if (dataToRename) { data = renameOrRemove(data, dataToRename, 'rename'); }\n    if (dataToRemove) { data = renameOrRemove(data, dataToRemove, 'remove'); }\n    if (dataToAddOrPatch) { data = patch(data, dataToAddOrPatch); }\n    if (!noTimestamp) {\n        const date = new Date();\n        data.timestamp = getTimestamp(date);\n        data.timestampMs = date.getMilliseconds();\n    }\n\n    // n-related\n    if (opts.nCounter || Object.keys(data).includes('n')) {\n        if (Object.keys(data).includes('n')) {\n            if (Number.isInteger(data.n)) {\n                if (data.n >= 0) {\n                    data.n = data.n + 1;\n                } else {\n                    console.warn(`${lc} data.n is less than 0, which is unexpected. Resetting data.n to 0.`);\n                    data.n = 0;\n                }\n            } else {\n                throw new Error('cannot increment nCounter because data.n is not a number.');\n            }\n        } else {\n            data.n = 0;\n        }\n    }\n\n    // tjp-related\n    // let tjpAddr: IbGibAddr | undefined = undefined;\n\n    // const srcIsTjp = data.isTjp && (rel8ns.tjp ?? []).length === 0; // if we only want one tjp\n    const srcIsTjp = data.isTjp; // if we want to allow more than one tjp\n    if (srcIsTjp) {\n        // if the src is tjp, e.g. is the first ibgib after a fork,\n        // then srcAddr is the tjpAddr\n        const tjpRel8n: string[] = rel8ns.tjp ?? [];\n        tjpRel8n.push(srcAddr);\n        rel8ns.tjp = tjpRel8n;\n        delete data.isTjp;\n    }\n\n    // dna-related\n    let transformDna: IbGib_V1 | null = null;\n    if (dna) {\n        transformDna = await buildDna(opts);\n        const dnaAddr = getIbGibAddr({ ibGib: transformDna });\n        rel8ns.dna = linkedRel8ns?.includes(Rel8n.dna) ?\n            rel8ns.dna = [dnaAddr] :\n            rel8ns.dna = (rel8ns.dna || []).concat(dnaAddr);\n    }\n\n    // set final ib, data, rel8ns, gib values\n    newIbGib.ib = mut8Ib ? mut8Ib : newIbGib.ib;\n    newIbGib.rel8ns = rel8ns;\n    if (Object.keys(data).length > 0) {\n        newIbGib.data = data;\n    } else {\n        // we've removed the last key in the data object so delete it\n        delete newIbGib.data;\n    }\n    const hasTjp = (rel8ns.tjp?.length ?? 0) > 0;\n    newIbGib.gib = await getGib({ ibGib: newIbGib, hasTjp });\n\n    // wrap in the result and return\n    const result: TransformResult<IbGib_V1> = { newIbGib };\n    if (transformDna) { result.dnas = [transformDna]; }\n    return result;\n}\n\n\nfunction renameOrRemove(obj: any, info: any, which: 'rename' | 'remove'): any {\n    const lc = `[renameOrRemove]`;\n    const FORBIDDEN_RENAME_REMOVE_KEYS = ['timestamp'];\n    Object.keys(info).forEach(key => {\n        if (FORBIDDEN_RENAME_REMOVE_KEYS.includes(key)) {\n            throw new Error(`${lc} Cannot rename to ${key}.`);\n        }\n        if (Object.keys(obj).includes(key)) {\n            let infoVal = info[key];\n            if (typeof (infoVal) === 'string') {\n                // rename\n                if (FORBIDDEN_RENAME_REMOVE_KEYS.includes(infoVal)) {\n                    throw new Error(`${lc} Cannot rename to ${infoVal}.`);\n                }\n                if (which === 'rename') {\n                    obj[infoVal] = obj[key];\n                }\n                delete obj[key];\n            } else {\n                // recurse\n                obj[key] = renameOrRemove(obj[key], infoVal, which);\n            }\n        } else {\n            console.log(`${lc} key to ${which} does not exist`);\n        }\n    });\n    return obj;\n};\n\n/**\n * Patches obj (active mutate, does not copy) with patchObj data. Special keys\n * can rename/remove keys, otherwise is an additive patch.\n *\n * @param obj source obj to patch, possibly is a subobject in a recursive call\n * @param patchInfo data to patch into obj, possibly containing nested objects\n */\nfunction patch(obj: any, patchInfo: any): any {\n    Object.keys(patchInfo).forEach(patchKey => {\n        // grab the patchVal before updating patchKey\n        let patchVal = patchInfo[patchKey];\n        let objVal = obj[patchKey];\n        if (objVal) {\n            if (Array.isArray(patchVal) || Array.isArray(objVal)) {\n                // both are arrays, so full replace\n                obj[patchKey] = patchVal;\n            } else if (typeof (patchVal) === 'object' && typeof (objVal) === 'object') {\n                // {a: {b: 2}}, {a: {b: 3, c: 4}}\n                // patchKey = 'a';\n                // patchVal = {b: 3, c: 4}\n                // objVal = {b: 2}\n                // recurse\n                obj[patchKey] = patch(objVal, patchVal);\n            } else {\n                // not both objects, so full replace\n                obj[patchKey] = patchVal;\n            }\n        } else {\n            // does not exist yet, so set new\n            obj[patchKey] = patchVal;\n        }\n    });\n    return obj;\n};\n", "import { getIbGibAddr, } from '../../helper.mjs';\nimport { clone, getTimestamp, } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';\nimport { IbGib_V1, IbGibData_V1, IbGibRel8ns_V1, Rel8n } from '../types.mjs';\nimport { TransformOpts_Rel8, TransformResult, IbGibAddr } from '../../types.mjs';\nimport { IBGIB_DELIMITER, GIB, FORBIDDEN_ADD_RENAME_REMOVE_REL8N_NAMES } from '../constants.mjs';\nimport { buildDna, getGib, isPrimitive } from './transform-helper.mjs';\n/**\n * Original-ish V1 transform behavior.\n *\n * NOTE:\n *   This is NOT going to do the plan^gib stuff ATM.\n *   Also this does NOT add any identity information ATM.\n */\n/**\n * Relate (and/or unrelate) other ibGib(s), thus mutating it **extrinsically**.\n */\nexport async function rel8(\n    opts: TransformOpts_Rel8<IbGib_V1>\n): Promise<TransformResult<IbGib_V1>> {\n    const {\n        noTimestamp, dna, linkedRel8ns,\n        rel8nsToAddByAddr, rel8nsToRemoveByAddr,\n        type = 'rel8'\n    } = opts;\n    let src = opts.src;\n    const lc = '[rel8_v1]';\n    if (type !== 'rel8') { throw new Error(`${lc} not a rel8 transform.`); }\n    if (!opts.type) { opts.type = 'rel8' }\n\n    // #region validation\n\n    if (type !== 'rel8') { throw new Error(`${lc} not a rel8 transform.`); }\n    if (!opts.type) { opts.type = 'rel8' }\n\n    if (!src) { throw new Error(`${lc} src required.`); }\n    if (!src!.ib) { throw new Error(`${lc} src.ib required.`); }\n    if (src!.ib!.includes(IBGIB_DELIMITER)) {\n        throw new Error(`${lc} ib can't contain hardcoded delimiter (${IBGIB_DELIMITER}) right now.`);\n    }\n    if (!src!.gib) { throw new Error(`${lc} src.gib required.`); }\n\n    // if (!src.gib || src.gib === GIB) { throw new Error(`${lc} cannot relate to primitive ibGib.`); }\n    if (isPrimitive({ ibGib: src })) { throw new Error(`${lc} cannot relate/unrelate primitive ibgib`); }\n\n    // if neither add nor remove specified, what are we even doing?\n    const isAdding = rel8nsToAddByAddr && Object.keys(rel8nsToAddByAddr!).length > 0;\n    const isRemoving = rel8nsToRemoveByAddr && Object.keys(rel8nsToRemoveByAddr!).length > 0;\n    if (!(isAdding || isRemoving)) {\n        throw new Error(`${lc} gotta provide relations to either add or remove.`);\n    }\n\n    const srcAddr = getIbGibAddr({ ib: src.ib, gib: src.gib });\n    if (opts.srcAddr && srcAddr !== opts.srcAddr) { throw new Error(`${lc} srcAddr from src does not equal opts.srcAddr`); }\n    opts.srcAddr = srcAddr;\n\n    // validate all ibgib addresses to add/remove\n    const fnValidIbGibAddr = (s: string) => {\n        // for now, only requiring a single character and trailing delim.\n        // i.e. primitive with implied 'gib'\n        return s && typeof (s) === 'string' && s.length >= 2 &&\n            s.includes('^') && s.split('^')[0].length >= 1;\n    };\n    Object.keys(rel8nsToAddByAddr || {})\n        .map(x => (rel8nsToAddByAddr || {})[x])\n        .forEach(rel8ds => {\n            if (!(rel8ds && rel8ds.every(rel8d => fnValidIbGibAddr(rel8d)))) {\n                throw new Error(`${lc} Invalid rel8n attempt. Must be valid ibGibs. Did you include a delimiter (^)?`);\n            }\n        });\n    Object.keys(rel8nsToRemoveByAddr || {})\n        .map(x => (rel8nsToRemoveByAddr || {})[x])\n        .forEach(rel8ds => {\n            if (!(rel8ds && rel8ds.every(rel8d => fnValidIbGibAddr(rel8d)))) {\n                throw new Error(`${lc} Invalid remove rel8n attempt. Must be valid ibGibs. Did you include a delimiter (^)?`);\n            }\n        });\n\n    // #endregion validation\n\n    // we want to forget `src` proper very quickly because it may have other\n    // non-IbGib properties that are not relevant to our transform.\n    let dto: IbGib_V1 = { ib: src.ib, gib: src.gib, };\n    if (src.data && Object.keys(src.data).length > 0) { dto.data = src.data; }\n    if (src.rel8ns && Object.keys(src.rel8ns).length > 0) { dto.rel8ns = src.rel8ns; }\n    src = dto;\n\n    const newIbGib = clone(src) as IbGib_V1<IbGibData_V1>;\n\n    const data: any = clone(src.data || {});\n    if (opts.nCounter || Object.keys(data).includes('n')) {\n        if (Object.keys(data).includes('n')) {\n            if (Number.isInteger(data.n)) {\n                if (data.n >= 0) {\n                    data.n = data.n + 1;\n                } else {\n                    console.warn(`${lc} data.n is less than 0, which is unexpected. Resetting data.n to 0.`);\n                    data.n = 0;\n                }\n            } else {\n                throw new Error('cannot increment nCounter because data.n is not a number.');\n            }\n        } else {\n            data.n = 0;\n        }\n    }\n\n    if (!noTimestamp) {\n        const date = new Date();\n        data.timestamp = getTimestamp(date);\n        data.timestampMs = date.getMilliseconds();\n    }\n\n    const rel8ns: IbGibRel8ns_V1 = clone(src.rel8ns || {});\n    Object.keys(rel8nsToAddByAddr || {}).forEach(rel8nName => {\n        if (FORBIDDEN_ADD_RENAME_REMOVE_REL8N_NAMES.includes(rel8nName)) {\n            throw new Error(`${lc} Cannot manually add relationship: ${rel8nName}.`);\n        }\n        const existingRel8d = rel8ns[rel8nName] || [];\n        const toAddRel8d = rel8nsToAddByAddr![rel8nName];\n        const newRel8d = toAddRel8d!.filter(x => !existingRel8d.includes(x));\n        rel8ns[rel8nName] = existingRel8d.concat(newRel8d);\n    });\n    Object.keys(rel8nsToRemoveByAddr || {}).forEach(rel8nName => {\n        if (FORBIDDEN_ADD_RENAME_REMOVE_REL8N_NAMES.includes(rel8nName)) {\n            throw new Error(`${lc} Cannot manually remove relationship: ${rel8nName}.`);\n        }\n        const existingRel8d = rel8ns[rel8nName] || [];\n        const toRemoveRel8d = rel8nsToRemoveByAddr![rel8nName] || [];\n        const prunedRel8d = existingRel8d.filter((x: IbGibAddr) => !toRemoveRel8d!.includes(x));\n        if (prunedRel8d.length > 0) {\n            rel8ns[rel8nName] = prunedRel8d;\n        } else {\n            delete rel8ns[rel8nName];\n        }\n    });\n    rel8ns.past = (rel8ns.past || []).concat([srcAddr]);\n    (linkedRel8ns || [])\n        .filter(linkedRel8nName => Object.keys(rel8ns).includes(linkedRel8nName))\n        .filter(linkedRel8nName => (rel8ns[linkedRel8nName] || []).length > 1)\n        .forEach(linkedRel8nName => {\n            // take the last item only, and put it in an array\n            let initialLength = rel8ns[linkedRel8nName]!.length;\n            rel8ns[linkedRel8nName] = [rel8ns[linkedRel8nName]![initialLength - 1]];\n        });\n\n    // rel8ns.past = linkedRel8ns?.includes(Rel8n.past) ?\n    //     [srcAddr] :\n    //     (rel8ns.past || []).concat([srcAddr]);\n\n    if (data.isTjp) {\n        let tjpRel8n: IbGibAddr[] = rel8ns['tjp'] || [];\n        tjpRel8n.push(srcAddr);\n        rel8ns.tjp = tjpRel8n;\n        delete data.isTjp;\n    }\n\n    newIbGib.data = data;\n    newIbGib.rel8ns = rel8ns;\n    // newIbGib.gib = await sha256v1(newIbGib, '');\n    const hasTjp = (rel8ns.tjp?.length ?? 0) > 0;\n\n    let transformDna: IbGib_V1 | null = null;\n    if (dna) {\n        transformDna = await buildDna(opts);\n        const dnaAddr = getIbGibAddr({ ibGib: transformDna });\n        rel8ns.dna = linkedRel8ns?.includes(Rel8n.dna) ?\n            rel8ns.dna = [dnaAddr] :\n            rel8ns.dna = (rel8ns.dna || []).concat(dnaAddr);\n    }\n\n    newIbGib.gib = await getGib({ ibGib: newIbGib, hasTjp });\n\n    const result: TransformResult<IbGib_V1> = { newIbGib };\n    if (transformDna) { result.dnas = [transformDna]; }\n    return result;\n}\n", "import { clone, } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';\n\nimport { getIbGibAddr, } from '../helper.mjs';\nimport { getGibInfo } from './transforms/transform-helper.mjs';\nimport { IbGibRel8ns_V1, IbGib_V1 } from \"./types.mjs\";\nimport { GIB, GIB_DELIMITER } from './constants.mjs';\n\n/**\n * Helper function that checks the given `ibGib` to see if it\n * either has a tjp or is a tjp itself.\n *\n * ## notes\n *\n * Only unique ibGibs are meant to have tjps, or rather, if an\n * ibGib timeline is expected to be unique over \"time\", then the\n * tjp is an extremely convenient mechanism that provides a\n * \"name\" for that timeline.\n *\n * Otherwise, if they are not unique, then successive \"different\"\n * timelines cannot be easily referenced by their first unique\n * frame in time, making it much harder to pub/sub updates among\n * other things. (If there are no unique frames, then they are\n * the same ibGib.)\n *\n * ## tjp = temporal junction point\n *\n * I've written elsewhere on this as well. Refer to B2tF2.\n *\n * @returns true if the ibGib has/is a tjp, else false\n */\nexport function hasTjp({ ibGib }: { ibGib: IbGib_V1 }): boolean {\n    const lc = `[${hasTjp.name}]`;\n\n    if (!ibGib) {\n        console.warn(`${lc} ibGib falsy. (W: 884178562f5b4f15933ac4d98db74cc6)`);\n        return false;\n    }\n\n    if (ibGib.data?.isTjp || ibGib.rel8ns?.tjp?.length! > 0) {\n        return true;\n    }\n\n    // dna transforms do not have tjp\n    const dnaPrimitives = ['fork^gib', 'mut8^gib', 'rel8^gib'];\n    if ((ibGib.rel8ns?.ancestor ?? []).some(x => dnaPrimitives.includes(x))) {\n        return false;\n    }\n\n    if (!ibGib.gib) {\n        console.warn(`${lc} ibGib.gib falsy. (W: 6400d780822b44d992846f1196509be3)`);\n        return false;\n    }\n    if (ibGib.gib.includes(GIB_DELIMITER)) {\n        return true;\n    }\n\n    if (ibGib.gib === GIB) {\n        // primitive\n        return false;\n    }\n\n    // use more expensive getGibInfo call.\n    // could possibly just return false at this point, but since gib info\n    // would change if we change our standards for gib, this is nicer.\n    const gibInfo = getGibInfo({ ibGibAddr: getIbGibAddr({ ibGib }) });\n    return gibInfo.tjpGib ? true : false;\n}\n\n/**\n * If you have an ibgib object, it may also contain other properties/functions.\n *\n * This helper function takes the incoming object and returns a copy\n * @param param0\n * @returns\n */\nexport function toDto<TData, TRel8ns extends IbGibRel8ns_V1 = IbGibRel8ns_V1>({\n    ibGib,\n}: {\n    ibGib: IbGib_V1,\n}): IbGib_V1<TData, TRel8ns> {\n    const lc = `[${toDto.name}]`;\n    if (!ibGib.ib) { console.warn(`${lc} ibGib.ib is falsy. (W: e60e41c2a1fc48268379d88ce13cb77b)`); }\n    if (!ibGib.gib) { console.warn(`${lc} ibGib.gib is falsy. (W: fb3889cbf0684ae4ac51e48f28570377)`); }\n\n    let dtoIbGib: IbGib_V1<TData, TRel8ns> = { ib: (ibGib.ib || '').slice() };\n    if (ibGib.gib) { dtoIbGib.gib = ibGib.gib.slice(); };\n    if (ibGib.data) {\n        // we do not clone binaries when creating the dto.\n        dtoIbGib.data =\n            ibGib.data instanceof Uint8Array ?\n                ibGib.data :\n                clone(ibGib.data);\n    }\n    if (ibGib.rel8ns) { dtoIbGib.rel8ns = clone(ibGib.rel8ns); }\n\n    return dtoIbGib;\n}\n", "import {\n    HEXADECIMAL_HASH_STRING_REGEXP_32, HEXADECIMAL_HASH_STRING_REGEXP_64,\n} from '@ibgib/helper-gib/dist/constants.mjs';\nimport { extractErrorMsg } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';\n\nimport { Ib, IbGibAddr, } from '../types.mjs';\nimport { IbGibRel8ns_V1, IbGib_V1, } from './types.mjs';\nimport { IBGIB_DELIMITER, GIB, IB, GIB_DELIMITER, } from './constants.mjs';\nimport { isPrimitive, getGib, getGibInfo } from './transforms/transform-helper.mjs';\nimport { hasTjp, toDto } from './v1-helper.mjs';\nimport { getIbAndGib, getIbGibAddr } from '../helper.mjs';\n\nconst logalot = false;\n\n/**\n * validates the ibGib's address (`ib` and `gib` properties) and recalculates\n * the `gib` against the `ibGib.gib`.\n *\n * this validates not only that the punctiliar gib hash for this ibgib record\n * hashes to the same value, but it also checks the internal tjp address and\n * ensures that it is the same tjp gib in the gib field.\n *\n * ## notes\n *\n * * By checking the tjp gib is the same in the address as in the tjp rel8n, we\n *   are providing (extremely?) good corroboration that the tjp listed in the\n *   address is accurate. However, it may still be theoretically possible to\n *   forge an ibgib that both hashes to the punctiliar hash and matches up this\n *   tjpAddr.gib. This would be AFAICT quite challenging.\n */\nexport async function validateIbGibIntrinsically({\n    ibGib\n}: {\n    ibGib: IbGib_V1\n}): Promise<string[] | null> {\n    const lc = `[${validateIbGibIntrinsically.name}]`;\n    try {\n        let errors: string[] = [];\n        if (ibGib) {\n            const addr = getIbGibAddr({ ibGib });\n            errors = validateIbGibAddr({ addr }) ?? [];\n\n            if (errors.length > 0) {\n                console.error(`${lc} errors found in addr: ${addr}`);\n                return errors; // <<<< returns early\n            }\n\n            // rest of the function assumes correctly formatted ib and gib\n\n            // if it's a primitive, the caller knows (or should know!) there are no\n            // metadata guarantees.\n            if (isPrimitive({ gib: ibGib.gib })) { return null; }\n\n            // this validates not only that the punctiliar gib hash for this ibgib record\n            // hashes to the same value, but it also checks the internal tjp address and\n            // ensures that it is the same tjp gib.\n            // not necessary the dto here, but I'm sensitive at this point.\n            let gottenGib = await getGib({ ibGib: toDto({ ibGib }), hasTjp: hasTjp({ ibGib }) });\n            if (gottenGib !== ibGib.gib) {\n                if (ibGib.data?.src && ibGib.data.srcAddr && ibGib.ib === 'rel8') {\n                    // this is NOT the place to do this, but I'm plodding through trying to think of how to fix it\n                    // this is what it looks like in data\n                    // {\n                    //     \"rel8nsToAddByAddr\":{\n                    //         \"comment\":[\"comment 11221^F6B9477984D31FEF5FD25297CA39126A64ADDE2C91C1A2D670CCFE3965DEC4C9.847F0E9A1B2738DC167B32AA9B2D7D9B88B76F21848B1F193E994BB21F90DAEE\"]\n                    //     },\n                    //     \"dna\":true,\n                    //     \"nCounter\":true,\n                    //     \"type\":\"rel8\"\n                    // }\n                    delete ibGib.data.src;\n                    delete ibGib.data.srcAddr;\n                    gottenGib = await getGib({ ibGib: toDto({ ibGib }), hasTjp: hasTjp({ ibGib }) });\n                    if (gottenGib !== ibGib.gib) {\n                        errors.push(`Ibgib invalid intrinsically - gottenGib (${gottenGib}) does not equal ibGib.gib (${ibGib.gib}). (E: 020b71479e944b2198fe436e7e137786)`);\n                        // } else {\n                        //     debugger;\n                    }\n                } else {\n                    errors.push(`Ibgib invalid intrinsically - gottenGib (${gottenGib}) does not equal ibGib.gib (${ibGib.gib}). (E: 7416db016878430ca3c5b20697f164ed)`);\n                }\n            }\n\n            return errors.length > 0 ? errors : null;\n        } else {\n            errors.push(`ibGib is itself falsy. (E: 4fb98caf6ed24ef7b35a19cef56e2d7e)`);\n            return errors;\n        }\n\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    }\n}\n\n/**\n * Naive synchronous validation for ibgib addresses.\n *\n * @returns error string array if validation errors found, else null\n */\nexport function validateIbGibAddr({\n    addr,\n    delimiter,\n    version,\n}: {\n    addr: IbGibAddr,\n    delimiter?: string,\n    version?: string,\n}): string[] | null {\n    const lc = `[${validateIbGibAddr.name}]`;\n    try {\n        let errors: string[] = [];\n        if (version) { console.warn(`${lc} version not implemented yet. Ignoring. (W: 2d19db16ec0c4766b5d35248787671f3)`); }\n\n        // validate as a whole\n        if (!addr) {\n            errors.push(`addr required. (E: e9a54041aa0b41c1bb2324d9d2d42c7f)`);\n            return errors;\n        }\n        delimiter = delimiter || IBGIB_DELIMITER;\n        if (!addr.includes(delimiter)) { errors.push(`No delimiter (${delimiter}) found. (E: 05e28dcb70ff44019edc53ed508bd1e8)`); }\n        if (addr.startsWith(delimiter)) { errors.push(`addr starts with delim. (E: d29f808c5a47452f9bb3ea684694c6eb)`); }\n\n        // validate pieces...\n        const { ib, gib } = getIbAndGib({ ibGibAddr: addr, delimiter });\n\n        // ...ib\n        const resValidateIb = validateIb({ ib, ibGibAddrDelimiter: delimiter, version });\n        if (resValidateIb) { errors = errors.concat(resValidateIb); }\n\n        // ...gib\n        const resValidateGib = validateGib({ gib, ibGibAddrDelimiter: delimiter, version });\n        if (resValidateGib) { errors = errors.concat(resValidateGib); }\n\n        if (errors.length > 0) {\n            if (logalot) { console.log(`${lc} errors.length > 0. errors: ${errors.join('|')} (I: 9c18f993e138f15613e4c6a340d41722)`); }\n        }\n\n        // we're done\n        return errors.length > 0 ? errors : null;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    }\n}\n\n/**\n * Naive validation of ib.\n *\n * @returns errors array if found, else null\n */\nexport function validateIb({\n    ib,\n    ibGibAddrDelimiter,\n    version,\n}: {\n    ib: Ib,\n    ibGibAddrDelimiter?: string,\n    version?: string,\n}): string[] | null {\n    const lc = `[${validateIb.name}]`;\n    try {\n        const errors: string[] = [];\n        if (version) { console.warn(`${lc} version not implemented yet. Ignoring. (W: 71228ba4ed994aaa8149910e295ab087)`); }\n\n        if (!ib) {\n            errors.push(`ib required. (E: a76d06c7b9c24db3a731a91dbe46acd5)`);\n            return errors;\n        }\n\n        if (ib === IB) { return null; }\n\n        ibGibAddrDelimiter = ibGibAddrDelimiter || IBGIB_DELIMITER;\n        if (ib.includes(ibGibAddrDelimiter)) { errors.push(`ib contains ibGibAddrDelimiter (${ibGibAddrDelimiter}) (E: 09e61b46c3e84874bc02b6918f1f2c39)`); }\n\n        return errors.length > 0 ? errors : null;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    }\n}\n\n/**\n * validates a `gib` of some ibGib/ibGibAddr.\n *\n * @returns array of validation error strings (if any) or null\n */\nexport function validateGib({\n    gib,\n    gibDelimiter,\n    ibGibAddrDelimiter,\n    version,\n}: {\n    /**\n     * gib to validate.\n     *\n     * ## notes\n     *\n     * If the gib has a tjp embedded in it (i.e. the associated ibgib has a\n     * tjp), then this will call validation on that tjpGib recursively.\n     */\n    gib: Ib,\n    /**\n     * This is a delimiter used with tjpGibs.\n     *\n     * atow this is a dot (`'.'`).\n     *\n     * ## notes\n     *\n     * THIS IS NOT THE SAME THING AS THE `ibGibAddrDelimiter`!\n     */\n    gibDelimiter?: string,\n    /**\n     * This is a delimiter used with the entire ibGibAddr.\n     *\n     * atow this is a caret (`'^'`).\n     *\n     * ## notes\n     *\n     * THIS IS NOT THE SAME THING AS THE `gibDelimiter`!\n     */\n    ibGibAddrDelimiter?: string,\n    /**\n     * Ignored atow, but in the future, probably will be used.\n     * May end up being an IbGibAddr but who knows.\n     */\n    version?: string,\n}): string[] | null {\n    const lc = `[${validateGib.name}]`;\n    try {\n        const errors: string[] = [];\n        if (version) { console.warn(`${lc} version not implemented yet. Ignoring. (E: 90ced1db69774702b92acb261bdaee23)`); }\n\n        if (!gib) {\n            errors.push(`gib required. (E: e217de4035b04086827199f4bace189c)`);\n            return errors;\n        }\n\n        ibGibAddrDelimiter = ibGibAddrDelimiter || IBGIB_DELIMITER;\n        /** Need to move this to ts-gib */\n        const INVALID_GIB_CHARS = [ibGibAddrDelimiter];\n        const invalidCharsFound: string[] = [];\n        INVALID_GIB_CHARS.forEach(invalidChar => {\n            if (gib.includes(invalidChar)) { invalidCharsFound.push(invalidChar); }\n        });\n        if (invalidCharsFound.length > 0) {\n            errors.push(`gib (${gib}}) contains invalid characters: (${JSON.stringify(invalidCharsFound.join(','))}) (E: 1e584258d9e049ba9ce7e516f3ab97f1)`);\n        }\n\n        // punctiliar = point, i.e., a single point in the universe, either a\n        // single point in time in a tjp ibgib's timeline, or a single point in\n        // space that lives outside of time (has no tjp thus no timeline).\n        //\n        // So if we've gotten here in code, then our gib is truthy and doesn't\n        // contain invalid characters.\n\n        const { punctiliarHash, tjpGib, isPrimitive } =\n            getGibInfo({ gib, gibDelimiter: gibDelimiter || GIB_DELIMITER });\n\n        // automatically valid if it's a primitive, as the caller should expect\n        // no cryptographical guarantees\n        if (isPrimitive) { return null; }\n\n        // Gib is not primitive so must have at least the punctiliar hash.\n        if (!punctiliarHash) { throw new Error(`${lc} punctiliarHash is falsy on a non-primitive gib. (E: 72835394918241bdb2632bf0510bdae5)`); }\n        const punctiliarHashIs_32 = punctiliarHash!.match(HEXADECIMAL_HASH_STRING_REGEXP_32);\n        const punctiliarHashIs_64 = punctiliarHash!.match(HEXADECIMAL_HASH_STRING_REGEXP_64);\n        if (!punctiliarHashIs_32 && !punctiliarHashIs_64) {\n            errors.push('gib punctiliar hash is neither a 32- or 64-char hash string. (E: d47ff6d6e14b4c02a62107090c8dad39)');\n        }\n\n        if (tjpGib) {\n            // if it is an ibgib in a timeline, that timeline has a tjp and this\n            // gib has a tjpGib component. So we must recursively validate the\n            // tjpGib\n            const tjpGibValidationErrors = validateGib({ gib: tjpGib });\n            if ((tjpGibValidationErrors ?? []).length > 0) {\n                errors.push(`tjpGib has errors (E: d6b79228d4a64c0b967cdb0efcea4d0d). tjpGibValidationErrors: ${tjpGibValidationErrors!.join('. ')}`);\n            }\n        }\n\n        return errors.length > 0 ? errors : null;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    }\n}\n\n/**\n * verifies that\n * @param param0\n * @returns\n */\nexport function validateRel8nsIntrinsically({\n    rel8ns,\n}: {\n    rel8ns: IbGibRel8ns_V1,\n}): string[] | null {\n    const lc = `[${validateRel8nsIntrinsically.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 62b4722599798dd8ab95fcebf42c0e23)`); }\n\n        let errors: string[] = [];\n\n        const rel8nNames = Object.keys(rel8ns);\n        for (let i = 0; i < rel8nNames.length; i++) {\n            // all rel8nNames/keys are strings\n            const rel8nName = Object.keys(rel8ns)[i];\n            if (typeof rel8nName !== 'string') {\n                errors.push(`non-string rel8nName found. all keys of rel8ns must be of type string. (E: 3b2e4582b638421681951f5475c85178)`)\n            }\n\n            // all values are ibgib addr arrays\n            const addrs = rel8ns[rel8nName] ?? [];\n            for (let j = 0; j < addrs.length; j++) {\n                const addr = addrs[j];\n                const addrErrors = validateIbGibAddr({ addr }) ?? [];\n                if (addrErrors.length > 0) {\n                    errors.push(`invalid addr found for rel8nName (${rel8nName}). addr errors: ${addrErrors.join('|')} (E: 56809a746c4f462db426e90395b80364)`);\n                }\n            }\n        }\n        return errors.length > 0 ? errors : null;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n", "import { extractErrorMsg, getUUID } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';\n\nimport { fork } from './transforms/fork.mjs';\nimport { mut8 } from './transforms/mut8.mjs';\nimport { rel8 } from './transforms/rel8.mjs';\nimport { Ib, IbGib, IbGibRel8ns, TransformResult, TemporalJunctionPointOptions } from '../types.mjs';\nimport { IbGib_V1, IbGibData_V1, IbGibRel8ns_V1 } from './types.mjs';\nimport { IB, GIB, ROOT, IB_REGEXP_DEFAULT, FORBIDDEN_ADD_RENAME_REMOVE_REL8N_NAMES } from './constants.mjs';\nimport { validateIb } from './validate-helper.mjs';\nimport { getGib } from './transforms/transform-helper.mjs';\n\nconst logalot = false;\n\nexport class Factory_V1 {\n    static root() {\n        return Factory_V1.primitive({ ib: IB });\n    }\n\n    /**\n     * Returns an ibGib primitive with the given `ib`, e.g. \"{ib: '7', gib: 'gib'}\".\n     *\n     * @returns a single primitive ibGib\n     */\n    static primitive({\n        ib\n    }: {\n        ib: Ib\n    }): IbGib_V1 {\n        return { ib, gib: GIB };\n    }\n\n    /**\n     * generates multiple primitive ibgibs from the given `ibs` array.\n     * @returns array of generated ibgibs.\n     */\n    static primitives({\n        ibs\n    }: {\n        ibs: Ib[]\n    }): IbGib_V1[] {\n        return ibs.map(ib => Factory_V1.primitive({ ib }));\n    }\n\n    /**\n     * Takes the incoming `parentIbGib` and forks it. Then applies the\n     * `data` and/or `rel8ns` if any, depending on the other config params.\n     *\n     * @returns The entire transform result object that includes the newly produced ibGib as well as any derivative/intermediate ibgibs.\n     */\n    static async firstGen<TData = any>({\n        ib = IB,\n        parentIbGib = Factory_V1.root(),\n        data,\n        rel8ns,\n        dna,\n        tjp,\n        linkedRel8ns,\n        noTimestamp,\n        nCounter,\n        squash,\n    }: {\n        ib: Ib,\n        parentIbGib: IbGib,\n        data?: TData,\n        rel8ns?: IbGibRel8ns,\n        dna?: boolean,\n        tjp?: TemporalJunctionPointOptions;\n        linkedRel8ns?: string[],\n        /**\n         * If true, no timestamp will be\n         */\n        noTimestamp?: boolean,\n        /**\n         * if true, data.n will be set to 0 on the first frame, and 1 on the\n         * second.\n         */\n        nCounter?: boolean,\n        /**\n         * ONLY USED IF {@link dna} IS FALSY.\n         *\n         * If {@link dna} is falsy and this is true, then the resulting 1st gen\n         * ibgib will be squashed into a single frame, even if both mut8 and\n         * rel8 transforms are executed.\n         *\n         * ## intent / driving use case\n         *\n         * We are working on the new, production-quality v1 sync saga and we\n         * want the saga ibgib to be one frame per participant (Alice, Bob).\n         * So Alice creates one frame, then Bob evolves 1 frame, etc. No dna\n         * is required, because this is not meant to be merged at a later time.\n         *\n         * So the use case is when you don't need dna and you want a single\n         * frame.\n         */\n        squash?: boolean,\n    }): Promise<TransformResult<IbGib_V1>> {\n        const lc = `[${Factory_V1.name}][${Factory_V1.firstGen.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: b7152fbd94382516d9f7c591bcf4c326)`); }\n\n            if (dna && squash) { throw new Error(`both dna and squash cannot be true. Squash requires that no dna exist. (E: abfc58b4a4c8654924aa5428d0831826)`); }\n\n            /** * Multiple transform steps will create multiple results. */\n            const interimResults: TransformResult<IbGib_V1>[] = [];\n            let src: IbGib_V1 = parentIbGib || ROOT;\n            let resFork = await fork({\n                src,\n                destIb: ib,\n                tjp,\n                dna,\n                linkedRel8ns,\n                noTimestamp,\n                nCounter,\n            });\n            interimResults.push(resFork);\n            src = resFork.newIbGib;\n\n            if (data) {\n                let resMut8 = await mut8({\n                    src,\n                    dataToAddOrPatch: data,\n                    dna,\n                    linkedRel8ns,\n                    noTimestamp,\n                    nCounter,\n                });\n                interimResults.push(resMut8);\n                src = resMut8.newIbGib;\n            };\n\n            if (rel8ns) {\n                let resRel8 = await rel8({\n                    src,\n                    rel8nsToAddByAddr: rel8ns,\n                    dna,\n                    linkedRel8ns,\n                    noTimestamp,\n                    nCounter,\n                });\n                interimResults.push(resRel8);\n                // src = resRel8.newIbGib; // not needed because not used (this is the last step)\n            }\n\n            if (interimResults.length > 1) {\n                const newIbGib = interimResults.slice(interimResults.length - 1)[0].newIbGib;\n                const resultWithIntermediates = {\n                    newIbGib,\n                    /**\n                     * all the interResults except the last one go in the intermediate ibGibs\n                     */\n                    intermediateIbGibs: interimResults.slice(0, interimResults.length - 1).map(x => x.newIbGib),\n                } as TransformResult<IbGib_V1>;\n\n                if (dna) {\n                    if (squash) { (`${lc} (E: 62c595422e21ad8ce8eae658976fd826)`) }\n\n                    // combine all of the interim dnas\n                    let dnas: IbGib_V1[] = [];\n                    interimResults.forEach(res => { dnas = dnas.concat(res.dnas!); });\n                    resultWithIntermediates.dnas = dnas;\n\n                    return resultWithIntermediates;\n                } else if (squash) {\n                    // manually remove past and change the tjp, if it exists, reset n\n                    if (!newIbGib.rel8ns) { throw new Error(`(UNEXPECTED) newIbGib.rel8ns is falsy? (E: 6b09e8057fc5b00c6cfd13be60e97f26)`); }\n\n                    delete newIbGib.rel8ns.past;\n\n                    if (newIbGib.rel8ns.tjp) {\n                        delete newIbGib.rel8ns.tjp;\n                        newIbGib.data ??= {};\n                        newIbGib.data.isTjp = true;\n                    }\n\n                    if (nCounter) {\n                        newIbGib.data ??= {};\n                        newIbGib.data.n = 0;\n                    }\n\n                    // recalculate the gib\n                    newIbGib.gib = await getGib({ ibGib: newIbGib });\n\n                    const resultSquashed: TransformResult<IbGib_V1> = { newIbGib };\n\n                    return resultSquashed;\n                } else {\n                    // no dna and no squash\n                    return resultWithIntermediates;\n                }\n            } else if (interimResults.length === 1) {\n                // for some reason the caller just used this as a fork.\n                return interimResults[0];\n            } else {\n                throw new Error(`(UNEXPECTED) interimResults.length is not 1 and not greater than 1? 0? But we had to fork? (E: a256c88c56916a46a888796f76ef4826)`);\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * Generate an ibgib datum that has no dna and no timeline.\n     * It's a one-off ibgib.\n     *\n     * This is similar to {@link Factory_V1.constant}, but this is not\n     * necessarily deterministic. It can have a timestamp and/or uuid, though it\n     * does not have dna, nCounter, or a tjp.\n     *\n     * ## validation\n     *\n     * * validates the given `ib` against `ibRegExpPattern` or default regexp.\n     * * validates that rel8ns doesn't include default forbidden rel8n names or\n     *   atow `'tjp'`.\n     *\n     * ## intent\n     *\n     * Stones are useful for one-off ibgibs that are not part of a timeline, but\n     * which still should have a timestamp and/or uuid.\n     *\n     * @see {@link Factory_V1.constant}\n     */\n    static async stone<\n        TData extends IbGibData_V1 = any,\n        TRel8ns extends IbGibRel8ns_V1 = IbGibRel8ns_V1\n    >({\n        parentPrimitiveIb,\n        ib,\n        ibRegExpPattern,\n        data,\n        rel8ns,\n        noTimestamp,\n        uuid,\n    }: {\n        parentPrimitiveIb: Ib,\n        ib: Ib,\n        /**\n         * for checking the stone's generated ib\n         */\n        ibRegExpPattern?: string,\n        data?: TData,\n        rel8ns?: TRel8ns,\n        noTimestamp?: boolean,\n        /**\n         * If true, will generate a uuid for the stone. If falsy, will not.\n         */\n        uuid?: boolean,\n    }): Promise<IbGib_V1<TData, TRel8ns>> {\n        const lc = `[${Factory_V1.name}][${Factory_V1.stone.name}]`;\n        try {\n            // validation\n            // parentPrimitiveIb\n            if (!parentPrimitiveIb) { throw new Error(`parentPrimitiveIb required. (E: genuuid)`); }\n            if (validateIb({ ib: parentPrimitiveIb }) !== null) { throw new Error(`Invalid parentPrimitiveIb: ${parentPrimitiveIb}. (E: genuuid)`); }\n\n            // ib\n            if (!ib) { throw new Error(`ib required. (E: genuuid)`); }\n            const regExp = ibRegExpPattern ? new RegExp(ibRegExpPattern) : IB_REGEXP_DEFAULT;\n            if (!ib.match(regExp)) { throw new Error(`invalid ib. does not match regexp (${regExp}) (E: genuuid)`); }\n\n            // rel8ns\n            const incomingRel8nNames = Object.keys(rel8ns ?? {});\n            const forbiddenRel8nNames = [...FORBIDDEN_ADD_RENAME_REMOVE_REL8N_NAMES, 'tjp'];\n            const rel8nsIsInvalid = incomingRel8nNames.some(x => {\n                // we don't want constants trying to look like they have/are descendants/tjps/etc.\n                return forbiddenRel8nNames.includes(x);\n            });\n            if (rel8nsIsInvalid) { throw new Error(`Invalid rel8ns. forbiddenRel8nNames: ${forbiddenRel8nNames}. rel8ns keys: ${Object.keys(rel8ns ?? {})}. (E: genuuid)`); }\n\n\n            // create the stone by using the firstGen factory. Then we'll pare\n            // off what we don't need.\n            const resFirstGen = await Factory_V1.firstGen({\n                ib,\n                parentIbGib: Factory_V1.primitive({ ib: parentPrimitiveIb }),\n                data,\n                rel8ns,\n                dna: false,\n                noTimestamp,\n                nCounter: false,\n            });\n            const stoneIbGib = resFirstGen.newIbGib as IbGib_V1<TData, TRel8ns>;\n            if (uuid) {\n                if (!stoneIbGib.data) { stoneIbGib.data = {} as TData; }\n                stoneIbGib.data.uuid = await getUUID();\n            }\n\n            // remove any extraneous stuff\n            if (stoneIbGib.rel8ns?.past) { delete stoneIbGib.rel8ns.past; }\n            if (stoneIbGib.rel8ns?.tjp) { delete stoneIbGib.rel8ns.tjp; }\n\n            // recalculate the gib hash\n            stoneIbGib.gib = await getGib({\n                ibGib: {\n                    ib: stoneIbGib.ib,\n                    data: stoneIbGib.data,\n                    rel8ns: stoneIbGib.rel8ns,\n                },\n                hasTjp: false,\n            });\n\n            return stoneIbGib;\n        } catch (error) {\n            console.error(`${lc} ${error.message}`);\n            throw error;\n        }\n    }\n\n    /**\n     * Generate a deterministic ibgib datum that has no dna and no timeline.\n     * It's a one-off ibgib.\n     *\n     * Because this is supposed to create and re-create deterministically the equivalent\n     * of a non-primitive ibgib \"constant\", this function creates a single ibgib with...\n     * * one ancestor\n     * * no past, dna, or tjp rel8ns\n     * * no tjp timestamp or uuid\n     * * no nCounter\n     *\n     * This is similar to {@link Factory_V1.stone}, but with guaranteed no\n     * timestamp or uuid (unless incoming {@link data} contains a uuid).\n     *\n     * @see {@link Factory_V1.stone}\n     *\n     * ## intent\n     *\n     * I want to be able to create deterministic ibGibs that I can reference at\n     * runtime, similar to an ibgib primitive (e.g. \"root^gib\"), but with the\n     * integrity of the `gib` hash. This way, I can reference a deterministic ibgib\n     * from code at compile time, and at runtime this will have a corresponding\n     * ibgib datum with gib-hashed integrity.\n     *\n     * ## example\n     *\n     * I want to create a \"hard-coded\" schema ibgib that I rel8 to some protocol\n     * ibgib. So I'll create the data here, which lives in source control in a text file,\n     * and then I'll render that as an ibgib that verifies integrity. If I as a coder change\n     * it at all, then the `gib` of course will be different.\n     */\n    static async constant<\n        TData extends IbGibData_V1 = any,\n        TRel8ns extends IbGibRel8ns_V1 = IbGibRel8ns_V1\n    >({\n        parentPrimitiveIb,\n        ib,\n        ibRegExpPattern,\n        data,\n        rel8ns,\n    }: {\n        parentPrimitiveIb: Ib,\n        ib: Ib,\n        /**\n         * for checking the constant's generated ib\n         */\n        ibRegExpPattern?: string,\n        data?: TData,\n        rel8ns?: TRel8ns,\n    }): Promise<IbGib_V1<TData, TRel8ns>> {\n        const lc = `[${Factory_V1.name}][${Factory_V1.constant.name}]`;\n        try {\n            const constantIbGib = await Factory_V1.stone({\n                parentPrimitiveIb,\n                ib,\n                ibRegExpPattern,\n                data,\n                rel8ns,\n                noTimestamp: true,\n                uuid: false,\n            });\n            return constantIbGib;\n        } catch (error) {\n            console.error(`${lc} ${error.message}`);\n            throw error;\n        }\n    }\n}\n", "/**\n * @module core-constants\n *\n * # IMPORTANT!\n *\n * In order to be able to actually use this in an ionic-gib-like clone front end,\n * I want to be sure to include all of these. So I can't remove/comment it out here\n * without putting it _somewhere_. For example, the very first import atow is a\n * reference to @capacitor/filesystem. This should not go in this package (core-gib)\n * so I'm going to create another lib specific to ionic/capacitor and put it there\n * **before** removing it from/commenting it out in this file.\n *\n * # about this file\n *\n * I'm copying this lump sum from ionic-gib and am breaking it out slowly into\n * other more specific constant files. When a constant is moved into one of\n * those sub files, then I will remove it from this file.\n *\n * Ultimately, this should only contain global constants like the logalot\n * and timer settings.\n */\n\nimport { GIB } from \"@ibgib/ts-gib/dist/V1/constants.mjs\";\nimport { IbGib_V1 } from \"@ibgib/ts-gib/dist/V1/types.mjs\";\n\n\n/**\n * Naive selective logging/tracing mechanism.\n *\n * I manually switch this in individual files as needed while\n * developing/troubleshooting. I can change it here to turn on extremely verbose\n * logging application wide (and turn off individual files).\n */\nexport const GLOBAL_LOG_A_LOT: boolean | number = false;\n\n/**\n * Used in console.timeLog() calls.\n */\nexport const GLOBAL_TIMER_NAME = '[core^gib timer]';\n\n\n// export const UUID_REGEXP = /^[a-zA-Z0-9_\\-.]{1,256}$/;\n\n/**\n * regular expression for a classname.\n *\n * Used in witnesses atm.\n */\nexport const CLASSNAME_REGEXP = /^[a-zA-Z0-9_]{1,255}$/;\n\n/**\n * Much restricted list of chars in english.\n *\n * ## intent\n *\n * When sanitizing input.\n */\nexport const SAFE_SPECIAL_CHARS = `.'\",!?-`;\n\nexport const IB_MAX_LENGTH_DEFAULT = 155;\n\n/**\n * Defaults to word characters, space, tab, hyphen, and other\n * non-slash (path navigating) chars.\n *\n * Does not allow new lines or other whitespace, only tabs and spaces.\n *\n * ## atow\n *\n * `^[\\\\w\\\\t\\\\-|=+.&%\\$#@!~\\` \\\\[\\\\]\\\\(\\\\)\\\\{\\\\}]{1,${IB_MAX_LENGTH_DEFAULT}}$`\n */\nexport const IB_REGEXP_DEFAULT = new RegExp(`^[\\\\w\\\\t\\\\-|=+.&%\\$#@!~\\` \\\\[\\\\]\\\\(\\\\)\\\\{\\\\}]{1,${IB_MAX_LENGTH_DEFAULT}}$`);\n\n/**\n * Ionicons const \"enum\"\n */\nexport const IONICONS = [\n    'add',\n    'add-circle',\n    'alert',\n    'alert-circle',\n    'add',\n    'airplane',\n    'alarm',\n    'albums',\n    'alert',\n    'alert-circle',\n    'american-football',\n    'analytics',\n    'aperture',\n    'apps',\n    'archive',\n    'arrow-back',\n    'arrow-back-circle',\n    'arrow-down',\n    'arrow-down-circle',\n    'arrow-forward',\n    'arrow-forward-circle',\n    'arrow-redo',\n    'arrow-redo-circle',\n    'arrow-undo',\n    'arrow-undo-circle',\n    'arrow-up',\n    'arrow-up-circle',\n    'at',\n    'at-circle',\n    'attach',\n    'backspace',\n    'bandage',\n    'bar-chart',\n    'barbell',\n    'barcode',\n    'baseball',\n    'basket',\n    'basketball',\n    'battery-charging',\n    'battery-dead',\n    'battery-full',\n    'battery-half',\n    'beaker',\n    'bed',\n    'beer',\n    'bicycle',\n    'bluetooth',\n    'boat',\n    'body',\n    'bonfire',\n    'book',\n    'bookmark',\n    'bookmarks',\n    'briefcase',\n    'browsers',\n    'brush',\n    'bug',\n    'build',\n    'bulb',\n    'bus',\n    'business',\n    'cafe',\n    'calculator',\n    'calendar',\n    'call',\n    'camera',\n    'camera-reverse',\n    'car',\n    'car-sport',\n    'card',\n    'caret-back',\n    'caret-back-circle',\n    'caret-down',\n    'caret-down-circle',\n    'caret-forward',\n    'caret-forward-circle',\n    'caret-up',\n    'caret-up-circle',\n    'cart',\n    'cash',\n    'cellular',\n    'chatbox',\n    'chatbox-ellipses',\n    'chatbubble',\n    'chatbubble-ellipses',\n    'chatbubbles',\n    'checkbox',\n    'checkmark',\n    'checkmark-circle',\n    'checkmark-done',\n    'checkmark-done-circle',\n    'chevron-back',\n    'chevron-back-circle',\n    'chevron-down',\n    'chevron-down-circle',\n    'chevron-forward',\n    'chevron-forward-circle',\n    'chevron-up',\n    'chevron-up-circle',\n    'clipboard',\n    'close',\n    'close-circle',\n    'cloud',\n    'cloud-circle',\n    'cloud-done',\n    'cloud-download',\n    'cloud-offline',\n    'cloud-upload',\n    'cloudy',\n    'cloudy-night',\n    'code',\n    'code-download',\n    'code-slash',\n    'code-working',\n    'cog',\n    'color-fill',\n    'color-filter',\n    'color-palette',\n    'color-wand',\n    'compass',\n    'construct',\n    'contract',\n    'contrast',\n    'copy',\n    'create',\n    'crop',\n    'cube',\n    'cut',\n    'desktop',\n    'disc',\n    'document',\n    'document-attach',\n    'document-text',\n    'documents',\n    'download',\n    'duplicate',\n    'ear',\n    'earth',\n    'easel',\n    'egg',\n    'ellipse',\n    'ellipsis-horizontal',\n    'ellipsis-horizontal-circle',\n    'ellipsis-vertical',\n    'ellipsis-vertical-circle',\n    'enter',\n    'exit',\n    'expand',\n    'eye',\n    'eye-off',\n    'eyedrop',\n    'fast-food',\n    'female',\n    'file-tray',\n    'file-tray-full',\n    'file-tray-stacked',\n    'film',\n    'filter',\n    'finger-print',\n    'fitness',\n    'flag',\n    'flame',\n    'flash',\n    'flash-off',\n    'flashlight',\n    'flask',\n    'flower',\n    'folder',\n    'folder-open',\n    'football',\n    'funnel',\n    'game-controller',\n    'gift',\n    'git-branch',\n    'git-commit',\n    'git-compare',\n    'git-merge',\n    'git-network',\n    'git-pull-request',\n    'glasses',\n    'globe',\n    'golf',\n    'grid',\n    'hammer',\n    'hand-left',\n    'hand-right',\n    'happy',\n    'hardware-chip',\n    'headset',\n    'heart',\n    'heart-circle',\n    'heart-dislike',\n    'heart-dislike-circle',\n    'heart-half',\n    'help',\n    'help-buoy',\n    'help-circle',\n    'home',\n    'hourglass',\n    'ice-cream',\n    'image',\n    'images',\n    'infinite',\n    'information',\n    'information-circle',\n    'journal',\n    'key',\n    'keypad',\n    'language',\n    'laptop',\n    'layers',\n    'leaf',\n    'library',\n    'link',\n    'list',\n    'list-circle',\n    'locate',\n    'location',\n    'lock-closed',\n    'lock-open',\n    'log-in',\n    'magnet',\n    'mail',\n    'mail-open',\n    'mail-unread',\n    'male',\n    'male-female',\n    'man',\n    'map',\n    'medal',\n    'medical',\n    'medkit',\n    'megaphone',\n    'menu',\n    'mic',\n    'mic-circle',\n    'mic-off',\n    'mic-off-circle',\n    'moon',\n    'move',\n    'musical-note',\n    'musical-notes',\n    'navigate',\n    'navigate-circle',\n    'newspaper',\n    'notifications',\n    'notifications-circle',\n    'notifications-off',\n    'notifications-off-circle',\n    'nuclear',\n    'nutrition',\n    'open',\n    'options',\n    'paper-plane',\n    'partly-sunny',\n    'pause',\n    'pause-circle',\n    'paw',\n    'pencil',\n    'people',\n    'people-circle',\n    'person',\n    'person-add',\n    'person-circle',\n    'person-remove',\n    'phone-landscape',\n    'phone-portrait',\n    'pie-chart',\n    'pin',\n    'pint',\n    'pizza',\n    'planet',\n    'play',\n    'play-back',\n    'play-back-circle',\n    'play-circle',\n    'play-forward',\n    'play-forward-circle',\n    'play-skip-back',\n    'play-skip-back-circle',\n    'play-skip-forward',\n    'play-skip-forward-circle',\n    'podium',\n    'power',\n    'pricetag',\n    'pricetags',\n    'print',\n    'pulse',\n    'push',\n    'qr-code',\n    'radio',\n    'radio-button-off',\n    'radio-button-on',\n    'rainy',\n    'reader',\n    'receipt',\n    'recording',\n    'refresh',\n    'refresh-circle',\n    'reload',\n    'reload-circle',\n    'remove',\n    'remove-circle',\n    'reorder-four',\n    'reorder-three',\n    'reorder-two',\n    'repeat',\n    'resize',\n    'restaurant',\n    'return-down-back',\n    'return-down-forward',\n    'return-up-back',\n    'return-up-forward',\n    'ribbon',\n    'rocket',\n    'rose',\n    'sad',\n    'save',\n    'scan',\n    'scan-circle',\n    'school',\n    'search',\n    'search-circle',\n    'send',\n    'server',\n    'settings',\n    'shapes',\n    'share',\n    'share-social',\n    'shield',\n    'shield-checkmark',\n    'shirt',\n    'shuffle',\n    'skull',\n    'snow',\n    'speedometer',\n    'square',\n    'star',\n    'star-half',\n    'stats-chart',\n    'stop',\n    'stop-circle',\n    'stopwatch',\n    'subway',\n    'sunny',\n    'swap-horizontal',\n    'swap-vertical',\n    'sync',\n    'sync-circle',\n    'tablet-landscape',\n    'tablet-portrait',\n    'tennisball',\n    'terminal',\n    'text',\n    'thermometer',\n    'thumbs-down',\n    'thumbs-up',\n    'thunderstorm',\n    'time',\n    'timer',\n    'today',\n    'toggle',\n    'trail-sign',\n    'train',\n    'transgender',\n    'trash',\n    'trash-bin',\n    'trending-down',\n    'trending-up',\n    'triangle',\n    'trophy',\n    'tv',\n    'umbrella',\n    'videocam',\n    'volume-high',\n    'volume-low',\n    'volume-medium',\n    'volume-mute',\n    'volume-off',\n    'walk',\n    'wallet',\n    'warning',\n    'watch',\n    'water',\n    'wifi',\n    'wine',\n    'woman',\n];\n\n// #region other robbot related\n\n/**\n * Robbot.data.name regexp\n */\nexport const ROBBOT_NAME_REGEXP = /^[a-zA-Z0-9_\\-.]{1,255}$/;\nexport const ROBBOT_PREFIX_SUFFIX_REGEXP = /^[a-zA-Z0-9_\\-.\\s\uD83D\uDC40\uD83E\uDD16:;&]{1,64}$/;\nexport const ROBBOT_PREFIX_SUFFIX_REGEXP_DESC =\n    `0 to 64 alphanumerics, spaces, select special characters and emojis.`;\n\n// #endregion other robbot related\n\n// #region gestures\n\nexport const GESTURE_DOUBLE_CLICK_THRESHOLD_MS = 500;\n/**\n * If a gesture's move threshold is less than this, then it can still be\n * considered a single punctiliar click. Otherwise, it's a move event.\n *\n * IOW, a click gesture only is considered a \"click\" if the onMove is triggered\n * less than this many times. If onMove is detected more than this many times,\n * then a move gesture will be triggered.\n */\nexport const GESTURE_CLICK_TOLERANCE_ONMOVE_THRESHOLD_COUNT = 5;\n\n// #endregion gestures\n\nexport const SIMPLE_CONFIG_KEY_APP_VISIBLE = 'appBarVisible';\nexport const SIMPLE_CONFIG_KEY_APP_SELECTED = 'appBarSelectedApp';\nexport const SIMPLE_CONFIG_KEY_ROBBOT_VISIBLE = 'robbotBarVisible';\nexport const SIMPLE_CONFIG_KEY_ROBBOT_SELECTED_ADDR = 'robbotBarSelectedAddr';\n\n// #region app\n\nexport const DEFAULT_APP_ICON = 'apps-outline';\n\n// #endregion app\n\nexport const YOUTUBE_LINK_REG_EXP = /^https:\\/\\/youtu\\.be\\/\\w+$/;\n\nexport const WEB_1_PATHS = ['welcome', 'about-us', 'your-data'];\n", "// #region from common/types/legacy.ts\n\n// todo: clean up legacy get/put functions\n// I started ionic-gib without a clear architectural design, so this is \"legacy\"\n// with respect to that. I had several functions that used these types, and I\n// left them as-is at the time. after this refactor, this needs to be cleaned\n// up. Perhaps this goes in capacitor-gib even?\n\nimport { IbGibAddr } from '@ibgib/ts-gib/dist/types.mjs';\nimport { IbGib_V1 } from '@ibgib/ts-gib/dist/V1/index.mjs';\nimport { IbGibSpaceAny } from '../../witness/space/space-base-v1.mjs';\n\nexport interface FileResult {\n    success?: boolean;\n    /**\n     * If errored, this will contain the errorMsg.\n     */\n    errorMsg?: string;\n    /**\n     * True if failed due to timing out.\n     */\n    timedOut?: boolean;\n}\n\n/**\n * Options for retrieving data from the file system.\n */\nexport interface GetIbGibOpts {\n    /**\n     * If getting ibGib object, this is its address.\n     */\n    addr?: IbGibAddr;\n    /**\n     * If getting multiple ibGibs, use this array of addrs.\n     */\n    addrs?: IbGibAddr[];\n    /**\n     * Are we looking for a DNA ibgib?\n     */\n    isDna?: boolean;\n    /**\n     * space from which to get the ibgib\n     *\n     * @default localUserSpace\n     */\n    space?: IbGibSpaceAny,\n    /**\n     * If supplied, first acquires the lock with this scope on the\n     * given `space` (which defaults to localUserSpace).\n     */\n    lockScope?: string,\n    /**\n     * Cancels if can't acquire lock after approximately this time.\n     */\n    lockTimeoutMs?: number,\n    /**\n     * If true, will not get from cache and will force retrieval from the real\n     * bucket. In Ionic space, this means will look in ionic storage proper.\n     */\n    force?: boolean;\n}\n\n/**\n * Result for retrieving an ibGib from the file system.\n */\nexport interface GetIbGibResult extends FileResult {\n    /**\n     * ibGibs if retrieving a \"regular\" ibGib.\n     *\n     * This is used when you're not getting a pic, e.g.\n     */\n    ibGibs?: IbGib_V1[];\n    /**\n     * This is used when you're getting a pic's binary content.\n     */\n    // binData?: any;\n    /**\n     * access to raw result ibgib that caller must cast to the correct shape.\n     */\n    rawResultIbGib?: IbGib_V1;\n}\n\nexport interface PutIbGibOpts {\n    /**\n     * ibGib to put.\n     *\n     * If you only want to do just one, use this param. Otherwise, use the\n     * `ibGibs` array param.\n     */\n    ibGib?: IbGib_V1;\n    /**\n     * ibGibs to put in the space.\n     *\n     * If you want to put more than one ibGib, use this param. If you only\n     * want to put a single ibGib, you could also use the `ibGib` param.\n     */\n    ibGibs?: IbGib_V1[];\n    /**\n     * if true, will store this data in the bin folder with its hash.\n     */\n    // binData?: string;\n    /**\n     * If true, will store in a different folder.\n     */\n    isDna?: boolean;\n    /**\n     * extension to store the bindata with.\n     */\n    // binExt?: string;\n    /**\n     * If true, will replace an existing ibGib file\n     */\n    force?: boolean;\n    /**\n     * space into which we shall put the ibgib.\n     *\n     * @default localCurrentSpace\n     */\n    space?: IbGibSpaceAny,\n}\n\n/**\n * Result for putting ibgib.\n */\nexport interface PutIbGibResult extends FileResult {\n    binHash?: string;\n}\n\nexport interface DeleteIbGibOpts extends GetIbGibOpts { }\nexport interface DeleteIbGibResult extends FileResult { }\n\n// #endregion from common/types/legacy.ts\n\n/**\n * Special ibgib types, used for metadata within a space.\n *\n * Unsure where to place this in core-gib...\n *\n * ## notes\n *\n * * 10/2023\n *   * I'm changing this to also be unioned with 'string' because I am working\n *     on ibgib app and I need to consume the create special ibgib. so this\n *     should be extensible per use case in consuming apps.\n */\nexport type SpecialIbGibType =\n    \"tags\" | \"aliases\" | \"roots\" |\n    \"outerspaces\" | \"secrets\" |\n    \"encryptions\" | \"autosyncs\" | \"robbots\" | \"apps\" | \"history\" |\n    string;\n/**\n * Special ibgib types, used for metadata within a space.\n *\n * Unsure where to place this...\n *\n * @see {@link SPECIAL_IBGIB_TYPE_REGEXP}\n */\nexport const SpecialIbGibType = {\n    /** indexes all tag ibgibs within a space */\n    tags: \"tags\" as SpecialIbGibType,\n    /** indexes all aliases within a space */\n    aliases: \"aliases\" as SpecialIbGibType,\n    /** indexes all root ibgibs within a space */\n    roots: \"roots\" as SpecialIbGibType,\n    /** indexes all outerspace ibgibs, including sync spaces, within a space */\n    outerspaces: \"outerspaces\" as SpecialIbGibType,\n    /** indexes all secret ibgibs within a space */\n    secrets: \"secrets\" as SpecialIbGibType,\n    /** indexes all encryption setting ibgibs within a space */\n    encryptions: \"encryptions\" as SpecialIbGibType,\n    /** indexes all tjp addresses that automatically sync. */\n    autosyncs: \"autosyncs\" as SpecialIbGibType,\n    robbots: \"robbots\" as SpecialIbGibType,\n    apps: \"apps\" as SpecialIbGibType,\n    /** timelines history */\n    history: \"history\" as SpecialIbGibType,\n}\n\n/**\n * There has been a new ibGib that is the latest for a given tjp timeline.\n */\nexport interface IbGibTimelineUpdateInfo extends IbGib_V1 {\n    ib: 'IbGibTimelineUpdateInfo',\n    tjpAddr?: IbGibAddr;\n    latestAddr: IbGibAddr;\n    latestIbGib?: IbGib_V1<any>;\n}\n\n/**\n * Serializing helper type for compressing dependency graphs.\n */\nexport type SerializedUint8Array = {\n    _dataType: 'Uint8Array_Base64';\n    value: string;\n};\n", "/**\n * In a Robbot's rel8ns, this is the rel8n name that links to tags that the\n * Robbot uses for tagging its output.\n */\nexport const ROBBOT_TAG_TJP_ADDRS_REL8N_NAME = 'tagTjpAddrs';\n/**\n * A spaces ibGib uses this rel8n name for related sync spaces, used\n * in replicating ibgib spaces.\n */\nexport const ROBBOT_REL8N_NAME = 'robbot';\n/**\n * When a robbot witnesses an ibgib, it will \"remember\" the ibgib\n * by relating the target ibgib to itself via this rel8nName.\n */\nexport const DEFAULT_ROBBOT_TARGET_REL8N_NAME = 'x';\n\n/**\n * wah wah wah...\n */\nexport const IBGIB_ROBBOT_NAME_DEFAULT = 'i';\n\n/**\n * Icon for a single robbot\n */\nexport const DEFAULT_ROBBOT_ICON = 'body-outline';\n", "import { GIB } from '@ibgib/ts-gib/dist/V1/index.mjs';\n\n/**\n * Zero space is a default space that uses default values that should be\n * reproducible and not break or something...it's all in flux really.\n */\nexport const ZERO_SPACE_ID = 'zero';\n\n/**\n * was 000_default_space in MVP. need to add a conversion\n */\nexport const IBGIB_SPACE_NAME_DEFAULT = 'zerospace';\n// export const IBGIB_SPACE_NAME_DEFAULT = 'default_space';\n\n\n/**\n * For use with documentation and UX help.\n *\n * This is probably scoped to a particular schema...(e.g. v1)\n */\nexport const VALID_SPACE_NAME_EXAMPLES = [\n    'justLetters', 'valid_here', 'hyphens-allowed', '0CanStartOrEndWithNumbers9'\n];\n/**\n * For use with documentation and UX help.\n *\n * This is probably scoped to a particular schema...(e.g. v1)\n */\nexport const INVALID_SPACE_NAME_EXAMPLES = [\n    'IHaveASymbol!', 'invalid hereWithSpace', '-cantStartWithHyphen', '_OrUnderscore'\n];\n\n/**\n *\n */\nexport const PERSIST_OPTS_AND_RESULTS_IBGIBS_DEFAULT = false;\n\n/**\n * Yep, this one starts with default instead of ending with it.\n */\nexport const DEFAULT_LOCAL_SPACE_DESCRIPTION = `This is a local space. There are many like it, but this one is mine.`;\n\n/**\n * The main roots^gib ibgib uses this rel8n name to keep track of roots.\n */\nexport const SPACE_REL8N_NAME = 'space';\n\n/**\n * rel8n name in a space ibgib to the config ibgib(s?)\n */\nexport const SPACE_REL8N_NAME_CONFIG = `config`;\n/**\n * note that atow this is implied in the regexp not derivative\n * @see {@link SPACE_NAME_REGEXP}\n */\nexport const SPACE_NAME_MAX_LENGTH = 64;\n/**\n * alphanumerics start + end, middle can also contain hyphens atow.\n *\n * NOTE: this implies the value of {@link SPACE_NAME_MAX_LENGTH} but this is not\n * derived from the value. so if you change this, be sure to change/check that\n *\n * @see {@link SPACE_NAME_MAX_LENGTH}\n */\nexport const SPACE_NAME_REGEXP = /^[a-zA-Z][\\w\\-]{0,62}[a-zA-Z]$/;\n\n/**\n * A spaces ibGib uses this rel8n name for related sync spaces, used\n * in replicating ibgib spaces.\n */\nexport const SYNC_SPACE_REL8N_NAME = 'syncSpace';\n\n/**\n * ...?\n */\nexport const DEFAULT_SPACE_TEXT = 'space';\n/**\n * Default icon specifically for spaces.\n */\nexport const DEFAULT_SPACE_ICON = 'sparkles-outline';\n/**\n * Default description specifically for spaces.\n */\nexport const DEFAULT_SPACE_DESCRIPTION =\n    `This is a space ibgib, which is basically a special ibgib who has behavior\nto interface with data stores and/or other space(s) to provide concrete location\nfor ibgibs. All ibgibs can have relationships with other ibgibs, but this one\nspecifically either implies a physical interface to things like databases,\nfile systems, and similar; OR, when this space interfaces with other spaces, this\nis a logical organization of ibgib locations, like when configuring clusters or\nconsensus algorithms.`;\n/**\n * rel8n name used inside the root to those ibgib it contains.\n *\n * @example\n * ```json\n *  {\n *      ib: root,\n *      gib: ABC123,\n *      data: {...},\n *      rel8ns: {\n *          [rel8nName]: [\"a^1\", \"b^2\"]\n *      }\n *  }\n * ```\n */\nexport const DEFAULT_SPACE_REL8N_NAME = 'x';\n\n/**\n * Interval in ms between polling for updates (\"notifications\") between local\n * space (ibgibs service) and dynamo sync space(s), or for use within a single\n * space for checking its internal state.\n *\n * Of course, long polling is very hacky, but so is using DynamoDB in the cloud\n * for a sync space. Obviously need to progress to a more mature and robust sync\n * space/outer space architecture.\n */\nexport const DEFAULT_LOCAL_SPACE_POLLING_INTERVAL_MS = 30_000;\nexport const DEFAULT_LOCAL_SPACE_POLLING_DELAY_FIRST_RUN_MS = 10_000;\n\n/**\n * it's a space\n */\nexport const SPACE_ATOM = 'space';\n\n/**\n * {@link DEFAULT_LOCAL_SPACE_POLLING_INTERVAL_MS} but for outer spaces, so\n * longer interval atow.\n */\nexport const DEFAULT_OUTER_SPACE_POLLING_INTERVAL_MS = 20_000;\n/**\n * Amount of time to delay for FIRST poll execution.\n */\nexport const DEFAULT_OUTER_SPACE_POLLING_DELAY_FIRST_RUN_MS = 10_000;\n\n/**\n * When a status is first created, this is used to indicate that\n * the tjp has not been set.\n */\nexport const STATUS_UNDEFINED_TJP_GIB = GIB;\n/**\n * When a status is first created, this is used to indicate that\n * the txId has not been set.\n */\nexport const STATUS_UNDEFINED_TX_ID = '0';\n\nexport const SPACE_LOCK_IB_TERM = 'space_lock';\n/**\n * When attempting to acquire a lock ona  space, and it is already lock, it will\n * wait a random amount of ms before trying to lock again. This is the default\n * max amount of ms before reattempting.\n */\nexport const DEFAULT_MAX_DELAY_MS_RETRY_LOCK_ACQUIRE = 100;\n/**\n * Will retry this many times before giving up...\n */\nexport const DEFAULT_MAX_DELAY_RETRY_LOCK_ACQUIRE_ATTEMPTS = 100;\n/**\n * We don't want someone locking a space forever by accident.\n */\nexport const MAX_LOCK_SECONDS_VALID = 60 * 2; // two minutes\n/**\n * Default value for secondsValid when acquiring/releasing lock in/on LOCAL\n * space.\n */\nexport const DEFAULT_SECONDS_VALID_LOCAL = 30;\n/**\n * Default value for secondsValid when acquiring/releasing lock in/on\n * OUTER space, e.g. sync spaces like aws dynamo sync space.\n */\nexport const DEFAULT_SECONDS_VALID_OUTER = 30;\n\n/**\n * retry count when calling getDependencyGraph.\n *\n * ## driving use case\n *\n * dependency graph fails when concurrent merges made in sync space.\n * need to wait until previous graph merger happens then retry.\n */\nexport const DEFAULT_MAX_RETRIES_GET_DEPENDENCY_GRAPH_OUTERSPACE = 5;\n/**\n * when getting dependency graph, sometimes we have to wait to retry\n */\nexport const DEFAULT_MS_BETWEEN_RETRIES_GET_DEPENDENCY_GRAPH_OUTERSPACE = 5000;\n/**\n * retry count when calling getDependencyGraph.\n *\n * ## driving use case\n *\n * dependency graph fails when concurrent merges made in sync space.\n * need to wait until previous graph merger happens then retry.\n */\nexport const DEFAULT_MAX_RETRIES_GET_DEPENDENCY_GRAPH_LOCAL = 3;\n/**\n * when getting dependency graph, sometimes we have to wait to retry\n */\nexport const DEFAULT_MS_BETWEEN_RETRIES_GET_DEPENDENCY_GRAPH_LOCAL = 1000;\n\n/**\n * currently not used in ionic-gib.\n */\nexport const DEFAULT_TX_ID_LENGTH = 5;\n", "/**\n * The main roots^gib ibgib uses this rel8n name to keep track of roots.\n *\n * NOTE: This is different than the rel8nName that a root ibgib uses to link to its ibgibs!\n * {@link DEFAULT_ROOT_REL8N_NAME}\n */\nexport const ROOT_REL8N_NAME = 'root';\n\n/**\n * rel8n name used inside the root to those ibgib it contains. (root.rel8ns.x = [pic1^gib, comment2^gib, ...])\n *\n *\n * NOTE: This is different than the rel8nName 'root' that the roots^gib uses. (roots.rel8ns.root = [root1^gib, root2^gib, ...])\n * {@link ROOT_REL8N_NAME}\n *\n * @example\n * ```json\n *  {\n *      ib: root,\n *      gib: ABC123,\n *      data: {...},\n *      rel8ns: {\n *          [rel8nName]: [\"a^1\", \"b^2\"]\n *      }\n *  }\n * ```\n */\nexport const DEFAULT_ROOT_REL8N_NAME = 'x';\n\n/**\n *\n */\nexport const DEFAULT_ROOT_TEXT = 'root';\n/**\n * Default icon specifically for roots.\n */\nexport const DEFAULT_ROOT_ICON = 'analytics-outline';\n/**\n * Default description specifically for roots.\n */\nexport const DEFAULT_ROOT_DESCRIPTION = 'This is a root ibgib, which is basically like a root folder that is primarily responsible for \"containing\" other ibgibs.';\n", "// export const TAGS_IB = 'tags';\n// export const TAGS_IBGIB_ADDR = `${TAGS_IB}^${GIB}`;\n// export const TAGS_IBGIB_ADDR_KEY = `key ${TAGS_IBGIB_ADDR}`;\n\n/**\n * The main tags^gib ibgib uses this rel8n name to keep track of tags.\n */\nexport const TAG_REL8N_NAME = 'tag';\n\n/**\n * A tag ibGib uses this rel8n name for the ibgibs that it targets.\n */\nexport const TAG_TARGET_REL8N_NAME = 'target';\n\n\nexport const ILLEGAL_TAG_TEXT_CHARS = [\n    '^', '?', '/', '\\\\', `|`,\n];\n\nexport const ILLEGAL_TAG_DESC_CHARS = [\n    '^',\n];\n\n/**\n * Default icon when creating a tag.\n */\nexport const DEFAULT_TAG_ICON = 'pricetag-outline';\n/**\n * Default description when creating a tag.\n */\nexport const DEFAULT_TAG_DESCRIPTION = 'This is a tag used for organizing data.';\n\n// export const TAG_TEXT_REGEXP = /^\\w[\\w .\\-?!]{1,30}[\\w.?!]$/;\n// export const TAG_TEXT_REGEXP_DESCRIPTION = `tag text must start and end with an alphanumeric, and can contain a hyphen, question mark, dot or space.`;\n", "/**\n * @module\n *\n * not quite sure where these go.\n *\n * todo: check after the project is building where these other-constants fit.\n */\n\n/**\n * default id settings where...?\n */\nexport const DEFAULT_UUID = undefined;\n\nimport { ROBBOT_REL8N_NAME } from '../../witness/robbot/robbot-constants.mjs';\nimport { SYNC_SPACE_REL8N_NAME } from '../../witness/space/space-constants.mjs';\nimport { DEFAULT_ROOT_REL8N_NAME, ROOT_REL8N_NAME } from '../root/root-constants.mjs';\nimport { TAG_TARGET_REL8N_NAME, TAG_REL8N_NAME } from '../tag/tag-constants.mjs';\n\nexport const AUTOSYNC_ALWAYS_REL8N_NAME = 'always';\nexport const ARCHIVE_REL8N_NAME = 'archive';\nexport const TRASH_REL8N_NAME = 'trash';\n\n/**\n * These rel8n names are shown in a list view by default.\n *\n * This should perhaps go into a chat or common ux constants?\n */\nexport const DEFAULT_LIST_REL8N_NAMES: string[] = [\n    'pic', 'comment', 'link',\n    'result', 'import',\n    'tagged',\n    TAG_TARGET_REL8N_NAME,\n    TAG_REL8N_NAME,\n    ROOT_REL8N_NAME, // hack for now to get all to show\n    DEFAULT_ROOT_REL8N_NAME,\n    ROBBOT_REL8N_NAME,\n    SYNC_SPACE_REL8N_NAME,\n];\n\n/**\n *\n */\nexport const CURRENT_VERSION = '1';\n\n/**\n * List of common special chars for english.\n *\n * ## intent\n *\n * When sanitizing input.\n */\nexport const ALLISH_SPECIAL_CHARS = `\\`~!@#$%^&*()_\\\\-+=|\\\\\\\\\\\\]}[{\"':;?/>.<,`;\nexport const FILENAME_SPECIAL_CHARS = ` \\`~!@#$%&*()_\\\\-+=|\\\\]}[{\"';?>.<,`;\n\n/**\n * If this matches, then we will encode the data field in our storage (aws\n * anyway atow)\n */\nexport const IBGIB_DATA_REGEX_INDICATES_NEED_TO_ENCODE = /[^\\w\\s\\d`~!@#$%\\^&*()_\\\\\\-+=|\\]\\}\\[\\{\"':;?/>.<,]/;\n\n/**\n * hacky scroll to bottom after items load per platform\n */\nexport const DEFAULT_SCROLL_DELAY_MS_WEB_HACK = 5_000;\n/**\n * hacky scroll to bottom after items load per platform\n */\nexport const DEFAULT_SCROLL_DELAY_MS_ANDROID_HACK = 3_000;\n/**\n * hacky scroll to bottom after items load per platform\n */\nexport const DEFAULT_SCROLL_DELAY_MS_IOS_HACK = 2_000;\n\n/**\n * when you create a meta special ibgib, it must just be some alphanumerics.\n */\nexport const SPECIAL_IBGIB_TYPE_REGEXP = /^\\w{1,32}$/;\n\n/**\n * big weird decision in JS this one...\n */\nexport const INVALID_DATE_STRING = \"Invalid Date\";\n", "import { GIB } from \"@ibgib/ts-gib/dist/V1/constants.mjs\"\nimport { IbGib_V1 } from \"@ibgib/ts-gib/dist/V1/types.mjs\"\n\n/**\n * primitive ibgib for indicating a true value\n */\nexport const TRUE_GIB: IbGib_V1 = { ib: 'true', gib: GIB }\n/**\n * primitive ibgib for indicating a truthy value\n */\nexport const TRUTHY_GIB: IbGib_V1 = { ib: 'truthy', gib: GIB };\n/**\n * primitive ibgib for indicating a false value\n */\nexport const FALSE_GIB: IbGib_V1 = { ib: 'false', gib: GIB }\n/**\n * primitive ibgib for indicating a falsy value\n */\nexport const FALSY_GIB: IbGib_V1 = { ib: 'falsy', gib: GIB }\n\n/**\n * config entries in space rel8ns/data will start with this\n */\nexport const CONFIG_KEY_ATOM = 'config_key';\n", "import { Ib } from '@ibgib/ts-gib/dist/types.mjs';\n\nexport const DEFAULT_META_IB_STARTS: Ib[] = [\n    'tags', 'tag ', 'settings', 'setting ', 'witness space ',\n]\nexport const SPECIAL_URLS = [\n    'tags', 'home'\n];\n\n/**\n * When showing a menu item, this is the max length\n */\nexport const MENU_ITEM_IB_SUBSTRING_LENGTH = 20;\n\nexport const QUERY_PARAM_PAUSED = 'paused';\nexport const QUERY_PARAM_ROBBOT = 'robbot';\n\nexport const APP_NAME_REGEXP = /^[a-zA-Z0-9_\\-.]{1,32}$/;\nexport const APP_REL8N_NAME = 'app';\n", "import { GIB } from '@ibgib/ts-gib/dist/V1/index.mjs';\n\n/**\n * See {@link BootstrapIbGib}\n */\nexport const BOOTSTRAP_IBGIB_ADDR = `bootstrap^${GIB}`;\n/**\n * {@see BootstrapData}\n */\nexport const BOOTSTRAP_DATA_DEFAULT_SPACE_ID_KEY = `defaultSpaceId`;\n/**\n * Key for index tracking known spaceIds in a bootstrap ibgib.\n * {@see BootstrapData}\n */\nexport const BOOTSTRAP_DATA_KNOWN_SPACE_IDS_KEY = `spaceIds`;\n", "/**\n * There are multiple ways to incorporate the salt into the overall algorithm.\n * See the individual constant properties for details.\n *\n * {@link SaltStrategy} constant\n */\nexport type SaltStrategy =\n    'prependPerHash' | 'appendPerHash' |\n    'initialPrepend' | 'initialAppend';\n/**\n * enum-like constant for use in tandem with `SaltStrategy` type.\n *\n * See the individual constant properties for details.\n */\nexport const SaltStrategy = {\n    /**\n     * EACH time we hash anything in a round function or initial key-stretching,\n     * we will prepend the salt via string concatenation with the secret, if\n     * initial (salt + secret), else with the previous hash (salt + prev).\n     */\n    prependPerHash: 'prependPerHash' as SaltStrategy,\n    /**\n     * EACH time we hash anything in a round function or initial key-stretching,\n     * we will append the salt via string concatenation with the secret, if\n     * initial (secret + salt), else with the previous hash (prev + salt).\n     */\n    appendPerHash: 'appendPerHash' as SaltStrategy,\n    /**\n     * We will only prepend the salt to the secret (salt + secret) via string\n     * concatenation ONLY in the initial key-stretching recurions phase.\n     */\n    initialPrepend: 'initialPrepend' as SaltStrategy,\n    /**\n     * We will only append the salt to the secret (secret + salt) via string\n     * concatenation ONLY in the initial key-stretching recurions phase.\n     */\n    initialAppend: 'initialAppend' as SaltStrategy,\n} as const satisfies { [key: string]: SaltStrategy };\n/**\n * convenience constant array containing all of `Object.values(SaltStrategy)`\n */\nexport const SALT_STRATEGIES: SaltStrategy[] = Object.values(SaltStrategy);\n\n/**\n * Hash algorithm type.\n *\n * atow this is only SHA-256 and SHA-512 because both of these are relatively\n * strong and are supported in both node and browser environments. I have found\n * conflicting information on whether or not these are post-quantum secure.\n */\nexport type HashAlgorithm = 'SHA-256' | 'SHA-512';\n/**\n * enum-like constant for use in tandem with `HashAlgorithm` type.\n */\nexport const HashAlgorithm = {\n    'sha_256': 'SHA-256' as HashAlgorithm,\n    'sha_512': 'SHA-512' as HashAlgorithm,\n} satisfies { [key: string]: HashAlgorithm };\nexport const HASH_ALGORITHMS: HashAlgorithm[] = Object.values(HashAlgorithm);\n\nexport type AlphabetIndexingMode = 'indexOf' | 'lastIndexOf';\n/**\n * when iterating characters, this determines whether we are using `'indexOf'` or\n * `'lastIndexOf'` on the alphabet string.\n *\n * So if the JIT hex alphabet is abc123abc456 and our character is b:\n *\n * abc123abc456\n *  ^     ^\n *  1\n * * `'indexOf'` -> 1\n * * `'lastIndexOf'` -> 7\n *\n * with immediately expanding JIT alphabets, this shouldn't make much of a\n * difference.  But when mitigating brute force short-circuit attacks, where\n * the brute forcer only decrypts the first couple of characters of data, we\n * may combine `'lastIndexOf'` with a \"multipass\" expanding alphabet to\n * ensure that a larger portion of the plaintext (up to 100% of the\n * plaintext), is required to be processed before any short-circuiting\n * decryption can occur. @see {@link BlockModeOptions}\n *\n * To help understand this, here is an example. Say we use a multi-pass\n * alphabet that requires a minimum of 3 expansions. We encipher the first\n * character of plaintext we first convert that character to hex. Say this\n * hex is 'a'. Now we create our corresponding alphabet by recursively\n * rounding on the initial `prevHash` (after key stretching with\n * `initialRecursions` has occurred). Say one round produces a hash\n * '123a56ba90' for our one-time JIT alphabet. If this were an immediately\n * expanding JIT alphabet with no minimum expansions and the ciphertext is\n * already present, then additional rounds won't be needed for the attacker\n * - they already have the index and the alphabet that has the plaintext.\n *\n * With `lastIndexOf` + multipass blocks, then the attacker is forced to\n * calculate at least the entire section's hashing because the encrypted\n * index will most likely be at the end of the alphabet.\n *\n * abc123...[200ish hex character]...bac231\n *                                      ^\n * The first `indexOf('2')` would just be 4, and no other alphabet\n * extensions would be required (not a single one in the section).  Whereas\n * the `lastIndexOf('2')` would be a 200+ index. This would require multiple\n * hashes for every previous character in the section, and would thus harder\n * to short-circuit.\n *\n * @default `'indexOf'`\n */\nexport const AlphabetIndexingMode = {\n    indexOf: 'indexOf',\n    lastIndexOf: 'lastIndexOf',\n} satisfies { [key: string]: AlphabetIndexingMode };\nexport const ALPHABET_INDEXING_MODES: AlphabetIndexingMode[] = Object.values(AlphabetIndexingMode);\n\n/**\n * # tl;dr\n *\n * Block mode is stronger but slower relative to the stream mode.\n *\n * When block mode is enabled, we do multiple passes on sections of plaintext\n * when encrypting/decrypting.\n *\n * This is one way to help mitigate against short-circuit brute force\n * attacks.\n *\n * # how it works\n *\n * The block-mode algorithm works as follows:\n *\n * ## encrypting\n *\n * * plaintext characters - p0, p1, .., pi\n * * JIT alphabet hashes - [a0.0, a0.1, a0.2, .., a0.j], [a1.0, a1.1, a1.2, .., a1.j], .., [ai.0, ai.1, ai.2, .., ai.j]\n *   * i = plaintext index\n *   * j = alphabet expansion index\n * * passes - PASS1, PASS2, .., PASSn\n *\n * 1. First we iterate through the plaintext data in multipass blocks, the\n * size of which is parameterized by `maxBlockSize`. If this is larger\n * than data, then the entire plaintext will be used.\n *\n * 2. Then we create the initial alphabets for the entire section, determined by\n * our pass section size and the number of passes.\n *\n * 3. We then extend any individual alphabets that do not contain an instance of\n * the plaintext character yet. We are extending only those alphabets in need of\n * extending, as opposed to the previous step where we extended all alphabets in\n * the pass section.\n *\n * 4. We get the index of each plaintext character into its corresponding\n * alphabet and store each index in an array for the entire multipass block.\n * We then concat this new section with any previous sections encrypted,\n * building out our entire result `encryptedData` array section by section.\n *\n * 5. Lastly, we return the array as a string, joining each index with the\n * parameterized delimiter (comma by default).\n *\n * ## decrypting\n *\n * The decryption process is very similar.\n *\n * 1. First we iterate through the ciphertext data in multipass blocks, the\n * size of which must be the same as the encryption process (all parameters\n * should be the same encrypting and decrypting. these are automatically stored\n * in encryption output file).\n *\n * 2. Next we create our alphabets for the entire section. The first phase of\n * this is to build out the minimum sized alphabets per parameters\n * (`numOfPasses`).\n *\n * 3. Next we iterate through the encryped indexes for the section. While the\n * index is larger than the existing alphabet, the alphabet is JIT extended by\n * the hash round function. Once the alphabet is large enough (i.e. the\n * encrypted index can index into it), the the encrypted index is used in the\n * alphabet and the plaintext hex character is stored in a result array for the\n * section.\n *\n * 4. Once the entire section is decrypted to hex, the section's plaintext array\n * is added to the previously decrypted sections' plaintext results.\n *\n * 5. Once all sections are decrypted to hex, the plaintext array is converted to a\n * hex string and then decoded to the original plaintext.\n */\nexport interface BlockModeOptions {\n    /**\n     * Maximum number of **hex-encoded** plaintext characters per section when\n     * making multiple passes. Each pass extends the JIT alphabet for each\n     * character in that pass by the length of the hash digest being used (since\n     * the hashes are what the alphabets are made of).\n     *\n     * * If this is greater than the hex-encoded `dataToEncrypt` length, then\n     *   each pass section will be the length of data (it's goin to do the whole\n     *   plaintext in one section).\n     * * Barring internal JS voodoo, each pass should require additional memory\n     *   roughly linearly proportional to\n     *   * `dataToEncrypt`/`maxBlockSize` length (whichever is smaller)\n     *   * `numOfPasses` to make\n     *   * length of the hash used in creating the JIT alphabets (`hashAlgorithm`)\n     * * The larger `maxBlockSize` & `numOfPasses` is, the more a brute\n     *   force attack has to calculate - and the more memory it is going to take\n     *   - before determining if a secret guess is correct.\n     */\n    maxBlockSize: number;\n    /**\n     * @deprecated\n     *\n     * use {@link maxBlockSize}\n     */\n    maxPassSectionLength?: number;\n    /**\n     * Number of \"passes\" to make over the pass section. Each pass will extend\n     * the JIT alphabet for each character in the pass section by the length of\n     * the hash digest string used in `hashAlgorithm`.\n     *\n     * This should be especially effective in mitigating against brute force\n     * cracking when used in tandem with an `indexingMode` of `lastIndexOf`.\n     * This is because at least `(numOfPasses - 1) * maxBlockSize`\n     * number of hash rounds must be calculated before the very first plaintext\n     * character can be deciphered. This is even more expensive if\n     * `recursionsPerHash` is larger.\n     */\n    numOfPasses: number;\n}\n\n/**\n * Shared interface among both args and results.\n *\n * ## notes\n *\n * Silly name... naming things hrmm.\n */\ninterface BaseBase {\n    /**\n     * how to index into the jit alphabet\n     *\n     * @see {@link AlphabetIndexingMode}\n     */\n    indexingMode?: AlphabetIndexingMode;\n    /**\n     * Settings to use if we want to use multiple passes when\n     * encrypting/decrypting.\n     *\n     * This is one way to help mitigate against short-circuit brute force\n     * attacks.\n     *\n     * @see {@link BlockModeOptions}\n     */\n    blockMode?: BlockModeOptions;\n    /**\n     * @deprecated\n     *\n     * Use `blockMode` instead.\n     */\n    multipass?: BlockModeOptions;\n    /**\n     * The hash algorithm to use.\n     *\n     * ATOW, this is either 'SHA-256' or 'SHA-512'.\n     *\n     * @see {@link HashAlgorithm} for current values.\n     */\n    hashAlgorithm?: HashAlgorithm;\n    /**\n     * The amount of recursions from the secret + salt to start actual\n     * encryption mapping.\n     *\n     * The bigger this is, the more time it takes to try guesses for an\n     * attacker, depending on how expensive the hash function is. But also the\n     * more time it would take on the legitimate user's password attempt.\n     */\n    initialRecursions: number;\n    /**\n     * The number of recursive hashes we perform for each round function of\n     * hashing (except the initial recursions, see `initialRecursions` param).\n     *\n     * This includes both when we hash each hex character of our hex-encoded\n     * data, as well as each time we JIT extend the alphabet when the plaintext\n     * hex character isn't found in the current JIT hash alphabet.\n     *\n     * So, if the initial hash alphabet is all a's (e.g. \"aaa...a\", a very\n     * contrived hash!), but our hex data is a b, then we will hash the all-a\n     * hash {recursionsPerHash} times to expand the alphabet.\n     *\n     * @example\n     * So if we have a data character of 'b', and its immediate hash alphabet is\n     * all a's, and we recurse 3 times per hash (ignoring salts for this\n     * example), here is some simplified pseudo code to give the gist:\n     *\n     * ```javascript\n     * dataCharToMap = 'b';\n     * alphabet = hash(prevHash) // say it gives us 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';\n     * needExpandAlphabet = alphabet.includes(dataCharToMap) // false in this case\n     * if (needExpandAlphabet) {\n     *     hashToAdd = alphabet;\n     *     for (i = 0; i < recursionsPerHash; i++) { hashToAdd = hash(hashToAdd); }\n     *     alphabet = alphabet + hashToAdd; // say it's now 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab';\n     * }\n     * index = alphabet.indexOf(dataCharToMap); // 63\n     * ```\n     *\n     * In actuality, the code will include salt and saltStrategy, and track how\n     * many times the alphabet expands to get the correct index.\n     *\n     * Note that this does not add on each and every recursive hash produced. It\n     * only adds on the last hash after recursionsPerHash number of hashes (i.e.\n     * the alphabet is JIT extended the length of a single hash digest - the\n     * last one).\n     */\n    recursionsPerHash?: number;\n    /**\n     * text to prepend/append to hashes for increased security.\n     *\n     * {@link SaltStrategy}\n     */\n    salt: string;\n\n    /**\n     * {@link SaltStrategy}\n     */\n    saltStrategy?: SaltStrategy;\n    /**\n     * Encrypted data is just an array of numbers (positive integers).\n     * This array is converted to a string by joining with a delimiter.\n     * This is that delimiter.\n     *\n     * @default DEFAULT_ENCRYPTED_DATA_DELIMITER in constants.ts\n     */\n    encryptedDataDelimiter?: string;\n}\n\n/**\n * Args-specific info, in contrast to result-specific info\n *\n * @see {@link BaseResult}\n */\nexport interface BaseArgs extends BaseBase {\n    secret: string;\n}\n\n/**\n * Info passed to the `encrypt` function.\n */\nexport interface EncryptArgs extends BaseArgs {\n    /**\n     * Plaintext data string\n     */\n    dataToEncrypt: string;\n    /**\n     * If true, will decrypt back and confirm that the decryption was\n     * successfully performed and the original plaintext is recoverable via the\n     * decryption process.\n     *\n     * Takes more time & resources.\n     */\n    confirm?: boolean;\n}\n\n/**\n * Info passed to the `decrypt` function.\n */\nexport interface DecryptArgs extends BaseArgs {\n    /**\n     * String of delimited encrypted indexes.\n     */\n    encryptedData: string;\n}\n\n/**\n * Result-specific info, in contrast to args-specific info\n *\n * @see {@link BaseArgs}\n */\ninterface BaseResult extends BaseBase {\n    /**\n     * If truthy, there were big problems...\n     */\n    errors?: string[];\n    /**\n     * If truthy, there were issues...\n     */\n    warnings?: string[];\n}\n\n/**\n * Result info from `encrypt` function.\n */\nexport interface EncryptResult extends BaseResult {\n    /**\n      String of delimited encrypted indexes.\n     */\n    encryptedData?: string;\n}\n\n/**\n * Result info from `decrypt` function.\n */\nexport interface DecryptResult extends BaseResult {\n    decryptedData?: string;\n}\n", "/**\n * @module helper utility functions specific to encrypt-gib\n *\n * THANK YOU Stack Overflow, Simon Buchan, and others at https://stackoverflow.com/questions/21647928/javascript-unicode-string-to-hex\n */\n\nimport { extractErrorMsg } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\n\n\n/**\n * Convert some string to a string with only hex characters.\n *\n * Should (hopefully!) be reversible.\n *\n * @param s string to convert to hex string\n * @returns string that only contains hexidecimal characters (0-9, a-f)\n */\nexport function encodeStringToHexString(s: string): Promise<string> {\n    const lc = `[${encodeStringToHexString.name}]`;\n    return new Promise((resolve, reject) => {\n        try {\n            let bytes = stringToUTF8Bytes(s);\n            let hexString = bytesToHexString(bytes);\n            resolve(hexString);\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            reject(error);\n        }\n    });\n}\n\nfunction stringToUTF8Bytes(s: string): Uint8Array {\n    const lc = `[${stringToUTF8Bytes.name}]`;\n    try {\n        return new TextEncoder().encode(s);\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    }\n}\n\nfunction bytesToHexString(bytes: Uint8Array): string {\n    const lc = `[${bytesToHexString.name}]`;\n    try {\n        return Array.from(\n            bytes,\n            byte => byte.toString(16).padStart(2, '0')\n        ).join(\"\");\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    }\n}\n\n/**\n * Decodes the hex-encoded string back to the original text.\n *\n * @param hexString Encoded x of some some data string\n * @returns Decoded (original hopefully!) text\n */\nexport function decodeHexStringToString(hexString: string): Promise<string> {\n    const lc = `[${decodeHexStringToString.name}]`;\n    return new Promise((resolve, reject) => {\n        try {\n            // console.log(`${lc} hexString (len: ${hexString.length}): ${hexString}`);\n            const bytes = hexStringToBytes(hexString);\n            const s = utf8BytesToString(bytes);\n            resolve(s);\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            reject(error);\n        }\n    });\n}\n\n/**\n * Converts hex to bytes.\n *\n * Ty also https://stackoverflow.com/questions/14603205/how-to-convert-hex-string-into-a-bytes-array-and-a-bytes-array-in-the-hex-strin\n *\n * @param hexString string that (obviously) should be hex to convert to bytes\n */\nfunction hexStringToBytes(hexString: string): Uint8Array {\n    const lc = `[${hexStringToBytes.name}]`;\n    try {\n        // console.log(`${lc} hexString (len: ${hexString.length}): ${hexString}`);\n        if (hexString.length % 2 !== 0) { throw new Error(`invalid hex string. length %2 !== 0`); }\n        const numBytes = hexString.length / 2;\n        const bytes = new Uint8Array(numBytes);\n        for (let i = 0; i < numBytes; i++) {\n            bytes[i] = parseInt(hexString.substr(i * 2, 2), 16);\n        }\n        return bytes;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    }\n}\nfunction utf8BytesToString(bytes: Uint8Array): string {\n    const lc = `[${utf8BytesToString.name}]`;\n    try {\n        return new TextDecoder().decode(bytes);\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    }\n}\n", "import { AlphabetIndexingMode, HashAlgorithm, SaltStrategy } from \"./index.mjs\";\n\nexport const ENCRYPT_LOG_A_LOT = false;\n\nexport var DEFAULT_SALT_STRATEGY: SaltStrategy = SaltStrategy.appendPerHash;\n// export var DEFAULT_HASH_ALGORITHM: HashAlgorithm = 'SHA-256';\nexport var DEFAULT_HASH_ALGORITHM: HashAlgorithm = 'SHA-512';\nexport var DEFAULT_GETUUID_SEEDSIZE: number = 1024;\nexport var DEFAULT_INITIAL_RECURSIONS: number = 20000;\nexport var DEFAULT_RECURSIONS_PER_HASH: number = 1;\n/**\n * This must be indexOf for backwards compatibility.\n */\nexport var DEFAULT_ALPHABET_INDEXING_MODE_LEGACY: AlphabetIndexingMode = 'indexOf';\n/**\n * In multipass, which is being developed to help mitigate against short-circuit\n * brute force attacks, I believe it's safer to use `lastIndexOf` in order to\n * leverage the alphabet extensions in other options. This may turn out to be\n * unnecessary.\n */\nexport var DEFAULT_ALPHABET_INDEXING_MODE_BLOCKMODE: AlphabetIndexingMode = 'lastIndexOf';\n/**\n * Default value for the maximum size of a block, when using block mode (if the\n * total plaintext data is smaller than this, then the effective block size is\n * that data's length).\n *\n * This is essentially how many groups of hex-encoded plaintext characters are\n * we going to iterate on at one time with multiple passes. So if you have a\n * block size of 1000, then the block mode encryption will have to keep in\n * memory (or store/retrieve dynamically if an attacker rewrites this library's\n * internals) at least 1000 hashes for the entire block before being able to\n * compute the second pass's hash of the first character. So for 2 passes and a\n * hashLength (digestLength) of 64 bytes, this would be roughly 1000 *\n * hashLength bytes * (numOfPasses - 1)~~> 64 kB of memory. (though really I\n * think this is 128 kB because current implementation just treats the digest as\n * a string)\n *\n * Used in block mode.\n */\nexport var DEFAULT_MAX_BLOCK_SIZE: number = 5_000_000;\n/**\n * Default value for the number of passes when using block mode.\n *\n * Used in block mode\n */\nexport var DEFAULT_NUM_OF_PASSES: number = 4;\n\nexport var DEFAULT_ENCRYPTED_DATA_DELIMITER: string = ',';\n", "import { extractErrorMsg, hash as hashFn } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';\n\nimport { HashAlgorithm, SaltStrategy } from \"../types.mjs\";\n\n/**\n * Builds the string that we will hash to get the next hash alphabet.\n *\n * @example\n * if we're prepending every hash, and this is the initial hash,\n * then we'll return `salt + secret`.\n *\n * @returns the string we're going to hash to get the next alphabet\n */\nexport function getPreHash({\n    secret,\n    prevHash,\n    salt,\n    saltStrategy,\n}: {\n    secret?: string,\n    prevHash?: string,\n    salt: string,\n    saltStrategy: SaltStrategy,\n}): string {\n    if (!(prevHash || secret)) { throw new Error(`Either secret or prevHash is required, but both are falsy (E: bee2849729ff410081d963777dcedb49))`); }\n    // either prevHash or secret is guaranteed for all the following cases\n    switch (saltStrategy) {\n        case SaltStrategy.prependPerHash:\n            return salt + (prevHash || secret)\n        case SaltStrategy.appendPerHash:\n            return (prevHash || secret) + salt;\n        case SaltStrategy.initialPrepend:\n            return prevHash ? prevHash : salt + secret;\n        case SaltStrategy.initialAppend:\n            return prevHash ? prevHash : secret + salt;\n        default:\n            throw new Error(`Unknown saltStrategy: ${saltStrategy} (E: 235136af1a6c40eb9c17b2ca41c08a01)`);\n    }\n}\n\nexport async function execRound_getNextHash({\n    secret,\n    prevHash,\n    count,\n    salt,\n    saltStrategy,\n    hashAlgorithm,\n}: {\n    secret?: string,\n    prevHash?: string,\n    count: number,\n    salt: string,\n    saltStrategy: SaltStrategy,\n    hashAlgorithm: HashAlgorithm,\n}): Promise<string> {\n    const lc = `[${execRound_getNextHash.name}]`;\n    try {\n        let hash = prevHash || undefined;\n        for (let i = 0; i < count; i++) {\n            const preHash = getPreHash({ secret, prevHash: hash, salt, saltStrategy });\n            hash = await hashFn({ s: preHash, algorithm: hashAlgorithm });\n        }\n        if (!hash) { throw new Error(`hash was not created (E: 09dfdfd644734727a34a1bc0bd8e93b9)`); }\n        return hash;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    }\n}\n\n/**\n * Creates the first \"alphabet\" that we will index into.\n *\n * We have this separate, because the initialRecursions help us\n * chug on the secret.\n *\n * If the data's hex character is not in this alphabet, it will\n * be expanded just as any\n */\nexport async function doInitialRecursions_keystretch({\n    secret,\n    initialRecursions,\n    salt,\n    saltStrategy,\n    hashAlgorithm,\n}: {\n    secret: string,\n    initialRecursions: number,\n    salt: string,\n    saltStrategy: SaltStrategy,\n    hashAlgorithm: HashAlgorithm,\n}): Promise<string> {\n    const lc = `[${doInitialRecursions_keystretch.name}]`;\n    try {\n        const hash = await execRound_getNextHash({\n            secret,\n            count: initialRecursions,\n            salt, saltStrategy, hashAlgorithm,\n        })\n        return hash;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    }\n}\n", "import { extractErrorMsg } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';\n\nimport { doInitialRecursions_keystretch, execRound_getNextHash, } from \"../common/encrypt-decrypt-common.mjs\";\nimport { AlphabetIndexingMode, HashAlgorithm, SaltStrategy } from \"../types.mjs\";\n\n/**\n * Does the actual encryption from hexEncodedData with the given params.\n *\n * @returns encryptedData\n */\nexport async function encryptFromHex_stream({\n    hexEncodedData,\n    initialRecursions,\n    recursionsPerHash,\n    salt,\n    saltStrategy,\n    secret,\n    hashAlgorithm,\n    encryptedDataDelimiter,\n    indexingMode,\n}: {\n    hexEncodedData: string,\n    initialRecursions: number,\n    recursionsPerHash: number,\n    salt: string,\n    saltStrategy: SaltStrategy,\n    secret: string,\n    hashAlgorithm: HashAlgorithm,\n    encryptedDataDelimiter: string,\n    indexingMode: AlphabetIndexingMode,\n}): Promise<string> {\n    const lc = `[${encryptFromHex_stream.name}]`;\n\n    try {\n        // set up \"prevHash\" as a starting point, similar to key-stretching\n        let prevHash = await doInitialRecursions_keystretch({\n            secret,\n            initialRecursions,\n            salt,\n            saltStrategy: saltStrategy!,\n            hashAlgorithm: hashAlgorithm!,\n        });\n        // console.log(`${lc} first prevHash: ${prevHash}`);\n\n        const getIndex: (alphabet: string, hexChar: string) => number =\n            indexingMode === 'indexOf' ?\n                (alphabet: string, hexChar: string) => { return alphabet.indexOf(hexChar) } :\n                (alphabet: string, hexChar: string) => { return alphabet.lastIndexOf(hexChar) };\n        // console.log(`${lc} using getIndex (indexingMode: ${indexingMode})`);\n\n        // we have our prevHash starting point, so now we can iterate through the data\n        let encryptedDataIndexes: number[] = [];\n        for (let i = 0; i < hexEncodedData.length; i++) {\n            // this is the character of data that we want to map to an index into the generated alphabet\n            const hexCharFromData: string = hexEncodedData[i];\n            let alphabet: string = \"\";\n            let hash: string;\n            while (!alphabet.includes(hexCharFromData)) {\n                // if (alphabet.length > 64) {\n                //     console.log(`alphabet is extending past 64... alphabet.length: ${alphabet.length}`);\n                // }\n                // console.log(`${lc} doing iteration...`);\n                hash = await execRound_getNextHash({\n                    count: recursionsPerHash,\n                    prevHash, salt, saltStrategy, hashAlgorithm\n                });\n                alphabet += hash!;\n                prevHash = hash;\n                // console.log(`${lc} alphabet: ${alphabet}`); // debug\n            }\n\n            // we now have the alphabet, so find the index of hex character\n            // const charIndex = alphabet.indexOf(hexCharFromData);\n            const charIndex = getIndex(alphabet, hexCharFromData);\n            // console.log(`${lc} charIndex: ${charIndex}`);\n            encryptedDataIndexes.push(charIndex);\n        }\n\n        const encryptedData = encryptedDataIndexes.join(encryptedDataDelimiter);\n        return encryptedData;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    }\n}\n", "import { extractErrorMsg } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';\n\nimport { doInitialRecursions_keystretch, execRound_getNextHash, getPreHash } from \"../common/encrypt-decrypt-common.mjs\";\nimport { HashAlgorithm, SaltStrategy } from \"../types.mjs\";\n\n/**\n * Takes a given encryptedData, in the form of a delimited string\n * of indexes, and decrypts it back into encoded hex (not the original\n * unencrypted data!).\n *\n * it does this by iterating\n *\n * @returns unencrypted, but still encoded, hex string of the original unencrypted data\n */\nexport async function decryptToHex_stream({\n    encryptedData,\n    initialRecursions,\n    recursionsPerHash,\n    salt,\n    saltStrategy,\n    secret,\n    hashAlgorithm,\n    encryptedDataDelimiter,\n}: {\n    encryptedData: string,\n    initialRecursions: number,\n    recursionsPerHash: number,\n    salt: string,\n    saltStrategy: SaltStrategy,\n    secret: string,\n    hashAlgorithm: HashAlgorithm,\n    encryptedDataDelimiter: string,\n}): Promise<string> {\n    const lc = `[${decryptToHex_stream.name}]`;\n\n    try {\n        // set up \"prevHash\" as a starting point, similar to key-stretching\n        let prevHash = await doInitialRecursions_keystretch({\n            secret,\n            initialRecursions,\n            salt,\n            saltStrategy: saltStrategy!,\n            hashAlgorithm: hashAlgorithm!,\n        });\n        // console.log(`${lc} first prevHash: ${prevHash}`);\n\n        // we have our prevHash starting point, so now we can iterate through the data\n        // console.log(`${lc} encryptedDataDelimiter: ${encryptedDataDelimiter}`);\n        let encryptedDataIndexes: number[] =\n            encryptedData.split(encryptedDataDelimiter).map((nString: string) => parseInt(nString));\n        // console.log(`${lc} encryptedDataIndexes: ${encryptedDataIndexes.toString()}`);\n        let decryptedDataArray: string[] = [];\n        for (let i = 0; i < encryptedDataIndexes.length; i++) {\n            // this is the index of the character of data that we want to get\n            // out of the alphabet map but to generate the alphabet, we may need\n            // to do multiple hash iterations, depending on how big the index\n            // is. So if we don't hit a '7' until the third hash, then we need\n            // to keep building out the alphabet until that third hash.\n\n            // HACK: I'm going to do this with a while loop instead of a for\n            // because I want to get it working first.\n\n            let charIndex = encryptedDataIndexes[i];\n            // console.log(`${lc} charIndex: ${charIndex}`);\n            let alphabet: string = \"\";\n            let hash: string;\n            while (charIndex >= alphabet.length) {\n                // console.log(`${lc} doing iteration...`);\n                hash = await execRound_getNextHash({\n                    count: recursionsPerHash,\n                    prevHash, salt, saltStrategy, hashAlgorithm\n                });\n                alphabet += hash;\n                prevHash = hash;\n                // console.log(`${lc} alphabet: ${alphabet}`); // debug\n            }\n\n            // we now have the alphabet, so index into it to get the decrypted hex char\n            let hexChar: string = alphabet[charIndex];\n            decryptedDataArray.push(hexChar);\n        }\n\n        // console.log(`${lc} decryptedDataArray: ${decryptedDataArray.toString()}`);\n        // reconstitute the decryptedHex\n        const decryptedHex: string = decryptedDataArray.join('');\n        // console.log(`${lc} decryptedHex: ${decryptedHex.toString()}`);\n        return decryptedHex;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    }\n}\n", "import { getUUID } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';\n\nimport * as c from '../constants.mjs';\nimport { decodeHexStringToString } from '../helper.mjs';\nimport { DecryptArgs, DecryptResult, HashAlgorithm, SALT_STRATEGIES } from \"../types.mjs\";\nimport { decryptToHex_stream } from './decrypt-to-hex-stream-mode.mjs';\n\n/**\n * Does the actual decryption work using the original stream code.\n *\n * I'm trying to change this as little as possible for reference and sanity\n * checks.\n *\n * {@link decrypt}\n * {@link DecryptArgs}\n * {@link DecryptResult}\n *\n * @returns a `DecryptResult` info object\n */\nexport async function decryptImpl_stream({\n    encryptedData,\n    initialRecursions,\n    recursionsPerHash,\n    salt,\n    saltStrategy,\n    secret,\n    hashAlgorithm,\n    encryptedDataDelimiter,\n}: DecryptArgs): Promise<DecryptResult> {\n    const lc = `[${decryptImpl_stream.name}]`;\n    // console.log(`${lc} encryptedDataDelimiter: ${encryptedDataDelimiter}`);\n\n    const errors: string[] = [];\n    const warnings: string[] = [];\n\n    // #region set args defaults\n\n    initialRecursions = initialRecursions || c.DEFAULT_INITIAL_RECURSIONS;\n    recursionsPerHash = recursionsPerHash || c.DEFAULT_RECURSIONS_PER_HASH;\n    saltStrategy = saltStrategy || c.DEFAULT_SALT_STRATEGY;\n    hashAlgorithm = hashAlgorithm || c.DEFAULT_HASH_ALGORITHM;\n    salt = salt || await getUUID(c.DEFAULT_GETUUID_SEEDSIZE);\n    encryptedDataDelimiter = encryptedDataDelimiter || c.DEFAULT_ENCRYPTED_DATA_DELIMITER;\n\n    // #endregion\n\n    // #region args validation\n\n    const lcv = `[validation]`;\n\n    if (!initialRecursions || initialRecursions < 1) { const e = `${lcv} initialRecursions required, and greater than 0`; console.error(e); errors.push(e); }\n    if (!recursionsPerHash || recursionsPerHash < 1) { const e = `${lcv} recursionsPerHash required, and greater than 0`; console.error(e); errors.push(e); }\n    if (!encryptedData) { const e = `${lcv} encryptedData required`; console.error(e); errors.push(e); }\n    if (!salt) { const e = `${lcv} salt required`; console.error(e); errors.push(e); }\n    if (!saltStrategy) { const e = `${lcv} saltStrategy required`; console.error(e); errors.push(e); }\n    if (!secret) { const e = `${lcv} secret required`; console.error(e); errors.push(e); }\n    if (!encryptedDataDelimiter) { const e = `${lcv} encryptedDataDelimiter required`; console.error(e); errors.push(e); }\n\n    // if (hashAlgorithm !== 'SHA-256') { const e = `${lcv} only SHA-256 implemented`; console.error(e); errors.push(e); }\n    if (!Object.values(HashAlgorithm).includes(hashAlgorithm)) {\n        const e = `${lcv} only ${Object.values(HashAlgorithm)} hash algorithms implemented`; console.error(e); errors.push(e);\n    }\n\n    if (saltStrategy && !SALT_STRATEGIES.includes(saltStrategy!)) {\n        const e = `${lcv} unknown saltStrategy: ${saltStrategy}`; console.error(e); errors.push(e);\n    }\n\n    if (errors.length > 0) {\n        return {\n            errors,\n            initialRecursions,\n            recursionsPerHash,\n            salt,\n            saltStrategy,\n            hashAlgorithm,\n            encryptedDataDelimiter,\n        }\n    }\n\n    // #endregion\n\n    // decrypt from indices into hex\n    // console.log(`${lc} encryptedData: ${encryptedData}`);\n    let hexEncodedData: string = await decryptToHex_stream({\n        encryptedData,\n        initialRecursions,\n        recursionsPerHash,\n        salt,\n        saltStrategy,\n        secret,\n        hashAlgorithm,\n        encryptedDataDelimiter,\n    });\n\n    // console.log(`${lc} hexEncodedData: ${hexEncodedData}`);\n    // decode hex back into original data\n    const decryptedData: string = await decodeHexStringToString(hexEncodedData);\n\n    return {\n        decryptedData,\n        initialRecursions,\n        recursionsPerHash,\n        salt,\n        saltStrategy,\n        hashAlgorithm,\n        encryptedDataDelimiter,\n        warnings: warnings.length > 0 ? warnings : undefined,\n    };\n}\n", "import { getUUID } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';\n\nimport * as c from '../constants.mjs';\nimport { decodeHexStringToString, encodeStringToHexString } from '../helper.mjs';\nimport { ALPHABET_INDEXING_MODES, EncryptArgs, EncryptResult, HashAlgorithm, SALT_STRATEGIES } from \"../types.mjs\";\nimport { encryptFromHex_stream } from './encrypt-from-hex-stream-mode.mjs';\nimport { decryptImpl_stream } from './decrypt-stream-mode.mjs';\n\n/**\n * Does the actual encryption work using the original \"stream\" streaming\n * encryption.\n *\n * {@link encrypt}\n * {@link EncryptArgs}\n * {@link EncryptResult}\n *\n * @returns a `EncryptResult` info object\n */\nexport async function encryptImpl_stream({\n    dataToEncrypt,\n    initialRecursions,\n    recursionsPerHash,\n    salt,\n    saltStrategy,\n    secret,\n    hashAlgorithm,\n    encryptedDataDelimiter,\n    confirm,\n    indexingMode,\n}: EncryptArgs): Promise<EncryptResult> {\n    const lc = `[${encryptImpl_stream.name}]`;\n\n    const errors: string[] = [];\n    let warnings: string[] = [];\n\n    // #region set args defaults\n\n    if (!initialRecursions) {\n        console.warn(`${lc} initial recursions required. defaulting to ${c.DEFAULT_INITIAL_RECURSIONS}`);\n        initialRecursions = c.DEFAULT_INITIAL_RECURSIONS;\n    }\n    recursionsPerHash = recursionsPerHash || c.DEFAULT_RECURSIONS_PER_HASH;\n    saltStrategy = saltStrategy || c.DEFAULT_SALT_STRATEGY;\n    hashAlgorithm = hashAlgorithm || c.DEFAULT_HASH_ALGORITHM;\n    salt = salt || await getUUID(c.DEFAULT_GETUUID_SEEDSIZE);\n    encryptedDataDelimiter = encryptedDataDelimiter || c.DEFAULT_ENCRYPTED_DATA_DELIMITER;\n    indexingMode = indexingMode || c.DEFAULT_ALPHABET_INDEXING_MODE_LEGACY;\n\n    // #endregion\n\n    // #region args validation\n\n    const lcv = `[validation]`;\n\n    if (!initialRecursions || initialRecursions < 1) { const e = `${lcv} initialRecursions required, and greater than 0`; console.error(e); errors.push(e); }\n    if (!recursionsPerHash || recursionsPerHash < 1) { const e = `${lcv} recursionsPerHash required, and greater than 0`; console.error(e); errors.push(e); }\n    if (!dataToEncrypt) { const e = `${lcv} dataToEncrypt required`; console.error(e); errors.push(e); }\n    if (!salt) { const e = `${lcv} salt required`; console.error(e); errors.push(e); }\n    if (!saltStrategy) { const e = `${lcv} saltStrategy required`; console.error(e); errors.push(e); }\n    if (!secret) { const e = `${lcv} secret required`; console.error(e); errors.push(e); }\n    if (!encryptedDataDelimiter) { const e = `${lcv} encryptedDataDelimiter required`; console.error(e); errors.push(e); }\n    if (!ALPHABET_INDEXING_MODES.includes(indexingMode)) { const e = `${lcv} invalid indexingMode (${indexingMode}). Must be one of ${ALPHABET_INDEXING_MODES} (E: 5955c46755434982982823c97adcf076)`; console.error(e); errors.push(e); }\n\n\n    // if (hashAlgorithm !== 'SHA-256') { const e = `${lcv} only SHA-256 implemented`; console.error(e); errors.push(e); }\n    if (!Object.values(HashAlgorithm).includes(hashAlgorithm)) {\n        const e = `${lcv} only ${Object.values(HashAlgorithm)} hash algorithms implemented`; console.error(e); errors.push(e);\n    }\n\n    if (saltStrategy && !SALT_STRATEGIES.includes(saltStrategy!)) {\n        const e = `${lcv} unknown saltStrategy: ${saltStrategy}`; console.error(e); errors.push(e);\n    }\n\n    if (errors.length > 0) {\n        return {\n            errors,\n            initialRecursions,\n            recursionsPerHash,\n            salt,\n            saltStrategy,\n            hashAlgorithm,\n            encryptedDataDelimiter,\n        }\n    }\n\n    // #endregion\n\n    // #region encode data to just hex (i.e. only have 0-9, a-f)\n\n    // console.log(`${lc} hex encoding dataToEncrypt: ${dataToEncrypt}`);\n    const hexEncodedData: string = await encodeStringToHexString(dataToEncrypt);\n    if (confirm) {\n        // confirm data can be converted back into the original data\n        // console.log(`${lc} hex decoding back to check with dataToEncrypt: ${hexEncodedData}`);\n        const confirmDecodedData = await decodeHexStringToString(hexEncodedData);\n        // console.log(`${lc} checkDecodedData: ${confirmDecodedData}`);\n        if (confirmDecodedData !== dataToEncrypt) {\n            throw new Error(`decoding encoded hex failed for this data: The encoded hex did not reverse to the original data.`);\n        }\n    }\n\n    // #endregion\n\n    // #region encrypt hex\n\n    // comma-delimited indexes string\n    let encryptedData: string = await encryptFromHex_stream({\n        hexEncodedData,\n        initialRecursions,\n        recursionsPerHash,\n        salt,\n        saltStrategy,\n        secret,\n        hashAlgorithm,\n        encryptedDataDelimiter,\n        indexingMode: 'indexOf',\n    });\n\n    if (confirm) {\n        const resDecrypt = await decryptImpl_stream({\n            encryptedData,\n            initialRecursions,\n            recursionsPerHash,\n            salt,\n            saltStrategy,\n            secret,\n            hashAlgorithm,\n            encryptedDataDelimiter,\n        });\n        if ((resDecrypt.errors || []).length > 0) {\n            return {\n                errors: [`Confirm check found that decrypt had errors.`, ...resDecrypt.errors!],\n                initialRecursions,\n                recursionsPerHash,\n                salt,\n                saltStrategy,\n                hashAlgorithm,\n                encryptedDataDelimiter,\n            };\n        } else if (!resDecrypt.decryptedData) {\n            throw new Error(`Confirm check call to decrypt produced falsy decryptedData`);\n        } else if (resDecrypt.decryptedData !== dataToEncrypt) {\n            // DO NOT LEAVE THIS IN PROD!!!\n            // console.log(`resDecrypt.decryptedData: ${resDecrypt.decryptedData}`); // DO NOT LEAVE THIS IN PROD!!!\n            // console.log(`dataToEncrypt: ${dataToEncrypt}`); // DO NOT LEAVE THIS IN PROD!!!\n            // DO NOT LEAVE THIS IN PROD!!!\n            throw new Error(`The ENCRYPTED data did not decrypt back to the original data.`);\n        } else {\n            // console.log(`${lc} decrypt confirmed.`);\n        }\n        if ((resDecrypt.warnings || []).length > 0) {\n            warnings = warnings.concat([`Confirm check call to decrypt had warnings.`, ...resDecrypt.warnings!])\n        }\n    }\n\n    // #endregion\n\n    return {\n        encryptedData,\n        initialRecursions,\n        recursionsPerHash,\n        salt,\n        saltStrategy,\n        hashAlgorithm,\n        encryptedDataDelimiter,\n        warnings: warnings.length > 0 ? warnings : undefined,\n    };\n}\n", "import { extractErrorMsg } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';\n\nimport { doInitialRecursions_keystretch, execRound_getNextHash, } from \"../common/encrypt-decrypt-common.mjs\";\nimport { AlphabetIndexingMode, HashAlgorithm, SaltStrategy } from \"../types.mjs\";\n\n// import { ENCRYPT_LOG_A_LOT } from '../constants.mjs';\n// const logalot = ENCRYPT_LOG_A_LOT || true;\n\n/**\n * Internal function that performs the encryption part of the overall `encrypt`\n * function when using the `multipass` option.\n *\n * @returns ciphertext string\n */\nexport async function encryptFromHex_blockMode({\n    hexEncodedData,\n    initialRecursions,\n    recursionsPerHash,\n    salt,\n    saltStrategy,\n    secret,\n    hashAlgorithm,\n    encryptedDataDelimiter,\n    indexingMode,\n    maxBlockSize,\n    numOfPasses,\n}: {\n    hexEncodedData: string,\n    initialRecursions: number,\n    recursionsPerHash: number,\n    salt: string,\n    saltStrategy: SaltStrategy,\n    secret: string,\n    hashAlgorithm: HashAlgorithm,\n    encryptedDataDelimiter: string,\n    indexingMode: AlphabetIndexingMode,\n    maxBlockSize: number,\n    numOfPasses: number,\n}): Promise<string> {\n    const lc = `[${encryptFromHex_blockMode.name}]`;\n\n    try {\n        // set up \"prevHash\" as a starting point, similar to key-stretching\n        let prevHash = await doInitialRecursions_keystretch({\n            secret,\n            initialRecursions,\n            salt,\n            saltStrategy: saltStrategy!,\n            hashAlgorithm: hashAlgorithm!,\n        });\n        // console.warn(`${lc} first prevHash: ${prevHash}`);\n        // if (logalot) { console.warn(`${lc} doInitialRecursions_keystretch result prevHash: ${prevHash} (W: 0a7979f8f0c6193e7a68d9573143e423)`); }\n\n        /**\n         * closure for avoiding checking `indexingMode` in a tight loop.\n         *\n         * usually I don't go for early optimization but this is low hanging\n         * fruit in a very tight loop.\n         */\n        const getIndexOfCharInAlphabet: (alphabet: string, hexChar: string) => number =\n            indexingMode === 'indexOf' ?\n                (alphabet: string, hexChar: string) => { return alphabet.indexOf(hexChar) } :\n                (alphabet: string, hexChar: string) => { return alphabet.lastIndexOf(hexChar) };\n        // if (logalot) { console.warn(`${lc} using getIndexOfCharInAlphabet (indexingMode: ${indexingMode})`); }\n\n        /**\n         * ultimate indexes that will be stored in output.\n         *\n         * The index into this array corresponds to the index into\n         * `hexEncodedData` array (`indexData`).\n         */\n        let encryptedDataIndexes: number[] = [];\n\n        // set the initial pass length.\n        let totalLength = hexEncodedData.length;\n        let blockSize = maxBlockSize;\n        if (blockSize > totalLength) { blockSize = totalLength; }\n        // if (logalot) { console.warn(`${lc} totalLength (hexEncodedData.length): ${totalLength}, blockSize: ${blockSize} (W: 1529570c6b474ad1a24f3a4c5b7eceb0)`); }\n\n        /**\n         * We are doing multiple passes, but possibly only on subsets of\n         * hexEncodedData. This variable is the number of sections that we're\n         * doing. The final section may be less than a full pass section.\n         *\n         * _note: I am avoiding the use of \"block\" since that is an overloaded term in cryptography._\n         */\n        let blockSections = Math.ceil(totalLength / blockSize);\n        // if (logalot) { console.warn(`${lc} blockSections: ${blockSections}`); }\n        /**\n         * the final pass may be less than the pass length.\n         */\n        // let finalBlockSize = (blockSize - ((blockSections * blockSize) - totalLength)) || blockSize; // if 0, then the last pass is full length\n        let finalBlockSize = (totalLength % blockSize) || blockSize; // if 0, then the last pass is full length\n        // if (logalot) { console.warn(`${lc} finalBlockSize: ${finalBlockSize}`); }\n        /**\n         * index into hexEncodedData at the start of each pass.\n         *\n         * This will be adjusted after each pass in the loop in preparation for\n         * next iteration.\n         */\n        let indexHexEncodedDataAtStartOfPass = 0;\n\n        // iterate through each pass \"section\" and create the alphabets for the\n        // entire section. once the alphabets are created, iterate the plaintext\n        // hexEncodedData and map them to the indices into those alphabets.\n        // todo: add parameterized step to encode indices into characters?\n        for (let indexOfBlock = 0; indexOfBlock < blockSections; indexOfBlock++) {\n\n            // adjust the blockSize if it's the final one which might be shorter\n            const isFinalBlock = indexOfBlock === blockSections - 1;\n            if (isFinalBlock) { blockSize = finalBlockSize; }\n            // if (logalot) { console.warn(`${lc} blockSize: ${blockSize}`); }\n\n            const resGetAlphabets = await getAlphabetsThisBlock({\n                blockSize,\n                indexHexEncodedDataAtStartOfPass,\n                numOfPasses,\n                hexEncodedData,\n                recursionsPerHash,\n                salt,\n                saltStrategy,\n                prevHash,\n                hashAlgorithm,\n            });\n\n            let alphabetsThisBlock = resGetAlphabets.alphabetsThisBlock;\n            // if (logalot) { console.warn(`${lc} alphabetsThisBlock: ${pretty(alphabetsThisBlock)} (W: 8c37818b9658d4c6a418b62ec38bd923)`); }\n            prevHash = resGetAlphabets.prevHash;\n            // if (logalot) { console.warn(`${lc} prevHash after alphabets created: ${prevHash} (W: 0b2ffc3ba7a19ecba74fcec8788a6c23)`); }\n\n            const encryptedIndexesThisBlock = await getEncryptedIndexesThisBlock({\n                alphabetsThisBlock,\n                blockSize,\n                indexHexEncodedDataAtStartOfPass,\n                hexEncodedData,\n                getIndexOfCharInAlphabet,\n            });\n\n            // if (logalot) { console.warn(`${lc} encryptedIndexesThisBlock: ${encryptedIndexesThisBlock} (W: f84c9d05e4160241664051b946ad3f23)`); }\n\n            // if (logalot) { console.warn(`${lc} info before add to encryptedDataIndexes info: ${pretty({ indexOfBlock, isFinalBlock, blockSize, prevHash, encryptedDataIndexes, encryptedIndexesThisBlock })}`); }\n            encryptedDataIndexes = encryptedDataIndexes.concat(encryptedIndexesThisBlock);\n            // if (logalot) { console.warn(`${lc} encryptedDataIndexes so far: ${encryptedDataIndexes} (W: 58f9bbabce8eeb90a213ab1fa0d88123)`); }\n\n            indexHexEncodedDataAtStartOfPass += blockSize;\n        }\n\n        // we now have populated encryptedDataIndexes fully.\n        const resEncryptedData = encryptedDataIndexes.join(encryptedDataDelimiter);\n        // if (logalot) { console.warn(`${lc} final resEncryptedData: ${resEncryptedData} (W: 681bf4eccdf6cddf675ee608804a7e23)`); }\n        // console.warn(`${lc} resEncryptedData: ${resEncryptedData}`);\n        return resEncryptedData;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    }\n}\n\nasync function getAlphabetsThisBlock({\n    blockSize,\n    numOfPasses,\n    indexHexEncodedDataAtStartOfPass,\n    hexEncodedData,\n    recursionsPerHash,\n    salt,\n    saltStrategy,\n    prevHash,\n    hashAlgorithm,\n}: {\n    /** size of the pass, i.e. number of characters to process */\n    blockSize: number,\n    /** number of times to iterate over the pass section */\n    numOfPasses: number,\n    indexHexEncodedDataAtStartOfPass: number,\n    hexEncodedData: string,\n    recursionsPerHash: number,\n    salt: string,\n    saltStrategy: SaltStrategy,\n    prevHash: string,\n    hashAlgorithm: HashAlgorithm,\n}): Promise<{ alphabetsThisBlock: string[], prevHash: string }> {\n    const lc = `[${getAlphabetsThisBlock.name}]`;\n    try {\n        // if (logalot) { console.warn(`${lc} info: ${pretty({ blockSize, numOfPasses, indexHexEncodedDataAtStartOfPass, prevHash })}`); }\n        /**\n         * one alphabet per plaintext character (hex only atow).\n         *\n         * index into this is index in this pass (`indexPass`).\n         *\n         * Instead of building each plaintext character's alphabet until at\n         * least one instance of that character is found, we will build up\n         * each of the alphabets for the entire pass. Then we will add on to\n         * those alphabets, depending on if the character is found (and once\n         * I implement it, additionalSuperfluousAlphabetExtensions).\n         */\n        let alphabetsThisBlock: string[] = [];\n        /** index into the `hexEncodedData` that we're working with */\n        let indexHexEncodedData: number;\n        let hash: string;\n        // first construct all alphabets for this pass section using the\n        // given number of passes. Note that zero or more of these alphabets\n        // may NOT include the hex character to encode, but this will be\n        // addressed in the next step.\n        for (let passNum = 0; passNum < numOfPasses; passNum++) {\n            for (let indexIntoBlock = 0; indexIntoBlock < blockSize; indexIntoBlock++) {\n                indexHexEncodedData = indexHexEncodedDataAtStartOfPass + indexIntoBlock;\n                // if (logalot) { console.warn(`${lc} passNum: ${passNum}, indexIntoBlock: ${indexIntoBlock} (W: 13d09af12647907d4497842616915223)`); }\n                let alphabet = alphabetsThisBlock[indexIntoBlock] ?? '';\n\n                // if (logalot) { console.warn(`${lc} starting alphabet: ${alphabet} (W: b5a3ba3203e679ac454a854c32846723)`); }\n                hash = await execRound_getNextHash({\n                    count: recursionsPerHash,\n                    prevHash, salt, saltStrategy, hashAlgorithm\n                });\n                alphabet += hash;\n                prevHash = hash;\n                // if (logalot) { console.warn(`${lc} extended alphabet: ${alphabet} (W: c0228b716a324761b581d38a805d192b)`); }\n\n                alphabetsThisBlock[indexIntoBlock] = alphabet;\n                // if (logalot) { console.warn(`${lc} alphabetsThisBlock: ${pretty(alphabetsThisBlock)} (W: 1bef26a111a4df4a6d501d5a662dd223)`); }\n            }\n        }\n        // if (logalot) { console.warn(`${lc} initial alphabetsThisBlock (${alphabetsThisBlock.length}): ${pretty(alphabetsThisBlock)} (W: ce1f77a7065e45cfb12995f097f70af4)`); }\n\n        // if (logalot) { console.warn(`${lc} at this point, each alphabet is the same size (numOfPasses * hash size), but it's not guaranteed that each alphabet will contain the plaintext character.  so go through and extend any alphabets that do not yet contain the plaintext character (I: c75085603497ea684865010dfd8a3b23)`); }\n\n        // at this point, each alphabet is the same size (numOfPasses * hash\n        // size), but it's not guaranteed that each alphabet will contain the\n        // plaintext character.  so go through and extend any alphabets that do\n        // not yet contain the plaintext character\n        for (let indexIntoBlock = 0; indexIntoBlock < blockSize; indexIntoBlock++) {\n            indexHexEncodedData = indexHexEncodedDataAtStartOfPass + indexIntoBlock;\n            const hexCharFromData: string = hexEncodedData[indexHexEncodedData];\n            let alphabet = alphabetsThisBlock[indexIntoBlock];\n\n            while (!alphabet.includes(hexCharFromData)) {\n                // if (logalot) { console.warn(`${lc} alphabet (${alphabet}) has to be extended because it does not contain hexChar (${hexCharFromData}).  (W: a8040eb78f4d123cfa423de33a7f3b23)`); }\n                // only executes if alphabet doesnt already contain hexChar\n                hash = await execRound_getNextHash({\n                    count: recursionsPerHash,\n                    prevHash, salt, saltStrategy, hashAlgorithm\n                });\n                alphabet += hash!;\n                prevHash = hash;\n            }\n\n            alphabetsThisBlock[indexIntoBlock] = alphabet;\n            // if (logalot) { console.warn(`${lc} alphabetsThisBlock (length ${alphabetsThisBlock.length}): ${pretty(alphabetsThisBlock)} (W: a86e76aa398d7e4b44dbe0fbb79c1623)`); }\n        }\n        // if (logalot) { console.warn(`${lc} guaranteed alphabetsThisBlock (${alphabetsThisBlock.length}): ${pretty(alphabetsThisBlock)} (W: 8d684c05b116467aa92e946b03160310)`); }\n\n        // if (logalot) { console.warn(`${lc} at this point, each alphabet is at least the minimum size and is guaranteed to have at least once instance of the plaintext hexChar. (W: c6f31445402b1c561670a2dd59530523)`); }\n        // at this point, each alphabet is at least the minimum size and is\n        // guaranteed to have at least once instance of the plaintext hexChar.\n        // if (logalot) { console.warn(`${lc} return prevHash: ${prevHash}`) }\n        return { alphabetsThisBlock, prevHash };\n    } catch (error) {\n        console.error(`${lc} error: ${extractErrorMsg(error)}`);\n        throw error;\n    }\n}\n\nasync function getEncryptedIndexesThisBlock({\n    alphabetsThisBlock,\n    blockSize,\n    indexHexEncodedDataAtStartOfPass,\n    hexEncodedData,\n    getIndexOfCharInAlphabet,\n}: {\n    alphabetsThisBlock: string[],\n    blockSize: number,\n    indexHexEncodedDataAtStartOfPass: number,\n    hexEncodedData: string,\n    getIndexOfCharInAlphabet: (alphabet: string, hexChar: string) => number,\n}): Promise<number[]> {\n    const lc = `[${getEncryptedIndexesThisBlock.name}]`;\n    try {\n        const resIndexes: number[] = [];\n        for (let indexIntoBlock = 0; indexIntoBlock < blockSize; indexIntoBlock++) {\n            const indexHexEncodedData = indexHexEncodedDataAtStartOfPass + indexIntoBlock;\n            const alphabet = alphabetsThisBlock[indexIntoBlock];\n            const encryptedIndexIntoAlphabet = getIndexOfCharInAlphabet(alphabet, hexEncodedData[indexHexEncodedData]);\n            resIndexes.push(encryptedIndexIntoAlphabet);\n        }\n\n        return resIndexes;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    }\n}\n", "import { extractErrorMsg } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';\n\nimport { doInitialRecursions_keystretch, execRound_getNextHash, getPreHash } from \"../common/encrypt-decrypt-common.mjs\";\nimport { AlphabetIndexingMode, HashAlgorithm, SaltStrategy } from \"../types.mjs\";\n\n/**\n * Internal function that takes a given encryptedData, in the form of a\n * delimited string of indexes, and decrypts it back into encoded hex (not the\n * original unencrypted data!).\n *\n * It does this by reconstructing the JIT alphabets for each section, just as\n * was done in the encrypting process. It then uses the encrypted indexes into\n * these alphabets and rebuilds the multipass section's plaintext **hex**.\n *\n * For documentation on args, see `DecryptArgs`.\n *\n * @returns unencrypted, but still hex-encoded plaintext string\n */\nexport async function decryptToHex_blockMode({\n    encryptedData,\n    initialRecursions,\n    recursionsPerHash,\n    salt,\n    saltStrategy,\n    secret,\n    hashAlgorithm,\n    encryptedDataDelimiter,\n    maxBlockSize,\n    numOfPasses,\n}: {\n    encryptedData: string,\n    initialRecursions: number,\n    recursionsPerHash: number,\n    salt: string,\n    saltStrategy: SaltStrategy,\n    secret: string,\n    hashAlgorithm: HashAlgorithm,\n    encryptedDataDelimiter: string,\n    maxBlockSize: number,\n    numOfPasses: number,\n}): Promise<string> {\n    const lc = `[${decryptToHex_blockMode.name}]`;\n\n    try {\n        // set up \"prevHash\" as a starting point, similar to key-stretching\n        let prevHash = await doInitialRecursions_keystretch({\n            secret,\n            initialRecursions,\n            salt,\n            saltStrategy: saltStrategy!,\n            hashAlgorithm: hashAlgorithm!,\n        });\n\n        // we have our prevHash starting point, so now we can iterate through the data\n        let encryptedDataIndexes: number[] =\n            encryptedData.split(encryptedDataDelimiter).map((nString: string) => parseInt(nString));\n        let decryptedDataArray: string[] = [];\n\n        // re-play multipass building of alphabets. Section by section, first\n        // create the minimum number of alphabets. Then iterate through each\n        // cipher index, extending individual alphabets JIT/on demand depending\n        // on the cipher index, i.e., if the index is larger than the existing\n        // alphabet, then we extend it another round.\n\n        // set the initial pass length.\n        let totalLength = encryptedDataIndexes.length;\n        let blockSize = maxBlockSize;\n        if (blockSize > totalLength) { blockSize = totalLength; }\n\n        /**\n         * We are doing multiple passes, but possibly only on subsets of\n         * encryptedDataIndexes. This variable is the number of sections that we're\n         * doing. The final section may be less than a full pass section.\n         *\n         * _note: I am avoiding the use of \"block\" since that is an overloaded term in cryptography and is usually related to padding._\n         */\n        let blockSections = Math.ceil(totalLength / blockSize);\n        /**\n         * the final pass may be less than the pass length.\n         */\n        let finalBlockSize = (totalLength % blockSize) || blockSize; // if 0, then the last pass is full length\n        /**\n         * index into encryptedDataIndexes at the start of each pass.\n         *\n         * This will be adjusted after each pass in the loop in preparation for\n         * next iteration.\n         */\n        let indexEncryptedDataIndexesAtStartOfPass = 0;\n\n        // iterate through each pass \"section\" and create the alphabets for the\n        // entire section. once the alphabets are created, iterate the plaintext\n        // hexEncodedData and map them to the indices into those alphabets.\n        // todo: add parameterized step to encode indices into characters?\n        for (let indexOfBlock = 0; indexOfBlock < blockSections; indexOfBlock++) {\n\n            // adjust the blockSize if it's the final one which might be shorter\n            const isFinalBlock = indexOfBlock === blockSections - 1;\n            if (isFinalBlock) { blockSize = finalBlockSize; }\n\n            const resGetAlphabets = await getAlphabetsThisBlock({\n                blockSize,\n                indexEncryptedDataIndexesAtStartOfPass,\n                numOfPasses,\n                encryptedDataIndexes,\n                recursionsPerHash,\n                salt,\n                saltStrategy,\n                prevHash,\n                hashAlgorithm,\n            });\n\n            let alphabetsThisBlock = resGetAlphabets.alphabetsThisBlock;\n            prevHash = resGetAlphabets.prevHash; // used in next section if there is one\n\n            const decryptedDataArrayThisBlock = await getDecryptedDataArrayThisBlock({\n                alphabetsThisBlock,\n                blockSize,\n                indexEncryptedDataIndexesAtStartOfPass,\n                encryptedDataIndexes,\n            });\n\n            decryptedDataArray = decryptedDataArray.concat(decryptedDataArrayThisBlock);\n\n            indexEncryptedDataIndexesAtStartOfPass += blockSize;\n        }\n\n        // reconstitute the decryptedHex\n        const decryptedHex: string = decryptedDataArray.join('');\n        return decryptedHex;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    }\n}\n\n/**\n * internal function that builds the JIT alphabets for a given multipass\n * section.\n *\n * @returns alphabetsThisBlock array of alphabets and the final `prevHash` for use in the next multipass section (if any).\n */\nasync function getAlphabetsThisBlock({\n    blockSize,\n    numOfPasses,\n    indexEncryptedDataIndexesAtStartOfPass,\n    encryptedDataIndexes,\n    recursionsPerHash,\n    salt,\n    saltStrategy,\n    prevHash,\n    hashAlgorithm,\n}: {\n    /**\n     * Size of the multipass section, i.e. number of characters to\n     * encrypt/decrypt as a whole.\n     */\n    blockSize: number,\n    /**\n     * Number of times to iterate over the multipass section\n     */\n    numOfPasses: number,\n    indexEncryptedDataIndexesAtStartOfPass: number,\n    encryptedDataIndexes: number[],\n    recursionsPerHash: number,\n    salt: string,\n    saltStrategy: SaltStrategy,\n    prevHash: string,\n    hashAlgorithm: HashAlgorithm,\n}): Promise<{ alphabetsThisBlock: string[], prevHash: string }> {\n    const lc = `[${getAlphabetsThisBlock.name}]`;\n    try {\n        /**\n         * one alphabet per plaintext character (hex only atow).\n         *\n         * index into this is index in this pass (`indexPass`).\n         *\n         * Instead of building each plaintext character's alphabet until at\n         * least one instance of that character is found, we will build up\n         * each of the alphabets for the entire pass. Then we will add on to\n         * those alphabets, depending on if the character is found (and once\n         * I implement it, additionalSuperfluousAlphabetExtensions).\n         */\n        let alphabetsThisBlock: string[] = [];\n        /** index into the `encryptedDataIndexes` that we're working with */\n        let indexEncryptedDataIndexes: number;\n        let hash: string;\n        // first construct all alphabets for this pass section using the\n        // given number of passes. Note that zero or more of these alphabets\n        // may NOT include the hex character to encode, but this will be\n        // addressed in the next step.\n        for (let passNum = 0; passNum < numOfPasses; passNum++) {\n            for (let indexIntoBlock = 0; indexIntoBlock < blockSize; indexIntoBlock++) {\n                indexEncryptedDataIndexes = indexEncryptedDataIndexesAtStartOfPass + indexIntoBlock;\n                let alphabet = alphabetsThisBlock[indexIntoBlock] ?? '';\n\n                hash = await execRound_getNextHash({\n                    count: recursionsPerHash,\n                    prevHash, salt, saltStrategy, hashAlgorithm\n                });\n                alphabet += hash;\n                prevHash = hash;\n\n                alphabetsThisBlock[indexIntoBlock] = alphabet;\n            }\n        }\n\n        // at this point, each alphabet is the same size (numOfPasses * hash\n        // size), but it's not guaranteed that each alphabet will contain the\n        // plaintext character.  so go through and extend any alphabets that do\n        // not yet contain the plaintext character\n        for (let indexIntoBlock = 0; indexIntoBlock < blockSize; indexIntoBlock++) {\n            indexEncryptedDataIndexes = indexEncryptedDataIndexesAtStartOfPass + indexIntoBlock;\n            const encryptedIndex: number = encryptedDataIndexes[indexEncryptedDataIndexes];\n            let alphabet = alphabetsThisBlock[indexIntoBlock];\n\n            // while (!alphabet.includes(hexCharFromData)) {\n            while (alphabet.at(encryptedIndex) === undefined) {\n                // only executes if alphabet isn't long enough for index\n                hash = await execRound_getNextHash({\n                    count: recursionsPerHash,\n                    prevHash, salt, saltStrategy, hashAlgorithm\n                });\n                alphabet += hash;\n                prevHash = hash;\n            }\n\n            alphabetsThisBlock[indexIntoBlock] = alphabet;\n        }\n\n        // at this point, each alphabet is at least the minimum size and is\n        // guaranteed to have at least once instance of the plaintext hexChar.\n        return { alphabetsThisBlock, prevHash };\n    } catch (error) {\n        console.error(`${lc} error: ${extractErrorMsg(error)}`);\n        throw error;\n    }\n}\n\n/**\n * Takes the incoming encrypted indexes for a multipass section and maps them to\n * plaintext.\n *\n * @param args see individual param docs\n * @returns plaintext as an array of strings\n */\nasync function getDecryptedDataArrayThisBlock({\n    alphabetsThisBlock,\n    blockSize,\n    indexEncryptedDataIndexesAtStartOfPass,\n    encryptedDataIndexes,\n}: {\n    /**\n     * All alphabets for this multipass section that we have already created in\n     * a previous step.\n     */\n    alphabetsThisBlock: string[],\n    /**\n     * Size of the multipass section that we are processing as a whole.\n     */\n    blockSize: number,\n    /**\n     * Start of the multipass section, used to index into {@link encryptedDataIndexes}.\n     */\n    indexEncryptedDataIndexesAtStartOfPass: number,\n    /**\n     * Reference to the entire encrypted data array.\n     *\n     * We will index into this array and get the \"encrypted data index\" which is\n     * the index into the alphabet for that encrypted character.\n     */\n    encryptedDataIndexes: number[],\n}): Promise<string[]> {\n    const lc = `[${getDecryptedDataArrayThisBlock.name}]`;\n    try {\n        const resDataArray: string[] = [];\n\n        for (let indexIntoBlock = 0; indexIntoBlock < blockSize; indexIntoBlock++) {\n            let indexEncryptedDataIndexes = indexEncryptedDataIndexesAtStartOfPass + indexIntoBlock;\n            const encryptedIndex: number = encryptedDataIndexes[indexEncryptedDataIndexes];\n            let alphabet = alphabetsThisBlock[indexIntoBlock];\n            let decryptedCharString = alphabet[encryptedIndex];\n            resDataArray.push(decryptedCharString);\n        }\n\n        return resDataArray;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    }\n}\n", "import { getUUID } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';\n\nimport * as c from '../constants.mjs';\nimport { decodeHexStringToString } from '../helper.mjs';\nimport { ALPHABET_INDEXING_MODES, DecryptArgs, DecryptResult, HashAlgorithm, SALT_STRATEGIES } from \"../types.mjs\";\nimport { decryptToHex_blockMode } from './decrypt-to-hex-block-mode.mjs';\n\n/**\n * Does the actual decryption work using shortCircuit mitigation strategies.\n *\n//  * {@link decrypt}\n * {@link DecryptArgs}\n * {@link DecryptResult}\n *\n * @returns a `DecryptResult` info object\n */\nexport async function decryptImpl_blockMode(args: DecryptArgs): Promise<DecryptResult> {\n    const lc = `[${decryptImpl_blockMode.name}]`;\n    let {\n        encryptedData,\n        initialRecursions,\n        recursionsPerHash,\n        salt,\n        saltStrategy,\n        secret,\n        hashAlgorithm,\n        encryptedDataDelimiter,\n        indexingMode,\n        blockMode,\n        multipass,\n    } = args;\n\n    const errors: string[] = [];\n    const warnings: string[] = [];\n\n    if (blockMode && multipass) { throw new Error(`blockMode and multipass set. blockMode was a refactored name of multipass, so these should not both be present. multipass is deprecated. (E: b9b3cd1f701c700835c0419260278223)`); }\n    if (!blockMode && !!multipass) {\n        console.warn(`${lc}[WARNING] \"multipass\" option is deprecated. this has been refactored to \"blockMode\". This will use multipass as blockMode. (W: b77c9773e30549cbb389ce61f31eb6d3)`);\n        blockMode = multipass; // to support older versions that use refactored \"multipass\"\n    }\n    if (!blockMode) { throw new Error(`(UNEXPECTED) blockMode required. This should be truthy in order to get to this impl fn. (E: 306bce36afd64b7182ca2b46ac04a261)`); }\n\n    // #region set args defaults\n\n    initialRecursions = initialRecursions || c.DEFAULT_INITIAL_RECURSIONS;\n    recursionsPerHash = recursionsPerHash || c.DEFAULT_RECURSIONS_PER_HASH;\n    saltStrategy = saltStrategy || c.DEFAULT_SALT_STRATEGY;\n    hashAlgorithm = hashAlgorithm || c.DEFAULT_HASH_ALGORITHM;\n    salt = salt || await getUUID(c.DEFAULT_GETUUID_SEEDSIZE);\n    encryptedDataDelimiter = encryptedDataDelimiter || c.DEFAULT_ENCRYPTED_DATA_DELIMITER;\n\n    indexingMode = indexingMode || c.DEFAULT_ALPHABET_INDEXING_MODE_BLOCKMODE;\n\n    let { maxBlockSize, maxPassSectionLength, numOfPasses } = blockMode;\n    if (!maxBlockSize && !!maxPassSectionLength) {\n        console.warn(`${lc}[WARNING] \"maxPassSectionLength\" option is deprecated. this has been refactored to \"maxBlockSize\". This will use maxPassSectioLength as maxBlockSize. (W: e2c83d78a3464704a6067e0f767f20b0)`);\n        maxBlockSize = maxPassSectionLength;\n    }\n    maxBlockSize = maxBlockSize || c.DEFAULT_MAX_BLOCK_SIZE;\n    numOfPasses = numOfPasses || c.DEFAULT_NUM_OF_PASSES;\n\n    // #endregion\n\n    // #region args validation\n\n    const lcv = `[validation]`;\n\n    if (!initialRecursions || initialRecursions < 1) { const e = `${lcv} initialRecursions required, and greater than 0`; console.error(e); errors.push(e); }\n    if (!recursionsPerHash || recursionsPerHash < 1) { const e = `${lcv} recursionsPerHash required, and greater than 0`; console.error(e); errors.push(e); }\n    if (!encryptedData) { const e = `${lcv} encryptedData required`; console.error(e); errors.push(e); }\n    if (!salt) { const e = `${lcv} salt required`; console.error(e); errors.push(e); }\n    if (!saltStrategy) { const e = `${lcv} saltStrategy required`; console.error(e); errors.push(e); }\n    if (!secret) { const e = `${lcv} secret required`; console.error(e); errors.push(e); }\n    if (!encryptedDataDelimiter) { const e = `${lcv} encryptedDataDelimiter required`; console.error(e); errors.push(e); }\n    if (!indexingMode) { const e = `${lcv} indexingMode required (E: a6fe15f8ba414e21b5355d23e808b976)`; console.error(e); errors.push(e); }\n    if (!ALPHABET_INDEXING_MODES.includes(indexingMode)) { const e = `${lcv} invalid indexingMode (${indexingMode}). Must be one of ${ALPHABET_INDEXING_MODES} (E: 17435268651444e0b7a594135635fc58)`; console.error(e); errors.push(e); }\n    if (maxBlockSize < 1) { const e = `${lcv} maxBlockSize must be greater than 0 (E: 0870831aa86b4bfa939aeee9f252326a)`; console.error(e); errors.push(e); }\n    if (numOfPasses < 1) { const e = `${lcv} numOfPasses must be greater than 0 (E: 691d3c3765584c6f8c9aba1ee378df00)`; console.error(e); errors.push(e); }\n\n    // if (hashAlgorithm !== 'SHA-256') { const e = `${lcv} only SHA-256 implemented`; console.error(e); errors.push(e); }\n    if (!Object.values(HashAlgorithm).includes(hashAlgorithm)) {\n        const e = `${lcv} only ${Object.values(HashAlgorithm)} hash algorithms implemented`; console.error(e); errors.push(e);\n    }\n\n    if (saltStrategy && !SALT_STRATEGIES.includes(saltStrategy!)) {\n        const e = `${lcv} unknown saltStrategy: ${saltStrategy}`; console.error(e); errors.push(e);\n    }\n\n    if (errors.length > 0) {\n        let result = { ...args, errors: errors };\n        delete (result as any).encryptedData;\n        delete (result as any).secret;\n        return result;\n    }\n\n    // #endregion args validation\n\n    // decrypt from indices into hex\n    let hexEncodedData: string = await decryptToHex_blockMode({\n        encryptedData,\n        initialRecursions,\n        recursionsPerHash,\n        salt,\n        saltStrategy,\n        secret,\n        hashAlgorithm,\n        encryptedDataDelimiter,\n        maxBlockSize,\n        numOfPasses,\n    });\n\n    // decode hex back into original data\n    const decryptedData: string = await decodeHexStringToString(hexEncodedData);\n\n    const result: DecryptResult = {\n        ...args,\n        decryptedData,\n        warnings: warnings.length > 0 ? warnings : undefined,\n    };\n    delete (result as any).encryptedData;\n    delete (result as any).secret;\n    return result;\n}\n", "import { extractErrorMsg } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';\n\nimport { decodeHexStringToString, encodeStringToHexString } from '../helper.mjs';\nimport { ALPHABET_INDEXING_MODES, EncryptArgs, EncryptResult, HashAlgorithm, SALT_STRATEGIES } from \"../types.mjs\";\nimport { encryptFromHex_blockMode } from './encrypt-from-hex-block-mode.mjs';\nimport { decryptImpl_blockMode } from './decrypt-block-mode.mjs';\nimport {\n    DEFAULT_ALPHABET_INDEXING_MODE_BLOCKMODE,\n    DEFAULT_ENCRYPTED_DATA_DELIMITER, DEFAULT_INITIAL_RECURSIONS,\n    DEFAULT_MAX_BLOCK_SIZE, DEFAULT_NUM_OF_PASSES,\n    ENCRYPT_LOG_A_LOT\n} from '../constants.mjs';\n\n// const logalot = ENCRYPT_LOG_A_LOT || true;\n\n/**\n * Does the actual encryption work using the original \"stream\" streaming\n * encryption.\n *\n * {@link encrypt}\n * {@link EncryptArgs}\n * {@link EncryptResult}\n *\n * @returns a `EncryptResult` info object\n */\nexport async function encryptImpl_blockMode(args: EncryptArgs): Promise<EncryptResult> {\n    const lc = `[${encryptImpl_blockMode.name}]`;\n\n    let {\n        dataToEncrypt,\n        initialRecursions,\n        recursionsPerHash,\n        salt,\n        saltStrategy,\n        secret,\n        hashAlgorithm,\n        encryptedDataDelimiter,\n        confirm,\n        indexingMode,\n        blockMode,\n        multipass,\n    } = args;\n\n    const errors: string[] = [];\n    let warnings: string[] = [];\n\n    if (blockMode && multipass) { throw new Error(`blockMode and multipass set. blockMode was a refactored name of multipass, so these should not both be present. multipass is deprecated. (E: bde5efd1a3e449dca549c5bff147f09b)`); }\n    if (!blockMode && !!multipass) {\n        console.warn(`${lc}[WARNING] \"multipass\" option is deprecated. this has been refactored to \"blockMode\". This will use multipass as blockMode. (W: 046b55a6d1304155b2e5352a9e6140b0)`);\n        blockMode = multipass; // to support older versions that use refactored \"multipass\"\n    }\n    if (!blockMode) { throw new Error(`(UNEXPECTED) blockMode required. This should be truthy in order to get to this impl fn. (E: 0b87871f81d849ef8f0263b7775bd3e3)`); }\n\n    // #region set args defaults\n\n    if (!initialRecursions) {\n        console.warn(`${lc} initial recursions required. defaulting to ${DEFAULT_INITIAL_RECURSIONS}`);\n        initialRecursions = DEFAULT_INITIAL_RECURSIONS;\n    }\n    encryptedDataDelimiter = encryptedDataDelimiter || DEFAULT_ENCRYPTED_DATA_DELIMITER;\n    indexingMode = indexingMode || DEFAULT_ALPHABET_INDEXING_MODE_BLOCKMODE;\n\n    // let { maxPassSectionLength, numOfPasses } = blockMode;\n    // maxPassSectionLength = maxPassSectionLength || DEFAULT_MAX_BLOCK_SIZE;\n    // numOfPasses = numOfPasses || DEFAULT_NUM_OF_PASSES;\n    let { maxBlockSize, maxPassSectionLength, numOfPasses } = blockMode;\n    if (!maxBlockSize && !!maxPassSectionLength) {\n        console.warn(`${lc}[WARNING] \"maxPassSectionLength\" option is deprecated. this has been refactored to \"maxBlockSize\". This will use maxPassSectioLength as maxBlockSize. (W: c28fe476105643e184d0ddd5d2aa8a5d)`);\n        maxBlockSize = maxPassSectionLength;\n    }\n    maxBlockSize = maxBlockSize || DEFAULT_MAX_BLOCK_SIZE;\n    numOfPasses = numOfPasses || DEFAULT_NUM_OF_PASSES;\n\n    // #endregion set args defaults\n\n    // #region args validation\n\n    const lcv = `[validation]`;\n\n    if (!initialRecursions || initialRecursions < 1) { const e = `${lcv} initialRecursions required, and greater than 0 (E: dd96a75f0c504f34b1f9f2f32e011c50)`; console.error(e); errors.push(e); }\n    if (!recursionsPerHash || recursionsPerHash < 1) { const e = `${lcv} recursionsPerHash required, and greater than 0 (E: 64cf53e0bf9f4963be6b165ca4e6566d)`; console.error(e); errors.push(e); }\n    if (!salt) { const e = `${lcv} salt required (E: 136a5d237e0f4b1d89f8c87ac12a1507)`; console.error(e); errors.push(e); }\n    if (!saltStrategy) { const e = `${lcv} saltStrategy required (E: 457ed117bf224b9f86fe81ab6bc35381)`; console.error(e); errors.push(e); }\n    if (!secret) { const e = `${lcv} secret required (E: 5c363255055a45cfb07656e2f4854ed7)`; console.error(e); errors.push(e); }\n    if (!encryptedDataDelimiter) { const e = `${lcv} encryptedDataDelimiter required (E: 1bbeb4dce19e4ac2bbe7d1e373739298)`; console.error(e); errors.push(e); }\n    if (!indexingMode) { const e = `${lcv} indexingMode required (E: 693ebd2be64a438aa3b075d0cb0d92bf)`; console.error(e); errors.push(e); }\n    if (!ALPHABET_INDEXING_MODES.includes(indexingMode)) { const e = `${lcv} invalid indexingMode (${indexingMode}). Must be one of ${ALPHABET_INDEXING_MODES} (E: 17435268651444e0b7a594135635fc58)`; console.error(e); errors.push(e); }\n    if (maxBlockSize < 1) { const e = `${lcv} maxBlockSize must be greater than 0 (E: 9f268207ae274b958fb91855331be259)`; console.error(e); errors.push(e); }\n    if (numOfPasses < 1) { const e = `${lcv} numOfPasses must be greater than 0 (E: c3bcab79bb024d65b84947806290a7d4)`; console.error(e); errors.push(e); }\n\n    // if (hashAlgorithm !== 'SHA-256') { const e = `${lcv} only SHA-256 implemented`; console.error(e); errors.push(e); }\n    if (!Object.values(HashAlgorithm).includes(hashAlgorithm!)) {\n        const e = `${lcv} only ${Object.values(HashAlgorithm)} hash algorithms implemented`; console.error(e); errors.push(e);\n    }\n\n    if (saltStrategy && !SALT_STRATEGIES.includes(saltStrategy!)) {\n        const e = `${lcv} unknown saltStrategy: ${saltStrategy}`; console.error(e); errors.push(e);\n    }\n\n    if (errors.length > 0) {\n        let result = { ...args, errors: errors };\n        delete (result as any).dataToEncrypt;\n        delete (result as any).secret;\n        return result;\n    }\n\n    // #endregion args validation\n\n    // #region encode data to just hex (i.e. only have 0-9, a-f)\n\n    // console.log(`${lc} hex encoding dataToEncrypt: ${dataToEncrypt}`);\n    const hexEncodedData: string = await encodeStringToHexString(dataToEncrypt);\n    if (confirm) {\n        // confirm data can be converted back into the original data\n        // console.log(`${lc} hex decoding back to check with dataToEncrypt: ${hexEncodedData}`);\n        // if (logalot) { console.log(`${lc} hexEncodedData: ${hexEncodedData} (I: 5568ee9bad6bfaa6f266bc9c5b5fc423)`); }\n        const confirmDecodedData = await decodeHexStringToString(hexEncodedData);\n        // console.log(`${lc} checkDecodedData: ${confirmDecodedData}`);\n        if (confirmDecodedData !== dataToEncrypt) {\n            throw new Error(`decoding encoded hex failed for this data: The encoded hex did not reverse to the original data.`);\n        }\n    }\n\n    // #endregion encode data to just hex (i.e. only have 0-9, a-f)\n\n    // #region encrypt hex\n\n    // comma-delimited indexes string\n    const encryptedData: string = await encryptFromHex_blockMode({\n        hexEncodedData,\n        initialRecursions,\n        recursionsPerHash: recursionsPerHash!,\n        salt,\n        saltStrategy: saltStrategy!,\n        secret,\n        hashAlgorithm: hashAlgorithm!,\n        encryptedDataDelimiter,\n        indexingMode,\n        maxBlockSize,\n        numOfPasses,\n    });\n\n    // DO NOT LEAVE THIS IN PROD!!!\n    // console.warn(`${lc} TAKE THIS OUT!! encryptedData: ${encryptedData}`); // DO NOT LEAVE THIS IN PROD!!!\n    // DO NOT LEAVE THIS IN PROD!!!\n\n    if (confirm) {\n        try {\n            const resDecrypt = await decryptImpl_blockMode({\n                encryptedData,\n                initialRecursions,\n                recursionsPerHash,\n                salt,\n                saltStrategy,\n                secret,\n                hashAlgorithm,\n                encryptedDataDelimiter,\n                indexingMode,\n                blockMode,\n            });\n            if (!resDecrypt.decryptedData) {\n                throw new Error(`Confirm check call to decrypt produced falsy decryptedData (E: a4fe82dee61f497e9dea188ea9c287a4)`);\n            } else if (resDecrypt.decryptedData !== dataToEncrypt) {\n                // DO NOT LEAVE THIS IN PROD!!!\n                // console.warn(`resDecrypt.decryptedData: ${resDecrypt.decryptedData}`); // DO NOT LEAVE THIS IN PROD!!!\n                // console.warn(`dataToEncrypt: ${dataToEncrypt}`); // DO NOT LEAVE THIS IN PROD!!!\n                // DO NOT LEAVE THIS IN PROD!!!\n                throw new Error(`The ENCRYPTED data did not decrypt back to the original data. (E: 16b5f1a11e4f438ab38a7f124178a7b8)`);\n                // } else {\n                // console.log(`${lc} decrypt confirmed.`);\n            }\n            if ((resDecrypt.warnings || []).length > 0) {\n                warnings = warnings.concat([`Confirm check call to decrypt had warnings.`, ...resDecrypt.warnings!])\n            }\n        } catch (error) {\n            throw new Error(`${lc} confirm failed. decrypt error: ${extractErrorMsg(error)} (E: 782a84d9dc294ce9a6a325e3ab293adf)`);\n        }\n    }\n\n    // #endregion\n\n    const result: EncryptResult = {\n        ...args,\n        encryptedData,\n        warnings: warnings.length > 0 ? warnings : undefined,\n    };\n    delete (result as any).dataToEncrypt;\n    delete (result as any).secret;\n    return result;\n}\n", "import { getUUID } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';\n\nimport * as c from './constants.mjs';\nimport {\n    EncryptArgs, EncryptResult,\n    DecryptArgs, DecryptResult,\n} from './types.mjs';\nimport { encryptImpl_stream } from './stream-mode/encrypt-stream-mode.mjs'\nimport { encryptImpl_blockMode } from './block-mode/encrypt-block-mode.mjs';\nimport { decryptImpl_stream } from './stream-mode/decrypt-stream-mode.mjs';\nimport { decryptImpl_blockMode } from './block-mode/decrypt-block-mode.mjs';\n\n/**\n * Encrypts given `dataToEncrypt` using the secret and other\n * given algorithm parameters.\n *\n * NOTE: These parameters must be the same when the call to `decrypt` happens!\n *\n * @see {@link DecryptArgs}\n * @see {@link DecryptResult}\n *\n * @returns `EncryptResult` info object with either `dataToEncrypt` or a populated `errors` array.\n */\nexport async function encrypt(args: EncryptArgs): Promise<EncryptResult> {\n    const lc = `[${encrypt.name}]`;\n    try {\n        // initial common validation\n        if (!args) { throw new Error('args required (E: 22e58e03c78f4c27bf18295b8d2cdd3a)'); }\n        if (!args.dataToEncrypt) { throw new Error(`dataToEncrypt required (E: 168c9076e5434c83ba81e3485ee6f3e4)`); }\n\n        // common defaults\n        args.salt = args.salt || await getUUID(c.DEFAULT_GETUUID_SEEDSIZE);\n        args.saltStrategy = args.saltStrategy || c.DEFAULT_SALT_STRATEGY;\n        args.hashAlgorithm = args.hashAlgorithm || c.DEFAULT_HASH_ALGORITHM;\n        args.recursionsPerHash = args.recursionsPerHash || c.DEFAULT_RECURSIONS_PER_HASH;\n\n        // route to appropriate implementor\n        let result: EncryptResult;\n        if (args.blockMode) {\n            result = await encryptImpl_blockMode(args);\n        } else {\n            result = await encryptImpl_stream(args);\n        }\n\n        // print out warnings/errors if necessary\n        if ((result.errors ?? []).length > 0) { result.errors!.forEach(e => console.warn(`${lc} ${e}`)); }\n        if ((result.warnings ?? []).length > 0) { result.warnings!.forEach(w => console.warn(`${lc} ${w}`)); }\n\n        // we're done\n        return result;\n    } catch (error) {\n        console.error(`${lc}${error.message}`);\n        throw error;\n        // const result = { ...args, errors: [error] };\n        // delete (result as any).dataToEncrypt;\n        // delete (result as any).secret;\n        // return result;\n    }\n}\n\n/**\n * Decrypts given `encryptedData` using the secret and other\n * given algorithm parameters.\n *\n * NOTE: These parameters must be the same as what the `encrypt` call used!\n *\n * @see {@link DecryptArgs}\n * @see {@link DecryptResult}\n *\n * @returns `DecryptResult` info object with either `decryptedData` or a populated `errors` array.\n */\nexport async function decrypt(args: DecryptArgs): Promise<DecryptResult> {\n    const lc = `[${decrypt.name}]`;\n    try {\n        // initial common validation\n        if (!args) { throw new Error('args required (E: fcd9b4aad85c4deba5fe5fde0b9ecb30)'); }\n        if (!args.encryptedData) { throw new Error(`encryptedData required (E: f879f612428b4283bae089acee929a58)`); }\n\n        // common defaults\n        args.salt = args.salt || await getUUID(c.DEFAULT_GETUUID_SEEDSIZE);\n        args.saltStrategy = args.saltStrategy || c.DEFAULT_SALT_STRATEGY;\n        args.hashAlgorithm = args.hashAlgorithm || c.DEFAULT_HASH_ALGORITHM;\n        args.recursionsPerHash = args.recursionsPerHash || c.DEFAULT_RECURSIONS_PER_HASH;\n\n        // route to appropriate implementor\n        let result: DecryptResult;\n        if (args.blockMode || args.multipass) {\n            result = await decryptImpl_blockMode(args);\n        } else {\n            result = await decryptImpl_stream(args);\n        }\n\n        // print out warnings/errors if necessary\n        if ((result.warnings ?? []).length > 0) { result.warnings!.forEach(w => console.warn(`${lc} ${w}`)); }\n        if ((result.errors ?? []).length > 0) { result.errors!.forEach(e => console.warn(`${lc} ${e}`)); }\n\n        // we're done\n        return result;\n        // console.log(`${lc} encryptedDataDelimiter: ${encryptedDataDelimiter}`);\n    } catch (error) {\n        console.error(`${lc}${error.message}`);\n        throw error;\n        // const result = { ...args, errors: [error] };\n        // delete (result as any).encryptedData;\n        // delete (result as any).secret;\n        // return result;\n    }\n}\n", "import { SaltStrategy } from '@ibgib/encrypt-gib/dist/index.mjs';\n\nexport const DEFAULT_ENCRYPTION_INITIAL_RECURSIONS = 50000;\nexport const MIN_ENCRYPTION_INITIAL_RECURSIONS = 1000;\nexport const MAX_ENCRYPTION_INITIAL_RECURSIONS = 10000000;\nexport const MIN_ENCRYPTION_RECURSIONS_PER_HASH = 1;\nexport const MAX_ENCRYPTION_RECURSIONS_PER_HASH = 1000;\nexport const MIN_ENCRYPTION_SALT_LENGTH = 50;\nexport const MAX_ENCRYPTION_SALT_LENGTH = 99999;\nexport const MIN_ENCRYPTION_PASSWORD_LENGTH = 8;\nexport const MAX_ENCRYPTION_PASSWORD_LENGTH = 9999999;\nexport const DEFAULT_ENCRYPTION_SALT_STRATEGY: SaltStrategy = SaltStrategy.appendPerHash;\nexport const DEFAULT_ENCRYPTION_RECURSIONS_PER_HASH = 10;\nexport const DEFAULT_ENCRYPTION_HASH_ALGORITHM = 'SHA-256';\n\n/**\n * atom at the start of encryption ibgibs' `ib`.\n */\nexport const ENCRYPTION_ATOM = 'encryption';\n\n/**\n * default regexp for a simple name string.\n */\nexport const ENCRYPTION_NAME_REGEXP = /^[a-zA-Z0-9_\\-.]{1,255}$/;\n\n/**\n * An encryptions ibgib uses this rel8n name for its children encryptions.\n */\nexport const ENCRYPTION_REL8N_NAME = 'encryption';\n\n/**\n * atom for ciphertext...hmm\n */\nexport const CIPHERTEXT_ATOM = 'ciphertext';\n/**\n * Related encrypted ciphertext ibgibs will use this rel8n name.\n * Those ciphertext ibgibs will then relate to the encryption used.\n */\nexport const CIPHERTEXT_REL8N_NAME = 'ciphertext';\n", "import { IbGibRel8ns_V1, IbGib_V1 } from '@ibgib/ts-gib/dist/V1/index.mjs';\nimport { IbGibAddr, IbGib, IbGibRel8ns, TjpIbGibAddr } from '@ibgib/ts-gib/dist/types.mjs';\n\nimport {\n    Witness,\n    WitnessData_V1, WitnessResultData, WitnessResultIbGib, WitnessResultRel8ns,\n} from '../witness-types.mjs';\nimport { IbGibSpaceAny } from './space-base-v1.mjs';\nimport { ENCRYPTION_REL8N_NAME } from '../../common/encrypt/encrypt-constants.mjs';\nimport { WitnessCmdData, WitnessCmdIbGib, WitnessCmdRel8ns, } from '../witness-cmd/witness-cmd-types.mjs';\n\n/**\n * Marker type to show intent that it should be the spaceId, i.e.\n * space.data.uuid.\n */\nexport type SpaceId = string;\n\nexport type SpaceLocation = \"local\" | \"sync\";\nexport const SpaceLocation = {\n    /**\n     * space is a local space, with lower latency and direct usage with\n     * metaspace. To be used as the primary local user space.\n     *\n     * no real proxy is involved, rather, we should be speaking \"directly\" with\n     * the local location.\n     */\n    local: 'local' as SpaceLocation,\n    /**\n     * space is an outerspace, with higher latency, probably some kind of proxy\n     * client access. More intended to be used with syncing...\n     */\n    outerspace: 'outerspace' as SpaceLocation,\n    /**\n     * in-memory-only space.\n     *\n     * Note: I haven't really incorporated this, but I have sketched an\n     * in-memory innerspace and in the future, I think this will be heavily\n     * utilized.\n     */\n    innerspace: 'innerspace' as SpaceLocation,\n}\nexport const VALID_SPACE_LOCATIONS = Object.values(SpaceLocation).concat();\n\nexport type SpaceType = \"user\" | \"sync\";\nexport const SpaceType = {\n    /**\n     * user space that usually (always?) acts locally as the main type of\n     * storage for a user.\n     *\n     * This means that the user is actively working in this space, and it isn't\n     * a derivative space. perhaps \"source\" would be better?\n     */\n    user: 'user' as SpaceType,\n    /**\n     * this is a derivative user space that is used to synchronize ibgib\n     * timelines among two or more other spaces.\n     */\n    sync: 'sync' as SpaceType,\n}\n/**\n * Object.values(SpaceType).concat()\n *\n * for now, you can add valid space types here in initialization code to\n * manually extend this.\n */\nexport const VALID_SPACE_TYPES = Object.values(SpaceType).concat();\n\nexport type UserSpaceSubtype = 'node-filesystem';\n/**\n * specific/concrete subtype implementations\n */\nexport const UserSpaceSubtype = {\n    /**\n     * local user space is driven by a node filesystem concrete implementation.\n     *\n     * Note: This is actually implemented elsewhere, but I am deferring the\n     * additional architectural requirements for putting the node filesystem and\n     * extending this to include it. so I'm just putting this here. But in the\n     * future, this should be moved to a node-specific library and brought in if\n     * the app requires it.\n     */\n    node_filesystem: 'node-filesystem' as UserSpaceSubtype,\n}\nexport type SyncSpaceSubtype = 'aws-dynamodb';\nexport const SyncSpaceSubtype = {\n    aws_dynamodb: 'aws-dynamodb' as SyncSpaceSubtype,\n}\n\nexport type SpaceSubtype = UserSpaceSubtype | SyncSpaceSubtype; // extend with logical OR types here\n/**\n * specific, concrete implementation of space\n */\nexport const SpaceSubtype = {\n    ...UserSpaceSubtype,\n    ...SyncSpaceSubtype,\n}\n/**\n * Object.values(SpaceSubtype).concat()\n *\n * for now, you can add valid subtypes here in initialization code to manually\n * extend this.\n */\nexport const VALID_SPACE_SUBTYPES = Object.values(SpaceSubtype).concat();\n\n/**\n * Common data among all ibgib spaces.\n */\nexport interface IbGibSpaceData extends WitnessData_V1 {\n    /**\n     * redeclaration for the name of the space, to make it required as opposed\n     * to the base declaration which is optional.\n     *\n     * does NOT have to be unique.\n     */\n    name: string;\n    /**\n     * Redeclared over {@link WitnessData_V1.uuid} just for code readability,\n     * showing the id to be a {@link SpaceId}, as well making it a required\n     * field.\n     */\n    uuid: SpaceId;\n    /**\n     * if not given, defaults to \"user\" by convention.\n     * @see {@link SpaceType}\n     */\n    type?: SpaceType;\n    /**\n     * should be required if {@link type} is set (truthy).\n     * @see {@link SpaceSubtype}\n     */\n    subtype?: SpaceSubtype | undefined;\n    /**\n     * If true, when this space receives a command that includes incoming ibGibs\n     * and ibGibAddrs, we will ensure the ibGibs have a 1-to-1 correspondence to\n     * the addrs we're logging, and that the gib hashes are verified against the\n     * ibGibs themselves.\n     *\n     * Otherwise, someone could pass in a bunch of legitimate addresses and\n     * illegitimate ibGibs (that have little to do with the addresses). This\n     * could at best be a coding mistake & at worst be malicious.\n     */\n    validateIbGibAddrsMatchIbGibs?: boolean;\n    /**\n     * interval between polling calls made to other spaces, e.g. sync spaces,\n     * or used within a space to check inside itself for updates.\n     *\n     * ## notes\n     *\n     * * use as needed\n     * * I want to just have this as a sync space setting, but since they are\n     *   enciphered, I don't want to just have them sitting around in plaintext.\n     *   * So I'm going to have it in the local app space, which the ibgibs\n     *     service will check in order for it to decide on interval.\n     *   * definitely a code smell, but I'm still resolving what a local app\n     *     space is vs the service that accesses it.\n     */\n    longPollingIntervalMs?: number;\n}\n\n/**\n * Specifically for ibgib spaces that are implemented via a path/subpath\n * strategy, i.e., using a filesystem-like addressing mechanism.\n */\nexport interface IbGibSpaceData_Subpathed extends IbGibSpaceData {\n    /**\n     * Redeclared here to make this required (not optional)\n     */\n    uuid: SpaceId;\n    baseDir: string | any;\n    encoding: string | any;\n    /**\n     * this is to help mitigate against too long path limits\n     */\n    mitigateLongPaths?: boolean;\n    /**\n     * if mitigating against long path lengths, this is the deciding split.\n     *\n     * so if the longPathLength is 250, and a full path would be 250, then\n     * that is now a long path. 249 would be a short path and would not need\n     * mitigation.\n     */\n    longPathLength?: number;\n    baseSubPath: string;\n    spaceSubPath: string;\n    /**\n     * if a filepath is too long, things get stuffed in here\n     *\n     * this is to help mitigate against too long path limits\n     */\n    longSubPath?: string;\n    ibgibsSubPath: string;\n    metaSubPath: string;\n    binSubPath: string;\n    dnaSubPath: string;\n    n?: number;\n    timestamp?: string;\n}\n\nexport interface IbGibSpaceRel8ns extends IbGibRel8ns_V1 {\n    [ENCRYPTION_REL8N_NAME]?: IbGibAddr[];\n}\n\n\n/**\n * Cmds for interacting with ibgib spaces.\n *\n * Not all of these will be implemented for every space.\n *\n * ## todo\n *\n * change these commands to better structure, e.g., verb/do/mod, can/get/addrs\n * */\nexport type IbGibSpaceOptionsCmd =\n    'get' | 'put' | 'delete';\n/** Cmds for interacting with ibgib spaces.  */\nexport const IbGibSpaceOptionsCmd = {\n    /** Retrieve ibGib(s) out of the space (does not remove them). */\n    get: 'get' as IbGibSpaceOptionsCmd,\n    /** Registers/imports ibGib(s) into the space. */\n    put: 'put' as IbGibSpaceOptionsCmd,\n    /** Delete an ibGib from a space */\n    delete: 'delete' as IbGibSpaceOptionsCmd,\n}\n\n/**\n * Flags to affect the command's interpretation.\n */\nexport type IbGibSpaceOptionsCmdModifier =\n    'can' | 'addrs' | 'latest' | 'watch' | 'unwatch' | 'tjps' | 'dependency-graph';\n/**\n * Flags to affect the command's interpretation.\n */\nexport const IbGibSpaceOptionsCmdModifier = {\n    /**\n     * Only interested if possibility to do command.\n     *\n     * This can be due to authorization or other.\n     */\n    can: 'can' as IbGibSpaceOptionsCmdModifier,\n    /**\n     * Only return the addresses of ibgibs\n     */\n    addrs: 'addrs' as IbGibSpaceOptionsCmdModifier,\n    /**\n     * Only interested in the latest one(s).\n     *\n     * The incoming addr(s) should be the tjp(s), since \"latest\"\n     * only makes sense with unique timelines which are referenced by\n     * their tjps.\n     *\n     * ## notes\n     *\n     * ATOW I'm actually using this in the aws dynamodb ibgib space to\n     * get \"newer\" ibgibs, not just the latest.\n     */\n    latest: 'latest' as IbGibSpaceOptionsCmdModifier,\n    /**\n     * Ask to get updates on tjps in ibGibAddrs.\n     */\n    watch: 'watch' as IbGibSpaceOptionsCmdModifier,\n    /*\n     * Ask to stop getting updates on tjps in ibGibAddrs.\n     */\n    unwatch: 'unwatch' as IbGibSpaceOptionsCmdModifier,\n    /**\n     * Get the tjp ibgibs/addrs for given ibgib(s)\n     */\n    tjps: 'tjps' as IbGibSpaceOptionsCmdModifier,\n    /**\n     * Modifies the get command to retrieve a dependency graph.\n     */\n    dependencyGraph: 'dependency-graph' as IbGibSpaceOptionsCmdModifier,\n}\n\n/** Information for interacting with spaces. */\nexport interface IbGibSpaceOptionsData\n    extends WitnessCmdData<IbGibSpaceOptionsCmd, IbGibSpaceOptionsCmdModifier> {\n    /**\n     * If putting, this will force replacing the file.\n     *\n     * ## intent\n     * atow this is just for `put` commands.\n     */\n    force?: boolean;\n    /**\n     */\n    catchAllErrors?: boolean;\n    /**\n     */\n    trace?: boolean;\n}\n\nexport interface IbGibSpaceOptionsRel8ns extends WitnessCmdRel8ns {\n}\n\nexport interface IbGibSpaceOptionsIbGib<\n    TIbGib extends IbGib = IbGib_V1,\n    TOptsData extends IbGibSpaceOptionsData = IbGibSpaceOptionsData,\n    // TOptsRel8ns extends IbGibSpaceOptionsRel8ns = IbGibSpaceOptionsRel8ns\n    TOptsRel8ns extends IbGibSpaceOptionsRel8ns = IbGibSpaceOptionsRel8ns,\n> extends WitnessCmdIbGib<TIbGib, IbGibSpaceOptionsCmd, IbGibSpaceOptionsCmdModifier, TOptsData, TOptsRel8ns> {\n}\n\n/**\n * Shape of result data common to all (most) space interactions.\n *\n * This is in addition of course to {@link WitnessResultData}.\n */\nexport interface IbGibSpaceResultData extends WitnessResultData {\n    /**\n     * If the `cmd` is `canGet` or `canPut`, this holds the result that indicates\n     * if you can or can't.\n     */\n    can?: boolean;\n    /**\n     * Addresses not found in a get.\n     */\n    addrsNotFound?: IbGibAddr[];\n    /**\n     * Addresses that are already in the space when requesting `put` or `canPut`.\n     */\n    addrsAlreadyHave?: IbGibAddr[];\n    /**\n     * Result map used when\n     *\n     * Mapping of incoming ibGibAddr -> latestAddr | null\n     *\n     * If there is a tjp/timeline -> maps to the latest in the store.\n     * If there is no tjp -> maps to the incoming addr.\n     * If the incoming addr is not found in the store -> maps to null.\n     */\n    latestAddrsMap?: { [addr: string]: IbGibAddr | null }\n    /**\n     * Map of TjpAddr -> newer LatestIbGibAddr notification.\n     *\n     * ## about\n     *\n     * When using the `watch` command modifier, a caller can subscribe to\n     * updates/notifications to a timeline. When an update occurs in the space\n     * via a `put` cmd that ends up creating/storing a newer ibgib address than\n     * the one the receiving space knows the caller is aware of, it will try to\n     * make the caller aware of the update.\n     *\n     * There are two ways to do this:\n     * 1. Store the notification info locally until the next interaction between\n     *    the space and the caller.\n     * 2. Send the notification actively to the caller.\n     *\n     * For the first implementation of notifications, only the first will be\n     * implemented. Local notifications will be implemented, but active\n     * internodal notification in the general sense will be implemented at a\n     * later time.\n     *\n     * ## notes\n     *\n     * * may also implement a dedicated command to watch subscriptions.\n     */\n    watchTjpUpdateMap?: { [tjpAddr: string]: IbGibAddr; }\n}\n\nexport interface IbGibSpaceResultRel8ns extends WitnessResultRel8ns { }\n\nexport interface IbGibSpaceResultIbGib<\n    TIbGib extends IbGib,\n    TResultData extends IbGibSpaceResultData,\n    TResultRel8ns extends IbGibSpaceResultRel8ns\n>\n    extends WitnessResultIbGib<TIbGib, TResultData, TResultRel8ns> {\n}\n\n/**\n* Data space adapter/provider, such that a space should only have one type of...\n*   * ibGib shape\n*   * witness arg shape (which brings in external ibGibs)\n*   * witness result shape\n*\n* So this interface facilitates that belief.\n*/\nexport interface IbGibSpace<\n    TIbGib extends IbGib,\n    TOptionsData extends IbGibSpaceOptionsData,\n    TOptionsRel8ns extends IbGibSpaceOptionsRel8ns,\n    TOptionsIbGib extends IbGibSpaceOptionsIbGib<TIbGib, TOptionsData, TOptionsRel8ns>,\n    TResultData extends IbGibSpaceResultData,\n    TResultRel8ns extends IbGibSpaceResultRel8ns,\n    TResultIbGib extends IbGibSpaceResultIbGib<TIbGib, TResultData, TResultRel8ns>,\n    TData extends IbGibSpaceData = IbGibSpaceData,\n    TRel8ns extends IbGibSpaceRel8ns = IbGibRel8ns,\n>\n    extends Witness<TOptionsIbGib, TResultIbGib, TData, TRel8ns> {\n    witness(arg: TOptionsIbGib): Promise<TResultIbGib | undefined>;\n}\n\nexport type SpaceLockAction = 'lock' | 'unlock';\nexport type SpaceLockScope = 'all' | TjpIbGibAddr;\n\n/**\n * Data shape for {@link IbGibSpaceLockIbGib}.\n *\n * This includes the options passed in and contains any result data of the lock\n * as well.\n */\nexport interface IbGibSpaceLockData {\n    /**\n     * In-memory unique identifier associated with the lock.\n     *\n     * ## intent\n     *\n     * I intend this mainly as a device for differentiating among multiple\n     * tabs open on the same browser. These share the same IndexedDB instance\n     * (and thus the same space bucket), but they have different caching\n     * mechanisms and interfaces to this bucket.\n     */\n    instanceId?: string;\n    /**\n     * self-explanatory\n     */\n    // action?: SpaceLockAction;\n    /**\n     * When setting the lock, this was the maximum amount of time the lock is\n     * valid.\n     *\n     * {@link expirationUTC}\n     */\n    secondsValid?: number;\n    /**\n     * When setting the lock, this was the calculated expiration string based on\n     * {@link secondsValid}.\n     *\n     * If the lock is not manually released, this will determine if the lock is\n     * adhered to.\n     */\n    expirationUTC?: string;\n    /**\n     * The scope to which the lock applies.\n     */\n    scope: SpaceLockScope;\n    /**\n     * True if space was already locked.\n     */\n    alreadyLocked?: boolean;\n    /**\n     * True if caller's request to lock the space was executed.\n     */\n    success?: boolean;\n    /**\n     * If errored, this is the message.\n     */\n    errorMsg?: string;\n}\n\n/**\n * Options for the function that locks a space.\n\n * {@link IbGibSpaceLockData}\n * {@link IbGibSpaceLockIbGib}\n */\nexport interface IbGibSpaceLockOptions extends IbGibSpaceLockData {\n    /**\n     * the space to lock/unlock\n     */\n    space: IbGibSpaceAny;\n}\n\n/**\n * Rel8ns shape for {@link IbGibSpaceLockIbGib}\n *\n * marker interface atm\n */\nexport interface IbGibSpaceLockRel8ns extends IbGibRel8ns_V1 { }\n\n/**\n * When locking a space, this is the ibGib that contains informatino regarding\n * the process. This includes if the lock was successful, how long the lock is\n * good for, etc.\n *\n * ## notes\n *\n * * This is meant to be completely ephemeral and there will be no gib. There\n *   may be many calls to lock/release in tight loops and atow it wouldn't seem\n *   provide us with much benefit to store this kind of metadata.\n */\nexport interface IbGibSpaceLockIbGib\n    extends IbGib_V1<IbGibSpaceLockData, IbGibSpaceLockRel8ns> {\n\n}\n\n/**\n * Marker type to indicate that a string is meant to be a transmission id.\n */\nexport type TxId = 'string';\n\n/**\n * we have a getDependencyGraph wrapper in the space base. This is the type of\n * that's result data.\n */\nexport interface GetDependencyGraphResultData extends IbGibSpaceResultData {\n    count: number;\n}", "import { UUID_REGEXP } from '@ibgib/helper-gib/dist/constants.mjs';\nimport { getRegExp, } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';\n\nimport { DynamicForm, FormItemInfo } from './form-items.mjs';\nimport { GLOBAL_LOG_A_LOT, SAFE_SPECIAL_CHARS } from '../../core-constants.mjs';\n\nconst logalot = GLOBAL_LOG_A_LOT || false;\n\n/**\n * Fluent-style builder helper class.\n *\n * I'm making this to share common fields' settings among witness classes.\n *\n * Descend from this class for sharing other commonalities.\n */\nexport class DynamicFormBuilder {\n    protected lc: string = `[${DynamicFormBuilder.name}]`;\n\n    protected items: FormItemInfo[] = [];\n    protected what: string = '';\n    /**\n     * pool of uuids pre-calculated to be passed in to the builder. if this is\n     * falsy, then it will use a Math.random() based approach.\n     */\n    protected idPool: string[] = [];\n\n    /**\n     * hacky wrapper for this.idPool.pop()\n     */\n    protected getNewId(): string {\n        const lc = `${this.lc}[${this.getNewId.name}]`;\n        if (this.idPool?.length > 0) {\n            return this.idPool.pop() ?? '';\n        } else {\n            // weak implementation...\n            let resultArray: string[] = [];\n            const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';\n            const charLength = chars.length;\n            for (let i = 0; i < 32; i++) {\n                let charIndex = Math.floor(Math.random() * charLength);\n                resultArray.push(chars[charIndex]);\n            }\n            let id = resultArray.join('');\n            if (logalot) { console.log(`${lc} id: ${id} (I: c6591ffee6d5bbea79ed19cfa6630422)`); }\n            return id;\n        }\n    }\n\n    /**\n     * Start fluent calls with this.\n     */\n    forA({\n        what,\n    }: {\n        /**\n         * Common name for the reified concrete type of the witness.\n         *\n         * Used in things like placeholders, descriptions, etc.\n         *\n         * @example \"robbot\" or \"space\"\n         */\n        what: string,\n    }): DynamicFormBuilder {\n        this.what = what || 'thingy';\n        return this;\n    }\n\n    protected addItem(item: FormItemInfo) {\n        if (!item.uuid) { item.uuid = this.getNewId(); }\n        this.items.push(item);\n    }\n\n    /**\n     * Empty function simply for more natural looking fluent syntax.\n     *\n     * You can override this for custom form builders that descend from this\n     * class.\n     *\n     * @returns this\n     */\n    with<T extends DynamicFormBuilder>({\n        idPool,\n    }: {\n        /**\n         * pre-built pool of uuids to draw from. this builder\n         * will mutate this array.\n         */\n        idPool?: string[],\n    }): T {\n        if (idPool) { this.idPool = idPool; }\n        return this as any as T;\n    }\n\n    /**\n     * I'm not a great fluent builder writer for TypeScript,\n     * and this function acts as a caster for which members of\n     * which concrete classes to expose for the proceeding builder lines.\n     *\n     *\n     * Basically, you use this to typecast the builder, possibly redundantly since\n     * I don't have any ordering implemented atow.\n     *\n     * @returns typecasted fluent builder\n     */\n    and<T extends DynamicFormBuilder>(): T { return this as any as T; }\n\n    name<T extends DynamicFormBuilder>({\n        of: value,\n        required = true,\n        defaultValue,\n    }: {\n        of: string,\n        required?: boolean,\n        defaultValue?: string,\n    }): T {\n        this.addItem({\n            // witness.data.name\n            name: \"name\",\n            description: `What to call this ${this.what}. Doesn't have to be unique, no spaces, up to 32 alphanumerics/underscores in length.`,\n            label: \"Name\",\n            placeholder: `e.g. \"bob_the_cool\"`,\n            regexp: getRegExp({ min: 1, max: 32, noSpaces: true }),\n            regexpErrorMsg: '1 to 32 characters, no spaces, underscores allowed.',\n            required,\n            dataType: 'text',\n            value,\n            defaultValue,\n        });\n        return this as any as T;\n    }\n\n    description({\n        of: value,\n        required,\n        defaultValue,\n    }: {\n        of: string,\n        required?: boolean,\n        defaultValue?: string,\n    }): DynamicFormBuilder {\n        this.addItem({\n            // witness.data.description\n            name: \"description\",\n            description: `Description/notes for this ${this.what}.`,\n            label: \"Description\",\n            placeholder: `Describe these ${this.what} settings here...`,\n            regexp: getRegExp({ min: 0, max: 155, chars: SAFE_SPECIAL_CHARS }),\n            regexpErrorMsg: `0 to 155 alphanumerics or any of ${SAFE_SPECIAL_CHARS}`,\n            // regexpSource: getRegExp({min: 0, max: 155, chars: SAFE_SPECIAL_CHARS}).source,\n            dataType: 'textarea',\n            required,\n            value,\n            defaultValue,\n        });\n        return this;\n    }\n\n    classname({\n        of,\n        required = true,\n    }: {\n        of: string,\n        required?: boolean,\n    }): DynamicFormBuilder {\n        this.addItem({\n            // witness.data.classname\n            name: \"classname\",\n            description: `Technical setting that is the name of the ${this.what}'s class in computer code.`,\n            label: \"Classname\",\n            regexp: getRegExp({ min: 1, max: 128, noSpaces: true }),\n            regexpErrorMsg: `1 to 128 alphanumerics or underscores without spaces`,\n            // regexpSource: getRegExp({min: 1, max: 128, noSpaces: true}).source,\n            dataType: 'text',\n            value: of,\n            readonly: true,\n            required,\n        });\n        return this;\n    }\n\n    uuid({\n        of,\n        label,\n        required,\n    }: {\n        of: string,\n        label?: string,\n        required?: boolean,\n    }): DynamicFormBuilder {\n        this.addItem({\n            // witness.data.uuid\n            name: \"uuid\",\n            description: `Unique(ish) id of the ${this.what}.`,\n            label: label ?? \"ID\",\n            dataType: 'text',\n            value: of,\n            regexp: UUID_REGEXP,\n            regexpErrorMsg: '1 to 256 alphanumerics, underscores, dots, hyphens allowed.',\n            readonly: true,\n            required,\n        });\n        return this;\n    }\n\n    version({\n        of,\n        required,\n    }: {\n        of: string | undefined,\n        required?: boolean,\n    }): DynamicFormBuilder {\n        this.addItem({\n            // witness.data.version\n            name: \"version\",\n            description: `Technical setting indicating the version of the ${this.what}.`,\n            label: \"Version\",\n            dataType: 'text',\n            value: of || '',\n            readonly: true,\n            required,\n        });\n        return this;\n    }\n\n    /**\n     * To pass in a completely customized item info.\n     *\n     * @returns `this` for fluent builder\n     */\n    customItem(item: FormItemInfo): DynamicFormBuilder {\n        this.addItem(item);\n        return this;\n    }\n\n\n    outputItems(): FormItemInfo[] {\n        return this.items;\n    }\n\n    outputForm({\n        formName,\n        label,\n    }: {\n        formName: string,\n        label?: string,\n    }): DynamicForm {\n        return {\n            name: formName,\n            // description: this.description ?? `This is a form for a ${this.what}`,\n            description: `This is a form for a ${this.what}`,\n            label: label ?? this.what,\n            items: this.items,\n        } as DynamicForm;\n    }\n}\n", "import { GLOBAL_LOG_A_LOT } from '../core-constants.mjs';\nimport { DynamicFormBuilder } from '../common/form/form-helper.mjs';\nimport { WitnessData_V1 } from '../witness/witness-types.mjs';\n\nconst logalot = GLOBAL_LOG_A_LOT || false;\n\n/**\n * Fluent-style builder helper class.\n *\n * I'm making this to share common fields' settings among witness classes.\n *\n * Descend from this class for sharing other commonalities.\n */\nexport class WitnessFormBuilder extends DynamicFormBuilder {\n    protected lc: string = `[${WitnessFormBuilder.name}]`;\n\n    allowPrimitiveArgs({\n        of,\n        required = true,\n    }: {\n        of: boolean | undefined,\n        required?: boolean,\n    }): WitnessFormBuilder {\n        this.addItem({\n            // witness.data.allowPrimitiveArgs\n            name: \"allowPrimitiveArgs\",\n            description: `Technical setting on if this ${this.what} accepts primitive incoming ibgibs`,\n            label: \"Allow Primitive Args\",\n            dataType: 'toggle',\n            value: of ?? true,\n            readonly: true,\n            required,\n        });\n        return this;\n    }\n\n    catchAllErrors({\n        of,\n        required = true,\n    }: {\n        of: boolean | undefined,\n        required?: boolean,\n    }): WitnessFormBuilder {\n        this.addItem({\n            // witness.data.catchAllErrors\n            name: \"catchAllErrors\",\n            description: `Technical setting on what the ${this.what} does when it encounters an internal error.`,\n            label: \"Catch All Errors\",\n            dataType: 'toggle',\n            value: of ?? true,\n            readonly: true,\n            required,\n        });\n        return this;\n    }\n\n    persistOptsAndResultIbGibs({\n        of,\n        required = true,\n    }: {\n        of: boolean | undefined,\n        required?: boolean,\n    }): WitnessFormBuilder {\n        this.addItem({\n            // witness.data.persistOptsAndResultIbGibs\n            name: \"persistOptsAndResultIbGibs\",\n            description: `Technical setting on if the ${this.what} maintains an audit trail of all of its inputs/outputs.`,\n            label: \"Persist Opts and Result IbGibs\",\n            dataType: 'toggle',\n            value: of ?? false,\n            readonly: true,\n            required,\n        });\n        return this;\n    }\n\n    trace({\n        of,\n        required,\n    }: {\n        of: boolean | undefined,\n        required?: boolean,\n    }): WitnessFormBuilder {\n        this.addItem({\n            // witness.data.trace\n            name: \"trace\",\n            description: `Technical setting on if the ${this.what}'s activity should be traced (logged to the console).`,\n            label: \"Trace\",\n            dataType: 'toggle',\n            value: of ?? false,\n            readonly: true,\n            required,\n        });\n        return this;\n    }\n\n    /**\n     * Includes common witness fields.\n     *\n     * All common fields default to `true`, so set any you want to skip to\n     * `false`.\n     *\n     * @returns `this` for fluent builder\n     */\n    commonWitnessFields({\n        data,\n        allowPrimitiveArgs = true,\n        catchAllErrors = true,\n        persistOptsAndResultIbGibs = true,\n        trace = true,\n        version = true,\n    }: {\n        data: WitnessData_V1,\n        allowPrimitiveArgs?: boolean,\n        catchAllErrors?: boolean,\n        persistOptsAndResultIbGibs?: boolean,\n        trace?: boolean,\n        version?: boolean,\n    }): WitnessFormBuilder {\n        if (allowPrimitiveArgs) { this.allowPrimitiveArgs({ of: data.allowPrimitiveArgs }); }\n        if (catchAllErrors) { this.catchAllErrors({ of: data.catchAllErrors }); }\n        if (persistOptsAndResultIbGibs) { this.persistOptsAndResultIbGibs({ of: data.persistOptsAndResultIbGibs }); }\n        if (trace) { this.trace({ of: data.trace }); }\n        if (version) { this.version({ of: data.version }); }\n        return this;\n    }\n\n}\n", "import { getTimestampInTicks, pretty } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';\nimport { UUID_REGEXP } from '@ibgib/helper-gib/dist/constants.mjs';\nimport { Gib, Ib, } from '@ibgib/ts-gib/dist/types.mjs';\nimport { validateIbGibIntrinsically } from '@ibgib/ts-gib/dist/V1/validate-helper.mjs';\n\nimport { GLOBAL_LOG_A_LOT } from '../../core-constants.mjs';\nimport { AppData_V1, AppIbGib_V1, AppPromptResult, } from './app-types.mjs';\nimport { APP_NAME_REGEXP, APP_REL8N_NAME, } from './app-constants.mjs';\nimport { IbGibAppAny } from './app-base-v1.mjs';\nimport { IbGibSpaceAny } from '../space/space-base-v1.mjs';\nimport { WitnessFormBuilder } from '../witness-form-builder.mjs';\nimport { IbGib_V1 } from '@ibgib/ts-gib/dist/V1/index.mjs';\nimport { IbGibTimelineUpdateInfo } from '../../common/other/other-types.mjs';\nimport { persistTransformResult, registerNewIbGib, rel8ToSpecialIbGib } from '../space/space-helper.mjs';\nimport { MetaspaceService } from '../space/metaspace/metaspace-types.mjs';\n\nconst logalot = GLOBAL_LOG_A_LOT || false;\n\n\nexport function getAppResultMetadata({ app }: { app: IbGibAppAny }): string {\n    return `${app.ib} ${getTimestampInTicks()}`;\n}\n\nexport function validateCommonAppData({\n    appData,\n}: {\n    appData: AppData_V1 | undefined,\n}): string[] {\n    const lc = `[${validateCommonAppData.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting...`); }\n        if (!appData) { throw new Error(`appData required (E: 3df782b29bc4406a87e4895cfcea28ed)`); }\n        const errors: string[] = [];\n        const {\n            name, uuid, classname,\n        } =\n            appData;\n\n        if (name) {\n            if (!name.match(APP_NAME_REGEXP)) {\n                errors.push(`name must match regexp: ${APP_NAME_REGEXP}`);\n            }\n        } else {\n            errors.push(`name required.`);\n        }\n\n        if (uuid) {\n            if (!uuid.match(UUID_REGEXP)) {\n                errors.push(`uuid must match regexp: ${UUID_REGEXP}`);\n            }\n        } else {\n            errors.push(`uuid required.`);\n        }\n\n        if (classname) {\n            if (!classname.match(APP_NAME_REGEXP)) {\n                errors.push(`classname must match regexp: ${APP_NAME_REGEXP}`);\n            }\n        }\n\n        return errors;\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport function getAppIb({\n    appData,\n    classname,\n}: {\n    appData: AppData_V1,\n    classname?: string,\n}): Ib {\n    const lc = `[${getAppIb.name}]`;\n    try {\n        const validationErrors = validateCommonAppData({ appData });\n        if (validationErrors.length > 0) { throw new Error(`invalid appData: ${validationErrors} (E: 9aff04f0cfc54a5188ca8bc40764160d)`); }\n        if (classname) {\n            if (appData.classname && appData.classname !== classname) { throw new Error(`classname does not match appData.classname (E: 66f1447eef97485fba521c40980f5eb5)`); }\n        } else {\n            classname = appData.classname;\n            if (!classname) { throw new Error(`classname required (E: 5f6ffb4317044125b94f662070e1f40b)`); }\n        }\n\n        const { name, uuid } = appData;\n        return `app ${classname} ${name} ${uuid}`;\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    }\n}\n\n/**\n * Current schema is `app ${classname} ${name} ${uuid}`\n *\n * NOTE this is space-delimited\n */\nexport function getInfoFromAppIb({\n    appIb,\n}: {\n    appIb: Ib,\n}): {\n    appClassname: string,\n    appName: string,\n    appId: string,\n} {\n    const lc = `[${getInfoFromAppIb.name}]`;\n    try {\n        if (!appIb) { throw new Error(`appIb required (E: 6b065aee67e641ba9f9c6db367ebb0fb)`); }\n\n        const pieces = appIb.split(' ');\n\n        return {\n            appClassname: pieces[1],\n            appName: pieces[2],\n            appId: pieces[3],\n        };\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    }\n}\n\nexport function getAppInfoIb({\n    appData,\n    appTjpGib,\n    classname,\n}: {\n    appData: AppData_V1,\n    appTjpGib: Gib,\n    /**\n     * Not sure why i have this here, since it should always be in the appData.classname...\n     */\n    classname?: string,\n}): Ib {\n    const lc = `[${getAppIb.name}]`;\n    try {\n        const validationErrors = validateCommonAppData({ appData });\n        if (validationErrors.length > 0) { throw new Error(`invalid appData: ${validationErrors} (E: 7be1f54ce8af4e4982966b2dedb4cf6e)`); }\n        if (classname) {\n            if (appData.classname && appData.classname !== classname) { throw new Error(`classname does not match appData.classname (E: 64bd9eaef1f94be8856e18b791d4ae52)`); }\n        } else {\n            classname = appData.classname;\n            if (!classname) { throw new Error(`classname required (E: 8d194cf8fb3f4c8eb2f708e0ccfe187c)`); }\n        }\n\n        const { name, uuid } = appData;\n        return `info_app ${classname} ${name} ${uuid} ${appTjpGib ?? 0}`;\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    }\n}\n\n/**\n * Current schema is `info_app ${classname} ${name} ${uuid} ${appTjpGib ?? 0}`\n *\n * NOTE this is space-delimited\n */\nexport function getInfoFromAppInfoIb({\n    appInfoIb,\n}: {\n    appInfoIb: Ib,\n}): {\n    appClassname: string;\n    appName: string;\n    appId: string;\n    appTjpGib: Gib;\n} {\n    const lc = `[${getInfoFromAppIb.name}]`;\n    try {\n        if (!appInfoIb) { throw new Error(`appInfoIb required (E: d12756f218144d22acb14c794dd3eeef)`); }\n\n        const pieces = appInfoIb.split(' ');\n\n        if (pieces.length !== 5) { throw new Error(`invalid appInfoIb. Expected space-delimited pieces.length === 5 (E: 21bfc58e4d88c298680ea95bc6dfc622)`); }\n\n        return {\n            appClassname: pieces[1],\n            appName: pieces[2],\n            appId: pieces[3],\n            appTjpGib: pieces[4],\n        };\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    }\n}\n\n\n/**\n * Prompts the user a form to build the app.\n *\n * Once prompted, the app is:\n * 1. validated\n * 2. persisted in the given {@link space}\n * 3. registered with the space\n * 4. related to the space's special apps index\n * 5. new app is returned\n *\n * @returns newly created app ibgib (witness)\n */\nexport async function createNewApp({\n    fnPromptApp,\n    ibgibs,\n    space,\n}: {\n    /**\n     * factory function for creating/editing an app ibgib.\n     *\n     * @param space space within which we're working\n     * @param ibGib set if editing app, null if creating\n     * @returns TransformResult<IbGibAppAny> for app ibgib created/edited\n     */\n    fnPromptApp: (space: IbGibSpaceAny, ibGib: AppIbGib_V1 | null) => Promise<AppPromptResult | undefined>,\n    /**\n     * Either {@link common} or {@link ibgibs} is required\n     * @hack\n     */\n    ibgibs?: MetaspaceService,\n    /**\n     * space within which to create the app. if not provided, the\n     * defaults to the local user space via {@link common} or {@link ibgibs}.\n     */\n    space: IbGibSpaceAny,\n}): Promise<IbGibAppAny | undefined> {\n    const lc = `[${createNewApp.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting...`); }\n\n        if (!ibgibs) { throw new Error(`ibgibs all powerful service required. (E: b24e78de0d204dc78909022bee296b30)`); }\n\n        space = space ?? await ibgibs.getLocalUserSpace({ lock: true });\n\n        // prompt user to create the ibgib, passing in null because we're\n        // creating not editing.\n        let resApp = await fnPromptApp(space, /*ibGib*/ null);\n\n        if (!resApp) { throw new Error(`resApp falsy after prompt for app. (E: 2225a567abcd680a5e957e81fbb64123)`); }\n\n        /** this should be the witness class itself at this point. */\n        const newApp = (resApp.newIbGib as IbGibAppAny);\n\n        let allIbGibs: IbGib_V1[] = [];\n        allIbGibs.push(newApp);\n        resApp.intermediateIbGibs?.forEach((x: IbGib_V1) => allIbGibs.push(x));\n        resApp.dnas?.forEach((x: IbGib_V1) => allIbGibs.push(x));\n        for (let i = 0; i < allIbGibs.length; i++) {\n            const ibGib = allIbGibs[i];\n            const validationErrors = await validateIbGibIntrinsically({ ibGib });\n            if ((validationErrors ?? []).length > 0) { throw new Error(`(UNEXPECTED) invalid app ibgib created. validationErrors: ${validationErrors}. app: ${pretty(newApp.toIbGibDto())} (E: 54cfc2f6bc284ed79be91d2da5e4bd2f)`); }\n        }\n\n        await persistTransformResult({ resTransform: resApp, space });\n        const { zeroSpace, fnBroadcast, fnUpdateBootstrap } = ibgibs;\n        await registerNewIbGib({\n            ibGib: newApp,\n            space,\n            fnBroadcast: (x: IbGibTimelineUpdateInfo) => fnBroadcast(x),\n        });\n\n        await rel8ToSpecialIbGib({\n            type: \"apps\",\n            rel8nName: APP_REL8N_NAME,\n            ibGibsToRel8: [newApp],\n            space,\n            zeroSpace,\n            fnUpdateBootstrap,\n            fnBroadcast,\n        });\n        return newApp;\n    } catch (error) {\n        debugger; // before error\n        console.error(`${lc} ${error.message}`);\n        return;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport class AppFormBuilder extends WitnessFormBuilder {\n    protected lc: string = `[${AppFormBuilder.name}]`;\n\n    constructor() {\n        super();\n        this.what = 'app';\n    }\n\n    icon({\n        of,\n        required,\n        defaultValue,\n        iconsList,\n    }: {\n        of: string,\n        required?: boolean,\n        defaultValue?: string,\n        iconsList: string[],\n    }): AppFormBuilder {\n        // const exampleIonicons = IONICONS.slice(0, 4).map(x => `\"${x}\"`).join(', ');\n        const exampleIonicons = iconsList.slice(0, 4).map(x => `\"${x}\"`).join(', ');\n        this.addItem({\n            // witness.data.outputPrefix\n            name: \"icon\",\n            description: `Icon name for the app's icon in the app bar. (NOTE: Only ionicons right now, e.g. ${exampleIonicons}). See https://ionic.io/ionicons for a full list.`,\n            label: \"Icon\",\n            fnValid: (x: string | number) => { return typeof x === 'string' && iconsList.includes(x); },\n            defaultErrorMsg: `Must be a valid icon from the icons list.`,\n            dataType: 'select',\n            value: of,\n            defaultValue: defaultValue || 'beer',\n            selectOptions: [\n                ...iconsList,\n            ],\n            required,\n        });\n        return this;\n    }\n\n}\n\n// export function documentLocationIsAtWelcomePage(): boolean {\n//     return ['welcome', '/welcome', '/welcome/'].includes(document.location.pathname);\n// }\n", "import { AppData_V1, AppRel8ns_V1 } from '../app-types.mjs';\n\nexport const DEFAULT_UUID_CHAT_APP = '0';\nexport const DEFAULT_NAME_CHAT_APP = 'chat_gib';\nexport const DEFAULT_DESCRIPTION_CHAT_APP =\n    `A chat app done ibgib style, enabling infinitely nesting comments, pics and links. It's ibgibs all the way down...`;\n\n\nexport interface ChatAppData_V1 extends AppData_V1 {\n\n}\n\n\nexport interface ChatAppRel8ns_V1 extends AppRel8ns_V1 {\n\n}\n\n/**\n * Default data values for a random app.\n *\n * If you change this, please bump the version\n *\n * (but of course won't be the end of the world when this doesn't happen).\n */\nexport const DEFAULT_CHAT_APP_DATA_V1: ChatAppData_V1 = {\n    version: '1',\n    uuid: DEFAULT_UUID_CHAT_APP,\n    name: DEFAULT_NAME_CHAT_APP,\n    description: DEFAULT_DESCRIPTION_CHAT_APP,\n    // classname: ChatApp_V1.name,\n    classname: `ChatApp_V1`,\n\n    icon: 'chatbubbles',\n\n    persistOptsAndResultIbGibs: false,\n    allowPrimitiveArgs: true,\n    catchAllErrors: true,\n    trace: false,\n}\nexport const DEFAULT_CHAT_APP_REL8NS_V1: ChatAppRel8ns_V1 | undefined = undefined;\n", "import { AppData_V1, AppRel8ns_V1 } from '../app-types.mjs';\n\nexport const DEFAULT_UUID_RAW_APP = '0';\nexport const DEFAULT_NAME_RAW_APP = 'raw_gib';\nexport const DEFAULT_DESCRIPTION_RAW_APP =\n    `Explorer app for navigating raw ibgib data.`;\n\n\nexport interface RawAppData_V1 extends AppData_V1 {\n\n}\n\nexport interface RawAppRel8ns_V1 extends AppRel8ns_V1 {\n\n}\n\n/**\n * Default data values for a random app.\n *\n * If you change this, please bump the version\n *\n * (but of course won't be the end of the world when this doesn't happen).\n */\nexport const DEFAULT_RAW_APP_DATA_V1: RawAppData_V1 = {\n    version: '1',\n    uuid: DEFAULT_UUID_RAW_APP,\n    name: DEFAULT_NAME_RAW_APP,\n    description: DEFAULT_DESCRIPTION_RAW_APP,\n    // classname: RawApp_V1.name,\n    classname: `RawApp_V1`,\n\n    icon: 'paper-plane',\n\n    persistOptsAndResultIbGibs: false,\n    allowPrimitiveArgs: true,\n    catchAllErrors: true,\n    trace: false,\n}\n\nexport const DEFAULT_RAW_APP_REL8NS_V1: RawAppRel8ns_V1 | undefined = undefined;\n", "import { Gib } from '@ibgib/ts-gib/dist/types.mjs';\nimport { IbGibData_V1, IbGibRel8ns_V1, IbGib_V1 } from '@ibgib/ts-gib/dist/V1/index.mjs';\n\nimport { AppData_V1, AppRel8ns_V1 } from '../app-types.mjs';\n\nexport const DEFAULT_UUID_TODO_APP = '0';\nexport const DEFAULT_NAME_TODO_APP = 'todo_gib';\nexport const DEFAULT_DESCRIPTION_TODO_APP =\n    `Todo app for viewing and interacting with ibgibs like they're checklists.`;\n\n\nexport interface TodoAppData_V1 extends AppData_V1 {\n\n}\n\nexport interface TodoAppRel8ns_V1 extends AppRel8ns_V1 {\n\n}\n\n/**\n * Default data values for a random app.\n *\n * If you change this, please bump the version\n *\n * (but of course won't be the end of the world when this doesn't happen).\n */\nexport const DEFAULT_TODO_APP_DATA_V1: TodoAppData_V1 = {\n    version: '1',\n    uuid: DEFAULT_UUID_TODO_APP,\n    name: DEFAULT_NAME_TODO_APP,\n    description: DEFAULT_DESCRIPTION_TODO_APP,\n    // classname: TodoApp_V1.name,\n    classname: `TodoApp_V1`,\n\n    icon: 'checkbox',\n\n    persistOptsAndResultIbGibs: false,\n    allowPrimitiveArgs: true,\n    catchAllErrors: true,\n    trace: false,\n}\nexport const DEFAULT_TODO_APP_REL8NS_V1: TodoAppRel8ns_V1 | undefined = undefined;\n\n/**\n * when an ibgib has children that are checked/unchecked using\n * the (a?) todo app, this is the rel8n name to the info.\n */\nexport const TODO_INFO_REL8N_NAME = 'todo';\nexport const TODO_INFO_IB = 'todo_info';\n\n\nexport interface TodoInfoData_V1 extends IbGibData_V1 {\n    tjpGibsDone: Gib[];\n}\n\nexport interface TodoInfoRel8ns_V1 extends IbGibRel8ns_V1 {\n}\n\nexport interface TodoInfoIbGib_V1 extends IbGib_V1<TodoInfoData_V1, TodoInfoRel8ns_V1> { }\n", "import { IbGib_V1 } from \"@ibgib/ts-gib/dist/V1/index.mjs\";\nimport { getIbGibAddr } from \"@ibgib/ts-gib/dist/helper.mjs\";\nimport { validateIbGibIntrinsically } from \"@ibgib/ts-gib/dist/V1/validate-helper.mjs\";\n\nimport { BOOTSTRAP_DATA_DEFAULT_SPACE_ID_KEY, BOOTSTRAP_IBGIB_ADDR } from \"./bootstrap-constants.mjs\";\nimport { BootstrapData, BootstrapRel8ns } from \"./bootstrap-types.mjs\";\n\nexport async function validateBootstrapIbGib(bootstrapSpace: IbGib_V1): Promise<boolean> {\n    const lc = `[${validateBootstrapIbGib.name}]`;\n    const errors: string[] = [];\n    try {\n        const addr = getIbGibAddr({ ibGib: bootstrapSpace });\n        if (addr !== BOOTSTRAP_IBGIB_ADDR) {\n            errors.push(`invalid bootstrapSpace addr. Should equal \"${BOOTSTRAP_IBGIB_ADDR}\" (E: ecfdbed719284db7a1aa3f867f706fe9)`);\n        }\n        let intrinsicErrors = await validateIbGibIntrinsically({ ibGib: bootstrapSpace });\n        if (intrinsicErrors?.length ?? -1 > 0) { intrinsicErrors!.forEach(e => errors.push(e)); }\n\n        const data = (bootstrapSpace.data as BootstrapData);\n        const rel8ns = (bootstrapSpace.rel8ns as BootstrapRel8ns);\n\n        if (Object.keys(data || {}).length === 0) {\n            errors.push(`invalid bootstrapSpace data. data required (E: 5a9bd15dd0644f9b93cafbbba660cfdf)`);\n        }\n        if ((data.spaceIds ?? []).length === 0) {\n            errors.push(`invalid bootstrapSpace, data.spaceIds required. (E: 6b91ddc12cfd41e59ded7d7502c1909f)`);\n        }\n        if (Object.keys(bootstrapSpace.rel8ns || {}).length === 0) {\n            errors.push(`invalid bootstrapSpace rel8ns (empty). Should have at least one rel8n, with rel8nName corresponding to the spaceId (E: b188ce4ae25e49f794f35e141bc2ecde)`);\n        }\n        data.spaceIds.forEach((spaceId: string) => {\n            if ((rel8ns[spaceId] ?? []).length === 0) {\n                errors.push(`invalid bootstrap. Each spaceId listed in data should have a corresponding address in rel8ns. spaceId (${spaceId}) missing. (E: 62dd0d76e29a415a98b4b27deb8db17e)`);\n            }\n        });\n        if (!data[BOOTSTRAP_DATA_DEFAULT_SPACE_ID_KEY]) {\n            errors.push(`invalid bootstrap. data.${BOOTSTRAP_DATA_DEFAULT_SPACE_ID_KEY} required. (E: f763af2e275f445cbf1db5801bacafad)`);\n        } else if ((rel8ns[data[BOOTSTRAP_DATA_DEFAULT_SPACE_ID_KEY]] ?? []).length === 0) {\n            errors.push(`invalid bootstrap. data.${BOOTSTRAP_DATA_DEFAULT_SPACE_ID_KEY} (${data[BOOTSTRAP_DATA_DEFAULT_SPACE_ID_KEY]}) not found in rel8ns. (E: 44d0799d232f4a51a0b0019ebebe019f)`);\n        }\n        if (errors.length === 0) {\n            return true;\n        } else {\n            console.error(`${lc} errors: ${errors.join('|')}`);\n            return false;\n        }\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        return false;\n    }\n}\n", "/**\n * @module meta-stone constants\n *\n * constants are in this file!\n */\n\n// /**\n//  * example enum-like type+const that I use in ibgib. sometimes i put\n//  * these in the types.mts and sometimes in the const.mts, depending\n//  * on context.\n//  */\n// export type SomeEnum =\n//     'ib' | 'gib';\n// export const SomeEnum = {\n//     ib: 'ib' as SomeEnum,\n//     gib: 'gib' as SomeEnum,\n// } satisfies { [key: string]: SomeEnum };\n// export const SOME_TYPE_VALUES: SomeEnum[] = Object.values(SomeEnum);\n\n/**\n * atom used in ibs\n *\n * atow (11/2023) this should also be (as with most atoms) the ib of the parent\n * primitive ibgib used when creating a new ibgib (forking a primitive ibgib\n * with this ib).\n */\nexport const META_STONE_ATOM = 'meta_stone';\n\n/**\n * default regexp for a simple name string.\n */\nexport const META_STONE_NAME_REGEXP = /^[a-zA-Z0-9_\\-.]{1,255}$/;\n\n/**\n * for use when creating a metastone targeting an ibgib without a tjp (i.e. a\n * stone ibgib itself).\n */\nexport const DEFAULT_META_STONE_TJPGIB = 'undefined';\n/**\n * for use when targetIbGib.data.n is falsy or NaN\n */\nexport const DEFAULT_META_STONE_N = -1;\n/**\n * for use when targetIbGib.data.timestamp is falsy\n */\nexport const DEFAULT_META_STONE_TIMESTAMP = 'undefined';\n\n/**\n * rel8n name pointing from the metastone to its target ibgib.\n */\nexport const META_STONE_TARGET_REL8N_NAME = 'target';\n/**\n * rel8n name pointing from the metastone to the target's temporal junction\n * point.\n */\nexport const META_STONE_TARGET_TJP_REL8N_NAME = 'targetTjp';\n", "/**\n * @module meta-stone helper/util/etc. functions\n *\n * this is where you will find helper functions like those that generate\n * and parse ibs for meta-stone.\n */\n\n// import * as pathUtils from 'path';\n// import { statSync } from 'node:fs';\n// import { readFile, } from 'node:fs/promises';\n// import * as readline from 'node:readline/promises';\n// import { stdin, stdout } from 'node:process'; // decide if use this or not\n\nimport {\n    extractErrorMsg, getTimestamp, getTimestampInTicks,\n} from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';\nimport { Ib, IbGibAddr, } from '@ibgib/ts-gib/dist/types.mjs';\nimport {\n    validateGib, validateIbGibAddr, validateIbGibIntrinsically,\n    validateRel8nsIntrinsically\n} from '@ibgib/ts-gib/dist/V1/validate-helper.mjs';\nimport { IbGib_V1 } from '@ibgib/ts-gib/dist/V1/types.mjs';\nimport { getIbAndGib, getIbGibAddr } from '@ibgib/ts-gib/dist/helper.mjs';\nimport { getGibInfo } from '@ibgib/ts-gib/dist/V1/transforms/transform-helper.mjs';\nimport { GIB } from '@ibgib/ts-gib/dist/V1/constants.mjs';\n\nimport { GLOBAL_LOG_A_LOT } from '../../core-constants.mjs';\nimport {\n    MetaStoneData_V1, MetaStoneRel8ns_V1, MetaStoneIbGib_V1, MetaStoneIbInfo,\n} from './meta-stone-types.mjs';\nimport {\n    DEFAULT_META_STONE_N, DEFAULT_META_STONE_TIMESTAMP,\n    DEFAULT_META_STONE_TJPGIB, META_STONE_ATOM, META_STONE_TARGET_REL8N_NAME,\n    META_STONE_TARGET_TJP_REL8N_NAME,\n} from './meta-stone-constants.mjs';\nimport { constantIbGib, getTimestampInfo, getTjpAddr, isBinary } from '../other/ibgib-helper.mjs';\n\n/**\n * for verbose logging\n */\nconst logalot = GLOBAL_LOG_A_LOT;\n\nexport function validateCommonMetaStoneIb({\n    ib,\n}: {\n    ib: Ib,\n}): string[] {\n    const lc = `[${validateCommonMetaStoneIb.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting...`); }\n\n        const errors: string[] = [];\n\n        const pieces = ib.split(' ');\n\n        // atom\n        const atom = pieces[0];\n        if (atom !== META_STONE_ATOM) {\n            errors.push(`${lc} invalid ib. atom is expected to be META_STONE_ATOM: ${META_STONE_ATOM} (E: a9812bffc18f44418aa091fb0ed260bd)`)\n        }\n\n        // validate tjpGib\n        const tjpGib = pieces[1];\n        const tjpGibValidationErrors = validateGib({ gib: tjpGib }) ?? [];\n        if (tjpGibValidationErrors.length > 0) {\n            errors.push(`invalid ib. pieces[1] should be a valid tjpGib. validation errors: ${tjpGibValidationErrors} (E: 233db2babfbe4d28a80f98261f1c0e01)`);\n        }\n\n        // n\n        const nAsString = pieces[2];\n        const parsedN = Number.parseInt(nAsString);\n        if (isNaN(parsedN)) { errors.push(`invalid ib. space-delimited pieces[2] should be valid integer (E: 71df0d6abd7b4cf4b11621e6bfb556cd)`); }\n\n        // timestampInTicks\n        const timestampInTicks = pieces[3];\n        if (timestampInTicks === 'undefined') {\n            // this happens when it's a binary ibgib or just doesn't have a timestamp in the data map\n        } else {\n            const timestampInfo = getTimestampInfo({ timestamp: timestampInTicks });\n            if (!timestampInfo.valid) {\n                errors.push(`invalid ib. pieces[3] should be valid timestampInTicks. emsg: (${timestampInfo.emsg}) (E: 06dae01d66f54f54b71d9c920c730840)`);\n            }\n        }\n\n        return errors;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport function validateCommonMetaStoneData({\n    data,\n}: {\n    data?: MetaStoneData_V1,\n}): string[] {\n    const lc = `[${validateCommonMetaStoneData.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting...`); }\n        if (!data) { throw new Error(`data required (E: c50ac422af4501b72af12481fbd4961e)`); }\n        const errors: string[] = [];\n\n        // we need to be careful here. we have two different \"data\" objects: 1)\n        // the metastone's data, and 2) the metastone's targetData.\n\n        // first validate 1) the metastone's data itself (barring the\n        // targetData)\n        const { targetData, timestamp } = data;\n\n        // timestamp is required\n        const timestampInfo = getTimestampInfo({ timestamp });\n        if (!timestampInfo.valid) {\n            errors.push(`invalid timestampInTicks. should be valid ticks number. (E: 7e381ed5b0c8486b90cfd37676da3626)`);\n        }\n\n        const {\n            tjpGib: targetTjpGib,\n            n: targetN,\n            timestamp: targetTimestamp,\n        } =\n            targetData;\n\n        // target tjpGib\n        if (targetTjpGib) {\n            if (targetTjpGib === 'undefined') {\n                // target had no tjpgib\n            } else {\n                const tjpGibValidationErrors = validateGib({ gib: targetTjpGib }) ?? [];\n                if (tjpGibValidationErrors.length > 0) {\n                    errors.push(`invalid data (targetTjpGib). validation errors: ${tjpGibValidationErrors} (E: d216b12eb75544ef8c5ffb27cd132e2e)`);\n                }\n            }\n        }\n\n        // target n\n        if (typeof targetN !== 'number') {\n            errors.push(`invalid n. should be valid integer. if target.data.n is falsy, targetN should be -1 (E: 8f234967b388ad80776c8054d71fbc23)`);\n        }\n\n        // target timestamp (optional)\n        if (targetTimestamp) {\n            if (targetTimestamp === 'undefined') {\n                // target had no timestamp\n            } else {\n                const targetTimestampInfo = getTimestampInfo({ timestamp: targetTimestamp });\n                if (!targetTimestampInfo.valid) {\n                    errors.push(`invalid targetTimestamp. emsg: ${targetTimestampInfo.emsg} (E: c15d4fd2a2b74a0fab3223e83d954379)`);\n                }\n            }\n\n        }\n        const timestampDate = new Date(timestamp);\n\n        return errors;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport function validateCommonMetaStoneRel8ns({\n    rel8ns,\n}: {\n    rel8ns?: MetaStoneRel8ns_V1,\n}): string[] {\n    const lc = `[${validateCommonMetaStoneRel8ns.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting...`); }\n        if (!rel8ns) { throw new Error(`rel8ns required (E: 7737ae550e2347e68c67b715c1221393)`); }\n        const errors: string[] = [];\n\n        // basic rel8ns validation\n        const intrinsicErrors = validateRel8nsIntrinsically({ rel8ns: rel8ns ?? {} }) ?? [];\n        if (intrinsicErrors.length > 0) {\n            errors.push(`invalid rel8ns intrinsically. errors: ${intrinsicErrors.join('|')}. (E: abc91753f0f946afa0a3ea2c1917960f)`);\n        }\n\n        // [META_STONE_TARGET_REL8N_NAME]: IbGibAddr[];\n        // all metastones should have exactly 1 targetAddr\n        const targetAddrs = rel8ns[META_STONE_TARGET_REL8N_NAME] ?? [];\n        if (targetAddrs.length === 0) {\n            errors.push(`invalid metastone rel8ns. should have exactly 1 rel8nName ${META_STONE_TARGET_REL8N_NAME}. has 0. (E: 8181652da9e89613e204d245db12d723)`);\n        } else if (targetAddrs.length > 1) {\n            errors.push(`invalid metastone rel8ns. should have exactly 1 rel8nName ${META_STONE_TARGET_REL8N_NAME}. has ${targetAddrs.length}. (E: 2318047c6fea482d9f53febe02cf8912)`);\n        }\n\n        // [META_STONE_TARGET_TJP_REL8N_NAME]?: IbGibAddr[];\n        // optional rel8n, should have 0 or 1\n        // if we want to get picky, we could check to make sure it is a tjpAddr\n        let targetTjpAddrs = rel8ns[META_STONE_TARGET_TJP_REL8N_NAME] ?? [];\n        if (targetTjpAddrs.length > 1) {\n            errors.push(`invalid metastone rel8ns. should have 0 or 1 rel8nName ${META_STONE_TARGET_TJP_REL8N_NAME}. has ${targetTjpAddrs.length}. (E: 34a8ae53825f46caa7ad024a64400db2)`)\n        }\n\n        return errors;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * performs validation on the ib, data and rel8ns, as well as validates the\n * ibgib intrinsically (i.e. ensures the gib hash is correct)\n * @returns errors array if any found, otherwise undefined (if no errors)\n */\nexport async function validateCommonMetaStoneIbGib({\n    ibGib,\n}: {\n    ibGib: MetaStoneIbGib_V1,\n}): Promise<string[] | undefined> {\n    const lc = `[${validateCommonMetaStoneIbGib.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: f32249d08105b997871a06cdee006311)`); }\n        const intrinsicErrors: string[] = await validateIbGibIntrinsically({ ibGib: ibGib }) ?? [];\n\n        if (!ibGib.data) { throw new Error(`MetaStoneIbGib.data required (E: 96432cf4f919d339277d9a1c61ea4264)`); }\n\n        // validate ib happens in parse...if only i had a memory...\n        const ibErrors: string[] = [];\n        try {\n            const { atom, tjpGib, n, timestampInTicks } =\n                parseMetaStoneIb({ ib: ibGib.ib });\n        } catch (error) {\n            ibErrors.push(extractErrorMsg(error));\n        }\n\n        const dataErrors = validateCommonMetaStoneData({ data: ibGib.data });\n        const rel8nsErrors = validateCommonMetaStoneRel8ns({ rel8ns: ibGib.rel8ns });\n\n        const result = [\n            ...(intrinsicErrors ?? []),\n            ...(ibErrors ?? []),\n            ...(dataErrors ?? []),\n            ...(rel8nsErrors ?? []),\n        ];\n        if (result.length > 0) {\n            return result;\n        } else {\n            return undefined;\n        }\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * validates the given `data` and builds the ib based on that data.\n *\n * _NOTE: This is **NOT** the function to use to build a metastone based a target ibgib._\n *\n * @returns ib shaped for metastone (atow 11/2023 has tjpGib,n,timestampInTicks)\n */\nexport function getMetaStoneIb({\n    data,\n    classname,\n}: {\n    data: MetaStoneData_V1,\n    classname?: string,\n}): Ib {\n    const lc = `[${getMetaStoneIb.name}]`;\n    try {\n        const validationErrors = validateCommonMetaStoneData({ data });\n        if (validationErrors.length > 0) { throw new Error(`invalid MetaStone data: ${validationErrors} (E: ac642cc5915f0fc0508cb2fb728c86fa)`); }\n        if (classname) {\n            if (logalot) { console.log(`${lc} classname not required. no big deal that it is provided here. (I: db4d41471cb976795afd3fa89f8cb823)`); }\n        }\n\n        // we need to be careful here. we have two different \"data\" objects: 1)\n        // the metastone's data, and 2) the metastone's targetData.\n\n        // these are validated in common data\n        const targetTimestamp = data.targetData.timestamp;\n        const targetTimestampInTicks = !!targetTimestamp && targetTimestamp !== 'undefined' ?\n            getTimestampInTicks(targetTimestamp) :\n            DEFAULT_META_STONE_TIMESTAMP;\n\n        return `${META_STONE_ATOM} ${data.targetData.tjpGib} ${data.targetData.n} ${targetTimestampInTicks}`;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    }\n}\n\n/**\n * Current schema is `${META_STONE_ATOM} ${data.targetData.tjpGib} ${data.targetData.n} ${targetTimestampInTicks}`;\n *\n * NOTE this ib is space-delimited\n */\nexport function parseMetaStoneIb({\n    ib,\n}: {\n    ib: Ib,\n}): MetaStoneIbInfo {\n    const lc = `[${parseMetaStoneIb.name}]`;\n    try {\n        if (!ib) { throw new Error(`MetaStone ib required (E: 8e74e098d7aeef52d3952e35150d83ed)`); }\n\n        const validationErrors = validateCommonMetaStoneIb({ ib });\n        if (validationErrors.length > 0) { throw new Error(`invalid ib. validationErrors: ${validationErrors} (E: a6107f62200eb943e523f70f51300623)`); }\n\n        const pieces = ib.split(' ');\n\n        return {\n            atom: pieces[0],\n            tjpGib: pieces[1],\n            n: Number.parseInt(pieces[2]),\n            timestampInTicks: pieces[3],\n        };\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    }\n}\n\n/**\n * metastone ibgibs are for things like helping to keep track of the latest\n * ibgib in a timeline (similar to the HEAD pointer in e.g. git).\n *\n * @returns true if `addr` is for a metastone ibgib, else false\n */\nexport function isMetaStone({\n    addr,\n    ibGib,\n}: {\n    addr?: IbGibAddr,\n    ibGib?: IbGib_V1,\n}): boolean {\n    // ignore edge case of checking if both are provided that they both should\n    // be equal.\n\n    addr ||= getIbGibAddr({ ibGib });\n    if (!addr) { throw new Error(`either addr or ibGib required. (E: 372b2574d5a9fac298119beed9f6e223)`); }\n    return addr.startsWith(`${META_STONE_ATOM} `);\n}\n\n/**\n * factory function that generates a metastone (constant) ibgib based on the\n * given `ibGib`.\n */\nexport async function newUpMetaStone({\n    targetIbGib,\n}: {\n    targetIbGib: IbGib_V1,\n}): Promise<MetaStoneIbGib_V1> {\n    const lc = `[${newUpMetaStone.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: d846313065c89c89e4b5afa2df2b7123)`); }\n\n        const targetAddr = getIbGibAddr({ ibGib: targetIbGib });\n        const targetTjpAddr = getTjpAddr({ ibGib: targetIbGib, defaultIfNone: \"incomingAddr\" })!;\n\n        let metaStoneData: MetaStoneData_V1;\n        const metaStoneRel8ns: MetaStoneRel8ns_V1 = {\n            [META_STONE_TARGET_REL8N_NAME]: [targetAddr],\n            [META_STONE_TARGET_TJP_REL8N_NAME]: [targetTjpAddr],\n        };\n\n        // const targetGibInfo = getGibInfo({ ibGibAddr: targetAddr });\n        if (!targetIbGib.gib) { throw new Error(`(UNEXPECTED) targetIbGib.gib falsy? (E: 28eaa8a799021dadd87b043711aee826)`); }\n        /**\n         * * if the targetIbGib is the tjp, then its gib is the tjpGib.\n         * * if the targetIbGib has a tjp, then gibInfo.tjpGib is what we want.\n         * * if the targetIbGib is a stone, then we pretend that it is the\n         *   tjpGib (any stone might one day be raised up & come to life)\n         */\n        const targetTjpGib = targetIbGib.data?.isTjp ?\n            targetIbGib.gib :\n            getGibInfo({ ibGibAddr: targetAddr }).tjpGib ?? targetIbGib.gib;\n\n        if (targetTjpGib === GIB) { throw new Error(`cannot create metastone for primitive ibgib (E: 2887e8ef83381a0698256b7bc7531826)`); }\n\n        const metaStoneTimestampDate = new Date();\n        /**\n         * timestamp for the metastone itself (not the target.data.timestamp)\n         */\n        const metaStoneTimestamp = getTimestamp(metaStoneTimestampDate);\n        const metaStoneTimestampMs = metaStoneTimestampDate.getMilliseconds();\n\n        if (targetIbGib.data) {\n            if (isBinary({ ibGib: targetIbGib })) {\n                // binary data is just a uint8array\n                metaStoneData = {\n                    targetData: {\n                        n: -1,\n                        tjpGib: targetTjpGib,\n                    },\n                    timestamp: metaStoneTimestamp,\n                    timestampMs: metaStoneTimestampMs,\n                };\n            } else {\n                metaStoneData = {\n                    targetData: {\n                        n: targetIbGib.data.n ?? DEFAULT_META_STONE_N,\n                        tjpGib: targetTjpGib,\n                        timestamp: targetIbGib.data.timestamp ?? DEFAULT_META_STONE_TIMESTAMP,\n                    },\n                    timestamp: metaStoneTimestamp,\n                    timestampMs: metaStoneTimestampMs,\n                }\n                if (targetIbGib.data?.isTjp) { metaStoneData.targetData.isTjp = true; }\n            }\n        } else {\n            // no target data\n            metaStoneData = {\n                targetData: {\n                    n: DEFAULT_META_STONE_N,\n                    tjpGib: targetTjpGib,\n                },\n                timestamp: metaStoneTimestamp,\n                timestampMs: metaStoneTimestampMs,\n            }\n        }\n\n        // now that we have the data, we can build the ib\n        const metaStoneIb = getMetaStoneIb({ data: metaStoneData });\n\n        // now that we have the data, rel8ns, and the ib, we can create the\n        // stone (which is a constant ibgib).\n        const metaStoneIbGib = await constantIbGib<MetaStoneData_V1, MetaStoneRel8ns_V1>({\n            parentPrimitiveIb: META_STONE_ATOM,\n            ib: metaStoneIb,\n            data: metaStoneData,\n            rel8ns: metaStoneRel8ns,\n        }) as MetaStoneIbGib_V1;\n\n        if (logalot) {\n            console.log(`${lc} metaStoneIbGib... (I: 2b16197478488b329246d22d2dc41423)`);\n            console.dir(metaStoneIbGib);\n        }\n\n        return metaStoneIbGib;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n", "export const WITNESS_ATOM = 'witness';\nexport const WITNESS_ARG_METADATA_STRING = 'witness_arg';\nexport const WITNESS_RESULT_METADATA_STRING = 'witness_result';\n\nexport const WITNESS_CONTEXT_REL8N_NAME = 'context';\n", "import {\n    clone, delay, getExpirationUTCString, getTimestampInTicks,\n    getUUID, isExpired, pretty, extractErrorMsg,\n} from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';\nimport { TransformResult, Ib, IbGibAddr, } from '@ibgib/ts-gib/dist/types.mjs';\nimport { getIbAndGib, getIbGibAddr } from '@ibgib/ts-gib/dist/helper.mjs';\nimport { GIB, IBGIB_DELIMITER } from '@ibgib/ts-gib/dist/V1/constants.mjs'\nimport { IbGib_V1, Rel8n } from '@ibgib/ts-gib/dist/V1/types.mjs';\nimport { Factory_V1 as factory } from '@ibgib/ts-gib/dist/V1/factory.mjs';\nimport { rel8 } from '@ibgib/ts-gib/dist/V1/transforms/rel8.mjs';\nimport { fork } from '@ibgib/ts-gib/dist/V1/transforms/fork.mjs';\nimport { getGib, getGibInfo, } from '@ibgib/ts-gib/dist/V1/transforms/transform-helper.mjs';\n\nimport { GLOBAL_LOG_A_LOT } from '../../core-constants.mjs';\nimport { APP_REL8N_NAME } from '../app/app-constants.mjs';\nimport {\n    GetIbGibOpts, GetIbGibResult, PutIbGibOpts, PutIbGibResult, DeleteIbGibOpts,\n    DeleteIbGibResult, SpecialIbGibType, IbGibTimelineUpdateInfo,\n} from '../../common/other/other-types.mjs';\nimport {\n    getRootIb, getSpecialConfigKey, getSpecialIbGibIb,\n    getSpecialTypeFromIb, getTjpAddr, isSpecial, isTjp_Naive, tagTextToIb\n} from '../../common/other/ibgib-helper.mjs';\nimport { TagData_V1, TagIbGib_V1 } from '../../common/tag/tag-types.mjs';\nimport { BOOTSTRAP_DATA_DEFAULT_SPACE_ID_KEY, BOOTSTRAP_DATA_KNOWN_SPACE_IDS_KEY, BOOTSTRAP_IBGIB_ADDR } from './bootstrap/bootstrap-constants.mjs';\nimport {\n    SpaceLockScope, IbGibSpaceLockIbGib, SpaceId, IbGibSpaceLockOptions, TxId,\n    IbGibSpaceResultIbGib, IbGibSpaceResultData, IbGibSpaceResultRel8ns, SpaceType, SpaceSubtype, VALID_SPACE_TYPES, VALID_SPACE_SUBTYPES, IbGibSpaceData,\n    IbGibSpaceOptionsCmd, IbGibSpaceOptionsCmdModifier,\n} from './space-types.mjs';\nimport { getAppIb, } from '../app/app-helper.mjs';\nimport { AppData_V1, AppIbGib_V1 } from '../app/app-types.mjs';\nimport { DEFAULT_CHAT_APP_DATA_V1, DEFAULT_CHAT_APP_REL8NS_V1 } from '../app/chat-app/chat-app-types.mjs';\nimport { DEFAULT_RAW_APP_DATA_V1, DEFAULT_RAW_APP_REL8NS_V1 } from '../app/raw-app/raw-app-types.mjs';\nimport { DEFAULT_TODO_APP_DATA_V1, DEFAULT_TODO_APP_REL8NS_V1, DEFAULT_UUID_TODO_APP } from '../app/todo-app/todo-app-types.mjs';\nimport { IbGibSpaceAny } from './space-base-v1.mjs';\nimport { RootData } from '../../common/root/root-types.mjs';\nimport { IbGibCacheService } from '../../common/cache/cache-types.mjs';\nimport {\n    DEFAULT_MAX_DELAY_MS_RETRY_LOCK_ACQUIRE,\n    DEFAULT_MAX_DELAY_RETRY_LOCK_ACQUIRE_ATTEMPTS, DEFAULT_SECONDS_VALID_LOCAL,\n    DEFAULT_TX_ID_LENGTH, IBGIB_SPACE_NAME_DEFAULT, SPACE_ATOM,\n    SPACE_LOCK_IB_TERM, SYNC_SPACE_REL8N_NAME,\n} from './space-constants.mjs';\nimport { DEFAULT_TAG_DESCRIPTION, DEFAULT_TAG_ICON, TAG_REL8N_NAME } from '../../common/tag/tag-constants.mjs';\nimport {\n    DEFAULT_ROOT_DESCRIPTION, DEFAULT_ROOT_ICON, DEFAULT_ROOT_REL8N_NAME,\n    DEFAULT_ROOT_TEXT, ROOT_REL8N_NAME\n} from '../../common/root/root-constants.mjs';\nimport { ARCHIVE_REL8N_NAME, TRASH_REL8N_NAME } from '../../common/other/other-constants.mjs';\nimport { validateBootstrapIbGib } from './bootstrap/bootstrap-helper.mjs';\nimport { BootstrapData, BootstrapIbGib, BootstrapRel8ns } from './bootstrap/bootstrap-types.mjs';\nimport { newUpMetaStone } from '../../common/meta-stone/meta-stone-helper.mjs';\nimport { WITNESS_ATOM } from '../witness-constants.mjs';\n\nlet logalot = GLOBAL_LOG_A_LOT;\n\n\n/**\n * Two spaces can be equivalent if they point to the same area.\n *\n * @returns true if the \"same\" space\n */\nexport function isSameSpace({\n    a,\n    b,\n    mustHaveSameData,\n}: {\n    a: IbGibSpaceAny,\n    b: IbGibSpaceAny,\n    /**\n     * If true, then only same exact internal data will do.\n     * Be careful if they have last modified timestamps.\n     */\n    mustHaveSameData?: boolean,\n}): boolean {\n    const lc = `[${isSameSpace.name}]`;\n\n    if (!a) { throw new Error(`${lc} a is falsy`) };\n    if (!b) { throw new Error(`${lc} b is falsy`) };\n\n    // try by data\n    if (a.data && JSON.stringify(a.data) === JSON.stringify(b.data)) {\n        return true;\n    } else if (mustHaveSameData) {\n        return false;\n    }\n\n    // try by uuid\n    if (a.data?.uuid && b.data?.uuid) { return a.data!.uuid === b.data!.uuid; }\n\n    // try by tjp\n    if (a.rel8ns?.tjp?.length === 1 && b.rel8ns?.tjp?.length === 1) {\n        return a.rel8ns.tjp[0] === b.rel8ns.tjp[0];\n    }\n\n    // try by gib (last resort), can't both be falsy or primitive (maybe overkill)\n    if (!a.gib && !b.gib) {\n        throw new Error(`${lc} Invalid spaces. both a.gib and b.gib are falsy, neither has uuid and neither has tjp.`);\n    }\n    if (a.gib === GIB && b.gib === GIB) { throw new Error(`${lc} both a and b are primitives`); }\n    return a.gib === b.gib;\n}\n\n/**\n * wrapper for dealing with a space.\n *\n * @returns legacy `GetIbGibResult`\n */\nexport async function getFromSpace({\n    addr,\n    addrs,\n    isDna,\n    space,\n    force,\n}: GetIbGibOpts): Promise<GetIbGibResult> {\n    let lc = `[${getFromSpace.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting...`); }\n        if (!space) { throw new Error(`space required. (E: 4d188d6c863246f28aa575753a052304)`); }\n        if (!addr && (addrs ?? []).length === 0) { throw new Error(`addr or addrs required. (E: 1a0b92564ba942f1ba91a089ac1a2125)`); }\n\n        if (addr && (addrs?.length ?? 0) > 0) {\n            console.warn(`${lc} both addr and addrs provided, but supposed to be used one or the other. (W: 87226c2ac50e4ea28211334a7b58782f)`);\n            if (!addrs!.includes(addr)) { addrs!.push(addr); }\n        }\n        addrs = (addrs ?? []).length > 0 ? addrs : [addr!];\n\n        const argGet = await space.argy({\n            ibMetadata: getSpaceArgMetadata({ space }),\n            argData: {\n                cmd: 'get',\n                ibGibAddrs: addrs,\n                isDna,\n            },\n        });\n        const result = await space.witness(argGet);\n        if (result?.data?.success) {\n            if (logalot) { console.log(`${lc} got.`) }\n            return {\n                success: true,\n                ibGibs: result.ibGibs,\n                rawResultIbGib: result,\n            }\n        } else {\n            if (logalot) { console.log(`${lc} didn't get.`) }\n            return {\n                success: false,\n                errorMsg: result.data?.errors?.join('|') || `${lc} something went wrong. addrs: ${addrs!.join('\\n')} (E: b9e9d5ce0cde4122bfb74f7688db85e0)`,\n                rawResultIbGib: result,\n            }\n        }\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        return { errorMsg: error.message, }\n    }\n}\n\n/**\n * Wrapper for saving ibgib in a given space.\n *\n * ## warnings\n *\n * The given space doesn't have to work this way.\n * This is a convenience for me ATOW.\n */\nexport async function putInSpace({\n    ibGib,\n    ibGibs,\n    isDna,\n    force,\n    space,\n}: PutIbGibOpts): Promise<PutIbGibResult> {\n    const lc = `[${putInSpace.name}]`;\n    try {\n        if (!ibGib && (ibGibs ?? []).length === 0) { throw new Error(`ibGib or ibGibs required. (E: e59c4de3695f4dd28c8fe82dbb9c4e90)`); }\n        if (!space) { throw new Error(`space required. (E: dd0b7189c67c43c586b905a8ed6f51c9)`); }\n\n        if (ibGib && (ibGibs ?? []).length > 0) {\n            console.warn(`${lc} Both ibGib and ibGibs is assigned, whereas this is intended to be exclusive one or the other. (W: 4c797835b620445f88e4cba6b5aa3460)`)\n            if (!ibGibs!.some(x => x.gib === ibGib.gib)) {\n                ibGibs = ibGibs!.concat([ibGib]);\n            }\n        }\n        ibGibs = ibGibs ?? [ibGib!];\n\n        if (logalot) { console.log(`${lc} ibGibs.length: ${ibGibs.length}`) }\n        const argPutIbGibs = await space.argy({\n            ibMetadata: getSpaceArgMetadata({ space }),\n            argData: {\n                cmd: 'put', force, isDna,\n                ibGibAddrs: ibGibs.map(x => getIbGibAddr({ ibGib: x })),\n            },\n            ibGibs: ibGibs.concat(),\n        });\n        const resPutIbGibs = await space.witness(argPutIbGibs);\n        if (resPutIbGibs.data?.success) {\n            if ((resPutIbGibs.data!.warnings ?? []).length > 0) {\n                resPutIbGibs.data!.warnings!.forEach((warning: string) => console.warn(`${lc} ${warning}`));\n            }\n            return { success: true }\n        } else {\n            const errorMsg = resPutIbGibs?.data?.errors?.length > 0 ?\n                `Error(s) putting in local space:\\n${resPutIbGibs.data.errors.join('\\n')}` :\n                '(UNEXPECTED) unknown error putting ibGibs (E: 3d7426d4527243b79c5e55eb25f3fa73)';\n            throw new Error(errorMsg);\n        }\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        return { errorMsg: error.message, }\n    }\n}\n\n/**\n * Wrapper for removing ibgib from the a given space, else the current space.\n */\nexport async function deleteFromSpace({\n    addr,\n    isDna,\n    space,\n}: DeleteIbGibOpts): Promise<DeleteIbGibResult> {\n    let lc = `[${deleteFromSpace.name}]`;\n    try {\n        if (!space) { throw new Error(`space required. (E: 40ab3b51e91c4b5eb4f215baeefbcef0)`); }\n        if (!space.data) { throw new Error(`space.data required. (E: 0d02c8e85ee143b8bd6a1a1db0d9af1b)`); }\n        lc = `${lc}[${space.data.name || 'noname?'}][${space.data.uuid || 'nouuid?'}]`;\n\n        const argDel = await space.argy({\n            ibMetadata: getSpaceArgMetadata({ space }),\n            argData: {\n                cmd: 'delete',\n                ibGibAddrs: [addr],\n                isDna,\n            },\n        });\n        const result = await space.witness(argDel);\n        if (result.data?.success) {\n            return { success: true, }\n        } else {\n            if (result.data?.warnings?.length > 0) {\n                console.warn(`${lc} warnings with delete (${addr}): ${result.data!.warnings!.join('|')}`);\n            }\n            if (result.data?.addrs?.length > 0) {\n                console.warn(`${lc} partial addrs deleted: ${result.data!.addrs!.join('|')}`);\n            }\n            const errorMsg: string = result.data?.errors?.join('|') || `${lc} something went wrong (E: e397fd09b4a746a3ba3305d6ea0893cb)`;\n            if (errorMsg.includes('File does not exist')) {\n                if (logalot) { console.log(`${lc} tried to delete file that does not exist. (I: cb5d1348ccbc58bf0bfc95f3006f1e22)`); }\n            }\n            return { errorMsg }\n        }\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        return { errorMsg: error.message };\n    }\n}\n\n/**\n * Convenience function for persisting a transform result, which has\n * a newIbGib and optionally intermediate ibGibs and/or dnas.\n *\n * it persists these ibgibs into the given space, else the current space.\n */\nexport async function persistTransformResult({\n    resTransform,\n    space,\n    force,\n}: {\n    resTransform: TransformResult<IbGib_V1>,\n    space: IbGibSpaceAny,\n    force?: boolean,\n}): Promise<void> {\n    const lc = `[${persistTransformResult.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: dc6835614ff1a1b82b179225023ae823)`); }\n        if (!space) { throw new Error(`space required. (E: cf94f1d74f1c4561bb88025a2095965b)`); }\n\n        const { newIbGib, intermediateIbGibs, dnas } = resTransform;\n        const ibGibs = [newIbGib, ...(intermediateIbGibs || [])];\n        const argPutIbGibs = await space.argy({\n            ibMetadata: getSpaceArgMetadata({ space }),\n            argData: {\n                cmd: 'put', force,\n                ibGibAddrs: ibGibs.map(x => getIbGibAddr({ ibGib: x })),\n            },\n            ibGibs: ibGibs.concat(),\n        });\n        const resPutIbGibs = await space.witness(argPutIbGibs);\n        if (resPutIbGibs.data?.success) {\n            if (resPutIbGibs.data!.warnings?.length > 0) {\n                resPutIbGibs.data!.warnings!.forEach((warning: string) => console.warn(`${lc} ${warning}`));\n            }\n        } else {\n            const errorMsg = resPutIbGibs?.data?.errors?.length > 0 ?\n                resPutIbGibs.data.errors.join('\\n') :\n                'unknown error putting ibGibs';\n            throw new Error(errorMsg);\n        }\n\n        if (dnas?.length ?? 0 > 0) {\n            const argPutDnas = await space.argy({\n                ibMetadata: getSpaceArgMetadata({ space }),\n                argData: {\n                    cmd: 'put', isDna: true, force,\n                    ibGibAddrs: dnas!.map(x => getIbGibAddr({ ibGib: x })),\n                },\n                ibGibs: dnas!.concat(),\n            });\n            const resPutDnas = await space.witness(argPutDnas);\n            if (resPutDnas.data?.success) {\n                if (resPutDnas.data!.warnings?.length > 0) {\n                    resPutDnas.data!.warnings!.forEach((warning: string) => console.warn(`${lc} ${warning}`));\n                }\n            } else {\n                const errorMsg = resPutDnas?.data?.errors?.length > 0 ?\n                    resPutDnas.data.errors.join('\\n') :\n                    'unknown error putting dna ibGibs';\n                throw new Error(errorMsg);\n            }\n        }\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete. (I: dc6835614ff1a1b82b179225023ae823)`); }\n    }\n}\n\nexport async function getSpecialRel8dIbGibs<TIbGib extends IbGib_V1 = IbGib_V1>({\n    type,\n    rel8nName,\n    space,\n}: {\n    type: SpecialIbGibType,\n    rel8nName: string,\n    space: IbGibSpaceAny,\n}): Promise<TIbGib[]> {\n    const lc = `[${getSpecialRel8dIbGibs.name}]`;\n    try {\n        if (!space) { throw new Error(`space required. (E: f73868a952ac4181a4f90ee6d86cacf3)`); }\n\n        let special = await getSpecialIbGib({ type, space });\n        if (!special) { throw new Error(`couldn't get special (${type}) (E: a65bef190416479697605be486846731)`) };\n        const rel8dAddrs = special.rel8ns ? special.rel8ns[rel8nName] || [] : [];\n        const rel8dIbgibs: TIbGib[] = [];\n        for (let i = 0; i < rel8dAddrs.length; i++) {\n            const addr = rel8dAddrs[i];\n            let resGet = await getFromSpace({ addr, space });\n            if (resGet.success && resGet.ibGibs?.length === 1) {\n                rel8dIbgibs.push(resGet.ibGibs[0] as TIbGib);\n            } else {\n                throw new Error(`couldn't get addr: ${addr} (E: 76ef256ee80149ab860c5786484b0e89)`);\n            }\n        }\n        return rel8dIbgibs;\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    }\n}\n\n/**\n * Gets one of the app's special ibGibs, e.g., TagsIbGib.\n *\n * When initializing tags, this will generate some boilerplate tags.\n * I'm going to be doing roots here also, and who knows what else, but each\n * one will have its own initialize specifics.\n *\n * @param initialize initialize (i.e. create) ONLY IF IbGib not found. Used for initializing app (first run).\n *\n * @see {@link createSpecial}\n * @see {@link createSpecial_Tags}\n */\nexport async function getSpecialIbGib({\n    type,\n    initialize,\n    space,\n    zeroSpace,\n    fnUpdateBootstrap,\n    fnBroadcast,\n    fnGetInitializing,\n    fnSetInitializing,\n    dontWarnIfNotExist,\n}: {\n    type: SpecialIbGibType,\n    initialize?: boolean,\n    space: IbGibSpaceAny,\n    /**\n     * Only required if `initialize` is true.\n     */\n    zeroSpace?: IbGibSpaceAny,\n    /**\n     * Only required if `initialize` is true.\n     */\n    fnUpdateBootstrap?: (newSpace: IbGibSpaceAny) => Promise<void>,\n    /**\n     * Only required if `initialize` is true.\n     */\n    fnBroadcast?: (info: IbGibTimelineUpdateInfo) => void,\n    /**\n     * Initialization lock getter function.\n     */\n    fnGetInitializing?: () => boolean,\n    /**\n     * Initialization lock setter function.\n     *\n     * Because we don't want to initialize while we're initializing.\n     */\n    fnSetInitializing?: (x: boolean) => void,\n    /**\n     * if true, won't warn about non-existent/non-initialized things.\n     * useful if you are just checking to see if a special ibgib exists.\n     */\n    dontWarnIfNotExist?: boolean,\n}): Promise<IbGib_V1 | null> {\n    const lc = `[${getSpecialIbGib.name}]`;\n    try {\n        if (!space) { throw new Error(`space required. (E: d454b31d58764a9bb9c4e47fb5ef38b5)`); }\n\n        let key = getSpecialConfigKey({ type });\n        let addr = await getConfigAddr({\n            key, space,\n            dontWarn: dontWarnIfNotExist || !!initialize // dont warn if we're initializing\n        });\n\n        if (!addr) {\n            if (initialize && (!fnGetInitializing || !fnSetInitializing)) { throw new Error(`if initialize, you must provide fnGetInitializeLock & fnSetInitializeLock. (E: 8eb322625d0c4538be089800882487de)`); }\n            if (initialize && !fnGetInitializing!()) {\n                fnSetInitializing!(true);\n                try {\n                    if (!zeroSpace) { throw new Error(`zeroSpace required when 'initialize' truthy (E: 8582c92c637f90c9b2dbe0ec8355b523)`); }\n                    addr = await createSpecial({ type, space, zeroSpace: zeroSpace!, fnBroadcast, fnUpdateBootstrap }) ?? undefined;\n                } catch (error) {\n                    console.error(`${lc} error initializing: ${error.message}`);\n                } finally {\n                    fnSetInitializing!(false);\n                }\n            }\n            if (!addr) {\n                if (fnGetInitializing && fnGetInitializing()) {\n                    console.warn(`${lc} couldn't get addr, but we're still initializing...`);\n                    return null;\n                } else {\n                    throw new Error(`Special address not in config and couldn't initialize it either. (E: d8ebdc9eaaa640b99cd206f132962c93)`);\n                }\n            }\n        }\n\n        if (logalot) { console.log(`${lc} getting addr: ${addr}`); }\n\n        let resSpecial = await getFromSpace({ addr, space });\n\n        // I'm putting in this check in case we're getting a meta that wasn't\n        // saved into the meta folder.\n        if (!resSpecial.success) {\n            resSpecial = await getFromSpace({ addr, space });\n            if (resSpecial.success) {\n                console.warn(`${lc} special ibgib was not stored in meta folder...putting in meta folder now for the future (W: e6f5571fd98c449bb2809359be5057cc)`);\n                const resPutInMeta = await putInSpace({ ibGib: resSpecial!.ibGibs![0], space });\n                if (!resPutInMeta.success) {\n                    console.warn(`${lc} (UNEXPECTED) tried to put special in meta but success was false? (W: b934b53571c24057af172c790e6a7240)`)\n                }\n            }\n        }\n        if (!resSpecial.success) { throw new Error(resSpecial.errorMsg); }\n        if (resSpecial.ibGibs?.length !== 1) { throw new Error(`no ibGib in result (E: 3a42abdddc3648e292d63dc45c560064)`); }\n        const specialIbGib = resSpecial.ibGibs[0];\n\n        // I'm putting this check in here because it's bad not to have the\n        // latest special associated with a space. eventually this shouldn't be\n        // necessary.\n        let resLatest = await getLatestAddrs({ ibGibs: [specialIbGib], space });\n        if (resLatest?.data?.success && resLatest.data.addrs?.length === 1) {\n            let specialAddr = getIbGibAddr({ ibGib: specialIbGib });\n            let latestAddr = resLatest.data.addrs[0];\n            if (latestAddr !== specialAddr) {\n                console.warn(`${lc} latest addr is not the one associated with the local space.\\nspecialAddr: ${specialAddr}\\nlatestAddr: ${latestAddr} (W: 141b69dc3c414efc9645bb76fcf12df9)`)\n            }\n        }\n\n        return specialIbGib;\n    } catch (error) {\n        const emsg = `${lc} ${error.message}`;\n        /**\n         * error code found in preceding try block (just do a find on it).\n         */\n        const notFoundErrorCode = 'd8ebdc9eaaa640b99cd206f132962c93';\n        if (emsg.includes(notFoundErrorCode) && dontWarnIfNotExist) {\n            // don't log error, it's expected\n        } else {\n            console.error(emsg);\n        }\n        return null;\n    }\n}\n\n/**\n * Gets a config addr from the current space via the given key\n * as the space's rel8n name.\n *\n * For example, for `key = tags`, a space may look like:\n *\n * ```json\n * {\n *    ib: space xyz,\n *    gib: e89ff8a1c4954db28432007615a78952,\n *    rel8ns: {\n *      past: [space xyz^21cb29cc353f45a491d2b49ff2f130db],\n *      ancestor: [space^gib],\n *      tags: [tags^99b388355f8f4a979ca30ba284d3a686], // <<< rel8n with name specified by key\n *    }\n * }\n * ```\n *\n * @param key config key\n * @returns addr in config if exists, else undefined\n */\nexport async function getConfigAddr({\n    key,\n    space,\n    dontWarn,\n}: {\n    key: string,\n    space: IbGibSpaceAny,\n    /**\n     * if true, won't warn about non-existent/non-initialized things.\n     * useful if you are just checking to see if a special ibgib exists.\n     */\n    dontWarn?: boolean,\n}): Promise<string | undefined> {\n    const lc = `[${getConfigAddr.name}](${key})`;\n    try {\n        if (logalot) { console.log(`${lc} getting... (I: 43e7bfc2515d45e5af8767b9a85b248e)`) }\n\n        if (!space) { throw new Error(`space required. (E: 4f135d4276e64054ba21aeb9c304ecec)`); }\n\n        if (!space.rel8ns) {\n            if (logalot || !dontWarn) { console.warn(`${lc} space.rel8ns falsy. (W: 7c642259fbf547dbaa1b2fdf0115f6ef)`); }\n            return undefined;\n        }\n        if (!space.rel8ns[key]) {\n            if (logalot || !dontWarn) { console.warn(`${lc} space.rel8ns[${key}] falsy. (W: 3c1c49b9987b45cc96dd78b808f98e91)`); }\n            return undefined;\n        }\n        if (space.rel8ns[key]!.length === 1) {\n            if (logalot) { console.log(`${lc} got (I: f13e71b693d5404c9535bda8ff0cc6a9)`); }\n            return space.rel8ns![key]![0];\n        } else if (space.rel8ns[key]!.length > 1) {\n            if (logalot || !dontWarn) { console.warn(`${lc} more than one config addr with ${key} rel8n. (W: 102f63eb74904bcfaac2eaf778043205)`) }\n            return space.rel8ns![key]![0];\n        } else {\n            if (logalot) { console.log(`${lc} didn't find (I: 1163e6ac60194d25b3f24881650edfad)`); }\n            // key not found or?\n            return undefined;\n        }\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        return undefined;\n    }\n}\n\nexport async function setConfigAddr({\n    key,\n    addr,\n    space,\n    zeroSpace,\n    fnUpdateBootstrap,\n}: {\n    key: string,\n    addr: string,\n    space: IbGibSpaceAny,\n    zeroSpace: IbGibSpaceAny,\n    fnUpdateBootstrap?: (newSpace: IbGibSpaceAny) => Promise<void>,\n}): Promise<IbGibSpaceAny> {\n    const lc = `[${setConfigAddr.name}]`;\n    try {\n        if (!space) { throw new Error(`space required. (E: c28b663c991d44419aef1026cc689636)`); }\n        if (!zeroSpace) { throw new Error(`zeroSpace required. (E: d3707ae5265d464891ad216f64be6184)`); }\n\n        // rel8 the `addr` to the current space via rel8n named `key`\n        // note that since we are replacing the pointer, we include the key\n        // in `linkedRel8ns` which will keep only the most recent\n        const rel8nsToAddByAddr = { [key]: [addr] };\n        const resNewSpace = await rel8({\n            src: space.toIbGibDto(),\n            dna: false,\n            linkedRel8ns: [\"past\", \"ancestor\", key], // we only want the most recent key address\n            rel8nsToAddByAddr,\n            nCounter: true,\n        });\n\n        if (!resNewSpace.newIbGib) { throw new Error(`create new space failed.`); }\n\n        // persist the new space in both default space and its own space\n        // (will actually have the space witness its future self interestingly\n        // enough...perhaps should have the new space witness itself instead\n\n        // witness in the default zero space\n        // in refactoring, may have to make this optional...hmm\n        await persistTransformResult({ resTransform: resNewSpace, space: zeroSpace });\n\n        // witness in the given space\n        await persistTransformResult({ resTransform: resNewSpace, space });\n\n        // going to update the bootstrap^gib with the new space address, but first...\n        const newSpace = (resNewSpace.newIbGib as IbGibSpaceAny);\n\n        // ...must update the original space reference any time we change it.\n        // messy atm...\n        await space.loadIbGibDto(newSpace);\n\n        // ...now update so the proper space (config) loads on next app start\n        if (fnUpdateBootstrap) {\n            await fnUpdateBootstrap(newSpace);\n        } else {\n            console.warn(`${lc} fnUpdateBootstrap is falsy. (W: 9fb874de2b19454dac18645e61ac463f)`);\n        }\n\n        return newSpace;\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    }\n}\n\nexport async function getCurrentRoot({\n    space,\n}: {\n    space: IbGibSpaceAny,\n}): Promise<IbGib_V1<RootData> | undefined> {\n    const lc = `[${getCurrentRoot.name}]`;\n\n    try {\n        if (!space) { throw new Error(`space required. (E: f0d546101fba4c169256158114ab3c56)`); }\n\n        const roots = await getSpecialIbGib({ type: \"roots\", space });\n        if (!roots) { throw new Error(`Roots not initialized. (E: 89b1ba12ed12416aac41cef9fdaf1fc2)`); }\n        if (!roots.rel8ns) { throw new Error(`Roots not initialized properly. No rel8ns. (E: 8513a07cf530484db9521a2a3a27b7f6)`); }\n        if (!roots.rel8ns.current) { throw new Error(`Roots not initialized properly. No current root. (E: 459c3a007a30486d96fb8d83f696e239)`); }\n        if (roots.rel8ns.current.length === 0) { throw new Error(`Invalid Roots: empty current root rel8n. (E: bede5864090440bca01ea7ab7fd107d6)`); }\n        if (roots.rel8ns.current.length > 1) { throw new Error(`Invalid Roots: multiple current roots selected. (E: 97561acbf63a48ecaa037697bd26555a)`); }\n\n        const currentRootAddr = roots.rel8ns.current[0]!;\n        const resCurrentRoot =\n            await getFromSpace({ addr: currentRootAddr, space });\n        if (resCurrentRoot.ibGibs?.length === 1) {\n            return resCurrentRoot.ibGibs![0] as IbGib_V1<RootData>;\n        } else {\n            throw new Error(`could not get current root. addr: ${currentRootAddr}`);\n        }\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        return undefined;\n    }\n}\n\nexport async function setCurrentRoot({\n    root,\n    space,\n    zeroSpace,\n    fnUpdateBootstrap,\n    fnBroadcast,\n}: {\n    root: IbGib_V1<RootData>,\n    space: IbGibSpaceAny,\n    zeroSpace: IbGibSpaceAny,\n    fnUpdateBootstrap?: (newSpace: IbGibSpaceAny) => Promise<void>,\n    fnBroadcast?: (info: IbGibTimelineUpdateInfo) => void,\n}): Promise<void> {\n    const lc = `[${setCurrentRoot.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 7f16e845a80fe95d28923e4170f0c825)`); }\n        if (!root) { throw new Error(`root required.`); }\n\n        if (!space) { throw new Error(`space required. (E: 186af2731c5342a78b063a0a4346f3db)`); }\n\n        const rootAddr = getIbGibAddr({ ibGib: root });\n\n        // get the roots and update its \"current\" rel8n\n        const roots = await getSpecialIbGib({ type: \"roots\", space });\n        if (!roots) { throw new Error(`Roots not initialized. (E: a8232b9afac89d0d189534480b7a9825)`); }\n\n        // we'll rel8 current with a linkedRel8n, thus ensuring a maximum of only\n        // one rel8d addr (the one we're adding here)\n        const rel8nsToAddByAddr = { current: [rootAddr] };\n        const resNewRoots = await rel8({\n            src: roots,\n            dna: false,\n            linkedRel8ns: [\"past\", \"ancestor\", \"current\"], // current here ensures only 1 rel8n\n            rel8nsToAddByAddr,\n            nCounter: true,\n        });\n        await persistTransformResult({ resTransform: resNewRoots, space });\n\n        const configKey = getSpecialConfigKey({ type: \"roots\" });\n        const newRoots = resNewRoots.newIbGib;\n        const newRootsAddr = getIbGibAddr({ ibGib: newRoots });\n        await setConfigAddr({ key: configKey, addr: newRootsAddr, space, zeroSpace, fnUpdateBootstrap });\n        await registerNewIbGib({ ibGib: newRoots, space, fnBroadcast, });\n\n        // how to let others know roots has changed?\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete. (I: 7f16e845a80fe95d28923e4170f0c825)`); }\n    }\n}\n\n/**\n * Every tjp should be related to one of the roots in a space.\n *\n * You should NOT relate every ibgib frame of a given ibGib.\n */\nexport async function rel8ToCurrentRoot({\n    ibGib,\n    linked,\n    rel8nName,\n    space,\n    fnBroadcast,\n    zeroSpace,\n    fnUpdateBootstrap,\n}: {\n    ibGib: IbGib_V1,\n    linked?: boolean,\n    rel8nName?: string,\n    space: IbGibSpaceAny,\n    fnBroadcast?: (info: IbGibTimelineUpdateInfo) => void,\n    zeroSpace: IbGibSpaceAny,\n    fnUpdateBootstrap?: (newSpace: IbGibSpaceAny) => Promise<void>,\n}): Promise<void> {\n    const lc = `[${rel8ToCurrentRoot.name}]`;\n\n    try {\n        if (!space) { throw new Error(`space required. (E: f2758eab3bb844d2b749515672d9e392)`); }\n        if (!ibGib) { throw new Error(`ibGib required (E: f1bfd67754a7271553f4af544d30bc22)`); }\n\n        let currentRoot = await getCurrentRoot({ space });\n        if (!currentRoot) { throw new Error('currentRoot undefined (E: 5c2d84dafc664808866008f6eb535750'); }\n\n        // only relate the tjp to roots and use the latest index ibgib to have\n        // the reference to the latest ibgib in the space.\n        const tjpAddr = getTjpAddr({ ibGib, defaultIfNone: \"incomingAddr\" });\n        const ibGibAddr = getIbGibAddr({ ibGib });\n\n        // check to see if it's already rel8d. If so, we're done.\n        if (rel8nName && tjpAddr &&\n            currentRoot.rel8ns &&\n            currentRoot.rel8ns[rel8nName] &&\n            currentRoot.rel8ns[rel8nName]!.includes(tjpAddr)) {\n            // already rel8d\n            return;\n        }\n\n        rel8nName = rel8nName || DEFAULT_ROOT_REL8N_NAME;\n\n        // we only need to add the ibgib itself to the root, not the tjp\n        // and not any dependent ibgibs. ...wakka doodle.\n        const resNewRoot = await rel8({\n            src: currentRoot,\n            dna: false,\n            linkedRel8ns: linked ? [\"past\", \"ancestor\", rel8nName] : [\"past\", \"ancestor\"],\n            rel8nsToAddByAddr: { [rel8nName]: [ibGibAddr] },\n            nCounter: true,\n        });\n        await persistTransformResult({ resTransform: resNewRoot, space });\n        const newRoot = resNewRoot.newIbGib as IbGib_V1<RootData>;\n        const newRootAddr = getIbGibAddr({ ibGib: newRoot });\n        if (logalot) { console.log(`${lc} updating _currentRoot root. newRootAddr: ${newRootAddr}`); }\n        await registerNewIbGib({ ibGib: newRoot, space, fnBroadcast, });\n        await setCurrentRoot({ root: newRoot, space, zeroSpace, fnUpdateBootstrap, fnBroadcast });\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        return;\n    }\n}\n\n/**\n * used atow (11/2023) for latest ibgib indexing.\n * i dont know any use cases right now to use this explicitly.\n * used in {@link registerNewIbGib}\n */\nexport async function createAndSaveNewMetaStone({\n    targetIbGib,\n    space,\n}: {\n    targetIbGib: IbGib_V1,\n    space: IbGibSpaceAny,\n}): Promise<void> {\n    const lc = `[${createAndSaveNewMetaStone.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 291638372117dbc983b4b7cbd8f52123)`); }\n        const metaStone = await newUpMetaStone({ targetIbGib });\n        const resPutMetaStone = await putInSpace({ ibGib: metaStone, space });\n        if (!resPutMetaStone.success) { throw new Error(`error putting metaStone in space. error: ${resPutMetaStone.errorMsg ?? '[unknown error (E: 45f700f4f1ff463ca8f5353c8e796ac7)]'} (E: 4c25379e66365055e3e423561a7d6123)`); }\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * Used for tracking tjpAddr -> latest ibGibAddr.\n *\n *\n * Call this when you create a new ibGib.\n *\n * Need to put this in another service at some point, but crunch crunch\n * like pacman's lunch.\n *\n * ## notes\n *\n * * atow (11/2023)the new implementation of this creates a metastone for\n *   the incoming ibgib and broadcasts if a timeline is involved.\n *   * double-checks if previous latest addr is actually older.\n */\nexport async function registerNewIbGib({\n    ibGib,\n    space,\n    fnBroadcast,\n}: {\n    ibGib: IbGib_V1,\n    space: IbGibSpaceAny,\n    fnBroadcast?: (info: IbGibTimelineUpdateInfo) => void,\n}): Promise<void> {\n    let lc = `[${registerNewIbGib.name}]`;\n    let initialLogalot = logalot;\n    // logalot = true;\n    try {\n        const ibGibAddr: IbGibAddr = getIbGibAddr({ ibGib });\n        lc = `${lc}[${ibGibAddr}]`;\n\n        if (!space) { throw new Error(`space required. (E: ea0c03256f8a4062b460aa4de11f1e3e)`); }\n\n        if (logalot) { console.log(`${lc} starting...`); }\n\n        // we only need to register as latest if there is a timeline involved.\n        let gibInfo = getGibInfo({ ibGibAddr });\n        if (!gibInfo.tjpGib && !ibGib.data?.isTjp) {\n            if (logalot) { console.log(`${lc} incoming ibGib has no timeline, so no broadcast. still going to create a metastone for it and return early. (I: 649752e3b1be0e0ceb078e0ec2a84f23)`); }\n            await createAndSaveNewMetaStone({ targetIbGib: ibGib, space });\n            return; /* <<<< returns early */\n        }\n\n        let tjpAddr = getTjpAddr({ ibGib, defaultIfNone: 'undefined' });\n        if (!tjpAddr) {\n            // get tjp information. used in multiple places in the rest of this fn\n            let tjp = ibGib.data?.isTjp ? ibGib : await getTjpIbGib({ ibGib, space });\n            if (!tjp) {\n                console.warn(`${lc} tjp not found for ${ibGibAddr}? Should at least just be the ibGib's address itself. (W: d9b570e5bf6d4312bc7d9249ed3bbaad)`);\n                tjp = ibGib;\n            }\n            tjpAddr = getIbGibAddr({ ibGib: tjp });\n        }\n        if (!tjpAddr) { throw new Error(`(UNEXPECTED) tjpAddr falsy? should be guaranteed at this point. (E: 39aafb70bc3c6d70b6d2cf8882311223)`); }\n\n        /**\n         * either we're adding the given ibGib, replacing the existing with the\n         * ibGib, or doing nothing. We can do this with our current vars in a\n         * closure at this point.\n         */\n        const replaceLatest: () => Promise<void> = async () => {\n            if (logalot) { console.log(`${lc} adding/replacing latest. tjp: ${tjpAddr} (I: 7f848da003a2436089fd6f044d96bb42)`); }\n\n            await createAndSaveNewMetaStone({ targetIbGib: ibGib, space });\n\n            // broadcast if available\n            if (fnBroadcast) {\n                if (logalot) { console.log(`${lc} fnBroadcast is true...(I: 0e3b561fb5474a0598b5c6d698df5e1f)`) }\n                // queue it up in event loop, as this spins off\n                setTimeout(() => {\n                    if (logalot) { console.log(`${lc} broadcasting... (I: 61785937be0346f0959d476d7267ab24)`) }\n                    fnBroadcast({\n                        ib: 'IbGibTimelineUpdateInfo',\n                        tjpAddr,\n                        latestAddr: ibGibAddr,\n                        latestIbGib: ibGib\n                    });\n                });\n            }\n        }\n\n        if (ibGib.data?.isTjp) {\n            // this is the temporal junction point, so we know it's new...but\n            // perhaps it has already been registered?  regardless, shouldn't be\n            // a big deal if multiple metastones are made for the same tjp, and\n            // there is a tradeoff here. either we spend extra processing time\n            // each time to check to be sure there isn't already one there\n            // (rare) or we just live with the possibility of some having\n            // multiple metastones created (also rare).\n            if (logalot) { console.log(`${lc} ibGib.data?.isTjp true. replacingLatest and returning early. (I: 02c626e006668291550e278b461bcb23)`); }\n            await replaceLatest();\n            return; /* <<<< returns early */\n        }\n\n        // there is a tjp/timeline involved. check to see if the new ibgib is\n        // actually new.\n        if (logalot) { console.log(`${lc} ibGib.data?.isTjp is falsy. (I: 84940e3a9eff869c9474b7b92b864b23)`); }\n        const resLatest = await getLatestAddrs({ ibGibs: [ibGib], space, });\n        if (!resLatest.data) { throw new Error(`(UNEXPECTED) resLatest.data falsy? (E: af3d3914d96adcc5525e4db83cc5d223)`); }\n        let { success, latestAddrsMap } = resLatest.data;\n        if (!success) {\n            let { errors } = resLatest.data;\n            errors ??= ['[unknown error (E: 344857f1853641aa842cea3931f90428)]'];\n            throw new Error(`resLatest.success falsy. errors: ${pretty(errors)}. addr: ${ibGibAddr} (E: b66721da6e1ef9ac4f4089e86c059323)`);\n        }\n\n        // #region validate expectations of resulting latestAddrsMap\n        if (!latestAddrsMap) { throw new Error(`(UNEXPECTED) latestAddrsMap falsy but success truthy? (E: c34caff7a256503575ff3ff491dec823)`); }\n        let keysLatestAddrsMap = Object.keys(latestAddrsMap);\n        if (keysLatestAddrsMap.length !== 1) { throw new Error(`(UNEXPECTED) latestAddrsMap size isn't 1? (E: e11ffc2c18d473745b5bbfc3fe5e3a23)`); }\n        if (keysLatestAddrsMap[0] !== ibGibAddr) { throw new Error(`(UNEXPECTED) latestAddrsMap has 1 key (correct) but the key isn't the incoming ibGibAddr? (incorrect). incoming ibGibAddr: ${ibGibAddr}. key found: ${keysLatestAddrsMap[0]} (E: 82d79a95d2d7de90eae9db571a360f23)`); }\n        // #endregion validate expectations of resulting latestAddrsMap\n\n\n        if (logalot) {\n            console.log(`${lc} valid latestAddrsMap. console.dir(latestAddrsMap)... (I: e24de41622cabbef375172c3017cfd23)`);\n            console.dir(latestAddrsMap);\n        }\n        const existingLatestAddr = latestAddrsMap[ibGibAddr];\n        if (existingLatestAddr) {\n            if (existingLatestAddr === ibGibAddr) {\n                // latest addr is the same as the incoming addr may indicate:\n                // 1. NOT NEW if it's already registered.\n                // 2. NEW but not necessarily registered (with new impl as of 11/2023).\n\n                // at the very least we can replace the latest (which saves a\n                // new metastone) and the broadcast subscribers can do\n                // additional checking if the address is actually new to them or\n                // not. (I think it's different logic so other things may break)\n                if (logalot) { console.log(`${lc} no other found. possible idempotent replacement. addr: ${ibGibAddr} (I: 7f5bd5d3391be95919240f0e97976e22)`); }\n                await replaceLatest();\n                return; /* <<<< returns early */\n            } else {\n                // different addr found, then YES the incoming ibGibAddr is expected\n                // to be NEW (note that the incoming ibgib may indeed be older but\n                // somehow the register new has gotten out of whack and this should be\n                // defensively checked elsewhere as needed). So broadcast that there is\n                // a new ibGib if there is a tjp involved.\n\n                if (logalot) { console.log(`${lc} different addr found. incoming ibgib addr is newer. existingLatestAddr: ${existingLatestAddr}. incoming addr: ${ibGibAddr}  (I: 6cadf13f82aabeb71d76babf1813e623)`); }\n\n                // double check that the existing ibGib actually is older. once that is\n                // determined, then we'll execute the replaceLatest\n\n                // not the latest or not registered, so get the full existing latest\n                // ibgib and analyze to see if the incoming ibgib is indeed newer\n                let resExistingLatest = await getFromSpace({ addr: existingLatestAddr, space });\n                if (!resExistingLatest.success || resExistingLatest.ibGibs?.length !== 1) {\n                    console.error(`Didn't find existing latest ibGib (${existingLatestAddr}). I haven't implemented more robust multi-node/distributed strategies for this scenario yet. so we are going ahead with setting the incoming ibgib as the latest in the timeline. (E: 10f6cca6e5ef45bfacbfe48f652e2102)`);\n                    await replaceLatest();\n                    return; /* <<<< returns early */\n                }\n                const existingLatestIbGib = resExistingLatest.ibGibs![0];\n\n                // if there is an nCounter, then we can go by that. Otherwise, we'll\n                // try to brute force \"latest\" comparison\n                const ibGibHasNCounter =\n                    typeof ibGib.data?.n === 'number' &&\n                    ibGib.data!.n! >= 0;\n                if (ibGibHasNCounter) {\n                    // #region ibGib.data.n counter method\n                    if (logalot) { console.log(`found ibGib.data.n (version counter), using this to determine latest ibGib: ${ibGib.data!.n!}`); }\n                    const n_ibGib = (ibGib.data!.n! as number);\n\n                    const existingLatestHasNCounter =\n                        typeof existingLatestIbGib.data?.n === 'number' &&\n                        existingLatestIbGib.data!.n! >= 0;\n\n                    if (existingLatestHasNCounter) {\n                        // both have counters, so compare by those.\n                        const n_existingLatest = (existingLatestIbGib.data!.n! as number);\n                        if (n_ibGib > n_existingLatest) {\n                            // is newer\n                            if (logalot) { console.log(`${lc} is newer (I: 040d05ac2032f08c7fd0c4d8b2887323)`); }\n                            await replaceLatest();\n                        } else {\n                            // not newer\n                            if (logalot) { console.log(`is not newer, so we don't need to do anything else. (I: 14c25dc3314748dc909d61b77eb64354)`) }\n                            console.warn(`${lc} incoming ibGib (${ibGibAddr}) is NOT NEWER than existing latest (${existingLatestAddr}). multiple branches for the same timeline? ignoring incoming ibGibAddr. n_ibGib: ${n_ibGib}. n_existingLatest: ${n_existingLatest}. space.ib: ${space.ib} (W: 057baadca494473dabb26fb4fb879774)`)\n                            return; /* <<<< returns early */\n                        }\n                    } else {\n                        // only the new one has the counter, so that wins by\n                        // default. this is common when existingLatestIbGib is a\n                        // tjp and the ibGib we're registering is n === 0\n                        if (existingLatestIbGib.data?.isTjp && ibGib.data!.n === 0) {\n                            // normal situation\n                            await replaceLatest();\n                        } else {\n                            console.warn(`${lc} (UNEXPECTED) only existingLatestIbGib (isTjp: ${existingLatestIbGib.data?.isTjp}) has a data.n counter? ibGib.data.n: ${ibGib.data!.n}. usually this only happens when existing latest is a tjp and the new ibGib we are registering is n === 0. This is falsy in this instance though. We will go ahead and replace the latest with the new one, but this is an anomalous state. (W: 73d08aea17ad4e1481a5f97e2556a878)`)\n                            console.log(`${lc} console.dir(existingLatestIbGib)... (I: 9ef7962d9cc74f1eb0409e5caf98e915)`);\n                            console.dir(existingLatestIbGib);\n                            console.log(`${lc} console.dir(ibGib)... (I: 9ef7962d9cc74f1eb0409e5caf98e915)`);\n                            console.dir(ibGib);\n                            await replaceLatest();\n                        }\n                    }\n                    // #endregion\n\n                } else {\n                    if (logalot) { console.log(`${lc} no nCounter found. Trying brute force method.`); }\n                    // #region brute force latest\n                    let latestAddr = await getLatestAddr_Brute({\n                        ibGib, ibGibAddr,\n                        existingLatest: existingLatestIbGib, existingLatestAddr,\n                        tjpAddr,\n                        space,\n                    });\n                    if (latestAddr === ibGibAddr) {\n                        await replaceLatest();\n                    } else {\n                        return; /* <<<< returns early */\n                    }\n                    // #endregion\n                }\n            }\n        } else {\n            // if latestAddr is null (no address is found), the incoming ibGib\n            // timeline (or ibGib itself if it's a stone) has not been found at all\n            // yet so YES the incoming ibGib is NEW\n            if (existingLatestAddr === null) {\n                if (logalot) { console.log(`${lc} no existing tjp mapping so incoming ibgib is considered new to this space. ibGib addr: ${ibGibAddr} (I: 4f2bbc32b31e4fa982d95b3a785db82f)`); }\n                await replaceLatest();\n                return; /* <<<< returns early */\n            } else {\n                // should we just warn?\n                throw new Error(`(UNEXPECTED) latestAddr is falsy but not null? the getLatestAddrs impl in the space should be guaranteed to provide either the incoming ibgib addr, the latest addr (if exists), or null if not found. (E: 3159dd531c0bc0efc1ece116adf28923)`);\n            }\n        }\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n        logalot = initialLogalot;\n    }\n}\n\n/**\n * Performs a rel8 transform on the special ibgib corresponding to the incoming\n * `type`.\n *\n * ## special ibgibs\n *\n * much metadata configuration is stored via \"special\" ibgibs. Most of these are\n * tracked in a space's ibgib directly, and the space itself is tracked in the\n * bootstrap. So when storing configuration data, I usually create a new special\n * ibgib. this function performs the plumbing for the rel8 transform related to\n * that special ibgib.\n *\n * ## notes\n *\n * * special ibgib must exist in the space, i.e. previously initialized\n * * i'm using this atm for mainly the local ionic space, but sometimes\n *   might be good in sync space, i dunno at this point.\n *   * I've migrated a lot of local space behavior into this space-agnostic file.\n *\n * @returns new special ibgib addr\n */\nexport async function rel8ToSpecialIbGib({\n    type,\n    rel8nName,\n    ibGibsToRel8,\n    ibGibsToUnRel8,\n    addrsToUnRel8,\n    linked,\n    severPast,\n    deletePreviousSpecialIbGib,\n    space,\n    zeroSpace,\n    fnUpdateBootstrap,\n    fnBroadcast,\n}: {\n    /**\n     * the \"name\" of the special ibgib.\n     *\n     * This will drive deterministically what the special ibgib's `ib` will be,\n     * among other things.\n     */\n    type: SpecialIbGibType,\n    /**\n     * The rel8nName by which to rel8 the target incoming `ibGibsToRel8`.\n     */\n    rel8nName: string,\n    /**\n     * multiple ibgibs to rel8\n     */\n    ibGibsToRel8?: IbGib_V1[],\n    /**\n     * multiple ibgibs to UNrel8.\n     * YOU CANNOT SET BOTH {@link ibGibsToUnRel8} AND {@link addrsToUnRel8}\n     * There is no technical reason for this, I'm just too tired to implement\n     * yagni overhead.\n     * @see {@link addrsToUnRel8}\n     */\n    ibGibsToUnRel8?: IbGib_V1[],\n    /**\n     * alternatively just specify addrs to unrel8.\n     * YOU CANNOT SET BOTH {@link ibGibsToUnRel8} AND {@link addrsToUnRel8}\n     * There is no technical reason for this, I'm just too tired to implement\n     * yagni overhead.\n     * @see {@link ibGibsToUnRel8}\n     */\n    addrsToUnRel8?: IbGibAddr[],\n    /**\n     * If linked, then the rel8nName will only contain one address, i.e. the\n     * last rel8d ibgib's address.\n     *\n     * This depends on your use case.\n     */\n    linked?: boolean,\n    /**\n     * Clears out the special.rel8ns.past array to an empty array.\n     *\n     * {@see deletePreviousSpecialIbGib} for driving use case.\n     */\n    severPast?: boolean,\n    /**\n     * Deletes the previous special ibGib.\n     *\n     * ## driving use case\n     *\n     * the latest ibGib is one that is completely ephemeral. It doesn't get attached\n     * to the current root, and it only has the current instance. So we don't want to\n     * keep around past incarnations.\n     */\n    deletePreviousSpecialIbGib?: boolean,\n    /**\n     * The space in which the special ibgib resides.\n     */\n    space: IbGibSpaceAny,\n    /**\n     * The default zero space that contains metaspace information, i.e.\n     * bootstrap ibgib, space ibgibs, etc.\n     */\n    zeroSpace: IbGibSpaceAny,\n    /**\n     * The function by which to update the bootstrap ibgib.\n     *\n     * This is necessary, because when you update a special ibgib,\n     * the address of that special ibgib must be updated in the given\n     * `space`. This will require an update to the space's address, which\n     * itself is tracked in the bootstrap ibgib.\n     */\n    fnUpdateBootstrap?: (newSpace: IbGibSpaceAny) => Promise<void>,\n    /**\n     * Use this if you want to broadcast the new space's address after this\n     * function performs the rel8 transform.\n     */\n    fnBroadcast?: (info: IbGibTimelineUpdateInfo) => void,\n}): Promise<IbGibAddr> {\n    const lc = `[${rel8ToSpecialIbGib.name}](type:${type},rel8nName:${rel8nName})`;\n    try {\n        if (!space) { throw new Error(`space required. (E: 956192eea28047eba6dad81620bb96fb)`); }\n        if ((ibGibsToRel8 ?? []).length === 0 &&\n            (ibGibsToUnRel8 ?? []).length === 0 &&\n            (addrsToUnRel8 ?? []).length === 0\n        ) {\n            throw new Error(`either ibGibsToRel8 or ibGibsToUnRel8 required. (E: 5add49c8e46a54e2c6b057c22646a822)`);\n        }\n        if ((ibGibsToUnRel8 ?? []).length > 0 && (addrsToUnRel8 ?? []).length > 0) {\n            throw new Error(`can't provide both ibGibsToUnRel8 and addrsToUnRel8. There isn't a technical reason but I'm too tired right now to implement the overhead to enable this atow (05/2025). (E: 31ef66be26349cfe1b1f352389b99425)`);\n        }\n\n        const addrsToRel8 = ibGibsToRel8?.map(ibGib => getIbGibAddr({ ibGib }));\n        addrsToUnRel8 ??= ibGibsToUnRel8?.map(ibGib => getIbGibAddr({ ibGib }));\n\n        // get the special ibgib\n        const configKey = getSpecialConfigKey({ type });\n        let specialAddr =\n            // type === SpecialIbGibType.latest ? // latest special ibgib addr is constant\n            //     getSpecialIbGibAddr({ type }) :\n            await getConfigAddr({ key: configKey, space });\n        if (!specialAddr) { throw new Error(`specialAddr not found (E: 680dfd1caa3e4d7cb0f593b893a10f0d)`) };\n        let resGetSpecial = await getFromSpace({ addr: specialAddr, space });\n        if (!resGetSpecial.success) { throw new Error(`couldn't get special (E: 897f7671d2184515866c5a675d33b3dc)`) }\n        if (!resGetSpecial.ibGibs) { throw new Error(`resGetSpecial.ibGibs falsy (E: 2405dd295b2444d88503f7731796a5a0)`) }\n        if (resGetSpecial.ibGibs!.length !== 1) { throw new Error(`resGetSpecial.ibGibs count is not 1 (${resGetSpecial.ibGibs!.length}) (E: b4547789016a4729af30cd972a4ca4ab)`) }\n\n        const oldSpecialIbGib = resGetSpecial.ibGibs![0];\n\n        // execute the rel8 transform on the special ibgib.\n        const resNewSpecial = await rel8({\n            src: oldSpecialIbGib,\n            rel8nsToAddByAddr: addrsToRel8 ? { [rel8nName]: addrsToRel8 } : undefined,\n            rel8nsToRemoveByAddr: addrsToUnRel8 ? { [rel8nName]: addrsToUnRel8 } : undefined,\n            dna: false,\n            linkedRel8ns: linked ? [Rel8n.past, rel8nName] : [Rel8n.past],\n            nCounter: true,\n        });\n        const newSpecialIbGib = resNewSpecial.newIbGib;\n\n        // sever\n        if (severPast) {\n            if (resNewSpecial.intermediateIbGibs) { throw new Error('new special creates intermediate ibgibs. so severing past is harder. (E: b580c0c56253494192e9c62212ee187d)'); }\n            newSpecialIbGib.rel8ns!.past = [];\n            newSpecialIbGib.gib = await getGib({ ibGib: newSpecialIbGib });\n        }\n\n        // // special ibgib latest index is always the same address\n        // if (type === SpecialIbGibType.latest) {\n        //     newSpecialIbGib.gib = GIB;\n        // }\n\n        // persist\n        await persistTransformResult({ resTransform: resNewSpecial, space });\n\n        // return the new special address (not the incoming new ibGib)\n        const newSpecialAddr = getIbGibAddr({ ibGib: newSpecialIbGib });\n        const specialTjpAddr = getTjpAddr({ ibGib: newSpecialIbGib });\n\n        // update the space ibgib which contains the special/config information\n        // if (type !== SpecialIbGibType.latest) {\n        await setConfigAddr({ key: configKey, addr: newSpecialAddr, space, zeroSpace, fnUpdateBootstrap });\n        // }\n\n        // delete if required, only after updating config with the new special addr.\n        // if (deletePreviousSpecialIbGib && type !== SpecialIbGibType.latest) {\n        if (deletePreviousSpecialIbGib) {\n            await deleteFromSpace({ addr: specialAddr, space });\n        }\n\n        await registerNewIbGib({ ibGib: newSpecialIbGib, fnBroadcast, space, });\n\n        // is this necessary? no i don't think so, as the above registerNewIbGib\n        // already has this dispatch\n        // if (fnBroadcast && specialTjpAddr && getIbAndGib({ ibGibAddr: specialTjpAddr }).gib !== GIB) {\n        //     fnBroadcast({\n        //         ib: 'IbGibTimelineUpdateInfo',\n        //         tjpAddr: specialTjpAddr,\n        //         latestIbGib: newSpecialIbGib,\n        //         latestAddr: newSpecialAddr,\n        //     });\n        // }\n\n        return newSpecialAddr;\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    }\n}\n\nexport async function getTjpIbGib({\n    ibGib,\n    naive = true,\n    space,\n}: {\n    ibGib: IbGib_V1<any>,\n    naive?: boolean,\n    space: IbGibSpaceAny,\n}): Promise<IbGib_V1<any> | undefined> {\n    const lc = `[${getTjpIbGib.name}]`;\n\n    try {\n        if (!space) { throw new Error(`space required. (E: 941f973d50e84415b58724af173f52c2)`); }\n        if (!ibGib) { throw new Error('ibGib required.'); }\n\n        let ibGibAddr = getIbGibAddr({ ibGib });\n        const { gib } = getIbAndGib({ ibGibAddr });\n        if (gib === GIB) { return ibGib; }\n        let isTjp = await isTjp_Naive({ ibGib, naive });\n        if (isTjp) { return ibGib; }\n\n        // the given ibGib arg isn't itself the tjp\n\n        // if no rel8ns, then there is no tjp ibgib, since this is not\n        // intrinsically the tjp and there is no 'tjp' or 'past' rel8n to check\n        if (!ibGib.rel8ns) {\n            if (logalot) { console.log(`${lc} ibgib not tjp in data, and rel8ns is falsy. so tjp is undefined (I: acdadb76a7568807db7a68f6f866de22)`); }\n            return undefined; // <<<< returns early\n        }\n\n        // check explicitly listed tjp in rel8ns\n        if (ibGib.rel8ns!.tjp && ibGib.rel8ns!.tjp.length > 0) {\n            let firstTjpAddr = ibGib.rel8ns!.tjp[0];\n            let resGetTjpIbGib = await getFromSpace({ addr: firstTjpAddr, space });\n            if (resGetTjpIbGib.success && resGetTjpIbGib.ibGibs?.length === 1) {\n                return resGetTjpIbGib.ibGibs[0]\n            } else {\n                const resErrorMsg = resGetTjpIbGib.errorMsg ?? '[unspecified error in get result]';\n                throw new Error(`ibGib references tjp but could not retrieve from space. res error: ${resErrorMsg} (E: 94f0340706ad48c794c6a62c1b235a22)`);\n            }\n        }\n\n        // couldn't get the tjp from the rel8ns.tjp, so look for manually in past.\n        // but we can't just get the earliest in the 'past', because the tjp\n        // may be one of the intermediates!\n        // So, check the immediate past ibGib recursively.\n\n        const past = ibGib.rel8ns!.past || [];\n        if (past.length === 0) {\n            console.warn(`${lc} past.length === 0, so there is no tjp.`)\n            if (logalot) { console.log(`${lc} ibgib is not tjp in data, not in tjp rel8n, and past is empty. so tjp is undefined (I: bf06f664917dcf4492fb9c4c106a6222)`); }\n            return undefined; // <<<< returns early\n        }\n        const pastIbGibAddr = past[past.length - 1];\n        const resGetPastIbGib = await getFromSpace({ addr: pastIbGibAddr, space });\n        if (!resGetPastIbGib.success || resGetPastIbGib.ibGibs?.length !== 1) { throw new Error(`get past failed. addr: ${pastIbGibAddr}`); }\n        const pastIbGib = resGetPastIbGib.ibGibs![0];\n\n        // call this method recursively!\n        return await getTjpIbGib({ ibGib: pastIbGib, naive, space });\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    }\n}\n\n// #region creates\n\n/**\n * Routing function to various `create_____` functions.\n *\n * @returns address of newly created special.\n */\nexport async function createSpecial({\n    type,\n    space,\n    zeroSpace,\n    fnUpdateBootstrap,\n    fnBroadcast,\n}: {\n    type: SpecialIbGibType,\n    space: IbGibSpaceAny,\n    zeroSpace: IbGibSpaceAny,\n    fnUpdateBootstrap?: (newSpace: IbGibSpaceAny) => Promise<void>,\n    fnBroadcast?: (info: IbGibTimelineUpdateInfo) => void,\n}): Promise<IbGibAddr | null> {\n    const lc = `[${createSpecial.name}]`;\n    try {\n        if (!space) { throw new Error(`space falsy and localUserSpace not initialized. (E: 66e7d3ff098248f0a5ddda51853c92e6)`); }\n\n        switch (type) {\n            case \"roots\": return createSpecial_Roots({ space, zeroSpace, fnBroadcast, fnUpdateBootstrap });\n            case \"tags\": return createSpecial_Tags({ space, zeroSpace, fnBroadcast, fnUpdateBootstrap });\n            // case \"latest\": return createSpecial_Latest({ space, zeroSpace, fnBroadcast, fnUpdateBootstrap });\n            case \"secrets\": return createSpecial_Secrets({ space, zeroSpace, fnBroadcast, fnUpdateBootstrap });\n            case \"encryptions\": return createSpecial_Encryptions({ space, zeroSpace, fnBroadcast, fnUpdateBootstrap });\n            case \"outerspaces\": return createSpecial_OuterSpaces({ space, zeroSpace, fnBroadcast, fnUpdateBootstrap });\n            case \"autosyncs\": return createSpecial_Autosyncs({ space, zeroSpace, fnBroadcast, fnUpdateBootstrap });\n            case \"robbots\": return createSpecial_Robbots({ space, zeroSpace, fnBroadcast, fnUpdateBootstrap });\n            case \"apps\": return createSpecial_Apps({ space, zeroSpace, fnBroadcast, fnUpdateBootstrap });\n            default: return createSpecial_Default({ type, space, zeroSpace, fnBroadcast, fnUpdateBootstrap });\n        }\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    }\n}\n\n/**\n * Creates a new special ibgib, persists it and if not skipped, relates\n * it to the current root.\n *\n * @returns newly created ibgib (not just address)\n */\nexport async function createSpecialIbGib({\n    type,\n    skipRel8ToRoot,\n    space,\n    zeroSpace,\n    fnUpdateBootstrap,\n    fnBroadcast,\n}: {\n    type: SpecialIbGibType,\n    skipRel8ToRoot?: boolean,\n    space: IbGibSpaceAny,\n    zeroSpace: IbGibSpaceAny,\n    fnUpdateBootstrap?: (newSpace: IbGibSpaceAny) => Promise<void>,\n    fnBroadcast?: (info: IbGibTimelineUpdateInfo) => void,\n}): Promise<IbGib_V1> {\n    const lc = `[${createSpecialIbGib.name}][${type || 'falsy type?'}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting...`); }\n        const specialIb = getSpecialIbGibIb({ type });\n        const src = factory.primitive({ ib: specialIb });\n        const resNewSpecial = await fork({\n            src,\n            destIb: specialIb,\n            linkedRel8ns: [Rel8n.past, Rel8n.ancestor],\n            tjp: { uuid: true, timestamp: true },\n            dna: true,\n            nCounter: true,\n        });\n        await persistTransformResult({ resTransform: resNewSpecial, space });\n        // we don't relate the special roots index to itself and we don't relate\n        // the latest index as it is a super (woohoo!) special ephemeral ibgib.\n        if (type !== 'roots' && type !== 'latest' && !skipRel8ToRoot) {\n            await rel8ToCurrentRoot({\n                ibGib: resNewSpecial.newIbGib,\n                linked: true,\n                space,\n                zeroSpace,\n                fnBroadcast,\n                fnUpdateBootstrap,\n            });\n        }\n        if (logalot) { console.log(`${lc} complete.`); }\n        return resNewSpecial.newIbGib;\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    }\n}\n\n/**\n * Creates a new tags^gib instance (unique to current space), as well as\n * default initial tags, e.g. \"home\", \"favorites\", etc., and relates these\n * individual tags to the tags ibGib itself.\n *\n * Stores the tags ibGib's addr in config.\n */\nexport async function createSpecial_Tags({\n    space,\n    zeroSpace,\n    fnUpdateBootstrap,\n    fnBroadcast,\n}: {\n    space: IbGibSpaceAny,\n    zeroSpace: IbGibSpaceAny,\n    fnUpdateBootstrap?: (newSpace: IbGibSpaceAny) => Promise<void>,\n    fnBroadcast?: (info: IbGibTimelineUpdateInfo) => void,\n}): Promise<IbGibAddr | null> {\n    const lc = `[${createSpecial_Tags.name}]`;\n    try {\n        if (!space) { throw new Error(`space required. (E: 9c05b9bd355943a39ca47afef67a50eb)`); }\n\n        const configKey = getSpecialConfigKey({ type: \"tags\" });\n        const special = await createSpecialIbGib({\n            type: \"tags\",\n            space,\n            zeroSpace,\n            fnBroadcast,\n            fnUpdateBootstrap,\n        });\n        let addr = getIbGibAddr({ ibGib: special });\n        await setConfigAddr({ key: configKey, addr: addr, space, zeroSpace, fnUpdateBootstrap });\n\n        // at this point, our tags ibGib has no associated tag ibGibs.\n        // add home, favorite tags\n        const initialTagDatas: TagData_V1[] = [\n            { text: 'home', icon: 'home-outline' },\n            { text: 'favorite', icon: 'heart-outline' },\n        ];\n        for (const data of initialTagDatas) {\n            const resCreate = await createTagIbGibAndSundry({ ...data, space, zeroSpace, fnBroadcast, fnUpdateBootstrap });\n            addr = resCreate.newTagsAddr;\n            await setConfigAddr({ key: configKey, addr: addr, space, zeroSpace, fnUpdateBootstrap });\n        }\n\n        return addr;\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        return null;\n    }\n}\n\n/**\n * 1. Creates a new tag ibgib with the given properties.\n * 2. Persists graph in given {@link space}\n * 3. Registers the new tag ibgib in that space, using the given\n *    {@link fnUpdateBootstrap} and {@link fnBroadcast} functions.\n * 4. Relates the new tag to the special tags ibgib.\n *\n * @returns the new tag ibgib and new tags address.\n */\nexport async function createTagIbGibAndSundry({\n    text,\n    icon,\n    description,\n    space,\n    zeroSpace,\n    fnUpdateBootstrap,\n    fnBroadcast,\n}: {\n    text: string,\n    icon?: string,\n    description?: string,\n    space: IbGibSpaceAny,\n    zeroSpace: IbGibSpaceAny,\n    fnUpdateBootstrap?: (newSpace: IbGibSpaceAny) => Promise<void>,\n    fnBroadcast?: (info: IbGibTimelineUpdateInfo) => void,\n}): Promise<{ newTagIbGib: TagIbGib_V1, newTagsAddr: string }> {\n    const lc = `[${createTagIbGibAndSundry.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting...`); }\n        if (!space) { throw new Error(`space required. (E: 5def0b1afab74b0c9286e3ac5060cb8f)`); }\n\n        if (!text) { throw new Error(`${lc} text required`); }\n        icon = icon || DEFAULT_TAG_ICON;\n        description = description || DEFAULT_TAG_DESCRIPTION;\n        const tagIb = tagTextToIb(text);\n        const tagPrimitive = factory.primitive({ ib: \"tag\" });\n        const resNewTag = await factory.firstGen({\n            parentIbGib: tagPrimitive,\n            ib: tagIb,\n            data: { text, icon, description },\n            tjp: { uuid: true, timestamp: true },\n            dna: true,\n            nCounter: true,\n        });\n        const newTag = resNewTag.newIbGib as TagIbGib_V1;\n        await persistTransformResult({ resTransform: resNewTag, space });\n        await registerNewIbGib({ ibGib: newTag, space, fnBroadcast, });\n        const newTagsAddr = await rel8TagToTagsIbGib({\n            tagIbGib: newTag, space, zeroSpace, fnUpdateBootstrap, fnBroadcast,\n        });\n        return { newTagIbGib: newTag, newTagsAddr };\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport async function createSpecial_Roots({\n    space,\n    zeroSpace,\n    fnUpdateBootstrap,\n    fnBroadcast,\n}: {\n    space: IbGibSpaceAny,\n    zeroSpace: IbGibSpaceAny,\n    fnUpdateBootstrap?: (newSpace: IbGibSpaceAny) => Promise<void>,\n    fnBroadcast?: (info: IbGibTimelineUpdateInfo) => void,\n}): Promise<IbGibAddr | null> {\n    const lc = `[${createSpecial_Roots.name}]`;\n    try {\n        if (!space) { throw new Error(`space required. (E: d12a8ea31163429fb6e53ff8e7579c57)`); }\n\n        const configKey = getSpecialConfigKey({ type: \"roots\" });\n        // const rootsIbGib = await createSpecialIbGib({type: \"roots\", space});\n        const rootsIbGib = await createSpecialIbGib({\n            type: \"roots\",\n            space,\n            zeroSpace,\n            fnBroadcast,\n            fnUpdateBootstrap,\n        });\n        let rootsAddr: IbGibAddr | undefined = getIbGibAddr({ ibGib: rootsIbGib });\n        await setConfigAddr({ key: configKey, addr: rootsAddr, space, zeroSpace, fnUpdateBootstrap });\n\n        // at this point, our ibGib has no associated ibGibs.\n        // so we add initial roots\n        const rootNames = ['A', 'B', 'C', 'D', 'E', 'F', 'G'];\n\n        const initialDatas: RootData[] = rootNames.map(n => {\n            return {\n                text: `${n}root`,\n                icon: DEFAULT_ROOT_ICON,\n                description: DEFAULT_ROOT_DESCRIPTION\n            };\n        });\n        let firstRoot: IbGib_V1<RootData> | undefined = undefined;\n        for (let i = 0; i < initialDatas.length; i++) {\n            const data = initialDatas[i];\n            const resCreate = await createRootIbGib({\n                ...data,\n                space,\n                zeroSpace,\n                fnUpdateBootstrap,\n                fnBroadcast,\n            });\n            if (!firstRoot) { firstRoot = resCreate.newRootIbGib; }\n            if (!resCreate.newRootIbGib) { throw new Error(`(UNEXPECTED) resCreate.newRootIbGib falsy? (E: c9fb2c94a9c1d762c1699b41a4d5ad23)`); }\n            rootsAddr = resCreate.newRootsAddr;\n            // update the config for the updated **roots** ibgib.\n            // that roots ibgib is what points to the just created new root.\n            await setConfigAddr({ key: configKey, addr: rootsAddr, space, zeroSpace, fnUpdateBootstrap });\n        }\n        if (!firstRoot) { throw new Error(`(UNEXPECTED) firstRoot still falsy? (E: b2e2c926d242966e7ed7159e4b129e23)`); }\n\n        // initialize current root\n        await setCurrentRoot({ root: firstRoot, space, zeroSpace, fnUpdateBootstrap, fnBroadcast });\n        // hack: the above line updates the roots in config. so get **that** addr.\n\n        rootsAddr = await getConfigAddr({ key: configKey, space });\n        if (!rootsAddr) { throw new Error('(UNEXPECTED) no roots address in config? (E: 76345340699a4738a195e48803ef0d31)'); }\n        return rootsAddr;\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        return null;\n    }\n}\n\nasync function createRootIbGib({\n    text,\n    icon,\n    description,\n    space,\n    zeroSpace,\n    fnUpdateBootstrap,\n    fnBroadcast,\n}: {\n    text: string,\n    icon?: string,\n    description?: string,\n    space: IbGibSpaceAny,\n    zeroSpace: IbGibSpaceAny,\n    fnUpdateBootstrap?: (newSpace: IbGibSpaceAny) => Promise<void>,\n    fnBroadcast?: (info: IbGibTimelineUpdateInfo) => void,\n}): Promise<{ newRootIbGib: IbGib_V1<RootData>, newRootsAddr: string }> {\n    const lc = `[${createRootIbGib.name}]`;\n    try {\n        if (!space) { throw new Error(`space required. (E: cfa876e5c8c64a53a463ca7a645571c8)`); }\n\n        text = text || DEFAULT_ROOT_TEXT;\n        icon = icon || DEFAULT_ROOT_ICON;\n        description = description || DEFAULT_ROOT_DESCRIPTION;\n        const ib = getRootIb(text);\n        const parentIbGib = factory.primitive({ ib: \"root\" });\n        const resNewIbGib = await factory.firstGen({\n            parentIbGib,\n            ib,\n            data: { text, icon, description },\n            linkedRel8ns: [Rel8n.past, Rel8n.ancestor],\n            tjp: { uuid: true, timestamp: true },\n            dna: true,\n            nCounter: true,\n        });\n        const { newIbGib } = resNewIbGib;\n        await persistTransformResult({\n            resTransform: resNewIbGib,\n            space,\n        });\n        const newRootsAddr = await rel8ToSpecialIbGib({\n            type: \"roots\",\n            rel8nName: ROOT_REL8N_NAME,\n            ibGibsToRel8: [newIbGib],\n            space,\n            zeroSpace,\n            fnUpdateBootstrap,\n            fnBroadcast,\n        });\n        return { newRootIbGib: newIbGib as IbGib_V1<RootData>, newRootsAddr };\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    }\n}\n\n// async function createSpecial_Latest({\n//     space,\n//     zeroSpace,\n//     fnUpdateBootstrap,\n//     fnBroadcast,\n// }: {\n//     space: IbGibSpaceAny,\n//     zeroSpace: IbGibSpaceAny,\n//     fnUpdateBootstrap?: (newSpace: IbGibSpaceAny) => Promise<void>,\n//     fnBroadcast?: (info: IbGibTimelineUpdateInfo) => void,\n// }): Promise<IbGibAddr | null> {\n//     const lc = `[${createSpecial_Latest.name}]`;\n//     try {\n//         if (!space) { throw new Error(`space required. (E: 173b08d7eb114238b32280c3efce9d1a)`); }\n\n//         const configKey = getSpecialConfigKey({ type: \"latest\" });\n//         // const special =\n//         //     await createSpecialIbGib({type: \"latest\", skipRel8ToRoot: true, space});\n//         const special = await createSpecialIbGib({\n//             type: \"latest\",\n//             space,\n//             skipRel8ToRoot: true,\n//             zeroSpace,\n//             fnBroadcast,\n//             fnUpdateBootstrap,\n//         });\n//         special.gib = GIB;\n//         let specialAddr = getIbGibAddr({ ibGib: special });\n//         await setConfigAddr({ key: configKey, addr: specialAddr, space, zeroSpace, fnUpdateBootstrap });\n\n//         // right now, the latest ibgib doesn't have any more initialization,\n//         // since it is supposed to be as ephemeral and non-tracked as possible.\n\n//         return specialAddr;\n//     } catch (error) {\n//         console.error(`${lc} ${error.message}`);\n//         return null;\n//     }\n// }\n\nasync function createSpecial_Secrets({\n    space,\n    zeroSpace,\n    fnUpdateBootstrap,\n    fnBroadcast,\n}: {\n    space: IbGibSpaceAny,\n    zeroSpace: IbGibSpaceAny,\n    fnUpdateBootstrap?: (newSpace: IbGibSpaceAny) => Promise<void>,\n    fnBroadcast?: (info: IbGibTimelineUpdateInfo) => void,\n}): Promise<IbGibAddr | null> {\n    const lc = `[${createSpecial_Secrets.name}]`;\n    try {\n        if (!space) { throw new Error(`space required. (E: 340960cd5ad24addb300b23d9722e30a)`); }\n\n        let secretsAddr: IbGibAddr;\n        const configKey = getSpecialConfigKey({ type: \"secrets\" });\n\n        // special ibgib doesn't exist, so create it (empty)\n        // const secretsIbgib = await createSpecialIbGib({type: \"secrets\", space});\n        const secretsIbgib = await createSpecialIbGib({\n            type: \"secrets\",\n            space,\n            zeroSpace,\n            fnBroadcast,\n            fnUpdateBootstrap,\n        });\n        secretsAddr = getIbGibAddr({ ibGib: secretsIbgib });\n        await setConfigAddr({ key: configKey, addr: secretsAddr, space, zeroSpace, fnUpdateBootstrap });\n\n        return secretsAddr;\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        return null;\n    }\n}\n\nasync function createSpecial_Encryptions({\n    space,\n    zeroSpace,\n    fnUpdateBootstrap,\n    fnBroadcast,\n}: {\n    space: IbGibSpaceAny,\n    zeroSpace: IbGibSpaceAny,\n    fnUpdateBootstrap?: (newSpace: IbGibSpaceAny) => Promise<void>,\n    fnBroadcast?: (info: IbGibTimelineUpdateInfo) => void,\n}): Promise<IbGibAddr | null> {\n    const lc = `[${createSpecial_Encryptions.name}]`;\n    try {\n        if (!space) { throw new Error(`space required. (E: 5084e698b6924e7090697ca50075ca59)`); }\n\n        let addr: IbGibAddr;\n        const configKey = getSpecialConfigKey({ type: \"encryptions\" });\n\n        // special ibgib doesn't exist, so create it (empty)\n        // const encryptionsIbgib = await createSpecialIbGib({type: \"encryptions\", space});\n        const encryptionsIbgib = await createSpecialIbGib({\n            type: \"encryptions\",\n            space,\n            zeroSpace,\n            fnBroadcast,\n            fnUpdateBootstrap,\n        });\n        addr = getIbGibAddr({ ibGib: encryptionsIbgib });\n        await setConfigAddr({ key: configKey, addr: addr, space, zeroSpace, fnUpdateBootstrap });\n\n        return addr;\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        return null;\n    }\n}\n\nasync function createSpecial_OuterSpaces({\n    space,\n    zeroSpace,\n    fnUpdateBootstrap,\n    fnBroadcast,\n}: {\n    space: IbGibSpaceAny,\n    zeroSpace: IbGibSpaceAny,\n    fnUpdateBootstrap?: (newSpace: IbGibSpaceAny) => Promise<void>,\n    fnBroadcast?: (info: IbGibTimelineUpdateInfo) => void,\n}): Promise<IbGibAddr | null> {\n    const lc = `[${createSpecial_OuterSpaces.name}]`;\n    try {\n        if (!space) { throw new Error(`space required. (E: 99dd9e92535c470482eb9f6625a33831)`); }\n\n        let outerSpacesAddr: IbGibAddr;\n        const configKey = getSpecialConfigKey({ type: \"outerspaces\" });\n\n        // special outerspaces ibgib doesn't exist, so create it (empty)\n        // const outerSpacesIbGib = await createSpecialIbGib({type: \"outerspaces\", space});\n        const outerSpacesIbGib = await createSpecialIbGib({\n            type: \"outerspaces\",\n            space,\n            zeroSpace,\n            fnBroadcast,\n            fnUpdateBootstrap,\n        });\n        outerSpacesAddr = getIbGibAddr({ ibGib: outerSpacesIbGib });\n        await setConfigAddr({ key: configKey, addr: outerSpacesAddr, space, zeroSpace, fnUpdateBootstrap });\n\n        return outerSpacesAddr;\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        return null;\n    }\n}\n\nasync function createSpecial_Autosyncs({\n    space,\n    zeroSpace,\n    fnUpdateBootstrap,\n    fnBroadcast,\n}: {\n    space: IbGibSpaceAny,\n    zeroSpace: IbGibSpaceAny,\n    fnUpdateBootstrap?: (newSpace: IbGibSpaceAny) => Promise<void>,\n    fnBroadcast?: (info: IbGibTimelineUpdateInfo) => void,\n}): Promise<IbGibAddr | null> {\n    const lc = `[${createSpecial_Autosyncs.name}]`;\n    try {\n        if (!space) { throw new Error(`space required. (E: f01cf6a4a460486796e16d505d629522)`); }\n\n        let autosyncsAddr: IbGibAddr;\n        const configKey = getSpecialConfigKey({ type: \"autosyncs\" });\n\n        const autosyncsIbGib = await createSpecialIbGib({\n            type: \"autosyncs\",\n            space,\n            zeroSpace,\n            fnBroadcast,\n            fnUpdateBootstrap,\n        });\n        autosyncsAddr = getIbGibAddr({ ibGib: autosyncsIbGib });\n        await setConfigAddr({ key: configKey, addr: autosyncsAddr, space, zeroSpace, fnUpdateBootstrap });\n\n        return autosyncsAddr;\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        return null;\n    }\n}\n\nexport async function createSpecial_Robbots({\n    space,\n    zeroSpace,\n    fnUpdateBootstrap,\n    fnBroadcast,\n}: {\n    space: IbGibSpaceAny,\n    zeroSpace: IbGibSpaceAny,\n    fnUpdateBootstrap?: (newSpace: IbGibSpaceAny) => Promise<void>,\n    fnBroadcast?: (info: IbGibTimelineUpdateInfo) => void,\n}): Promise<IbGibAddr | null> {\n    const lc = `[${createSpecial_Robbots.name}]`;\n    try {\n        if (!space) { throw new Error(`space required. (E: f01cf6a4a460486796e16d505d629522)`); }\n\n        let robbotsAddr: IbGibAddr;\n        const configKey = getSpecialConfigKey({ type: \"robbots\" });\n\n        const robbotsIbGib = await createSpecialIbGib({\n            type: \"robbots\",\n            space,\n            zeroSpace,\n            fnBroadcast,\n            fnUpdateBootstrap,\n        });\n        robbotsAddr = getIbGibAddr({ ibGib: robbotsIbGib });\n        await setConfigAddr({ key: configKey, addr: robbotsAddr, space, zeroSpace, fnUpdateBootstrap });\n\n        return robbotsAddr;\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        return null;\n    }\n}\n\nexport async function createSpecial_Apps({\n    space,\n    zeroSpace,\n    fnUpdateBootstrap,\n    fnBroadcast,\n}: {\n    space: IbGibSpaceAny,\n    zeroSpace: IbGibSpaceAny,\n    fnUpdateBootstrap?: (newSpace: IbGibSpaceAny) => Promise<void>,\n    fnBroadcast?: (info: IbGibTimelineUpdateInfo) => void,\n}): Promise<IbGibAddr | null> {\n    const lc = `[${createSpecial_Apps.name}]`;\n    try {\n        if (!space) { throw new Error(`space required. (E: f01cf6a4a460486796e16d505d629522)`); }\n\n        let appsAddr: IbGibAddr | undefined | null;\n        const configKey = getSpecialConfigKey({ type: \"apps\" });\n\n        const appsIbGib = await createSpecialIbGib({\n            type: \"apps\",\n            space,\n            zeroSpace,\n            fnBroadcast,\n            fnUpdateBootstrap,\n        });\n        appsAddr = getIbGibAddr({ ibGib: appsIbGib });\n        await setConfigAddr({ key: configKey, addr: appsAddr, space, zeroSpace, fnUpdateBootstrap });\n\n        // at this point, our apps ibGib has no associated app ibGibs.\n        // so create our initial apps.\n        // appsAddr = await createApps_Chat({ space, zeroSpace, fnUpdateBootstrap, fnBroadcast });\n        appsAddr = await createApp({\n            defaultAppData: DEFAULT_CHAT_APP_DATA_V1,\n            defaultAppRel8ns: DEFAULT_CHAT_APP_REL8NS_V1,\n            space, zeroSpace, fnUpdateBootstrap, fnBroadcast,\n        });\n        // appsAddr = await createApps_Raw({ space, zeroSpace, fnUpdateBootstrap, fnBroadcast });\n        appsAddr = await createApp({\n            defaultAppData: DEFAULT_RAW_APP_DATA_V1,\n            defaultAppRel8ns: DEFAULT_RAW_APP_REL8NS_V1,\n            space, zeroSpace, fnUpdateBootstrap, fnBroadcast,\n        });\n        // appsAddr = await createApps_Todo({ space, zeroSpace, fnUpdateBootstrap, fnBroadcast });\n        appsAddr = await createApp({\n            defaultAppData: DEFAULT_TODO_APP_DATA_V1,\n            defaultAppRel8ns: DEFAULT_TODO_APP_REL8NS_V1,\n            space, zeroSpace, fnUpdateBootstrap, fnBroadcast,\n        });\n\n        return appsAddr;\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        return null;\n    }\n}\n\nexport async function createApp({\n    defaultAppData,\n    defaultAppRel8ns,\n    space,\n    zeroSpace,\n    fnUpdateBootstrap,\n    fnBroadcast,\n}: {\n    /**\n     * object that contains all of the default \"data\" for the app.  Data here\n     * does not mean an app's data like other apps. In ibgib, data is\n     * everywhere. This means particularly the defalut app ibGib's data, i.e.\n     * `ibGib.data`.\n     */\n    defaultAppData: any,\n    defaultAppRel8ns: any,\n    space: IbGibSpaceAny,\n    zeroSpace: IbGibSpaceAny,\n    fnUpdateBootstrap?: (newSpace: IbGibSpaceAny) => Promise<void>,\n    fnBroadcast?: (info: IbGibTimelineUpdateInfo) => void,\n}): Promise<IbGibAddr | null> {\n    const lc = `[${createApp.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 677f68789abdc7316887e8f38c764e22)`); }\n\n        // #region torn from chat-app-v1.ts because of circular dependency...eesh\n\n        if (logalot) { console.log(`${lc} starting...`); }\n        let data = clone(defaultAppData) as AppData_V1;\n        let rel8ns = defaultAppRel8ns ? clone(defaultAppRel8ns) : undefined;\n        data.uuid = (!data.uuid || data.uuid === DEFAULT_UUID_TODO_APP) ?\n            await getUUID() :\n            data.uuid;\n        let { classname } = data;\n\n        const ib = getAppIb({ appData: data, classname });\n\n        const resNewApp = await factory.firstGen({\n            ib,\n            parentIbGib: factory.primitive({ ib: `app ${classname}` }),\n            data: data,\n            rel8ns,\n            dna: true,\n            linkedRel8ns: [Rel8n.ancestor, Rel8n.past],\n            nCounter: true,\n            tjp: { timestamp: true },\n        }) as TransformResult<AppIbGib_V1>;\n\n        // #endregion torn from chat-app-v1.ts because of circular dependency...eesh\n\n        await persistTransformResult({ resTransform: resNewApp, space });\n        await registerNewIbGib({ ibGib: resNewApp.newIbGib, fnBroadcast, space, });\n        let appsAddr = await rel8ToSpecialIbGib({\n            type: \"apps\",\n            rel8nName: APP_REL8N_NAME,\n            ibGibsToRel8: [resNewApp.newIbGib],\n            fnBroadcast,\n            fnUpdateBootstrap,\n            space, zeroSpace,\n        });\n\n        return appsAddr;\n\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nasync function createSpecial_Default({\n    type,\n    space,\n    zeroSpace,\n    fnUpdateBootstrap,\n    fnBroadcast,\n}: {\n    type: SpecialIbGibType,\n    space: IbGibSpaceAny,\n    zeroSpace: IbGibSpaceAny,\n    fnUpdateBootstrap?: (newSpace: IbGibSpaceAny) => Promise<void>,\n    fnBroadcast?: (info: IbGibTimelineUpdateInfo) => void,\n}): Promise<IbGibAddr | null> {\n    const lc = `[${createSpecial_Default.name}]`;\n    try {\n        if (!space) { throw new Error(`space required. (E: c7bbafcbe901418db4c6048f17f53091)`); }\n\n        if (logalot) { console.log(`${lc} creating special of type: ${type} (I: 283c8bb30ed6f9698b74b886c6078622)`); }\n\n        let specialAddr: IbGibAddr;\n        const configKey = getSpecialConfigKey({ type });\n\n        const specialIbGib = await createSpecialIbGib({\n            type,\n            space,\n            zeroSpace,\n            fnBroadcast,\n            fnUpdateBootstrap,\n        });\n        specialAddr = getIbGibAddr({ ibGib: specialIbGib });\n        await setConfigAddr({ key: configKey, addr: specialAddr, space, zeroSpace, fnUpdateBootstrap });\n\n        return specialAddr;\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        return null;\n    }\n}\n\n/**\n * 1. Creates a new robbot ibgib with the given properties.\n * 2. Persists graph in given {@link space}\n * 3. Registers the new robbot ibgib in that space, using the given\n *    {@link fnUpdateBootstrap} and {@link fnBroadcast} functions.\n * 4. Relates the new robbot to the special robbots ibgib.\n *\n * @returns the new robbot ibgib and new robbots address.\n */\n// export async function createRobbotIbGib({\n//     robbotData,\n//     space,\n//     zeroSpace,\n//     fnUpdateBootstrap,\n//     fnBroadcast,\n// }: {\n//     robbotData: RobbotData_V1,\n//     space: IbGibSpaceAny,\n//     zeroSpace: IbGibSpaceAny,\n//     fnUpdateBootstrap?: (newSpace: IbGibSpaceAny) => Promise<void>,\n//     fnBroadcast?: (info: IbGibTimelineUpdateInfo) => void,\n// }): Promise<{ newRobbotIbGib: RobbotIbGib_V1, newRobbotsAddr: string }> {\n//     const lc = `[${createRobbotIbGib.name}]`;\n//     try {\n//         if (logalot) { console.log(`${lc} starting...`); }\n//         if (!space) { throw new Error(`space required. (E: 5def0b1afab74b0c9286e3ac5060cb8f)`); }\n//         if (!robbotData) { throw new Error(`robbotData required (E: cd0304401a2f5a63d86dd71f76f31222)`); }\n\n//         const ib = getRobbotIb({ robbotData });\n//         const resNewRobbot = await factory.firstGen({\n//             parentIbGib: factory.primitive({ ib: \"robbot\" }),\n//             ib,\n//             data: robbotData,\n//             linkedRel8ns: [Rel8n.past, Rel8n.ancestor],\n//             tjp: { uuid: true, timestamp: true },\n//             dna: true,\n//             nCounter: true,\n//         });\n//         const newRobbot = (resNewRobbot.newIbGib as RobbotIbGib_V1);\n//         await persistTransformResult({ resTransform: resNewRobbot, space });\n//         await registerNewIbGib({ ibGib: newRobbot, space, zeroSpace, fnBroadcast, fnUpdateBootstrap });\n//         const newRobbotsAddr = await rel8ToSpecialIbGib({\n//             type: \"robbots\",\n//             rel8nName: ROBBOT_REL8N_NAME,\n//             ibGibsToRel8: [newRobbot],\n//             space,\n//             zeroSpace,\n//             fnUpdateBootstrap,\n//             fnBroadcast,\n//         });\n//         return { newRobbotIbGib: newRobbot, newRobbotsAddr };\n//     } catch (error) {\n//         console.error(`${lc} ${error.message}`);\n//         throw error;\n//     } finally {\n//         if (logalot) { console.log(`${lc} complete.`); }\n//     }\n// }\n\n\n/**\n * We are NOT searching through all of our data looking for a needle in a haystack.\n * What we ARE doing is we are looking through the past of the existing latest and\n * the prospective latest (the given ibGib param) and comparing between the two.\n *\n * Since `past` rel8n is usually a linked rel8n now, we may have to traverse it all\n * the way to its beginning for each possibility.\n *\n * @returns either {@param ibGibAddr} or {@param existingLatestAddr}\n */\nasync function getLatestAddr_Brute({\n    ibGib, ibGibAddr,\n    existingLatest, existingLatestAddr,\n    tjpAddr,\n    space,\n}: {\n    ibGib: IbGib_V1<any>, ibGibAddr: string,\n    existingLatest: IbGib_V1<any>, existingLatestAddr: string,\n    tjpAddr: string,\n    space: IbGibSpaceAny,\n}): Promise<string> {\n    const lc = `[${getLatestAddr_Brute.name}][${ibGibAddr}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting...`); }\n\n        if (!space) { throw new Error(`space required. (E: 64eb9a271f5d43deadec30b9638746c8)`); }\n\n        // no nCounter, so we need to brute force.\n        // The easiest way is to check each's past, as the most common\n        // scenario would be registering a newer one, or less likely, a timing issue\n        // with registering a previous ibGib frame.\n\n        let ibGibPast = ibGib.rel8ns?.past || [];\n        let existingLatestPast = existingLatest.rel8ns?.past || [];\n\n        // going to check a bunch of specific, easy cases to narrow things down.\n\n        if (ibGibPast.length === 1 && existingLatestPast.length === 0) {\n            if (logalot) { console.log(`prospective has a past, so it \"must\" be newer. (won't quote \"must\" anymore)`); }\n            return ibGibAddr;\n        } else if (existingLatestPast.length === 1 && ibGibPast.length === 0) {\n            if (logalot) { console.log(`existing has a past, so it must be newer.`); }\n            return existingLatestAddr;\n        } else if (existingLatestPast.length === 0 && ibGibPast.length === 0) {\n            console.warn(`${lc} neither existing latest nor prospective new ibGib has a past, so keeping existing.`);\n            return existingLatestAddr;\n        } else if (existingLatestPast.includes(ibGibAddr)) {\n            if (logalot) { console.log(`existing by definition is newer`); }\n            return existingLatestAddr;\n        } else if (ibGibPast.includes(existingLatestAddr)) {\n            if (logalot) { console.log(`ibGib by definition is newer`); }\n            return ibGibAddr;\n        } else if (existingLatestAddr === ibGibAddr) {\n            if (logalot) { console.log(`they're the same!`); }\n            return existingLatestAddr;\n        } else if (existingLatestAddr === tjpAddr && existingLatest.rel8ns?.tjp?.length === 1) {\n            if (logalot) { console.log(`ibGib must be newer because the existingLatestAddr is the tjp, which is by definition first in unique past.`); }\n            return ibGibAddr;\n        } else if (ibGibAddr === tjpAddr && ibGib.rel8ns?.tjp?.length === 1) {\n            if (logalot) { console.log(`existing must be newer because the ibGibAddr is the tjp, which is by definition first in unique past.`); }\n            return existingLatestAddr;\n        }\n\n        // well, neither one really gives us any indicator alone\n        // so load each one in the past\n        if (logalot) { console.log(`${lc} brute forcing through iterating the pasts.`); }\n        let newerAddr: string | undefined;\n        let firstIterationCount = -1; // klugy hack, but is an ugly method anyway (brute after all!)\n\n        let getPastCount: (x: IbGib_V1<any>, n: number, otherAddr: string) => Promise<number> =\n            async (x, n, otherAddr) => {\n                let xPast = x.rel8ns?.past || [];\n                if (xPast.includes(otherAddr)) {\n                    // no need to proceed further, since the other is found in the past of x, so x is newer\n                    newerAddr = getIbGibAddr({ ibGib: x });\n                    return -1;\n                }\n                if (xPast.length === 0) { return n; } // no more past to increment\n                let newCount = n + xPast.length;\n                if (firstIterationCount !== -1 && newCount > firstIterationCount) {\n                    // we've determined that the second iteration has a longer past,\n                    // so we don't need to look further\n                    newerAddr = getIbGibAddr({ ibGib: x });\n                    return -1;\n                }\n                // load up the earliest one and call recursively\n                let resNextX = await getFromSpace({ addr: xPast[0], space });\n                if (!resNextX.success || resNextX.ibGibs?.length !== 1) { throw new Error(`Couldn't load past addr (xPast[0]): ${xPast[0]}`); }\n                return getPastCount(resNextX.ibGibs![0], n + xPast.length, otherAddr);\n            }\n\n        if (logalot) { console.log(`${lc} doing ibGibPastCount`); }\n        let ibGibPastCount = await getPastCount(ibGib, 0, existingLatestAddr);\n        if (newerAddr) { return newerAddr; }\n\n        // we didn't hit upon it, so set the firstIterationCount so we don't spend unnecessary cycles\n        if (logalot) { console.log(`${lc} Doing existingPastCount`); }\n        firstIterationCount = ibGibPastCount;\n        let existingPastCount = await getPastCount(existingLatest, 0, ibGibAddr);\n        if (newerAddr) { return newerAddr; }\n\n        // we didn't yet determine it, so whichever has the longer past is newer\n        if (ibGibPastCount > existingPastCount) {\n            if (logalot) { console.log(`${lc} ibGibPastCount (${ibGibPastCount}) is longer than existingPastCount (${existingPastCount}), so ibGib is newer.`); }\n            newerAddr = ibGibAddr;\n        } else {\n            if (logalot) { console.log(`${lc} existingPastCount (${existingPastCount}) is longer than ibGibPastCount (${ibGibPastCount}), so ibGib is newer.`); }\n            newerAddr = existingLatestAddr;\n        }\n        return newerAddr;\n\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n// #endregion\n\n\n/**\n * Relates the given tag to the TagsIbGib, saves the generated\n * TagsIbGib and updates the settings to point to the new TagsIbGib.\n *\n * @param tagIbGib to add to Tags\n */\nexport function rel8TagToTagsIbGib({\n    tagIbGib,\n    space,\n    zeroSpace,\n    fnUpdateBootstrap,\n    fnBroadcast,\n}: {\n    tagIbGib: IbGib_V1,\n    space: IbGibSpaceAny,\n    zeroSpace: IbGibSpaceAny,\n    fnUpdateBootstrap?: (newSpace: IbGibSpaceAny) => Promise<void>,\n    fnBroadcast?: (info: IbGibTimelineUpdateInfo) => void,\n}): Promise<IbGibAddr> {\n    return rel8ToSpecialIbGib({\n        type: \"tags\",\n        rel8nName: TAG_REL8N_NAME,\n        ibGibsToRel8: [tagIbGib],\n        space,\n        zeroSpace,\n        fnUpdateBootstrap,\n        fnBroadcast,\n    });\n}\n\n\n/**\n * Throws an error if any duplicates found in either array.\n *\n * ## notes\n *\n * Only pass in ibGib or ibGibAddrs, not both. Warns if both are passed in though.\n *\n * @throws if both params are falsy or if addrs || mapped addrs contains duplicates.\n */\nexport function throwIfDuplicates({\n    ibGibs,\n    ibGibAddrs,\n}: {\n    ibGibs?: IbGib_V1[],\n    ibGibAddrs?: IbGibAddr[],\n}): void {\n    const lc = `[${throwIfDuplicates.name}]`;\n    try {\n        if (!ibGibs && !ibGibAddrs) { throw new Error(`either ibGibs or ibGibAddrs required. (E: 37776788620f4966b0964945ce181fc6)`); }\n        if (ibGibs && ibGibAddrs) { console.warn(`${lc} both ibGibs and ibGibAddrs provided. You should only provide one. Only ibGibAddrs will be checked. (W: dc13f9e197834e2daaba3bcfd08418db)`); }\n\n        const addrs = ibGibAddrs ? ibGibAddrs.concat() : ibGibs!.map(x => getIbGibAddr({ ibGib: x }));\n        for (let i = 0; i < addrs.length; i++) {\n            const addr = addrs[i];\n            if (addrs.filter(x => x === addr).length > 1) { throw new Error(`duplicate addr found: ${addr} (E: 70fbef040dd449c38c667d53b8092053)`); }\n        }\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    }\n}\n\nexport function getSpaceLockAddr({\n    space,\n    scope,\n}: {\n    space: IbGibSpaceAny,\n    scope: SpaceLockScope,\n}): IbGibAddr {\n    const lc = `[${getSpaceLockAddr.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting...`); }\n\n        if (!space) { throw new Error(`space required. (E: 3ba16e6c3e5e47948b0e63448da11752)`); }\n        if (!space.data?.uuid) { throw new Error(`invalid space (space.data.uuid falsy) (E: 273262b32f2ef27b2e690bc699f33822)`); }\n        if (!scope) { throw new Error(`scope required. (E: f47801d6c45e2247b42a53d9b604b522)`); }\n        while (scope.includes(IBGIB_DELIMITER)) {\n            if (logalot) { console.log(`${lc} scope contains ibgib delimiter...replacing... (I: 0f456fd7cc6552a799673a0c5b4a7d22)`); }\n            scope = scope.replace(IBGIB_DELIMITER, '_');\n        }\n\n        const spaceId = space.data!.uuid;\n        const ib = `${SPACE_LOCK_IB_TERM} ${spaceId} ${scope}`;\n        const gib = GIB;\n        return getIbGibAddr({ ib, gib });\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * Executes some function `fn` against/in a given `space` while\n * performing lock plumbing in that space.\n *\n * By this, I mean that this function takes care of acquiring the lock,\n * attempting retries according to the parameters, and then unlocking\n * the space regardless of result/error.\n *\n * @returns result of inner `fn` with `TResult`\n */\nexport async function execInSpaceWithLocking<TResult>({\n    space,\n    scope,\n    secondsValid,\n    maxDelayMs,\n    fn,\n    callerInstanceId,\n    maxLockAttempts,\n}: {\n    space: IbGibSpaceAny,\n    scope: string,\n    secondsValid: number,\n    /**\n     * If resource locked, will delay at max this ms.\n     */\n    maxDelayMs?: number,\n    fn: () => Promise<TResult>,\n    /**\n     * for use differentiating among tabs.\n     *\n     * ## intent\n     * the idea is the ibgibs service has an instance id and passes it in here.\n     */\n    callerInstanceId?: string,\n    /**\n     * if given, will try to acquire lock at most this many times, else\n     * will default to {@link DEFAULT_MAX_DELAY_RETRY_LOCK_ACQUIRE_ATTEMPTS}.\n     */\n    maxLockAttempts?: number,\n}): Promise<TResult> {\n    const lc = `[${execInSpaceWithLocking.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting...`); }\n\n        // #region validation\n\n        if (!space) { throw new Error(`space required. (E: 66fd8f21a5b2b572d18cdeb9472a7722)`); }\n        if (!secondsValid) { throw new Error(`secondsValid required. (E: 92c5610e57ceede5ce83cff86d5c2a22)`); }\n        if (secondsValid < 0) { throw new Error(`secondsValid must be positive. (E: 970a7510c517235d7a355a843d18d222)`); }\n        // if (secondsValid > MAX_LOCK_SECONDS_VALID) { throw new Error(`secondsValid arg (${secondsValid}) exceeds max secondsValid (${MAX_LOCK_SECONDS_VALID}) (E: 4cffe49a23c8f1698bf7c78eaccbb722)`); }\n        if (!fn) { throw new Error(`fn required (E: 7022e280252ec2faf756b6db05c56e22)`); }\n\n        // #endregion validation\n\n        let resultFn: TResult;\n\n        if (logalot) { console.log(`${lc} attempting to acquire lock with scope ${scope} (I: fed36d42a975b1c52897a4df804ac722)`); }\n        let lockIbGib: IbGibSpaceLockIbGib;\n        maxDelayMs =\n            (maxDelayMs ?? 0) > 0 ? maxDelayMs : DEFAULT_MAX_DELAY_MS_RETRY_LOCK_ACQUIRE\n        let attempts = 0;\n        maxLockAttempts =\n            maxLockAttempts ?? -1 > 0 ?\n                maxLockAttempts :\n                DEFAULT_MAX_DELAY_RETRY_LOCK_ACQUIRE_ATTEMPTS;\n        do {\n            lockIbGib = await lockSpace({\n                space,\n                scope,\n                secondsValid,\n                instanceId: callerInstanceId,\n            });\n            if (lockIbGib?.data?.success) { break; }\n            /** Delay a small random amount of time before trying again. */\n            let delayMs = Math.ceil(Math.random() * maxDelayMs!);\n            await delay(delayMs);\n            attempts++;\n        } while (attempts < maxLockAttempts!);\n        if (lockIbGib?.data?.success) {\n            if (logalot) { console.log(`${lc} lock acquired. (I: d847fa953ee131a57e1a89c537342722)`); }\n        } else {\n            throw new Error(`could not acquire lock after ${attempts} attempts with intermittent delays of ${maxDelayMs} ms (E: 898c559dbd0c9bf20c14cf87a8f1e222)`);\n        }\n\n        // execute the actual get inside an additional try..catch..finally\n        // to ensure (attempted) unlockSpace call.\n        const lc2 = `${lc}[fn]`;\n        try {\n            if (logalot) { console.log(`${lc2} starting... (I: c2f7bedf95d3f1dd1f76de34a68d3f22)`); }\n            resultFn = await fn();\n        } catch (error) {\n            console.error(`${lc2} ${error.message}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc2} unlocking space with scope: ${scope} (I: 21034d9c3395499756e9000e40417d22)`); }\n            await unlockSpace({ space: space, scope: scope, instanceId: callerInstanceId });\n            if (logalot) { console.log(`${lc2} complete. (I: 79d8ac03714a4d429c7e6c2ac6e18d22)`); }\n        }\n\n        return resultFn;\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * Gets the bootstrap ibgib in the given `zeroSpace`.\n *\n * @example\n *\n * ```json\n * {\n *     \"ib\":\"bootstrap\",\n *     \"gib\":\"gib\",\n *     \"data\":{\n *         \"defaultSpaceId\":\"d455d9a72807617634ccbf1e532b71037c45762f824ec85fcd9a4c2275562f33\",\n *         \"spaceIds\":[\"d455d9a72807617634ccbf1e532b71037c45762f824ec85fcd9a4c2275562f33\"]\n *     },\n *     \"rel8ns\":{\n *         \"d455d9a72807617634ccbf1e532b71037c45762f824ec85fcd9a4c2275562f33\":[\n *             \"witness space IonicSpace_V1 oij d455d9a72807617634ccbf1e532b71037c45762f824ec85fcd9a4c2275562f33^B336251655E8C56B38E9E86F20E0E42E6C153785F1A0A798ADE6916E71CF055B\"\n *         ]\n *     }\n * }\n * ```\n *\n * @returns bootstrapIbGib if found, else null\n */\nexport async function getValidatedBootstrapIbGib({\n    zeroSpace,\n}: {\n    zeroSpace: IbGibSpaceAny,\n}): Promise<BootstrapIbGib | null> {\n    const lc = `[${getValidatedBootstrapIbGib.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting...`); }\n\n        if (!zeroSpace) { throw new Error(`zeroSpace required. (E: 66fd8f21a5b2b572d18cdeb9472a7722)`); }\n\n        const bootstrapAddr = BOOTSTRAP_IBGIB_ADDR;\n\n        if (logalot) { console.log(`${lc} getting from zeroSpace...`); }\n        const argGet = await zeroSpace.argy({\n            ibMetadata: getSpaceArgMetadata({ space: zeroSpace }),\n            argData: {\n                cmd: 'get',\n                ibGibAddrs: [bootstrapAddr],\n            },\n        });\n        const resGetBootstrapIbGib = await zeroSpace.witness(argGet);\n\n        if (resGetBootstrapIbGib?.data?.success && resGetBootstrapIbGib.ibGibs?.length === 1) {\n            // bootstrap found\n            const bootstrapIbGib = resGetBootstrapIbGib!.ibGibs![0]!;\n            if (logalot) { console.log(`${lc} bootstrapibGib found: ${pretty(bootstrapIbGib)}`); }\n            if (await validateBootstrapIbGib(bootstrapIbGib)) {\n                return (bootstrapIbGib as BootstrapIbGib);\n            } else {\n                if (logalot) { console.log(`${lc} bootstrapIbGib was invalid. (I: cce66b26805404fc85525d565e1f8b22)`); }\n                return null;\n            }\n        } else {\n            // bootstrap NOT found\n            if (logalot) { console.log(`${lc} bootstrapIbGib NOT found. (I: 421562993bf3464eb507d2967d311e22)`); }\n            return null;\n        }\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * So when loading the local user space, even if the class changes or default\n * constructors change, the internal `data` is loaded from file.\n */\nexport async function getLocalSpace<TSpace extends IbGibSpaceAny>({\n    zeroSpace,\n    bootstrapIbGib,\n    localSpaceId,\n    lock,\n    callerInstanceId,\n    fnDtoToSpace,\n    localSpaceCacheSvc,\n}: {\n    /**\n     * A zero space is a space that is built with default settings that\n     * is not specific to a user.\n     *\n     * This is the foundational space that all spaces share, out of which\n     * a bootstrap ibgib can be found that will itself have rel8ns to other\n     * spaces.\n     *\n     * ## notes\n     *\n     * This is what I was calling a zeroSpace, but that will in the future\n     * mean a default space among a group of spaces.\n     */\n    zeroSpace: IbGibSpaceAny,\n    /**\n     * bootstrap ibGib, if provided, which was found in the zero space.\n     * The bootstrap ibgib should have a rel8n entry to the local space.\n     *\n     * ## future\n     *\n     * We will have multiple local spaces to choose from, with a default\n     * being the one that we're referring to atow.\n     */\n    bootstrapIbGib?: BootstrapIbGib,\n    /**\n     * If provided, will look for the space via this id in the bootstrap ibgib.\n     * If not provided, will use the bootstrap ibgib's default spaceId.\n     */\n    localSpaceId?: SpaceId,\n    /**\n     * If true, we will lock on getting the bootstrap ibgib (if needed), as\n     * well as getting the user space.\n     */\n    lock?: boolean,\n    /**\n     * for use differentiating among tabs.\n     *\n     * ## intent\n     * the idea is the ibgibs service has an instance id and passes it in here.\n     */\n    callerInstanceId: string,\n    /**\n     * function that turns the space dto into the space witness.\n     *\n     * ## intent\n     *\n     * When loading a space, the only part stored is the ibgib data. You still\n     * need a function that hydrates a witness class with that data.\n     */\n    fnDtoToSpace: (spaceDto: IbGib_V1) => Promise<TSpace>,\n    /**\n     * Optional caching service\n     */\n    localSpaceCacheSvc?: IbGibCacheService,\n}): Promise<TSpace> {\n    const lc = `[${getLocalSpace.name}]`;\n    try {\n        if (!zeroSpace) { throw new Error(`zeroSpace required. (E: 0793781a98c456a666cfa9eb960bcd22)`); }\n\n        if (!bootstrapIbGib) {\n            if (logalot) { console.log(`${lc} bootstrap falsy, so loading it... (I: f2366e38283495a38b5501297aa34422)`); }\n            if (lock) {\n                const bootstrapAddr = BOOTSTRAP_IBGIB_ADDR;\n                if (logalot) { console.log(`${lc} using locked version of loading bootstrap... (I: 52b9b11999674e586d051c2b23f59b22)`); }\n                bootstrapIbGib = await execInSpaceWithLocking<BootstrapIbGib>({\n                    space: zeroSpace,\n                    scope: bootstrapAddr,\n                    fn: async () => {\n                        let validatedBootstrapIbGib = await getValidatedBootstrapIbGib({ zeroSpace });\n                        if (validatedBootstrapIbGib) {\n                            return validatedBootstrapIbGib;\n                        } else {\n                            throw new Error(`(UNEXPECTED) unable to get bootstrap ibgib? (E: c111dc7627acbfb992134ddf4064ea23)`);\n                        }\n                    },\n                    callerInstanceId,\n                    secondsValid: DEFAULT_SECONDS_VALID_LOCAL,\n                });\n            } else {\n                if (logalot) { console.log(`${lc} lock is false, so just getting the bootstrap ibgib (I: 49d55e5a824510bb3ee0ccd9f5ec3322)`); }\n                bootstrapIbGib = await getValidatedBootstrapIbGib({ zeroSpace }) ?? undefined;\n            }\n        }\n\n        if (!bootstrapIbGib) { throw new Error(`bootstrapIbGib falsy. not initialized? (E: 91f5c82b5e124178d958701ebcb09822)`); }\n\n        if (!bootstrapIbGib.data) { throw new Error(`(UNEXPECTED) bootstrapIbGib.data required. invalid bootstrap? (E: 568c6b837c1a39f7a25d188a90167423)`); }\n\n        localSpaceId = localSpaceId ?? bootstrapIbGib!.data[BOOTSTRAP_DATA_DEFAULT_SPACE_ID_KEY];\n        const localSpaceAddr = bootstrapIbGib.rel8ns![localSpaceId]![0]; // guaranteed b/c bootstrap was validated\n\n        const fnGet: () => Promise<TSpace> = async () => {\n\n            const argGet = await zeroSpace.argy({\n                ibMetadata: getSpaceArgMetadata({ space: zeroSpace }),\n                argData: {\n                    cmd: 'get',\n                    ibGibAddrs: [localSpaceAddr],\n                },\n            });\n            const resLocalSpace = await zeroSpace.witness(argGet);\n            if (resLocalSpace?.data?.success && resLocalSpace.ibGibs?.length === 1) {\n                const localSpaceDto = resLocalSpace.ibGibs[0] as TSpace;\n                const localSpace = await fnDtoToSpace(localSpaceDto);\n                if (localSpaceCacheSvc) { localSpace.cacheSvc = localSpaceCacheSvc; }\n                return localSpace;\n            } else {\n                throw new Error(`Could not get local space addr (${localSpaceAddr}) specified in bootstrap space (${getIbGibAddr({ ibGib: bootstrapIbGib })}). (E: 6d6b45e7eae4472697ddc971438e4922)`);\n            }\n        }\n\n        if (lock) {\n            if (logalot) { console.log(`${lc} getting localSpaceId (${localSpaceId}) WITH locking (I: c48a0e4ac5971cdbc57273dd35f8a522)`); }\n            return await execInSpaceWithLocking({\n                space: zeroSpace,\n                scope: localSpaceId,\n                fn: () => { return fnGet(); },\n                callerInstanceId,\n                secondsValid: DEFAULT_SECONDS_VALID_LOCAL,\n            });\n        } else {\n            if (logalot) { console.log(`${lc} getting localSpaceId (${localSpaceId}) WITHOUT locking (I: 48e504835dee4006839df8820d860b22)`); }\n            return fnGet();\n        }\n\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    }\n}\n\nexport async function lockSpace({\n    space,\n    scope,\n    secondsValid,\n    instanceId,\n}: IbGibSpaceLockOptions): Promise<IbGibSpaceLockIbGib> {\n    const lc = `[${lockSpace.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting...`); }\n\n        if (!space) { throw new Error(`space required. (E: 5c0a7197a75f483a82d74e5eea60df37)`); }\n        if (!scope) { throw new Error(`scope required. (E: c7f1dde9570f4df3b450faa2c2f85122)`); }\n        if (!secondsValid) { throw new Error(`secondsValid required and positive (E: b42b6733638b46c06c9aff59a6c49822)`); }\n        if (secondsValid < 0) { throw new Error(`secondsValid must be positive (E: bbe3b6d567583bfb35a1c0825eb29622)`); }\n\n        /** what we will return */\n        let resLockIbGib: IbGibSpaceLockIbGib;\n\n        /** space lock address is deterministic ibgib primitive (gib === 'gib') */\n        const spaceLockAddr = getSpaceLockAddr({ space, scope });\n\n        // check for existing lock...\n        let existingLock: IbGibSpaceLockIbGib | undefined;\n\n        // ...in space's backing store (file, IndexedDB entry, DB, etc.)\n\n        let getLock = await getFromSpace({\n            addr: spaceLockAddr, space, force: true\n        });\n        if (getLock.success && getLock.ibGibs?.length === 1) {\n            existingLock = getLock.ibGibs[0] as IbGibSpaceLockIbGib;\n            if (existingLock?.data?.expirationUTC) {\n                if (isExpired({ expirationTimestampUTC: existingLock.data.expirationUTC })) {\n                    // lock expired, so log only. skipping delete atow because should be overwritten\n                    // when the new lock is in place.\n                    console.warn(`${lc} ignoring expired existing lock in space at ${spaceLockAddr}. Should be overwritten (W: 7421c5b051724b189f88cecbbd449b22)`);\n                    existingLock = undefined;\n                }\n            } else {\n                console.error(`${lc} (UNEXPECTED) exisingLock.data.expirationUTC falsy? (E: 218dc0e935534a149d0be153c532cf25)`);\n                existingLock = undefined;\n            }\n        } else {\n            if (logalot) { console.log(`${lc} existing lock not found for ${spaceLockAddr} (I: 191af56ec4e2db3d19084e46bf949222)`); }\n        }\n\n        // populate resLockIbGib if/else existingLock\n        if (existingLock) {\n            if (!existingLock.data) { throw new Error(`(UNEXPECTED) existingLock.data falsy? (E: 00069b4662e5566d971760d15e293723)`); }\n            // valid lock already exists, so return informing caller. this\n            // includes the existing lock's info, i.e. its expiration\n            resLockIbGib = clone(existingLock) as IbGibSpaceLockIbGib;\n            resLockIbGib.data!.alreadyLocked = true;\n            resLockIbGib.data!.success = false;\n        } else {\n            // not yet locked so immediately lock in memory for space, then via\n            // `space.put(lock)`\n            const { ib, gib } = getIbAndGib({ ibGibAddr: spaceLockAddr });\n            resLockIbGib = {\n                ib, gib,\n                data: {\n                    scope,\n                    secondsValid,\n                    instanceId,\n                    expirationUTC: getExpirationUTCString({ seconds: secondsValid }),\n                }\n            } as IbGibSpaceLockIbGib;\n\n            // We must use space.witness (via argy) directly here instead of\n            // `putInSpace` helper, because we need to check\n            // `addrsAlreadyHave`. If the space already has the addr, then\n            // we have lost a race condition and the space is ALREADY locked.\n            const argPut = await space.argy({\n                ibMetadata: getSpaceArgMetadata({ space }),\n                argData: {\n                    cmd: 'put',\n                    force: true,\n                    ibGibAddrs: [spaceLockAddr],\n                },\n                ibGibs: [resLockIbGib],\n            });\n            const resPut = await space.witness(argPut);\n\n            if (resPut.data?.success) {\n                if ((resPut.data.addrsAlreadyHave ?? []).includes(spaceLockAddr)) {\n                    // Race condition lost! The lock was put by someone else in the interim.\n                    if (logalot) { console.log(`${lc} racelost! addrsAlreadyHave includes spaceLockAddr (${spaceLockAddr}) (I: 2e8a1562947c40698110b64251141753)`); }\n\n                    // get the existing lock that beat us\n                    const getLockRace = await getFromSpace({\n                        addr: spaceLockAddr, space, force: true\n                    });\n                    if (getLockRace.success && getLockRace.ibGibs?.length === 1) {\n                        const existingLockRace = getLockRace.ibGibs[0] as IbGibSpaceLockIbGib;\n                        resLockIbGib = clone(existingLockRace) as IbGibSpaceLockIbGib;\n                        resLockIbGib.data!.alreadyLocked = true;\n                        resLockIbGib.data!.success = false;\n                    } else {\n                        // Should be unreachable if addrsAlreadyHave is true, but handle gracefully\n                        const emsg = `${lc} (UNEXPECTED) addrsAlreadyHave true, but couldn't get lock? (E: 8374a2b6628b49369363bc5843105763)`;\n                        console.error(emsg);\n                        resLockIbGib.data!.success = false;\n                        resLockIbGib.data!.errorMsg = emsg;\n                    }\n                } else {\n                    // Success! We put the lock and it was new.\n                    resLockIbGib.data!.success = true;\n                }\n            } else {\n                const emsg = `${lc} there was an error putting the lock in the space: ${resPut.data?.errors?.join('|')}`;\n                resLockIbGib.data!.success = false;\n                resLockIbGib.data!.errorMsg = emsg;\n                console.error(emsg);\n            }\n        }\n\n        return resLockIbGib;\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport async function unlockSpace({\n    space,\n    scope,\n    instanceId,\n}: IbGibSpaceLockOptions): Promise<IbGibSpaceLockIbGib | undefined> {\n    const lc = `[${unlockSpace.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting...`); }\n\n        if (!space) { throw new Error(`space required. (E: 5c0a7197a75f483a82d74e5eea60df37)`); }\n        if (!scope) { throw new Error(`scope required. (E: c7f1dde9570f4df3b450faa2c2f85122)`); }\n\n        /** space lock address is deterministic ibgib primitive (gib === 'gib') */\n        const spaceLockAddr = getSpaceLockAddr({ space, scope });\n\n        // delete in file if it exists\n        let resDelete = await deleteFromSpace({ addr: spaceLockAddr, space, force: true });\n        if (resDelete.success) {\n            const { ib, gib } = getIbAndGib({ ibGibAddr: spaceLockAddr });\n            return {\n                ib, gib,\n                data: {\n                    // action: 'unlock',\n                    success: true,\n                    instanceId,\n                    scope,\n                }\n            } as IbGibSpaceLockIbGib;\n        } else {\n            /** May NOT be an error, just setting this here is convenient to code. */\n            const emsg = `Delete lock in space failed. delete errorMsg: ${resDelete.errorMsg}`;\n            if (emsg.includes('not implemented')) {\n                // rethrow error if space has not implemented a delete command handler\n                throw new Error(emsg);\n            } else if (\n                emsg.toLowerCase().includes(`does not exist`) ||\n                emsg.toLowerCase().includes(`doesn't exist`) ||\n                emsg.toLowerCase().includes(`not found`)\n            ) {\n                // don't want to warn if just file didn't exist\n                if (logalot) { console.log(`${lc} ${emsg} (I: b647916fd0f3e5366e9387131be21c22)`); }\n                const { ib, gib } = getIbAndGib({ ibGibAddr: spaceLockAddr });\n                return {\n                    ib, gib,\n                    data: {\n                        action: 'unlock',\n                        success: true,\n                        instanceId,\n                        scope,\n                    }\n                } as IbGibSpaceLockIbGib;\n            } else {\n                console.warn(`${lc} ${emsg} (W: 14c84fcac15944bd9a417099964d5d9d)`);\n            }\n        }\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * Updates the bootstrap^gib record in the default space data store\n * with the 'space' rel8n set to the `newSpaceAddr`.\n *\n * This way, if the app closes at this point, it will know to look at this\n * space when it loads.\n *\n * ## notes\n *\n * I'm probably typing this all over, but the bootstrap^gib is the\n * first record that the app looks at to know what space to load.\n * The space itself has configuration and has a proper gib hash\n * so it's verifiable. But the initial bootstrap^gib record is\n * NOT, since it only has 'gib' as its address (and thus its not hashed).\n *\n * In the future, this could be alleviated by asking other witnesses\n * \"Hey what was my last bootstrap^gib hash\", but there's no way to\n * do it beyond this without using some kind of authentication/secret(s)\n * that generate the record, i.e. encrypting bootstrap^gib cleverly.\n */\nexport async function updateBootstrapIbGib({\n    space,\n    zeroSpace,\n    setSpaceAsDefault,\n    createIfNotFound,\n}: {\n    /**\n     * space to add/replace in the bootstrap^gib ibgib.\n     */\n    space: IbGibSpaceAny,\n    /**\n     * default \"zero\" space which contains a bootstrap^gib ibgib.\n     */\n    zeroSpace?: IbGibSpaceAny,\n    /**\n     * set the space as the default local space in the bootstrap^gib ibgib.\n     */\n    setSpaceAsDefault?: boolean,\n    /**\n     * If bootstrap not found, create a new one\n     */\n    createIfNotFound?: boolean,\n}): Promise<void> {\n    const lc = `[${updateBootstrapIbGib.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting...`); }\n\n        if (!space) { throw new Error(`space required. (E: 6fc19548fa7d1d5219e19871f280a322)`); }\n        if (!space.data?.uuid) { throw new Error(`space.data.uuid required (E: 6483188ca6f2ed2085fd355595f3ab22)`); }\n        if (!zeroSpace) { throw new Error(`zeroSpace required. (E: abbf156e18b1018d96273e22a260f122)`); }\n\n        const spaceId = space.data.uuid;\n        const newSpaceAddr = getIbGibAddr({ ibGib: space });\n\n        /** validated bootstrap ibgib or null */\n        let bootstrapIbGib = await getValidatedBootstrapIbGib({ zeroSpace });\n        if (!bootstrapIbGib) {\n            if (!createIfNotFound) {\n                if (logalot) { console.log(`${lc} bootstrapIbGib not found but createIfNotFound falsy, so returning early. (I: 5c67d85a8599a5ba4a6780f26a66ea22)`); }\n                return; /* <<<< returns early */\n            }\n\n            // create the bootstrap^gib space that points to user space\n            if (logalot) { console.log(`${lc} creating new bootstrap ibgib for spaceId (${spaceId}) with address of (${newSpaceAddr}) (I: 651959c27bf2ebc5be1f7f44e2b9e422)`); }\n            const { ib: bootstrapIb, gib } = getIbAndGib({ ibGibAddr: BOOTSTRAP_IBGIB_ADDR });\n            bootstrapIbGib = (factory.primitive as any)({ ib: bootstrapIb });\n            bootstrapIbGib!.gib = gib;\n            bootstrapIbGib!.data = {\n                /**\n                 * first space is automatically set as default, regardless of\n                 * `setSpaceAsDefault` value\n                 */\n                [BOOTSTRAP_DATA_DEFAULT_SPACE_ID_KEY]: spaceId,\n                [BOOTSTRAP_DATA_KNOWN_SPACE_IDS_KEY]: [spaceId],\n            } as BootstrapData;\n            bootstrapIbGib!.rel8ns = {\n                /**\n                 * individual spaces indexed by spaceId, should be length === 1\n                 * with the value being the most recent.\n                 */\n                [spaceId]: [newSpaceAddr],\n            } as BootstrapRel8ns;\n        } else {\n            // at this point, we have a validated bootstrap.\n            // update existing bootstrap with newSpaceAddr for given spaceId\n            if (logalot) { console.log(`${lc} updating existing bootstrap (I: 977d4aa7ed47bef73b35743c05ce0722)`); }\n            if (bootstrapIbGib.data!.spaceIds.includes(spaceId)) {\n                if (logalot) { console.log(`${lc} space already rel8d to bootstrap, possibly updating its addr (I: b5e2c515ef732d4bbcf02625a9e7c722)`); }\n                const existingSpaceAddr = bootstrapIbGib.rel8ns![spaceId]![0];\n                if (existingSpaceAddr === newSpaceAddr) {\n                    if (logalot) { console.log(`${lc} bootstrap already rel8d to space (I: c1be027b23e7350c64790a631cae2822)`); }\n                } else {\n                    if (logalot) { console.log(`${lc} updating rel8ns[${spaceId}] with newSpaceAddr (${newSpaceAddr}). (Old address: ${existingSpaceAddr})(I: 297a9b0061fd471b8d28a06e04a6ad22)`); }\n                    bootstrapIbGib.rel8ns![spaceId] = [newSpaceAddr];\n                }\n            } else {\n                // new space being rel8d to bootstrap\n                if (logalot) { console.log(`${lc} new space being rel8d. adding spaceId to data.spaceIds and amending rel8ns (I: 40903d71719aa1d56e498299f5699a22)`); }\n                bootstrapIbGib.data!.spaceIds.push(spaceId);\n                bootstrapIbGib.rel8ns![spaceId] = [newSpaceAddr];\n            }\n            if (setSpaceAsDefault) {\n                if (logalot) { console.log(`${lc} setting spaceId (${spaceId}) as default space (I: f85eda6c6ad2b0bec9750ce3c7795b22)`); }\n                bootstrapIbGib.data![BOOTSTRAP_DATA_DEFAULT_SPACE_ID_KEY] = spaceId;\n            }\n        }\n\n        if (!bootstrapIbGib) { throw new Error(`(UNEXPECTED) bootstrapIbGib still falsy? (E: cf21d7f1756710a66aa0e6a28d762723)`); }\n\n        if (logalot) { console.log(`${lc} saving bootstrapIbGib: ${pretty(bootstrapIbGib)} (I: 3cceca0b98dde90e4a58a734be252322)`); }\n\n        // save the bootstrap^gib in the zero space for future space loadings,\n        // especially when the app first starts up\n        const argPutBootstrap = await zeroSpace.argy({\n            ibMetadata: bootstrapIbGib!.ib,\n            argData: {\n                cmd: 'put', force: true,\n                ibGibAddrs: [getIbGibAddr({ ibGib: bootstrapIbGib })],\n            },\n            ibGibs: [bootstrapIbGib],\n        });\n        if (logalot) { console.log(`${lc} zeroSpace will witness/put... (I: 1be9aca22ffc4951b6690965a7aeae5b)`); }\n        const resPutBootstrap = await zeroSpace.witness(argPutBootstrap);\n        if (resPutBootstrap?.data?.success) {\n            if (logalot) { console.log(`${lc} zero space put complete. (I: ac3056d655e841f1a3c442bcc64942f9)`); }\n        } else {\n            throw new Error(`${resPutBootstrap?.data?.errors?.join('|') || \"There was a problem with zeroSpace witnessing the bootstrap^gib primitive pointing to the new user space\"}`);\n        }\n        if (logalot) { console.log(`${lc} complete.`); }\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    }\n\n}\n\nexport function getSpaceArgMetadata({ space }: { space: IbGibSpaceAny }): string {\n    return `${space.ib} ${getTimestampInTicks()}`;\n}\n\nexport function getSpaceResultMetadata({ space }: { space: IbGibSpaceAny }): string {\n    return `${space.ib} ${getTimestampInTicks()}`;\n}\n\n/**\n * builds the space's ib based on either spaceData or space.data, depending on\n * what is passed in.  if for some reason both are passed in, this does some\n * basic checking to be sure that they are the same data.\n * @returns generated spaceIb\n */\nexport function getSpaceIb({\n    space,\n    spaceData,\n    classname,\n}: {\n    space?: IbGibSpaceAny,\n    spaceData?: IbGibSpaceData,\n    classname?: string,\n}): Ib {\n    const lc = `[${getSpaceIb.name}]`;\n    try {\n        if (!space && !spaceData) { throw new Error(`either space or spaceData required (E: 4dabec34ee77d67c9cc30ee3c3049622)`); }\n        if (space && !space.data) { throw new Error(`(UNEXPECTED) given space has falsy space.data? (E: 058d298876ebbeada7bbddb9e3da2f23)`); }\n        if (space && spaceData) {\n            if (space.data!.uuid !== spaceData.uuid) { throw new Error(`(UNEXPECTED) both space and spaceData given, but uuid don't match? (E: efdd4603cba93a17340a76811fe56b24)`); }\n            if (space.data!.n !== spaceData.n) { throw new Error(`(UNEXPECTED) both space and spaceData given, but n don't match? (E: e51278a707c9bccc57a08a4b86524524)`); }\n        }\n        spaceData ??= space!.data!;\n        if (!spaceData) { throw new Error(`(UNEXPECTED) spaceData falsy? (thought this was a compiler problem that this was even possible.) (E: b3c7ffedcae4b1f45b263b3825930b24)`); }\n\n\n        if (classname && spaceData.classname && classname !== spaceData.classname) {\n            throw new Error(`both classname arg (${classname}) and spaceData.classname (${spaceData.classname}) are different truthy values. (E: f98f012ee876eb8fbe7403f7b53e4624)`);\n        } else {\n            classname ||= spaceData.classname;\n        }\n        if (!classname) { throw new Error(`classname required (E: fa3af4613ad56742dab51d1b0d839322)`); }\n        if (classname.includes(' ')) { throw new Error(`invalid classname (${classname}). cannot contain spaces (E: 243adbf720dcce7904e2665933208b22)`); }\n\n        const name = spaceData?.name || IBGIB_SPACE_NAME_DEFAULT;\n        if (name.includes(' ')) { throw new Error(`invalid space name. cannot contain spaces (E: a8450e1651081412c8ac018520182422)`); }\n\n        const id = spaceData?.uuid || undefined;\n        if (!id) { throw new Error(`invalid space, spaceData.uuid falsy (E: 50ae723a9ab24f4fc7132613e65faf23)`); }\n        if (id.includes(' ')) { throw new Error(`invalid space id. cannot contain spaces (E: 8696830fe7f54bfa85e670a063f3e089)`); }\n\n        const spaceType = spaceData.type ?? undefined;\n        const spaceSubtype = spaceData.subtype ?? undefined;\n        if (spaceType && !spaceSubtype) {\n            throw new Error(`spaceType (${spaceType}) is set but spaceSubtype is falsy. (E: 878ab960d7987ae2331103b4a00d0d24)`);\n        }\n\n        return `${WITNESS_ATOM} ${SPACE_ATOM} ${classname} ${name} ${id} ${spaceType} ${spaceSubtype}`;\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    }\n}\n\n/**\n * determines if the given ib belongs to a space ibgib.\n *\n * atow (03/2024) checks to see if the ib starts with\n *\n *   `${WITNESS_ATOM} ${SPACE_ATOM} `\n */\nexport function isSpaceIb({\n    ib\n}: {\n    ib: Ib\n}): boolean {\n    const lc = `[${isSpaceIb.name}]`;\n    if (!ib) {\n        const emsg = `${lc} ib required (E: dd5244f62f964359a86e59bb08ee47e6)`;\n        console.error(emsg);\n        throw new Error(emsg);\n    }\n    return ib.startsWith(`${WITNESS_ATOM} ${SPACE_ATOM} `);\n    // return ib.startsWith('witness space ') || ib.startsWith('outerspace sync ');\n}\n\n/**\n * atow (03/2024), (space-delimited) schema is...\n *\n * `${WITNESS_ATOM} ${SPACE_ATOM} ${classname} ${name} ${id} ${spaceType} ${spaceSubtype}`\n */\nexport function parseSpaceIb({\n    spaceIb,\n}: {\n    spaceIb: Ib,\n}): {\n    /**\n     * currently this can be the classname OR undefined of the space.\n     */\n    spaceClassname: string | undefined,\n    /**\n     * non-unique spaceName of the given space (i.e. most likely space.data.name)\n     */\n    spaceName: string,\n    /**\n     * currently this returns EITHER SpaceId OR undefined.\n     *\n     * This is because of my using different schemas for local/outer spaces...\n     *\n     * (for better or worse)\n     */\n    spaceId: SpaceId | undefined,\n    /**\n     * if undefined, by convention, this is a user space\n     */\n    spaceType: SpaceType | undefined,\n    /**\n     * subtype, if applicable\n     */\n    spaceSubtype: SpaceSubtype | undefined,\n} {\n    const lc = `[${parseSpaceIb.name}]`;\n    try {\n        if (!spaceIb) { throw new Error(`spaceIb required (E: fa5424cfb7e846e2851562f2f417944f)`); }\n\n        //  `${WITNESS_ATOM} ${SPACE_ATOM} ${classname} ${name} ${id} ${spaceType} ${spaceSubtype}`\n        const [witnessAtom, spaceAtom, spaceClassname, spaceName, spaceId, spaceType_string, spaceSubtype_string] =\n            spaceIb.split(' ');\n\n        if (witnessAtom !== WITNESS_ATOM) { throw new Error(`invalid spaceIb (${spaceIb}). witnessAtom !== WITNESS_ATOM (E: 5ae1ca12cf8f30ae341f3e582b025224)`); }\n        if (spaceAtom !== SPACE_ATOM) { throw new Error(`invalid spaceIb (${spaceIb}). spaceAtom !== SPACE_ATOM (E: 9cc6b6f30e13455eb29748148a94fa0f)`); }\n        if (!spaceClassname) { throw new Error(`invalid spaceIb (${spaceIb}). spaceClassname falsy (E: 00d3392da007ca8b2840b16b199d9a24)`); }\n        if (!spaceName) { throw new Error(`invalid spaceIb (${spaceIb}). spaceName falsy (E: b957d8e74ef34d889fa64c60c7a5ea0b)`); }\n        if (!spaceId) { throw new Error(`invalid spaceIb (${spaceIb}). spaceId falsy (E: 7a1773722d8e46a0866d683130b65b89)`); }\n\n        let spaceType: SpaceType | undefined = undefined;\n        if (spaceType_string && spaceType_string !== 'undefined') {\n            if (VALID_SPACE_TYPES.includes(spaceType_string as SpaceType)) {\n                spaceType = spaceType_string as SpaceType;\n            } else {\n                throw new Error(`invalid spaceIb (${spaceIb}). spaceType (${spaceType_string}) is set but not a valid type. valid types: ${VALID_SPACE_TYPES.join(', ')} (E: 838f4638a88cfbf3545a3a3a38b6dd24)`);\n            }\n        }\n\n        let spaceSubtype: SpaceSubtype | undefined = undefined;\n        if (spaceSubtype_string && spaceSubtype_string !== 'undefined') {\n            if (VALID_SPACE_SUBTYPES.includes(spaceSubtype_string as SpaceSubtype)) {\n                spaceSubtype = spaceSubtype_string as SpaceSubtype;\n            } else {\n                throw new Error(`invalid spaceIb (${spaceIb}). spaceSubtype (${spaceSubtype_string}) is set but not a valid subtype. valid subtypes: ${VALID_SPACE_SUBTYPES.join(', ')} (E: 5bdcf23027f94e73860e4340313b04ab)`);\n            }\n        }\n\n        return {\n            spaceClassname,\n            spaceName,\n            spaceId,\n            spaceType,\n            spaceSubtype,\n        }\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    }\n}\n\n/**\n * @deprecated\n * use `parseSpaceIb`\n */\nexport function getInfoFromSpaceIb({\n    spaceIb,\n}: {\n    spaceIb: Ib,\n}): {\n    /**\n     * currently this can be SpaceId OR undefined.\n     */\n    spaceClassname: string | undefined,\n    /**\n     * non-unique spaceName of the given space (i.e. most likely space.data.name)\n     */\n    spaceName: string,\n    /**\n     * currently this returns EITHER SpaceId OR undefined.\n     *\n     * This is because of my using different schemas for local/outer spaces...\n     *\n     * (for better or worse)\n     */\n    spaceId: SpaceId | undefined,\n} {\n    return parseSpaceIb({ spaceIb });\n}\n\n/**\n * Helper function that generates a unique-ish id.\n *\n * atow this is just `return (await getUUID()).slice(0, DEFAULT_TX_ID_LENGTH);`\n *\n * ## notes\n *\n * The thinking is that it only has to be a couple characters in length\n * because this is supposed to only be a unique id within the scope of\n * a tx which has its own tjp (gib) used as the id for the entire communication\n * saga.\n *\n * @returns txId\n */\nexport async function getNewTxId({\n    length,\n}: {\n    /**\n     * length of txId\n     *\n     * @default DEFAULT_TX_ID_LENGTH\n     */\n    length?: number,\n} = { length: DEFAULT_TX_ID_LENGTH }): Promise<TxId> {\n    const lc = `[${getNewTxId.name}]`;\n    try {\n        length = length || DEFAULT_TX_ID_LENGTH;\n        return (await getUUID()).slice(0, length) as TxId;\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    }\n}\n\n/**\n * wrapper for dealing with a space.\n *\n * convenience function for creating an arg ibgib to send to the given space\n * using Cmd/CmdModifiers for getting latest addrs.\n *\n * @returns space result ibgib from the given `space.witness` call.\n */\nexport async function getLatestAddrs({\n    ibGibs,\n    addrs,\n    tjps,\n    tjpAddrs,\n    space,\n}: {\n    ibGibs?: IbGib_V1[],\n    addrs?: IbGibAddr[],\n    tjps?: IbGib_V1[],\n    tjpAddrs?: IbGibAddr[],\n    space: IbGibSpaceAny,\n}): Promise<IbGibSpaceResultIbGib<IbGib_V1, IbGibSpaceResultData, IbGibSpaceResultRel8ns>> {\n    let lc = `[${getLatestAddrs.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting...`); }\n\n        if (!space) { throw new Error(`space required. (E: 4d188d6c863246f28aa575753a052304)`); }\n\n        // so we don't have to do a bunch of conditional checks all over\n        ibGibs = ibGibs ?? []; addrs = addrs ?? [];\n        tjps = tjps ?? []; tjpAddrs = tjpAddrs ?? [];\n\n        if (\n            addrs.length === 0 && ibGibs.length === 0 &&\n            tjps.length === 0 && tjpAddrs.length === 0\n        ) {\n            throw new Error(`Either addrs, ibGibs, tjps, or tjpAddrs required. (E: 7c6ebfbab98d4d21a431b144457fd991)`);\n        }\n\n        /**\n         * Addrs that we'll ultimately send to the space. They start off as\n         * tjpAddrs (and derived from `tjps` if any), and then add the incoming\n         * ibgibs/addrs if we don't already have their corresponding tjpAddrs\n         * being queried.\n         * */\n        const addrsToQuery = new Set<IbGibAddr>(\n            tjpAddrs.concat(tjps.map(ibGib => getIbGibAddr({ ibGib })))\n        );\n\n        // add ibgibs/addrs only if they do not already have their corresponding\n        // tjpAddr in the query addrs. We can do this by checking if the tjpGib\n        // is located in the ibGibAddr.gib, which has the form\n        // [punctiliarHash].[tjpGib]\n        const tjpGibs = Array.from(addrsToQuery).map(x => getIbAndGib({ ibGibAddr: x }).gib);\n        ibGibs.map(ibGib => getIbGibAddr({ ibGib }))\n            .concat(addrs)\n            .forEach(ibGibAddr => {\n                const { gib } = getIbAndGib({ ibGibAddr });\n                const addrHasExistingTjpGib =\n                    tjpGibs.some(tjpGib => gib.includes(tjpGib));\n                if (!addrHasExistingTjpGib) { addrsToQuery.add(ibGibAddr); }\n            });\n\n        if (logalot) { console.log(`${lc}[testing] ${space.data?.name || space.ib} (${space.data?.uuid || '[space.data.uuid falsy]'}) addrsToQuery: ${Array.from(addrsToQuery)} (I: 8a2202912c364238b6d6eb09577bc246)`); }\n\n        // construct the arg and execute\n        const argGet = await space.argy({\n            ibMetadata: getSpaceArgMetadata({ space }),\n            argData: {\n                cmd: 'get',\n                cmdModifiers: ['latest', 'addrs'],\n                ibGibAddrs: Array.from(addrsToQuery),\n            },\n        });\n        return await space.witness(argGet);\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    }\n}\n\n/**\n * I'm making this because i want to archive on a special tags index ibgib.\n * But we can't allow archiving on any old special ibgib, like the 'roots' index.\n * so this checks to see if it's on the forbidden list (winging that atm), and if it\n * is then this throws.\n *\n * use this function inside of commands that act on ibgibs that are special.\n */\nexport function throwIfContextIsSpecial({\n    ibGib_Context,\n}: {\n    ibGib_Context: IbGib_V1,\n}): void {\n    const lc = `[${throwIfContextIsSpecial.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 5f583fd94d27731a65d514e731b8aa22)`); }\n\n        if (!isSpecial({ ibGib: ibGib_Context })) { return; /* <<<< returns early */; }\n\n        const FORBIDDEN_MANUAL_SPECIAL_TYPES: SpecialIbGibType[] = [\n            'roots', 'autosyncs'\n        ];\n        if (FORBIDDEN_MANUAL_SPECIAL_TYPES.some(x => ibGib_Context.ib.includes(x))) {\n            throw new Error(`cannot perform a modification of this type on this special ibgib (E: b8fb718a7323fc54454464b973412722)`);\n        }\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport async function trash({\n    ibGib_Context,\n    rel8nName_Context,\n    addr,\n    space,\n    zeroSpace,\n    fnUpdateBootstrap,\n    fnBroadcast,\n}: {\n    ibGib_Context: IbGib_V1,\n    rel8nName_Context: string,\n    addr: IbGibAddr,\n    space: IbGibSpaceAny,\n    zeroSpace: IbGibSpaceAny,\n    fnUpdateBootstrap?: (newSpace: IbGibSpaceAny) => Promise<void>,\n    fnBroadcast?: (info: IbGibTimelineUpdateInfo) => void,\n}): Promise<void> {\n    const lc = `[${trash.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 2dc486bb2d516e4534f437aaf5ec7f22)`); }\n        if (!ibGib_Context) { throw new Error(`ibGib_Context required (E: 75f7bfa93145d6dffe85d488443ca722)`); }\n        if (!rel8nName_Context) { throw new Error(`rel8nName_Context required (E: 12aaa43de9e34b68b25dc9a2a68ad6b9)`); }\n        if (!addr) { throw new Error(`addr required (E: e27df3bdc5a2554697cc9597afc4e422)`); }\n        if (!space) { throw new Error(`space required (E: 2e3562486ed2956a770ed9e8d77a3f22)`); }\n\n        const contextIsSpecialIbGib = isSpecial({ ibGib: ibGib_Context });\n        if (contextIsSpecialIbGib) { throwIfContextIsSpecial({ ibGib_Context }); }\n\n        const resNewContext = await rel8({\n            src: ibGib_Context,\n            rel8nsToAddByAddr: { [TRASH_REL8N_NAME]: [addr] },\n            rel8nsToRemoveByAddr: { [rel8nName_Context]: [addr] },\n            dna: true,\n            nCounter: true,\n        });\n\n        await persistTransformResult({ resTransform: resNewContext, space });\n\n        if (contextIsSpecialIbGib) {\n            const newSpecialAddr = getIbGibAddr({ ibGib: resNewContext.newIbGib });\n            const specialType = getSpecialTypeFromIb({ ib: ibGib_Context.ib });\n            const configKey = getSpecialConfigKey({ type: specialType });\n            await setConfigAddr({ key: configKey, addr: newSpecialAddr, space, zeroSpace, fnUpdateBootstrap });\n        }\n\n        await registerNewIbGib({ ibGib: resNewContext.newIbGib, fnBroadcast, space, });\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport async function archive({\n    ibGib_Context,\n    rel8nName_Context,\n    addr,\n    space,\n    zeroSpace,\n    fnUpdateBootstrap,\n    fnBroadcast,\n}: {\n    ibGib_Context: IbGib_V1,\n    rel8nName_Context: string,\n    addr: IbGibAddr,\n    space: IbGibSpaceAny,\n    zeroSpace: IbGibSpaceAny,\n    fnUpdateBootstrap?: (newSpace: IbGibSpaceAny) => Promise<void>,\n    fnBroadcast?: (info: IbGibTimelineUpdateInfo) => void,\n}): Promise<void> {\n    const lc = `[${archive.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 38098552b830495187299bb24fcddff0)`); }\n        if (!ibGib_Context) { throw new Error(`ibGib_Context required (E: d819e8c4db5b4c0bb721300ba434cd40)`); }\n        if (!rel8nName_Context) { throw new Error(`rel8nName_Context required (E: de061adff8c04429a211aa09116a532d)`); }\n        if (!addr) { throw new Error(`addr required (E: 7059ebb8ef6149ea94e22f961d6b5c81)`); }\n        if (!space) { throw new Error(`space required (E: e19566f2d42347798621447edcae312e)`); }\n\n        const contextIsSpecialIbGib = isSpecial({ ibGib: ibGib_Context });\n        if (contextIsSpecialIbGib) { throwIfContextIsSpecial({ ibGib_Context }); }\n\n        const resNewContext = await rel8({\n            src: ibGib_Context,\n            rel8nsToAddByAddr: { [ARCHIVE_REL8N_NAME]: [addr] },\n            rel8nsToRemoveByAddr: { [rel8nName_Context]: [addr] },\n            dna: true,\n            nCounter: true,\n        });\n\n        await persistTransformResult({ resTransform: resNewContext, space });\n\n        if (contextIsSpecialIbGib) {\n            const newSpecialAddr = getIbGibAddr({ ibGib: resNewContext.newIbGib });\n            const specialType = getSpecialTypeFromIb({ ib: ibGib_Context.ib });\n            const configKey = getSpecialConfigKey({ type: specialType });\n            await setConfigAddr({ key: configKey, addr: newSpecialAddr, space, zeroSpace, fnUpdateBootstrap });\n        }\n\n        await registerNewIbGib({ ibGib: resNewContext.newIbGib, fnBroadcast, space, });\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport function spaceNameIsValid(name: string): boolean {\n    const lc = `[${spaceNameIsValid.name}]`;\n    try {\n        // non-falsy\n        if (!name) {\n            console.error(`${lc} name is falsy`)\n            return false;\n        }\n\n        // valid characters are alphanumerics, numbers, underscores, hyphens\n        const regexOnlyIncluded = /[\\w-]+/;\n        const matchOnlyIncluded = name.match(regexOnlyIncluded);\n        if (matchOnlyIncluded?.length !== 1 || matchOnlyIncluded[0].length !== name.length) {\n            console.error(`${lc} name can only contain letters, numbers, underscores, hyphens`);\n            return false;\n        }\n\n        // start with alphanumeric\n        const regexStart = /[a-zA-Z\\d]/;\n        const matchStart = name[0].match(regexStart);\n        if (!matchStart) {\n            console.error(`${lc} name must start with a letter or number`);\n            return false;\n        }\n\n        return true;\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        return false;\n    }\n}\n\n/**\n * wrapper for getting dependency graph from a space.\n *\n * NOTE: This calls the witness space with the command. This is NOT the\n * same as the logic helper in graph-helper.mts which performs the graph\n * traversal logic potentially in-memory or naively.\n */\nexport async function getDependencyGraph({\n    space,\n    ibGibAddrs,\n    live,\n}: {\n    space: IbGibSpaceAny,\n    ibGibAddrs: IbGibAddr[],\n    live?: boolean,\n}): Promise<{ [addr: string]: IbGib_V1 } | null> {\n    const lc = `[${getDependencyGraph.name}]`;\n    try {\n        if (!space) { throw new Error(`space required (E: 8f2441c099084898953153549725f778)`); }\n        if ((ibGibAddrs ?? []).length === 0) { throw new Error(`ibGibAddrs required (E: 9c3b8853609841808093153927649526)`); }\n\n        const argData: any = {\n            cmd: IbGibSpaceOptionsCmd.get,\n            cmdModifiers: [IbGibSpaceOptionsCmdModifier.dependencyGraph],\n            ibGibAddrs,\n            live,\n        };\n        const arg = await space.argy({ argData });\n\n        const result = await space.witness(arg);\n        if (result?.data?.success) {\n            const graph: { [addr: string]: IbGib_V1 } = {};\n            if (result.ibGibs) {\n                for (const ibGib of result.ibGibs) {\n                    const addr = getIbGibAddr({ ibGib });\n                    graph[addr] = ibGib;\n                }\n            }\n            return graph;\n        } else {\n            return null;\n        }\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    }\n}\n", "import {\n    HashAlgorithm, clone, extractErrorMsg, groupBy, hash, pretty\n} from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs'\nimport { UUID_REGEXP } from '@ibgib/helper-gib/dist/constants.mjs';\nimport { Ib, IbGibAddr, } from '@ibgib/ts-gib/dist/types.mjs';\nimport { getIbAndGib, getIbGibAddr, } from '@ibgib/ts-gib/dist/helper.mjs';\nimport { IbGib_V1, IbGibData_V1, IbGibRel8ns_V1 } from '@ibgib/ts-gib/dist/V1/types.mjs';\nimport { Factory_V1 } from '@ibgib/ts-gib/dist/V1/factory.mjs';\nimport { GIB, FORBIDDEN_ADD_RENAME_REMOVE_REL8N_NAMES, GIB_DELIMITER, ROOT } from '@ibgib/ts-gib/dist/V1/constants.mjs';\nimport { validateIb } from '@ibgib/ts-gib/dist/V1/validate-helper.mjs';\nimport { getGib, getGibInfo } from '@ibgib/ts-gib/dist/V1/transforms/transform-helper.mjs';\n\nimport { GLOBAL_LOG_A_LOT, IB_REGEXP_DEFAULT } from '../../core-constants.mjs';\nimport { SpecialIbGibType } from './other-types.mjs';\nimport { INVALID_DATE_STRING, SPECIAL_IBGIB_TYPE_REGEXP } from './other-constants.mjs';\nimport { CONFIG_KEY_ATOM } from './ibgib-constants.mjs';\nimport { IbGibSpaceAny } from '../../witness/space/space-base-v1.mjs';\nimport { getFromSpace } from '../../witness/space/space-helper.mjs';\nimport { FlatIbGibGraph } from './graph-types.mjs';\nimport { IbGibSpaceResultData } from '../../witness/space/space-types.mjs';\n\nconst logalot = GLOBAL_LOG_A_LOT || false;\n\n/**\n * Gets ibgibs that are directly related to the given `ibGib` via `rel8nNames`.\n *\n * @returns map of rel8nName -> ibgibs that are related.\n */\nexport async function getRel8dIbGibs({\n    ibGib,\n    rel8nNames,\n    space,\n}: {\n    ibGib: IbGib_V1,\n    rel8nNames?: string[],\n    space: IbGibSpaceAny,\n}): Promise<{ [rel8nName: string]: IbGib_V1[] }> {\n    const lc = `[${getRel8dIbGibs.name}]`;\n    try {\n        if (!ibGib) { throw new Error(`ibGib required (E: a3c1b2d4e5f6a7b8c9d0e1f2a3b4c5d6)`); }\n        if (!space) { throw new Error(`space required (E: b4d2c3e4f5a6b7c8d9e0f1a2b3c4d5e6)`); }\n\n        // Default to all rel8n names if none provided\n        if (!rel8nNames) {\n            rel8nNames = Object.keys(ibGib.rel8ns || {});\n        }\n\n        const rel8dIbGibs: { [rel8nName: string]: IbGib_V1[] } = {};\n\n        for (const rel8nName of rel8nNames) {\n            const rel8dAddrs = ibGib.rel8ns?.[rel8nName] || [];\n\n            if (rel8dAddrs.length > 0) {\n                const resGet = await getFromSpace({ addrs: rel8dAddrs, space });\n                if (resGet.success && resGet.ibGibs?.length === rel8dAddrs.length) {\n                    rel8dIbGibs[rel8nName] = resGet.ibGibs.concat();\n                } else {\n                    // Start logging warnings instead of throwing immediately?\n                    // For now, consistent with user request to adapt legacy code\n                    throw new Error(`Problem getting rel8d ibgibs for rel8nName: ${rel8nName}. ${resGet.errorMsg || 'Unknown error'} (E: c5e3d4f5a6b7c8d9e0f1a2b3c4d5e6)`);\n                }\n            } else {\n                rel8dIbGibs[rel8nName] = [];\n            }\n        }\n\n        return rel8dIbGibs;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    }\n}\n\n/**\n * Utility function to generate hard-coded ibgibs to use at runtime \"on-chain\" but\n * written at compile-time in (for now) \"off-chain\" source code.\n *\n * Because this is supposed to create and re-create deterministically the equivalent\n * of a non-primitive ibgib \"constant\", this function creates a single ibgib with...\n * * one ancestor\n * * no past, dna, or tjp rel8ns\n * * no tjp timestamp or uuid\n * * no nCounter\n *\n * ## validation\n *\n * * validates the given `ib` against `ibRegExpPattern` or default regexp.\n * * validates that rel8ns doesn't include default forbidden rel8n names or\n *   atow `'tjp'`.\n *\n * ## intent\n *\n * I want to be able to create deterministic ibGibs that I can reference at\n * runtime, similar to an ibgib primitive (e.g. \"root^gib\"), but with the\n * integrity of the `gib` hash. This way, I can reference a deterministic ibgib\n * from code at compile time, and at runtime this will have a corresponding\n * ibgib datum with gib-hashed integrity.\n *\n * ## example\n *\n * I want to create a \"hard-coded\" schema ibgib that I rel8 to some protocol\n * ibgib. So I'll create the data here, which lives in source control in a text file,\n * and then I'll render that as an ibgib that verifies integrity. If I as a coder change\n * it at all, then the `gib` of course will be different.\n */\nexport async function constantIbGib<\n    TData extends IbGibData_V1 = any,\n    TRel8ns extends IbGibRel8ns_V1 = IbGibRel8ns_V1\n>({\n    parentPrimitiveIb,\n    ib,\n    ibRegExpPattern,\n    data,\n    rel8ns,\n}: {\n    parentPrimitiveIb: Ib,\n    ib: Ib,\n    /**\n     * for checking the constant's generated ib\n     */\n    ibRegExpPattern?: string,\n    data?: TData,\n    rel8ns?: TRel8ns,\n}): Promise<IbGib_V1<TData, TRel8ns>> {\n    const lc = `[${constantIbGib.name}]`;\n    try {\n        // validation\n        // parentPrimitiveIb\n        if (!parentPrimitiveIb) { throw new Error(`parentPrimitiveIb required. (E: 88ddf188cc5a4340b597abefba1481e2)`); }\n        if (validateIb({ ib: parentPrimitiveIb }) !== null) { throw new Error(`Invalid parentPrimitiveIb: ${parentPrimitiveIb}. (E:5aec0320956d492ebeeaca41eb1fe1c6)`); }\n\n        // ib\n        if (!ib) { throw new Error(`ib required. (E: 7bbc88f4f2e842d6b00126e55b1783e4)`); }\n        const regExp = ibRegExpPattern ? new RegExp(ibRegExpPattern) : IB_REGEXP_DEFAULT;\n        if (!ib.match(regExp)) { throw new Error(`invalid ib. does not match regexp (${regExp})`); }\n\n        // rel8ns\n        const incomingRel8nNames = Object.keys(rel8ns ?? {});\n        const forbiddenRel8nNames = [...FORBIDDEN_ADD_RENAME_REMOVE_REL8N_NAMES, 'tjp'];\n        const rel8nsIsInvalid = incomingRel8nNames.some(x => {\n            // we don't want constants trying to look like they have/are descendants/tjps/etc.\n            return forbiddenRel8nNames.includes(x);\n        });\n        if (rel8nsIsInvalid) { throw new Error(`Invalid rel8ns. forbiddenRel8nNames: ${forbiddenRel8nNames}. rel8ns keys: ${Object.keys(rel8ns ?? {})}. (E: 837a993c265c4362b6aa0b1a234ea5f8)`); }\n\n\n        // create the constant\n        const resFirstGen = await Factory_V1.firstGen({\n            ib,\n            parentIbGib: Factory_V1.primitive({ ib: parentPrimitiveIb }),\n            data,\n            rel8ns,\n            dna: false,\n            noTimestamp: true,\n            nCounter: false,\n        });\n        const constantIbGib = resFirstGen.newIbGib as IbGib_V1<TData, TRel8ns>;\n\n        // remove any extraneous stuff\n        if (constantIbGib?.rel8ns?.past) { delete constantIbGib.rel8ns.past; }\n        if (constantIbGib?.rel8ns?.tjp) { delete constantIbGib.rel8ns.tjp; }\n        if (constantIbGib?.rel8ns?.identity) { delete constantIbGib.rel8ns.identity; }\n\n        // recalculate the gib hash\n        // constantIbGib.gib = await sha256v1({\n        constantIbGib.gib = await getGib({\n            ibGib: {\n                ib: constantIbGib.ib,\n                data: constantIbGib.data,\n                rel8ns: constantIbGib.rel8ns,\n            },\n            hasTjp: false,\n        });\n\n        return constantIbGib;\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    }\n}\n\n/**\n * Binaries require special handling, since they do not conform to the\n * \"normal\" IbGib_V1 data structure per se. This stems from wanting to\n * be able to have binaries (jpgs, gifs, etc. especially) able to\n * sit on a server and be served as regular files.\n *\n * @returns string in expected template for binaries in this app.\n */\nexport function getBinIb({ binHash, binExt, binEncoding }: { binHash: string, binExt?: string, binEncoding?: string }): IbGibAddr {\n    if (binEncoding) {\n        // adding this part after the fact here. not sure how this is going to\n        // go down. just noting because of the strange shape of the logic here.\n        return binExt ? `bin ${binHash} ${binExt} enc=${binEncoding}` : `bin ${binHash} enc=${binEncoding}`;\n    } else {\n        return binExt ? `bin ${binHash} ${binExt}` : `bin ${binHash}`;\n    }\n}\n\n/**\n * @deprecated\n *\n * use {@link parseBinIb}\n */\nexport function getBinHashAndExt({ addr }: { addr: IbGibAddr }): { binHash: string, binExt: string, binEncoding?: string } {\n    return parseBinIb({ addr });\n}\n\n/**\n * parses a given addr that is expected to be for a {@link BinIbGib_V1}.\n *\n * @throws an error if addr is not for a {@link BinIbGib_V1} (via {@link isBinary})\n *\n * @returns parsed bin ib information\n */\nexport function parseBinIb({ addr }: { addr: IbGibAddr }): { binHash: string, binExt: string, binEncoding?: string } {\n    const lc = `[${parseBinIb.name}]`;\n    try {\n        if (!isBinary({ addr })) { throw new Error(`not a bin address (E: df0804d129bc4888bd6939cb76c5e0f6)`); }\n        const { ib } = getIbAndGib({ ibGibAddr: addr });\n        const ibPieces = ib.split(' ');\n        if (ibPieces.length === 2) {\n            // bin ${binHash}\n            return {\n                binHash: ibPieces[1],\n                binExt: '',\n                // binEncoding: undefined,\n            };\n        } else if (ibPieces.length === 3) {\n            // could be\n            // bin ${binHash} enc=${binEncoding}\n            // or...\n            // bin ${binHash} ${binExt}\n            return ibPieces[2].startsWith(\"enc=\") ?\n                {\n                    binHash: ibPieces[1],\n                    binExt: '',\n                    binEncoding: ibPieces[2].substring(\"enc=\".length),\n                } :\n                {\n                    binHash: ibPieces[1],\n                    binExt: ibPieces[2],\n                    // binEncoding: undefined,\n                };\n        } else if (ibPieces.length === 4) {\n            if (!ibPieces[3].startsWith(\"enc=\")) {\n                throw new Error(`bin ib (${ib}) has 4 space-delimited pieces. we expect therefore the form to be bin \\${binHash} \\${binExt} enc=\\${binEncoding}. but ibPieces[3] doesn't start with \"enc=\". (E: 87196d7cdd7c12d982cc8204a1163524)`);\n            }\n            return {\n                binHash: ibPieces[1],\n                binExt: ibPieces[2],\n                binEncoding: ibPieces[3].substring(\"enc=\".length),\n            };\n        } else {\n            throw new Error(`(UNEXPECTED) ibPieces.length not 2, 3, or 4? atow (01/2024) the only components of a bin ib are: atom, binHash, binExt, binEncoding. binExt and binEncoding are optional, with binEncoding being prefixed with \"enc=\". (E: b05df3c1b3949f76464a83c9fd1c4f24)`);\n        }\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    }\n}\n\n/**\n * atow (01/2024) this looks to see...\n *\n * * that data is truthy (if ibGib is truthy)\n * * gib is a UUID\n *\n * ## dev note\n *\n * this is tightly coupled with {@link getBinIb} and {@link parseBinIb}\n *\n * @returns true if analysis of ibgib indicates it is a {@link BinIbGib_V1}, else false\n */\nexport function isBinary({\n    ibGib,\n    addr,\n}: {\n    ibGib?: IbGib_V1,\n    addr?: IbGibAddr,\n}): boolean {\n    const lc = `[${isBinary.name}]`;\n    try {\n        // probably overkill here, but...\n        if (!ibGib && !addr) { throw new Error(`either ibGib or addr required. (E: c935b51e773f41a2a547c556e9dc16c6)`); }\n        if (ibGib && !ibGib.data) { return false; }\n        addr = addr || getIbGibAddr({ ibGib });\n        const { ib, gib } = getIbAndGib({ ibGibAddr: addr });\n        if (!ib) { return false; }\n        if (!gib) { return false; }\n        if (!ib.startsWith('bin ')) { return false; }\n\n        // at this point any weirdness throws an error, because the ib plainly\n        // indicates this is a bin ibgib.\n\n        if (gib.length !== 64) {\n            throw new Error(`ib starts with \"bin \" but gib length is not 64, so return false. Two things: 1) bin ibgibs are expected to be stones, i.e., have no temporal junction point and only a single punctiliar hash for the gib. the default hash used atow (01/2024) is sha-256, so the length should be 64. But this may not be true if using another hash algorithm. need to change this function when this becomes the case. (W: 60725d65d13c4b4fbb7b96d7feb19d67)`);\n        }\n\n        // tightly coupled here with parsing algorithm\n\n        const ibPieces = ib.split(' ');\n        if (ibPieces.length === 2) {\n            // bin ${binHash}\n            if (!ibPieces[1].match(UUID_REGEXP)) {\n                throw new Error(`(UNEXPECTED) ib starts with \"bin \" but space-delimited !ibPieces[1].match(UUID_REGEXP)? (E: f6baca2ff155f1017b278a5d7597a224)`);\n            }\n        } else if (ibPieces.length === 3) {\n            // could be\n            // bin ${binHash} enc=${binEncoding}\n            // or...\n            // bin ${binHash} ${binExt}\n            if (!ibPieces[1].match(UUID_REGEXP)) {\n                throw new Error(`(UNEXPECTED) ib starts with \"bin \" but space-delimited !ibPieces[1].match(UUID_REGEXP)? (E: 8d0443d6cada4b50be79a8390a7a426c)`);\n            }\n        } else if (ibPieces.length === 4) {\n            if (!ibPieces[1].match(UUID_REGEXP)) {\n                throw new Error(`(UNEXPECTED) ib starts with \"bin \" but space-delimited !ibPieces[1].match(UUID_REGEXP)? (E: 3209eacc0a3848a59593d4c3ee956191)`);\n            }\n            // bin ${binHash} ${binExt} enc=${binEncoding}\n            if (!ibPieces[3].startsWith(\"enc=\")) {\n                throw new Error(`(UNEXPECTED) ib starts with \"bin \" but space-delimited !ibPieces[3].startsWith(\"enc=\")? (E: 4c8a0c3b07a90d30e3d1a4373d57d824)`);\n            }\n        } else {\n            throw new Error(`(UNEXPECTED) ib starts with \"bin \" but space-delimited ibPieces length is not 2, 3 or 4? (E: c7eccf88518304997c7e42b32e08d224)`);\n        }\n\n        // passed gauntlet\n        return true;\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    }\n}\n\n/**\n * Recursively hashes some string {@link recursionCount} number of times.\n */\nexport async function hash16816({\n    s,\n    algorithm,\n    recursionCount,\n    saltPrependedPerHash,\n}: {\n    /**\n     * string to hash\n     */\n    s: string,\n    /**\n     * algorithm to use. defaults to 'SHA-256'\n     */\n    algorithm: HashAlgorithm,\n    /**\n     * number of recursions to do. Defaults to 16816.\n     */\n    recursionCount: number,\n    saltPrependedPerHash: string,\n}): Promise<string> {\n    const lc = `[${hash16816.name}]`;\n    try {\n        saltPrependedPerHash ??= '';\n        recursionCount ??= 16816;\n        algorithm ??= 'SHA-256';\n        let hashed: string = '';\n        if (saltPrependedPerHash) {\n            for (let i = 0; i < recursionCount; i++) {\n                hashed = await hash({ s: saltPrependedPerHash + s, algorithm });\n            }\n        } else {\n            for (let i = 0; i < recursionCount; i++) {\n                hashed = await hash({ s, algorithm });\n            }\n        }\n        return hashed;\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    }\n}\n\n/**\n * creates atow (10/2023) space-delimited ib in the form of `meta special ${type}`.\n *\n * @returns ib for given `type`\n * @throws error if `type` doesn't match {@link SPECIAL_IBGIB_TYPE_REGEXP}\n *\n * @see {@link getSpecialTypeFromIb}\n * @see {@link SPECIAL_IBGIB_TYPE_REGEXP}\n */\nexport function getSpecialIbGibIb({ type }: { type: SpecialIbGibType }): Ib {\n    if (!type.match(SPECIAL_IBGIB_TYPE_REGEXP)) {\n        throw new Error(`special ibgib type must not have spaces and just be alphanumerics. regexp: ${SPECIAL_IBGIB_TYPE_REGEXP.source} (E: 6c1c92521b7f076cc4666e4915593723)`);\n    }\n    return `meta special ${type}`;\n}\n\n/**\n * extracts the {@link SpecialIbGibType} from the given `ib`.\n *\n * @returns type {@link SpecialIbGibType}\n *\n * @see {@link getSpecialIbGibIb}\n * @see {@link SPECIAL_IBGIB_TYPE_REGEXP}\n */\nexport function getSpecialTypeFromIb({ ib }: { ib: Ib }): SpecialIbGibType {\n    const lc = `[${getSpecialTypeFromIb.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: c82ba222bd345ee6b695df4d63a23322)`); }\n        if (!ib) { throw new Error(`ib required (E: 08897145f7138e644fe01c4a59353322)`); }\n        if (!isSpecial({ ib })) { throw new Error(`ib is not special (E: 174aff63b992adff3ac2394643735922)`); }\n        const pieces = ib.split(' ');\n        if (pieces.length < 3) { throw new Error(`invalid ib. should be space-delimited in form of \"meta special [type]\" (E: ffd89e2cbe63427f98634ab897aab222)`); }\n        const specialType = pieces[2];\n        if (!Object.values(SpecialIbGibType).some(x => x === specialType)) {\n            console.warn(`unknown special type (${specialType}). This may be expected, but atow I am adding special types to the SpecialIbGibType enum-like. (W: f4e26c3ebb57fe49d69014a4ba32a922)`);\n        }\n        return (specialType as SpecialIbGibType);\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * gets a special ib and tacks on ^gib for a constant address.\n *\n * used in primitives (ancestors for special ibgibs), as well as as of atow\n * (11/2023) the \"latest\" special ibgib.\n *\n * @returns special IbGibAddr\n */\nexport function getSpecialIbGibAddr({ type }: { type: SpecialIbGibType }): string {\n    const ib = getSpecialIbGibIb({ type });\n    return `${ib}^${GIB}`;\n}\n\nexport function getSpecialConfigKey({ type }: { type: SpecialIbGibType }): string {\n    return `${CONFIG_KEY_ATOM} ${getSpecialIbGibAddr({ type })}`;\n}\n\nexport function isSpecial({ ib, ibGib }: { ib?: Ib, ibGib?: IbGib_V1 }): boolean {\n    if (!ib && !ibGib?.ib) { throw new Error(`either ib or ibGib.ib required (E: b4cf539638d7966c2e351987f55e1a23)`); }\n    return (ib ?? ibGib?.ib)?.startsWith('meta special')!;\n}\n\n/**\n * returns ib for a given root. ATOW this is simply \"root {text}\"\n *\n * @returns ib for the given rootText\n */\nexport function getRootIb(rootText: string): string {\n    const lc = `[${getRootIb.name}]`;\n    if (!rootText) { throw new Error(`${lc} text required.`) }\n    return `root ${rootText}`;\n}\n\n/**\n * Tags for this app have the form: tag [tagText]\n *\n * @param tagText e.g. \"Favorites\"\n *\n * @example\n * For the Favorites tag, the ib would be \"tag Favorites\"\n */\nexport function tagTextToIb(tagText: string): string {\n    const lc = `[${tagTextToIb.name}]`;\n    if (!tagText) { throw new Error(`${lc} tag required.`) }\n    return `tag ${tagText}`;\n}\n\n/**\n * Living: has tjp and dna.\n * Stones: does not have Dna, maybe has tjp.\n *\n * Splits the given `ibGibs` into two maps, one that includes the ibgibs that\n * have a tjp (temporal junction point) AND dna (\"living\") and those that do not\n * have both tjp AND dna (\"stones\").\n *\n * ## notes\n *\n * Having dna implies having a tjp, but the reverse is not necessarily true.\n * Sometimes you want an ibgib that has a tjp so you can, e.g., reference the\n * entire timeline easily.  But at the same time you don't want to keep track of\n * the transforms, perhaps this is because you don't want to be able to merge\n * timelines.\n */\nexport function splitPerTjpAndOrDna({\n    ibGibs,\n    filterPrimitives,\n}: {\n    ibGibs: IbGib_V1[],\n    filterPrimitives?: boolean,\n}): {\n    /** ibgibs have both tjp and dna */\n    mapWithTjp_YesDna: { [gib: string]: IbGib_V1 },\n    /** ibgibs have tjp but NO dna */\n    mapWithTjp_NoDna: { [gib: string]: IbGib_V1 },\n    /** ibgibs that have no tjp (and implicitly no dna) */\n    mapWithoutTjps: { [gib: string]: IbGib_V1 }\n} {\n    const lc = `[${splitPerTjpAndOrDna.name}]`;\n    try {\n        const mapWithTjp_YesDna: { [gib: string]: IbGib_V1 } = {};\n        const mapWithTjp_NoDna: { [gib: string]: IbGib_V1 } = {};\n        const mapWithoutTjps: { [gib: string]: IbGib_V1 } = {};\n        // const mapLivingIbGibs: { [gib: string]: IbGib_V1 } = {};\n        // const mapStoneIbGibs: { [gib: string]: IbGib_V1 } = {};\n        const ibGibsTodo = filterPrimitives ?\n            ibGibs.filter(ibGib => ibGib.gib ?? ibGib.gib !== GIB) :\n            ibGibs;\n        ibGibsTodo.forEach(ibGib => {\n            if (hasTjp({ ibGib })) {\n                if ((ibGib.rel8ns?.dna ?? []).length > 0) {\n                    mapWithTjp_YesDna[ibGib.gib!] = ibGib;\n                } else {\n                    mapWithTjp_NoDna[ibGib.gib!] = ibGib;\n                }\n            } else {\n                mapWithoutTjps[ibGib.gib!] = ibGib;\n            }\n        });\n        return { mapWithTjp_YesDna, mapWithTjp_NoDna, mapWithoutTjps };\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    }\n}\n\n/**\n * Takes incoming `ibGibs`, filters out those that do\n * not have tjps( i.e. non-timelines), and groups\n * the timeline ibgibs by tjp in ascending order.\n *\n * This means that each map entry will be in the form:\n * `[tjpAddr] => [ibgib0 (tjp), ibgib1, ibgib2, ..., ibgibN (latest)]`\n *\n * ## notes\n *\n * * sorts by `ibgib.data.n`. If this is undefined, will not sort in ascending\n *   order properly.\n *\n * @returns filtered, sorted map of incoming `ibGibs` [tjpAddr] => timeline [ibgib0 (tjp), ibgib1, ibgib2, ..., ibgibN (latest)]\n */\nexport function getTimelinesGroupedByTjp({\n    ibGibs,\n}: {\n    /**\n     * group of source ibGibs to filter/group/sort by tjp.\n     */\n    ibGibs: IbGib_V1[],\n}): { [tjpAddr: string]: IbGib_V1[] } {\n    const lc = `[${getTimelinesGroupedByTjp.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting...`); }\n\n        // pull out only the ibgibs in timelines (either is tjp or has tjp)\n        let { mapWithTjp_YesDna, mapWithTjp_NoDna } =\n            splitPerTjpAndOrDna({ ibGibs, filterPrimitives: true });\n        const mapIbGibsWithTjp = { ...mapWithTjp_YesDna, ...mapWithTjp_NoDna };\n        const ibGibsWithTjp = Object.values(mapIbGibsWithTjp);\n\n        const mapTjpTimelines_Ascending = groupBy({\n            items: ibGibsWithTjp,\n            keyFn: x => {\n                // x.data?.isTjp ? getIbGibAddr({ ibGib: x }) : (x.rel8ns?.tjp[0] ?? '') // converting this untested...hmm\n                if (x.data?.isTjp) {\n                    return getIbGibAddr({ ibGib: x });\n                } else if (x.rel8ns?.tjp) {\n                    return x.rel8ns?.tjp[0] ?? '';\n                } else {\n                    if (logalot) { console.log(`${lc} neither isTjp nor x.rel8ns.tjp truthy (I: ec9a5597bf53dec1bd3d83350abbf823)`); }\n                    return '';\n                }\n\n            }\n        });\n\n        if (logalot) { console.log(`${lc} sorting (ascending) ibGibsWithTjpGroupedByTjpAddr: ${pretty(mapTjpTimelines_Ascending)} (I: 9b9fff5ce61444a6cb06d62db9a99422)`); }\n        Object.entries(mapTjpTimelines_Ascending).forEach(([_tjpAddr, timeline]) => {\n            if (timeline.some(ibGib => ibGib.data?.n === undefined)) {\n                console.warn(`${lc} timeline includes ibgibs with ibGib.data?.n === undefined (W: cab9a6b64a38c4279fe82c3569bbab22)`);\n            }\n            // sort mutates array in place\n            timeline.sort((a, b) => (a.data?.n ?? -1) > (b.data?.n ?? -1) ? 1 : -1); // sorts ascending, e.g., 0,1,2...[Highest]\n        });\n        if (logalot) { console.log(`${lc} after sort ibGibsWithTjpGroupedByTjpAddr: ${pretty(mapTjpTimelines_Ascending)} (I: 9b9fff5ce61444a6cb06d62db9a99422)`); }\n\n        return mapTjpTimelines_Ascending; // ascending\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * Helper function that checks the given `ibGib` to see if it\n * either has a tjp or is a tjp itself.\n *\n * ## notes\n *\n * Only unique ibGibs are meant to have tjps, or rather, if an\n * ibGib timeline is expected to be unique over \"time\", then the\n * tjp is an extremely convenient mechanism that provides a\n * \"name\" for that timeline.\n *\n * Otherwise, if they are not unique, then successive \"different\"\n * timelines cannot be easily referenced by their first unique\n * frame in time, making it much harder to pub/sub updates among\n * other things. (If there are no unique frames, then they are\n * the same ibGib.)\n *\n * ## tjp = temporal junction point\n *\n * I've written elsewhere on this as well. Refer to B2tF2.\n *\n * @returns true if the ibGib has/is a tjp, else false\n */\nexport function hasTjp({ ibGib }: { ibGib: IbGib_V1 }): boolean {\n    const lc = `[${hasTjp.name}]`;\n\n    if (!ibGib) { throw new Error(`(UNEXPECTED) ibGib falsy? (E: ce3a59f9db14e6158bb2c438ca1a3823)`); }\n\n    // most likely is that rel8ns.tjp has an entry or the internal data.isTjp\n    if ((ibGib.rel8ns?.tjp?.length ?? 0) > 0 || ibGib.data?.isTjp) {\n        return true; /* <<<< returns early */\n    }\n\n    // dna transforms do not have tjp\n    const dnaPrimitives = ['fork^gib', 'mut8^gib', 'rel8^gib'];\n    if ((ibGib.rel8ns?.ancestor ?? []).some(x => dnaPrimitives.includes(x))) {\n        return false; /* <<<< returns early */\n    }\n\n    if (!ibGib.gib) {\n        console.warn(`${lc} ibGib.gib falsy. (W: 6400d780822b44d992846f1196509be3)`);\n        return false; /* <<<< returns early */\n    }\n    if (ibGib.gib.includes(GIB_DELIMITER)) {\n        return true; /* <<<< returns early */\n    }\n\n    if (ibGib.gib === GIB) {\n        // primitive\n        return false; /* <<<< returns early */\n    }\n\n    // at this point, we've already determined most likely what the result is.\n    // definitively, we'll pass the buck to getGibInfo in case implementation\n    // details change in the future.  it is a more expensive call.  could\n    // possibly just return false at this point, but since gib info would change\n    // if we change our standards for gib, this is nicer.\n    const gibInfo = getGibInfo({ ibGibAddr: getIbGibAddr({ ibGib }) });\n    return !!gibInfo.tjpGib;\n}\n\nexport function hasDna({ ibGib }: { ibGib: IbGib_V1 }): boolean {\n    const lc = `[${hasDna.name}]`;\n\n    if (!ibGib) {\n        console.warn(`${lc} ibGib falsy. (W: 5fd19751f5c84da59d83dd33487ed859)`);\n        return false;\n    }\n\n    return (ibGib.rel8ns?.dna ?? []).length > 0;\n}\n\n/**\n * Extracts the tjp addr from the ibgib record. If there is no tjp addr found,\n * then refers to `defaultIfNone` arg to determine if it returns undefined or\n * the incoming ibgib's addr.\n * @returns extracted tjp addr or undefined, depending on if found and defaultIfNone value\n */\nexport function getTjpAddr({\n    ibGib,\n    defaultIfNone = 'undefined',\n}: {\n    ibGib: IbGib_V1,\n    defaultIfNone?: 'incomingAddr' | 'undefined',\n}): IbGibAddr | undefined {\n    const lc = `[${getTjpAddr.name}]`;\n    try {\n        const tjpMap = getTjpAddrs({ ibGibs: [ibGib], defaultIfNone });\n        return tjpMap && Object.keys(tjpMap).length === 1 ? Object.values(tjpMap)[0] : undefined;\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    }\n}\n\n/**\n * builds a map of the given ibgib's addrs to each's corresponding tjp addr.\n *\n * @returns a map of ibgib addr -> tjp addr\n */\nexport function getTjpAddrs({\n    ibGibs,\n    defaultIfNone = 'undefined',\n}: {\n    ibGibs: IbGib_V1[],\n    defaultIfNone?: 'incomingAddr' | 'undefined',\n}): { [ibGibAddr: IbGibAddr]: IbGibAddr | undefined } {\n    const lc = `[${getTjpAddrs.name}]`;\n    try {\n        const resultMap: { [ibGibAddr: IbGibAddr]: IbGibAddr | undefined } = {};\n\n        ibGibs.forEach(ibGib => {\n            let ibGibAddr = getIbGibAddr({ ibGib });\n            let tjpAddr: IbGibAddr | undefined;\n            if (ibGib.rel8ns?.tjp?.length ?? 0 > 0) {\n                // get the last tjp addr atow\n                tjpAddr = ibGib.rel8ns!.tjp![ibGib.rel8ns!.tjp!.length - 1];\n            } else if (ibGib.data?.isTjp || defaultIfNone === 'incomingAddr') {\n                // either the incoming addr is the tjp or we're defaulting to it per defaultIfNone arg\n                tjpAddr = ibGibAddr;\n            } else {\n                // explicitly set to undefined per defaultIfNone arg\n                tjpAddr = undefined;\n            }\n            resultMap[ibGibAddr] = tjpAddr;\n        });\n\n        return resultMap;\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    }\n}\n\n/**\n * Returns true if the given {@param ibGib} is the temporal junction\n * point for a given ibGib timeline.\n */\nexport async function isTjp_Naive({\n    ibGib,\n    naive = true,\n}: {\n    ibGib: IbGib_V1<any>,\n    naive?: boolean,\n}): Promise<boolean> {\n    const lc = `[${isTjp_Naive.name}]`;\n    try {\n        if (!ibGib) { throw new Error('ibGib required.'); }\n        if (naive) {\n            if (ibGib.data) {\n                if (ibGib.data.isTjp) { return true; }\n                if (!ibGib.rel8ns) {\n                    if (logalot) { console.log(`${lc} ibGib.rel8ns falsy (I: c69c9e78b34845311ce7c674d7195622)`); }\n                    return false;\n                }\n                if (ibGib.rel8ns.past && ibGib.rel8ns.past.length > 0) { return false; }\n                if (ibGib.rel8ns.past && ibGib.rel8ns.past.length === 0) { return true; }\n                return false;\n            } else {\n                throw new Error('loaded ibGib required (data).');\n            }\n        } else {\n            throw new Error('only naive implemented right now.');\n        }\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    }\n}\n\nexport function toDto<TData = IbGibData_V1, TRel8ns extends IbGibRel8ns_V1 = IbGibRel8ns_V1>({\n    ibGib,\n}: {\n    ibGib: IbGib_V1,\n}): IbGib_V1<TData, TRel8ns> {\n    const lc = `[${toDto.name}]`;\n    if (!ibGib.ib) { console.warn(`${lc} ibGib.ib is falsy. (W: e60e41c2a1fc48268379d88ce13cb77b)`); }\n    if (!ibGib.gib) { console.warn(`${lc} ibGib.gib is falsy. (W: fb3889cbf0684ae4ac51e48f28570377)`); }\n\n\n    let dtoIbGib: IbGib_V1<TData, TRel8ns> = { ib: (ibGib.ib || '').slice() };\n    if (ibGib.gib) { dtoIbGib.gib = ibGib.gib.slice(); };\n    if (ibGib.data) {\n        if (isBinary({ ibGib })) {\n            // binary has data of Uint8Array atow (02/2024)\n            dtoIbGib.data = (ibGib.data as Uint8Array).slice() as any;\n        } else {\n            dtoIbGib.data = clone(ibGib.data);\n        }\n    }\n    if (ibGib.rel8ns) { dtoIbGib.rel8ns = clone(ibGib.rel8ns); }\n\n    return dtoIbGib;\n}\n\n/**\n * helpful for differentiating discriminated unions.\n *\n * technically, atow, anything with an ib meets the minimum requirements for an\n * ibgib. this is because you can think of any value as being a metadata\n * \"header\" with other derivative & metadatas as being absent.\n *\n * For example, a string value \"my string yo\" is all you have to go on if you\n * don't have a hash which would be metadata about that value. its address would\n * be \"my string yo^gib\" as it's a primitive, and its intrinisic data would just\n * be a duplicate of the ib, so it's left undefined, and there are no extrinsic\n * rel8ns so rel8ns would be undefined.\n *\n * ## driving use case\n *\n * In doing rxjs replacement, I'm needing to tell if an error coming down the\n * pipe is ErrorIbGib_V1 | Error | string.\n *\n * @param obj any object. note: if falsy, returns false\n * @returns true if the obj is an ibgib, else false\n */\nexport function isIbGib(obj: any): boolean {\n    const lc = `[${isIbGib.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 57aef93fc6cc2309523b5c72a6b11823)`); }\n        // technically\n        return !!obj && typeof obj.ib === 'string';\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * extracts timestamp info from the given `ibGib`.\n *\n * ## about\n *\n * not all ibGibs have timestamps (data.timestamp) and they may be in the form\n * of a timestamp string. this may actually be a timestamp string for a Date\n * object or it could be a string of ticks from date.getTime(). or maybe\n * downstream someone just does a number instead of a string.\n *\n * so this function is supposed to be good at figuring this out given an\n * `ibGib`.\n *\n * ## todo\n *\n * 1. we could add an optional path parameter that allows us to specify the\n * path(s) of things that should be timestamps.\n *\n * 2. we could have a simple extractTimestamp(value: any) that does the same\n * thing and then call that from this function.\n *\n * @returns info object that has the timestamp in various formats (if valid) or an error msg (if invalid)\n */\nexport function getTimestampInfo({\n    ibGib,\n    data,\n    timestamp,\n}: {\n    // /**\n    //  * ibGib from which we are extracting timestamp info.\n    //  */\n    ibGib?: IbGib_V1;\n    data?: IbGibData_V1;\n    timestamp?: string;\n}): {\n    valid: true;\n    date: Date,\n    utc: string,\n    ticks: string,\n    ms: number | undefined;\n} | {\n    valid: false;\n    emsg: string;\n} {\n    const lc = `[${getTimestampInfo.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 35cb68744bcf6139d78e37de644fad23)`); }\n\n        timestamp = timestamp || data?.timestamp || ibGib?.data?.timestamp;\n        const ms = ibGib?.data?.timestampMs || data?.timestampMs;\n\n        // ensure timestamp truthy\n        if (!timestamp) {\n            const emsg = `${lc} timestamp is falsy. (W: 5f1f1182c8804807b886a3d922ac3dcf)`;\n            console.warn(emsg);\n            return { valid: false, emsg }; /* <<<< returns early */\n        }\n\n        // we have a timestamp, but no idea what it actually is. supposed to be\n        // a string with either a utc timestamp or a number, but check for other\n        // cases as well\n\n        // try it as a timestamp string\n        if (typeof timestamp === 'string') {\n            if (Number.isInteger(Number.parseInt(timestamp))) {\n\n                // #region maybe ticks string\n                const parsedTimestamp = Number.parseInt(timestamp);\n                let date = new Date();\n                date.setTime(parsedTimestamp);\n                if (date.toString() !== INVALID_DATE_STRING) {\n                    // valid timestampInTicks string\n                    if (logalot) { console.log(`${lc} valid timestampInTicks string (I: 7069a1c3047f3bbc92b78674b20f5b23)`); }\n                    return {\n                        valid: true,\n                        date,\n                        utc: date.toUTCString(),\n                        ticks: date.getTime().toString(),\n                        ms,\n                    }; /* <<<< returns early */\n                } else {\n                    const emsg = `${lc} data.timestamp (${timestamp}) is an integer string but not a valid timestampInTicks string. (produces invalid date) (E: f49fbb600fe1426c8805dfc8afbe5cf3)`;\n                    console.error(emsg);\n                    return { valid: false, emsg }; /* <<<< returns early */\n                }\n                // #endregion maybe ticks string\n            } else {\n                // #region maybe timestamp string\n                let date = new Date(timestamp);\n                if (date.toString() !== INVALID_DATE_STRING) {\n                    // valid timestamp string (may or may not be UTC)\n                    return {\n                        valid: true,\n                        date,\n                        utc: date.toUTCString(),\n                        ticks: date.getTime().toString(),\n                        ms,\n                    }; /* <<<< returns early */\n                } else {\n                    const emsg = `${lc} data.timestamp is a non-integer string but not a valid date timestamp string (new date instantiated produces invalid date). (W: c6c90f7f3bfb49838d2081ba84fdb5fb)`;\n                    console.warn(emsg)\n                    return { valid: false, emsg }; /* <<<< returns early */\n                }\n                // #endregion maybe timestamp string\n            }\n        } else if (typeof (timestamp as any) === 'number') {\n            if (Number.isInteger(timestamp)) {\n                console.warn(`${lc} expected data.timestamp to be a string but is a number (W: 9d786f4d4e8d4279b5af7bee19bf721b)`);\n                let date = new Date();\n                date.setTime(timestamp as number);\n                if (date.toString() !== INVALID_DATE_STRING) {\n                    // valid timestamp string\n                    return {\n                        valid: true,\n                        date,\n                        utc: date.toUTCString(),\n                        ticks: date.getTime().toString(),\n                        ms,\n                    }; /* <<<< returns early */\n                } else {\n                    const emsg = `${lc} timestamp (${timestamp}) is an integer number but not a valid timestampInTicks (new date setTime produces invalid date). (W: c6c90f7f3bfb49838d2081ba84fdb5fb)`;\n                    console.warn(emsg)\n                    return { valid: false, emsg }; /* <<<< returns early */\n                }\n            } else {\n                // number but not integer? hmm\n                const emsg = `${lc} timestamp (${timestamp}) is a non-integer number (supposed to be a string either timestamp string or ticks). (E: 2963d95f8d3b464c992b0bff948b4479)`;\n                console.error(emsg)\n                return { valid: false, emsg }; /* <<<< returns early */\n            }\n        } else {\n            const emsg = `${lc} unknown typeof timestamp (${typeof timestamp}). (E: 12458a9c16c84e4f859b5771a30dd2ef)`;\n            console.error(emsg);\n            return { valid: false, emsg }; /* <<<< returns early */\n        }\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * First we combine {@link readCache_graph} and {@link readCache_array} into\n * one unified cache. This can even be empty (if both empty/falsy).\n *\n * Then looks in {@link space} for all other addrs (throws if *any* not found).\n *\n * Then creates the result array, which will be in the same order as incoming\n * {@link addrs} (so this acts like a fancy .map() call).\n *\n * @throws if any addr is not found\n *\n * ## notes\n *\n * Since you can pass in empty cache(s), you can actually use this as a generic\n * getIbGibs function that throws if you don't want to use `getFromSpace` and\n * parse the results. (which is what I find I want more and more the lazier I\n * get).\n */\nexport async function getIbGibsFromCache_fallbackToSpaces({\n    addrs,\n    readCache_graph,\n    readCache_array,\n    space,\n}: {\n    addrs: IbGibAddr[],\n    readCache_graph?: FlatIbGibGraph,\n    readCache_array?: IbGib_V1[],\n    space: IbGibSpaceAny,\n}): Promise<IbGib_V1[]> {\n    const lc = `[${getIbGibsFromCache_fallbackToSpaces.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 5db66871239dfa05182277f886a20926)`); }\n        readCache_graph ??= {};\n        readCache_array ??= [];\n\n        /**\n         * we're going to put all ibgibs into this graph. IOW, we'll start with\n         * incoming caches, then get all other addrs not found here from the\n         * space in a single call. At that point, we'll be able to create the\n         * result array.\n         */\n        const allIbGibs_graph = { ...readCache_graph };\n        readCache_array.forEach(x => allIbGibs_graph![getIbGibAddr({ ibGib: x })] = x);\n\n        const allCachedAddrs = Object.keys(readCache_graph);\n        const addrsNotFoundInCache = addrs.filter(x => !allCachedAddrs.includes(x));\n\n\n        if (addrsNotFoundInCache.length > 0) {\n            if (logalot) { console.log(`${lc} ${addrsNotFoundInCache.length} addrsNotFoundInCache: ${addrsNotFoundInCache} (I: fccbd18116ffb849f813aaebfc6c0826)`); }\n\n            /**\n             * I changed this to spaces for a workaround but I am putting back\n             * the signature to the single space. But I kind of like the idea of\n             * this being able to pull from multiple spaces, so I'm leaving the\n             * logic here for future.\n             */\n            const spaces = [space];\n            let addrsStillNotFound = addrsNotFoundInCache.concat();\n            for (const space of spaces) {\n                const resGet = await getFromSpace({ addrs: addrsStillNotFound, space });\n                if (resGet.success && resGet.ibGibs && resGet.ibGibs.length === addrsStillNotFound.length) {\n                    resGet.ibGibs.forEach(x => allIbGibs_graph![getIbGibAddr({ ibGib: x })] = x);\n                    addrsStillNotFound = [];\n                } else {\n                    // might have gotten some ibgibs\n                    if (resGet.ibGibs && resGet.ibGibs.length > 0) {\n                        addrsStillNotFound =\n                            addrsStillNotFound.filter(addr =>\n                                !resGet.ibGibs!.some(gottenIbGib => getIbGibAddr({ ibGib: gottenIbGib }) === addr)\n                            );\n                        if (addrsStillNotFound.length === 0) {\n                            break;\n                        }\n                    } else {\n                        if (logalot) { console.log(`${lc} no addrs found in space (${space.ib}). trying next space. (I: 4f99d8bacbb10ab3f8737a752564b326)`); }\n                    }\n                }\n            }\n\n            if (addrsStillNotFound.length > 0) {\n                throw new Error(`could not get all addrs from cache or spaces. addrsStillNotFound: ${addrsStillNotFound}. spaces: ${spaces.map(x => x.ib).join('|')} (E: 0c6418f83dd85bda886e56f5b98f3126)`);\n            }\n        }\n\n        // at this point, we're guaranteed to have all addrs in allIbGibs_graph,\n        // but we will still check\n\n        const resIbGibs: IbGib_V1[] = [];\n        for (const addr of addrs) {\n            // refactor this later to be less defensive if this stands the test\n            // of time. (ATOW 01/28/2026)\n            const ibGib = allIbGibs_graph[addr];\n            if (!ibGib) { throw new Error(`(UNEXPECTED) allIbGibs_graph doesn't have addr? We're expecting logic to preclude this at this point. addr: ${addr} (E: f68e1d236ae5e3eb08da9933c8230626)`); }\n            resIbGibs.push(ibGib);\n        }\n\n        return resIbGibs;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * naive general purpose helper guard function based off of a given ibgib's\n * `ib` property.\n *\n * uses conventional V1 `ib` schema, expecting space-delimited `ib` with the\n * first piece being the atom.\n *\n * @param x - any object, usually known to be an ibgib\n * @param atom - the expected atom that determines the type of ibgib\n * @returns true if `x.ib` contains `atom` and thus is `TIbGib`, else false\n */\nexport function isIbGibWithAtom<TIbGib extends IbGib_V1>(x: any, atom: string): x is TIbGib {\n    const lc = `[${isIbGibWithAtom.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: e946f8ca70b65e6968bd8e78aa473826)`); }\n\n        if (!x.ib) {\n            return false; /* <<<< returns early */\n        }\n\n        if (typeof x.ib !== 'string') {\n            return false; /* <<<< returns early */\n        }\n\n        const [pieceAtom, ...otherPieces] = x.ib.split(' ');\n\n        if (atom !== pieceAtom) {\n            return false; /* <<<< returns early */\n        }\n\n        return true;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n", "import { tagTextToIb } from \"@ibgib/core-gib/dist/common/other/ibgib-helper.mjs\";\nimport { ZERO_SPACE_ID } from \"@ibgib/core-gib/dist/witness/space/space-constants.mjs\";\nimport { IbGibAmbientContextConfig } from \"@ibgib/web-gib/dist/app-bootstrap/types.mjs\";\n\nexport const GLOBAL_LOG_A_LOT = false;\nexport const GLOBAL_TIMER_NAME = '[blank^gib timer]';\n\n\n/**\n * I'm debating whether or not to have a single db.\n */\nexport const BLANK_GIB_DB_NAME = 'blank^gib';\n/**\n * don't remember why this is named this\n */\nexport const ARMY_STORE = 'army store';\n/**\n * don't remember why this is named this\n */\nexport const BEE_KEY = 'bee key';\nexport const BLANK_GIB_INDEXEDDB_KEY_LOCAL_SPACE_NAME = 'local_space_name';\n/**\n * user's default local space will be first initialized on first visit to this\n * plus some random id.\n */\nexport const BLANK_GIB_INDEXEDDB_LOCAL_SPACE_NAME_PREFIX = 'ibgib_dot_com';\n\n/**\n * Ambient context configuration for the blank-gib app.\n * Uses existing constant values to maintain storage compatibility.\n */\nexport const APP_CONFIG: IbGibAmbientContextConfig = {\n    dbName: BLANK_GIB_DB_NAME,\n    storeName: ARMY_STORE,\n    apiKeyName: BEE_KEY,\n    additionalStoreNames: [ZERO_SPACE_ID], // ZERO_SPACE_ID from core-gib is usually 'zero_space'\n};\n\n/**\n * regex for what we think of as a gemini api key.\n */\nexport const GEMINI_API_KEY_REGEXP = /^[a-zA-Z0-9\\-_]{32,64}$/;\nexport const CONFIG_OPTION_GEMINI_API_KEY_LOCATION_HELP = `Gemini API Key Config option (\u2699\uFE0F icon in the top right)`;\n\n/**\n * if the app should show expand panels animation\n */\nexport const KEY_TUTORIAL_PANELS_EXPAND_ANIMATION_COUNT = 'tutorial panels expand animation count';\nexport const TUTORIAL_PANELS_EXPAND_ANIMATION_COUNT_ENOUGH_ALREADY = 3;\n\n/**\n * this is used to differentiate the shell from embedded sites. I can't just\n * test for iframe embedded because project idx shows the entire app in an\n * iframe, and this throws things off.\n */\nexport const HTML_META_APP_ID_NAME = \"ibgib-app-id\";\n/**\n * @see {@link HTML_META_APP_ID_NAME}\n */\nexport const HTML_META_APP_ID_CONTENT = \"8d6217327e6490650169be9cb22a0b25\";\n\n/**\n * used for the agent tag, in ibgib.data.text\n */\nexport const TAG_AGENT_TEXT = \"agent\";\n/**\n * used for the agent tag, in ibgib.data.icon\n */\nexport const TAG_AGENT_ICON = \"body-outline\";\n/**\n * used for the agent tag, in ibgib.data.description\n */\nexport const TAG_AGENT_DESCRIPTION = \"This tag tracks the active agents for the current local user space.\";\n/**\n * the ib value of the tag ibgib for the agents.\n */\nexport const TAG_AGENT_IB = tagTextToIb(TAG_AGENT_TEXT);\n\nexport const DEFAULT_IBGIB_COLOR = '#78f87e88';\nexport const DEFAULT_IBGIB_TRANSLUCENT = '#78f87e10';\nexport const DEFAULT_IBGIB_COLOR_CONTRAST = '#ffffff';\nexport const DEFAULT_TJP_COLOR = '#78f87e88';\nexport const DEFAULT_TJP_COLOR_TRANSLUCENT = '#78f87e10';\nexport const DEFAULT_TJP_COLOR_CONTRAST = '#ffffff';\n\n/**\n * I am toying with tagging hardcoded prompts at the moment (atow 05/2025)\n */\nexport const HARDCODED_PROMPT_TAG_TEXT = 'AUTOMATED_TEXT';\n", "import { extractErrorMsg } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\n\nimport { GLOBAL_LOG_A_LOT } from \"../../core-constants.mjs\";\nimport { FlatIbGibGraph } from \"./graph-types.mjs\";\nimport { SerializedUint8Array } from \"./other-types.mjs\";\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\n/**\n * @internal Helper to convert a Uint8Array to a Base64 string\n * @param uint8Array @\n * @returns Base64 string\n */\nfunction uint8ArrayToBase64(uint8Array: Uint8Array): Promise<string> {\n    return new Promise((resolve, reject) => {\n        const blob = new Blob([uint8Array as any], { type: 'application/octet-stream' });\n        const reader = new FileReader();\n        reader.onload = () => {\n            const dataUrl = reader.result as string;\n            // The result is a data URL: \"data:application/octet-stream;base64,...\"\n            // We only want the Base64 part.\n            const base64String = dataUrl.split(',')[1];\n            resolve(base64String);\n        };\n        reader.onerror = (error) => reject(error);\n        reader.readAsDataURL(blob);\n    });\n}\n\n/**\n * @internal Helper to convert a Base64 string back to a Uint8Array\n * @param base64String to convert back to Uint8Array\n * @returns Uint8Array\n */\nasync function base64ToUint8Array(base64String: string): Promise<Uint8Array> {\n    // Use the fetch API to decode the Base64 string.\n    // This is a modern and robust way to handle Base64 in the browser.\n    const dataUrl = `data:application/octet-stream;base64,${base64String}`;\n    const response = await fetch(dataUrl);\n    const blob = await response.blob();\n    const buffer = await blob.arrayBuffer();\n    return new Uint8Array(buffer);\n}\n\nexport async function serializeGraphToString({ graph }: { graph: FlatIbGibGraph }): Promise<string> {\n    const lc = `[${serializeGraphToString.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 4ddb8803cf68e1d3d35f60680cb69825)`); }\n\n        // 1. Serialize: Create a JSON-safe representation of the graph\n        // We use a custom replacer to handle Uint8Array\n        // const replacer = (key: string, value: any) => {\n        //     if (value instanceof Uint8Array) {\n        //         // This part is async, so we can't use it directly in JSON.stringify.\n        //         // We must pre-process the object first.\n        //         throw new Error(\"Cannot use async replacer. Pre-process the object first.\");\n        //     }\n        //     return value;\n        // };\n\n        // Pre-process the graph to handle async Base64 conversion\n        const serializableGraph = JSON.parse(JSON.stringify(graph)); // Deep clone to avoid mutation\n        for (const key in serializableGraph) {\n            if (graph[key].data instanceof Uint8Array) {\n                serializableGraph[key].data = {\n                    _dataType: 'Uint8Array_Base64',\n                    value: await uint8ArrayToBase64(graph[key].data as Uint8Array)\n                } as SerializedUint8Array;\n            }\n        }\n\n        // 2. Stringify: Convert the serializable object to a JSON string\n        const jsonString = JSON.stringify(serializableGraph);\n\n        if (logalot) { console.log(`${lc} jsonString.length: ${jsonString.length} (I: 56dec8ad0931ab8ba9b5ca3d4e66be25)`); }\n\n        return jsonString;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * Takes an incoming jsonString created via {@link serializeGraphToString}\n * and returns the original FlatIbGibGraph dto.\n *\n * @param jsonString\n * @returns graph that was originally serialized\n *\n * ## notes\n *\n * This serialize/deserialize is used in the compress/decompress fns:\n *\n * @see {@link compressIbGibToBlob}\n * @see {@link decompressIbGibFromBlob}\n * @see {@link compressIbGibGraphToString}\n * @see {@link decompressIbGibGraphFromString}\n */\nexport async function deserializeStringToGraph({ jsonString }: { jsonString: string }): Promise<FlatIbGibGraph> {\n    const lc = `[${deserializeStringToGraph.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 52e1a1fb1adcc75168fbc6d819868825)`); }\n\n        const reviver = (key: string, value: any) => {\n            if (value && value._dataType === 'Uint8Array_Base64') {\n                // Converting base64 to Uint8Array is async, so we can't use it\n                // in JSON.parse. We will post-process the object.\n                return value; // Return the placeholder for now\n            }\n            return value;\n        };\n\n        const parsedGraph = JSON.parse(jsonString, reviver);\n\n        // Post-process to convert Base64 back to Uint8Array\n        for (const key in parsedGraph) {\n            const data = parsedGraph[key].data;\n            if (data && data._dataType === 'Uint8Array_Base64') {\n                parsedGraph[key].data = await base64ToUint8Array(data.value);\n            }\n        }\n\n        return parsedGraph as FlatIbGibGraph;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * Compresses an FlatIbGibGraph object into a Blob.\n * @param graph The FlatIbGibGraph object to compress.\n * @returns A Promise that resolves with the compressed Blob.\n */\nexport async function compressIbGibToBlob(graph: FlatIbGibGraph): Promise<Blob> {\n    const lc = `[${compressIbGibToBlob.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 8d306868b718596fe8f562bd5118d825)`); }\n\n        // 1. Serialize: Create a JSON-safe representation of the graph and stringify\n        const jsonString = await serializeGraphToString({graph});\n\n        // 2. Encode: Convert the string to a Uint8Array (UTF-8)\n        const dataToCompress = new TextEncoder().encode(jsonString);\n\n        // 3. Compress: Use the Compression Streams API\n        const stream = new Response(dataToCompress).body!;\n        const compressedStream = stream.pipeThrough(new CompressionStream('gzip'));\n\n        // Return the compressed data as a Blob\n        return await new Response(compressedStream).blob();\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * Decompresses a Blob back into an FlatIbGibGraph object.\n * @param compressedBlob The Blob containing the compressed graph data.\n * @returns A Promise that resolves with the original FlatIbGibGraph object.\n */\nexport async function decompressIbGibFromBlob(compressedBlob: Blob): Promise<FlatIbGibGraph> {\n    // 1. Decompress: Use the Decompression Streams API\n    const decompressedStream = compressedBlob.stream().pipeThrough(\n        new DecompressionStream('gzip')\n    );\n\n    // 2. Decode: Convert the decompressed stream back to a string\n    const jsonString = await new Response(decompressedStream).text();\n\n    // 3. Deserialize: Parse the JSON with a reviver to restore Uint8Arrays\n    const parsedGraph = await deserializeStringToGraph({jsonString});\n    return parsedGraph;\n}\n\n/**\n * Compresses an FlatIbGibGraph object and returns a Base64 string representation.\n * @param graph The FlatIbGibGraph object to compress.\n * @returns A Promise that resolves with the compressed data as a Base64 string.\n */\nexport async function compressIbGibGraphToString({\n    graph\n}: {\n    graph: FlatIbGibGraph\n}): Promise<string> {\n    const lc = `[${compressIbGibGraphToString.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 1352f8540c08f0b725952df8f18c4825)`); }\n\n        // 1. Get the compressed data as a Blob first.\n        const compressedBlob = await compressIbGibToBlob(graph);\n\n        // 2. Convert the Blob's binary data to a Uint8Array.\n        const buffer = await compressedBlob.arrayBuffer();\n        const uint8Array = new Uint8Array(buffer);\n\n        // 3. Convert that Uint8Array to a Base64 string.\n        return await uint8ArrayToBase64(uint8Array);\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * Decompresses a Base64 string back into an FlatIbGibGraph object.\n * @param compressedBase64 The Base64 string containing the compressed graph data.\n * @returns A Promise that resolves with the original FlatIbGibGraph object.\n */\nexport async function decompressIbGibGraphFromString({\n    compressedBase64,\n}: {\n    compressedBase64: string,\n}): Promise<FlatIbGibGraph> {\n    const lc = `[${decompressIbGibGraphFromString.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 5f3fa940a2c8f8d7b877978ae7f87825)`); }\n\n        // 1. Convert the Base64 string back to a Uint8Array.\n        const compressedUint8Array = await base64ToUint8Array(compressedBase64);\n\n        // 2. Create a Blob from the Uint8Array.\n        // The MIME type isn't strictly necessary for DecompressionStream but is good practice.\n        const compressedBlob = new Blob([compressedUint8Array as any], { type: 'application/gzip' });\n\n        // 3. Use our existing function to decompress the Blob.\n        return await decompressIbGibFromBlob(compressedBlob);\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n", "export const RAW_EXPORT_ATOM = 'export';\n", "import { extractErrorMsg, getSaferSubstring, getTimestamp, getTimestampInTicks } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { Ib, IbGibAddr } from \"@ibgib/ts-gib/dist/types.mjs\";\nimport { getIbAndGib, getIbGibAddr } from \"@ibgib/ts-gib/dist/helper.mjs\";\nimport { getGib, getGibInfo } from \"@ibgib/ts-gib/dist/V1/transforms/transform-helper.mjs\";\nimport { validateIbGibIntrinsically } from \"@ibgib/ts-gib/dist/V1/validate-helper.mjs\";\n\nimport { GLOBAL_LOG_A_LOT } from \"../../core-constants.mjs\";\nimport { RawExportData_V1, RawExportIbGib_V1, RawExportIbInfo } from \"./import-export-types.mjs\";\nimport { RAW_EXPORT_ATOM } from \"./import-export-constants.mjs\";\nimport { IbGib_V1 } from \"@ibgib/ts-gib/dist/V1/types.mjs\";\nimport { MetaspaceService } from \"../../witness/space/metaspace/metaspace-types.mjs\";\nimport { IbGibSpaceAny } from \"../../witness/space/space-base-v1.mjs\";\nimport { compressIbGibGraphToString, serializeGraphToString } from \"../other/other-helper.web.mjs\";\nimport { getTjpAddr } from \"../other/ibgib-helper.mjs\";\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\n/**\n * builds the ib for a {@link RawExportIbGib_V1}\n */\nexport function getRawExportIb({\n    data,\n}: {\n    data: RawExportData_V1,\n}): Ib {\n    const lc = `[${getRawExportIb.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 158dfaeb9613a1531be71a9735184624)`); }\n        const { graphSize, dependencyGraphAsString, timestamp } = data;\n        const graphStringLength = dependencyGraphAsString.length;\n        const timestampInTicks = getTimestampInTicks(timestamp);\n        const compressDescription = data.compression === 'gzip' ? 'gzip' : 'raw';\n\n        if (!data.timestamp) { throw new Error(`(UNEXPECTED) data.timestamp falsy? (E: 2f5bc88488cbf260634239a8a8396825)`); }\n        const date = new Date(data.timestamp);\n\n        const { ib, gib } = getIbAndGib({ ibGibAddr: data.contextIbGibAddr });\n        const gibInfo = getGibInfo({ gib });\n        const tjpGib = gibInfo.tjpGib ?? gib;\n\n        /**\n         * make it easiest to sort in a file explorer but still be readable.\n         *\n         * timestampInTicks is not easily human-readable\n         */\n        const dateString =\n            date.toISOString().slice(0, 19)\n                .replace('T', '_').replace(/:/g, '').replace(/ /g, '_');\n        // it's just too much to include the entire ib as well I think\n        // let safeSubtextOfThisIb = getSaferSubstring({\n        //     text: ib.replace(' ', '___'),\n        //     length: 20, // wth\n        // });\n\n        return `${RAW_EXPORT_ATOM} ${dateString} ${compressDescription} ${graphSize} ${graphStringLength} ${tjpGib}`;\n\n        // let exportIb = `ibgib_export ${nowString} ${compress ? 'gzip' : 'raw'} ${safeSubtextOfThisIb} ${gib}`;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * space-delimited info contained in ib.\n *\n * atow (06/2025)\n *   `${RAW_EXPORT_ATOM} ${dateString} ${compressDescription} ${graphSize} ${graphStringLength} ${tjpGib}`;\n * OLD (02/2024)\n *   `${RAW_EXPORT_ATOM} ${timestampInTicks} ${graphSize} ${graphStringLength}`\n */\nexport function parseRawExportIb({\n    ib,\n}: {\n    ib: Ib,\n}): RawExportIbInfo {\n    const lc = `[${parseRawExportIb.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 3297e51184f87a45d343d8654b165324)`); }\n        const [atom, dateString, compressDescription, graphSizeStr, graphStringLengthStr, tjpGib] = ib.split(' ');\n        if (atom !== RAW_EXPORT_ATOM) { throw new Error(`atom (${atom}) !== ${RAW_EXPORT_ATOM} (E: ad7545da5b8c4baeb15d86e92d657524)`); }\n        const graphSize = Number.parseInt(graphSizeStr);\n        if (Number.isNaN(graphSize) || graphSize < 0) { throw new Error(`graphSize (${graphSizeStr}) is not a positive integer. (E: 2b43d9d3462f6e16547b121bccef9b24)`); }\n\n        const graphStringLength = Number.parseInt(graphStringLengthStr);\n        if (Number.isNaN(graphStringLength) || graphStringLength < 0) { throw new Error(`graphStringLength (${graphStringLengthStr}) is not a positive integer. (E: 112ceccee1a54b19ab4f4662b6694ba0)`); }\n\n        const compression = compressDescription === 'gzip' ? 'gzip' : undefined;\n\n        return { atom, dateString, graphSize, graphStringLength, compression, tjpGib, };\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport interface GetRawExportIbGibOpts {\n    ibGib: IbGib_V1,\n    metaspace: MetaspaceService,\n    space: IbGibSpaceAny,\n    live: boolean;\n    compress?: boolean;\n    /**\n     * if true, will ignore as much errors as possible to try to get as much data exported as possible.\n     */\n    ignoreErrors?: boolean;\n    // /**\n    //  * If true, then the export should disassociate from its past and ancestor rel8ns.\n    //  */\n    // detach?: boolean;\n    // detachRel8nNames?: string[];\n}\nexport interface ExportErrorInfo {\n    errorMsg: string;\n    ibGibAddr?: IbGibAddr;\n    rawError?: any;\n}\n/**\n * this should be an ibgib right?\n */\nexport interface GetRawExportIbGibResult {\n    rawExportIbGib: RawExportIbGib_V1;\n    /**\n     * all addrs included in the export.\n     */\n    manifest: IbGibAddr[];\n    errors?: ExportErrorInfo[];\n}\nexport async function getRawExportIbGib({\n    ibGib,\n    metaspace,\n    space,\n    compress,\n    live,\n    ignoreErrors,\n    // detach,\n    // detachRel8nNames,\n}: GetRawExportIbGibOpts): Promise<GetRawExportIbGibResult> {\n    const lc = `[${getRawExportIbGib.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 0b6ba8608ba8bde0682a0936b9a01825)`); }\n        if (!ibGib) { throw new Error(`(UNEXPECTED) ibGib falsy? (E: d2898eea744360865f0da5fb91baae22)`); }\n        const ibGibAddr = getIbGibAddr({ ibGib });\n        // if (preparingExport) {\n        //   console.warn(`${lc} already preparing export. (W: cb31b23a313247f0ad128dd984645db4)`);\n        //   return; /* <<<< returns early */\n        // }\n        const errorInfos: ExportErrorInfo[] = [];\n\n        // preparingExport = true;\n\n        // build an ibgib that contains the entire dependency graph of this.ibGib and save it\n\n        const validationErrors = await validateIbGibIntrinsically({ ibGib }) ?? [];\n        if (validationErrors.length > 0) {\n            const errorMsg = `ibGib had validation errors: ${validationErrors} (E: 84890bbc0598192498178a98ae299825)`;\n            if (ignoreErrors) {\n                errorInfos.push({ errorMsg, ibGibAddr });\n            } else {\n                throw new Error(errorMsg);\n            }\n        }\n\n        // build the data\n        const resGraph = await metaspace.getDependencyGraph({\n            ibGib,\n            live,\n            space,\n        });\n        const dependencyGraphAsString = compress ?\n            await compressIbGibGraphToString({ graph: resGraph }) :\n            await serializeGraphToString({ graph: resGraph });\n        const tjpAddr = getTjpAddr({ ibGib, defaultIfNone: 'incomingAddr' }) ?? ibGibAddr;\n        const now = new Date();\n        let exportData: RawExportData_V1 = {\n            contextIbGibAddr: ibGibAddr,\n            tjpAddr,\n            dependencyGraphAsString,\n            graphSize: Object.keys(resGraph).length,\n            timestamp: getTimestamp(now),\n            timestampMs: now.getMilliseconds(),\n        };\n        if (compress) { exportData.compression = 'gzip'; }\n\n        // [no rel8ns because this is a self-contained export ibgib]\n\n        // gib\n        const exportIbGib: RawExportIbGib_V1 = {\n            ib: getRawExportIb({ data: exportData }),\n            data: exportData,\n        };\n        let exportGib = await getGib({ ibGib: exportIbGib, hasTjp: false });\n        exportIbGib.gib = exportGib;\n\n        if (logalot || true) { console.log(`${lc} JSON.stringify(exportIbGib).length: ${JSON.stringify(exportIbGib).length} (I: db3a8d913a91d8fc5d6e45981e034822)`); }\n\n        return {\n            rawExportIbGib: exportIbGib,\n            manifest: Object.keys(resGraph),\n            errors: errorInfos.length > 0 ? errorInfos : undefined,\n        };\n\n\n        // // at this point, we have a possibly quite large ibGib whose data includes\n        // // every single ibgib that this.ibGib relates to (its dependency graph).\n        // // so now we can save this file and later import from it.\n\n        // // thank you SO, OP and volzotan at https://stackoverflow.com/questions/19721439/download-json-object-as-a-file-from-browser\n        // // set the anchor's href to a data stream\n        // var dataStr = \"data:text/json;charset=utf-8,\" + encodeURIComponent(JSON.stringify(exportIbGib));\n\n        // // get the filename for the anchor to suggest for the \"download\"\n        // let exportAddr = getIbGibAddr({ ibGib: exportIbGib });\n        // const filename = `${exportAddr}.json`;\n\n        // // if (this.web) {\n        //     // trigger the click\n        //     const dlAnchorElemId ='export-ibgib-anchor';\n        //     const dlAnchorElem = document.getElementById(dlAnchorElemId);\n        //     if (!dlAnchorElem) { throw new Error(`(UNEXPECTED) dlAnchorElem falsy? should be an element with id ${dlAnchorElemId}? (E: 51dfe2d823eedeefb8b9c9580090e625)`); }\n        //     dlAnchorElem.setAttribute(\"href\", dataStr);\n        //     dlAnchorElem.setAttribute(\"download\", filename);\n        //     dlAnchorElem.click();\n        // } else {\n        //     // let res = await Filesystem.requestPermissions();\n        //     await Filesystem.writeFile({\n        //         data: dataStr,\n        //         directory: Directory.ExternalStorage,\n        //         path: `/Download/${filename}`,\n        //         encoding: Encoding.UTF8,\n        //         recursive: true,\n        //     });\n        // }\n        // await Dialog.alert({ title: 'export succeeded', message: 'way to go, the export succeeded' });\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n", "import { tagTextToIb } from \"@ibgib/core-gib/dist/common/other/ibgib-helper.mjs\";\n\n/**\n * @internal\n * Library-internal toggle for verbose logging.\n *\n * ## Usage note\n *\n * This is an ibgib-pattern meant to be redefined per project. Downstream apps\n * should NOT import this from web-gib, but instead define their own\n * `GLOBAL_LOG_A_LOT` constant for their own logging needs.\n */\nexport const GLOBAL_LOG_A_LOT = false;\nexport const GLOBAL_TIMER_NAME = '[web^gib timer]';\n/**\n * `globalThis[GLOBAL_THIS_IBGIB_KEY]`\n *\n * So the pattern for other apps/libs is:\n *\n * `globalThis[GLOBAL_THIS_IBGIB_KEY][APP_SPECIFIC_GLOBAL_KEY]`\n *\n * and given the value of this continues to be `\"ibgib\"`:\n * `globalThis.ibgib.[APP_SPECIFIC_GLOBAL_KEY]`\n *\n * @example globalThis.ibgib.myApp\n * @example globalThis.ibgib.blankGib\n */\nexport const GLOBAL_THIS_IBGIB_KEY = 'ibgib';\n\n/**\n * regex for what we think of as a gemini api key.\n */\nexport const GEMINI_API_KEY_REGEXP = /^[a-zA-Z0-9\\-_]{32,64}$/;\nexport const CONFIG_OPTION_GEMINI_API_KEY_LOCATION_HELP = `Gemini API Key Config option (\u2699\uFE0F icon in the top right)`;\n\n/**\n * used for the agent tag, in ibgib.data.text\n */\nexport const TAG_AGENT_TEXT = \"agent\";\n/**\n * used for the agent tag, in ibgib.data.icon\n */\nexport const TAG_AGENT_ICON = \"body-outline\";\n/**\n * used for the agent tag, in ibgib.data.description\n */\nexport const TAG_AGENT_DESCRIPTION = \"This tag tracks the active agents for the current local user space.\";\n/**\n * the ib value of the tag ibgib for the agents.\n */\nexport const TAG_AGENT_IB = tagTextToIb(TAG_AGENT_TEXT);\n\nexport const DEFAULT_IBGIB_COLOR = '#78f87e88';\nexport const DEFAULT_IBGIB_TRANSLUCENT = '#78f87e10';\nexport const DEFAULT_IBGIB_COLOR_CONTRAST = '#ffffff';\nexport const DEFAULT_TJP_COLOR = '#78f87e88';\nexport const DEFAULT_TJP_COLOR_TRANSLUCENT = '#78f87e10';\nexport const DEFAULT_TJP_COLOR_CONTRAST = '#ffffff';\n\n/**\n * I am toying with tagging hardcoded prompts at the moment (atow 05/2025)\n */\nexport const HARDCODED_PROMPT_TAG_TEXT = 'AUTOMATED_TEXT';\n", "/**\n * @module storage-helpers.web.mts\n *\n * This is the storage abstraction that wraps indexed db.\n *\n * NOTE:\n *\n * I just want to say that callbacks are not very cool and that much of the\n * ridiculousness of this code is due to this fact.\n *\n * That said, these functions try to ensure db is closed per function via global\n * finally block. With nested promises and callbacks, this is a big f*n mess.\n * But more importantly, this is why there aren't db.close() calls sprinkled\n * throughout each function. But ths assumes that I am wiring up resolve/reject\n * calls correctly through all the paths and this is far from certain.\n */\n\nimport { extractErrorMsg } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\n\nimport { GLOBAL_LOG_A_LOT, } from \"../constants.mjs\";\nimport { uint8ArrayToString } from \"../helpers.web.mjs\";\nimport { Dirent } from \"./storage-types.web.mjs\";\n\n\nlet logalot = GLOBAL_LOG_A_LOT;\n\n/**\n * key/value pair interface for working with indexeddb\n */\nexport interface IndexedDBStorageDatum {\n    key: string;\n    /**\n     * may have to change this to work with binary array buffers.\n     */\n    value: string | Uint8Array;\n}\n\nlet initRequestCount: number = 0;\n\nexport async function askForPersistStorage(): Promise<void> {\n    const lc = `[${askForPersistStorage.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 94b9aca3633e3d4cd3d420329a9c7425)`); }\n        const _unusedtesting = await navigator.storage.persist();\n        if (navigator.storage?.persist) {\n            const alreadyPersisted = await navigator.storage.persisted();\n            if (alreadyPersisted) {\n                if (logalot) { console.log(`${lc} navigator.storage is already persisted (I: 2e55a7106e6d07715356b5feb5300b25)`); }\n            } else {\n                if (logalot) { console.log(`${lc} navigator.storage not already persisted. asking navigator.storage for persist... (I: 78086d15e2e94c14a0028c584099d715)`); }\n                const persisted = await navigator.storage.persist();\n                if (logalot) { console.log(`${lc} navigator.storage persist: ${persisted} (I: 923eb26c2c3240c9b5659c3266388071)`); }\n            }\n        } else {\n            if (logalot) { console.warn(`${lc} navigator.storage.persist not supported. (W: f5a9c3a8f7614d30b9f205f3f6c61b34)`); }\n        }\n\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * initializes db ALWAYS but initializes store given by {@link storeName} ONLY\n * WHEN VERSION IS HIGHER THAN EXISTING VERSION.\n *\n * @see {@link storageCreateStoreIfNotExist}\n */\nexport async function initializeStorage({\n    dbName,\n    storeName,\n    version,\n    logalot = false,\n}: {\n    dbName: string,\n    storeName?: string,\n    version?: number,\n    logalot?: boolean,\n}): Promise<void> {\n    const lc = `[${initializeStorage.name}][${dbName}][${storeName ?? 'no store name'}]`;\n    const uuid = crypto.randomUUID();\n    if (logalot) { console.time(lc + uuid); }\n    /** db variable outside try block for finally access in order to close it. */\n    let db: IDBDatabase | undefined = undefined;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: f35d4e1ba37252f14c8532fb861b1125)`); }\n\n        const prom = new Promise<void>((resolve, reject) => {\n            try {\n                if (logalot) { console.log(`${lc} starting... (I: 0aeddd9376daa0a044677ce4cf8a4c24)`); }\n\n                // Open a database connection\n                if (logalot) { console.timeLog(lc + uuid, 'opening... (I: e748b4ddb445d77cb10a7ba158b49125)') }\n                // so when we get here via storageCreateStoreIfNotExist function,\n                // the version is going to be a bumped number. so is this what is\n                // necessarily triggering the onblocked?\n                const openDBRequest = indexedDB.open(dbName, /*version*/version);\n                initRequestCount++;\n                console.log(`${lc} initRequestCount: ${initRequestCount} (I: 294d5f0b12ffe5512bacebe891824d25)`);\n                let storeAlreadyExisted: boolean | undefined = undefined;\n                openDBRequest.onupgradeneeded = (event: IDBVersionChangeEvent) => {\n                    try {\n                        db = (event.target as any).result as IDBDatabase;\n                        if (logalot) { console.timeLog(lc + uuid, 'onupgradeneeded... (I: e748b4ddb445d77cb10a7ba158b49125)') }\n\n                        // Create a store if it doesn't exist. note that\n                        // db.createObjectStore can only be called within this\n                        // onupgradeneeded handler.\n                        if (storeName) {\n                            if (!db.objectStoreNames.contains(storeName)) {\n                                storeAlreadyExisted = false;\n                                db.createObjectStore(storeName, { keyPath: 'key' });\n                            } else {\n                                storeAlreadyExisted = true;\n                            }\n                        }\n                    } catch (error) {\n                        console.error(`${lc}[openDBRequest.onupgradeneeded] ${extractErrorMsg(error)} (E: 4a5fa1b0850be47e28bee653da287325)`);\n                        reject(error);\n                    }\n                };\n\n                openDBRequest.onblocked = (event: IDBVersionChangeEvent) => {\n                    console.log(`${lc}[openDBRequest.onblocked] openDBRequest blocked...time wasted a bit here. version change event (old -> new):  ${event.oldVersion} -> ${event.newVersion} (I: 9074ebf4afdba54d6f9d41b360b96a25)`);\n                    console.dir(event);\n                };\n\n                /**\n                 * this handler fires independently of upgradeneeded\n                 */\n                openDBRequest.onsuccess = (ev) => {\n                    try {\n                        if (logalot) { console.log('init success (I: 297a5a71e405a0b56413af813f248d24)'); }\n                        if (logalot) { console.timeLog(lc + uuid, 'onupgradeneeded... (I: e748b4ddb445d77cb10a7ba158b49125)') }\n                        db = (ev.target as any).result as IDBDatabase;\n                        if (storeName) {\n                            storeAlreadyExisted ??= db.objectStoreNames.contains(storeName);\n                            if (logalot) { console.log(`${lc} ${dbName} store \"${storeName}\" ${storeAlreadyExisted ? 'already exists' : 'does not exist'}. (I: db64712bc69c5287b1cf77af1fc13d24)`); }\n                        }\n                        resolve();\n                    } catch (error) {\n                        console.error(`${lc}[openDBRequest.onsuccess] ${extractErrorMsg(error)}`);\n                        reject(error);\n                    }\n                };\n\n                openDBRequest.onerror = (event: any) => { // IDBRequestEvent but doesn't compile\n                    debugger; // error initializeStorage openDBRequest.onerror\n                    console.error(`${lc}[initRequest.onerror] ${extractErrorMsg(openDBRequest.error)} (E: 74cf09e9fba2dd9e41225e943c331124)`);\n                    reject(openDBRequest.error); // same as below?\n                    // reject(event.target.error);\n                };\n            } catch (error) {\n                console.error(`${lc} ${extractErrorMsg(error)}`);\n                debugger; // error\n                reject(error);\n            } finally {\n                if (logalot) { console.log(`${lc} complete.`); }\n            }\n        });\n        await prom;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (db) {\n            if (logalot) { console.log(`${lc} closing db ${dbName}... (I: 3f1c18eec567ea63f3927eef0f038925)`); }\n            (db as any).close();\n            if (logalot) {\n                console.log(`${lc} closing db ${dbName} complete. (I: bc3b2f504245d6203dbba6bd65d30325)`);\n                console.timeLog(lc + uuid, 'db closed. (I: e748b4ddb445d77cb10a7ba158b49125)')\n            }\n        }\n        if (logalot) {\n            console.log(`${lc} complete.`);\n            console.timeEnd(lc + uuid);\n        }\n    }\n\n}\n\n/**\n * wrapper for filtered indexedDB.databases() call basically\n *\n * @returns db info for given dbName\n */\nexport async function storageGetDBInfo({\n    dbName,\n    logalot = false,\n}: {\n    dbName: string,\n    logalot?: boolean,\n}): Promise<IDBDatabaseInfo | undefined> {\n    const lc = `[${storageGetDBInfo.name}]`;\n\n    const uuid = crypto.randomUUID();\n    if (logalot) { console.time(lc + uuid); }\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 8516795b20529d19eb6923defd7a0f24)`); }\n        const dbInfo = (await indexedDB.databases()).filter(x => x.name === dbName).at(0);\n        return dbInfo;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n    } finally {\n        if (logalot) { console.timeEnd(lc + uuid); }\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n\n/**\n * wrapper that ensures indexeddb store exists\n */\nexport async function storageCreateStoreIfNotExist({\n    dbName,\n    storeName,\n    logalot = false,\n}: {\n    dbName: string,\n    storeName: string,\n    logalot?: boolean,\n}): Promise<void> {\n    const lc = `[${storageCreateStoreIfNotExist.name}]`;\n    const uuid = crypto.randomUUID();\n    if (logalot) { console.time(lc + uuid); }\n    /** db variable outside try block for finally access in order to close it. */\n    let db: IDBDatabase | undefined = undefined;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 029f7caa8ea5ea08a865f3924c82b624)`); }\n\n        const dbInfo_viaIndexedDBDatabasesFn = (await indexedDB.databases()).filter(x => x.name === dbName).at(0);\n        if (!dbInfo_viaIndexedDBDatabasesFn) { throw new Error(`db (${dbName}) does not exist. can't create store (${storeName}) (E: 5b15f7aed6f7068d077b2c7ebcbe8524)`); }\n\n        let storeExists = false;\n\n        if (logalot) { console.timeLog(lc + uuid); }\n\n        await new Promise<void>((resolve, reject) => {\n            const openDBRequest = indexedDB.open(dbName);\n            openDBRequest.onsuccess = (ev: Event) => {\n                db = (ev.target as any).result as IDBDatabase;\n                storeExists = db.objectStoreNames?.contains(storeName);\n                if (logalot) { console.timeLog(lc + uuid, 'open db request'); }\n                resolve();\n            };\n            openDBRequest.onerror = (event: any) => { // IDBRequestEvent but doesn't compile\n                debugger; // error storageCreateStoreIfNotExist openDBRequest.onerror\n                console.error(`${lc}[openDBRequest.onerror] ${extractErrorMsg(openDBRequest.error)} (E: 63695744e9e59ff8019e04ceeb8e2524)`);\n                // reject(event.target.error); // same as openDBRequest.error?\n                reject(openDBRequest.error);\n            };\n        });\n\n        if (logalot) { console.timeLog(lc + uuid); }\n\n        if (storeExists) {\n            if (logalot) { console.log(`${lc} store ${storeName} already existed. (I: a2263b510c18240fc59fca54e3892324)`); }\n            return; /* <<<< returns early */\n        }\n\n        // store does not exist, so get the version number, bump it, and in the upgradeneeded handler, create the store\n        const dbInfo = await storageGetDBInfo({ dbName, logalot }); // does not need db closed yet\n        if (logalot) { console.timeLog(lc + uuid, 'storageGetDBInfo complete'); }\n        if (!dbInfo) { throw new Error(`db (${dbName}) does not exist. can't create store (${storeName}) (E: c771db13fa28f67079aad45e1ab7e624)`); }\n        const version = dbInfo.version;\n        if (!version) { throw new Error(`db (${dbName}) has no version. can't create store (${storeName}) (E: 3d2ec52853ad99f92b19ac5aa7fbfe24)`); }\n        const newVersion = version + 1;\n        if (logalot) { console.log(`${lc} creating store ${storeName} with version ${newVersion} (I: 312b79f28243c650cf38935114f21e24)`); }\n        // we need to manually close db here before calling the inititalizeStorage\n        if (db) {\n            (db as any).close();\n            db = undefined;\n        } else {\n            throw new Error(`(UNEXPECTED) how did we get here with db falsy? (E: b561784879e19bac54b1c4936aff0c25)`);\n        }\n        await initializeStorage({ dbName, storeName, version: newVersion, logalot });\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error; // why wasn't I rethrowing??\n    } finally {\n        if (db) {\n            if (logalot) { console.log(`${lc} closing db ${dbName}... (I: 3f1c18eec567ea63f3927eef0f038925)`); }\n            (db as any).close();\n            if (logalot) { console.log(`${lc} closing db ${dbName} complete. (I: bc3b2f504245d6203dbba6bd65d30325)`); }\n        }\n        if (logalot) { console.timeLog(lc + uuid); }\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * set key/value item\n * helper for indexeddb storage.\n */\nexport async function storagePut({\n    dbName,\n    version,\n    storeName,\n    key,\n    value,\n    logalot = false,\n}: {\n    dbName: string,\n    version?: number,\n    storeName: string,\n    key: string,\n    value: string | Uint8Array,\n    logalot?: boolean,\n}): Promise<void> {\n    const lc = `[${storagePut.name}]`;\n    /** db variable outside try block for finally access in order to close it. */\n    let db: IDBDatabase | undefined = undefined;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: bf7316c244888cb8ead2d3aac1d9f625)`); }\n\n        const prom = new Promise<void>((resolve, reject) => {\n            try {\n                if (logalot) { console.log(`${lc} starting... (I: 81df59e3961d711ce5d8f2ae3e2f3824)`); }\n\n                const openDBRequest = indexedDB.open(dbName, /*version*/version);\n                openDBRequest.onsuccess = (event: any) => { // IDBOpenDBRequestEvent?\n                    db = event.target.result as IDBDatabase;\n                    try {\n                        const store = db.transaction(storeName, 'readwrite').objectStore(storeName);\n                        const data: IndexedDBStorageDatum = { key, value };\n                        store.put(data);\n                        resolve();\n                    } catch (error) {\n                        console.error(`${lc}[putRequest.onsuccess] ${extractErrorMsg(error)}`);\n                        reject(error);\n                    }\n                };\n\n                openDBRequest.onerror = (event: any) => { // IDBRequestEvent?\n                    debugger; // storagePut openDBRequest error\n                    // is openDBRequest.error same as event.target.error?\n                    console.error(`${lc}[putRequest.onerror] ${extractErrorMsg(openDBRequest.error)} (E: 7a946d99ede2b248df4dcfea4ac99724)`);\n                    reject(openDBRequest.error);\n                };\n            } catch (error) {\n                console.error(`${lc} ${extractErrorMsg(error)}`);\n                reject(error);\n            } finally {\n                if (logalot) { console.log(`${lc} complete.`); }\n            }\n        });\n\n        await prom;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (db) {\n            if (logalot) { console.log(`${lc} closing db ${dbName}... (I: 438c6edced94b83a3478c71b08c6c325)`); }\n            (db as any).close();\n            if (logalot) { console.log(`${lc} closing db ${dbName} complete. (I: 0d081553b1eb53c65ade2cedb802cf25)`); }\n        }\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * get item via key\n * helper for indexeddb storage.\n */\nexport async function storageGet({\n    dbName,\n    version,\n    storeName,\n    key,\n    logalot = false,\n}: {\n    dbName: string,\n    version?: number,\n    storeName: string,\n    key: string,\n    logalot?: boolean,\n}): Promise<string | undefined> {\n    const lc = `[${storageGet.name}]`;\n    /** db variable outside try block for finally access in order to close it. */\n    let db: IDBDatabase | undefined = undefined;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: f8ba7cd5801918a8580e91b7c90aa525)`); }\n        const prom = new Promise<string | undefined>((resolve, reject) => {\n            try {\n                if (logalot) { console.log(`${lc} starting... (I: 24163c4a11c8712097db45febaf9c724)`); }\n\n                // Retrieve the value later\n                const openDBRequest = indexedDB.open(dbName, version);\n                openDBRequest.onsuccess = (event: any) => { // IDBOpenDBRequestEvent?\n                    db = event.target.result as IDBDatabase;\n\n                    let store: IDBObjectStore;\n                    try {\n                        store = db.transaction(storeName).objectStore(storeName);\n                    } catch (error) {\n                        debugger; // error getting objectStore\n                        console.error(`${lc}[openDBRequest.onsuccess][objectStore] ${extractErrorMsg(error)}`);\n                        reject(error);\n                        return; /* <<<< returns early */\n                    }\n\n                    // Get the value using the key\n                    const getRequest = store.get(key);\n                    getRequest.onsuccess = (event: any) => { // IDBRequestEvent?\n                        try {\n                            let value = (event.target?.result as IndexedDBStorageDatum)?.value ?? undefined;\n                            if (!value) {\n                                resolve(value);\n                                return; /* <<<< returns early */\n                            }\n\n                            if (logalot) { console.log('Retrieved value:', value); }\n                            if (value instanceof Uint8Array) {\n                                resolve(uint8ArrayToString(value as Uint8Array));\n                            } else {\n                                if (typeof value !== 'string') { throw new Error(`(UNEXPECTED) truthy, non-Uint8Array value is not a string? (E: 6a4ec24e2e5d9848f8b542bc2661dc24)`); }\n                                resolve(value);\n                            }\n                        } catch (error) {\n                            reject(error);\n                        }\n                    };\n\n                    getRequest.onerror = (event: any) => {\n                        debugger; // storageGet getRequest.onerror\n                        const error = getRequest.error;\n                        console.error(`${lc}[openDBRequest.onsuccess][getRequest.onerror] ${extractErrorMsg(error)}`);\n                        reject(error);\n                    };\n                };\n\n                openDBRequest.onerror = (event: any) => { // IDBRequestEvent but doesn't compile\n                    debugger; // error indexeddb storageGet openDBRequest.onerror\n                    // are openDBRequest.error and event.target.error the same?\n                    console.error(`${lc}[openDBRequest.onerror] ${extractErrorMsg(openDBRequest.error)} (E: 074963a908fa9a075f01c73cae829224)`);\n                    reject(openDBRequest.error);\n                };\n\n            } catch (error) {\n                console.error(`${lc} ${extractErrorMsg(error)}`);\n                reject(error);\n            } finally {\n                if (logalot) { console.log(`${lc} complete.`); }\n            }\n        });\n\n        const result = await prom;\n        return result;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (db) {\n            if (logalot) { console.log(`${lc} closing db ${dbName}... (I: a938fc22dfdc76b15f6926bc4d458225)`); }\n            (db as any).close();\n            if (logalot) { console.log(`${lc} closing db ${dbName} complete. (I: 18f2ec1557bc83ec4e2c5d5e72264525)`); }\n        }\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * checks if db exists. if store is provided, checks to see if that specific\n * store exists in the db's schema.\n *\n * helper for indexeddb storage.\n */\nexport async function storageDBExists({\n    dbName,\n    store,\n}: {\n    dbName: string,\n    store?: string,\n}): Promise<boolean> {\n    const lc = `[${storageDBExists.name}]`;\n    /** db variable outside try block for finally access in order to close it. */\n    let db: IDBDatabase | undefined = undefined;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 2b4373affa3841220f0b7ca690406624)`); }\n\n        const dbs = await window.indexedDB.databases();\n        const dbExists = dbs.some(db => db.name === dbName);\n        if (dbExists) {\n            if (store) {\n                return await new Promise((resolve, reject) => {\n                    const openDBRequest = indexedDB.open(dbName);\n                    openDBRequest.onsuccess = (event: any) => { // IDBOpenDBRequestEvent?\n                        db = event.target.result as IDBDatabase;\n                        const storeExists = db.objectStoreNames.contains(store);\n                        resolve(storeExists);\n                    };\n                    openDBRequest.onerror = (event: any) => { // IDBRequestEvent but doesn't compile\n                        debugger; // onerror\n                        db = openDBRequest.result;\n                        const { error } = event.target;\n                        console.error(`${lc}[openDBRequest.onerror] ${extractErrorMsg(openDBRequest.error)} (E: c783fe607451e46c1feae3a81e0f7924)`);\n                        reject(error);\n                    };\n                });\n            } else {\n                return true;\n            }\n        } else {\n            return false;\n        }\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (db) {\n            if (logalot) { console.log(`${lc} closing db ${dbName}... (I: 8782d9eea285cf9eb638d493a421a625)`); }\n            // for some reason, typescript incorrectly thinks db is type\n            // \"never\", so this any cast is necessary\n            (db as any).close();\n            if (logalot) { console.log(`${lc} closing db ${dbName} complete. (I: 76a0c5dea2643e2bb84c82c8446a8125)`); }\n        }\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * helper function equivalent to rm -rf in our filesystem space\n */\nexport async function storageRmRF({\n    dbName,\n    storeName,\n    pathToRm,\n}: {\n    dbName: string;\n    storeName: string;\n    pathToRm: string;\n}): Promise<void> {\n    const lc = `[${storageRmRF.name}]`;\n    /**\n     * turning it off for this function...note that this does not call any other\n     * functions in this file that would be affected.\n     */\n    const logalotInitDebug = logalot;\n    // logalot = false;\n    if (logalot) { console.log(`${lc} starting... (I: c7e4cb759789ece0a8189d7dfb4d2a24)`); }\n    /** db variable outside try block for finally access in order to close it. */\n    let db: IDBDatabase | undefined = undefined;\n    return new Promise<void>((resolve, reject) => {\n        try {\n            if (!dbName) { throw new Error(`(UNEXPECTED) dbName falsy? (E: ed336d88c9c4e8d4916b29356dc58324)`); }\n            if (!storeName) { throw new Error(`(UNEXPECTED) storeName falsy? (E: ad493bb79b63a192524b14c59a706524)`); }\n            if (!pathToRm) { throw new Error(`(UNEXPECTED) pathToRm falsy? (E: 88c9631d93467e17996946882254af24)`); }\n            const openDBRequest = indexedDB.open(dbName);\n\n            openDBRequest.onerror = () => {\n                debugger; // error\n                if (openDBRequest.result) { // Only close if a DB object was obtained\n                    (openDBRequest.result as IDBDatabase).close();\n                }\n                console.error(`${lc}[openDBRequest.onerror] ${extractErrorMsg(openDBRequest.error)} (E: 4c5ab71a765e61b4292008fd4fafe324)`);\n                reject(openDBRequest.error);\n            };\n\n            openDBRequest.onsuccess = () => {\n                db = openDBRequest.result;\n                const transaction = db.transaction(storeName, \"readwrite\");\n                const objectStore = transaction.objectStore(storeName);\n\n                // Use IDBKeyRange.lowerBound() for efficiency\n                const range = IDBKeyRange.lowerBound(pathToRm);\n                const openCursorRequest = objectStore.openCursor(range);\n\n                openCursorRequest.onerror = () => {\n                    debugger; // error\n                    console.error(`${lc}[openCursorRequest.onerror] ${extractErrorMsg(openCursorRequest.error)} (E: caefdda2bb95f92e9fb8d89ee412b524)`);\n                    reject(openCursorRequest.error);\n                };\n\n                openCursorRequest.onsuccess = () => {\n                    try {\n                        let rmCount = 0;\n                        // does it matter if the path is a dir vs. a file?\n                        const cursor = openCursorRequest.result;\n                        if (cursor) {\n                            if (cursor.key.toString().startsWith(pathToRm)) {\n                                const deleteRequest = cursor.delete();\n                                rmCount++;\n\n                                deleteRequest.onerror = () => {\n                                    debugger; // error\n                                    console.error(`${lc}[deleteRequest.onerror] ${extractErrorMsg(deleteRequest.error)} (E: abc031c53e5387322cd8909b3ada9b24)`);\n                                    reject(deleteRequest.error);\n                                };\n                                cursor.continue();\n                            } else {\n                                // No more keys starting with dirPath, we can stop\n                                if (logalot) { console.log(`${lc} rmCount: ${rmCount} (I: e4bc613a5514c0942484b79267e16724)`); }\n                                resolve();\n                            }\n                        } else {\n                            if (logalot) { console.log(`${lc} cursor is falsy, so either we have no more records or had no records to begin with. (I: 9ff3aec6274416501a7baf6dcc5f2624)`); }\n                            resolve();\n                        }\n                    } catch (error) {\n                        console.error(`${lc}[openCursorRequest.onsuccess] ${extractErrorMsg(error)}`);\n                        reject(error);\n                    }\n                };\n            };\n        } catch (error) {\n            debugger; // error storageRmDir\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            reject(error);\n        }\n    }).finally(() => {\n        if (db) {\n            if (logalot) { console.log(`${lc} closing db ${dbName}... (I: 39b4ba83de4bdfd541e3384ebab27425)`); }\n            db.close();\n            if (logalot) { console.log(`${lc} closing db ${dbName} complete. (I: e4015b9436c4b2bc0ccf0e11e2037925)`); }\n        }\n        if (logalot) { console.log(`${lc} complete.`); }\n        logalot = logalotInitDebug;\n    });\n}\n\n/**\n * helper function equivalent to readdir in our filesystem space\n */\nexport async function storageReaddir({\n    dbName,\n    storeName,\n    dirPath,\n    withFileTypes = false,\n}: {\n    dbName: string;\n    storeName: string;\n    dirPath: string;\n    withFileTypes?: boolean;\n}): Promise<string[] | Dirent[]> {\n    const lc = `[${storageReaddir.name}]`;\n    /** db variable outside try block for finally access in order to close it. */\n    let db: IDBDatabase | undefined = undefined;\n    try {\n        const prom = new Promise<string[] | Dirent[]>((resolve, reject) => {\n            const openDBRequest = indexedDB.open(dbName);\n\n            openDBRequest.onerror = () => {\n                debugger; // error\n                // if (openDBRequest.result) { // Only close if a DB object was obtained\n                //     (openDBRequest.result as IDBDatabase).close();\n                // }\n                reject(openDBRequest.error);\n            };\n\n            openDBRequest.onsuccess = () => {\n                db = openDBRequest.result;\n                const transaction = db.transaction(storeName, \"readonly\");\n                const objectStore = transaction.objectStore(storeName);\n\n                const normalizedDirPath = dirPath.endsWith(\"/\") ? dirPath : dirPath + \"/\";\n                const range = IDBKeyRange.lowerBound(normalizedDirPath);\n                const openCursorRequest = objectStore.openCursor(range);\n                const entries: Set<string> = new Set();\n                const dirents: Dirent[] = [];\n\n                openCursorRequest.onerror = () => {\n                    debugger; // error\n                    console.error(`${lc}[openCursorRequest.onerror] ${extractErrorMsg(openCursorRequest.error)}`);\n                    reject(openCursorRequest.error);\n                };\n\n                // cursor.continue() repeatedly calls this handler ick\n                openCursorRequest.onsuccess = () => {\n                    try {\n                        const cursor = openCursorRequest.result;\n                        if (cursor) {\n                            const key = cursor.key.toString();\n                            if (key.startsWith(normalizedDirPath) && key !== normalizedDirPath) {\n                                const relativePath = key.substring(normalizedDirPath.length);\n                                const childSegment = relativePath.split(\"/\")[0];\n                                if (withFileTypes) {\n                                    // Determine if it's a file or directory\n                                    const isDirectory = relativePath.substring(childSegment.length).startsWith(\"/\");\n                                    dirents.push({\n                                        name: childSegment,\n                                        isDirectory: () => isDirectory,\n                                        isFile: () => !isDirectory,\n                                        isBlockDevice: () => false,\n                                        isCharacterDevice: () => false,\n                                        isSymbolicLink: () => false,\n                                        isFIFO: () => false,\n                                        isSocket: () => false,\n                                    });\n                                } else {\n                                    entries.add(childSegment);\n                                }\n                                cursor.continue();\n                            } else if (!key.startsWith(normalizedDirPath)) {\n                                resolve(withFileTypes ? dirents : Array.from(entries));\n                            } else {\n                                cursor.continue();\n                            }\n                        } else {\n                            resolve(withFileTypes ? dirents : Array.from(entries));\n                        }\n                    } catch (error) {\n                        console.error(`${lc}[openCursorRequest.onsuccess] ${extractErrorMsg(error)}`);\n                        reject(error);\n                    }\n                };\n            };\n        });\n\n        const result = await prom;\n\n        return result;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (db) {\n            if (logalot) { console.log(`${lc} closing db ${dbName}... (I: 39b4ba83de4bdfd541e3384ebab27425)`); }\n            // for some reason, typescript incorrectly thinks db is type\n            // \"never\", so this any cast is necessary\n            (db as any).close();\n            if (logalot) { console.log(`${lc} closing db ${dbName} complete. (I: e4015b9436c4b2bc0ccf0e11e2037925)`); }\n        }\n    }\n}\n", "/**\n * these are the variables able to be changed dynamically in the UI.\n *\n * For this to work, these variables must be used in the consuming app's css.\n */\nexport const VALID_CSS_VARIABLES = [\n    '--text-color-base',\n    '--background-color-base',\n    '--border-color-base',\n    '--border-width-base',\n    '--border-style-base',\n    '--font-family-base',\n    '--font-size-base',\n    '--highlight-border-color',\n    '--highlight-box-shadow-color',\n    '--side-panel-tab-content-background-color',\n\n    '--light-background-color',\n    '--very-light-background-color',\n\n    // #region tabs\n    '--tab-background-color',\n    '--tab-background-color-active',\n    '--tab-text-color',\n    '--tab-text-color-active',\n    '--tab-border-color',\n    '--tab-border-color-active',\n    '--tab-border-width',\n    '--tab-border-width-active',\n    '--tab-border-style',\n    '--tab-border-radius',\n    '--tab-padding',\n    // #endregion tabs\n\n    // #region links\n    '--link-color',\n    '--link-visited-color',\n    '--link-hover-color',\n    '--link-text-decoration',\n    '--link-hover-text-decoration',\n    // #endregion links\n\n    // #region buttons\n    '--button-background-color-base',\n    '--button-text-color-base',\n    '--button-border-color-base',\n    '--button-border-width-base',\n    '--button-border-style-base',\n    '--button-border-radius-base',\n    '--button-padding-base',\n    '--button-hover-background-color',\n    '--button-hover-text-color',\n    '--button-hover-border-color',\n    // #endregion buttons\n\n    // #region inputs\n    '--input-background-color',\n    '--input-text-color',\n    '--input-border-color',\n    '--input-border-width',\n    '--input-border-style',\n    '--input-border-radius',\n    '--input-padding',\n    // #endregion inputs\n\n    // #region headings\n    '--h1-font-size',\n    '--h1-font-weight',\n    '--h1-margin',\n    '--h2-font-size',\n    '--h2-font-weight',\n    '--h2-margin',\n    '--h3-font-size',\n    '--h3-font-weight',\n    '--h3-margin',\n    // #endregion headings\n\n    // #region message types\n    '--agent-background-color',\n    '--agent-text-color',\n    '--human-background-color',\n    '--human-text-color',\n    '--code-background-color',\n    '--code-text-color',\n    '--function-background-color',\n    '--function-text-color',\n    '--unknown-background-color',\n    '--unknown-text-color',\n    // #endregion message types\n\n    // #region scrollbar\n    '--scrollbar-thumb-color',\n    '--scrollbar-track-color',\n    // #endregion scrollbar\n];\n\n/**\n * 06/2025\n * going to use this for storing/restoring themes\n */\nexport const UI_THEME_INFO_KEY = 'ui-theme-info';\n", "import { delay, extractErrorMsg, } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\n\nimport { GLOBAL_LOG_A_LOT } from \"../constants.mjs\";\nimport { UIThemeInfo } from \"./ui-types.mjs\";\nimport { storageGet } from \"../storage/storage-helpers.web.mjs\";\nimport { UI_THEME_INFO_KEY } from \"./ui-constants.mjs\";\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\n/**\n * Shows the fullscreen dialog with the given title, message, and optional prompt.\n *\n * @param {object} details - Options for showing the dialog.\n * @param {string} details.title - Title of the dialog.\n * @param {string} details.message - Message to display in the dialog body.\n * @param {boolean} [details.prompt] - If true, shows a text input for prompting the user.\n * @returns {Promise<string | null>} - A promise that resolves with the text entered by the user (if prompt is true) or null if canceled/dismissed.\n */\nexport async function showFullscreenDialog(opts: {\n    title: string,\n    msg: string,\n    /**\n     * determines if to show the cancel button. does NOT control whether or not\n     * we show the input control.\n     *\n     * so if you want to prompt just for a boolean, just set this to true. If\n     * you need actual string input from the user, set {@link showInput} to\n     * true.\n     *\n     * @see {@link showInput}\n     */\n    prompt?: boolean,\n    /**\n     * this flag determines if the user input field is shown. If this is truthy,\n     * then {@link prompt} will be ignored and always set to `true`.\n     *\n     * @see {@link prompt}\n     */\n    showInput?: boolean,\n    defaultValue?: string,\n    okButtonTitle?: string,\n    cancelButtonTitle?: string,\n    isPassword?: boolean,\n}): Promise<string | undefined> {\n    const lc = `[${showFullscreenDialog.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 037b228a2568181cd3eb25dba4e03225)`); }\n\n        // const dialog = document.getElementById(ID_FULLSCREEN_DIALOG) as HTMLDialogElement;\n        // const dialogBody = document.getElementById(ID_FULLSCREEN_DIALOG_BODY) as HTMLDialogElement;\n        // const titleElement = document.getElementById(ID_FULLSCREEN_DIALOG_TITLE) as HTMLElement;\n        // const messageElement = document.getElementById(ID_FULLSCREEN_DIALOG_MESSAGE) as HTMLElement;\n        // const promptInput = document.getElementById(ID_FULLSCREEN_DIALOG_PROMPT_INPUT) as HTMLInputElement;\n        // const okButton = document.getElementById(ID_FULLSCREEN_DIALOG_OK_BUTTON) as HTMLButtonElement;\n        // const cancelButton = document.getElementById(ID_FULLSCREEN_DIALOG_CANCEL_BUTTON) as HTMLButtonElement;\n\n        const dialog = document.getElementById('fullscreen-dialog') as HTMLDialogElement;\n        const dialogBody = document.getElementById('fullscreen-dialog-body') as HTMLDialogElement;\n        const titleElement = document.getElementById('fullscreen-dialog-title') as HTMLElement;\n        const messageElement = document.getElementById('fullscreen-dialog-message') as HTMLElement;\n        const promptInput = document.getElementById('fullscreen-dialog-prompt-input') as HTMLInputElement;\n        const okButton = document.getElementById('fullscreen-dialog-ok-button') as HTMLButtonElement;\n        const cancelButton = document.getElementById('fullscreen-dialog-cancel-button') as HTMLButtonElement;\n\n        if (!dialog || !dialogBody || !titleElement || !messageElement || !promptInput || !okButton || !cancelButton) {\n            throw new Error(`(UNEXPECTED) One or more dialog elements not found in DOM (E: 578e37c0271cc57a99e95e780ad18a25)`);\n        }\n\n        titleElement.textContent = opts.title || '';\n        [...messageElement.childNodes as any].forEach(child => messageElement.removeChild(child));\n        // messageElement.innerHTML = '';\n        let msgLines = (opts.msg || '').split('\\n');\n        msgLines.forEach(line => {\n            const pLine = document.createElement('p');\n            pLine.textContent = line;\n            messageElement.appendChild(pLine);\n        });\n        // messageElement.textContent = opts.msg || '';\n\n        // reset the input classList\n        promptInput.classList.remove('collapsed');\n        cancelButton.classList.remove('collapsed');\n        cancelButton.style.display = 'inline-block';\n        okButton.textContent = opts.okButtonTitle || 'OK';\n\n        // Prompt-specific setup\n        const onKeypress = (ev: KeyboardEvent) => {\n            /**\n             * apparently an input has ev.key of 'Enter' but textarea is '\\n'\n             */\n            const isEnter = ev.key === 'Enter' || ev.key === '\\n';\n            if (isEnter && ev.ctrlKey) { okButton.click(); }\n        };\n\n        if (opts.prompt || opts.showInput) {\n            promptInput.addEventListener('keypress', onKeypress);\n            if (opts.showInput) {\n                promptInput.autofocus = true;\n                promptInput.value = opts.defaultValue ?? '';\n                promptInput.addEventListener('keypress', (ev) => {\n                    if (ev.key === 'Enter') { okButton.click(); }\n                });\n                if (opts.isPassword) {\n                    promptInput.type = 'password';\n                    promptInput.autocomplete = 'off';\n                    promptInput.required = true;\n                } else {\n                    promptInput.type = 'text';\n                    promptInput.autocomplete = 'on';\n                    promptInput.required = false;\n                    promptInput.attributes['auto-complete'] = 'on';\n                }\n            } else {\n                promptInput.autofocus = false;\n                promptInput.classList.add('collapsed');\n            }\n            cancelButton.textContent = opts.cancelButtonTitle || 'Cancel';\n        } else {\n            promptInput.classList.add('collapsed');    // Hide prompt input\n            cancelButton.style.display = 'none';       // Hide cancel button for alerts\n        }\n\n        return new Promise<string | undefined>((resolve) => {\n            // handlers\n\n            /** helper used in other handlers */\n            const removeEventListeners = () => {\n                if (opts.prompt || opts.showInput) {\n                    promptInput.removeEventListener('keypress', onKeypress);\n                }\n                okButton.removeEventListener('click', onOK);\n                cancelButton.removeEventListener('click', onCancel);\n                dialog.removeEventListener('close', onClose); // Remove dialog-level listener too\n            };\n            /** user clicks OK or hits \"ENTER\" in input */\n            const onOK = () => {\n                removeEventListeners();\n                let result = opts.showInput ?\n                    promptInput.value ?? '' :\n                    true.toString();\n                if (promptInput) { promptInput.value = ''; } // Clear input for next time\n                dialog.close(result);\n                resolve(result);\n            };\n\n            /** user actively clicks Cancel */\n            const onCancel = () => {\n                removeEventListeners();\n                if (promptInput) { promptInput.value = ''; } // Clear input for next time\n                dialog.close(undefined); // Pass back null for cancel\n                resolve(undefined);\n            };\n            /**\n             * Handle dialog.close() without button click (e.g., Esc key)\n             *\n             * NOTE: this does not trigger when dialog.close() is executed. This\n             * is only firing when esc is pressed.\n             */\n            const onClose = () => {\n                removeEventListeners();\n                if (promptInput) { promptInput.value = ''; } // Clear input for next time\n                dialog.close(undefined);\n                resolve(undefined);\n            };\n\n            // wire up\n            okButton.addEventListener('click', onOK);\n            cancelButton.addEventListener('click', onCancel);\n            dialog.addEventListener('close', onClose); // e.g. escape key\n\n            // show it\n            dialog.showModal();\n            delay(1000).then(() => {\n                dialogBody.scrollTo({ top: 0, behavior: 'smooth' });\n            });\n        });\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport async function getExistingUIInfo({\n    dbName,\n    storeName,\n    key = UI_THEME_INFO_KEY,\n}: {\n    dbName: string,\n    storeName: string,\n    key?: string,\n}): Promise<UIThemeInfo | undefined> {\n    const lc = `[${getExistingUIInfo.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 4c9d7c7f1e8bfcc917d405b842438825)`); }\n\n        key ??= UI_THEME_INFO_KEY;\n\n        let existingUIInfo: UIThemeInfo | undefined = undefined;\n        const existingUIInfoAsString = await storageGet({\n            dbName,\n            storeName,\n            key,\n        });\n        if (existingUIInfoAsString) {\n            try {\n                existingUIInfo = JSON.parse(existingUIInfoAsString) as UIThemeInfo;\n                if (!existingUIInfo.cssVariableOverrides) { throw new Error(`invalid existing UI info (E: 2fb408362178ce79a57da313d6680d25)`); }\n            } catch (error) {\n                existingUIInfo = undefined;\n            }\n        }\n\n        return existingUIInfo;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n", "import { clone, delay, extractErrorMsg, getTimestampInTicks } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { IbGib_V1, Rel8n } from \"@ibgib/ts-gib/dist/V1/types.mjs\";\nimport { getIbAndGib, getIbGibAddr } from \"@ibgib/ts-gib/dist/helper.mjs\";\nimport { GIB } from \"@ibgib/ts-gib/dist/V1/constants.mjs\";\nimport { Gib, IbGibAddr } from \"@ibgib/ts-gib/dist/types.mjs\";\nimport { getGibInfo, isPrimitive } from \"@ibgib/ts-gib/dist/V1/transforms/transform-helper.mjs\";\nimport { mut8 } from \"@ibgib/ts-gib/dist/V1/transforms/mut8.mjs\";\nimport { getSpecialConfigKey, getTjpAddr } from \"@ibgib/core-gib/dist/common/other/ibgib-helper.mjs\";\nimport { execInSpaceWithLocking, persistTransformResult } from \"@ibgib/core-gib/dist/witness/space/space-helper.mjs\";\nimport { MetaspaceService } from \"@ibgib/core-gib/dist/witness/space/metaspace/metaspace-types.mjs\";\nimport { IbGibSpaceAny } from \"@ibgib/core-gib/dist/witness/space/space-base-v1.mjs\";\nimport { SpecialIbGibType } from \"@ibgib/core-gib/dist/common/other/other-types.mjs\";\n\nimport { DEFAULT_IBGIB_COLOR, DEFAULT_IBGIB_COLOR_CONTRAST, DEFAULT_IBGIB_TRANSLUCENT, GLOBAL_LOG_A_LOT, GLOBAL_THIS_IBGIB_KEY, } from \"./constants.mjs\";\nimport { GibColorInfo, IbGibGlobalThisInfo } from \"./types.mjs\";\n\nconst logalot = GLOBAL_LOG_A_LOT; // change this when you want to turn off verbose logging\n\nexport async function getTagsIbGib({\n    metaspace,\n    space,\n}: {\n    metaspace: MetaspaceService,\n    space: IbGibSpaceAny | undefined,\n}): Promise<IbGib_V1> {\n    const lc = `[${getTagsIbGib.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 2ccb79537a75e7896bace84e6c710d25)`); }\n\n        const tagsIbGib = await metaspace.getSpecialIbGib({ type: SpecialIbGibType.tags, space });\n        if (!tagsIbGib) { throw new Error(`tagsIbGib not found in metaspace. space: ${!!space ? space.ib : 'default local user space'} (E: 4734c510a411274315c0add8f70e1925)`); }\n\n        return tagsIbGib;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * NOTE: This was originally written only for agents and I'm generalizing it to\n * any \"coupled\" ibgib. The idea is that for local-space-specific ibgibs that\n * are related to domain ibgibs, but where we don't want to modify the domain\n * ibgib directly, we create this \"coupled\" ibgib. We then index it in a local\n * space special (index) ibgib and associate it by tjpAddr.\n *\n * Generates a consistent special name for the agent index ibGib based on the\n * domain ibGib's primitive ancestor's ib or the ibGibAddr's ib atom.\n *\n * RIGHT NOW I\"M PRIORITIZING THE ATOM. I THINK IT ALWAYS RETURNS THE ATOM, I.E., THE FIRST SPACE-DELIMITED PIECE OF THE `ib`.\n *\n * I am doing this because the project ibgib actually forks from a comment\n * ibgib, so its primitive ancestor is \"comment^gib\".\n *\n * ## notes\n *\n * We are trying to get a special ibgib index that maps from ibgibs (the domain)\n * to what local agent is registered to handle that ibgib's timeline.\n *\n * Concretely, we're working on the project ibgibs and we need a way to get at\n * the agent that is assigned to that project. But we can't just mut8 the\n * project itself because this would cause issues once the project is spread out\n * among multiple execution contexts (similar to \"remotes\" in git).\n *\n * So we will have a special ibgib registered with the local space which will\n * act as this index that maps ibgib -> handling agent. This function helps get\n * the *name* of that special indexing ibgib.\n *\n * This can be driven either by the ibgib itself, via the last primitive ancestor\n * ibgib's address, or via the ib's atom (the first space-delimited term in the\n * `ib` metadata).\n *\n * So if an ancestor is [comment^gib, specialComment^gib, specialComment\n * abc123^ABC123.DEF456] (where the abc123 things are representative of the full\n * hashes 64 characters long atow since we're using sha256), then the *last*\n * primitive address is specialComment^gib.\n */\nexport function getIndexNameFromIbGib({\n    scope,\n    ibGib,\n    ibGibAddr,\n    defaultNameIfError,\n}: {\n    /**\n     * what kind of index are we talking in general?\n     */\n    scope: string,\n    ibGib?: IbGib_V1,\n    ibGibAddr?: IbGibAddr,\n    /**\n     * if truthy and an error is produced, then this will be returned.\n     */\n    defaultNameIfError?: string,\n}): string {\n    const lc = `[${getIndexNameFromIbGib.name}]`;\n    try {\n        if (!ibGib && !ibGibAddr) { throw new Error(`${lc} Must provide either ibGib or ibGibAddr. (E: genuuid)`); }\n        if (scope.includes(' ')) {\n            console.warn(`${lc} scope includes one or more spaces. These will be converted to double underscores. (W: 1554a81454e8ae0a6858ea5dd17f8925)`);\n            scope = scope.replace(/ /g, '__');\n        }\n        /**\n         * note: non-alphanumerics are replaced with underscores\n         */\n        let primitiveAncestorIb: IbGibAddr | undefined = undefined;\n        let atom: string | undefined = undefined;\n        /**\n         * This is what we're trying to extract. once we have this, then we can\n         * simply append our index name, e.g. `${ancestorIbOrAtom}-agent-index`\n         */\n        let ancestorIbOrAtom: string | undefined = undefined;\n        if (ibGib) {\n            // go by the ibgib's full data\n            if (!ibGib.data) { throw new Error(`(UNEXPECTED) ibGib.data falsy? (E: genuuid)`); }\n            if (!ibGib.rel8ns) { throw new Error(`(UNEXPECTED) ibGib.rel8ns falsy? (E: genuuid)`); }\n            if (!ibGib.rel8ns.ancestor) { throw new Error(`(UNEXPECTED) ibGib.rel8ns.ancestor falsy? (E: genuuid)`); }\n            if (ibGib.rel8ns.ancestor.length === 0) {\n                throw new Error(`(UNEXPECTED) ibGib.rel8ns.ancestor.length === 0? there should be at least one ancestor (E: genuuid)`);\n                // this may turn into a warning later on down the road and return based on the ibGib's addr\n            }\n            if (ibGib && ibGibAddr) {\n                if (getIbGibAddr({ ibGib }) !== ibGibAddr) {\n                    throw new Error(`(UNEXPECTED) both ibGib and ibGibAddr provided, but addr of ibGib doesn't equal ibGibAddr? (E: genuuid)`);\n                }\n            }\n\n            // const primitiveAncestor = getPrimitiveAncestor({ ibGib });\n            const primitiveAncestorAddrs =\n                ibGib.rel8ns.ancestor!.filter(x => isPrimitive({ gib: getIbAndGib({ ibGibAddr: x }).gib }));\n            if (primitiveAncestorAddrs.length === 0) {\n                debugger; // error no primitive ancestor addrs?\n                console.error(`${lc} ibGib has no primitive ancestor addrs? Still going to work off of the ib then, which should have the atom as the first space-delimited term. (E: genuuid)`)\n            }\n            const primitiveAncestorAddr = primitiveAncestorAddrs.at(-1)!;\n            primitiveAncestorIb =\n                getIbAndGib({ ibGibAddr: primitiveAncestorAddr }).ib;\n            // replace ALL spaces with underscores\n            ancestorIbOrAtom = primitiveAncestorIb;\n        }\n\n        // get the atom from the address\n        ibGibAddr ??= getIbGibAddr({ ibGib });\n\n        // try to get at it from the ibGibAddr\n        const { ib } = getIbAndGib({ ibGibAddr });\n        atom = (ib.split(' ').at(0) ?? '');\n\n        // at this point we have a raw atom and possibly a raw primitive\n        // ancestor ib.  we want to compare the two, which usually should be the\n        // same (i think?). if different, warn and return\n        atom = atom.replace(/\\W/g, '_');\n\n        primitiveAncestorIb ??= atom;\n        primitiveAncestorIb = primitiveAncestorIb.replace(/\\W/g, '_');\n\n        if (!primitiveAncestorIb && !atom) {\n            throw new Error(`(UNEXPECTED) both primitiveAncestorIb and atom falsy? one should be truthy at this point. (E: genuuid)`);\n        }\n\n        // if (primitiveAncestorIb !== atom) {\n        //     // warn and do per arg\n        //     console.warn(`${lc} ibGib primitive ancestor ib (${primitiveAncestorIb}) doesn't match atom (${atom}). going with ancestorIbOrAtom: ${ancestorIbOrAtom} (W: genuuid)`);\n        // }\n        ancestorIbOrAtom = atom.toLowerCase();\n        if (logalot) { console.log(`${lc} ancestorIbOrAtom: ${ancestorIbOrAtom} (I: genuuid)`); }\n\n        /**\n         * I forgot, this cannot be kebab-cased because we only allow \\w regexp\n         * on the special ibgib name. I don't remember the reasoning for this,\n         * may be arbitrary. But for now, going to change this to underscore,\n         * even though the atom or ancestor ib may have underscores in it. Ah\n         * well.\n         */\n        const indexName = `${ancestorIbOrAtom}_${scope}index`;\n        if (logalot) { console.log(`${lc} indexName: ${indexName} (I: genuuid)`); }\n        return indexName;\n    } catch (error) {\n        if (!!defaultNameIfError) {\n            console.warn(`${lc} error happened but defaultNameIfError (${defaultNameIfError}) provided. So will return this value. error that was thrown: ${extractErrorMsg(error)}`);\n            return defaultNameIfError;\n        } else {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        }\n    }\n}\n\n/**\n * NOTE: This was originally written only for agents and I'm generalizing it to\n * any \"coupled\" ibgib. The idea is that for local-space-specific ibgibs that\n * are related to domain ibgibs, but where we don't want to modify the domain\n * ibgib directly, we create this \"coupled\" ibgib. We then index it in a local\n * space special (index) ibgib and associate it by tjpAddr.\n * Retrieves the agent ibGib associated with a domain ibGib from the special agent index ibGib.\n *\n * may have to change this to require the ibgib, not give an optional\n * domainIbGibAddr\n */\nexport async function getLocalCoupledIbGibForDomainIbGib<TIbGib extends IbGib_V1>({\n    scope,\n    ibGib,\n    metaspace,\n    space,\n    skipGetLatest,\n}: {\n    scope: string,\n    ibGib: IbGib_V1,\n    metaspace: MetaspaceService,\n    space: IbGibSpaceAny,\n    /**\n     * if true, will not call getLatest on the coupled ibgib if found.\n     */\n    skipGetLatest?: boolean,\n}): Promise<TIbGib | undefined> {\n    const lc = `[${getLocalCoupledIbGibForDomainIbGib.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: f19dc86aab380fe809aef27ccc7a7425)`); }\n\n        if (!scope) { throw new Error(`scope required to be a non-empty string (E: 73e702495c38c7d8747d1cf8850af825)`); }\n        if (!ibGib) { throw new Error(`ibGib required (E: genuuid)`); }\n\n        // Get the index name and domain TJP address\n        const indexSpecialIbGibType: SpecialIbGibType =\n            getIndexNameFromIbGib({ scope, ibGib, }) as SpecialIbGibType;\n\n        const domainTjpAddr = getTjpAddr({ ibGib, defaultIfNone: 'incomingAddr' })!;\n\n        // Get the index ibGib\n        const fn: () => Promise<TIbGib | undefined> = async () => {\n            const specialIndex = await metaspace.getSpecialIbGib({\n                type: indexSpecialIbGibType,\n                space,\n                initialize: false, // Do not create if it doesn't exist when retrieving\n                dontWarnIfNotExist: true, // Don't warn if the index doesn't exist\n                lock: true,\n            });\n\n            // If the index ibGib doesn't exist, nothing is registered for this domain ibgib\n            if (!specialIndex || !specialIndex.data) {\n                if (logalot) { console.log(`${lc} special ${scope} index ibGib not found for indexSpecialIbGibType (${indexSpecialIbGibType}). No coupled ibgib registered, returning undefined. (I: genuuid)`); }\n                return undefined; /* <<<< returns early */\n            }\n\n            // Get the address from the map\n            const coupleMap: { [tjpAddr: string]: IbGibAddr } =\n                specialIndex.data.coupleMap ??\n                specialIndex.data.agentMap ??\n                {};\n            const coupledAddr = coupleMap[domainTjpAddr];\n\n            if (!coupledAddr) {\n                if (logalot) { console.log(`${lc} No coupled ${scope} ibgib address found for domain ${domainTjpAddr} in the coupled index map. indexSpecialIbGibType: ${indexSpecialIbGibType}. returning undefined. (I: genuuid)`); }\n                return undefined; /* <<<< returns early */\n            }\n\n            let addrToGet = skipGetLatest ?\n                coupledAddr :\n                await metaspace.getLatestAddr({ addr: coupledAddr, space }) ?? coupledAddr;\n\n            let resGet = await metaspace.get({\n                addrs: [addrToGet],\n                space,\n            });\n\n            if (resGet.errorMsg || (resGet.ibGibs ?? []).length !== 1) {\n                throw new Error(`couldn't get latest coupled ibgib (${addrToGet}) for domain ${domainTjpAddr}.  (E: 8aa7b25f5cd4ebadd8bf2f8807dfe825)`);\n            }\n\n            return resGet.ibGibs![0] as TIbGib;\n        }\n\n        const result = await execInSpaceWithLocking({\n            scope: indexSpecialIbGibType,\n            secondsValid: 180,     // Example timeout\n            maxDelayMs: 100,       // Example delay\n            maxLockAttempts: 1800, // Example attempts\n            space,\n            callerInstanceId: lc + getTimestampInTicks(),\n            fn,\n        });\n\n        return result;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * Registers a domain ibGib with its associated agent ibGib in the special agent\n * index ibGib.  This creates or updates a mapping from the domain ibGib's TJP\n * address to the agent's address.\n *\n * ## intent\n *\n * we want to rel8 ibgibs but not directly change the domain ibgib. Like if we\n * have an ibgib that we want to collaborate on, we want a mechanism for the\n * local space (later local user via keystone) to have settings, agents, etc.,\n * for that domain ibgib. But each space has its own version, like a local/user\n * settings vs. a workspace settings.\n *\n * So this gets/creates an index on the local space and associates the domain\n * with the local.\n *\n * @example\n * use this to couple a local agent to a domain ibgib or a local settings ibgib\n * to a domain ibgib, that you do not want to share with others who will have\n * their own versions.\n */\nexport async function coupleDomainIbGibWithLocalIbGibViaIndex({\n    scope,\n    domainIbGib,\n    localIbGib,\n    metaspace,\n    space,\n}: {\n    scope: string,\n    domainIbGib: IbGib_V1,\n    localIbGib: IbGib_V1,\n    metaspace: MetaspaceService,\n    space: IbGibSpaceAny,\n}): Promise<void> {\n    const lc = `[${coupleDomainIbGibWithLocalIbGibViaIndex.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 217ae68e0c820e48f4c00409f7f14325)`); }\n\n        const indexSpecialIbGibType: SpecialIbGibType =\n            getIndexNameFromIbGib({ scope, ibGib: domainIbGib, });\n\n        const domainTjpAddr = getTjpAddr({ ibGib: domainIbGib });\n        const localAddr = getIbGibAddr({ ibGib: localIbGib });\n\n        if (!domainTjpAddr) { throw new Error(`${lc} Could not get TJP address for domain ibGib. (E: 35a4e8ac291b0b85cb958e28dd812f25)`); }\n        if (!localAddr) { throw new Error(`${lc} Could not get address for agent ibGib. (E: 2fce1187630b45934c4155a23204d125)`); }\n\n        const fn = async () => {\n\n            // Get or create the agent index ibGib\n            const agentSpecialIndex = await metaspace.getSpecialIbGib({\n                type: indexSpecialIbGibType,\n                space,\n                initialize: true, // Create if it doesn't exist\n                dontWarnIfNotExist: true,\n                lock: false,\n            });\n\n            if (!agentSpecialIndex) { throw new Error(`${lc} Could not get or create agent index ibGib.`); }\n\n            // Initialize data if it doesn't exist\n            if (!agentSpecialIndex.data) {\n                throw new Error(`(UNEXPECTED) agentSpecialIndex.data falsy? (E: 74299eed147debf6398ca37e7b8d5c25)`);\n            }\n\n            // Get the current mapping or initialize an empty one\n            const map = agentSpecialIndex.data.coupleMap ?? agentSpecialIndex.data.agentMap;\n            const coupleMap: { [tjpAddr: string]: IbGibAddr } =\n                !!map ? clone(map) : {};\n\n            // Update the mapping\n            const existingMappedAgentAddr = coupleMap[domainTjpAddr];\n            if (existingMappedAgentAddr) {\n                if (existingMappedAgentAddr === localAddr) {\n                    if (logalot) { console.log(`${lc} domain ibGib (${domainTjpAddr}) already mapped to agent (${localAddr}). returning early (I: cb5d4dcef8cf14de7336120fb8ffef25)`); }\n                    return; /* <<<< returns early */\n                } else {\n                    console.warn(`${lc} domainTjpAddr (${domainTjpAddr}) already assigned to existingMappedAgentAddr (${existingMappedAgentAddr}). We will be changing to new localAddr (${localAddr}). (W: eb993e33f7731e570fa76f24a2d80625)`)\n                }\n            }\n            coupleMap[domainTjpAddr] = localAddr;\n\n            // Assign the updated map back to data Save the updated index ibGib.\n            // there is extra plumbing involved with special index ibgibs. see\n            // `rel8ToSpecialIbGib` for an example in\n            // libs/core-gib/src/witness/space/space-helper.mts\n            // await updateSpecialIndex({\n            //     metaspace,\n            //     type: indexSpecialIbGibType,\n            //     dataToAddOrPatch: { coupleMap },\n            //     space,\n            // });\n            const resNewSpecial = await mut8({\n                src: agentSpecialIndex,\n                dataToAddOrPatch: { coupleMap },\n                dna: false,\n                linkedRel8ns: [Rel8n.past],\n                nCounter: true,\n            });\n\n            const newSpecialIbGib = resNewSpecial.newIbGib;\n\n            // persist\n            await persistTransformResult({ resTransform: resNewSpecial, space });\n\n            // update the space ibgib which contains the special/config information\n            const configKey = getSpecialConfigKey({ type: indexSpecialIbGibType });\n            await metaspace.setConfigAddr({\n                key: configKey,\n                addr: getIbGibAddr({ ibGib: newSpecialIbGib }),\n                space,\n            });\n\n            await metaspace.registerNewIbGib({ ibGib: newSpecialIbGib, space, });\n        }\n\n        await execInSpaceWithLocking({\n            scope: indexSpecialIbGibType, // Use the special index type as the lock scope.\n            secondsValid: 60, // Example timeout\n            maxDelayMs: 100, // Example delay\n            maxLockAttempts: 600, // Example attempts\n            space,\n            // callerInstanceId: // You might need a way to generate a unique ID for the caller\n            fn,\n        });\n\n        if (logalot) { console.log(`${lc} Registered domain ${domainTjpAddr} with agent ${localAddr}`); }\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * Returns a function, that, as long as it continues to be invoked, will not\n * be triggered. The function will be called after it stops being called for\n * N milliseconds. If `immediate` is passed, trigger the function on the\n * leading edge, instead of the trailing.\n *\n * @param func The function to debounce.\n * @param wait The number of milliseconds to wait after the last call.\n * @param immediate If true, trigger the function on the leading edge.\n * @returns A debounced version of the function.\n */\nexport function debounce<T extends (...args: any[]) => void>(\n    func: T,\n    wait: number,\n    immediate?: boolean\n): (...args: Parameters<T>) => void {\n    let timeout: ReturnType<typeof setTimeout> | null = null;\n\n    return function (this: any, ...args: Parameters<T>): void {\n        const context = this;\n\n        const later = function (): void {\n            timeout = null;\n            if (!immediate) {\n                func.apply(context, args);\n            }\n        };\n\n        const callNow = immediate && !timeout;\n\n        if (timeout) {\n            clearTimeout(timeout);\n        }\n\n        timeout = setTimeout(later, wait);\n\n        if (callNow) {\n            func.apply(context, args);\n        }\n    };\n}\n\nexport function getMaskedSecret({ secret, countToShow }: { secret: string, countToShow: number }): string {\n    const lc = `[${getMaskedSecret.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 4d479c342b77f12568501c085b4b0425)`); }\n        if (secret) {\n            if (countToShow > secret.length) {\n                if (secret.length === 1) {\n                    console.warn(`${lc} secret is one character? (W: genuuid)`);\n                    return secret; // whatever\n                } else {\n                    console.warn(`${lc} countToShow is longer than the entire secret! just showing the last two (W: genuuid)`);\n                    return `****${secret.substring(secret.length - 2)}`;\n                }\n            } else {\n                // show the last countToShow\n                const secretMasked = `****${secret.substring(secret.length - countToShow)}`;\n                return secretMasked;\n            }\n        } else {\n            console.error(`${lc} secret falsy? empty? returning empty string. (E: genuuid)`);\n            return '';\n        }\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport function insertAt<T>({\n    newItems,\n    index,\n    targetArray,\n}: {\n    newItems: T[],\n    index: number,\n    targetArray: T[],\n}): T[] {\n    const lc = `[${insertAt.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 5fc3c84d9e08f4ee88978be8bd117a25)`); }\n\n        if (index < 0 || index >= targetArray.length) {\n            throw new Error(`index (${index}) is out of bounds for targetArray (length ${targetArray.length}) (E: genuuid)`);\n        }\n\n        const arrayCopy = [...targetArray];\n        arrayCopy.splice(index, 0, ...newItems);\n        return arrayCopy;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport function deleteAt<T>({\n    targetArray,\n    index,\n}: {\n    targetArray: T[],\n    index: number,\n}): T[] {\n    const lc = `[${deleteAt.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 6f2df80039f897a0883714686af97925)`); }\n\n        if (index < 0 || index >= targetArray.length) {\n            throw new Error(`index (${index}) is out of bounds for targetArray (length ${targetArray.length}) (E: genuuid)`);\n        }\n\n        const arrayCopy = [...targetArray];\n        arrayCopy.splice(index, 1);\n        return arrayCopy;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport function getShortenedStringWithEllipsis({\n    str,\n    maxChars,\n}: {\n    str: string,\n    maxChars: number,\n}): string {\n    const lc = `[${getShortenedStringWithEllipsis.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 228729c84d2805bc186e96c8cbc56825)`); }\n\n        if (str.length <= maxChars) {\n            return str;\n        } else {\n            return str.substring(0, maxChars - 1) + '\u2026';\n        }\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * location for globals to be used across ALL ibgib apps/libs, present and future.\n *\n * NOTE: Very little should be in here, since it pertains to such a broad scope.\n *\n * ## how to use this class\n *\n * ibgib apps are expected to have a metaspace singleton, and this is expected to be\n */\nexport class IbGibGlobalThis_IbGib {\n    private lc: string = `[${IbGibGlobalThis_IbGib.name}]`;\n\n    private _metaspacesByAppId: { [appId: string]: MetaspaceService } = {};\n    private _globalThisObjectsByAppId: { [appId: string]: any } = {};\n\n    constructor() {\n\n    }\n\n    /**\n     * The metaspace should already be initialized.\n     *\n     * @throws if metaspace.initialized is falsy\n     *\n     * @see {@link IbGibGlobalThis_IbGib} for general instructions on how to use\n     * this class.\n     */\n    public async registerInitializedMetaspace({\n        appId,\n        metaspace,\n    }: {\n        appId: string,\n        metaspace: MetaspaceService,\n    }): Promise<void> {\n        const lc = `${this.lc}[${this.registerInitializedMetaspace.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: d65058fb49953ac8bff6823cbc464825)`); }\n            if (this._metaspacesByAppId[appId]) { throw new Error(`appId (${appId}) already has a metaspace registered. (E: 1601f88722b849bdd85b6b98075e8225)`); }\n\n            if (metaspace.initialized) {\n                this._metaspacesByAppId[appId] = metaspace;\n            } else {\n                throw new Error(`metaspace.initialized is false. (E: 00e361cff998dd54e4f7b8a10106ed25)`);\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    /**\n     * sync call to a metaspace that was registered by the appId.\n     *\n     * @throws If no metaspace was registered with the {@link appId}\n     *\n     * @see {@link IbGibGlobalThis_IbGib} for general instructions on how to use\n     * this class.\n     */\n    getMetaspace({ appId }: { appId: string }): MetaspaceService {\n        const lc = `${this.lc}[${this.getMetaspace.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: b918969698bf80cf18a03a3b91385525)`); }\n            const metaspace = this._metaspacesByAppId[appId];\n            if (metaspace) {\n                return metaspace;\n            } else {\n                throw new Error(`NOT FOUND: appId (${appId}) does not have a metaspace registered. (E: 0ebcf95fb208d2d3f27edb06260d9d25)`);\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    /**\n     * Registers an app-specific global object for global state with ibgib apps,\n     * on the ibgib global object (atow 12/2025 this is `globalThis.ibgib`).\n     * @see {@link IbGibGlobalThis_IbGib.getGlobalThis}\n     *\n     * @see {@link IbGibGlobalThis_IbGib} for general instructions on how to use\n     * this class.\n     */\n    registerGlobalThis<TGlobalInfo>({ appId, appGlobal }: { appId: string, appGlobal: TGlobalInfo }): void {\n        const lc = `${this.lc}[${this.registerGlobalThis.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 0680ec122948fe23cd0f4c3a61451825)`); }\n            if (this._globalThisObjectsByAppId[appId]) { throw new Error(`appId (${appId}) already has a globalThis object registered. (E: 1e71e8859a8b94c9a85af595818cd825)`); }\n\n            this._globalThisObjectsByAppId[appId] = appGlobal;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * Get the app-specific global object on globalThis.ibgib that was\n     * (or should have been) registered by the {@link appId}\n     *\n     * @throws if no globalThis obj was registered with `appId`\n     * @see {@link IbGibGlobalThis_IbGib.registerGlobalThis}\n     *\n     * @see {@link IbGibGlobalThis_IbGib} for general instructions on how to use\n     * this class.\n     */\n    getGlobalThis<TGlobalInfo>({ appId }: { appId: string }): TGlobalInfo {\n        const lc = `${this.lc}[${this.getGlobalThis.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: f59f58a8344664092877a0f8b43c1125)`); }\n\n            const globalThisObj = this._globalThisObjectsByAppId[appId] as (TGlobalInfo | undefined);\n            if (globalThisObj) {\n                return globalThisObj;\n            } else {\n                throw new Error(`NOT FOUND: appId (${appId}) does not have a globalThis object registered. (E: 8e3b08d05c475399781871d2a12ba825)`);\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n}\n\n/**\n *\n */\nexport function getIbGibGlobalThis_IbGib(): IbGibGlobalThisInfo {\n    const lc = `[${getIbGibGlobalThis_IbGib.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 890f53e984d69461d9f4ded8741fcc25)`); }\n\n        let result = globalThis[GLOBAL_THIS_IBGIB_KEY];\n        if (!result) {\n            console.log(`${lc} initializing globalThis.${GLOBAL_THIS_IBGIB_KEY}... (I: 9d9ff1813448d9a1b82b0e5790a74825)`);\n            result = {};\n        }\n\n        return result;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * helper that waits until the global metaspace is initialized and then returns\n * that metaspace.\n *\n * NOTE: This does not have a max count breakout or cancellation. The metaspace\n * is simply integral to the website and this is not expected to fail (otherwise\n * the entire website is foo anyway).\n *\n * ## driving use case\n *\n * when the router tries to load a route that is based on an ibgib, the\n * metaspace is required.\n */\nexport async function getGlobalMetaspace_waitIfNeeded({\n    delayIntervalMs = 50\n}: {\n    delayIntervalMs: number\n} = { delayIntervalMs: 50 }): Promise<MetaspaceService> {\n    const lc = `[${getGlobalMetaspace_waitIfNeeded.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 4acc22d08dd1100503f9b0423f302925)`); }\n        let metaspace: MetaspaceService | undefined;\n        while (!metaspace) {\n            if (getIbGibGlobalThis_IbGib().metaspace) {\n                metaspace = getIbGibGlobalThis_IbGib().metaspace!;\n            }\n            if (!metaspace) {\n                // global metaspace is loading. we have loaded html immediately\n                // out of the gate and the metaspace hasn't initialized yet.\n                console.log(`${lc} metaspace still not initialized. delayIntervalMs: ${delayIntervalMs} until next retry... (I: 490f77ac4ded1d7d3c0340e460404125)`);\n                await delay(delayIntervalMs);\n            }\n        }\n        return metaspace;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * builds a color schema based on the gib.\n *\n * note that the alpha drives the translucent property, but the solid color is\n * always built\n */\nexport function getDeterministicColorInfo({\n    ibGibAddr,\n    gib,\n    ibGib,\n    translucentAlpha = 10,\n}: {\n    ibGibAddr?: IbGibAddr,\n    gib?: Gib,\n    ibGib?: IbGib_V1,\n    /**\n     * drives the translucent color.\n     *\n     * @default 10\n     */\n    translucentAlpha?: number\n}): GibColorInfo {\n    const lc = `[${getDeterministicColorInfo.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 3b70af42d1c4f6ae91870f3a15c6c625)`); }\n        if (!ibGibAddr && !gib && !ibGib) { gib = GIB; }\n        gib ??= ibGib?.gib ?? getIbAndGib({ ibGibAddr }).gib;\n        const gibInfo = getGibInfo({ gib });\n        translucentAlpha ??= 10;\n        /**\n         * we want to color coordinate according to timeline if possible, i.e.,\n         * by tjpGib.\n         */\n        let drivingHash = '';\n        if (gibInfo.isPrimitive) {\n            return {\n                gib,\n                gibInfo,\n                punctiliarColor: DEFAULT_IBGIB_COLOR,\n                punctiliarColorTranslucent: DEFAULT_IBGIB_TRANSLUCENT,\n                punctiliarColorContrast: DEFAULT_IBGIB_COLOR_CONTRAST,\n            }; /* <<<< returns early */\n        } else {\n            drivingHash = gibInfo.tjpGib ?? gibInfo.punctiliarHash ?? gib; // hmm, gib should be punctiliar but meh\n        }\n\n\n\n        /**\n         * gets the color string\n         */\n        // const fnGetColorStr = (drivingHash: string) => {\n        //     function getContrastColor(hexcolor: string) {\n        //         const c = hexcolor.concat().replace(\"#\", \"\");\n        //         var r = parseInt(c.substr(0, 2), 16);\n        //         var g = parseInt(c.substr(2, 2), 16);\n        //         var b = parseInt(c.substr(4, 2), 16);\n        //         var yiq = ((r * 299) + (g * 587) + (b * 114)) / 1000;\n        //         return (yiq >= 128) ? '#000000' : '#FFFFFF';\n        //     }\n        //     let alphaStr = '';\n        //     if (translucentAlpha || translucentAlpha === 0) {\n        //         if (translucentAlpha < 0 || translucentAlpha > 100) {\n        //             throw new Error(`alpha must be between 0 and 100 (E: c78faeb1477482c739b03dd32d2e1825)`);\n        //         }\n        //         if (translucentAlpha === 100) {\n        //             alphaStr = '';\n        //         } else if (translucentAlpha >= 0 && translucentAlpha < 10) {\n        //             // single digit\n        //             alphaStr = `0${translucentAlpha}`;\n        //         } else {\n        //             alphaStr = translucentAlpha.toString();\n        //         }\n        //     }\n        //     const color = `#${drivingHash.substring(0, 6)}`;\n        //     const colorTranslucent = `#${drivingHash.substring(0, 6)}${alphaStr}`;\n        //     const colorContrast = getContrastColor(color);\n        //     return [color, colorTranslucent, colorContrast];\n        // };\n\n        const [punctiliarColor, punctiliarColorTranslucent, punctiliarColorContrast] = getColorStrings(translucentAlpha, gibInfo.punctiliarHash ?? gib);\n        const [tjpColor, tjpColorTranslucent, tjpColorContrast] = !!gibInfo.tjpGib ?\n            getColorStrings(translucentAlpha, gibInfo.tjpGib) :\n            [undefined, undefined, undefined];\n\n        return {\n            gib,\n            gibInfo,\n            punctiliarColor, punctiliarColorTranslucent, punctiliarColorContrast,\n            tjpColor, tjpColorTranslucent, tjpColorContrast,\n        };\n    } catch (error) {\n        const errorMsg = `${lc} ${extractErrorMsg(error)}`;\n        console.error(errorMsg);\n        return {\n            gib: gib ?? GIB,\n            gibInfo: { isPrimitive: true },\n            punctiliarColor: '#ff0000', // red\n            punctiliarColorTranslucent: '#ff000010', // translucent red\n            punctiliarColorContrast: '#ffffff', // black\n            errorMsg,\n        };\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * gets the color, colorTranslucent and colorContrast\n */\nexport function getColorStrings(translucentAlpha: number, drivingHash: string): [string, string, string] {\n    function getContrastColor(hexcolor: string) {\n        const c = hexcolor.concat().replace(\"#\", \"\");\n        var r = parseInt(c.substr(0, 2), 16);\n        var g = parseInt(c.substr(2, 2), 16);\n        var b = parseInt(c.substr(4, 2), 16);\n        var yiq = ((r * 299) + (g * 587) + (b * 114)) / 1000;\n        return (yiq >= 128) ? '#000000' : '#FFFFFF';\n    }\n    let alphaStr = '';\n    if (translucentAlpha || translucentAlpha === 0) {\n        if (translucentAlpha < 0 || translucentAlpha > 100) {\n            throw new Error(`alpha must be between 0 and 100 (E: c78faeb1477482c739b03dd32d2e1825)`);\n        }\n        if (translucentAlpha === 100) {\n            alphaStr = '';\n        } else if (translucentAlpha >= 0 && translucentAlpha < 10) {\n            // single digit\n            alphaStr = `0${translucentAlpha}`;\n        } else {\n            alphaStr = translucentAlpha.toString();\n        }\n    }\n    const color = `#${drivingHash.substring(0, 6)}`;\n    const colorTranslucent = `#${drivingHash.substring(0, 6)}${alphaStr}`;\n    const colorContrast = getContrastColor(color);\n    return [color, colorTranslucent, colorContrast];\n};\n\n\n", "/**\n * @module helpers.web\n *\n * helper functions specific to the web version.\n */\n\nimport { delay, extractErrorMsg, pretty, } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { IbGib_V1 } from \"@ibgib/ts-gib/dist/V1/types.mjs\";\nimport { getIbGibAddr } from \"@ibgib/ts-gib/dist/helper.mjs\";\nimport { isPrimitive } from \"@ibgib/ts-gib/dist/V1/transforms/transform-helper.mjs\";\nimport { validateIbGibIntrinsically } from \"@ibgib/ts-gib/dist/V1/validate-helper.mjs\";\nimport { MetaspaceService } from \"@ibgib/core-gib/dist/witness/space/metaspace/metaspace-types.mjs\";\nimport { RawExportIbGib_V1 } from \"@ibgib/core-gib/dist/common/import-export/import-export-types.mjs\";\nimport { FlatIbGibGraph } from \"@ibgib/core-gib/dist/common/other/graph-types.mjs\";\nimport { decompressIbGibGraphFromString, deserializeStringToGraph } from \"@ibgib/core-gib/dist/common/other/other-helper.web.mjs\";\nimport { getRawExportIbGib } from \"@ibgib/core-gib/dist/common/import-export/import-export-helper.web.mjs\";\nimport { IbGibSpaceAny } from \"@ibgib/core-gib/dist/witness/space/space-base-v1.mjs\";\n\nimport {\n    GLOBAL_LOG_A_LOT, GEMINI_API_KEY_REGEXP,\n    CONFIG_OPTION_GEMINI_API_KEY_LOCATION_HELP\n} from \"./constants.mjs\";\nimport { showFullscreenDialog } from \"./ui/ui-helpers.mjs\";\nimport {\n    initializeStorage, storageCreateStoreIfNotExist, storageDBExists, storagePut\n} from \"./storage/storage-helpers.web.mjs\";\nimport { getIbGibGlobalThis_IbGib } from \"./helpers.mjs\";\n\n\n/**\n * used in verbose logging\n */\nconst logalot = GLOBAL_LOG_A_LOT;\n\n\n/**\n * converts string to Uint8Array.\n * @param str to convert\n * @returns array\n */\nexport function stringToUint8Array(str: string): Uint8Array {\n    const encoder = new TextEncoder();\n    return encoder.encode(str);\n}\n\n/**\n * converts Uint8Array to string.\n * @param array to convert\n * @returns string\n */\nexport function uint8ArrayToString(array: Uint8Array) {\n    const decoder = new TextDecoder();\n    return decoder.decode(array);\n}\n\n/**\n * I'm pulling out node from @ibgib/ibgib rcli code. This interface is just to\n * aid in that transition.\n */\nexport interface PathUtilsHelper {\n    isAbsolute(path: string): boolean;\n    isRelative(path: string): boolean;\n\n    // for now I'm taking out resolve since it requires being stateful and isn't\n    // used AFAICT in the code I'm porting over\n    // resolve(path: string): string;\n\n    join(...paths: string[]): string;\n    dirname(path: string): string;\n    basename(path: string, ext?: string): string;\n}\n\n/**\n * Helper class that exposes pathUtils functions. Note that this is relative to\n * an individual space.\n */\nexport class PathUtilsHelper implements PathUtilsHelper {\n    /** class-level log context */\n    lc: string = `[${PathUtilsHelper.name}]`;\n\n    // /**\n    //  * this path utils helper is per space, so this is the id of that space.\n    //  */\n    // spaceId: SpaceId;\n    /**\n     *\n     */\n    // constructor({ spaceId, initialCwd, }: { spaceId: SpaceId, initialCwd: string }) {\n    //     const lc = `${this.lc}[ctor]`;\n    //     this.spaceId = spaceId;\n    //     let ibGibGlobalThis = getIbGibGlobalThis();\n    //     if (!ibGibGlobalThis.spaceShim[spaceId]) {\n    //         console.log(`${lc} initializing IbGibGlobalThis data`);\n    //         // initialize\n    //         ibGibGlobalThis.spaceShim[spaceId] = {\n    //             cwd: initialCwd,\n    //             initialCwd,\n    //         };\n    //     } else {\n    //         if (logalot) { console.log(`${lc} ibgib global this already initialized (I: e48b0cb4075e536d150919e87ddc1f24)`); }\n    //     }\n    // }\n    /**\n     *\n     */\n    constructor() { }\n\n    isAbsolute(path: string): boolean {\n        if (!path) { throw new Error(`(UNEXPECTED) path falsy? (E: dcb92e11770ba06205c0afe3e6560b24)`); }\n        return path.startsWith('/');\n    }\n\n    isRelative(path: string): boolean {\n        return !this.isAbsolute(path);\n    }\n\n    // resolve(path: string): string {\n    //     const lc = `${this.lc}[${this.resolve.name}]`;\n    //     if (!path) { throw new Error(`(UNEXPECTED) path falsy? (E: 76161b12dbd446a0c2a9e18f4847fc24)`); }\n\n    //     // for our implementation, we will throw if there is a relative path\n    //     // specifier (. or ..) in the middle of the path. the proper\n    //     // implementation probably resolves these concretely.\n\n    //     if (this.isAbsolute(path)) {\n    //         if (path.includes('/../') || path.endsWith('/..')) { throw new Error(`path is absolute but contains \"/../\" in it or ends with \"../\"? (E: 16145bf37d874abc886111c32c035124)`); }\n    //         return path;\n    //     }\n\n    //     // we have a relative path. get the cwd from global for this particular space. If this space has no\n    //     let ibGibGlobalThis = getIbGibGlobalThis();\n    //     let info = ibGibGlobalThis.spaceShim[this.spaceId];\n    //     if (!info) { throw new Error(`(UNEXPECTED) no info for spaceId in ibgibglobalthis? (E: c063f34ed784e70ccd19a6b2026eb924)`); }\n\n    //     const { cwd } = info;\n    //     if (!cwd) { throw new Error(`(UNEXPECTED) cwd falsy? (E: 91cbd7418a51d9d152ae53d4f87b3a24)`); }\n    //     if (path.startsWith(cwd)) {\n    //         console.log(`${lc} path already resolved (starts with cwd). path: ${path} (I: 1d99a4bad47398174fe127b85088fb24)`);\n    //     }\n    //     if (cwd.endsWith('/')) {\n    //         // cwd does end with slash, so slice off initial if needed\n    //         return cwd + (path.startsWith('/') ? path.slice(1) : path);\n    //     } else {\n    //         // cwd does NOT end with slash, so add if needed\n    //         return cwd + (path.startsWith('/') ? path : `/${path}`);\n    //     }\n    // }\n\n    join(...paths: string[]): string {\n        const lc = `${this.lc}[${this.join.name}]`;\n\n        if (paths.length === 0) {\n            console.log(`${lc} paths.length === 0. returning '.' per node convention. (I: 153da80765ff6160675fae895ebac225)`);\n            return '.'; /* <<<< returns early */\n        }\n        if (paths.length === 1 && paths[0] === '..') {\n            console.log(`${lc} paths.length === 1 && paths[0] === '..'.  returning '..' per node convention. (I: 9af242b7615430a8c6899b1a332e9925)`);\n            return '..'; /* <<<< returns early */\n        }\n\n        let joined = '';\n        for (let i = 0; i < paths.length; i++) {\n            let path = paths[i];\n            if (path === '..') {\n                joined = joined.split('/').slice(0, -1).join('/');\n            } else {\n                if (path.startsWith('/')) { path = path.slice(1); }\n                if (path.endsWith('/')) {\n                    path = path.slice(0, -1);\n                }\n                joined += (i > 0 ? '/' : '') + path;\n            }\n        }\n\n        return joined;\n    }\n\n    dirname(path: string): string {\n        return path.split('/').slice(0, -1).join('/');\n    }\n\n    basename(path: string, ext?: string): string {\n        return path.split('/').pop() ?? '';\n    }\n}\n\n\nexport async function copyToClipboard({\n    data,\n    logalot,\n}: {\n    data: { title?: string, text?: string, url?: string },\n    logalot?: boolean,\n}): Promise<void> {\n    const lc = `[${copyToClipboard.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 37d6a4e3c3ee9fa46a0b1cd5c8a5cf24)`); }\n        let { title, text, url } = data;\n        const textToCopy = [\n            `${data.title || ''}`,\n            `${data.text || ''}`,\n            `${data.url || ''}`,\n        ].join('\\n').trim();\n        await navigator.clipboard.writeText(textToCopy);\n        console.log('Content copied to clipboard!');\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * helper to trigger browser's share functionality (or fallback).\n */\nexport async function shareContent({\n    data,\n    logalot,\n}: {\n    data: { title?: string, text?: string, url?: string },\n    logalot?: boolean,\n}): Promise<void> {\n    const lc = `[${shareContent.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: bfc7e484eba91f9126c3f5fc381e6424)`); }\n\n        if (navigator.share) {\n            await navigator.share(data);\n            console.log('Content shared successfully!');\n        } else {\n            console.warn('Web Share API not supported. Copying to clipboard instead.');\n            alert(`Share info copied to clipboard!`);\n            await copyToClipboard({ data, logalot });\n        }\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * useful for knowing if we are executing in our website or within an iframe.\n *\n * ## driving use case\n *\n * When we are loading an embedded iframe for link-gib, it is trying to trigger\n * the router which is no bueno.\n *\n * This is causing a problem though when testing inside an iframe in Project\n * IDX...I guess I'll have to whitelist embedded sites like link-gib\n *\n * ## usage\n *\n * Put something like this in the html in <head>:\n * ```html\n * <meta name=\"ibgib-app-id-yo\" content=\"0f73bca49d2856a446044768fbab8d25\" />\n * ```\n * Then create constants like this (I put them in a constants file):\n *\n * ```typescript\n * export const HTML_META_APP_ID_NAME = \"ibgib-app-id-yo\";\n * export const HTML_META_APP_ID_CONTENT = \"0f73bca49d2856a446044768fbab8d25\";\n * ```\n *\n * Then you can call this like this:\n *\n * ```typescript\n * const isInWebAppProper = isExecutingInBlankGibWebAppProper({\n *   metaName_appId: HTML_META_APP_ID_NAME,\n *   metaContent_appId: HTML_META_APP_ID_CONTENT\n * });\n * ```\n *\n * @returns true if we are executing in an iframe, false otherwise.\n */\nexport function isExecutingInBlankGibWebAppProper({\n    metaName_appId,\n    metaContent_appId\n}: {\n    /**\n     * this runs code:\n     *\n     * `const metaElement = document.querySelector(`meta[name=${metaName_appId}]`) as (HTMLMetaElement | null);`\n     *\n     * in the index, you should tag the meta tag with attribute of this.\n     */\n    metaName_appId: string,\n    /**\n     * this is an appId on the `metaElement.content`\n     */\n    metaContent_appId: string,\n}): boolean {\n    const metaElement =\n        document.querySelector(`meta[name=${metaName_appId}]`) as (HTMLMetaElement | null);\n    return !!metaElement && metaElement.content === metaContent_appId;\n}\n\n/**\n * Low-level plumbing for prompting the user for some text.\n *\n * ## notes\n *\n * * if an empty string is entered, confirm is automatic/always happens.\n * * if confirm is true, will confirm on any entry\n * * can just hit ENTER to confirm anything\n *   * this should be parameterized\n *\n * @returns the text the user entered.\n */\nexport async function promptForText({\n    msg,\n    title,\n    confirm,\n    noNewLine,\n    rl,\n    defaultValue,\n    dontCloseRl,\n    cancelable,\n}: {\n    msg: string,\n    title?: string,\n    confirm?: boolean,\n    noNewLine?: boolean,\n    /**\n     * ignored in web version. used in node version. this is after all, a hack\n     * port\n     */\n    rl?: any,\n    defaultValue?: string,\n    /**\n     * ignored in web version. used in node version. this is after all, a hack\n     * port\n     */\n    dontCloseRl?: boolean,\n    /**\n     * if true, cancel will show and an empty string will be returned\n     */\n    cancelable?: boolean,\n}): Promise<string> {\n    const lc = `[${promptForText.name}]`;\n    try {\n        if (!msg) { throw new Error(`msg required (E: 7f4d67bca4cf98ea95fa110aabc98924)`); }\n\n        let result: string | undefined;\n\n        let attempts = 0;\n        let maxAttempts = 5;\n        do {\n            attempts++;\n            if (attempts >= maxAttempts) {\n                throw new Error(`max attempts reached (E: 1ef20ae955622d4b39479f3da91a1d25)`);\n            }\n            await delay(50);\n            result = await showFullscreenDialog({\n                title: title || 'Prompt for Info',\n                msg,\n                prompt: true,\n                showInput: true,\n                isPassword: false,\n                defaultValue,\n            });\n\n        } while (result === undefined && !cancelable);\n\n        return result ?? '';\n\n        // let userText: string | undefined = undefined;\n        // try {\n        //     do {\n        //         title = title ? `[${title}] ` : '';\n        //         let promptMessage = `${title}${msg}${noNewLine ? ' ' : '\\n'}`;\n        //         let prompt = window.prompt;\n\n        //         // Handle default value (Note: `prompt` can't pre-fill like readline.write)\n        //         if (defaultValue) {\n        //             if (defaultValue.includes('\\n')) {\n        //                 if (logalot) { console.log(`defaultValue includes newline. (I: 147d4ea942995d0f92a19c3534c18a24)`); }\n        //                 // We can't pre-fill with newline in prompt, so we'll just inform if needed\n        //             }\n        //             promptMessage += ` (Default: ${defaultValue})`;\n        //         }\n\n        //         let userText1 = prompt(promptMessage);\n\n        //         // Check for cancellation (prompt returns null on cancel)\n        //         if (userText1 === null) {\n        //             // return null; // User cancelled\n        //             throw new Error(`user cancelled (E: bf3a221626f8cd14b2a945bfe661cb24)`);\n        //         }\n\n        //         if (userText1 === \"\") {\n        //             let userText2 = prompt(`empty string entered. confirm:${noNewLine ? ' ' : '\\n'}`);\n        //             if (userText2 === userText1) {\n        //                 userText = userText1;\n        //                 break;\n        //             } else {\n        //                 console.log(`confirm failed. please try again.`);\n        //             }\n        //         } else if (confirm) {\n        //             let userText2 = prompt(`confirm by either hitting ENTER (empty string) or retype input:${noNewLine ? ' ' : '\\n'}`);\n        //             if (userText2 === '' || userText2 === userText1) {\n        //                 userText = userText1;\n        //             } else {\n        //                 console.log(`confirm failed. please try again.`);\n        //             }\n        //         } else {\n        //             userText = userText1;\n        //         }\n\n        //     } while (userText === undefined);\n\n        //     return userText;\n\n        // } catch (error) {\n        //     throw error;\n        // }\n    } catch (error) {\n        debugger; // in error block promptForText\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    }\n}\n\n/**\n * not implemented atow (12/2024). I think we'll have perhaps a modal dialog\n * with a known name and get at it that way.\n */\nexport async function promptForSecret({\n    msg,\n    confirm,\n}: {\n    msg?: string,\n    confirm: boolean,\n}): Promise<string> {\n    const lc = `[${promptForSecret.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 795a4ce348ddb9a5119770f4c572ac24)`); }\n\n        let result: string | undefined = undefined;\n\n        let firstTry = true;\n        let attempts = 0;\n        let maxAttempts = 5;\n\n        do {\n            attempts++;\n            if (attempts >= maxAttempts) {\n                throw new Error(`max attempts reached (E: d4166b4bf37aff0c6d44567792e9ad25)`);\n            }\n            await delay(50);\n            result = await showFullscreenDialog({\n                title: firstTry ? 'Shh...' : 'Secrets didn\\'t match, try again...',\n                msg: msg || 'Enter Your Secret...',\n                prompt: true,\n                showInput: true,\n                isPassword: true,\n                defaultValue: undefined,\n            });\n            if (result === undefined) { throw new Error(`user cancelled (E: 91519d04378e84106f3df8eb36d99725)`); }\n\n            if (confirm) {\n                await delay(250);\n                let result2 = await showFullscreenDialog({\n                    title: 'Shh...',\n                    msg: 'Confirm...',\n                    prompt: true,\n                    showInput: true,\n                    isPassword: true,\n                    defaultValue: undefined,\n                });\n                if (result2 === undefined) { result = undefined; }\n                if (result !== result2) {\n                    result = undefined;\n                    firstTry = false;\n                    await delay(250);\n                }\n            }\n\n\n        } while (result === undefined);\n\n        return result;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * prompt specifically looking to confirm something. if \"cancelled\", returns\n * false.\n */\nexport async function promptForConfirm({\n    msg,\n    yesLabel,\n    noLabel,\n}: {\n    /**\n     * if provided, this is the message displayed when confirming.\n     */\n    msg?: string,\n    yesLabel?: string,\n    noLabel?: string,\n}): Promise<boolean> {\n    const lc = `[${promptForConfirm.name}]`;\n    try {\n        await delay(50);\n        let result = await showFullscreenDialog({\n            title: 'Confirm?',\n            msg: msg ?? 'Confirm?',\n            okButtonTitle: yesLabel || undefined,\n            cancelButtonTitle: noLabel || undefined,\n            prompt: true,\n        });\n        return !!result;\n        // msg ||= 'confirm?';\n        // yesLabel ||= '(y)es';\n        // noLabel ||= '(n)o';\n        // try {\n        //     const fnAnswerMatchesLabel = (answer: string, label: string) => {\n        //         if (answer === label.replace(/[\\(\\)]/g, '').toLowerCase()) {\n        //             // matched full label\n        //             return true; /* <<<< returns early */\n        //         } else {\n        //             // check for short answers\n        //             const regexCaptureCharsInsideParens = /\\((\\w+)\\)/;\n        //             const shortLabel = label.match(regexCaptureCharsInsideParens);\n        //             if ((shortLabel ?? []).length >= 2) {\n        //                 if (answer === shortLabel![1].toLowerCase()) {\n        //                     // matched short label\n        //                     return true; /* <<<< returns early */\n        //                 }\n        //             }\n        //         }\n        //         // if got this far, nothing positive matched\n        //         return false;\n        //     };\n\n        //     const prompt = window.prompt;\n\n        //     // try up to three times. if match found, either way, return early.\n        //     const maxTries = 3;\n        //     for (let i = 0; i < maxTries; i++) {\n        //         let answer = prompt(`${msg} [${yesLabel}, ${noLabel}]\\n`);\n        //         if (answer) {\n        //             answer = answer.toLowerCase();\n        //             const matchesYesLabel = fnAnswerMatchesLabel(answer, yesLabel);\n        //             if (matchesYesLabel) { return true; /* <<<< returns early */ }\n        //             const matchesNoLabel = fnAnswerMatchesLabel(answer, noLabel);\n        //             if (matchesNoLabel) { return false; /* <<<< returns early */ }\n        //         } else {\n        //             `no answer provided. defaulting to no...`;\n        //             console.log('huh?');\n        //         }\n        //     }\n\n        //     // max tries reached\n        //     throw new Error(`could not confirm (E: ebbd2f642bde103c41d0102cf7e38d24)`);\n        // } catch (error) {\n        //     throw error;\n        // }\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport async function alertUser({\n    msg,\n    title,\n    skipHitEnterToContinue,\n}: {\n    msg: string,\n    title?: string,\n    /**\n     * ignored in web version atow (12/2024)\n     */\n    skipHitEnterToContinue?: boolean,\n}): Promise<void> {\n    const lc = `[${alertUser.name}]`;\n    try {\n\n        if (!msg) { throw new Error(`msg required (E: ffcf7dd00324df7cea2792223d229524)`); }\n        try {\n            title ??= '';\n            await delay(50);\n            await showFullscreenDialog({\n                title,\n                msg,\n            });\n        } catch (error) {\n            throw error;\n        }\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    }\n}\n\nexport function getUserPreferredColorScheme(): 'light' | 'dark' {\n    const lc = `[${getUserPreferredColorScheme.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 196286d17b656bce5ce16f358f386525)`); }\n        const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;\n        return prefersDark ? 'dark' : 'light';\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * helper function to get a query param in the current url.\n *\n * # ONLY IN BROWSER\n *\n * not for use in node.js\n *\n * @returns raw\n */\nexport function getQueryParam<TValue>({ paramName, parseJSON, logalot, }: {\n    paramName: string, parseJSON?: boolean, logalot?: boolean,\n}): TValue | undefined {\n    const lc = `[${getQueryParam.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: f1a61ecdbb52cff1b958d1ceaea85f24)`); }\n\n        const url = new URL(window.location.href);\n        const rawValue = url.searchParams.get(paramName);\n        if (rawValue) {\n            const decodedValue = decodeURIComponent(rawValue);\n            if (parseJSON) {\n                try {\n                    return JSON.parse(decodedValue) as TValue;\n                } catch (parseError) {\n                    console.error(`${lc} Error parsing JSON from query parameter ${paramName}: ${parseError} (E: fa8128dbe8ed41fc9fdf57a8146d88de)`);\n                    throw parseError;\n                }\n            } else {\n                return decodedValue as TValue;\n            }\n        } else {\n            return undefined;\n        }\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * helper function to set a query param in the current url.\n *\n * # ONLY IN BROWSER\n *\n * not for use in node.js\n */\nexport function setQueryParam<TValue>({\n    paramName, paramValue, rmParam, logalot,\n}: {\n    paramName: string,\n    paramValue?: TValue,\n    /**\n     * if true, we will remove the param from the URL.\n     */\n    rmParam?: boolean,\n    logalot?: boolean,\n}): void {\n    const lc = `[${setQueryParam.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: f3c557d19f5b3a723611c59aa4a20324)`); }\n        const url = new URL(window.location.href);\n\n        if (rmParam) {\n            url.searchParams.delete(paramName);\n        } else {\n            const actualValue = typeof paramValue === 'string' ?\n                paramValue :\n                JSON.stringify(paramValue);\n            url.searchParams.set(paramName, actualValue);\n        }\n\n        // Update the URL without reloading the page\n        window.history.replaceState({}, '', url.toString());\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * helper to highlight an element with border/background.\n *\n * ## requires\n *\n * .highlight and .unhighlight classes\n *\n * The unhighlight is for correctly showing the transition/animation.\n *\n * ## intent\n *\n * Just making this to make highlighting things (drawing the user's eye)\n * easier and more consistent.\n *\n * @see {@link unhighlightElement}\n */\nexport async function highlightElement({\n    el,\n    magicHighlightTimingMs,\n    scrollIntoView,\n}: {\n    el: HTMLElement,\n    /**\n     * if provided, will unhighlight the element after this delay in ms\n     */\n    magicHighlightTimingMs?: number,\n    scrollIntoView?: boolean,\n}): Promise<void> {\n    const lc = `[${highlightElement.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 1820329f88bb937b21ff98e624c03e25)`); }\n\n        if (scrollIntoView) { el.scrollIntoView({ behavior: 'smooth' }); }\n\n        el.classList.add('highlight');\n        if (magicHighlightTimingMs) {\n            await delay(magicHighlightTimingMs);\n            el.classList.add('unhighlight');\n            el.classList.remove('highlight');\n            await delay(magicHighlightTimingMs);\n            el.classList.remove('unhighlight');\n        }\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * @see {@link highlightElement}\n */\nexport async function unhighlightElement({\n    el,\n}: {\n    el: HTMLElement,\n}): Promise<void> {\n    const lc = `[${unhighlightElement.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: ee5894b05ec31085883098cc512e1c25)`); }\n\n        el.classList.add('unhighlight');\n        el.classList.remove('highlight');\n        await delay(500);\n        el.classList.remove('unhighlight');\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * Takes an incoming string. Assumes it's invalid. Does best effort at validating this.\n * Gets the raw export ibgib if it can. If so, and if it is compressed, decompresses the\n * compressed graph contained in the export ibgib.\n *\n * @returns RawExportIbGib_V1 and its decompressed graph\n */\nexport async function getRawExportIbGibAndGraphFromJsonString({\n    exportIbGibJsonString,\n    metaspace,\n}: {\n    exportIbGibJsonString: string,\n    metaspace: MetaspaceService,\n}): Promise<[RawExportIbGib_V1, FlatIbGibGraph]> {\n    const lc = `[${getRawExportIbGibAndGraphFromJsonString.name}]`;\n    try {\n        debugger; // walk thru getRawExportIbGibAndGraphFromJsonString\n        if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n        if (!metaspace) { throw new Error(`(UNEXPECTED) metaspace falsy? (E: genuuid)`); }\n\n        const space = await metaspace.getLocalUserSpace({ lock: false });\n        if (!space) { throw new Error(`(UNEXPECTED) couldn't get default local user space? (E: genuuid)`); }\n\n        let parsedIbGib_notYetValidated: IbGib_V1;\n        let parsedExportIbGib_dependenciesNotValidated: RawExportIbGib_V1;\n        try {\n            parsedIbGib_notYetValidated = JSON.parse(exportIbGibJsonString) as IbGib_V1;\n        } catch (error) {\n            const emsg = `Error during parse JSON. error: ${extractErrorMsg(error)} (E: genuuid)`;\n            const errorHack = new Error(emsg);\n            (errorHack as any).cause = error;\n            throw errorHack;\n        }\n        try {\n            const validationErrors = await validateIbGibIntrinsically({ ibGib: parsedIbGib_notYetValidated }) ?? [];\n            if (validationErrors.length > 0) {\n                throw new Error(`validation errors when validating the parsed ibgib that should be a RawExportIbGib_V1: ${validationErrors} (E: 8ba178d3b26e8eca28a67c182fe16825)`);\n            }\n            // todo: other validation raw export ibgib, maybe to see if it's a full dependency graph, etc.\n\n            parsedExportIbGib_dependenciesNotValidated = parsedIbGib_notYetValidated as RawExportIbGib_V1;\n            if (!parsedExportIbGib_dependenciesNotValidated.data) { throw new Error(`(UNEXPECTED) rawExportIbGib.data falsy? (E: ef1824d1cca5584ab8e34288346e9825)`); }\n        } catch (error) {\n            const emsg = `Error during parse JSON. error: ${extractErrorMsg(error)} (E: genuuid)`;\n            const errorHack = new Error(emsg);\n            (errorHack as any).cause = error;\n            throw errorHack;\n        }\n\n\n\n        // at this point, we have a possibly quite large ibGib whose data\n        // includes a dependencyGraphAsString. this could possibly be\n        // compressed.\n        let payloadGraph: FlatIbGibGraph;\n        if (!!parsedExportIbGib_dependenciesNotValidated.data.compression) {\n            switch (parsedExportIbGib_dependenciesNotValidated.data.compression) {\n                case 'gzip':\n                    payloadGraph = await decompressIbGibGraphFromString({\n                        compressedBase64: parsedExportIbGib_dependenciesNotValidated.data.dependencyGraphAsString,\n                    });\n                    break;\n                default:\n                    throw new Error(`unknown value of rawExportIbGib.data.compression: ${parsedExportIbGib_dependenciesNotValidated.data.compression} (E: 784672fae568312d887ddbb841199925)`);\n            }\n        } else {\n            payloadGraph = await deserializeStringToGraph({\n                jsonString: parsedExportIbGib_dependenciesNotValidated.data.dependencyGraphAsString\n            });\n        }\n\n        const validationErrorMap: { [addr: string]: string[] } = {};\n        for (const [addr, payloadIbGib] of Object.entries(payloadGraph)) {\n            const validationErrors = await validateIbGibIntrinsically({ ibGib: payloadIbGib }) ?? [];\n            if (validationErrors.length > 0) { validationErrorMap[addr] = validationErrors; }\n        }\n        if (Object.keys(validationErrorMap).length > 0) {\n            throw new Error(`there were validation errors for the RawExportIbGib_V1.data payload (contained in data.dependencyGraphAsString). Here is the validationErrorMap:\\n${pretty({ validationErrorMap })} (E: e63f38b182a84122d83a55befb369825)`);\n        }\n        const exportIbGib_validated = parsedExportIbGib_dependenciesNotValidated;\n\n        return [exportIbGib_validated, payloadGraph];\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * exports a given ibgib to the default local userspace in the metaspace.\n */\nexport async function exportIbGib({\n    ibGib,\n    compress,\n    // downloadAnchorEl,\n    metaspace,\n    space,\n}: {\n    ibGib: IbGib_V1,\n    compress: boolean,\n    // downloadAnchorEl: HTMLAnchorElement,\n    metaspace: MetaspaceService,\n    space: IbGibSpaceAny,\n}): Promise<void> {\n    const lc = `[${exportIbGib.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 623d9463d919683be81f749821a95825)`); }\n        if (isPrimitive({ ibGib })) { throw new Error(`ibGib is primitive. Can't export primitive. (E: dd42c42e9fda0707e81c692af1a2a225)`); }\n\n        const resGetExport = await getRawExportIbGib({\n            ibGib,\n            live: true,\n            compress,\n            metaspace: metaspace,\n            space,\n        });\n\n        const { rawExportIbGib: exportIbGib, errors: exportErrors } = resGetExport;\n        if ((exportErrors ?? []).length > 0) { throw new Error(`Export had errors: ${exportErrors!} (E: 05faf83f25d3449ab809dfd24eeaf825)`); }\n\n        // at this point, we have a possibly quite large ibGib whose data includes\n        // every single other ibgib that ibGib relates to (its dependency graph). This\n        // so now we can save this file and later import from it.\n\n        /**\n         * exportIbGib is guaranteed to have a serializable structure, i.e.,\n         * the data has only primitives. (there are no Uint8Array)\n         */\n        const exportIbGibAsString = JSON.stringify(exportIbGib);\n\n        // thank you SO, OP and volzotan at https://stackoverflow.com/questions/19721439/download-json-object-as-a-file-from-browser\n        // set the anchor's href to a data stream\n        const dataStr = \"data:text/json;charset=utf-8,\" + encodeURIComponent(exportIbGibAsString);\n\n        // get the filename for the anchor to suggest for the \"download\"\n        const exportAddr = getIbGibAddr({ ibGib: exportIbGib });\n        const filename = `${exportAddr}.json`;\n\n        // trigger the click\n        const downloadAnchorEl = document.createElement('a');\n        downloadAnchorEl.setAttribute(\"style\", \"none\");\n        downloadAnchorEl.setAttribute(\"href\", dataStr);\n        downloadAnchorEl.setAttribute(\"download\", filename);\n        const div = document.getElementsByTagName('div')[0]; // just append to the first div then remove it\n        div.appendChild(downloadAnchorEl);\n        downloadAnchorEl.click();\n        div.removeChild(downloadAnchorEl);\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport async function promptForAPIKey({\n    msg,\n}: {\n    /**\n     * msg to tell the user when prompting for the API key (secret)\n     *\n     * originally in blankgib, this is CHAT_WITH_AGENT_NEED_API_KEY\n     */\n    msg: string,\n}): Promise<string | undefined> {\n    const lc = `[${promptForAPIKey.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n        let resAPIKey = '';\n        let tryAgain = false;\n        let attempts = 0;\n        let maxAttempts = 5;\n        do {\n            attempts++;\n            if (attempts >= maxAttempts) { throw new Error(`too many attempts (E: genuuid)`); }\n            resAPIKey = await promptForSecret({\n                msg,\n                confirm: false,\n            });\n            if (resAPIKey) {\n                if (resAPIKey.match(GEMINI_API_KEY_REGEXP)) {\n                    tryAgain = false;\n                    // return resAPIKey; /* <<<< returns early */\n                } else {\n                    await alertUser({\n                        title: `That's an API Key?`,\n                        msg: `That doesn't look like a valid API key, please try again, or hit cancel if you don't want to at this time.`,\n                    });\n                    tryAgain = true;\n                }\n            } else {\n                console.log(`${lc} user cancelled entering API key. (I: genuuid)`);\n                tryAgain = false;\n            }\n        } while (tryAgain);\n\n        return resAPIKey;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * updates the given {@link apiKey}. if {@link force} is true and `apiKey` is\n * empty, then this will set an empty string for the apiKey, effectively\n * deleting it.\n */\nexport async function updateAPIKeyInStorage({\n    dbName,\n    storeName,\n    key,\n    apiKey,\n    force,\n}: {\n    dbName: string,\n    storeName: string,\n    key: string,\n    apiKey: string,\n    force: boolean,\n}): Promise<void> {\n    const lc = `[${updateAPIKeyInStorage.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 64951b38da35ec5ff847004d53b2d425)`); }\n\n        const matches = apiKey.match(GEMINI_API_KEY_REGEXP);\n        if (matches || force) {\n            await storagePut({\n                dbName, storeName,\n                key,\n                value: apiKey,\n            });\n            if (apiKey) {\n                // set a new truthy key\n                await alertUser({ title: `need to reload...`, msg: `Cool! We successfully SAVED your Gemini API key in your browser's IndexedDB.\\n\\nIf you'd like to remove it later, you can clear it out by using the ${CONFIG_OPTION_GEMINI_API_KEY_LOCATION_HELP}.\\n\\nWe must now reload the page to use the new API key... (investment would be a good thing to improve this UX workflow!)` });\n            } else {\n                // cleared out the key\n                await alertUser({ title: `need to reload...`, msg: `Cool! We successfully CLEARED your Gemini API key from your browser's IndexedDB.\\n\\nIf you'd like to set a new key, use the ${CONFIG_OPTION_GEMINI_API_KEY_LOCATION_HELP}.\\n\\nThe API key is already removed, but we must now reload the page for this to propagate throughout the web page... (investment would be a good thing to improve this UX workflow!)` });\n            }\n            window.location.reload();\n        } else {\n            throw new Error(`apiKey does not match apiKeyRegex (${GEMINI_API_KEY_REGEXP.source}) and force is false. (E: 2d6c798803e6b71bf6aa70bd60170825)`);\n        }\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n\n}\n\n/**\n * wrapper for simplifying/asserting an element that is expected to exist.\n *\n * ## intent\n *\n * This avoids using TypeScript truthy assertions (!) or excessive\n * falsy/exception checks.\n */\nexport function getElementById_throwsIfFalsy<TElement extends Element>({\n    id,\n    shadowRoot,\n}: {\n    id: string;\n    /**\n     * If set, will get element here, else will use document\n     */\n    shadowRoot?: ShadowRoot;\n}): TElement {\n    const lc = `[${getElementById_throwsIfFalsy.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 18a338c6dab8690c72b8759b8d952925)`); }\n        let resElement = !!shadowRoot ?\n            shadowRoot.getElementById(id) as TElement | null :\n            document.getElementById(id) as TElement | null;\n\n        if (resElement) {\n            return resElement;\n        } else {\n            throw new Error(`${!!shadowRoot ? 'shadowRoot' : 'document'}.getElementById(${id}) returned null. So...Element was not found. (E: 5e501f6835cc74cd4c2faf0d9e387825)`);\n        }\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * wrapper that throws if element not found.\n * @param id of Element\n * @returns Element of type TElement or throws.\n * @see {@link shadowRoot_getElementById}\n *\n * ## intent\n *\n * This avoids using TypeScript truthy assertions (!) or excessive\n * falsy/exception checks.\n */\nexport function document_getElementById<TElement extends Element = HTMLElement>(id: string): TElement {\n    return getElementById_throwsIfFalsy<TElement>({ id });\n}\n\n/**\n * wrapper that throws if element not found.\n * @param shadowRoot in which the element MUST be truthy or throws\n * @param id of Element\n * @returns Element of type TElement or throws.\n * @see {@link document_getElementById}\n *\n * ## intent\n *\n * This avoids using TypeScript truthy assertions (!) or excessive\n * falsy/exception checks.\n */\nexport function shadowRoot_getElementById<TElement extends Element = HTMLElement>(shadowRoot: ShadowRoot, id: string): TElement {\n    return getElementById_throwsIfFalsy<TElement>({ id, shadowRoot });\n}\n\nexport function getGlobalStoreName(): string {\n    const lc = `[${getGlobalStoreName.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 62a29f9982b4b5ecd91ff58ca4dd6825)`); }\n        // ARMY_STORE in blankgib\n        const hackGlobal = getIbGibGlobalThis_IbGib();\n        if (!hackGlobal.storeName_hack) { throw new Error(`(UNEXPECTED) global store name falsy? (E: 3b9b680f6a980debbb877c9a13fb2625)`); }\n        return hackGlobal.storeName_hack;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport function getGlobalDbName(): string {\n    const lc = `[${getGlobalDbName.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 8c8f08728fc7384f87697377358cc825)`); }\n        //    BLANK_GIB_DB_NAME in blankgib\n        const hackGlobal = getIbGibGlobalThis_IbGib();\n        if (!hackGlobal.dbName_hack) { throw new Error(`(UNEXPECTED) global db name falsy? (E: 3aa028d5e4088f3f3841aae94ac02825)`); }\n        return hackGlobal.dbName_hack;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport function getGlobalIndexedDbKey_APIKey(): string {\n    const lc = `[${getGlobalIndexedDbKey_APIKey.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 59a2510a85051f97ed15fbc8825b6825)`); }\n        // BEE_KEY in blankgib\n        const hackGlobal = getIbGibGlobalThis_IbGib();\n        if (!hackGlobal.apiKeyName_hack) { throw new Error(`(UNEXPECTED) global api key name falsy? (E: 1782e812f0c87f54b8059468a5b60125)`); }\n        return hackGlobal.apiKeyName_hack;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * helper info for {@link initAppStorage}\n */\ninterface AppStorageInfo {\n    dbName: string;\n    storeNames: string[];\n}\n/**\n * ensures db and stores are created and can be used.\n */\nexport async function initAppStorage({\n    infos,\n}: {\n    infos: AppStorageInfo[],\n}): Promise<void> {\n    const lc = `[${initAppStorage.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 4d41880fb748ee2302a624a255665825)`); }\n\n        for (const info of infos) {\n            const { dbName, storeNames } = info;\n            const dbExists = await storageDBExists({\n                dbName,\n                // dbName: BLANK_GIB_DB_NAME,\n            });\n            if (!dbExists) {\n                await initializeStorage({\n                    dbName,\n                    // dbName: BLANK_GIB_DB_NAME,\n                });\n            }\n            for (const storeName of storeNames) {\n                await storageCreateStoreIfNotExist({\n                    dbName,\n                    storeName,\n                    // dbName: BLANK_GIB_DB_NAME,\n                    // storeName: ARMY_STORE,\n                });\n            }\n            // await storageCreateStoreIfNotExist({\n            //     dbName: BLANK_GIB_DB_NAME,\n            //     storeName: ARMY_STORE,\n            // });\n\n            // await storageCreateStoreIfNotExist({\n            //     dbName: BLANK_GIB_DB_NAME,\n            //     storeName: ZERO_SPACE_ID,\n            //     logalot,\n            // });\n        }\n\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n", "/**\n * @module component-one-file.mts contains all the types, helpers, constants and\n * classes for the **shell** ui component system. the differentiating factor\n * between this system and other front end ui frameworks is that this is\n * ibgib-driven, with especially ibgib addresses driving components' backing\n * model/data.\n *\n * this is not to be confused with \"components\" that may be dynamically\n * generated within a blank-canvas environment that the canvas agents will\n * build. this is for the old-school html shell.\n *\n * the ui component system is being built piecemeal as we go.\n *\n * ## approach\n *\n * there are two basic pieces to a component: the component metadata declaration\n * and the concrete component instance that that declaration instantiates. these\n * will be tightly coupled per use-case, with the intention that the meta object\n * will not need to be a descendant class, whereas the component instance will\n * most likely be the class that is extended from an abstract base class.\n *\n * @see {@link IbGibDynamicComponentMeta}\n * @see {@link IbGibDynamicComponentInstance}\n */\n\nimport { extractErrorMsg, } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { IbGibAddr } from \"@ibgib/ts-gib/dist/types.mjs\";\n\nimport { GLOBAL_LOG_A_LOT } from \"../../constants.mjs\";\nimport { IbGibDynamicComponentInstance, IbGibDynamicComponentMeta } from \"./component-types.mjs\";\n\nconst logalot = GLOBAL_LOG_A_LOT;\n/**\n * Service for managing dynamic ibgib-aware components via web components.\n */\nexport class IbGibComponentService {\n    protected lc: string = `[${IbGibComponentService.name}]`;\n    /**\n     * @internal references to component meta's registered with the service.\n     */\n    private _registeredComponentsMeta: IbGibDynamicComponentMeta[] = [];\n\n    initialized: Promise<void>;\n\n    constructor() {\n        this.initialized = this.initialize();\n    }\n\n    private async initialize(): Promise<void> {\n        const lc = `[${this.initialize.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 1cf04e8d768f4b5c55e7c3861e2d2225)`); }\n            console.log(`${lc} does nothing atow (I: 65bb46c88c82b637ad928b8bf1a07225)`)\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * Registers a dynamic ibgib-aware component META object with the service.\n     * @param {IbGibDynamicComponentMeta} componentMeta - The component meta object to register.\n     */\n    registerComponentMeta(componentMeta: IbGibDynamicComponentMeta): void {\n        this._registeredComponentsMeta.push(componentMeta);\n        if (logalot) { console.log(`${this.lc}[registerComponentMeta] component meta registered: ${componentMeta.constructor.name} (I: 88ddcbd0c8caa2342af0e7348f171225)`); }\n    }\n\n    /**\n     * Unregisters a dynamic ibgib-aware component META object from the service.\n     * @param {IbGibDynamicComponentMeta} componentMeta - The component meta object to unregister.\n     */\n    unregisterComponentMeta(componentMeta: IbGibDynamicComponentMeta): void {\n        this._registeredComponentsMeta = this._registeredComponentsMeta.filter(c => c !== componentMeta);\n        if (logalot) { console.log(`${this.lc}[unregisterComponentMeta] component meta unregistered: ${componentMeta.constructor.name} (I: 4e84b5274de688248984896a90f5cc25)`); }\n    }\n\n    async getComponentInstance({\n        useRegExpPrefilter,\n        path,\n        ibGibAddr,\n    }: {\n        useRegExpPrefilter: boolean,\n        path: string,\n        ibGibAddr: IbGibAddr,\n    }): Promise<IbGibDynamicComponentInstance | undefined> {\n        const lc = `${this.lc}[${this.getComponentInstance.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 684ef316cbdb4a3b1fdc96096c273b25)`); }\n\n            let componentToInject: IbGibDynamicComponentInstance | undefined = undefined;\n\n            // 1. Get registered components from the component service (NEW)\n            const registeredComponents = componentSvc.getRegisteredComponentsMeta();\n\n            // 2. Filter by routeRegExp (quick filter)\n            const possibleComponentsMeta = useRegExpPrefilter ?\n                registeredComponents.filter(component => {\n                    const componentMatchesPath = component.routeRegExp ? component.routeRegExp.test(path) : false;\n                    if (logalot) { console.log(`${lc} ${component.componentName} ${component.routeRegExp} componentMatchesPath: ${componentMatchesPath} (I: 3758520e6a4a57f218396c8649283425)`); }\n                    return componentMatchesPath;\n                }) :\n                registeredComponents.concat();\n\n            // 3. Iterate and call fnHandleRoute for finer-grained check\n            for (const componentMeta of possibleComponentsMeta) {\n                /**\n                 * order of component registration wins right now\n                 */\n                const componentHandlesPath = componentMeta.fnHandleRoute ?\n                    await componentMeta.fnHandleRoute({ path, ibGibAddr }) :\n                    true;\n                if (componentHandlesPath) {\n                    componentToInject = await componentMeta.createInstance({\n                        path, ibGibAddr,\n                    });\n                    break; // Stop on first component that handles the route\n                }\n            }\n\n            return componentToInject;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * Injects a dynamic ibgib-aware component into a parent HTML element based on the route path.\n     *\n     * @param {object} arg - Arguments object.\n     * @param {HTMLElement} arg.parentEl - The parent HTML element where the component should be injected.\n     * @param {string} arg.path - The route path to determine which component to load.\n     * @param {IbGibAddr} [arg.ibGibAddr] - Optional ibGib address parsed from the route path.\n     * @returns {Promise<void>} - Promise that resolves when the component is injected and created.\n     */\n    async inject({\n        parentEl,\n        componentToInject,\n    }: {\n        parentEl: HTMLElement,\n        componentToInject: IbGibDynamicComponentInstance,\n    }): Promise<void> {\n        const lc = `${this.lc}[${this.inject.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 6844cf07eaf8a5b1b106784f7db17125)`); }\n\n            if (!parentEl) { throw new Error(`${lc} parentEl required. (E: 6f4eb2d682856ef47d173b970ec3c825)`); }\n            if (!componentToInject) { throw new Error(`${lc} componentToInject required. (E: decf0b51ad49257ce44fecbcf84c3a25)`); }\n            if (!componentToInject.meta) { throw new Error(`${lc} componentToInject.meta required. (E: f8827c0602ca7b0e030d0b3e2c4a4825)`); }\n            if (!componentToInject.meta.componentName) { throw new Error(`${lc} componentToInject.meta.componentName required. (E: 5dcae244ae32690f7b73ce27a32a3c25)`); }\n\n            // Clear parent content\n            parentEl.innerHTML = '';\n\n            // attach the component (web component) to the parent\n            parentEl.appendChild(componentToInject);\n\n            // right now we're manually fading in/out with this kluge.\n            parentEl.classList.remove('fade-out');\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            parentEl.innerHTML = `<p class=\"error\">Error loading component for route. error:</p><br /><br /><p>${error.message}</p>`;\n            // console.error(`${lc} ${extractErrorMsg(error)}`);\n            // throw error; // Re-throw error for upstream handling\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    getRegisteredComponentsMeta(): readonly IbGibDynamicComponentMeta[] {\n        return [...this._registeredComponentsMeta];\n    }\n}\n\n/**\n * Singleton instance of the IbGibComponentService.\n */\nlet componentSvc: IbGibComponentService;\nexport async function getComponentSvc(): Promise<IbGibComponentService> {\n    const lc = `[${getComponentSvc.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 853694c88223381339103a3765129925)`); }\n\n        if (!componentSvc) {\n            componentSvc = new IbGibComponentService();\n            await componentSvc.initialized;\n        }\n\n        return componentSvc;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n", "/**\n * @module app-constants is a temporary home for constants specifically for app\n * names/subnames.\n *\n * This also contains type guards.\n */\n\n// #region RouterAppName\n/**\n * @see {@link RouterAppName.web1}\n */\nexport const ROUTER_APP_NAME_WEB1 = 'web1';\n/**\n * projects is a terrible name but this is what ibgib \"projects\" will be, like\n * timelines. I dunno, terrible name, it will resolve with time.\n */\nexport const ROUTER_APP_NAME_PROJECTS = 'projects';\n/**\n * tags is used for browsing tags...are these actually \"app\" names? hmm....\n */\nexport const ROUTER_APP_NAME_TAGS = 'tags';\n\n/**\n * Enum-like type for valid app names. These are atow used in whitelisting and\n * parsing for the SPA routing.\n *\n * Currently, this is only 'web1', but we can add more in the future.\n */\nexport type RouterAppName =\n    | typeof ROUTER_APP_NAME_WEB1\n    | typeof ROUTER_APP_NAME_PROJECTS\n    | typeof ROUTER_APP_NAME_TAGS\n    ;\n\n/**\n * @see {@link RouterAppName}\n */\nexport const RouterAppName = {\n    /**\n     * @see {@link ROUTER_APP_NAME_WEB1}\n     */\n    web1: ROUTER_APP_NAME_WEB1 satisfies RouterAppName,\n    /**\n     * @see {@link ROUTER_APP_NAME_PROJECTS}\n     */\n    projects: ROUTER_APP_NAME_PROJECTS satisfies RouterAppName,\n    /**\n     * @see {@link ROUTER_APP_NAME_TAGS}\n     */\n    tags: ROUTER_APP_NAME_TAGS satisfies RouterAppName,\n} as const satisfies { [k: string]: RouterAppName };\n\n/**\n * Valid values for {@link RouterAppName}.\n */\nexport const VALID_ROUTER_APP_NAMES =\n    Object.freeze(Object.values(RouterAppName));\n\n/**\n * Type guard to check if a string is a valid {@link RouterAppName}.\n *\n * @param str string to check\n * @returns true if the string is a value in {@link RouterAppName}, else false.\n */\nexport function isValidRouterAppName(str: string): str is RouterAppName {\n    return !!str && VALID_ROUTER_APP_NAMES.includes(str as any);\n}\n\n// #endregion RouterAppName\n\n// #region Web1Filename\nexport const WEB1_FILENAME_HOME = 'home.html';\nexport const WEB1_FILENAME_ABOUT = 'about.html';\nexport const WEB1_FILENAME_FUNDING = 'funding.html';\nexport const WEB1_FILENAME_LINKS = 'links.html';\nexport type Web1Filename =\n    | typeof WEB1_FILENAME_HOME\n    | typeof WEB1_FILENAME_ABOUT\n    | typeof WEB1_FILENAME_FUNDING\n    | typeof WEB1_FILENAME_LINKS\n    ;\nexport const WEB1_FILENAMES = {\n    home: WEB1_FILENAME_HOME,\n    about: WEB1_FILENAME_ABOUT,\n    funding: WEB1_FILENAME_FUNDING,\n    links: WEB1_FILENAME_LINKS,\n} as const satisfies { [k: string]: Web1Filename };\nexport const VALID_WEB1_FILENAMES = Object.freeze(Object.values(WEB1_FILENAMES));\nexport function isValidWeb1Filename(str: string): str is Web1Filename {\n    return !!str && VALID_WEB1_FILENAMES.includes(str as any);\n}\n// #endregion Web1Filename\n", "/**\n * ids for elements in index.html (layout)\n *\n * categorized by section of the ui for readability\n */\n\n// #region fullscreen-dialog ids\nexport const ID_FULLSCREEN_DIALOG = 'fullscreen-dialog';\nexport const ID_FULLSCREEN_DIALOG_CONTENT = 'fullscreen-dialog-content';\nexport const ID_FULLSCREEN_DIALOG_TITLE = 'fullscreen-dialog-title';\nexport const ID_FULLSCREEN_DIALOG_HEADER = 'fullscreen-dialog-header';\nexport const ID_FULLSCREEN_DIALOG_BODY = 'fullscreen-dialog-body';\nexport const ID_FULLSCREEN_DIALOG_MESSAGE = 'fullscreen-dialog-message';\nexport const ID_FULLSCREEN_DIALOG_PROMPT_INPUT = 'fullscreen-dialog-prompt-input';\nexport const ID_FULLSCREEN_DIALOG_FOOTER = 'fullscreen-dialog-footer';\nexport const ID_FULLSCREEN_DIALOG_OK_BUTTON = 'fullscreen-dialog-ok-button';\nexport const ID_FULLSCREEN_DIALOG_CANCEL_BUTTON = 'fullscreen-dialog-cancel-button';\n// #endregion fullscreen-dialog ids\n\n// #region app-shell ids\nexport const ID_APP_SHELL = 'app-shell';\n// #endregion app-shell ids\n\n// #region header-panel ids\nexport const ID_HEADER_PANEL = 'header-panel';\nexport const ID_HEADER_PANEL_CONTENT = 'header-panel-content';\nexport const ID_HEADER_PANEL_HEADER = 'header-panel-header';\nexport const ID_IBGIB_COM_TITLE_LINK = 'ibgib-com-title-link';\n// #endregion header-panel ids\n\n// #region panel-container ids\nexport const ID_PANEL_CONTAINER = 'panel-container';\n\n// #region left-panel ids\nexport const ID_LEFT_PANEL = 'left-panel';\nexport const ID_LEFT_PANEL_HEADER = 'left-panel-header';\nexport const ID_LEFT_PANEL_CONTENT = 'left-panel-content';\nexport const ID_LEFT_PANEL_PROJECT_LIST = 'project-list';\nexport const ID_LEFT_PANEL_FOOTER = 'left-panel-footer';\nexport const ID_LEFT_PANEL_TABS = 'left-panel-tabs';\nexport const ID_LEFT_PANEL_COLLAPSE_HANDLE = 'left-panel-collapse-handle';\nexport const ID_LEFT_PANEL_EXPAND_HANDLE = 'left-panel-expand-handle';\nexport const ID_LEFT_PANEL_MAXIMIZE_HANDLE = 'left-panel-maximize-handle';\n\n// #region web10-tab-content ids\nexport const ID_WEB10_TAB_CONTENT = 'web10-tab-content';\nexport const ID_WEB10_TAB_BUTTON = 'web10-tab-button';\nexport const ID_WEB_1_NAV = 'web1-nav';\n// #endregion web10-tab-content ids\n\n// #region tag-explorer-tab-content ids\nexport const ID_TAG_EXPLORER_TAB_CONTENT = 'tag-explorer-tab-content';\nexport const ID_TAG_EXPLORER_TAB_BUTTON = 'tag-explorer-tab-button';\nexport const ID_TAG_NAV = 'tag-nav';\n// #endregion tag-explorer-tab-content ids\n\n// #region project-explorer-tab-content ids\nexport const ID_PROJECT_EXPLORER_TAB_CONTENT = 'project-explorer-tab-content';\nexport const ID_PROJECT_EXPLORER_TAB_BUTTON = 'project-explorer-tab-button';\n// export const ID_PROJECT_LIST = 'project-list';\n// #endregion project-explorer-tab-content ids\n\n// #endregion left-panel ids\n\n// #region center-panel ids\nexport const ID_CENTER_PANEL = 'center-panel';\nexport const ID_CENTER_PANEL_HEADER = 'center-panel-header';\nexport const ID_CENTER_PANEL_CONTENT = 'center-panel-content';\nexport const ID_CENTER_PANEL_TABS = 'center-panel-tabs';\nexport const ID_CENTER_CANVAS_AREA = 'center-canvas-area';\nexport const ID_CENTER_PANEL_FOOTER = 'center-panel-footer';\n// #endregion center-panel ids\n\n// #region right-panel ids\nexport const ID_RIGHT_PANEL = 'right-panel';\nexport const ID_RIGHT_PANEL_HEADER = 'right-panel-header';\nexport const ID_RIGHT_PANEL_CONTENT = 'right-panel-content';\nexport const ID_RIGHT_PANEL_FOOTER = 'right-panel-footer';\nexport const ID_RIGHT_PANEL_CHAT_LOG = 'chronologys-content';\nexport const ID_RIGHT_PANEL_COLLAPSE_HANDLE = 'right-panel-collapse-handle';\nexport const ID_RIGHT_PANEL_EXPAND_HANDLE = 'right-panel-expand-handle';\nexport const ID_RIGHT_PANEL_MAXIMIZE_HANDLE = 'right-panel-maximize-handle';\nexport const ID_TAB_BUTTON_CHRONOLOGYS = 'chronologys-tab-button';\nexport const ID_CHRONOLOGYS_CONTENT = 'chronologys-content';\n// #endregion right-panel ids\n\n// #endregion panel-container ids\n\n// #region footer-panel ids\nexport const ID_FOOTER_PANEL = 'footer-panel';\nexport const ID_FOOTER_PANEL_HEADER = 'footer-panel-header';\nexport const ID_FOOTER_INPUT_CONTAINER = 'footer-input-container';\nexport const ID_PRIMARY_AGENT_INPUT = 'primary-agent-input';\nexport const ID_PRIMARY_AGENT_INPUT_SEND_BTN = 'primary-agent-input-send-btn';\nexport const ID_FOOTER_PANEL_COLLAPSE_HANDLE = 'footer-panel-collapse-handle';\nexport const ID_FOOTER_PANEL_EXPAND_HANDLE = 'footer-panel-expand-handle';\nexport const ID_FOOTER_PANEL_MAXIMIZE_HANDLE = 'footer-panel-maximize-handle';\n// #endregion footer-panel ids\n\nexport const ID_PRIMARY_AGENT_CHAT_LOG = 'chronologys-content';\n", "<div id=\"canvas-component\" class=\"canvas-component\">\n    <!-- width/height 1000 somewhat arbitrary at this point. trying to determine\n    if it affects blurriness of the text objects. -->\n    <div id=\"canvas-content\">\n        <canvas id=\"ibgib-canvas\" width=\"1000\" height=\"1000\"></canvas>\n    </div>\n\n    <div id=\"canvas-footer-panel\" class=\"canvas-footer-panel\">\n        <!-- <textarea id=\"canvas-agent-input\" class=\"agent-input\" placeholder=\"loading...\" readonly></textarea>\n        <button id=\"canvas-agent-input-send-btn\" class=\"send-btn\"><b>\u276F</b></button> -->\n    </div>\n</div>\n", "#canvas-component {\n    --footer-panel-background-color: var(--button-background-color);\n    --footer-panel-border-color: var(--button-border-color);\n    --footer-panel-border-radius: 4px;\n\n    /* debug add border style */\n    border-width: 2px;\n    border-color: var(--primary-border-color-dark);\n    border-style: solid;\n    border-radius: 2px;\n    padding: 1%;\n\n    display: flex;\n    flex-direction: column;\n    width: 100%;\n    height: 100%;\n    box-sizing: border-box;\n\n    #canvas-content {\n\n        /* debug add border style */\n        /* border-width: 5px;\n        border-color: rgb(96, 93, 224);\n        border-style: solid; */\n        padding: 1px;\n\n        flex-grow: 1;\n\n        display: grid;\n        align-items: center;\n        justify-items: center;\n\n        width: 100%;\n        height: 80%;\n        box-sizing: border-box;\n\n        canvas {\n            /* debug add border style */\n            border-width: 2px;\n            border-color: rgba(91, 198, 67, 0.669);\n            border-style: solid;\n            border-radius: 5px;\n            padding: 1px;\n\n            max-width: 100%;\n            max-height: 100%;\n            /* this is required for some reason to keep the full canvas in view\n             * in content */\n            overflow: hidden;\n        }\n\n    }\n\n    #canvas-footer-panel {\n        /* maybe should take out the footer completely in html */\n        display: none;\n    }\n\n    /* #canvas-footer-panel {\n        padding: 1px;\n        box-sizing: border-box;\n\n        flex-shrink: 0;\n        width: 100%;\n        height: 20%;\n\n        display: flex;\n        flex-direction: row;\n        align-items: stretch;\n        justify-content: stretch;\n\n        textarea {\n            flex-grow: 1;\n        }\n\n        button {\n            height: 100%;\n            flex-shrink: 0;\n            align-self: center;\n            margin: 2px;\n            border-color: var(--footer-panel-border-color);\n            background-color: var(--footer-panel-background-color);\n            border-width: 1px;\n        }\n    } */\n}\n", "/* * { */\n/* if I do this, it screws up other layout issues... */\n/* box-sizing: border-box; */\n/* font-family: 'Courier New', Courier, monospace; */\n/* } */\n\nbutton {\n    display: flex;\n    flex-direction: row;\n    align-items: center;\n    justify-content: center;\n    color: var(--button-text-color-base);\n    background-color: var(--button-background-color-base);\n    border-color: var(--button-border-color-base);\n    border-radius: var(--button-border-radius-base);\n    border-width: var(--button-border-width-base);\n    padding: var(--button-padding-base);\n    user-select: none;\n}\n\nbutton:hover {\n    cursor: pointer;\n    border-color: currentColor;\n    border-width: calc(var(--button-border-width-base) + 2px);\n}\n\ntextarea {\n    background-color: var(--input-background-color);\n    color: var(--input-text-color);\n    border: var(--input-border-width) var(--input-border-style) var(--input-border-color);\n    border-radius: var(--input-border-radius);\n    padding: var(--input-padding);\n}\n\nbody {\n    margin: 0;\n    font-family: var(--font-family-base);\n    display: flex;\n    flex-direction: column;\n    height: auto;\n    /* Ensure body takes at least full viewport height */\n    min-height: 100vh;\n    min-height: 100dvh;\n    /* Prevent body scrollbars */\n    overflow: hidden;\n}\n\n.app-shell {\n    display: flex;\n    flex-direction: column;\n    /* Take full viewport height */\n    height: 100vh;\n    height: 100dvh;\n    max-height: 100dvh;\n    overflow-y: hidden;\n}\n\n.header-panel {\n    height: auto;\n    border-bottom: 1px solid #ccc;\n    border-width: var(--debug-border-width);\n    border-style: var(--debug-border-style);\n    border-color: var(--header-border-color);\n    /* Prevent header panel overflow */\n    overflow: hidden;\n    /* min-height: 5vh; */\n    flex-shrink: 0;\n    display: flex;\n    flex-direction: row;\n    align-items: stretch;\n    justify-content: flex-start;\n\n    #header-panel-header {\n        /* no right margin so the breadcrumb can be closer */\n        /* margin: 10px 0 10px 10px; */\n        margin: 3px 0 3px 0;\n\n        #ibgib-com-title-link {\n            color: var(--text-color-base);\n        }\n    }\n\n    #header-panel-footer {\n        width: auto;\n        display: flex;\n        flex-direction: row;\n        align-items: center;\n        justify-content: stretch;\n\n        #header-panel-config-btn {\n            display: flex;\n            align-items: center;\n            justify-content: center;\n\n            span {\n                font-size: large;\n                /* just tweak it to look right...need to be able to adjust text padding but hey*/\n                padding-left: 2px;\n            }\n        }\n\n        /* Add back the relative container for the button and popover */\n        .config-button-container {\n            background-color: transparent;\n            /* position: relative;\n            display: inline-block; */\n        }\n\n        /* Keep the styles for the popover options */\n        .config-popover-option {\n            padding: 8px 15px;\n            margin-bottom: 2px;\n            cursor: pointer;\n            transition: background-color 0.2s ease;\n            background-color: var(--tab-background-color);\n            color: var(--tab-text-color);\n        }\n\n        /* Keep the styles for the popover options */\n        .config-popover-option:hover {\n            /* color: var(--tjp-color-contrast, #f0f0f0); */\n            color: contrast-color(var(--tjp-color, #f0f0f0));\n            background-color: var(--tjp-color, #f0f0f0);\n        }\n\n        /* Use anchor() for positioning */\n        .config-popover {\n            /* bottom: anchor(top); */\n            /* Position the bottom of the popover at the top of the anchor */\n            /* left: anchor(left); */\n            /* Align the left of the popover with the left of the anchor */\n            flex-direction: column;\n            margin: 0px;\n            /* padding: 5px 0; */\n            border-radius: var(--border-radius, 4px);\n            background-color: var(--background-color, #fff);\n            border: 1px solid var(--border-color, #ccc);\n            box-shadow: var(--box-shadow, 0 2px 5px rgba(0, 0, 0, 0.2));\n            z-index: 10;\n            /* Ensure it appears above other content */\n        }\n    }\n}\n\n.right-panel-header.collapsed {\n    rotate: 90deg;\n    /* margin-bottom: auto; */\n    padding-left: 10px;\n}\n\n.left-panel-header.collapsed {\n    rotate: 270deg;\n    direction: rtl;\n    padding-right: 10px;\n    /* margin-bottom: auto; */\n}\n\n.left-panel.collapsed {\n    width: var(--left-panel-header-calculated-height);\n}\n\n.right-panel.collapsed {\n    width: var(--right-panel-header-calculated-height);\n}\n\n.panel-container {\n    /* Arrange left, center, right panels horizontally */\n    display: flex;\n    /* Take recentering vertical space */\n    flex: 1;\n    height: calc(75% + var(--header-calculated-height-loss));\n    /* max-height: 90vh; */\n}\n\n.panel-container.collapsed {\n    max-height: 25vh;\n}\n\n.left-panel {\n    border-width: var(--debug-border-width);\n    border-style: var(--debug-border-style);\n    border-color: var(--left-border-color);\n    width: var(--side-panel-width);\n    /* padding: 10px; */\n    overflow-y: auto;\n}\n\n/* each side panel is a flexbox */\n.left-panel,\n.right-panel {\n    display: flex;\n    flex-direction: column;\n    /*\n     * make left and right panels resizable, right panel has to reverse in order to\n     * put the resize affordance on the left side of the panel.\n     */\n    resize: auto;\n}\n\n/*\n * \"dirty hack\" to put the affordance on the left side\n * see https://stackoverflow.com/a/60633726/3897838\n */\n.right-panel {\n    direction: rtl;\n\n    /* put it back to normal */\n    .panel-header,\n    .panel-content,\n    .right-panel-footer {\n        direction: ltr;\n    }\n}\n\n#center-panel {\n    border-width: var(--debug-border-width);\n    border-style: var(--debug-border-style);\n    border-color: var(--center-border-color);\n    width: 100%;\n    height: 100%;\n    /* Take remaining horizontal space */\n    flex: 1;\n    display: flex;\n    /* Stack tabs and canvas area vertically */\n    flex-direction: column;\n    /* No idea why this is needed. it's already defined in :root */\n    box-sizing: border-box;\n\n    iframe {\n        height: 100%;\n        width: 100%;\n    }\n\n    overflow-y: auto;\n\n    #center-panel-content {\n        flex: 1;\n        padding: 1%;\n        display: flex;\n        flex-direction: column;\n        /* center horizontally */\n        align-items: center;\n        /* stretch vertically, part of kluge to get scrolling to work with web component */\n        justify-content: stretch;\n        overflow: auto;\n        /* Default opacity - fully visible */\n        opacity: 1;\n        /* Fade-in transition */\n        transition: opacity 1.0s ease-in-out;\n\n        /*\n         * kluge to get links inside an iframe to fill up and scroll properly.\n         * there are two parts to this kluge (no pun intended). the ::part\n         * selector in #center-panel-content (also had to set justify-content to\n         * stretch), and I added hardcoded web1-links-component class to this\n         * file (even though it is component-specific).\n         */\n        ::part(links-page) {\n            height: 100%;\n            width: 100%;\n        }\n    }\n\n    /* Class for fade-out effect */\n    #center-panel-content.fade-out {\n        /* Fully transparent */\n        opacity: 0;\n    }\n}\n\n#canvas {\n    aspect-ratio: 1 / 1;\n    width: 100%;\n    height: auto;\n    max-width: 100%;\n    max-height: 100%;\n    display: block;\n}\n\n.right-panel {\n    border-width: var(--debug-border-width);\n    border-style: var(--debug-border-style);\n    border-color: var(--right-border-color);\n    width: var(--side-panel-width);\n    /* padding: 2px; */\n    overflow-y: auto;\n}\n\n#footer-panel {\n    border-width: var(--debug-border-width);\n    border-style: var(--debug-border-style);\n    border-color: var(--footer-border-color);\n    /* Height will be determined by content (initially collapsded) */\n    /* height: auto; */\n    border-top: 1px solid #ccc;\n    /* box-sizing: border-box; */\n    overflow: hidden;\n    display: flex;\n    flex-direction: row;\n    align-items: center;\n}\n\n/* Footer now has a header, and header will contain the buttons */\n.footer-panel .panel-header {\n    /* Don't shrink the header */\n    flex-shrink: 0;\n    /* height: calc(var(--handle-size) * 2); */\n    /* overrides the default .panel-header margin-bottom */\n    margin-bottom: 0px;\n    display: flex;\n    flex-direction: column;\n\n    /* the skinny arrows aren't quite centered, so this is a hack */\n    .panel-expand-handle,\n    .panel-collapse-handle {\n        padding-left: 10px;\n        padding-right: 4px;\n    }\n\n    /* adjust the maximize handle due to above hack */\n    .panel-maximize-handle {\n        padding-left: 7px;\n        padding-right: 7px;\n    }\n}\n\n.footer-panel.collapsed {\n    height: auto;\n    overflow: hidden;\n}\n\n.footer-panel.expanded {\n    height: 20%;\n}\n\n.footer-panel.maximized {\n    height: 80vh;\n    max-height: 80vh;\n    z-index: 100;\n}\n\n#primary-agent-input {\n    flex: 1;\n    /* margin-right: 10px; */\n    margin-right: 0px;\n    width: 100%;\n    min-width: 0;\n    /* height: auto; */\n    height: 100%;\n    flex-grow: 1;\n    resize: vertical;\n    overflow-y: auto;\n    box-sizing: border-box;\n    background-color: var(--input-background-color);\n    color: var(--input-text-color);\n    border: var(--input-border-width) var(--input-border-style) var(--input-border-color);\n    border-radius: var(--input-border-radius);\n    padding: var(--input-padding);\n    /* font-family: var(--font-family-base); */\n}\n\n.agent-input {\n    background-color: var(--input-background-color);\n    color: var(--input-text-color);\n    border: var(--input-border-width) var(--input-border-style) var(--input-border-color);\n    border-radius: var(--input-border-radius);\n    padding: var(--input-padding);\n    box-sizing: border-box;\n    margin: 3px 3px 5px 3px;\n    font-family: var(--font-family-base);\n}\n\n.send-btn {\n    min-width: 40px;\n    max-width: 70px;\n    background-color: var(--button-background-color-base);\n    color: var(--button-text-color-base);\n    border: var(--button-border-width-base) var(--button-border-style-base) var(--button-border-color-base);\n    border-radius: var(--button-border-radius-base);\n    padding: var(--button-padding-base);\n}\n\n.send-btn:hover {\n    background-color: var(--button-hover-background-color);\n    color: var(--button-hover-text-color);\n    border-color: var(--button-hover-border-color);\n}\n\n.tab-btn {\n    margin: 2px;\n    border-color: var(--button-border-color-base);\n    background-color: var(--button-background-color-base);\n    color: var(--button-text-color-base);\n    border: var(--button-border-width-base) var(--button-border-style-base) var(--button-border-color-base);\n    border-radius: var(--button-border-radius-base);\n    padding: var(--button-padding-base);\n    /* Added padding */\n    border-width: 1px;\n    width: 50px;\n    border-radius: var(--button-border-radius);\n}\n\n.tab-btn:hover,\n.panel-tab-button:hover {\n    background-color: var(--button-hover-background-color) !important;\n    color: var(--button-hover-text-color) !important;\n    border-color: var(--button-hover-border-color);\n}\n\n#footer-input-container {\n    input-component {\n        width: 100%;\n        height: 100%;\n        flex-grow: 1;\n    }\n\n    display: flex;\n    flex-direction: row;\n    align-items: stretch;\n    justify-content: stretch;\n\n    textarea {\n        height: 100%;\n        background-color: var(--input-background-color);\n        color: var(--input-text-color);\n        border: var(--input-border-width) var(--input-border-style) var(--input-border-color);\n        border-radius: var(--input-border-radius);\n        padding: var(--input-padding);\n        flex-grow: 1;\n    }\n\n    button {\n        height: 100%;\n        flex-shrink: 0;\n        align-self: center;\n        margin: 2px;\n        background-color: var(--button-background-color-base);\n        color: var(--button-text-color-base);\n        border: var(--button-border-width-base) var(--button-border-style-base) var(--button-border-color-base);\n        border-radius: var(--button-border-radius-base);\n        padding: var(--button-padding-base);\n    }\n\n    #footer-input-container button:hover {\n        background-color: var(--button-hover-background-color);\n        color: var(--button-hover-text-color);\n        border-color: var(--button-hover-border-color);\n    }\n\n    ibgib-input {\n        width: 100%;\n    }\n}\n\n.footer-input-container.collapsed {\n    display: none !important;\n}\n\n/* Basic panel header styling */\n.panel-header {\n    /* Enable Flexbox for header */\n    display: flex;\n    /* Space header text and collapse handle */\n    justify-content: flex-start;\n    /* Vertically align header items */\n    align-items: center;\n    font-weight: bold;\n    margin: 1px 1px 0px 1px;\n    gap: calc(var(--handle-size) / 3);\n    overflow-x: auto;\n    overflow-y: clip;\n    scrollbar-width: none;\n}\n\n.panel-header.collapsed {\n    overflow-x: visible;\n    overflow-y: visible;\n\n    .panel-tab-button.active {\n        margin-right: -5px;\n    }\n}\n\n/* Basic chat log styling (adjust as needed) */\n/* .chat-log {\n    font-size: 0.9em;\n    white-space: pre-wrap;\n    overflow-y: auto;\n    overflow-x: hidden;\n} */\n/* Make the chatlog use all available space. */\n#chronologys-content {\n    height: 100%;\n\n    section {\n        margin-top: 10px;\n\n        p {\n            text-indent: -1%;\n            padding-left: 1%;\n            margin-top: 5px;\n        }\n    }\n}\n\n.panel-collapse-handle,\n.panel-expand-handle,\n.panel-maximize-handle {\n    cursor: pointer;\n    padding: 5px;\n    user-select: none;\n    margin: 0;\n    /* Make handles grow to equal size */\n    flex: 1;\n    /* Center text within handles */\n    text-align: center;\n}\n\n.left-panel-footer.collapsed,\n.right-panel-footer.collapsed {\n    flex-direction: column;\n    gap: calc(var(--handle-size) / 3);\n}\n\n.footer-panel.collapsed .panel-header {\n    flex-direction: row;\n}\n\n/* Styles for collapsed left and right panels */\n.left-panel.collapsed,\n.right-panel.collapsed {\n    /* width handled in custom update via css vars in root selector. see\n     * --left/right-panel-header-calculated-height */\n    /* Hide panel content */\n    overflow: hidden;\n    /* Add transition for smooth animation on collapse */\n    /* Match duration to panel transition */\n    transition: width var(--panel-transition-duration) ease-in-out;\n}\n\n#left-panel-content,\n#right-panel-content {\n    width: 100%;\n    height: 100%;\n}\n\n.panel-collapse-handle.collapsed,\n.panel-expand-handle.collapsed,\n.panel-maximize-handle.collapsed,\n.left-panel.collapsed .project-list,\n.left-panel.collapsed .tag-nav,\n.right-panel.collapsed .chat-log,\n.footer-panel.collapsed .panel-content,\n.left-panel.collapsed .left-panel-footer .panel-collapse-handle,\n.right-panel.collapsed .right-panel-footer .panel-collapse-handle,\n.footer-panel.collapsed .panel-header .panel-collapse-handle,\n.left-panel-content.collapsed,\n.right-panel-content.collapsed {\n    display: none;\n}\n\n/* Style for expanded panel (optional, can adjust as needed) */\n.left-panel.expanded,\n.right-panel.expanded {\n    width: var(--side-panel-width);\n    /* Original expanded width */\n    overflow-y: auto;\n    /* Keep scrollable when expanded */\n    /* Add transition for smooth animation on collapse */\n    /* Match duration to panel transition */\n    transition: width var(--panel-transition-duration) ease-in-out;\n}\n\n/* Style for expanded panel (optional, can adjust as needed) */\n.left-panel.maximized,\n.right-panel.maximized {\n    width: var(--side-panel-width-maximized);\n    /* Keep scrollable when expanded */\n    overflow-y: auto;\n    z-index: 100;\n    /* Add transition for smooth animation on collapse */\n    /* Match duration to panel transition */\n    transition: width var(--panel-transition-duration) ease-in-out;\n}\n\n.left-panel-footer,\n.right-panel-footer {\n    /* Separator line for footers */\n    border-top: 1px solid #eee;\n    padding: 5px;\n    /* Center handles in footer */\n    text-align: center;\n    /* Push footers to the bottom */\n    margin-top: auto;\n    display: flex;\n    /* Distribute items evenly */\n    justify-content: space-around;\n    /* Vertically align items */\n    align-items: center;\n}\n\n/* Show expand handle when collapsed */\n.left-panel.collapsed .left-panel-footer .panel-expand-handle,\n.right-panel.collapsed .right-panel-footer .panel-expand-handle {\n    /* display: inline-block; */\n    margin: 0px;\n}\n\n/* Hide expand handle when expanded */\n.left-panel.expanded .panel-expand-handle,\n.right-panel.expanded .panel-expand-handle,\n.footer-panel.expanded .panel-header .panel-expand-handle {\n    display: none;\n}\n\n/* Hide maximize handle when maximized */\n.left-panel.maximized .panel-maximize-handle,\n.right-panel.maximized .panel-maximize-handle,\n.footer-panel.maximized .panel-header .panel-maximize-handle {\n    display: none;\n}\n\n/* Show footer content when expanded */\n.left-panel.expanded .left-panel-footer,\n.right-panel.expanded .right-panel-footer,\n.left-panel.maximized .left-panel-footer,\n.right-panel.maximized .right-panel-footer {\n    display: block;\n}\n\n.panel-handle {\n    height: var(--handle-size);\n    width: var(--handle-size);\n    min-height: var(--handle-size);\n    min-width: var(--handle-size);\n    border-radius: 50%;\n    background-color: var(--button-background-color-base);\n    /* Use button base background */\n    color: var(--button-text-color-base);\n    /* Use button base text color */\n    border: var(--button-border-width-base) var(--button-border-style-base) var(--button-border-color-base);\n    /* Use button base border */\n    aspect-ratio: 1;\n    /* center text inside handle span's */\n    display: inline-flex;\n    align-items: center;\n    justify-items: center;\n}\n\n.left-panel .panel-handle,\n.right-panel .panel-handle {\n    padding-bottom: 5px;\n}\n\n.panel-handle:hover {\n    background-color: var(--button-hover-background-color);\n    color: var(--button-hover-text-color);\n    border-color: var(--button-hover-border-color);\n    padding-bottom: 5px;\n}\n\n/* General panel content style (applies to both left and right) */\n.panel-content {\n    /* Scrollable content */\n    overflow-y: auto;\n    /* Take all available space within the panel, pushing the footer down */\n    flex-grow: 1;\n    /* what does this do? */\n    min-height: 0;\n    align-self: stretch;\n}\n\n/* Updated tab styles consuming CSS variables */\n.panel-tab-button {\n    /* General tab button styles */\n    background-color: var(--tab-background-color);\n    border: var(--tab-border-width) var(--tab-border-style) var(--tab-border-color);\n    border-bottom-color: transparent !important;\n    padding: var(--tab-padding);\n    cursor: pointer;\n    /* Rounded top corners */\n    border-radius: var(--tab-border-radius);\n    margin-top: calc(var(--tab-border-width) + 2) !important;\n    /* Spacing between tabs */\n    margin-right: 2px;\n    /* margin-bottom: 4px; */\n    font-weight: bold;\n    /* Prevent text selection */\n    user-select: none;\n    color: var(--tab-text-color);\n    transform: translateY(calc(var(--tab-border-width-active) + 5px));\n    text-wrap-mode: nowrap;\n}\n\n.panel-tab-button.active {\n    /* Style for active tab button */\n    background-color: var(--tab-background-color-active);\n    /* Visually \"lift\" active tab */\n    border: var(--tab-border-width-active) var(--tab-border-style) var(--tab-border-color-active);\n    border-bottom: 5px solid transparent;\n    color: var(--tab-text-color-active);\n    transform: translateY(calc(var(--tab-border-width-active) + 3px));\n    /* don't move the \"X\" close button span */\n    /* span {\n        transform: inherit;\n    } */\n}\n\n/* Link Styles */\na {\n    color: var(--link-color);\n    text-decoration: var(--link-text-decoration);\n    display: inline-block;\n}\n\na:visited {\n    color: var(--link-visited-color);\n}\n\n/* Animation for link hover */\n@keyframes bounce-on-hover {\n    0% {\n        transform: translateX(0px);\n    }\n\n    50% {\n        transform: translateX(6px);\n    }\n\n    100% {\n        transform: translateX(5px);\n    }\n\n    /* End with a slight indentation */\n}\n\na:hover {\n    color: var(--link-hover-color);\n    text-decoration: var(--link-hover-text-decoration);\n    animation: bounce-on-hover 0.2s ease-in-out;\n    transform: translateX(4px);\n    /* display: inline-block; */\n}\n\n/* General tab content styles */\n.tab-content {\n    width: 100%;\n    height: 100%;\n    /* padding: 10px; */\n    padding: 10px 2px 2px 2px;\n    border: 1px solid #ccc;\n    border-top: none;\n    /* Remove top border to visually connect to tabs */\n    /* background-color: #eee; */\n    /* Optional: Background color for content area */\n    /* debug */\n    background-color: var(--side-panel-tab-content-background-color);\n    box-sizing: border-box;\n\n    /* I had to enclose the a tags with li for formatting */\n    nav {\n        padding-left: 10px;\n\n        ul {\n            display: grid;\n            gap: 10px;\n            padding: 0px;\n\n            li {\n                list-style-type: none;\n            }\n        }\n    }\n}\n\n.tab-content.collapsed {\n    /* Style for collapsed tab content */\n    display: none;\n}\n\n.fullscreen-dialog {\n    /* on thin screens, still show a sliver of green. Doesn't affect\n     * desktop/normal phone screens. */\n    max-width: 85vw;\n    padding: 0px;\n}\n\n/*\n * Styles for fullscreen dialog. overall the approach is to cover a majority of\n * the screen with a diffuse blur of the app backdrop.\n */\n.fullscreen-dialog-content {\n    /* for some reason width 100% causes overflow? */\n    /* width: 100%; */\n    height: 100%;\n    min-width: 50vw;\n    min-height: 50vh;\n    max-width: 80vw;\n    max-height: 80vw;\n    margin: 0;\n    padding: 20px;\n    border: none;\n    /* Semi-transparent background overlay */\n    /* background-color: rgba(203, 236, 199, 0.719); */\n    background-color: var(--background-color-base);\n    color: var(--text-color-base);\n    /* Center dialog content */\n    /* color: var(--text-color-light); */\n    display: flex;\n    flex-direction: column;\n    align-items: center;\n    justify-content: center;\n    /* Ensure dialog is on top */\n    z-index: 1000;\n    /* Enable scroll if content overflows */\n    overflow: auto;\n}\n\n/* Style the backdrop (behind the dialog) */\n.fullscreen-dialog::backdrop {\n    /* Semi-transparent black backdrop */\n    /* background-color: rgba(0, 0, 0, 0.5); */\n    background-color: var(--dialog-backdrop-color);\n    /* Optional: Apply blur effect to backdrop */\n    backdrop-filter: blur(2px);\n}\n\n/* Style dialog header */\n.fullscreen-dialog-header {\n    padding-bottom: 10px;\n    border-bottom: 1px solid #ccc;\n    margin-bottom: 10px;\n    text-align: center;\n}\n\n/* Style dialog body */\n.fullscreen-dialog-body {\n    width: 95%;\n    padding: 10px 0;\n    margin-bottom: 15px;\n    /* Take available height */\n    flex: 1;\n    /* Enable scroll if message is long */\n    overflow-y: auto;\n    min-height: 50%;\n    display: flex;\n    flex-direction: column;\n    align-items: center;\n    justify-items: center;\n    gap: 5px;\n}\n\n.fullscreen-dialog-message {\n    padding: 10px;\n}\n\n/* Style prompt input field */\n#fullscreen-dialog-prompt-input {\n    background-color: var(--input-background-color);\n    color: var(--input-text-color);\n    border: var(--input-border-width) var(--input-border-style) var(--input-border-color);\n    border-radius: var(--input-border-radius);\n    padding: var(--input-padding);\n    padding: 8px;\n    border: 1px solid #ccc;\n    border-radius: 5px;\n    /* margin-top: 10px; */\n    width: 90%;\n    box-sizing: border-box;\n}\n\n/* Hide prompt input when collapsed */\n#fullscreen-dialog-prompt-input.collapsed {\n    display: none;\n}\n\n/* Style dialog footer (button container) */\n.fullscreen-dialog-footer {\n    display: flex;\n    /* Align buttons to the right */\n    justify-content: flex-end;\n    /* Spacing between buttons */\n    gap: 10px;\n    padding-top: 15px;\n    border-top: 1px solid #eee;\n}\n\n/* Style for dialog buttons */\n.dialog-button {\n    background-color: var(--button-background-color-base);\n    /* Or create a separate --button-secondary-... */\n    color: var(--button-text-color-base);\n    border: var(--button-border-width-base) var(--button-border-style-base) var(--button-border-color-base);\n    border-radius: var(--button-border-radius-base);\n    padding: var(--button-padding-base);\n    cursor: pointer;\n}\n\n.dialog-button:hover {\n    background-color: var(--button-hover-background-color);\n    color: var(--button-hover-text-color);\n    border-color: var(--button-hover-border-color);\n}\n\n/* Hover effect for buttons */\n.dialog-button:hover {\n    background-color: #ddd;\n}\n\n/*\n * kluge to get links inside an iframe to fill up and scroll properly.  there\n * are two parts to this kluge (no pun intended). the ::part selector in\n * #center-panel-content (also had to set justify-content to stretch), and I\n * added hardcoded web1-links-component class to this file (even though it is\n * component-specific).\n */\nweb1-links-component {\n    height: 100%;\n    width: 100%;\n}\n\n#center-panel-content:has(> ibgib-projects) {\n    padding: 0px !important;\n}\n\n/* these are the components. I can't figure out how to get web components to do\n * this automatically */\n/* i think i can do a :only-child on the center panel content, but I\"m holding\n * off on this atm */\nibgib-canvas,\nibgib-projects,\nibgib-project {\n    height: 100%;\n    width: 100%;\n    box-sizing: border-box;\n}\n\n/* ibgib-project {\n    overflow: auto;\n} */\n/* used with components that are injected at the page-level (via URL route) */\n.ibgib-page {\n    width: 100%;\n}\n\nh1 {\n    font-size: var(--h1-font-size);\n    font-weight: var(--h1-font-weight);\n    margin: var(--h1-margin);\n}\n\nh2 {\n    font-size: var(--h2-font-size);\n    font-weight: var(--h2-font-weight);\n    margin: var(--h2-margin);\n}\n\nh3 {\n    font-size: var(--h3-font-size);\n    font-weight: var(--h3-font-weight);\n    margin: var(--h3-margin);\n}\n\n/* The main loader container - NOW USES FIXED POSITIONING FOR CENTERING */\n.paramecium-loader {\n    /* --- Viewport Centering --- */\n    position: fixed;\n    /* Position relative to the browser window */\n    top: 50%;\n    left: 50%;\n    transform: translate(-50%, -50%);\n    /* Center the element precisely */\n    z-index: 9999;\n    /* Ensure it stays on top of other content */\n    /* --- Size & Internal Layout --- */\n    width: 150px;\n    /* Container size */\n    height: 150px;\n    display: flex;\n    /* Still useful for centering the body *within* this box */\n    justify-content: center;\n    align-items: center;\n    /* No longer needs 'position: relative' for the text,\n       as 'position: fixed' also creates a positioning context */\n}\n\n/* The paramecium body shape and animation (No changes needed here) */\n.paramecium-body {\n    width: calc(1.1 * 100px);\n    /* Main width */\n    height: calc(3.5 * 60px);\n    /* Main height */\n    /* width: 100px; Main width */\n    /* height: 60px;  Main height */\n    background-color: var(--very-light-background-color);\n    /* A silly green */\n    border: 2px solid var(--border-color-base);\n    /* Darker green border */\n    border-radius: 50% / 45%;\n    /* More squished vertically */\n    position: relative;\n    /* Still needed For positioning the nucleus */\n    box-shadow:\n        inset 0 0 5px rgba(0, 0, 0, 0.1),\n        /* Subtle inner shadow */\n        0 0 10px rgba(160, 232, 160, 0.5);\n    /* Outer glow */\n    animation: wobble-spin 5.5s linear infinite;\n}\n\n/* The little nucleus inside (No changes needed here) */\n.paramecium-nucleus {\n    position: absolute;\n    width: 12px;\n    height: 12px;\n    background-color: #407040;\n    /* Darker nucleus */\n    border-radius: 50%;\n    top: 20%;\n    left: 40%;\n    transform: translate(-75%, -75%);\n    /* Center it based on its own size */\n    box-shadow: inset 0 0 3px var(--primary-border-color-dark);\n}\n\n/* The \"Loading...\" text (No changes needed here) */\n.loading-text {\n    position: absolute;\n    /* Positioned relative to .paramecium-loader */\n    top: 50%;\n    left: 50%;\n    transform: translate(-50%, -50%);\n    font-size: 14px;\n    font-weight: bold;\n    color: #333;\n    white-space: nowrap;\n    /* Prevent text wrapping */\n    animation: pulse-text 1.5s ease-in-out infinite alternate;\n}\n\n/* The silly wobble and spin loading animation (currently a paramecium) */\n@keyframes wobble-spin {\n    0% {\n        transform: rotate(0deg) translateX(0px) scale(1);\n    }\n\n    25% {\n        transform: rotate(90deg) translateX(5px) scale(1.25) skewX(-5deg);\n        /* Wobble out */\n    }\n\n    50% {\n        transform: rotate(180deg) translateX(0px) scale(1);\n    }\n\n    75% {\n        transform: rotate(270deg) translateX(-5px) scale(0.75) skewX(5deg);\n        /* Wobble in */\n    }\n\n    100% {\n        transform: rotate(360deg) translateX(0px) scale(1);\n    }\n}\n\n/* Optional text pulsing animation (No changes needed here) */\n@keyframes pulse-text {\n    from {\n        opacity: 0.2;\n    }\n\n    to {\n        opacity: 1;\n    }\n}\n\n.info-popover-btn {\n    background-color: var(--button-background-color-base);\n    color: var(--button-text-color-base);\n    border: var(--button-border-width-base) var(--button-border-style-base) var(--button-border-color-base);\n    border-radius: var(--button-border-radius-base);\n}\n\n.info-popover-btn:hover {\n    cursor: pointer;\n    border-color: currentColor;\n    border-width: calc(var(--button-border-width-base) + 2px);\n}\n\n.info-popover {\n    color: var(--text-color-base);\n    background-color: var(--background-color-base);\n    border-color: var(--border-color-base);\n    border-width: var(--border-width-base);\n    border-style: var(--border-style-base);\n    font-family: var(--font-family-base);\n    font-size: var(--font-size-base);\n    border-radius: var(--input-border-radius);\n    padding: 2dvw;\n    max-height: 70dvh;\n    max-width: 90dvw;\n    overflow: auto;\n\n    /* box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); */\n    /* background: white; */\n    /* Popovers are positioned automatically, but you can override */\n    button {\n        position: absolute;\n        top: 10px;\n        right: 10px;\n        background-color: rgba(255, 0, 0, 0.7);\n        color: white;\n        border: none;\n        border-radius: 50%;\n        width: 25px;\n        height: 25px;\n        font-size: 16px;\n        cursor: pointer;\n        display: flex;\n        align-items: center;\n        justify-content: center;\n        z-index: 1;\n        /* Ensure button is above content */\n    }\n}\n\n/* The browser adds a backdrop for popovers, you can style it */\n.info-popover::backdrop {\n    background-color: rgba(0, 0, 0, 0.2);\n    backdrop-filter: blur(2px);\n}\n\n.green {\n    color: #1df116;\n    text-decoration-color: #13b90d;\n}\n\n.spinning {\n    animation: spin 1s linear infinite;\n}\n\n@keyframes spin {\n    0% {\n        transform: rotate(0deg);\n    }\n\n    100% {\n        transform: rotate(360deg);\n    }\n}\n\n.error {\n    color: red;\n    border: 1px solid red;\n}\n\n.labeled-control {\n    display: flex;\n    flex-direction: row;\n    justify-content: flex-start;\n    align-items: center;\n    flex-wrap: nowrap;\n\n    label {\n        text-wrap: p;\n    }\n}\n\n/** HAMBURGER (MOBILE) */\n#left-panel-hamburger-btn {\n    display: none;\n    /* Hidden by default */\n    background: none;\n    border: none;\n    font-size: 1.5em;\n    cursor: pointer;\n}\n\n#left-panel-close-btn {\n    display: none;\n}\n\n/* Show hamburger on small screens */\n@media (max-width: 768px) {\n    #left-panel-hamburger-btn {\n        display: block;\n    }\n\n    /*\n      In mobile view, the left panel is initially hidden off-screen to the left.\n      We keep it rendered (not display: none) so we can transition it.\n    */\n    .left-panel {\n        position: absolute;\n        top: 0;\n        left: 0;\n        height: 100%;\n        width: 80%;\n        z-index: 2000;\n        flex-direction: column;\n        background-color: var(--background-color-base);\n        border-right: var(--border-color-base) var(--border-width-base) var(--border-style-base);\n        box-shadow: 2px 0 5px rgba(0, 0, 0, 0.2);\n        /* Hide off-screen by default */\n        transform: translateX(-100%);\n        /* Add transition for a smooth slide-in/out effect */\n        transition: transform var(--panel-transition-duration) ease-in-out;\n    }\n\n    /* correct transitions for mobile view */\n    .left-panel.maximized,\n    .right-panel.maximized,\n    .left-panel.expanded,\n    .right-panel.expanded {\n        transition: transform var(--panel-transition-duration) ease-in-out;\n    }\n\n    /* The .mobile-visible class will now slide the panel into view. */\n    .left-panel.mobile-visible {\n        transform: translateX(0);\n\n        #left-panel-close-btn {\n            display: block;\n        }\n    }\n\n    /* we don't need the footer with the desktop handles in mobile view */\n    .left-panel .left-panel-footer {\n        display: none;\n    }\n\n    /* Only show the close button when the mobile overlay is visible */\n    .left-panel.mobile-visible .close-btn {\n        display: block;\n    }\n}\n\n/** END HAMBURGER (MOBILE) */\n", ":root {\n    /* Scrollbar Styles */\n    --scrollbar-thumb-color: rgba(16, 237, 35, 0.18);\n    /* Example thumb color */\n    --scrollbar-track-color: rgba(134, 5, 132, 0.111);\n    /* Example track color */\n    scrollbar-color: var(--scrollbar-thumb-color) var(--scrollbar-track-color);\n    /* Heading Styles */\n    --h1-font-size: 2em;\n    /* Adjust as needed */\n    --h1-font-weight: bold;\n    --h1-margin: 0.5em 0;\n    --h2-font-size: 1.5em;\n    /* Adjust as needed */\n    --h2-font-weight: bold;\n    --h2-margin: 0.4em 0;\n    --h3-font-size: 1.2em;\n    /* Adjust as needed */\n    --h3-font-weight: bold;\n    /* Message Type Colors */\n    --agent-background-color: #e0f7fa;\n    /* Light blue */\n    --agent-text-color: #333;\n    /* Dark gray */\n    --human-background-color: #fff9c4;\n    /* Light yellow */\n    --human-text-color: #333;\n    /* Dark gray */\n    --code-background-color: #f5f5f5;\n    /* Very light gray */\n    --code-text-color: #333;\n    /* Dark gray */\n    --function-background-color: #e8f5e9;\n    /* Light green */\n    --function-text-color: #333;\n    /* Dark gray */\n    --unknown-background-color: #ffAAAA;\n    /* Light red */\n    --unknown-text-color: #333;\n    /* Dark gray */\n    --h3-margin: 0.3em 0;\n    /* Chronology Item Background Colors */\n    --chronology-agent-background-color: #e0f7fa;\n    /* Light blue */\n    --chronology-agent-text-color: #333;\n    /* Dark gray */\n    --chronology-human-background-color: #fff9c4;\n    /* Light yellow */\n    --chronology-human-text-color: #333;\n    /* Dark gray */\n    --chronology-code-background-color: #f5f5f5;\n    /* Very light gray */\n    --chronology-code-text-color: #333;\n    /* Dark gray */\n    --chronology-function-background-color: #e8f5e9;\n    /* Light green */\n    --chronology-function-text-color: #333;\n    /* Dark gray */\n    --chronology-unknown-background-color: #ffAAAA;\n    /* Light red */\n    --chronology-unknown-text-color: #333;\n    --debug-border-width: 1px;\n    --debug-border-style: solid;\n    --header-border-color: lightcoral;\n    --left-border-color: lightseagreen;\n    --center-border-color: rgb(226, 226, 85);\n    --right-border-color: lightsalmon;\n    --footer-border-color: lightskyblue;\n    --text-color-base: black;\n    --background-color-base: white;\n    --border-color-base: #78f87e88;\n    --border-width-base: 1px;\n    --border-style-base: solid;\n    --font-family-base: 'Courier New', Courier, monospace;\n    --font-size-base: 16px;\n    color: var(--text-color-base);\n    background-color: var(--background-color-base);\n    border-color: var(--border-color-base);\n    border-width: var(--border-width-base);\n    border-style: var(--border-style-base);\n    font-family: var(--font-family-base);\n    font-size: var(--font-size-base);\n    /* Button Styles */\n    --button-background-color-base: var(--light-background-color);\n    --button-text-color-base: var(--text-color-base);\n    --button-border-color-base: var(--primary-border-color);\n    --button-border-width-base: 1px;\n    --button-border-style-base: solid;\n    --button-border-radius-base: 20px;\n    --button-padding-base: 8px 15px;\n    --button-hover-background-color: rgba(88, 207, 86, 0.25);\n    --button-hover-text-color: var(--text-color-base);\n    --button-hover-border-color: var(--primary-border-color-dark);\n    /* Input Styles */\n    --input-background-color: var(--background-color-base);\n    /* Use base background color */\n    --input-text-color: var(--text-color-base);\n    /* Use base text color */\n    --input-border-color: var(--border-color-base);\n    /* Use base border color */\n    --input-border-width: 1px;\n    --input-border-style: solid;\n    --input-border-radius: 5px;\n    /* Adjust as needed */\n    --input-padding: 8px;\n    /* Adjust as needed */\n    /* Link Styles */\n    --link-color: blue;\n    --link-visited-color: rgb(13, 117, 35);\n    --link-hover-color: rgb(0, 157, 255);\n    --link-text-decoration: none;\n    --link-hover-text-decoration: underline;\n    /* Tabs */\n    --tab-background-color: #9ff2a86b;\n    --tab-background-color-active: #3d972b;\n    --tab-text-color: #333;\n    --tab-text-color-active: #000;\n    --tab-border-color: #65d961;\n    --tab-border-color-active: #1df116;\n    --tab-border-width: 1px;\n    --tab-border-width-active: 5px;\n    --tab-border-style: solid;\n    /* Rounded top corners */\n    --tab-border-radius: 5px 5px 0 0;\n    --tab-padding: 8px 15px;\n    --side-panel-tab-content-background-color: #6be2621f;\n    --highlight-border-color: rgb(255, 204, 0);\n    --highlight-box-shadow-color: rgb(179, 68, 238);\n    --primary-border-color: rgba(73, 202, 71, 0.274);\n    --primary-border-color-dark: rgba(49, 138, 47, 0.837);\n    --dialog-backdrop-color: rgba(49, 138, 47, 0.58);\n    --header-border-color: var(--primary-border-color);\n    --left-border-color: var(--primary-border-color);\n    --center-border-color: var(--primary-border-color);\n    --right-border-color: var(--primary-border-color);\n    --footer-border-color: var(--primary-border-color);\n    --light-background-color: rgba(88, 207, 86, 0.144);\n    /* --very-light-background-color: rgba(88, 207, 86, 0.032); */\n    --very-light-background-color: #6be2621f;\n    /* 6be2621f */\n    /* size of the button to expand/maximize/collapse panels */\n    --handle-size: 15px;\n    --side-panel-width: 25vw;\n    --side-panel-width-maximized: 85vw;\n    --panel-transition-duration: 0.5s;\n    /* --button-background-color: var(--light-background-color); */\n    /* --button-border-color: var(--primary-border-color); */\n    /* --button-border-radius: 20px; */\n    box-sizing: border-box;\n    /* dymanically calculated pixel height loss of the header when hiding header\n     * per scrolling down */\n    --header-calculated-height-loss: 0px;\n    /* helper var to make the left panel match the panel header height when\n     * collapsed. */\n    --left-panel-header-calculated-height: 5px;\n    /* helper var to make the left panel match the panel header height when\n     * collapsed. */\n    --right-panel-header-calculated-height: 5px;\n    /* used when highlighting elements */\n    --fast-highlight-transition-time: 0.3s;\n    --slow-highlight-transition-time: 0.8s;\n    --fast-highlight-transition: border-width var(--fast-highlight-transition-time) ease-in-out,\n        border-color var(--fast-highlight-transition-time) ease-in-out,\n        border-radius var(--fast-highlight-transition-time) ease-in-out,\n        background-color var(--fast-highlight-transition-time) ease-in-out,\n        padding var(--fast-highlight-transition-time) ease-in-out;\n    --slow-highlight-transition: border-width var(--slow-highlight-transition-time) ease-in-out,\n        border-color var(--slow-highlight-transition-time) ease-in-out,\n        border-radius var(--slow-highlight-transition-time) ease-in-out,\n        background-.DS_Store color var(--slow-highlight-transition-time) ease-in-out,\n        padding var(--slow-highlight-transition-time) ease-in-out;\n}\n\n", "import { delay, extractErrorMsg, pretty, unique } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';\nimport { IbGibAddr, TjpIbGibAddr, } from '@ibgib/ts-gib/dist/types.mjs';\nimport { getIbAndGib, getIbGibAddr, } from '@ibgib/ts-gib/dist/helper.mjs';\nimport { validateIbGibAddr } from '@ibgib/ts-gib/dist/V1/validate-helper.mjs';\nimport {\n    GIB, IbGib_V1,\n    isPrimitive,\n    IBGIB_DELIMITER,\n} from '@ibgib/ts-gib/dist/V1/index.mjs';\n\nimport { GLOBAL_LOG_A_LOT } from '../../core-constants.mjs';\nimport { getFromSpace, getLatestAddrs } from '../../witness/space/space-helper.mjs';\nimport { getTimelinesGroupedByTjp, toDto } from './ibgib-helper.mjs';\nimport { IbGibSpaceAny } from '../../witness/space/space-base-v1.mjs';\nimport { FlatIbGibGraph } from './graph-types.mjs';\n\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\n/**\n * Options when getting dependency graph for ibGib(s).\n *\n * Note that this is used both in local and outer space contexts.\n * When you want to default to the local user space in the local context,\n * i.e. in `IbgibsService` atow, pass in `null` for {@link space}.\n */\nexport interface GetGraphOptions {\n    /**\n     * source ibGib to grab dependencies of.\n     *\n     * caller can pass in `ibGib` or `ibGibs` or `ibGibAddr` or `ibGibAddrs`.\n     */\n    ibGib?: IbGib_V1,\n    /**\n     * source ibGibs to grab dependencies of.\n     *\n     * caller can pass in `ibGib` or `ibGibs` or `ibGibAddr` or `ibGibAddrs`.\n     */\n    ibGibs?: IbGib_V1[],\n    /**\n     * source ibGib address to grab dependencies of.\n     *\n     * caller can pass in `ibGib` or `ibGibs` or `ibGibAddr` or `ibGibAddrs`.\n     */\n    ibGibAddr?: IbGibAddr,\n    /**\n     * source ibGib addresses to grab dependencies of.\n     *\n     * caller can pass in `ibGib` or `ibGibs` or `ibGibAddr` or `ibGibAddrs`.\n     */\n    ibGibAddrs?: IbGibAddr[],\n    /**\n     * If true, for each timeline in each \"frozen\" ibgib graph we will get the\n     * latest address in the timeline and recheck rel8d ibgibs for newly\n     * added timeline branches.\n     *\n     * If false, this will only look in the past for each rel8d ibgib.\n     *\n     * ## notes\n     *\n     * Say you have a source ibgib with a comment \"child\" (relative to our\n     * source ibgib).  Now say you add an ibgib to that child comment. The rel8d\n     * addr in the source ibgib will still point to the child comment's initial\n     * addr - before it was changed by adding its own \"child\" (\"grandchild\" to\n     * the source). So if you get a live dependency graph on the parent, it will\n     * come across the child's timeline and get the latest for that timeline\n     * (and associated ibgibs like the child's dna transforms that add the\n     * grandchild). This will include the grandchild.  If it's not a live graph,\n     * then the parent will only have the child and will exclude the grandchild.\n     */\n    live?: boolean,\n    /**\n     * object that will be populated through recursive calls to this function.\n     *\n     * First caller of this function should not provide this and I'm not atow\n     * coding a separate implementation function to ensure this.\n     *\n     * @see {@link skipAddrs}\n     */\n    gotten?: { [addr: string]: IbGib_V1 },\n    /**\n     * used when doing {@link live} dependency graph gets. Same use as\n     * {@link gotten}, but with regards to timelines.\n     */\n    tjpAddrsAlreadyAnalyzed?: TjpIbGibAddr[],\n    /**\n     * List of ibgib addresses to skip not retrive in the dependency graph.\n     *\n     * This will also skip any ibgib addresses that would have occurred in the\n     * past of these ibgibs, as when skipping an ibgib, you are also skipping\n     * its dependencies implicitly as well (unless those others are related via\n     * another ibgib that is not skipped of course).\n     *\n     * ## driving use case\n     *\n     * We don't want to get ibgibs that we already have, and this is cleaner\n     * than pre-populating the `gotten` parameter for double-duty. That property\n     * should be strictly used within this call recursively.\n     *\n     * @see {@link gotten}\n     */\n    skipAddrs?: IbGibAddr[],\n    /**\n     * Skip these particular rel8n names.\n     *\n     * ## driving intent\n     *\n     * I'm adding this to be able to skip getting dna ibgibs.\n     *\n     * ## see also\n     *\n     * @see {@link onlyRel8nNames} for whitelist of rel8n names for traversal\n     */\n    skipRel8nNames?: string[],\n    /**\n     * whitelist of rel8nNames to traverse.\n     *\n     * ## see also\n     *\n     * @see {@link skipRel8nNames} for a blacklist of rel8n names for traversal\n     */\n    onlyRel8nNames?: string[],\n    /**\n     * If not found when getting dependency graph, do we retry? This is the\n     * max number of retries.\n     */\n    maxRetries?: number,\n    /**\n     * If provided and {@link maxRetries} is non-zero, the next retry will be\n     * delayed this amount of time if one or more addrs are not found.\n     */\n    msBetweenRetries?: number,\n    /**\n     * Space within which we should be looking for ibGibs.\n     *\n     * ## NOTE on providing space vs local user space\n     *\n     * I'm reusing this interface for both generic space function and ibgib service\n     * function, which has an implicit default space of the local user space if this\n     * is falsy. So just pass in `null` if you are using this with ibgibs service and\n     * want it to default to the local user space.\n     */\n    space: IbGibSpaceAny | null,\n    /**\n     * If supplied, will make intermittent calls to console.timeLog using this name.\n     */\n    timeLogName?: string,\n    /**\n     * When getting the live dependency graph, this is used so we don't\n     * duplicate work in recursive calls.\n     *\n     * IOW, in the first run of{@link getGraphProjection_Live}, we call\n     * getLatestAddrs which maps some addrs to the latest addrs in the space. So\n     * we now have a reference to the latest and if we need to call the function\n     * {@link getGraphProjection_Live} recursively, then we can provide this\n     * info to reduce unnecessary computation.\n     */\n    mapTjpAddrToLatestAddrsInSpace?: { [tjpAddr: string]: IbGibAddr }\n}\n\nexport type GetGraphResult = FlatIbGibGraph;\n\nexport interface GetGraphProjectionOptions extends GetGraphOptions {\n    // /**\n    //  * max depth away from source ibgibs to traverse\n    //  */\n    // depth?: number;\n}\n\nexport interface GetDependencyGraphOptions extends GetGraphProjectionOptions {\n    // depth?: undefined;\n}\n\n/**\n *\n * @returns dependency graph, live or non-live depending on {@link GetDependencyGraphOptions}\n *\n * Getting a `live` dependency graph means that we will be looking in the given\n * @see {@link GetDependencyGraphOptions.space} for updates to ibGibs' timelines\n * (those ibGibs that have timelines/tjps). This is more costly computationally\n * in the short-term, but often cheaper in the long-term.\n */\nexport async function getDependencyGraph({\n    ibGib, ibGibs, ibGibAddr, ibGibAddrs,\n    live,\n    gotten, tjpAddrsAlreadyAnalyzed,\n    skipAddrs, skipRel8nNames, onlyRel8nNames,\n    maxRetries, msBetweenRetries,\n    space,\n    timeLogName,\n    mapTjpAddrToLatestAddrsInSpace,\n}: GetGraphProjectionOptions): Promise<GetGraphResult> {\n    const lc = `[${getDependencyGraph.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: c2a4426c22e849611ca0cedabe683a22)`); }\n\n        const graph = await getGraphProjection({\n            ibGib, ibGibs, ibGibAddr, ibGibAddrs,\n            live,\n            gotten, tjpAddrsAlreadyAnalyzed,\n            skipAddrs, skipRel8nNames, onlyRel8nNames,\n            maxRetries, msBetweenRetries,\n            space,\n            timeLogName,\n            mapTjpAddrToLatestAddrsInSpace,\n        });\n\n        Object.values(graph).filter(ibGib => ibGib.ib.startsWith('comment ')).forEach(ibGib => { console.table(ibGib); });\n        if (logalot) {\n            console.log(`${lc} graph size: ${Object.keys(graph).length} (I: c6cb5e7e1e2611d35b9006fac6503d22)`);\n            const ibs =\n                Object.values(graph).filter(ibGib => ibGib.ib.startsWith('comment ') || ibGib.ib.startsWith('pic '))\n                    .map(ibGib => ibGib.ib);\n            unique(ibs).forEach(ib => console.log(ib));\n        }\n        return graph;\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nasync function getGraphProjection_initializeOpts({\n    ibGib, ibGibs, ibGibAddr, ibGibAddrs,\n    live,\n    gotten, tjpAddrsAlreadyAnalyzed,\n    skipAddrs, skipRel8nNames, onlyRel8nNames,\n    maxRetries, msBetweenRetries,\n    space,\n    timeLogName,\n    mapTjpAddrToLatestAddrsInSpace,\n}: GetDependencyGraphOptions): Promise<GetDependencyGraphOptions> {\n    const lc = `[${getGraphProjection_initializeOpts.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: bd6807477f679345df9dddefe0b4e922)`); }\n\n        if (!space) { throw new Error(`space required. (E: 9f38166ab70340cb919174f8d26af909)`); }\n        if (!ibGib && !ibGibAddr && (ibGibs ?? []).length === 0 && (ibGibAddrs ?? []).length === 0) {\n            throw new Error(`either ibGib/s or ibGibAddr/s required. (E: b6d08699651f455697f0d05a41edb039)`);\n        }\n\n        skipRel8nNames = skipRel8nNames || [];\n        // do NOT initialize onlyRel8nNames because we do logic based on falsy value\n        skipAddrs = skipAddrs || [];\n        gotten = gotten || {};\n        tjpAddrsAlreadyAnalyzed = tjpAddrsAlreadyAnalyzed || [];\n\n        // convert single args (ibGib, ibGibAddr) into the array args, filtering\n        // out primitives that we don't want. The `filter` function creates the\n        // copy here, so we won't mutate the incoming arrays. (The ibgibs and\n        // addrs themselves are immutable).\n        ibGibAddrs = (ibGibAddrs ?? [])\n            .filter(x => !isPrimitive({ gib: getIbAndGib({ ibGibAddr: x }).gib })) // no primitives\n            .filter(x => !skipAddrs!.includes(x));\n        ibGibs =\n            (ibGibs ?? [])\n                .filter(x => !isPrimitive({ ibGib: x })) // no primitives\n                .filter(x => !skipAddrs!.includes(getIbGibAddr({ ibGib: x })));\n        // if we're passed in a single ibGib, add it to the ibGibs array because\n        // we're going to work off of that.\n        if (ibGib &&\n            !isPrimitive({ ibGib }) &&\n            !ibGibs.some(x => x.gib === ibGib.gib) &&\n            !skipAddrs.includes(getIbGibAddr({ ibGib }))\n        ) {\n            ibGibs.push(ibGib);\n        }\n        // if we're passed in a single ibGibAddr, add it to the ibGibAddrs array because\n        // we're going to work off of that.\n        if (ibGibAddr &&\n            !isPrimitive({ gib: getIbAndGib({ ibGibAddr }).gib }) &&\n            !ibGibAddrs.includes(ibGibAddr) &&\n            !skipAddrs.includes(ibGibAddr)\n        ) {\n            ibGibAddrs.push(ibGibAddr);\n        }\n        return {\n            ibGib, ibGibs, ibGibAddr, ibGibAddrs,\n            live,\n            gotten, tjpAddrsAlreadyAnalyzed,\n            skipAddrs, skipRel8nNames, onlyRel8nNames,\n            maxRetries, msBetweenRetries,\n            space,\n            timeLogName,\n            mapTjpAddrToLatestAddrsInSpace,\n        };\n\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nasync function getGraphProjection_getIbGibsInIbGibAddrs({\n    ibGibs,\n    ibGibAddrs,\n    gotten,\n    skipAddrs,\n    maxRetries, msBetweenRetries,\n    timeLogName,\n    space,\n}: GetGraphProjectionOptions): Promise<IbGib_V1[]> {\n    const lc = `[${getGraphProjection_getIbGibsInIbGibAddrs.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 67b2be37ff24393fff56e229304da122)`); }\n\n        /**\n         * ibgibs that we'll return\n         */\n        const resIbGibs: IbGib_V1[] = [];\n        ibGibs ??= [];\n        ibGibAddrs ??= [];\n        skipAddrs ??= [];\n        gotten ??= {};\n\n        const addrsToGetFromSpace: IbGibAddr[] = [];\n        const gottenAddrs: IbGibAddr[] = Object.keys(gotten ?? {}); // compute once in this closure\n        const incomingIbGibAddrs = ibGibs.map(x => getIbGibAddr({ ibGib: x }));\n        // const noNeedAddrs = [...gottenAddrs, ...incomingIbGibAddrs, ...skipAddrs,];\n        for (let i = 0; i < ibGibAddrs.length; i++) {\n            const addr = ibGibAddrs[i];\n            if (skipAddrs.includes(addr) || incomingIbGibAddrs.includes(addr)) {\n                continue;\n            } else if (gottenAddrs.includes(addr)) {\n                // we've already gotten this addr previously and put it into the\n                // gotten object, so we don't need to retrieve it from space\n                resIbGibs.push(gotten[addr]);\n            } else {\n                // if (!noNeedAddrs.includes(ibGibAddrs[i])) {\n                addrsToGetFromSpace.push(ibGibAddrs[i]);\n            }\n        }\n\n        if (logalot) { console.log(`${lc}[analyze debugging] addrsToGetFromSpace (${addrsToGetFromSpace.length}):\\n${addrsToGetFromSpace.join('\\n')} (I: b45a2614184b48b694becfd377c789f5)`); }\n\n        if (addrsToGetFromSpace.length > 0) {\n            // get from space, with retries if applicable\n            let addrsToGet = addrsToGetFromSpace.concat();\n            let retryCount = 0;\n            maxRetries = maxRetries ?? 0;\n            while (retryCount <= maxRetries && addrsToGet.length > 0) {\n                if (timeLogName && retryCount === 0) { console.timeLog(timeLogName, `${lc} FIRST try starting...`) }\n                if (timeLogName && retryCount > 0) { console.timeLog(timeLogName, `${lc} RETRY starting...`) }\n                // delay if applicable\n                if (retryCount > 0 && msBetweenRetries) {\n                    if (timeLogName) { console.timeLog(timeLogName, `${lc} delaying ${msBetweenRetries}ms for retry`); }\n                    if (logalot) { console.log(`${lc} retrying. addrsToGet (${addrsToGet.length}): ${addrsToGet} (I: 8460694cdd5518472680784c3b96a822)`); }\n                    await delay(msBetweenRetries);\n                }\n\n                // do the get\n                if (timeLogName) { console.timeLog(timeLogName, `${lc} getFromSpace (${addrsToGet?.length}) starting...`); }\n                if (!space) { throw new Error(`(UNEXPECTED) space falsy? (E: aa9f657695717034b3581066932d7d23)`); }\n                let resGetThese = await getFromSpace({ addrs: addrsToGet, space });\n                if (timeLogName) { console.timeLog(timeLogName, `${lc} getFromSpace complete.`); }\n                if (resGetThese.success && (resGetThese.ibGibs?.length ?? 0) > 0) {\n                    resGetThese.ibGibs!.forEach(x => resIbGibs.push(x));\n                    // resGetThese.ibGibs.forEach(x => ibGibs.push(x));\n                    const gottenAddrs = resGetThese.ibGibs!.map(x => getIbGibAddr({ ibGib: x }));\n                    if (gottenAddrs.length === addrsToGet.length) {\n                        if (timeLogName) { console.timeLog(timeLogName, `${lc} got all.`) }\n                        // got them all, so we're done\n                        addrsToGet = [];\n                        break;\n                    } else {\n                        if (timeLogName) { console.timeLog(timeLogName, `${lc} got some.`) }\n                        // got only some, prune addrsToGet for next retry (if any)\n                        addrsToGet = addrsToGet.filter(x => !gottenAddrs.includes(x));\n                    }\n                } else {\n                    // failed, maybe partial maybe completely\n                    const gottenIbGibs: IbGib_V1[] = (resGetThese.rawResultIbGib as any).ibGibs ?? [];\n                    if (gottenIbGibs.length > 0) {\n                        // failed partial\n                        gottenIbGibs.forEach(x => resIbGibs.push(x));\n                        // resGetThese.ibGibs.forEach(x => ibGibs.push(x));\n                        const gottenAddrs = gottenIbGibs.map(x => getIbGibAddr({ ibGib: x }));\n                        if (timeLogName) { console.timeLog(timeLogName, `${lc} got some.`) }\n                        // got only some, prune addrsToGet for next retry (if any)\n                        addrsToGet = addrsToGet.filter(x => !gottenAddrs.includes(x));\n                    } else {\n                        // failed completely, addrsToGet stays the same\n                        if (timeLogName) { console.timeLog(timeLogName, `${lc} failed. addrs: ${addrsToGet?.join(',')}`) }\n                    }\n                }\n                retryCount++;\n            }\n            if (addrsToGet?.length > 0) {\n                // console.dir(primaryKeysDebug);\n                throw new Error(`unable to retrieve dependency ibgibs from space (ib: ${space?.ib}). addrsToGet: ${addrsToGet.join('\\n')} (E: 8413594b6c1b447988781cf3f3e1729d)`);\n                // throw new Error(`unable to retrieve dependency ibgibs from space (ib: ${space?.ib}).\\n\\nThis is often because downloading failed due to the sync space's server getting temporarily overloaded, OR...it sometimes happens when an ibgib doesn't get fully published to the sync space in the first place.\\n\\nYou could retry immediately or later, but if the problem persists, then retry from the publishers end (have the publisher sync again). (E: 8413594b6c1b447988781cf3f3e1729d)`);\n            }\n        }\n\n        return resIbGibs;\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport async function getGraphProjection(opts: GetDependencyGraphOptions): Promise<GetGraphResult> {\n    const lc = `[${getGraphProjection.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 70508d7a5c63eae1f22ae851b32b3d22)`); }\n\n        if (!opts.ibGib && !opts.ibGibAddr && (opts.ibGibs ?? []).length === 0 && (opts.ibGibAddrs ?? []).length === 0) {\n            // no ibgibs/addrs, return empty - don't throw\n            return {} as GetGraphResult; /* <<<< returns early */\n        }\n\n        // ibGib and ibGibAddr get condensed into ibGibs and ibGibAddrs\n        let {\n            /*ibGib,*/ ibGibs, /*ibGibAddr,*/ ibGibAddrs,\n            live,\n            gotten, tjpAddrsAlreadyAnalyzed,\n            skipAddrs, skipRel8nNames, onlyRel8nNames,\n            maxRetries, msBetweenRetries,\n            space,\n            timeLogName,\n            mapTjpAddrToLatestAddrsInSpace,\n        } = await getGraphProjection_initializeOpts(opts);\n\n        if (timeLogName) { console.timeLog(timeLogName, `${lc} starting...`) }\n\n        // retrieve ibgibs listed in incoming ibGibAddrs (if any) and put them\n        // in our incoming ibGibs array\n        if (ibGibAddrs?.length ?? 0 > 0) {\n            const supplementalIbGibs = await getGraphProjection_getIbGibsInIbGibAddrs({\n                ibGibs, ibGibAddrs,\n                gotten,\n                skipAddrs,\n                maxRetries, msBetweenRetries,\n                timeLogName,\n                space,\n            });\n            ibGibs = ibGibs ?\n                [...ibGibs, ...supplementalIbGibs] :\n                [...supplementalIbGibs]\n        }\n        ibGibAddrs = ibGibs!.map(x => getIbGibAddr({ ibGib: x }));\n\n\n        // at this point, there are two different strategies for diving deeper,\n        // depending on if we are building a `live` graph or not.\n\n        let commentIbs = unique(ibGibs!.map(x => x.ib).filter(x => x.startsWith('comment ')));\n        if (logalot) { console.log(`${lc}[analyze debugging] ibGibs commentIbs: ${commentIbs.join('\\n')} (I: c89dc951315f746954f9bddbe8941122)`); }\n\n        if (live) {\n            return getGraphProjection_Live({\n                ibGibs, ibGibAddrs,\n                gotten, tjpAddrsAlreadyAnalyzed,\n                skipAddrs, skipRel8nNames, onlyRel8nNames,\n                maxRetries, msBetweenRetries,\n                space, timeLogName,\n                mapTjpAddrToLatestAddrsInSpace,\n            });\n        } else {\n            return getGraphProjection_NonLive({\n                ibGibs, ibGibAddrs,\n                gotten, /* tjpAddrsAlreadyAnalyzed not used */\n                skipAddrs, skipRel8nNames, onlyRel8nNames,\n                maxRetries, msBetweenRetries,\n                space, timeLogName,\n            });\n        }\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n\n/**\n * Get the dependency graph for {@link ibGibAddr} since {@link latestCommonFrameAddr}.\n *\n * if ibGibAddr is A^5 and latestCommonFrameAddr is A^3, then this should\n * get all dependencies in A^5 dependency graph NOT ALREADY IN the A^3\n * graph.\n *\n * NOTE: The {@link live} param is for the delta graph itself. The graph\n * corresponding to {@link latestCommonFrameAddr} is always calculated live ===\n * false.\n */\nexport async function getDeltaDependencyGraph({\n    ibGibAddr,\n    latestCommonFrameAddr,\n    live,\n    space,\n}: {\n    ibGibAddr: string;\n    latestCommonFrameAddr: string;\n    live: boolean,\n    space: IbGibSpaceAny;\n}): Promise<FlatIbGibGraph> {\n    const lc = `[${getDeltaDependencyGraph.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 5d225e56dc11e62cd83c5366ea288826)`); }\n\n        if (ibGibAddr === latestCommonFrameAddr) {\n            console.warn(`${lc} ibGibAddr === latestCommonFrameAddr. So the delta graph is empty. what are we doing here? (W: e0c8287ae6de8152bf36b6c73ca59a26)`);\n            return {};\n        }\n\n        const dependencyGraph_lcf = await getDependencyGraph({\n            ibGibAddr: latestCommonFrameAddr,\n            live: false, // always get the smaller graph live === false!\n            space,\n        });\n        const dependencyGraph_delta = await getDependencyGraph({\n            ibGibAddr,\n            live,\n            skipAddrs: Object.keys(dependencyGraph_lcf),\n            space,\n        });\n\n        return dependencyGraph_delta;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n *\n * live dependency graph searching requires a timeline-centric approach.\n * for each incoming ibGib, we must first determine if it has a\n * timeline.  if it does, then we get the latest in that timeline and\n * get all ibgibs in that lineage only. we do NOT YET go through any\n * rel8d ibgibs that also have timelines\n *\n * what we can do is compile our list of ibGib addrs according to each\n * timeline and then call the nonlive version of the dependency graph.\n * but we must get the latest in the timeline, then get all associated\n * timelines and get the latest of those. Then we can call get\n * dependency graph on the non-live version, passing in all of those\n * latest ibgibs in the timelines (and everything we've gotten in the\n * interim so we don't waste time getting more).\n *\n * @see {@link getGraphProjection}\n * @see {@link getDependencyGraph}\n */\nasync function getGraphProjection_Live({\n    ibGibs, ibGibAddrs,\n    gotten, tjpAddrsAlreadyAnalyzed,\n    mapTjpAddrToLatestAddrsInSpace,\n    skipAddrs, skipRel8nNames, onlyRel8nNames,\n    maxRetries, msBetweenRetries,\n    space,\n    timeLogName,\n}: GetGraphProjectionOptions): Promise<GetGraphResult> {\n    const lc = `[${getGraphProjection_Live.name}]`;\n    try {\n        mapTjpAddrToLatestAddrsInSpace = mapTjpAddrToLatestAddrsInSpace ?? {};\n        tjpAddrsAlreadyAnalyzed = tjpAddrsAlreadyAnalyzed ?? [];\n\n        // ibGibs contains the ones we explicitly are still working on getting\n        // projections within, gotten are the ones we have completed. so we want\n        // to get all of them together so we have a complete (up to this point)\n        // picture of timelines, because we're looking for timelines that we\n        // haven't yet analyzed\n        let allIbGibsSoFar = { ...gotten };\n        (ibGibs ?? []).forEach(x => allIbGibsSoFar[getIbGibAddr({ ibGib: x })] = x);\n        const allKnownTimelinesAtThisPoint = getTimelinesGroupedByTjp({\n            ibGibs: Object.values(allIbGibsSoFar),\n        });\n        if (logalot) { console.log(`${lc}[analyze debugging] timeline tjps(${Object.keys(allKnownTimelinesAtThisPoint).length}): ${Object.keys(allKnownTimelinesAtThisPoint)} (I: 509f04ac15ca08c5a3f0777b48934622)`); }\n\n        const timelinesNotAnalyzed: { [addr: string]: IbGib_V1[] } = {};\n        Object.keys(allKnownTimelinesAtThisPoint).forEach(tjpAddr => {\n            if (!tjpAddrsAlreadyAnalyzed!.includes(tjpAddr)) {\n                timelinesNotAnalyzed[tjpAddr] = allKnownTimelinesAtThisPoint[tjpAddr];\n            }\n        });\n        if (logalot) { console.log(`${lc}[analyze debugging] timelinesNotAnalyzed: ${pretty(timelinesNotAnalyzed)} (I: a4b67d95fdd6b98d3241c0a7d0a93c22)`); }\n\n        const mapTjpAddrToLatestIbGibInTimelineThatWeHaventAlreadyAnalyzed: { [tjpAddr: IbGibAddr]: IbGib_V1 } = {};\n        /**\n         * Convience mapping back from latest addr already gotten back to the tjp addr.\n         * Convenience = not strictly necessary, but makes it easier later.\n         */\n        const mapLatestAddrAlreadyGottenToTjpAddr: { [latestAddrAlreadyGotten: IbGibAddr]: IbGibAddr } = {};\n\n        Object.keys(allKnownTimelinesAtThisPoint)\n            .filter(tjpAddr => !tjpAddrsAlreadyAnalyzed!.includes(tjpAddr))\n            .forEach(tjpAddr => {\n                const timeline = allKnownTimelinesAtThisPoint[tjpAddr];\n                // add to the array we'll send below\n                const latestIbGibAlreadyGotten = timeline[timeline.length - 1];\n                mapTjpAddrToLatestIbGibInTimelineThatWeHaventAlreadyAnalyzed[tjpAddr] = latestIbGibAlreadyGotten;\n                // add to mapping back from addr to tjpaddr for convenience below\n                const latestAddrAlreadyGotten = getIbGibAddr({ ibGib: latestIbGibAlreadyGotten });\n                mapLatestAddrAlreadyGottenToTjpAddr[latestAddrAlreadyGotten] = tjpAddr;\n            });\n        let countOfTimelinesNotYetGotten =\n            Object.keys(mapTjpAddrToLatestIbGibInTimelineThatWeHaventAlreadyAnalyzed).length;\n\n        if (countOfTimelinesNotYetGotten > 0) {\n            // we have more timelines still to do. get the latest ibGib in each timeline,\n            // add it, check for more timelines. But we may have already gotten a latestAddrsMap\n            // in a previous call, so account for this.\n\n            // query only latest ibgibs that we haven't already gotten AND whose\n            // timelines we've not already analyzed, per\n            // mapTjpAddrToLatestAddrsInSpace.\n            /**\n             * build this map of latest addr given -> latest addr in space (per timeline/tjp).\n             */\n            let latestAddrsMap: { [addr: string]: IbGibAddr | null } = {};\n            Object.keys(mapTjpAddrToLatestAddrsInSpace)\n                .filter(tjpAddr => !tjpAddrsAlreadyAnalyzed!.includes(tjpAddr))\n                .forEach(tjpAddr => {\n                    const latestIbGibCorrespondingToTjpAddr =\n                        mapTjpAddrToLatestIbGibInTimelineThatWeHaventAlreadyAnalyzed[tjpAddr];\n                    if (latestIbGibCorrespondingToTjpAddr) {\n                        const latestAddrCorrespondingToTjpAddr =\n                            getIbGibAddr({ ibGib: latestIbGibCorrespondingToTjpAddr });\n                        latestAddrsMap[latestAddrCorrespondingToTjpAddr] = mapTjpAddrToLatestAddrsInSpace![tjpAddr];\n                    } else {\n                        console.error(`${lc} latestIbGibCorrespondingToTjpAddr is falsy`)\n                    }\n                });\n            if (logalot) { console.log(`${lc} latestAddrsMap *before* getLatestAddrs: ${pretty(latestAddrsMap)} (I: 427b4bb78595e9e521ecf2c5e5c80722)`); }\n            /**\n             * these are the ibgibs whose timelines we are aware of but haven't\n             * explicitly queried for the latest in the space.\n             */\n            const ibGibsToQueryLatestAddrs =\n                Object.values(mapTjpAddrToLatestIbGibInTimelineThatWeHaventAlreadyAnalyzed);\n\n            /**\n             * this is the result map of ibgibs whose timelines we are aware of\n             * but hadn't explicitly queried for.\n             */\n            let queriedLatestAddrsMap: { [addr: string]: IbGibAddr | null } = {};\n            if (ibGibsToQueryLatestAddrs.length > 0) {\n                if (!space) { throw new Error(`(UNEXPECTED) space falsy? (E: 8e878975e3561df9a8dc4c628b0abc23)`); }\n                /** This is result with the map of the latest addrs in the space */\n                const resLatestAddrsMapInEntireSpace = await getLatestAddrs({\n                    ibGibs: ibGibsToQueryLatestAddrs,\n                    space,\n                });\n                if (!resLatestAddrsMapInEntireSpace?.data?.latestAddrsMap) { throw new Error(`(UNEXPECTED) getLatestAddrs result latestAddrsMap falsy (E: 088caa1fc95fd3b079108ab63ef33422)`); }\n                queriedLatestAddrsMap = resLatestAddrsMapInEntireSpace?.data?.latestAddrsMap;\n                if (Object.keys(queriedLatestAddrsMap).length !== countOfTimelinesNotYetGotten) {\n                    // this happens when the space does not have the address, sometimes because of\n                    // not pushing the most recent changes to the sync space...hmmm\n                    throw new Error(`(UNEXPECTED) latestAddrsMap is not the same size as the incoming map (E: 666af512bbd44534983bb28ee8d43fed)`);\n                }\n                if (logalot) { console.log(`${lc} queriedLatestAddrsMap: ${pretty(queriedLatestAddrsMap)} (I: 7b39a5f7ce9e9d9fabae4be98ed44522)`); }\n                latestAddrsMap = {\n                    ...queriedLatestAddrsMap,\n                    ...latestAddrsMap\n                };\n            }\n            if (logalot) { console.log(`${lc} combined latestAddrsMap: ${pretty(latestAddrsMap)} (I: e3aedea63f29c5b06a79632f691aa522)`); }\n\n            /**\n             * these addrs are those whose timelines we did not yet have the latest.\n             * this means that we will have to work off of these ibgibs.\n             */\n            const newerAddrsFound: IbGibAddr[] = [];\n            const newerAddrFoundToTjpAddrMap: { [newerAddrFound: string]: IbGibAddr } = {}\n            Object.values(mapTjpAddrToLatestIbGibInTimelineThatWeHaventAlreadyAnalyzed)\n                .forEach(latestIbGibAlreadyGotten => {\n                    const latestAddrAlreadyGotten = getIbGibAddr({ ibGib: latestIbGibAlreadyGotten });\n                    const tjpAddr = mapLatestAddrAlreadyGottenToTjpAddr[latestAddrAlreadyGotten];\n                    const latestAddrInSpace = latestAddrsMap[latestAddrAlreadyGotten];\n                    if (!latestAddrInSpace) { throw new Error(`(UNEXPECTED) latestAddrInSpace not found in latestAddrsMap (E: 095d2b3f88e3e8a2c3e7d3de4c6d5622)`); }\n                    if (latestAddrInSpace === latestAddrAlreadyGotten) {\n                        // we've already got the latest for this timeline. This\n                        // means that we must have already at least queued all\n                        // timelines possible, so nothing else to do.\n                        if (logalot) { console.log(`${lc} analyzed ${tjpAddr}(I: afb7960900f04b8a87538f4c7bd903b7)`); }\n                        tjpAddrsAlreadyAnalyzed!.push(tjpAddr);\n                    } else {\n                        // there is a newer \"latest\" in this timeline that we\n                        // haven't gotten yet, so add that addr to the\n                        newerAddrsFound.push(latestAddrInSpace);\n                        newerAddrFoundToTjpAddrMap[latestAddrInSpace] = tjpAddr;\n                    }\n                });\n\n            let rel8dAddrsNotYetGotten: IbGibAddr[] = [];\n            for (let i = 0; i < (ibGibs ?? []).length; i++) {\n                const ibGib = ibGibs![i];\n                const rel8ns = ibGib.rel8ns ?? {};\n                const rel8nNames = Object.keys(rel8ns)\n                    .filter(x => !(skipRel8nNames ?? []).includes(x))\n                    .filter(x => onlyRel8nNames ? onlyRel8nNames.includes(x) : true);\n                rel8nNames.forEach(rel8nName => {\n                    const rel8dAddrs = rel8ns[rel8nName] ?? [];\n                    rel8dAddrs.forEach(rel8dAddr => {\n                        // only add todo if we don't already have the ibgib\n\n                        if (!rel8dAddrsNotYetGotten.includes(rel8dAddr) &&\n                            !ibGibs!.some(x => getIbGibAddr({ ibGib: x }) === rel8dAddr)\n                        ) {\n                            rel8dAddrsNotYetGotten.push(rel8dAddr);\n                        }\n                    });\n                });\n            }\n            ibGibAddrs = unique([...(ibGibAddrs ?? []), ...rel8dAddrsNotYetGotten, ...newerAddrsFound]);\n\n            // if (newerAddrsFound.length === 0) {\n            // there were no newer addrs found, necessitating that we have\n            // no additional ibgibs that we don't know about.\n\n            return await getGraphProjection({\n                ibGibs, ibGibAddrs,\n                gotten, tjpAddrsAlreadyAnalyzed,\n                skipAddrs, skipRel8nNames, onlyRel8nNames,\n                maxRetries, msBetweenRetries,\n                space,\n                timeLogName,\n                live: true,\n                mapTjpAddrToLatestAddrsInSpace,\n            });\n            // } else {\n            //     // #region old notes\n\n            //     // i don't know if i'll need these or if this algorithm is\n            //     // working correctly.  atow (02/2024) it looks like it is\n            //     // working from initial testing in b2tfs ibgib testing.\n\n            //     // there are still newer ibgibs that must be included in the analysis., without yet\n            //     // going into the direct rel8ns of\n            //     // need to call recursively this _Live function, passing in\n            //     // the already computated latest map in mapTjpAddrToLatestAddrsInSpace\n            //     // I need to also adjust preceding code to use this map.\n            //     // Object.keys(queriedLatestAddrsMap).forEach(latestAddrNotGotten => {\n            //     // Object.keys(queriedLatestAddrsMap).forEach(tjpAddr => {\n            //     //     const latestAddrNotGotten = queriedLatestAddrsMap[tjpAddr];\n            //     //     // const tjpAddr = mapLatestAddrAlreadyGottenToTjpAddr[latestAddrNotGotten];\n            //     //     mapTjpAddrToLatestAddrsInSpace![tjpAddr] = latestAddrNotGotten;\n            //     //     if (queriedLatestAddrsMap[latestAddrNotGotten]) { ibGibAddrs!.push(); }\n            //     // });\n            //     // ibGibAddrs = unique(ibGibAddrs);\n            //     // // ibGibAddrs = unique([...ibGibAddrs, ...rel8dAddrsNotYetGotten]);\n            //     // #endregion old notes\n\n            //     return await getGraphProjection({\n            //         ibGibs, ibGibAddrs,\n            //         gotten, tjpAddrsAlreadyAnalyzed,\n            //         skipAddrs, skipRel8nNames, onlyRel8nNames,\n            //         maxRetries, msBetweenRetries,\n            //         space,\n            //         timeLogName,\n            //         live: true,\n            //         mapTjpAddrToLatestAddrsInSpace,\n            //     });\n            // }\n        } else {\n            // we have no more timelines that we haven't already gotten, so we\n            // can pass off to the non-live version\n            if (!ibGibs) { ibGibs = []; }\n            Object.values(gotten ?? {}).forEach(x => {\n                const addr = getIbGibAddr({ ibGib: x });\n                if (!ibGibs!.some(y => getIbGibAddr({ ibGib: x }) === addr)) {\n                    ibGibs!.push(x);\n                }\n            });\n            return await getGraphProjection({ /* <<<< returns early */\n                ibGibs, ibGibAddrs,\n                gotten, /* tjpAddrsAlreadyAnalyzed not used */\n                skipAddrs, skipRel8nNames, onlyRel8nNames,\n                maxRetries, msBetweenRetries,\n                space,\n                timeLogName,\n                live: false,\n            });\n        }\n    } catch (error) {\n        const emsg = `${lc} ${error.message}`;\n        console.error(emsg);\n        if (timeLogName) { console.timeLog(timeLogName, `${lc} error: ${emsg}`); }\n        throw error;\n    } finally {\n        if (timeLogName) { console.timeLog(timeLogName, `${lc} complete.`) }\n    }\n}\n\n/**\n * NOT EXPORTED\n *\n * @see {@link getGraphProjection}\n * @see {@link getDependencyGraph}\n */\nasync function getGraphProjection_NonLive({\n    ibGibs, ibGibAddrs,\n    gotten, /* tjpAddrsAlreadyAnalyzed not used */\n    skipAddrs, skipRel8nNames, onlyRel8nNames,\n    maxRetries, msBetweenRetries,\n    space,\n    timeLogName,\n}: GetGraphProjectionOptions): Promise<GetGraphResult> {\n    const lc = `[${getGraphProjection_NonLive.name}]`;\n    try {\n        // next, compile what could be a rather large list of rel8d ibgibAddrs\n        // which must necessarily be in the past of the futuremost incoming\n        // ibGib/ibGibAddr/s as rel8ns only work backwards (whereas tjp's can\n        // refer to future timelines, the DAG substrate only looks backwards)\n        const addrsWeDontHaveAlready_Rel8dAddrs: IbGibAddr[] = [];\n        ibGibs ??= [];\n        gotten ??= {};\n        skipAddrs ??= [];\n        skipRel8nNames ??= [];\n\n        // so, we will iterate through all of our given and loaded ibGibs (not\n        // the ones in gotten map though), look through all of their rel8ns, and\n        // add any that haven't already been gotten\n        if (timeLogName) { console.timeLog(timeLogName, `${lc} analyzing next step starting...`); }\n        for (let i = 0; i < ibGibs.length; i++) {\n            const ibGib = ibGibs[i];\n            const ibGibAddr = getIbGibAddr({ ibGib });\n\n            // do i need this?\n            const { gib } = getIbAndGib({ ibGib });\n            if (gib === GIB) { throw new Error(`cannot get dependency graph of primitive.`); }\n\n            // ?\n            // I believe I have this so we don't try to do this ibgib again on recursive call.\n            // but should I be adding it at this point? hmm...\n            if (!Object.keys(gotten).includes(ibGibAddr)) { gotten[ibGibAddr] = ibGib; }\n\n            // iterate through rel8ns and compile list of ibgib addrs not yet gotten\n            /** map of addr to validation errors array */\n            const invalidAddrs: { [addr: string]: string[] } = {};\n            const rel8ns = ibGib.rel8ns || {};\n            let rel8nNames = (Object.keys(rel8ns) || []).filter(x => !skipRel8nNames!.includes(x));\n            if (onlyRel8nNames) {\n                rel8nNames = rel8nNames.filter(x => onlyRel8nNames.includes(x));\n            }\n            const gottenKeys = Object.keys(gotten);\n            for (let i = 0; i < rel8nNames.length; i++) {\n                const rel8nName = rel8nNames[i];\n                const rel8dAddrs = rel8ns[rel8nName] ?? [];\n                const falsyAddrs = rel8dAddrs.filter(addr =>\n                    addr === '' ||\n                    addr === undefined ||\n                    addr === null ||\n                    !addr.includes(IBGIB_DELIMITER)\n                );\n                if (falsyAddrs.length > 0) { console.warn(`${lc} (UNEXPECTED) has falsyAddrs: ${falsyAddrs} (W: da9505cb0a4db68a4aff7f279ad2d322)`); }\n                const rel8dAddrsNotGottenYetThisRel8n =\n                    rel8dAddrs\n                        .filter(addr => !!addr)\n                        .filter(addr => !gottenKeys.includes(addr))\n                        .filter(addr => !skipAddrs!.includes(addr))\n                        .filter(addr => getIbAndGib({ ibGibAddr: addr }).gib !== GIB)\n                        .filter(addr => !addrsWeDontHaveAlready_Rel8dAddrs.includes(addr));\n                rel8dAddrsNotGottenYetThisRel8n.forEach(rel8dAddr => {\n                    const validationErrors = validateIbGibAddr({ addr: rel8dAddr });\n                    if ((validationErrors || []).length === 0) {\n                        // valid addr. add it if we haven't gotten/queued it yet\n                        addrsWeDontHaveAlready_Rel8dAddrs.push(rel8dAddr);\n                    } else {\n                        // invalid address\n                        invalidAddrs[rel8dAddr] = validationErrors!;\n                    }\n                });\n            }\n\n            if (Object.keys(invalidAddrs).length > 0) {\n                throw new Error(`invalid addresses found in dependency graph. Errors (clipped to 1kB): ${JSON.stringify(invalidAddrs).substring(0, 1024)}`);\n            }\n        }\n        if (timeLogName) { console.timeLog(timeLogName, `${lc} analyzing next step complete.`); }\n\n        if (addrsWeDontHaveAlready_Rel8dAddrs.length > 0) {\n            if (timeLogName) { console.timeLog(timeLogName, `${lc} get addrsWeDontHaveAlready_Rel8dAddrs starting...`); }\n            // execute the get on those addrs\n            if (!space) { throw new Error(`(UNEXPECTED) space falsy? (E: 0ce327cf5d521bd798340333460f3423)`); }\n            const resGet = await getFromSpace({ addrs: addrsWeDontHaveAlready_Rel8dAddrs, space });\n            if (timeLogName) { console.timeLog(timeLogName, `${lc} get addrsWeDontHaveAlready_Rel8dAddrs complete.`); }\n            if (resGet.success) {\n                if (resGet.ibGibs?.length === addrsWeDontHaveAlready_Rel8dAddrs.length) {\n                    if (logalot) { console.log(`${lc} got ALL of them (happy path)`); }\n                    resGet.ibGibs.forEach(x => gotten![getIbGibAddr({ ibGib: x })] = x);\n                    // return a recursive call for the newly-gotten ibgibs'\n                    // dependencies, passing in the now-larger accumulating\n                    // `gotten` map of ibgibs already processed.\n                    if (timeLogName) { console.timeLog(timeLogName, `${lc} call getGraphProjection recursively starting...`); }\n                    const result = await getGraphProjection({\n                        ibGibs: resGet.ibGibs,\n                        live: false,\n                        gotten, /* tjpAddrsAlreadyAnalyzed not used */\n                        skipAddrs, skipRel8nNames, onlyRel8nNames,\n                        maxRetries, msBetweenRetries,\n                        space,\n                    });\n                    if (timeLogName) { console.timeLog(timeLogName, `${lc} call getGraphProjection recursively complete.`); }\n                    return result; // <<<< returns early\n                } else if ((resGet.ibGibs?.length ?? 0) > 0 && resGet.ibGibs!.length < addrsWeDontHaveAlready_Rel8dAddrs.length) {\n                    if (logalot) { console.warn(`${lc} got SOME of them (happy-ish path?). not sure what to do here... (W: e3458f61a1ae4979af9e6b18ac935c14)`); }\n                    throw new Error(`trouble getting dependency ibgibs (E: 8156bf65fd084ae4a4e8a0669db28b07)`);\n                } else if ((resGet.ibGibs?.length ?? 0 > 0) && resGet.ibGibs!.length > addrsWeDontHaveAlready_Rel8dAddrs.length) {\n                    // got more than our original list? not a good space behavior...\n                    throw new Error(`(UNEXPECTED) got more ibGibs than addrs that we asked for. space not working properly. (E: 352219b3d18543bcbda957f2d60b78f3)`);\n                } else {\n                    // didn't get any...hmm...\n                    throw new Error(`couldn't get dependency ibgibs from space. (E: 225f26b7d7f84911bb033753a062209b)`);\n                }\n            } else {\n                // resGet.success falsy indicates an error in the space. If it wasn't found\n                // then resGet.success would (should) still be truthy.\n                throw new Error(`failure getting addrs in space ${space?.data?.name || '[no name?]'} (id: ${space?.data?.uuid || '[no uuid?]'}). (E: 60404e6e389249d9bbecf0039cd51878) addrs:\\n${addrsWeDontHaveAlready_Rel8dAddrs.join('\\n')} `);\n            }\n        } else {\n            // no other rel8d addrs to get, so our job is done and the `gotten`\n            // map of dependency ibgibs is complete (no need for another\n            // recursive call).\n            return gotten;\n        }\n\n    } catch (error) {\n        const emsg = `${lc} ${error.message}`;\n        console.error(emsg);\n        if (timeLogName) { console.timeLog(timeLogName, `${lc} error: ${emsg}`); }\n        throw error;\n    } finally {\n        if (timeLogName) { console.timeLog(timeLogName, `${lc} complete.`) }\n    }\n}\n\n/**\n * Helper function to convert an array of {@link ibGibs} (or undefined) to a\n * {@link FlatIbGibGraph} ([addr] -> ibGib map).\n * @returns if ibGibs undefined returns undefined, else flat graph map\n */\nexport function toFlatGraph({ ibGibs }: { ibGibs: IbGib_V1[] | undefined }): FlatIbGibGraph | undefined {\n    const lc = `[${toFlatGraph.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 6019a812cff8597f79c12088e45cc226)`); }\n\n        if (ibGibs) {\n            const resGraph: FlatIbGibGraph = {};\n            ibGibs.forEach(x => { resGraph[getIbGibAddr({ ibGib: x })] = x; })\n            return resGraph;\n        } else {\n            return undefined;\n        }\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * compare two graphs for \"equivalency\".\n *\n * The default just checks that sizes and addrs are the same.\n *\n * The more thorough check does the json strings of the values (as dtos).\n */\nexport function graphsAreEquivalent({\n    graphA,\n    graphB,\n    slowButThorough,\n}: {\n    graphA: FlatIbGibGraph,\n    graphB: FlatIbGibGraph,\n    /**\n     * if true, will actually compare the dto strings of each ibgib in the graph\n     */\n    slowButThorough?: boolean,\n}): boolean {\n    const lc = `[${graphsAreEquivalent.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: e50a98b659189dece8b4ef581e4ad826)`); }\n\n        const sameSize = Object.keys(graphA).length === Object.keys(graphB).length;\n        if (!sameSize) {\n            if (logalot) { console.log(`${lc} not the same size. false. (I: e1044e52421dbf7e067e0fe850ac6826)`); }\n            return false; /* <<<< returns early */\n        }\n\n        for (const addr of Object.keys(graphA)) {\n            if (!graphB[addr]) {\n                if (logalot) { console.log(`${lc} addr (${addr}) in graphA not found in graphB (I: 264c68408378ce30b8f6a978f8b86926)`); }\n                return false; /* <<<< returns early */\n            }\n        }\n\n        if (slowButThorough) {\n            // go back through and check for dto string equality (deep equality)\n            for (const addr of Object.keys(graphA)) {\n                const ibGibA = toDto({ ibGib: graphA[addr] });\n                const jsonA = JSON.stringify(ibGibA);\n                const ibGibB = toDto({ ibGib: graphB[addr] });\n                const jsonB = JSON.stringify(ibGibB);\n                if (jsonA !== jsonB) {\n                    if (logalot) { console.log(`${lc} jsonA !== jsonB for addr (${addr}) (I: 98ed9f58ac88dabba83f96582f725926)`); }\n                    return false; /* <<<< returns early */\n                }\n            }\n        }\n\n        return true;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}", "/**\n * @module timeline-api.mts This facade provides a simplified, timeline-oriented\n * API for interacting with ibGibs, abstracting away low-level transform details\n * (like nCounter, dna, dna, tjp rel8ns) and handling concurrency control (via\n * locking) for maintaining timeline integrity.\n */\n\nimport { extractErrorMsg, getTimestampInTicks } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport {\n    IbGib_V1, IbGibData_V1, IbGibRel8ns_V1, Rel8n\n} from \"@ibgib/ts-gib/dist/V1/types.mjs\";\nimport {\n    IbGibAddr, TransformOpts_Mut8, TransformResult, Ib, IbGibRel8ns,\n} from \"@ibgib/ts-gib/dist/types.mjs\";\nimport { getIbGibAddr } from \"@ibgib/ts-gib/dist/helper.mjs\";\nimport { mut8 } from \"@ibgib/ts-gib/dist/V1/transforms/mut8.mjs\";\nimport { rel8 } from \"@ibgib/ts-gib/dist/V1/transforms/rel8.mjs\";\nimport type { TransformOpts_Rel8 } from \"@ibgib/ts-gib/dist/types.mjs\";\nimport { getGibInfo, isPrimitive } from \"@ibgib/ts-gib/dist/V1/transforms/transform-helper.mjs\";\nimport { Factory_V1 } from \"@ibgib/ts-gib/dist/V1/factory.mjs\";\nimport { ROOT } from '@ibgib/ts-gib/dist/V1/constants.mjs';\n\nimport { GLOBAL_LOG_A_LOT } from \"../core-constants.mjs\";\nimport { MetaspaceService } from \"../witness/space/metaspace/metaspace-types.mjs\";\nimport { IbGibSpaceAny } from \"../witness/space/space-base-v1.mjs\";\nimport { SpecialIbGibType } from \"../common/other/other-types.mjs\";\nimport { getSpecialConfigKey, toDto } from \"../common/other/ibgib-helper.mjs\";\nimport { execInSpaceWithLocking, getFromSpace, persistTransformResult } from \"../witness/space/space-helper.mjs\";\nimport { TimelineHistoryInfo } from \"./timeline-types.mjs\";\nimport { toFlatGraph } from \"../common/other/graph-helper.mjs\";\nimport { FlatIbGibGraph } from \"../common/other/graph-types.mjs\";\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\nexport interface Rel8nInfo {\n    rel8nName: string;\n    ibGibs: IbGib_V1[];\n}\nexport interface Rel8nRemovalInfo {\n    rel8nName: string;\n    ibGibAddrs: IbGibAddr[];\n}\n\nexport interface CommonTimelineOptsSansSkipLock {\n    /**\n     * If true, dna will not be created when executing transforms.\n     *\n     * ## intent / driving use case\n     *\n     * We want to use the timeline api in working with the new sync saga code.\n     * However, we do not want dna, because the sync saga should not be merged\n     * and there should be no dynamic composition required from dna.\n     *\n     * But the default for this api should be for dna to be created, so we add\n     * this negative flag.\n     */\n    noDna?: boolean,\n    /**\n     * space of spaces. Should be a singleton. @see {@link MetaspaceService}\n     */\n    metaspace: MetaspaceService,\n    /**\n     * the space that contains both the {@link timeline} and ibGibs contained in\n     * {@link rel8nInfos}.\n     *\n     * if falsy, then the default local user space will be gotten from the\n     * {@link metaspace}.\n     */\n    space?: IbGibSpaceAny,\n}\nexport interface CommonTimelineOpts extends CommonTimelineOptsSansSkipLock {\n    /**\n     * if true, will not lock the timeline. ONLY use this if you know what you\n     * are doing, otherwise divergent timelines can occur.\n     *\n     * Really at that point, you may consider using the raw transforms\n     * themselves.\n     */\n    skipLock?: boolean,\n}\n\n/**\n * Deterministically generates a lock scope for a given timeline.\n *\n * ## internal details, may change\n *\n * ATOW (05/2025), this will return the tjpGib of the timeline.  So if the addr\n * is `comment Foo^ABC123.DEF456`, where ABC123 and DEF456 are hashes, then this\n * will return `DEF456`. For an addr that is just `comment Bar^GHI789`, then\n * this *is* the TJP and thus its gib is `GHI789` and that is what is returned.\n */\nexport async function getLockScope({ timeline }: { timeline: IbGib_V1 }): Promise<string> {\n    const lc = `[${getLockScope.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting...`); }\n\n        if (isPrimitive({ ibGib: timeline })) {\n            // this is an abnormal/unusual path\n            console.warn(`${lc} getting lock scope on a primitive ibgib can grossly impact performance. (W: 55203e415ae2ac7ddb19c21772b28925)`)\n            return getIbGibAddr({ ibGib: timeline });\n        } else {\n            // happy path\n            const gibInfo = getGibInfo({ gib: timeline.gib });\n            const tjpGib = gibInfo.tjpGib ?? gibInfo.punctiliarHash;\n            if (!tjpGib) {\n                // This should not happen for a valid ibGib, but as a safeguard\n                throw new Error(`${lc} (UNEXPECTED) Could not determine tjpGib or punctiliarHash from ibGib. (E: eb3b6472e9b335991a1b0869f772f7d3)`);\n            }\n            return tjpGib;\n        }\n\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport async function isSameTimeline({\n    a,\n    b,\n}: {\n    a: IbGib_V1,\n    b: IbGib_V1,\n}): Promise<boolean> {\n    const lc = `[${isSameTimeline.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 0f8b68106f48a5c5c8d67f58b4b4d825)`); }\n        // DRY kluge b/c I'm soooooooo tired ...need to gtfo here\n        const aLockScope = await getLockScope({ timeline: a });\n        const bLockScope = await getLockScope({ timeline: b });\n        return aLockScope === bLockScope;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * Appends a list of ibGibs to a timeline in the order given using the\n * associated rel8nName (named edge).\n *\n * ## regarding persistence and registerNewIbGib pubsub\n *\n * The caller is responsible for persisting any ibGibs that are contained in\n * {@link rel8nInfos}. However, all newly created ibgibs resulting from extending\n * {@link timeline} *WILL* be saved in the {@link space}.\n *\n * This also will call `metaspace.registerNewIbGib` for the new timeline ibgib\n * created ONLY, and will only do this AFTER both...\n * * the timeline's lock is released AND AFTER\n * * any indexes are updated if given via {@link timelineIndexInfo}.\n * * atow (05/2025) this does not await the registerNewIbGib call, but this may\n *   change at any time.\n */\nexport async function appendToTimeline({\n    timeline,\n    rel8nInfos,\n    rel8nRemovalInfos,\n    timelineIndexInfo,\n    metaspace,\n    space,\n    skipLock,\n    noDna,\n}: {\n    timeline: IbGib_V1,\n    /**\n     * rel8nName/ibGibs pairings to append to the timeline.\n     */\n    rel8nInfos: Rel8nInfo[],\n    /**\n     * if provided, will remove this rel8ns before appending {@link rel8nInfos}\n     *\n     * ## intent/driving use case\n     *\n     * we need to be able to clear out the existing rel8ns when evolving\n     * `SyncSagaIbGib_V1`. This is not quite linkedRel8ns, rather, we just need\n     * to clear out the message stones rel8n. The underlying {@link rel8}\n     * transform already supports this via this:\n     *\n     * {@link TransformOpts_Rel8.rel8nsToRemoveByAddr}\n     *\n     * So these removal infos will translate to those `rel8nsToRemoveByAddr`.\n     */\n    rel8nRemovalInfos?: Rel8nRemovalInfo[],\n    /**\n     * If provided, will automatically update the index associated with the\n     * given {@link type} AFTER the timeline is extended but BEFORE the\n     * timeline's new ibgib is published via the {@link registerNewIbGib}\n     * function on {@link metaspace}.\n     *\n     * NOTE that this WILL LOCK the special ibgib index unless {@link skipLock}\n     * is true.\n     *\n     * @see {@link updateSpecialIndex}\n     */\n    timelineIndexInfo?: {\n        type: SpecialIbGibType,\n        rel8nName: string,\n    },\n} & CommonTimelineOpts): Promise<IbGib_V1> {\n    const lc = `[${appendToTimeline.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: fcdff10832215068019355265f4cbc25)`); }\n        space ??= await metaspace.getLocalUserSpace({ lock: false });\n        if (!space) { throw new Error(`(UNEXPECTED) space falsy? couldn't even get default local user space? (E: 2051b44a052d6a2984b9a22f680e4625)`); }\n\n        const lockScope = await getLockScope({ timeline });\n\n        /**\n         * This fn actually does the append and will be executed in the locked\n         * setting if skipLock is falsy.\n         */\n        const fn: () => Promise<IbGib_V1> = async () => {\n            if (!space) { throw new Error(`(UNEXPECTED) space falsy? couldn't even get default local user space? (E: 845c4181c8c15d7219166ceb3c4dca25)`); }\n            // Get the latest version of the provided timeline ibgib.\n            const timelineAddr = getIbGibAddr({ ibGib: timeline });\n            const latestTimelineIbGibAddr = await metaspace.getLatestAddr({\n                addr: timelineAddr,\n                space,\n            });\n            if (!latestTimelineIbGibAddr) {\n                throw new Error(`${lc} (UNEXPECTED) Could not get latest address for timeline ${getIbGibAddr({ ibGib: timeline })}. (E: a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9)`);\n            }\n            let latestTimelineIbGibDto: IbGib_V1 = toDto({ ibGib: timeline });\n            if (timelineAddr !== latestTimelineIbGibAddr) {\n                const resGetLatest = await metaspace.get({\n                    addrs: [latestTimelineIbGibAddr],\n                    space,\n                });\n                if (resGetLatest.errorMsg || (resGetLatest.ibGibs ?? []).length !== 1) {\n                    throw new Error(`${lc} (UNEXPECTED) couldn't get latest timeline ibgib (${latestTimelineIbGibAddr}) from space (${space.ib}). errorMsg: ${resGetLatest.errorMsg ?? '[unknown error]'} (E: b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0)`);\n                }\n                latestTimelineIbGibDto = resGetLatest.ibGibs!.at(0)!;\n            }\n\n            /**\n             * these rel8ns will be passed into rel8 transform for removal\n             */\n            let rel8nsToRemoveByAddr: { [name: string]: IbGibAddr[] } | undefined = undefined;\n            if (rel8nRemovalInfos && rel8nRemovalInfos.length > 0) {\n                rel8nsToRemoveByAddr = {};\n                for (const rel8nRemovalInfo of rel8nRemovalInfos) {\n                    const { rel8nName, ibGibAddrs } = rel8nRemovalInfo;\n                    if (ibGibAddrs.length === 0) {\n                        console.warn(`${lc} tried to remove 0 ibGibAddrs in rel8nName ${rel8nName}? skipping... (W: 93aeb601be66d680989e72ec70e4c826)`);\n                        continue;\n                    }\n                    if (!rel8nsToRemoveByAddr[rel8nName]) { rel8nsToRemoveByAddr[rel8nName] = []; }\n                    rel8nsToRemoveByAddr[rel8nName] = rel8nsToRemoveByAddr[rel8nName].concat(ibGibAddrs);\n                }\n            }\n\n            // Add rel8ns from the provided rel8nInfos.\n            /**\n             * these rel8ns will be passed into rel8 transform to be added\n             */\n            const rel8nsToAddByAddr: { [name: string]: IbGibAddr[] } = {};\n            for (const rel8nInfo of rel8nInfos) {\n                const { rel8nName, ibGibs } = rel8nInfo;\n                if (ibGibs.length === 0) {\n                    console.warn(`${lc} tried to add 0 ibGibs to rel8nName ${rel8nName}? skipping... (W: 708252dfdeb60757fee4554e769aaa25)`);\n                    continue;\n                }\n                if (!rel8nsToAddByAddr[rel8nName]) { rel8nsToAddByAddr[rel8nName] = []; }\n                rel8nsToAddByAddr[rel8nName].push(...ibGibs.map(ibGib => getIbGibAddr({ ibGib })));\n            }\n\n            // Perform a rel8 transform on the latest timeline ibgib.\n            const resRel8 = await rel8({\n                src: latestTimelineIbGibDto,\n                rel8nsToRemoveByAddr,\n                rel8nsToAddByAddr,\n                dna: noDna ? false : true,\n                nCounter: true,\n            });\n            const newTimelineIbGib = resRel8.newIbGib;\n\n            // Persist the transform result.\n            await metaspace.persistTransformResult({ resTransform: resRel8, space });\n\n            // If timelineIndexInfo is provided, update the special index.\n            if (timelineIndexInfo) {\n                await updateSpecialIndex({\n                    type: timelineIndexInfo.type,\n                    rel8nInfos: [{ rel8nName: timelineIndexInfo.rel8nName, ibGibs: [newTimelineIbGib] }],\n                    metaspace,\n                    space,\n                    skipLock,\n                });\n            }\n\n            // should we publish within the lock or not within the lock?\n            // should we await the publish or spin it off\n            // right now I have this spin off, inside the lock\n            // await metaspace.registerNewIbGib({ ibGib: newTimelineIbGib, space });\n            metaspace.registerNewIbGib({ ibGib: newTimelineIbGib, space }); // spin off\n\n            return newTimelineIbGib;\n        };\n\n        const newTimelineIbGib = skipLock ?\n            await fn() :\n            await execInSpaceWithLocking({\n                scope: lockScope,\n                secondsValid: 180,     // Example timeout\n                maxDelayMs: 100,       // Example delay\n                maxLockAttempts: 1800, // Example attempts\n                space,\n                callerInstanceId: getTimestampInTicks(),\n                fn,\n            });\n\n        // should we publish within the lock or not within the lock?\n        // should we await the publish or spin it off\n        // right now I have this spin off, inside the lock\n        // await metaspace.registerNewIbGib({ ibGib: newTimelineIbGib, space });\n        // metaspace.registerNewIbGib({ ibGib: newTimelineIbGib, space }); // spin off\n\n        return newTimelineIbGib;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * Updates a special ibgib in the given {@link space} with new and/or updated\n * {@link rel8nInfos}.\n *\n * ## on \"special\" ibgibs\n *\n * \"Special\" ibgibs are mostly used as indexes, but not necessarily. These are\n * slightly different than most normal ibgibs in that they are not in some way\n * or another attached to a root in the space, rather, they are rel8d directly\n * to the local user space itself. So when a special ibgib is changed, i.e. its\n * own timeline is extended, its new address is always proactively updated on\n * the space directly.  so `space.rel8ns[key]` (where key is derived from the\n * given {@link type}) is updated with newSpecialIbGib's addr.\n *\n * @see {@link setConfigAddr}\n * @see {@link rel8ToSpecialIbGib}\n *\n * ## upsert\n *\n * This is analogous to an upsert operation *into* the special index. So we are\n * updating the index's rel8ns either way whether or not that rel8n already\n * exists.\n */\nexport async function updateSpecialIndex({\n    type,\n    rel8nInfos,\n    dataToAddOrPatch,\n    metaspace,\n    space,\n    skipLock,\n}: {\n    /**\n     * identifying type of the special index. For example, spaces usually get\n     * initialized with a \"tags\" index. Individual tag ibgibs will be rel8d\n     * to this index using the `SpecialIbGibType.tags`, but really any string\n     * can be used as this type.\n     *\n     * For example, agents (atow 05/2025) have a soft type in their data.\n     * These agents are then indexed via this agent.data.type so that each type of\n     * agent has its own index, e.g., \"primaryagent\" or \"renderable\".\n     */\n    type: SpecialIbGibType,\n    rel8nInfos?: Rel8nInfo[],\n    dataToAddOrPatch?: any,\n} & CommonTimelineOpts): Promise<void> {\n    const lc = `[${updateSpecialIndex.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 6e7d05fe916d813b71766e2eaa747c25)`); }\n\n        if (type === \"latest\") { throw new Error(`cannot update the \"latest\" special index by this function. The registerNewIbGib will do this automatically. (E: 231eb78a221ccdbcf56cd1899260a425)`); }\n\n        space ??= await metaspace.getLocalUserSpace({ lock: false });\n        if (!space) { throw new Error(`(UNEXPECTED) space falsy? couldn't even get default local user space? (E: 43067821a4749a7648fe2612d25d7f25)`); }\n\n        /**\n         * This fn actually does the update and will be executed in the locked\n         * setting.\n         */\n        const fn: () => Promise<void> = async () => {\n            const fnGetSpecialIndex = async () => {\n                // always get the latest version of the special index ibgib\n                // fresh. The initialize: true option will create it if it\n                // doesn't exist.\n                const specialIndex = await metaspace.getSpecialIbGib({\n                    type,\n                    space,\n                    initialize: true,\n                });\n                if (!specialIndex) {\n                    throw new Error(`(UNEXPECTED) couldn't initialize/get special ibgib index of type ${type}. (E: a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6)`);\n                }\n                if (!specialIndex.rel8ns) {\n                    console.warn(`${lc} not sure if this ever hits, but is there ever a scenario where specialIndex.rel8ns is falsy? (W: 06161c366bc7ec858b9b5aa7ee9b6d25)`)\n                }\n                return specialIndex;\n            }\n\n            for (const rel8nInfo of (rel8nInfos ?? [])) {\n                // parse the rel8nInfo for this iteration\n                const { rel8nName, ibGibs } = rel8nInfo;\n                if (ibGibs.length === 0) {\n                    console.error(`${lc} ibGibs empty. skipping rel8nName (${rel8nName}). (E: 150d74f73f97aea1b97d173d92c77125)`);\n                }\n\n                const specialIndex = await fnGetSpecialIndex();\n\n                // // always get the latest version of the special index ibgib\n                // // fresh. The initialize: true option will create it if it\n                // // doesn't exist.\n                // const specialIndex = await metaspace.getSpecialIbGib({\n                //     type,\n                //     space,\n                //     initialize: true,\n                // });\n                // if (!specialIndex) {\n                //     throw new Error(`(UNEXPECTED) couldn't initialize/get special ibgib index of type ${type}. (E: a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6)`);\n                // }\n                // if (!specialIndex.rel8ns) {\n                //     console.warn(`${lc} not sure if this ever hits, but is there ever a scenario where specialIndex.rel8ns is falsy? (W: 06161c366bc7ec858b9b5aa7ee9b6d25)`)\n                // }\n\n                const existingSpecialIndexRel8ns = specialIndex.rel8ns ?? {};\n\n                // before we just add all the ibgibs, we need to gather info on\n                // what previous ibgibs we need to unrel8\n                let addrsToUnRel8: undefined | IbGibAddr[] = undefined;\n\n                // check if we even need to even compare existing rel8ns\n                const existingAddrsThisRel8nName = existingSpecialIndexRel8ns[rel8nName] ?? [];\n                if (existingAddrsThisRel8nName.length > 0) {\n\n                    // we have existing rel8ns for this rel8nName, so remove any\n                    // that share the tjpGib of addrs we're adding or use the\n                    // past/current full addrs. check actual code here for impl\n                    const toUnrel8ThisRel8nName_Set: Set<IbGibAddr> = new Set();\n                    ibGibs.forEach(ibGib => {\n                        const addr = getIbGibAddr({ ibGib });\n\n                        // by tjpGib impl\n                        // const gibInfo = getGibInfo({ gib: ibGib.gib });\n                        // const tjpGib = gibInfo.tjpGib ?? gibInfo.punctiliarHash ?? ibGib.gib ?? GIB;\n                        // existingAddrsThisRel8nName\n                        //     .filter(x => x.includes(tjpGib))\n                        //     .forEach(x => toUnrel8ThisRel8nName_Set.add(x));\n\n                        // by full addrs impl\n                        const pastAddrs = ibGib.rel8ns?.past ?? [];\n                        existingAddrsThisRel8nName\n                            .filter(x => [...pastAddrs, addr].includes(x))\n                            .forEach(x => toUnrel8ThisRel8nName_Set.add(x));\n                    });\n\n                    if (toUnrel8ThisRel8nName_Set.size > 0) {\n                        addrsToUnRel8 = Array.from(toUnrel8ThisRel8nName_Set);\n                    }\n                }\n\n                // we now have enough to execute the rel8\n                await metaspace.rel8ToSpecialIbGib({\n                    type,\n                    rel8nName,\n                    ibGibsToRel8: ibGibs,\n                    addrsToUnRel8,\n                    space,\n                    linked: false,\n                    severPast: false,\n                    deletePreviousSpecialIbGib: false, // only used in latest special ibgib\n                })\n            }\n\n            if (Object.keys(dataToAddOrPatch ?? {}).length > 0) {\n                const specialIndex = await fnGetSpecialIndex();\n                const resNewSpecial = await mut8({\n                    src: specialIndex,\n                    dataToAddOrPatch,\n                    dna: false,\n                    linkedRel8ns: [Rel8n.past],\n                    nCounter: true,\n                });\n\n                const newSpecialIbGib = resNewSpecial.newIbGib;\n\n                // persist\n                await persistTransformResult({ resTransform: resNewSpecial, space: space! });\n\n                // update the space ibgib which contains the special/config information\n                const configKey = getSpecialConfigKey({ type });\n                await metaspace.setConfigAddr({\n                    key: configKey,\n                    addr: getIbGibAddr({ ibGib: newSpecialIbGib }),\n                    space,\n                });\n\n                await metaspace.registerNewIbGib({ ibGib: newSpecialIbGib, space, });\n            }\n        }\n\n        if (skipLock) {\n            await fn();\n        } else {\n            // Use execInSpaceWithLocking with the special index type as the scope.\n            // We are currently choosing to always lock for special indexes for\n            // safety.  The skipLock parameter from CommonTimelineOpts is included\n            // in the signature for consistency but not used in the locking logic\n            // here based on our decision to always lock special indexes.\n            await execInSpaceWithLocking({\n                scope: type, // Use the special index type as the lock scope.\n                secondsValid: 60, // Example timeout\n                maxDelayMs: 100, // Example delay\n                maxLockAttempts: 600, // Example attempts\n                space,\n                // callerInstanceId: // You might need a way to generate a unique ID for the caller\n                fn,\n            });\n        }\n\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport async function getLatestTimelineIbGibDto_nonLocking<TIbGib extends IbGib_V1>({\n    timeline,\n    timelineAddr,\n    metaspace,\n    space,\n}: {\n    timeline?: TIbGib,\n    timelineAddr?: IbGibAddr,\n    metaspace: MetaspaceService,\n    space: IbGibSpaceAny,\n}): Promise<TIbGib> {\n    const lc = `[${getLatestTimelineIbGibDto_nonLocking.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: f2b605361368e1956f6db878dbfeb825)`); }\n\n        if (!timeline && !timelineAddr) { throw new Error(`either timeline or timelineAddr required. (E: 97551b2b18ecd22a18185a783f9a0825)`); }\n        timelineAddr ??= getIbGibAddr({ ibGib: timeline });\n\n        // const timelineAddr = getIbGibAddr({ ibGib: timeline });\n        const latestTimelineIbGibAddr = await metaspace.getLatestAddr({\n            addr: timelineAddr,\n            space,\n        }) ?? timelineAddr;\n        if (!latestTimelineIbGibAddr) {\n            throw new Error(`${lc} (UNEXPECTED) Could not get latest address for timeline ${getIbGibAddr({ ibGib: timeline })}. (E: a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9)`);\n        }\n        let latestTimelineIbGibDto: TIbGib;// = toDto({ ibGib: timeline }) as TIbGib;\n        if (timelineAddr === latestTimelineIbGibAddr) {\n            // latest addr is the same\n            if (!timeline) {\n                const resGetLatest = await metaspace.get({\n                    addrs: [latestTimelineIbGibAddr],\n                    space,\n                });\n                if (resGetLatest.errorMsg || (resGetLatest.ibGibs ?? []).length !== 1) {\n                    throw new Error(`${lc} (UNEXPECTED) couldn't get latest timeline ibgib (${latestTimelineIbGibAddr}) from space (${space.ib}). errorMsg: ${resGetLatest.errorMsg ?? '[unknown error]'} (E: 3fc767a594788a43a4ba18c87491a825)`);\n                }\n                timeline = resGetLatest.ibGibs!.at(0)! as TIbGib;\n            }\n            latestTimelineIbGibDto = toDto({ ibGib: timeline }) as TIbGib;\n        } else {\n            // latest addr is different\n            const resGetLatest = await metaspace.get({\n                addrs: [latestTimelineIbGibAddr],\n                space,\n            });\n            if (resGetLatest.errorMsg || (resGetLatest.ibGibs ?? []).length !== 1) {\n                throw new Error(`${lc} (UNEXPECTED) couldn't get latest timeline ibgib (${latestTimelineIbGibAddr}) from space (${space.ib}). errorMsg: ${resGetLatest.errorMsg ?? '[unknown error]'} (E: b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0)`);\n            }\n            latestTimelineIbGibDto = resGetLatest.ibGibs!.at(0)! as TIbGib;\n        }\n\n        return latestTimelineIbGibDto;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport async function mut8Timeline<TData extends IbGibData_V1 = any>({\n    timeline,\n    timelineAddr,\n    mut8Opts,\n    metaspace,\n    space,\n    skipLock,\n    timelineIndexInfo,\n    noDna,\n}: {\n    /**\n     * timeline ibgib whose `data` we're mutating.\n     */\n    timeline?: IbGib_V1<TData, any>,\n    timelineAddr?: IbGibAddr,\n    /**\n     * 'dataToRename' | 'dataToRemove' | 'dataToAddOrPatch' | 'mut8Ib'\n     *\n     * The rest of the mut8 options are automatic in this simplified timeline\n     * api.\n     */\n    mut8Opts: Pick<TransformOpts_Mut8<IbGib_V1, Partial<TData>>, 'dataToRename' | 'dataToRemove' | 'dataToAddOrPatch' | 'mut8Ib'>,\n    /**\n     * If provided, will automatically update the index associated with the\n     * given {@link type} AFTER the timeline is extended but BEFORE the\n     * timeline's new ibgib is published via the {@link registerNewIbGib}\n     * function on {@link metaspace}.\n     *\n     * NOTE that this WILL LOCK the special ibgib index unless {@link skipLock}\n     * is true.\n     *\n     * @see {@link updateSpecialIndex}\n     */\n    timelineIndexInfo?: {\n        type: SpecialIbGibType,\n        rel8nName: string,\n    },\n} & CommonTimelineOpts): Promise<IbGib_V1<TData, any>> {\n    const lc = `[${mut8Timeline.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n\n        if (!timeline && !timelineAddr) { throw new Error(`(UNEXPECTED) both timeline and timelineAddr falsy? either one is required. (E: a19d98c6acb87af3b876c1484f6ac825)`); }\n\n        space ??= await metaspace.getLocalUserSpace({ lock: false });\n        if (!space) { throw new Error(`(UNEXPECTED) space falsy? couldn't even get default local user space? (E: genuuid)`); }\n\n        if (!timeline) {\n            const resGet = await metaspace.get({\n                addrs: [timelineAddr!],\n                space,\n            });\n            if (!resGet.success || resGet.ibGibs?.length !== 1) {\n                throw new Error(`couldn't get timeline ibGib from timelineAddr (${timelineAddr!}) in space (${space?.ib ?? 'undefined'}) (E: genuuid)`);\n            }\n            timeline = resGet.ibGibs.at(0)! as IbGib_V1<TData, any>;\n        }\n\n        const lockScope = await getLockScope({ timeline });\n\n        /**\n         * This fn actually does the update and will be executed in the locked\n         * setting.\n         */\n        const fn: () => Promise<IbGib_V1<TData, any>> = async () => {\n            if (!space) { throw new Error(`(UNEXPECTED) space falsy? couldn't even get default local user space? (E: 845c4181c8c15d7219166ceb3c4dca25)`); }\n            // Get the latest version of the provided timeline ibgib.\n\n            if (!timeline) { throw new Error(`(UNEXPECTED) timeline falsy? we should be ensured that it's truthy at this point. (E: 2e1758b2cc3820531f7ac7f5f6b3a825)`); }\n\n            const latestTimelineIbGibDto = await getLatestTimelineIbGibDto_nonLocking({\n                timeline, metaspace, space,\n            });\n\n            // adjust mut8Opts depending\n            const resMut8 = await mut8({\n                ...mut8Opts,\n                src: latestTimelineIbGibDto,\n                dna: noDna ? false : true,\n                nCounter: true,\n            }) as TransformResult<IbGib_V1<TData, any>>;\n            const newTimelineIbGib = resMut8.newIbGib;\n\n            // Persist the transform result.\n            await metaspace.persistTransformResult({ resTransform: resMut8, space });\n\n            // If timelineIndexInfo is provided, update the special index.\n            if (timelineIndexInfo) {\n                await updateSpecialIndex({\n                    type: timelineIndexInfo.type,\n                    rel8nInfos: [{ rel8nName: timelineIndexInfo.rel8nName, ibGibs: [newTimelineIbGib] }],\n                    metaspace,\n                    space,\n                    skipLock,\n                });\n            }\n\n            // should we publish within the lock or not within the lock?\n            // should we await the publish or spin it off\n            // right now I have this spin off, inside the lock\n            // await metaspace.registerNewIbGib({ ibGib: newTimelineIbGib, space });\n            // we await the register call because this spins off the publish events (we are assuming implementation details here)\n            await metaspace.registerNewIbGib({ ibGib: newTimelineIbGib, space }); // already spins off\n\n            return newTimelineIbGib;\n        }\n\n        const newTimelineIbGib = skipLock ?\n            await fn() :\n            await execInSpaceWithLocking({\n                scope: lockScope,\n                secondsValid: 180,     // Example timeout\n                maxDelayMs: 100,       // Example delay\n                maxLockAttempts: 1800, // Example attempts\n                space,\n                callerInstanceId: getTimestampInTicks(),\n                fn,\n            });\n\n        return newTimelineIbGib;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n// todo: implement simplified locking wrappers to raw `rel8`, and `fork`\n// transforms functions. These should be `rel8Timeline`, and `forkTimeline`. But\n// these should not have skipLock available, since at that point you're really\n// basically doing the raw transforms and can use those.\n\n/**\n * Creates a new ibGib timeline and persists it to the given space.\n *\n * This is the primary entry point for creating any new, trackable piece of data\n * in the ibGib system.\n *\n * ## On usage of this factory function\n *\n * This is often used for one-offs or testing, but usually you will want to\n * create your own factory function and use this internally.\n *\n * ## On \"New\" vs. \"Fork\"\n *\n * Every ibGib is a transformation (a \"fork\") of an existing ibgib, with the\n * most primitive ibGib being the {@link ROOT} primitive. This is like the ibgib\n * analog to a zero/infinity value (the same asymptote from two sides), or in CS\n * OOP, this is like the root/base of the class hierarchy. But it's important to\n * keep in mind that time is a first-class citizen and that we are always\n * working with that instead of some detached \"new\" siloed thing.\n *\n * ## On Parenting\n *\n * The identity of an ibGib is tied to its ancestry via the `ancestor` rel8n\n * (`someIbGib.rel8ns.ancestor`). This function gives you two ways to specify\n * the parent to fork:\n *\n * 1. {@link parentIb}: If you provide a simple string like `'comment'` or `'picture'`,\n *    this function will handle creating the \"primitive\" parent ibGib\n *    (`comment^gib` or `picture^gib`) for you. This is the easiest way to\n *    create \"typed\" data, so that if you examine the `ancestor` rel8n, and see\n *    this, you know would know that this ibgib is a \"comment\" or \"picture\". Use\n *    this if you are not forking a particular instance of another ibGib.\n *\n * 2. {@link parentIbGib}: Provide a full, existing `IbGib` reference to be the\n *    parent. This can be used when using a previous ibGib as a template for\n *    just one use case. Note that this parent ibgib (and all of its\n *    dependency graph) must exist in the same given {@link space} (if\n *    provided), or in the default local user space via the {@link metaspace}.\n *    Almost always (always?), an existing parent ibgib will itself ultimately\n *    descend from a primitive ibgib.\n *\n * If neither `parentIb` nor `parentIbGib` is provided, it defaults to forking\n * the absolute {@link ROOT} ibGib, resulting in a generic, untyped timeline (or\n * relegates the typing to some other mechanism, like the `ibGib.ib` or other).\n *\n * @returns The entire transform result object, which includes `newIbGib` (the\n * latest/head of the newly created timeline) and `intermediateIbGibs` (the\n * primitive ibGibs that form its DNA and any interstitial ibGibs that were\n * created).\n */\nexport async function createTimeline<TData extends IbGibData_V1 = IbGibData_V1>({\n    ib,\n    data,\n    rel8ns,\n    noDna,\n    parentIb,\n    parentIbGib,\n    metaspace,\n    space,\n}: {\n    /**\n     * The \"ib\" content of the new ibGib. Often a short descriptor.\n     * e.g., \"some_atom SomeMetadata\".\n     *\n     * ## notes on `ib` schemas\n     *\n     * Note that the `ib` is usually a space-delimited string, with the first\n     * piece being an \"atom\" that is a naive \"type\" of the ibgib. Any\n     * constituent pieces of the `ib`, including that atom`, are usually\n     * underscore-delimited, but this is not a definite rule. The `ib` cannot\n     * contain the ib^gib delimiter (the caret ^).\n     *\n     * ## factory functions for common ibgibs\n     *\n     * There are also existing factory functions for comments (text ibgibs),\n     * pics, links, and some others. These create additional special schemas for\n     * those, if you wish to use the existing constructs, so those factory\n     * functions should be used instead of this one.\n     */\n    ib: string,\n    /**\n     * Optional data payload for the new ibGib.\n     */\n    data?: TData,\n    /**\n     * Optional relationships to other ibGibs.\n     */\n    rel8ns?: IbGibRel8ns,\n    /**\n     * The `ib` of the primitive parent to fork, e.g., `'comment'`.\n     * (See \"On Parenting\" in function docs).\n     */\n    parentIb?: Ib,\n    /**\n     * The actual `IbGib` object to fork. Overrides `parentIb` if provided.\n     * (See \"On Parenting\" in function docs).\n     */\n    parentIbGib?: IbGib_V1,\n} & CommonTimelineOptsSansSkipLock): Promise<TransformResult<IbGib_V1<TData, IbGibRel8ns_V1>>> {\n    const lc = `[${createTimeline.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting...`); }\n        space ??= await metaspace.getLocalUserSpace({ lock: false });\n        if (!space) { throw new Error(`(UNEXPECTED) space is required, but is falsy. (E: 252994a554224b17aa9816c7a765c925)`); }\n\n        // Determine the parent to fork based on the provided options.\n        parentIbGib ??= parentIb ?\n            // Easiest consumer-friendly path: create a primitive parent from a string.\n            parentIbGib = Factory_V1.primitive({ ib: parentIb }) :\n            // Default to the absolute ROOT if no parent info is given.\n            parentIbGib = ROOT;\n\n        const resNew = await Factory_V1.firstGen<TData>({\n            parentIbGib,\n            ib,\n            data,\n            rel8ns,\n            dna: noDna ? false : true,\n            nCounter: true,\n            squash: noDna ? true : false,\n            tjp: {\n                /**\n                 * always use the timestamp to generate a unique timeline\n                 */\n                timestamp: true,\n                /**\n                 * only generate new uuid if it's not in the incoming data\n                 */\n                uuid: !data?.uuid,\n            },\n        });\n\n        // Persist the new timeline and its DNA to the designated space.\n        await metaspace.persistTransformResult({ resTransform: resNew, space });\n        await metaspace.registerNewIbGib({ ibGib: resNew.newIbGib, space });\n\n        // We don't need to lock here because it's a new, independent timeline,\n        // so there are no concurrency concerns yet.\n\n        return resNew as TransformResult<IbGib_V1<TData, IbGibRel8ns_V1>>;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    }\n}\n\n/**\n * Retrieves the DNA ibGibs for a given ibGib.\n *\n * In V1, DNA is considered atomic and is not nested. This function performs a\n * direct lookup of the ibGibs pointed to by the `dna` rel8n.\n *\n * @returns An array of the primitive DNA ibGibs.\n */\nexport async function getDna({\n    ibGib,\n    metaspace,\n    space,\n}: {\n    ibGib: IbGib_V1,\n} & CommonTimelineOptsSansSkipLock): Promise<IbGib_V1[]> {\n    const lc = `[${getDna.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting...`); }\n        space ??= await metaspace.getLocalUserSpace({ lock: false });\n        if (!space) { throw new Error(`(UNEXPECTED) space is required. (E: c1b9a9b8c7d6e5f4a3b2a1a0b9c8d7e6)`); }\n\n        const dnaAddrs = ibGib.rel8ns?.dna ?? [];\n        if (dnaAddrs.length === 0) { return []; }\n\n        const resGet = await metaspace.get({ addrs: dnaAddrs, space });\n        if (!resGet.success || (resGet.ibGibs ?? []).length !== dnaAddrs.length) {\n            const notFound = dnaAddrs.filter(addr => !resGet.ibGibs?.some(x => getIbGibAddr({ ibGib: x }) === addr));\n            throw new Error(`Could not get all dna ibGibs for ${getIbGibAddr({ ibGib })}. Addrs not found: ${notFound.join(', ')}. Errors: ${resGet.errorMsg ?? '[unknown error (E: 92cf95774828d8a978331da859098625)]'} (E: d2c0b1a9a8b7c6d5e4f3a2b1a0b9c8d7)`);\n        }\n\n        return resGet.ibGibs!;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    }\n}\n\n/**\n * Constructs a {@link TimelineHistoryInfo} record about the given timeline\n * (using the {@link timeline} `ibGib.rel8ns.past`), with loaded past ibgibs,\n * and if {@link includeDna}, a reference to their dna ibgibs as well.\n *\n * @returns A complete, ordered array of ibGibs constituting the timeline,\n * from the earliest ancestor to the provided `timeline` ibGib.\n */\nexport async function getHistory({\n    timeline,\n    getLatest,\n    includeDna,\n    metaspace,\n    space,\n}: {\n    /**\n     * The ibGib at the head of the timeline whose history you want to retrieve.\n     */\n    timeline: IbGib_V1,\n    /**\n     * if true, will first retrieve the latest ibgib in the {@link timeline} in\n     * the given {@link space} if provided, else in the default local user space\n     * according to the {@link metaspace}.\n     */\n    getLatest?: boolean,\n    /**\n     * If true, includes all DNA ibGibs for the entire timeline at the\n     * beginning of the returned array.\n     * @default true\n     */\n    includeDna?: boolean,\n} & CommonTimelineOptsSansSkipLock): Promise<TimelineHistoryInfo> {\n    const lc = `[${getHistory.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 7fbc442a27e8f9fda8ac4228ded84825)`); }\n\n        space ??= await metaspace.getLocalUserSpace({ lock: false });\n        if (!space) { throw new Error(`(UNEXPECTED) space is required. (E: e3d1c0b1a9a8b7c6d5e4f3a2b1a0b9c8)`); }\n\n        const headIbGib = getLatest ?\n            await getLatestTimelineIbGibDto_nonLocking({ timeline, metaspace, space }) :\n            toDto({ ibGib: timeline }) as IbGib_V1;\n        const headAddr = getIbGibAddr({ ibGib: headIbGib });\n\n        let pastIbGibMap: FlatIbGibGraph = {};\n\n        const dnaMap = includeDna ?\n            toFlatGraph({\n                ibGibs: await getDna({ ibGib: headIbGib, metaspace, space })\n            }) :\n            undefined;\n\n        const pastAddrs = timeline.rel8ns?.past ?? [];\n        if (pastAddrs.length === 0) {\n            return {\n                headIbGib,\n                orderedPastIbGibs: [],\n                pastIbGibMap,\n                dnaMap,\n            } /* <<<< returns early */\n        }\n\n        const resGet = await metaspace.get({ addrs: pastAddrs, space });\n        if (!resGet.success || (resGet.ibGibs ?? []).length !== pastAddrs.length) {\n            const notFound = pastAddrs.filter(addr => !resGet.ibGibs?.some(x => getIbGibAddr({ ibGib: x }) === addr));\n            throw new Error(`Could not get all dna ibGibs for ${headAddr}. Addrs not found: ${notFound.join(', ')}. Errors: ${resGet.errorMsg ?? '[unknown error (E: 887339d8b5580ed1ac9892a554255525)]'} (E: 4ab7a8a58adff4e238171f7c110c6825)`);\n        }\n\n        pastIbGibMap = toFlatGraph({ ibGibs: resGet.ibGibs! }) ?? {};\n\n        const orderedPastIbGibs: IbGib_V1[] = [];\n        for (const pastAddr of pastAddrs) {\n            const pastIbGib = pastIbGibMap[pastAddr];\n            if (!pastIbGib) { throw new Error(`(UNEXPECTED) pastIbGib falsy? due to our logic, the pastIbGibMap should be complete. (E: 6010d8c14184124008631928e1265525)`); }\n            orderedPastIbGibs.push(pastIbGib);\n        }\n\n        return {\n            headIbGib,\n            orderedPastIbGibs,\n            pastIbGibMap,\n            dnaMap,\n        }\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport async function getHistoryAddrs({\n    timeline,\n    getLatest,\n    metaspace,\n    space,\n}: {\n    /**\n     * The ibGib at the head of the timeline whose history you want to retrieve.\n     */\n    timeline: IbGib_V1,\n    /**\n     * if true, will first retrieve the latest ibgib in the {@link timeline} in\n     * the given {@link space} if provided, else in the default local user space\n     * according to the {@link metaspace}.\n     */\n    getLatest?: boolean,\n} & CommonTimelineOptsSansSkipLock): Promise<IbGibAddr[]> {\n    const lc = `[${getHistoryAddrs.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: c7a328b14018642138ebb47870c15626)`); }\n\n        const historyInfo = await getHistory({\n            timeline,\n            getLatest,\n            includeDna: false,\n            metaspace,\n            space,\n        });\n\n        const addrs = historyInfo.orderedPastIbGibs.map(x => getIbGibAddr({ ibGib: x }));\n\n        return addrs;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n", "/**\n * comment ibs atow are comment [commentText substring]\n */\nexport const DEFAULT_COMMENT_TEXT_IB_SUBSTRING_LENGTH = 20;\n/**\n * comment ib can have additional metadata string,\n *\n * @example \"comment thisisacomm here_is_addl_metadata\"\n */\nexport const DEFAULT_COMMENT_METADATA_IB_SUBSTRING_LENGTH = 128;\n\n/**\n * if whitespace-only comment ibgib is enabled, the ib will contain this in\n * place of the whitespace text.\n */\nexport const COMMENT_IB_WHITESPACE_ONLY_TEXT = '___whitespace___';\n", "import { getSaferSubstring, getTimestamp, pretty } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';\nimport { Ib, TransformResult } from '@ibgib/ts-gib/dist/types.mjs';\nimport { Factory_V1 as factory, IbGib_V1 } from '@ibgib/ts-gib/dist/V1/index.mjs';\n\nimport { GLOBAL_LOG_A_LOT } from '../../core-constants.mjs';\nimport { IbGibSpaceAny } from '../../witness/space/space-base-v1.mjs';\nimport { persistTransformResult } from '../../witness/space/space-helper.mjs';\nimport { CommentData_V1, CommentIbGib_V1 } from './comment-types.mjs';\nimport { COMMENT_IB_WHITESPACE_ONLY_TEXT, DEFAULT_COMMENT_METADATA_IB_SUBSTRING_LENGTH, DEFAULT_COMMENT_TEXT_IB_SUBSTRING_LENGTH } from './comment-constants.mjs';\n\nconst logalot = GLOBAL_LOG_A_LOT || false;\n\n\n/**\n * generates an ib based on the comment text.\n *\n * Basically this gets a short substring of the comment text and replaces\n * any non alphanumeric characters.\n *\n * @param commentText comment text\n * @returns comment ib for the given comment text\n */\nexport function getCommentIb({\n  commentText,\n  addlMetadataText,\n}: {\n  commentText: string;\n  /**\n   * Optional metadata string to be included in the comment's ib.\n   * Should be underscore-delimited but not a hard rule atow.\n   *\n   * @example \"comment thisisacomm here_is_addl_metadata\"\n   */\n  addlMetadataText?: string;\n}): string {\n  const lc = `[${getCommentIb.name}]`;\n  try {\n    if (!commentText) { throw new Error(`commentText required. (E: 22fdfd0aa0524a18b63a9405b312c99e)`); }\n\n    // get a safe slice of the comment text to add to the ib\n    const ibCommentText =\n      getSaferSubstring({\n        text: commentText,\n        length: DEFAULT_COMMENT_TEXT_IB_SUBSTRING_LENGTH,\n        replaceMap: { ['?']: '__qm__' }, // we want to preserve question marks for requests for robbots\n      });\n\n    if (addlMetadataText) {\n      if (addlMetadataText.length > DEFAULT_COMMENT_METADATA_IB_SUBSTRING_LENGTH) {\n        console.warn(`${lc} addlMetadataText (${addlMetadataText.length}) is too long. Max length: ${DEFAULT_COMMENT_METADATA_IB_SUBSTRING_LENGTH}`);\n      }\n      const ibCommentMetadata =\n        getSaferSubstring({ text: addlMetadataText, length: DEFAULT_COMMENT_METADATA_IB_SUBSTRING_LENGTH });\n      if (!ibCommentMetadata) { throw new Error(`(UNEXPECTED) addlMetadataText contains no safe characters? (E: dd03c578ada2836b05c94a4aa1785222)`); }\n      return `comment ${ibCommentText} ${ibCommentMetadata}`;\n    } else {\n      return `comment ${ibCommentText}`;\n    }\n\n  } catch (error) {\n    console.error(`${lc} ${error.message}`);\n    throw error;\n  }\n}\n\nexport function parseCommentIb({\n  ib,\n}: {\n  ib: Ib,\n}): {\n  safeIbCommentText: string;\n  safeIbCommentMetadataText?: string;\n} {\n  const lc = `${parseCommentIb.name}]`;\n  try {\n    if (logalot) { console.log(`${lc} starting... (I: 1a16f5e3134599eeb585eae77ee6af22)`); }\n\n    if (!ib) { throw new Error(`ib required (E: d89f8c4df46b970585c82bc89c1c6322)`); }\n\n    let [_, safeIbCommentText, safeIbCommentMetadataText] = ib.split(' ');\n    // replaceMap: { ['?']: '__qm__' }, // we want to preserve question marks for requests for robbots\n    while (safeIbCommentText.includes('__qm__')) {\n      safeIbCommentText = safeIbCommentText.replace('__qm__', '?');\n    }\n    return { safeIbCommentText, safeIbCommentMetadataText };\n  } catch (error) {\n    console.error(`${lc} ${error.message}`);\n    throw error;\n  } finally {\n    if (logalot) { console.log(`${lc} complete.`); }\n  }\n}\n\n/**\n * creates a comment ibgib, returning the transform result,\n * optionally saving it in a given {@link space}.\n */\nexport async function createCommentIbGib({\n  text,\n  addlMetadataText,\n  saveInSpace,\n  space,\n  dontTrimText,\n}: {\n  /**\n   * comment text\n   */\n  text: string,\n  /**\n   * Optional metadata string to be included in the comment's ib.\n   * Should be underscore-delimited but not a hard rule atow.\n   *\n   * @example \"comment thisisacomm here_is_addl_metadata\"\n   */\n  addlMetadataText?: string;\n  /**\n   * If true, will save the ibgibs created in the given {@link space}.\n   */\n  saveInSpace?: boolean,\n  /**\n   * If {@link saveInSpace}, all ibgibs created in this function will be stored in\n   * this space.\n   */\n  space?: IbGibSpaceAny,\n  /**\n   * If true, stores `text` verbatim without trimming leading/trailing\n   * whitespace. Required for lossless chunking where rawTexts must tile the\n   * parent source exactly.\n   *\n   * Default: false (existing behaviour \u2014 trims whitespace).\n   */\n  dontTrimText?: boolean,\n}): Promise<TransformResult<CommentIbGib_V1>> {\n  const lc = `[${createCommentIbGib.name}]`;\n\n  if (logalot) { console.log(`${lc} starting...`); }\n  try {\n    if (!text) { throw new Error(`text required (E: 3e3d0f555e1a83771a6548eb10943522)`); }\n\n    if (!dontTrimText) { text = text.trim(); }\n\n    if (!text) { throw new Error(`text cannot be only whitespace when dontTrimText is falsy. (E: d6db3537b9834294836aeb70987c908e)`); }\n\n    const data: CommentData_V1 = { text, textTimestamp: getTimestamp() };\n\n    // create an ibgib with the filename and ext\n    const opts: any = {\n      parentIbGib: factory.primitive({ ib: 'comment' }),\n      ib: getCommentIb({ commentText: text.trim() || COMMENT_IB_WHITESPACE_ONLY_TEXT, addlMetadataText }),\n      data,\n      dna: true,\n      tjp: { uuid: true, timestamp: true },\n      nCounter: true,\n    };\n\n    // this makes it more difficult to share/sync ibgibs...\n    // if (this.addr) { opts.rel8ns = { 'comment on': [this.addr] }; }\n\n    if (logalot) { console.log(`${lc} opts: ${pretty(opts)}`); }\n    const resCommentIbGib = await factory.firstGen(opts) as TransformResult<CommentIbGib_V1>;\n\n    if (saveInSpace) {\n      if (!space) { throw new Error(`space required if saveInSpace is truthy (E: 40f69f22f21b4279a83cb746cb4b0da1)`); }\n      await persistTransformResult({ resTransform: resCommentIbGib, space });\n    }\n\n    return resCommentIbGib;\n  } catch (error) {\n    console.error(`${lc} ${error.message}`);\n    throw error;\n  }\n}\n\nexport function isComment({\n  ibGib,\n}: {\n  ibGib: IbGib_V1,\n}): boolean {\n  const lc = `[${isComment.name}]`;\n  try {\n    if (logalot) { console.log(`${lc} starting...`); }\n\n    if (!ibGib) { throw new Error(`ibGib required (E: f204dac30ae548b0a049f1c4d8048502)`); }\n\n    const { ib, data, rel8ns } = ibGib;\n\n    // try rel8ns first\n    if (!rel8ns) {\n      if (logalot) { console.log(`${lc} rel8ns falsy, NOT a comment (I: 6e145eb2d0ba46629746215a3b655fd5)`); }\n      return false;\n    }\n\n    // descends from comment^gib\n    const ancestors = rel8ns.ancestor || [];\n    if (ancestors && ancestors.includes('comment^gib')) {\n      if (logalot) { console.log(`${lc} descends from comment^gib, YES is a comment (I: 1a8557780e2e4c1580d5a2585567762b)`); }\n      return true;\n    }\n\n    // has binary qualities and ib contains 'comment'\n    if (!data) {\n      if (logalot) { console.log(`${lc} data falsy, NOT a comment (I: 30b20ff6785f432f98489f11efe24299)`); }\n      return false;\n    }\n    if (data.text && ib?.includes('comment')) {\n      if (logalot) { console.log(`${lc} has text, and ib has 'comment', YES is a comment (I: 3aa03bcd639d4ec7abd7ead917eda3d8)`); }\n      return true;\n    }\n\n    if (logalot) { console.log(`${lc} reached end, doesn't have comment qualities. NOT a comment. (I: cfa529f27f9d490abd476c924ef77087)`); }\n    return false;\n  } catch (error) {\n    console.error(`${lc} ${error.message}`);\n    throw error;\n  } finally {\n    if (logalot) { console.log(`${lc} complete.`); }\n  }\n}\n", "\n/**\n * beginning of agent.ib\n */\nexport const AGENT_ATOM = 'witness_agent';\nexport const AGENT_NAME_REGEXP = /^[a-zA-Z0-9_\\-.]{1,32}$/;\nexport const AGENT_DESC_REGEXP = /.{1,255}/;\n\nexport const DEFAULT_UUID_AGENT = '';\nexport const DEFAULT_NAME_AGENT = 'Manco';\nexport const DEFAULT_DESCRIPTION_AGENT = 'This is a generic, unspecified agent.';\n\n\n/**\n * demarcates a block of entries loaded from ibgibs requested by the model on a\n * one-time basis.\n */\nexport const CONTEXT_DECOMPRESSION_TAG = 'CONTEXT_DECOMPRESSION_REFERENCE';\n/**\n * demarcates a block of function info ibgib addresses\n */\nexport const FUNCTION_CALL_REQUEST_COMMENT_TAG = 'List of function info ibgib addresses. These contain info on both the requests you made and the resultant values.';\n\n// export const PRIMARY_AGENT_SPECIAL_IBGIB_TYPE = 'primaryagent';\n// export const PRIMARY_AGENT_SPECIAL_IBGIB_NAME = 'Robbie';\n\n/**\n * this is the rel8nName ON the special ibgib index that points to its agents.\n *\n * So `agentIndex.rel8ns[AGENT_REL8N_NAME]` is a list of the agents (addrs)\n * registered in the space.\n *\n * @see {@link MetaspaceService.getSpecialIbGib}\n * @see {@link MetaspaceService.getSpecialRel8dIbGibs}\n */\nexport const AGENT_REL8N_NAME = 'agent';\n\nexport const GEMINI_SCHEMA_AGENT_ID = {\n    type: 'string',\n    description: 'unique identifier for the agent. Should be provided to the agent in system instructions upon creation.',\n};\n\nexport const GEMINI_SCHEMA_AGENT_TYPE = {\n    type: 'string',\n    description: 'type of the agent that governs basic responsibilities. Should be provided to the agent in system instructions upon creation.',\n}\n\nexport const GEMINI_SCHEMA_SPACE_ID_FORAGENTS = {\n    type: 'string',\n    description: 'the id of a space, usually local user space. Each agent, atow (04/2025), has two spaces: a superSpace and a subSpace. The superSpace right now is just the default local user space for all agents, though this may change. The subSpace is particular only to the agent and corresponds to where internal ibgib notes/memories should be stored. So use the subSpace for internal notes, and superSpace for any user/interagent communications/notes.',\n}\n\n// #region TextSource enum\n/**\n * @see {@link TextSource.HARDCODED}\n */\nconst TEXT_SOURCE_HARDCODED = 'hardcoded';\n/**\n * @see {@link TextSource.HUMAN}\n */\nconst TEXT_SOURCE_HUMAN = 'human';\n/**\n * @see {@link TextSource.AI}\n */\nconst TEXT_SOURCE_AI = 'ai';\n/**\n * @see {@link TextSource.FUNCTION}\n */\nconst TEXT_SOURCE_FUNCTION = 'function';\n/**\n * @see {@link TextSource.UNKNOWN}\n */\nconst TEXT_SOURCE_UNKNOWN = 'unknown';\n\n/**\n * @see {@link TextSource}\n */\nexport type TextSource =\n    | typeof TEXT_SOURCE_HARDCODED\n    | typeof TEXT_SOURCE_HUMAN\n    | typeof TEXT_SOURCE_AI\n    | typeof TEXT_SOURCE_FUNCTION\n    | typeof TEXT_SOURCE_UNKNOWN\n    ;\n\n/**\n * The source of the text, which helps the LLM differentiate\n */\nexport const TextSource = {\n    /**\n     * The text was hardcoded in the system.\n     */\n    HARDCODED: TEXT_SOURCE_HARDCODED as TextSource,\n    /**\n     * The text originated from a human.\n     */\n    HUMAN: TEXT_SOURCE_HUMAN as TextSource,\n    /**\n     * The text originated from an AI.\n     */\n    AI: TEXT_SOURCE_AI as TextSource,\n    /**\n     * The text originated from a function, e.g. a function response/result.\n     */\n    FUNCTION: TEXT_SOURCE_FUNCTION as TextSource,\n    /**\n     * The origin is unknown.\n     */\n    UNKNOWN: TEXT_SOURCE_UNKNOWN as TextSource,\n} satisfies { [key: string]: TextSource };\n\nexport const TEXT_SOURCE_VALUES = Object.freeze(Object.values(TextSource));\nexport function isTextSource(str: string): str is TextSource {\n    return !!str && TEXT_SOURCE_VALUES.includes(str as TextSource);\n}\n\n// #endregion TextSource enum\n\nexport const GEMINI_SCHEMA_AGENTS_SELF_IDENTIFIED_NAME = {\n    type: 'string',\n    description: `The agent should pick a name with which to represent him/her/itself to the user. This should not be \"Gemini\" or something bland like that, rather, it should be a name that the agent likes. Should contain no spaces, only alphanumerics. Note that the example given has a name, but really it should be up to the agent's own preference. Please be consistent with this with yourself, i.e., don't change it once established. Must pass regex: ${AGENT_NAME_REGEXP.source}`,\n};\n\n/**\n * this is used in the \"special ibgib\" that indexes (keeps track of) primary\n * agents in a space.\n *\n * @see {@link MetaspaceService.getSpecialIbGib}\n * @see {@link MetaspaceService.getSpecialRel8dIbGibs}\n */\nexport const AGENT_SPECIAL_IBGIB_TYPE_PRIMARYAGENT = 'primaryagent';\nexport const AGENT_SPECIAL_IBGIB_NAME_PRIMARYAGENT = 'Robbie';\n", "import { GEMINI_SCHEMA_AGENT_ID, GEMINI_SCHEMA_AGENTS_SELF_IDENTIFIED_NAME } from \"../../witness/agent/agent-constants.mjs\";\n\n/**\n * common properties for available functions passed to models.\n */\nexport const COMMAND_BASE_SCHEMA_PROPERTIES = {\n    agentId: GEMINI_SCHEMA_AGENT_ID,\n    agentName: GEMINI_SCHEMA_AGENTS_SELF_IDENTIFIED_NAME,\n    repromptWithResult: {\n        type: 'boolean',\n        description: `Set this to true if you want to be reprompted with the function's result. Unless you really want a fire-and-forget style of function call, set this to true. NOTE: This is ignored with tellUser command, so you can't call tellUser and then repromptWithResult of true and then tellUser again.`,\n    },\n    notesToSelf: {\n        type: 'string',\n        description: 'Quick note scratchpad related to a requested function. For example, you could write your intent here.',\n    },\n} as const;\n", "import { extractErrorMsg } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\n\nimport { GLOBAL_LOG_A_LOT } from \"../constants.mjs\";\nimport { APIFunctionInfo } from \"./api-types.mjs\";\n\nconst logalot = GLOBAL_LOG_A_LOT || true;\n\nlet AllFunctionInfos: Map<string, APIFunctionInfo<any>> = new Map();\n// /**\n//  * Map of all available API functions for agents.\n//  *\n//  * NOTE: Any and all functions should be added to this.\n//  */\n// // export const AllFunctionInfos: { [nameOrId: string]: APIFunctionInfo<any> } = {\n// //     ...RenderAgentFunctionInfos.reduce((acc, info) => ({ ...acc, [info.nameOrId]: info }), {}),\n// // }\n// export const AllFunctionInfos: Map<string, APIFunctionInfo<any>> = new Map([\n//     ...ChatAPIFunctionInfos,\n//     ...TextAPIFunctionInfos,\n\n//     fetchWeb1PageFunctionInfo,\n\n//     ...RenderAgentFunctionInfos,\n//     ...ProjectFunctionInfos,\n//     ...UIAgentFunctionInfos,\n//     ...IbGibAPIFunctionInfos,\n//     ...MinigameFunctionInfos,\n// ].map(x => [x.nameOrId, x]));\n\nlet DeprecatedFunctionInfoNames: string[] = [];\n\n// export const DeprecatedFunctionInfoNames: string[] = [\n//     'minigameBuilderAddStimuli',\n//     // 'minigameBuilderEditStimuli', // debug only...this is a valid function and this needs to be removed from this list. i'm just trying to cause the prune action to happen for debugging.\n// ];\n\nexport function getAllFunctionInfos(): Map<string, APIFunctionInfo<any>> {\n    const lc = `[${getAllFunctionInfos.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: a5cf5821b42e1c71182dd61431977e25)`); }\n        return AllFunctionInfos;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport function getDeprecatedFunctionInfoNames(): string[] {\n    const lc = `[${getDeprecatedFunctionInfoNames.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 82c9a8fc91d8121fb843af32e76c2e25)`); }\n        return DeprecatedFunctionInfoNames;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport function registerDeprecatedFunctionInfoName({\n    nameOrId,\n}: {\n    nameOrId: string,\n}): void {\n    const lc = `[${registerDeprecatedFunctionInfoName.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 7519b74f49fc1d0e7b65e1ef28974225)`); }\n        if (!DeprecatedFunctionInfoNames.includes(nameOrId)) {\n            DeprecatedFunctionInfoNames.push(nameOrId);\n            if (AllFunctionInfos.has(nameOrId)) {\n                console.warn(`${lc} AllFunctionInfos contained deprecated function name (${nameOrId}). Removing from active AllFunctionInfos, but really this should not have been added as the deprecated name should have happened first. (W: fcb5681023987f258777ea18cdb90325)`);\n                AllFunctionInfos.delete(nameOrId);\n            }\n        } else {\n            console.warn(`${lc} name (${nameOrId}) already in DeprecatedFunctionInfoNames. Skipping add. (W: 6710621153282dd78c9c4aaaa4173a25)`);\n        }\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport function registerFunctionInfos({\n    functionInfos,\n}: {\n    functionInfos: Map<string, APIFunctionInfo<any>>,\n}): void {\n    const lc = `[${registerFunctionInfos.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 14fee8e27384a040494542182031ae25)`); }\n        if (functionInfos.size === 0) { console.warn(`${lc} empty functionInfos? (W: 97fcb8fc47689bc418893c09a16a2525)`); }\n        for (const [nameOrId, functionInfo] of functionInfos) {\n            if (!DeprecatedFunctionInfoNames.includes(nameOrId)) {\n                AllFunctionInfos.set(nameOrId, functionInfo);\n            } else {\n                if (logalot) { console.log(`${lc} functionInfo.nameOrId (${nameOrId}) is deprecated. Skipping add. (I: 3256eadf54f8087088a704798e2fd825)`); }\n            }\n        }\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n", "import { extractErrorMsg, pretty } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\n\nimport { APIFunctionInfo } from \"../api-types.mjs\";\nimport { CommandDataBase, CommandService, EnqueuedCommand } from \"./command-types.mjs\";\nimport { getAllFunctionInfos } from \"../api-index.mjs\";\n\n/**\n * @class CommandService_V1 - Implementation of the command service.\n * Implements the {@link CommandService} interface.\n */\nexport class CommandService_V1 implements CommandService {\n    protected lc: string = `[${CommandService_V1.name}]`;\n    private commandQueue: EnqueuedCommand<CommandDataBase<string, string[]>>[] = [];\n    private isProcessing = false;\n\n    // private anonFns: Map<string, APIFunctionInfo<any>> = new Map();\n\n    constructor() { }\n\n    // registerAnonFn({ apiFnInfo }: { apiFnInfo: APIFunctionInfo<any> }): void {\n    //     const lc = `${this.lc}[${this.registerAnonFn.name}]`;\n    //     if (this.anonFns.has(apiFnInfo.nameOrId)) {\n    //         console.warn(`${lc} anonFn already registered? (W: c6721a63affe97f5514d54bbe780f625)`)\n    //     }\n    //     this.anonFns.set(apiFnInfo.nameOrId, apiFnInfo);\n    // }\n\n    enqueueCommand<TCommand extends CommandDataBase<string, string[]>>(enqueuedCommand: EnqueuedCommand<TCommand>): void {\n        this.commandQueue.push(enqueuedCommand);\n        if (!this.isProcessing) {\n            this.startProcessing();\n        }\n    }\n\n    private startProcessing(): void {\n        this.isProcessing = true;\n        this.processQueue().finally(() => {\n            this.isProcessing = false;\n            if (this.commandQueue.length > 0) {\n                this.startProcessing(); // If more commands were added, process them\n            }\n        });\n    }\n\n    async processQueue(): Promise<void> {\n        const lc = `${this.lc}[${this.processQueue.name}]`;\n        while (this.commandQueue.length > 0) {\n            const enqueuedCommand = this.commandQueue.shift();\n            if (enqueuedCommand) {\n                try {\n                    const result =\n                        await this.executeCommand(enqueuedCommand.command, enqueuedCommand.anonApiFn);\n                    enqueuedCommand.resolve(result);\n                } catch (error: any) {\n                    console.error(`Error executing command ${enqueuedCommand.command.cmd} ${enqueuedCommand.command.cmdModifiers?.join(',') ?? ''}:`, error);\n                    enqueuedCommand.reject(error);\n                }\n            }\n        }\n    }\n\n    private async executeCommand(cmdData: CommandDataBase<string, string[]>, anonApiFn?: APIFunctionInfo<any>): Promise<any | void> {\n        const lc = `[${CommandService_V1.name}.${this.executeCommand.name}]`;\n        try {\n            const functionInfo =\n                anonApiFn ??\n                Array.from(getAllFunctionInfos().entries())\n                    .map(x => x[1] as APIFunctionInfo<any>)\n                    .find((info) => {\n                        return info.cmd === cmdData.cmd &&\n                            info.cmdModifiers.every(modifier => !!cmdData.cmdModifiers?.includes(modifier));\n                    });\n\n            if (functionInfo) {\n                console.log(`${lc} command executing. cmdData: ${pretty(cmdData)}`)\n                // Type checking and argument passing will need refinement based on schema\n                if (cmdData.notesToSelf) {\n                    console.log(`${lc} Notes to self: ${cmdData.notesToSelf}.  (I: ebcc5471b2b309ba186281c134f77e25)`);\n                }\n                const args = this.getCommandArgs(cmdData, functionInfo);\n                const result = await functionInfo.functionImpl(args);\n                return result;\n            } else {\n                throw new Error(`${lc} Unknown command: ${cmdData.cmd} with modifiers ${cmdData.cmdModifiers?.join(', ')} (E: cc9cb829f118de05b762020213ef2825)`);\n            }\n        } catch (error) {\n            debugger; // error in command svc exec\n            const errorMsg = `${lc} ${extractErrorMsg(error)}`;\n            console.error(errorMsg);\n            return { errorMsg };\n        }\n    }\n\n    /**\n     * todo: change the structure so these explicit calls aren't necessary.\n     * @param cmdData about the cmd to invoke\n     * @param functionInfo full function info corresponding to cmd\n     * @returns args that the cmd expects depending on incoming {@link cmdData}\n     */\n    private getCommandArgs(cmdData: CommandDataBase<string, string[]>, functionInfo: APIFunctionInfo): any {\n        return cmdData as any;\n        // // This will need to be refined based on the actual function signature and schema\n        // if (functionInfo.nameOrId === 'renderableCreate') {\n        //     // return { initialStates: (cmdData as RenderableCreateCommandData).initialStates, };\n        //     return cmdData as RenderableCreateCommandData;\n        // } else if (functionInfo.nameOrId === 'renderableUpdate') {\n        //     // return { handle: (cmdData as RenderableUpdateCommandData).handle,\n        //     // updatedState: (cmdData as RenderableUpdateCommandData).updatedState\n        //     // };\n        //     return cmdData as RenderableUpdateCommandData;\n        // } else if (functionInfo.nameOrId === 'renderableDestroy') {\n        //     return cmdData as RenderableDestroyCommandData;\n        // } else if (functionInfo.nameOrId === 'tellUser') {\n        //     return { text: (cmdData as TellUserCommandData).text };\n        // } else {\n        //     throw new Error(`(UNEXPECTED) unknown command? functionInfo.nameOrId: ${functionInfo.nameOrId}, cmdData: ${pretty(cmdData)} (E: 376725f2024d48c5056a9f8989616125)`);\n        // }\n    }\n\n}\n\n/**\n * @private\n */\nlet globalCommandService: CommandService | undefined;\n\n/**\n * Gets the singleton instance of the CommandService.\n * @returns {CommandService} The CommandService instance.\n */\nexport function getCommandService(): CommandService {\n    if (!globalCommandService) {\n        globalCommandService = new CommandService_V1();\n    }\n    return globalCommandService;\n}\n", "/**\n * in the OpenAPI schema for APIFunctionInfo , this is the header to be used\n * when putting examples in the OpenAPI schema description field.\n *\n * Note that this does NOT have a newline char in it, so that will be up to the\n * calling code.\n */\nexport const FUNCTION_CALL_EXAMPLES_HEADER = `## Examples: `;\n", "import { extractErrorMsg } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { IbGibAddr } from \"@ibgib/ts-gib/dist/types.mjs\";\nimport { IbGib_V1 } from \"@ibgib/ts-gib/dist/V1/types.mjs\";\nimport { getIbGibAddr } from \"@ibgib/ts-gib/dist/helper.mjs\";\nimport { rel8 } from \"@ibgib/ts-gib/dist/V1/transforms/rel8.mjs\";\n\nimport { GLOBAL_LOG_A_LOT } from \"../../core-constants.mjs\";\nimport { TagIbGib_V1 } from \"./tag-types.mjs\";\nimport { TAG_TARGET_REL8N_NAME } from \"./tag-constants.mjs\";\nimport { MetaspaceService } from \"../../witness/space/metaspace/metaspace-types.mjs\";\nimport { IbGibSpaceAny } from \"../../witness/space/space-base-v1.mjs\";\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\n/**\n * relates an ibgib provided by {@link ibGib} or {@link addr} to the latest\n * version of the given {@link tagIbGib}.\n *\n * persists this result in the same {@link space} and registers the newly\n * created tag ibgib via the {@link metaspace}.\n *\n * @returns new tag ibgib that has the ibgib related to it\n * @see {@link TAG_TARGET_REL8N_NAME}\n */\nexport async function rel8ToTag({\n    ibGib,\n    addr,\n    tagIbGib,\n    metaspace,\n    space,\n}: {\n    /**\n     * the ibgib that we're relating to the tag. can also provide just the\n     * {@link addr}.\n     */\n    ibGib?: IbGib_V1,\n    /**\n     * the ibgib addr that we're relating to the tag.\n     */\n    addr?: IbGibAddr,\n    /**\n     * the tag that we're relating to. Note that this gets the latest of this\n     * tag in the given {@link space}.\n     */\n    tagIbGib: TagIbGib_V1,\n    /**\n     * it's meta\n     */\n    metaspace: MetaspaceService,\n    /**\n     * space in which the tag exists on the tags special ibgib index\n     */\n    space: IbGibSpaceAny,\n}): Promise<TagIbGib_V1> {\n    const lc = `[${rel8ToTag.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: b1fd25ec28bce8f1916b4ab55f48a724)`); }\n\n\n        if (!addr && !ibGib) { throw new Error(`either addr or ibGib required (E: 3d580f8ecc251a0c81c7ea8bc3d38524)`); }\n        addr ??= getIbGibAddr({ ibGib });\n        if (addr !== getIbGibAddr({ ibGib })) { throw new Error(`addr (${addr}) differs from incoming ibGib's addr (${getIbGibAddr({ ibGib })}). (E: f2c14234a78c917fb9f587beaee89324)`); }\n\n        const latestTagAddr = await metaspace.getLatestAddr({ ibGib: tagIbGib, space });\n        if (latestTagAddr !== getIbGibAddr({ ibGib: tagIbGib })) {\n            let resGetLatestTag = await metaspace.get({ addr: latestTagAddr, space });\n            if (!resGetLatestTag.success || resGetLatestTag.ibGibs?.length !== 1) {\n                throw new Error(`could not get latest tag (${latestTagAddr}) from space (${space.ib}). error: ${resGetLatestTag.errorMsg ?? '[unknown error (E: a4e31c98398b417db8f617f98a5f2741)]'} (E: 73c085d81efdab0e7b8939222ec07524)`);\n            }\n            tagIbGib = resGetLatestTag.ibGibs!.at(0)! as TagIbGib_V1;\n        }\n\n        const rel8nsToAddByAddr = { [TAG_TARGET_REL8N_NAME]: [addr] };\n        const resRel8ToTag =\n            await rel8({ src: tagIbGib, rel8nsToAddByAddr, dna: true, nCounter: true });\n        const newTagIbGib = resRel8ToTag.newIbGib as TagIbGib_V1;\n\n        await metaspace.persistTransformResult({ resTransform: resRel8ToTag, space });\n        await metaspace.registerNewIbGib({ ibGib: newTagIbGib, space });\n\n        return newTagIbGib;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n", "import { extractErrorMsg, pretty } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { IbGib_V1 } from \"@ibgib/ts-gib/dist/V1/types.mjs\";\nimport { IbGibAddr } from \"@ibgib/ts-gib/dist/types.mjs\";\nimport { getIbAndGib } from \"@ibgib/ts-gib/dist/helper.mjs\";\nimport { Factory_V1 } from \"@ibgib/ts-gib/dist/V1/factory.mjs\";\nimport { rel8ToTag } from \"@ibgib/core-gib/dist/common/tag/tag-helper.mjs\";\nimport { SpaceId } from \"@ibgib/core-gib/dist/witness/space/space-types.mjs\";\nimport { MetaspaceService } from \"@ibgib/core-gib/dist/witness/space/metaspace/metaspace-types.mjs\";\nimport { SpecialIbGibType } from \"@ibgib/core-gib/dist/common/other/other-types.mjs\";\nimport { IbGibSpaceAny } from \"@ibgib/core-gib/dist/witness/space/space-base-v1.mjs\";\nimport { toDto } from \"@ibgib/core-gib/dist/common/other/ibgib-helper.mjs\";\nimport { updateSpecialIndex } from \"@ibgib/core-gib/dist/timeline/timeline-api.mjs\";\n\nimport { GLOBAL_LOG_A_LOT, HARDCODED_PROMPT_TAG_TEXT } from \"../../constants.mjs\";\nimport { getGlobalMetaspace_waitIfNeeded } from \"../../helpers.mjs\";\nimport { getAgents, getConcreteAgentFactory, getTag_Agents, getAgentIb, parseAgentIb, taggifyForPrompt  } from \"./agent-helpers.mjs\";\nimport { AddTextInfo, AgentWitnessData_V1, AgentWitnessIbGib_V1, } from \"./agent-types.mjs\";\nimport { AgentDtoToWitnessFunction, CreateNewAgentArg, CreateNewAgentResult } from \"./agent-types.mjs\";\nimport { AGENT_ATOM, AGENT_REL8N_NAME } from \"./agent-constants.mjs\";\nimport { AgentWitnessAny } from \"./agent-one-file.mjs\";\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\n\n/**\n * I'm having an issue with agents being out of date. I don't want to have to\n * update the agent to the latest which would require calling getLatest\n * (relatively expensive).\n *\n * but I am having an issue where I update an agent, but before I can update the\n * spcial ibgib index, it is being loaded again. So I am trying a hack to have a\n * simple in-memory latest hack.\n *\n * So the idea is that we will consider agents to be singleton-like, i.e., only\n * one local timeline allowed.\n */\nexport class AgentsService_V1 {\n    private lc: string = `[${AgentsService_V1.name}]`;\n\n    /**\n     * dtos of latest agents\n     */\n    private latestAgents: Map<string, AgentWitnessAny> = new Map();\n\n    private factoryFns: { [classname: string]: AgentDtoToWitnessFunction } = {};\n\n    constructor() {\n    }\n\n    async getAgentById(opts: {\n        agentId: string,\n        agentType: string,\n        spaceId?: SpaceId,\n    }): Promise<AgentWitnessAny | undefined> {\n        const lc = `${this.lc}[${this.getAgentById.name}]`;\n        try {\n            const {\n                agentId,\n                agentType,\n                spaceId,\n            } = opts;\n            if (logalot) { console.log(`${lc} starting... (I: 0c4214b4614a43bd2825978e54aee325)`); }\n            let agent = this.latestAgents.get(agentId);\n            if (!agent) {\n                const metaspace = await getGlobalMetaspace_waitIfNeeded();\n                const agents = await getAgents({ metaspace, type: agentType, spaceId });\n                agent = agents.find(x => x.data!.uuid === agentId);\n            }\n            if (!agent) { console.warn(`${lc} couldn't find any agent by id. opts: ${pretty(opts)} (W: 70cf51ecbe68dfdcfe1e9995a7468f25)`); }\n            return agent;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * SHOULD NOT NEED THIS... USE A GD PROXY.\n     *\n     * if the incoming {@link agent} is the most recent, then this will save\n     * this agent as the latest.\n     *\n     * if the incoming {@link agent} is equal, then nothing happens.\n     *\n     * if the incoming {@link agent} is older than the known latest agent, then\n     * the incoming {@link agent} will load the most recent agent's dto unless {@link throwIfNewerFound} is true.\n     */\n    async updateOrSetLatestAgent({\n        agent,\n        throwIfNewerFound,\n    }: {\n        agent: AgentWitnessAny,\n        throwIfNewerFound?: boolean,\n    }): Promise<void> {\n        const lc = `${this.lc}[${this.updateOrSetLatestAgent.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 9bb74f19b989fc0ee969cb4c2c2aa525)`); }\n            if (!agent.data) { throw new Error(`invalid agent. data falsy. agent.ib: ${agent.ib} (E: 7356db7395cb0c5664d13437dd62c425)`); }\n            if (!agent.data.uuid) { throw new Error(`invalid agent. data.uuid falsy. agent.ib: ${agent.ib} (E: 48afcd6658154bee1138fca31cbfbf25)`); }\n\n            const existing = await this.getLatestAgent({ id: agent.data.uuid });\n            if (existing) {\n                // check existing against the one we're trying to set.\n                if (!existing.data) { throw new Error(`(UNEXPECTED) existing.data falsy? should have thrown on previous set function call? (E: f3cbae9922ea9849ada25db2eea40825)`); }\n                if (existing.data.n! === agent.data.n!) {\n                    if (existing.gib === agent.gib) {\n                        // already have this version\n                        return; /* <<<< returns early */\n                    } else {\n                        console.warn(`existing.data.n === agent.data.n but gibs are different. We have a branched timeline. just logging this error, need to figure out wth is going on here. we should not have this with the timeline being locked. The only thing I can think of is if the ibgib is updated very quickly, but even then, the n should be incremented. still the approach is valid. anyway, we're going ahead and taking the newer agent.\\nexisting: ${pretty(toDto({ ibGib: existing }))}\\nnew: ${pretty(toDto({ ibGib: agent }))} (E: 5e079b566ff3533acdb2d01359f08625)`);\n                        await existing.loadIbGibDto(agent.toIbGibDto())\n                        this.latestAgents.set(agent.data.uuid, agent);\n                        return; /* <<<< returns early */\n                    }\n                } else if (existing.data.n! > agent.data.n!) {\n                    const msg = `existing.data.n > agent.data.n, i.e., the one we already have is newer. So why was the caller trying to set to the older agent thinking it was the most recent? Probably have a branched timeline.`;\n                    if (throwIfNewerFound) {\n                        throw new Error(`${lc} ${msg} (E: bb2cc3ce8cfa88b80fb62149b0e70225)`);\n                    } else {\n                        console.warn(`${lc} ${msg} (W: caaf66deb4e6fd8e2eb9261685dc0325)`);\n                    }\n                    return; /* <<<< returns early */\n                } else {\n                    // happy path, the new one is newer than the existing one\n                    await existing.loadIbGibDto(agent.toIbGibDto())\n                    this.latestAgents.set(agent.data.uuid, agent);\n                    return; /* <<<< returns early */\n                }\n            } else {\n                this.latestAgents.set(agent.data.uuid, agent);\n                return; /* <<<< returns early */\n            }\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * gets the most recent agent witness corresponding to the given {@link id},\n     * if found. If not found, then returns undefined.\n     *\n     * ## atow 04/2025 - implementation note\n     *\n     * right now this executes sync but is promise-based, because in the future\n     * this has a decent chance of becoming truly promise-based.\n     */\n    getLatestAgent({\n        id,\n    }: {\n        id: string,\n    }): Promise<AgentWitnessAny | undefined> {\n        const lc = `${this.lc}[${this.getLatestAgent.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 8e85b55057760b712a913a92e88ead25)`); }\n            return Promise.resolve(this.latestAgents.get(id));\n            // const agents = this.latestAgents.filter(x => x.data!.uuid === id);\n            // if (agents.length === 1) {\n            //     return agents.at(0)!;\n            // } else if (agents.length === 0) {\n            //     return undefined;\n            // } else {\n            //     throw new Error(`(UNEXPECTED) more than one agent with the same agent.data.uuid (${id})? (E: a4e3bc9053523e0eb4ec5514e1825825)`);\n            // }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    registerFactory({\n        classname,\n        fnDtoToAgentWitness,\n    }: {\n        classname: string,\n        fnDtoToAgentWitness: AgentDtoToWitnessFunction,\n    }): void {\n        this.factoryFns[classname] = fnDtoToAgentWitness;\n    }\n\n    async getAgentWitnessFromDto({\n        dto,\n        classname,\n    }: {\n        dto: IbGib_V1,\n        /**\n         * if provided, wills pecifically attempt to use the factory function\n         * registered for this classname. otherwise, will attempt to derive from\n         * {@link dto}.\n         */\n        classname?: string,\n    }): Promise<AgentWitnessAny | undefined> {\n        const lc = `${this.lc}[${this.getAgentWitnessFromDto.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 718837d4ee3d590177f3425b99106225)`); }\n            if (!dto.data) { throw new Error(`dto.data falsy (E: fad89dd4c787b687a657c13968946925)`); }\n\n            let agent: AgentWitnessAny | undefined = undefined;\n            classname ??= (dto.data as AgentWitnessData_V1).classname;\n            if (classname) {\n                const fn = this.factoryFns[classname];\n                const res = await fn(dto);\n                if (res.applies) {\n                    if (!res.agent) { throw new Error(`(UNEXPECTED) factory function for agent dto applies: true, but the resulting agent is undefined? (E: b13cdf0f3d9c50f1fa419f2c409ebf25)`); }\n                    agent = res.agent;\n                } else {\n                    throw new Error(`classname (${classname}) factory function found and attempted, but result says applied: false. (E: 751a2502c9a7e2d61c76c8ae2f7fb125)`);\n                }\n            } else {\n                // not found, try to brute force\n                const fnClassnames = Object.keys(this.factoryFns);\n                for (const fnClassname of fnClassnames) {\n                    const fn = this.factoryFns[fnClassname];\n                    const res = await fn(dto);\n                    if (res.applies) {\n                        if (!res.agent) { throw new Error(`(UNEXPECTED) factory function for agent dto applies: true, but the resulting agent is undefined? (E: 60e97c083a668baf11efcd6adf6a3525)`); }\n                        agent = res.agent;\n                        break;\n                    }\n                }\n            }\n            return agent;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * Retrieves an agent instance by its ibGib address.\n     * Checks the in-memory cache first. If not found, retrieves the agent ibGib\n     * from the specified space, converts the DTO to a witness, and caches it.\n     */\n    async getAgentByAddr({\n        agentAddr,\n        spaceId,\n        metaspace, // Assuming metaspace might be needed here\n    }: {\n        agentAddr: IbGibAddr,\n        spaceId?: SpaceId,\n        metaspace?: MetaspaceService,\n    }): Promise<AgentWitnessAny | undefined> {\n        const lc = `${this.lc}[${this.getAgentByAddr.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 42dfecbe6d6b5a3a7d392af5a66cc625)`); }\n\n            if (!agentAddr) { throw new Error(`${lc} agentAddr is required. (E: 389351659a2e08fa179ceede16925a25)`); }\n\n            // first check to see if we have it in the agents service already\n            const { ib: agentIb } = getIbAndGib({ ibGibAddr: agentAddr });\n            let { uuid: agentId, type: agentType } = parseAgentIb({ ib: agentIb });\n\n            if (!agentId) {\n                debugger; // error agent ib didn't have uuid?\n                throw new Error(`(UNEXPECTED) agentAddr doesn't have uuid in the ib? agentAddr: ${agentAddr} (E: fedcacffed98fdc78b1e80e45c413925)`);\n            }\n\n            let resAgent = await this.getAgentById({\n                agentId,\n                agentType,\n            });\n\n            if (resAgent) {\n                if (logalot) { console.log(`${lc} agent found already in agents svc so didn't need to go get it from the space. (I: ec6abaf3badd8e301d79a7476845bc25)`); }\n                return resAgent; /* <<<< returns early */\n            }\n\n            // we do NOT yet have it in the agents svc. so get the ibgib,\n            // convert it to a witness, add it to this service's cache,\n            // and return it\n\n            // Let's try to get the ibGib from the space first to get the UUID.\n            // We'll need the metaspace and space instance.\n            metaspace ??= await getGlobalMetaspace_waitIfNeeded();\n            const space = await metaspace.getLocalUserSpace({\n                localSpaceId: spaceId,\n                lock: false\n            });\n            if (!space) {\n                if (spaceId) {\n                    throw new Error(`couldn't get space with spaceId (${spaceId}) (E: 26b3f1414a93cc339e704d0162cb8b25)`);\n                } else {\n                    throw new Error(`(UNEXPECTED) couldn't get default local user space? (E: 2e19a1fae8b3f00595257f51426ac225)`);\n                }\n            }\n\n            const resGet = await metaspace.get({ addrs: [agentAddr], space, });\n            if (!resGet.success || !resGet.ibGibs || resGet.ibGibs.length === 0) {\n                if (logalot) { console.log(`${lc} Agent ibGib not found in space (${spaceId}) at address ${agentAddr}. (I: 29c5c7994fb3ed388b28a81a9ed68325)`); }\n                return undefined; // Agent not found in the space\n            }\n            const agentIbGib = resGet.ibGibs[0] as AgentWitnessIbGib_V1;\n\n            // 3. Convert DTO to Witness\n            const agentWitness = await this.getAgentWitnessFromDto({ dto: agentIbGib });\n            if (!agentWitness) {\n                debugger; // error couldn't get agent from dto?\n                throw new Error(`${lc} Couldn't get actual agent witness from agent dto (${agentAddr}). Have we registered classname (${agentIbGib.data?.classname}) and factory fn with agents service? (E: e6e9da6c91d14bd7acb5c571c8de1a25)`);\n            }\n\n            // 4. Cache the witness\n            await this.updateOrSetLatestAgent({\n                agent: agentWitness,\n                throwIfNewerFound: true, // we just checked, it would be weird if already exists\n            });\n            if (logalot) { console.log(`${lc} Cached agent witness with id ${agentId}. (I: b862f63147a3fac3c6e6210d5ab87c25)`); }\n\n            if (logalot) { console.log(`${lc} complete. Retrieved and cached agent witness for address ${agentAddr}.`); }\n            return agentWitness;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        }\n    }\n\n    /**\n     * factory function that creates a new agent ibgib and witness. this **DOES**\n     * save all created ibgibs (including dependency and intermediate ibgibs) in the\n     * given {@link space} if provided, else the default local space according to\n     * the given {@link metaspace}.\n     */\n    async createNewAgent(arg: CreateNewAgentArg): Promise<CreateNewAgentResult> {\n        const lc = `[${this.createNewAgent.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: a3e07b54bb7bf45f7739eff2d738c825)`); }\n            let {\n                metaspace,\n                superSpace,\n                name,\n                // api, // extracted and used in getConcreteAgentFactory\n                // model, // extracted and used in getConcreteAgentFactory\n                availableFunctions,\n                initialSystemText,\n                initialChatText,\n                fnGetAPIKey,\n                addToAgentsTag,\n                type,\n            } = arg;\n            superSpace ??= await metaspace.getLocalUserSpace({});\n            if (!superSpace) { throw new Error(`(UNEXPECTED) superSpace falsy? (E: ceb60d96ff25b6d6aaa5aa69a7a51d25)`); }\n            if (!superSpace.data) { throw new Error(`(UNEXPECTED) superSpace.data falsy? (E: 56b4ec127f8559da96e6f70c7cb13825)`); }\n\n            /**\n             * this sets the factory to the given {@link arg}\n             */\n            const agentFactory = getConcreteAgentFactory(arg);\n\n            // do the data (should be in concrete api function, pass in superSpaceId)\n            const data = await agentFactory.createInitialData(superSpace);\n            if (!data.uuid) { throw new Error(`(UNEXPECTED) data.uuid falsy? (E: 4e4f6fcf89d1e3775971ad843a083725)`); }\n\n            const newSubSpace = await metaspace.createLocalSpaceAndUpdateBootstrap({\n                allowCancel: false,\n                zeroSpace: metaspace.zeroSpace,\n                spaceName: name + data.uuid.substring(0, 5), // arbitrary\n                createBootstrap: false,\n            });\n            // let debugerrors = await validateIbGibIntrinsically({ ibGib: newSubSpace! }) ?? []; // debugging\n            // console.log(`${lc}\\n${debugerrors?.join('\\n')}`)\n            if (!newSubSpace) { throw new Error(`(UNEXPECTED) newSubSpace falsy after creating locally? (E: af8b5503c15d4292e2f591b316e7d825)`); }\n            data.subSpaceId = newSubSpace.data!.uuid;\n\n            // do the rel8ns (should be in concrete api function, pass in superSpaceId)\n            // const rel8ns = !!DEFAULT_AGENT_REL8NS_V1 ?\n            //     clone(DEFAULT_AGENT_REL8NS_V1) as AgentWitnessRel8ns_V1 :\n            //     undefined;\n            const rel8ns = await agentFactory.createInitialRel8ns();\n\n            const resFirstGen = await Factory_V1.firstGen({\n                ib: getAgentIb({ data }),\n                parentIbGib: Factory_V1.primitive({ ib: AGENT_ATOM }),\n                data, rel8ns,\n                nCounter: true, dna: true,\n                tjp: { timestamp: true, },\n            });\n            await metaspace.persistTransformResult({ resTransform: resFirstGen });\n            // await metaspace.registerNewIbGib\n            // skipping registering new ibgib with metaspace for now. maybe should\n            // do this, I don't remember.\n            const agentIbGib = resFirstGen.newIbGib as AgentWitnessIbGib_V1;\n            const agentWitness = await agentFactory.createWitness();\n            // agentWitness.setMetaspace(metaspace); // must set metaspace 1st\n\n            agentWitness.fnGetAPIKey = fnGetAPIKey;\n            await agentWitness.loadIbGibDto(agentIbGib);\n\n            if (addToAgentsTag) {\n                const agentsTagIbGib = await getTag_Agents({ metaspace, space: superSpace, });\n                // this will persist the new agents tag and register it with the\n                // given superSpace\n                let _newAgentsTagIbGib = await rel8ToTag({\n                    ibGib: agentIbGib, // just need the dto\n                    metaspace,\n                    space: superSpace,\n                    tagIbGib: agentsTagIbGib,\n                });\n            }\n\n            // always add to agent index\n                await updateSpecialIndex({\n                    type,\n                    rel8nInfos: [{ rel8nName: AGENT_REL8N_NAME, ibGibs: [agentIbGib], }],\n                    metaspace,\n                    space: superSpace,\n                });\n\n            // at this point, we should have a witness that is able to build itself\n            // up with its own functions.\n\n            if (availableFunctions.length > 0) {\n                await agentWitness.addAvailableFunctions(availableFunctions);\n            }\n\n            const textsToAdd: AddTextInfo[] = [];\n            // always tell the agent their id, superSpaceId and subSpaceId\n            textsToAdd.push({\n                textSrc: 'hardcoded',\n                text: taggifyForPrompt({\n                    tagText: HARDCODED_PROMPT_TAG_TEXT,\n                    contentText: `Your id (agent id) is: ${data.uuid}. Your superSpaceId is: ${data.superSpaceId}. Your subSpaceId is: ${data.subSpaceId}. These may be useful/required in some functions, though you should refer to those functions' instructions/descriptions for applicability.`,\n                }),\n                isSystem: true,\n            });\n\n            if (initialSystemText) {\n                textsToAdd.push({ textSrc: 'hardcoded', text: initialSystemText, isSystem: true, });\n            }\n            if (initialChatText) {\n                textsToAdd.push({ textSrc: 'hardcoded', text: initialChatText, });\n            }\n            await agentWitness.addTexts({ infos: textsToAdd, });\n\n             this.latestAgents.set(agentWitness.data!.uuid!, agentWitness);\n\n            return agentWitness;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    getAgents(opts: {\n        metaspace: MetaspaceService,\n        type: SpecialIbGibType,\n        spaceId?: SpaceId,\n        space?: IbGibSpaceAny,\n    }): Promise<AgentWitnessAny[]> {\n        const lc = `${this.lc}[${this.getAgents.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 4663f125c3a21fa3ecccc2c5a38d1225)`); }\n            return getAgents(opts);\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n}\n\n\n/**\n * Singleton {@link AgentsService_V1} instance.\n */\nlet _agentsSvcInstance: AgentsService_V1 | undefined = undefined;\nexport function getAgentsSvc(): AgentsService_V1 {\n    if (!_agentsSvcInstance) {\n        _agentsSvcInstance = new AgentsService_V1();\n    }\n    return _agentsSvcInstance;\n}\n", "export const GEMINI_ERROR_STATUS_MODEL_OVERLOADED = 503;\nexport const GEMINI_ERROR_STATUS_RATE_QUOTA_EXCEEDED = 429;\n\n/**\n * the path error.errorDetails is an array of error info objects.\n */\nexport const GEMINI_ERROR_DETAILS_TYPE_QUOTA_FAILURE = \"type.googleapis.com/google.rpc.QuotaFailure\";\nexport const GEMINI_ERROR_DETAILS_TYPE_RETRY_INFO = \"type.googleapis.com/google.rpc.RetryInfo\";\nexport const GEMINI_ERROR_DETAILS_TYPE_RETRY_INFO_RETRY_DELAY_KEY = 'retryDelay';\n\n\n// #region GeminiModel enum\nconst GEMINI_MODEL_GEMINI_3_1_PRO_PREVIEW = 'gemini-3.1-pro-preview';\nconst GEMINI_MODEL_GEMINI_3_FLASH_PREVIEW = 'gemini-3-flash-preview';\nconst GEMINI_MODEL_GEMINI_3_1_FLASH_LITE_PREVIEW = 'gemini-3.1-flash-lite-preview';\nconst GEMINI_MODEL_GEMINI_3_1_FLASH_LIVE_PREVIEW = 'gemini-3.1-flash-live-preview';\nconst GEMINI_MODEL_GEMINI_2_5_PRO = 'gemini-2.5-pro';\nconst GEMINI_MODEL_GEMINI_2_5_FLASH = 'gemini-2.5-flash';\nconst GEMINI_MODEL_GEMINI_2_5_FLASH_LITE = 'gemini-2.5-flash-lite';\nconst GEMINI_MODEL_GEMINI_2_5_FLASH_PREVIEW_TTS = 'gemini-2.5-flash-preview-tts';\nconst GEMINI_MODEL_GEMINI_2_0_FLASH = 'gemini-2.0-flash';\nconst GEMINI_MODEL_GEMINI_2_0_FLASH_LITE = 'gemini-2.0-flash-lite';\n\n// const GEMINI_MODEL_GEMINI_2_0_FLASH = 'gemini-2.0-flash-exp';\n// /**\n//  * @see {@link GeminiModel.GEMINI_1_5_FLASH}\n//  */\n// const GEMINI_MODEL_GEMINI_1_5_FLASH = 'gemini-1.5-flash';\n// /**\n//  * @see {@link GeminiModel.GEMINI_1_5_FLASH_8B}\n//  */\n// const GEMINI_MODEL_GEMINI_1_5_FLASH_8B = 'gemini-1.5-flash-8b';\n// /**\n//  * @see {@link GeminiModel.GEMINI_1_5_PRO}\n//  */\n// const GEMINI_MODEL_GEMINI_1_5_PRO = 'gemini-1.5-pro';\n\n/**\n * Enum of Gemini models that are available to the agent.\n */\nexport type GeminiModel =\n    | typeof GEMINI_MODEL_GEMINI_3_1_PRO_PREVIEW\n    | typeof GEMINI_MODEL_GEMINI_3_FLASH_PREVIEW\n    | typeof GEMINI_MODEL_GEMINI_3_1_FLASH_LITE_PREVIEW\n    | typeof GEMINI_MODEL_GEMINI_3_1_FLASH_LIVE_PREVIEW\n    | typeof GEMINI_MODEL_GEMINI_2_5_PRO\n    | typeof GEMINI_MODEL_GEMINI_2_5_FLASH\n    | typeof GEMINI_MODEL_GEMINI_2_5_FLASH_LITE\n    | typeof GEMINI_MODEL_GEMINI_2_5_FLASH_PREVIEW_TTS\n    | typeof GEMINI_MODEL_GEMINI_2_0_FLASH\n    | typeof GEMINI_MODEL_GEMINI_2_0_FLASH_LITE\n    // | typeof GEMINI_MODEL_GEMINI_1_5_FLASH\n    // | typeof GEMINI_MODEL_GEMINI_1_5_FLASH_8B\n    // | typeof GEMINI_MODEL_GEMINI_1_5_PRO\n    ;\n\n/**\n * @see {@link GeminiModel}\n */\nexport const GeminiModel = {\n    GEMINI_3_1_PRO_PREVIEW: GEMINI_MODEL_GEMINI_3_1_PRO_PREVIEW as GeminiModel,\n    GEMINI_3_FLASH_PREVIEW: GEMINI_MODEL_GEMINI_3_FLASH_PREVIEW as GeminiModel,\n    GEMINI_3_1_FLASH_LITE_PREVIEW: GEMINI_MODEL_GEMINI_3_1_FLASH_LITE_PREVIEW as GeminiModel,\n    GEMINI_3_1_FLASH_LIVE_PREVIEW: GEMINI_MODEL_GEMINI_3_1_FLASH_LIVE_PREVIEW as GeminiModel,\n    GEMINI_2_5_PRO: GEMINI_MODEL_GEMINI_2_5_PRO as GeminiModel,\n    GEMINI_2_5_FLASH: GEMINI_MODEL_GEMINI_2_5_FLASH as GeminiModel,\n    GEMINI_2_5_FLASH_LITE: GEMINI_MODEL_GEMINI_2_5_FLASH_LITE as GeminiModel,\n    GEMINI_2_5_FLASH_PREVIEW_TTS: GEMINI_MODEL_GEMINI_2_5_FLASH_PREVIEW_TTS as GeminiModel,\n    GEMINI_2_0_FLASH: GEMINI_MODEL_GEMINI_2_0_FLASH as GeminiModel,\n    GEMINI_2_0_FLASH_LITE: GEMINI_MODEL_GEMINI_2_0_FLASH_LITE as GeminiModel,\n    // /**\n    //  * @see {@link GEMINI_MODEL_GEMINI_1_5_FLASH}\n    //  */\n    // GEMINI_1_5_FLASH: GEMINI_MODEL_GEMINI_1_5_FLASH as GeminiModel,\n    // /**\n    //  * @see {@link GEMINI_MODEL_GEMINI_1_5_FLASH_8B}\n    //  */\n    // GEMINI_1_5_FLASH_8B: GEMINI_MODEL_GEMINI_1_5_FLASH_8B as GeminiModel,\n    // /**\n    //  * @see {@link GEMINI_MODEL_GEMINI_1_5_PRO}\n    //  */\n    // GEMINI_1_5_PRO: GEMINI_MODEL_GEMINI_1_5_PRO as GeminiModel,\n} satisfies { [key: string]: GeminiModel };\n\nexport const GEMINI_MODEL_VALUES = Object.freeze(Object.values(GeminiModel));\nexport function isGeminiModel(str: string): str is GeminiModel {\n    return !!str && GEMINI_MODEL_VALUES.includes(str as GeminiModel);\n}\n\n// #endregion GeminiModel enum\n\n// export const GEMINI_BACKUP_MODEL_STR = GeminiModel.GEMINI_2_0_FLASH_LITE;\nexport const GEMINI_DEFAULT_MODEL_STR = GeminiModel.GEMINI_2_5_FLASH;\nexport const GEMINI_BACKUP_MODEL_STR = GeminiModel.GEMINI_2_5_FLASH_LITE;\nexport const GEMINI_MAX_TRY_COUNT = 5;\n", "// import { extractErrorMsg, pretty, } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';\nimport { IbGib_V1 } from '@ibgib/ts-gib/dist/V1/types.mjs';\nimport { ROOT_ADDR } from '@ibgib/ts-gib/dist/V1/constants.mjs';\nimport { IbGibAddr } from '@ibgib/ts-gib/dist/types.mjs';\nimport { CommentIbGib_V1 } from '@ibgib/core-gib/dist/common/comment/comment-types.mjs';\nimport { IbGibSpaceAny } from '@ibgib/core-gib/dist/witness/space/space-base-v1.mjs';\nimport { MetaspaceService } from '@ibgib/core-gib/dist/witness/space/metaspace/metaspace-types.mjs';\nimport { WitnessData_V1, WitnessRel8ns_V1 } from '@ibgib/core-gib/dist/witness/witness-types.mjs';\nimport { SpaceId } from '@ibgib/core-gib/dist/witness/space/space-types.mjs';\n\n// import { GLOBAL_LOG_A_LOT } from '../../constants.mjs';\nimport { APIFunctionInfo } from '../../api/api-types.mjs';\nimport type { AgentWitness_V1 } from './agent-one-file.mjs';\nimport { AgentWitnessAny, } from './agent-one-file.mjs';\nimport { GEMINI_DEFAULT_MODEL_STR, GeminiModel } from './gemini/gemini-constants.mjs';\nimport {\n    AGENT_SPECIAL_IBGIB_TYPE_PRIMARYAGENT, DEFAULT_DESCRIPTION_AGENT,\n    DEFAULT_NAME_AGENT, DEFAULT_UUID_AGENT, TextSource\n} from './agent-constants.mjs';\nimport { PromptAPIResult_Gemini } from './gemini/gemini-types.mjs';\n\n\nexport const DEFAULT_AGENT_DATA_V1: AgentWitnessData_V1 = {\n    version: '1',\n    uuid: DEFAULT_UUID_AGENT,\n    name: DEFAULT_NAME_AGENT,\n    description: DEFAULT_DESCRIPTION_AGENT,\n    classname: `AgentWitness_V1`,\n    icon: 'happy', // arbitrary\n    persistOptsAndResultIbGibs: false,\n    allowPrimitiveArgs: true,\n    catchAllErrors: true,\n    trace: false,\n\n    // agent-specific props\n    subSpaceId: '',\n    // purpose: '',\n    superSpaceId: '',\n    availableFunctionNameOrIds: [],\n    model: GEMINI_DEFAULT_MODEL_STR,\n    api: 'gemini',\n    type: AGENT_SPECIAL_IBGIB_TYPE_PRIMARYAGENT,\n    \"@currentContextTjpAddr\": ROOT_ADDR,\n}\n/**\n * don't init with an empty obj. use undefined or factory_v1.firstGen blows up.\n */\nexport const DEFAULT_AGENT_REL8NS_V1: AgentWitnessRel8ns_V1 | undefined = undefined;\n\n\n/**\n * @interface AgentWitnessData - Data interface for the AgentWitness.\n * @extends WitnessData_V1\n */\nexport interface AgentWitnessData_V1 extends WitnessData_V1 {\n    /**\n     * this id corresponds to what space the agent has access to as its own \"internal\" space.\n     *\n     * TODO: implement initialization code to create/get this space when the\n     * agent is created/initialized.\n     *\n     * TODO: implement an APIFunctionInfo for the agent\n     *\n     * it is possible that we will add access to other spaces in the future.\n     */\n    subSpaceId: SpaceId;\n    /**\n     * The space in which the agent's ibgib itself is saved. This is often\n     * (always?) different than the super space in which the agent itself\n     * resides.\n     */\n    superSpaceId: SpaceId;\n    /**\n     * nameOrId corresponding to the function info\n     */\n    availableFunctionNameOrIds: string[];\n    /**\n     * @see {@link AgentAPI}\n     */\n    api: AgentAPI;\n    /**\n     * @see {@link AgentModel}\n     */\n    model: AgentModel;\n    /**\n     * A more fine-grained discriminator.\n     */\n    type: string;\n    /**\n     * soft link to the current context ibgib. May be out of date, so should use\n     * get latest on the space (often can do this via metaspace with this\n     * agent's {@link superSpaceId}).\n     *\n     * This defaults to ib^gib (ROOT_ADDR), so if this is the value, then this\n     * has not been initialized yet and the agent needs to have their context\n     * set.\n     */\n    \"@currentContextTjpAddr\": IbGibAddr; // string\n}\n\n/**\n * @interface AgentWitnessRel8ns - Rel8ns interface for the AgentWitness.\n * @extends IbGibRel8ns_V1\n */\nexport interface AgentWitnessRel8ns_V1 extends WitnessRel8ns_V1 {\n    /**\n     * @property chat - Relationships to comment ibgibs representing chat\n     * history for this agent.\n     *\n     * These are expected to be comment ibgibs with special additional metadata\n     * text in the ib that pertains to the agents {@link AgentWitness_V1}.\n     *\n     * @see {@link system}\n     */\n    chat?: IbGibAddr[];\n    /**\n     * @property system - Relationships to comment ibgibs representing the\n     * system prompt.\n     *\n     * This is a Gemini-specific construct that I don't know if it exists in\n     * other APIs. But the intent is that these are comment ibgibs to be used in\n     * composing any meta text that is not part of a \"chat\" between one or more\n     * users and one or more models.\n     *\n     * These are expected to be comment ibgibs with special additional metadata\n     * text in the ib that pertains to the agents {@link AgentWitness_V1}.\n     *\n     * @see {@link system}\n     */\n    system?: IbGibAddr[];\n}\n\n/**\n * @interface AgentWitnessIbGib_V1 - Interface for an agent ibgib.\n *\n * @see {@link AgentWitness_V1}\n */\nexport interface AgentWitnessIbGib_V1 extends IbGib_V1<AgentWitnessData_V1, AgentWitnessRel8ns_V1> {\n}\n\nexport interface AddTextInfo {\n    /**\n     * @property text - raw comment text string to add\n     * @optional\n     */\n    text?: string;\n    /**\n     * @optional @property commentIbGib - existing comment to add\n     */\n    commentIbGib?: CommentIbGib_V1;\n    // textSrc: 'hardcoded' | 'human' | 'ai' | 'unknown';\n    textSrc: TextSource;\n    /**\n     * @property isSystem - If true, adds the text to the system prompt instead of chat history.\n     * @default false\n     */\n    isSystem?: boolean;\n}\n\n/**\n * @interface AddTextsOpts - Options for adding multiple text comments.\n */\nexport interface AddTextsOpts {\n    infos: AddTextInfo[];\n}\n\nexport interface PromptOneOffOpts {\n    text: string;\n    /**\n     * ad hoc system instructions for the one off call.\n     */\n    systemInstructions: string;\n    /**\n     * ad hoc model overrides for the one off call. If provided, these will be\n     * tried in order before the default model.\n     */\n    modelOverrides?: string[];\n    /**\n     * ad hoc model backup overrides for the one off call. If provided, these will be\n     * tried in order before the default backup model.\n     */\n    modelBackupOverrides?: string[];\n}\n\n/**\n * an agent can only have one active context at any time.\n *\n * Really this is a timeline, so the key thing of this context ibgib is its\n * temporal junction point (tjp).\n */\nexport interface SetActiveContextOpts {\n    contextIbGib: IbGib_V1;\n    /**\n     * for debug purposes\n     */\n    loggingInfo?: string;\n}\n\n/**\n * When composing the prompt to send to the model, this is the information that\n * we build up.\n */\nexport interface PromptInfo {\n    /**\n     * discriminator of what concrete info is contained in this object.\n     */\n    api: AgentAPI;\n}\n\n/**\n * @interface {@link PromptAPIResult} - shape of the result when calling into an\n * api-specific model. In general, the api will either return a string or a\n * function call request with optional arg(s)\n * @see {@link AgentWitness_V1.callTextAPI}\n */\nexport type PromptAPIResult = | PromptAPIResult_Gemini;\n\n/**\n * info object containing information in an agent ib schema.\n */\nexport interface AgentIbInfo {\n    /**\n     * should be {@link AGENT_ATOM}\n     */\n    atom: string,\n    name: string,\n    uuid: string,\n    type: string,\n}\n\n/**\n * information encoded in the addlMetadataText part of a comment ibgib that is\n * part of an agent's chat/system text.\n *\n * notes: long name...\n */\nexport interface AddlMetadataTextForAgentTextInfo {\n    /**\n     * @see {@link AddTextInfo.textSrc}\n     */\n    textSrc: TextSource;\n    timestampInTicks: number;\n    /**\n     * if there are additional underscore-delimited metadata texts, they will be here.\n     */\n    other?: string[];\n    errorMsg?: string;\n}\n\nexport type AgentModel =\n    | GeminiModel;\n/**\n * API discriminator of the underlying model.\n *\n * @see {@link AgentWitness_V1}\n * @see {@link AgentWitnessData_V1.api}\n */\nexport type AgentAPI = 'gemini';\n\n/**\n * shape of passed in arg of {@link createNewAgent}.\n *\n * ATOW (01/2024)\n*/\nexport interface CreateNewAgentArg {\n    /**\n     * metaspace singleton\n     */\n    metaspace: MetaspaceService;\n    /**\n     * optional space in which to save the agent itself (and dependency ibgibs).\n     * This is often (always?) different than\n     * @default superSpace is the metaspace's default local user space\n     */\n    superSpace?: IbGibSpaceAny;\n    /**\n     * optional name of new agent. Does not have to be unique, but that's always\n     * nice. if not provided, a random one will be created.\n     */\n    name?: string;\n    api: AgentAPI;\n    model: AgentModel;\n    /**\n     * what functions are available to the agent. if no functions are available\n     * to the agent, then provide an empty array.\n     * @see {@link AgentWitness_V1.getAvailableFunctions}\n     */\n    availableFunctions: APIFunctionInfo[];\n    initialSystemText: string;\n    /**\n     * initial text from the user to the agent.\n     */\n    initialChatText: string;\n    /**\n     * @see {@link AgentWitness_V1.fnGetAPIKey}\n     */\n    fnGetAPIKey: () => Promise<string>;\n    /**\n     * if true, will tag the agent with the agents tag in the {@link metaspace}\n     * and {@link superSpace}.\n     */\n    addToAgentsTag?: boolean;\n    /**\n     * will be used as the SpecialIbGibType\n     */\n    type: string;\n}\n\n/**\n * shape of return value of {@link createNewAgent}.\n *\n * ATOW (01/2025)\n */\nexport type CreateNewAgentResult = AgentWitnessAny;\n\n/**\n * factory to create concrete agents that correspond to a given {@link arg}.\n *\n * Specifically this is intended to look at the {@link CreateNewAgentArg.api}\n */\nexport interface CreateConcreteAgentWitnessFactory {\n    createInitialData(superSpace: IbGibSpaceAny): Promise<AgentWitnessData_V1>;\n    createInitialRel8ns(): Promise<AgentWitnessRel8ns_V1 | undefined>;\n    createWitness(): Promise<AgentWitnessAny>;\n}\n\nexport type AgentDtoToWitnessFunction =\n    (dto: IbGib_V1) => Promise<{ applies: boolean, agent?: AgentWitnessAny }>;\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {HttpOptions} from './types.js';\n\nlet _defaultBaseGeminiUrl: string | undefined = undefined;\nlet _defaultBaseVertexUrl: string | undefined = undefined;\n\n/**\n * Parameters for setting the base URLs for the Gemini API and Vertex AI API.\n */\nexport interface BaseUrlParameters {\n  geminiUrl?: string;\n  vertexUrl?: string;\n}\n\n/**\n * Overrides the base URLs for the Gemini API and Vertex AI API.\n *\n * @remarks This function should be called before initializing the SDK. If the\n * base URLs are set after initializing the SDK, the base URLs will not be\n * updated. Base URLs provided in the HttpOptions will also take precedence over\n * URLs set here.\n *\n * @example\n * ```ts\n * import {GoogleGenAI, setDefaultBaseUrls} from '@google/genai';\n * // Override the base URL for the Gemini API.\n * setDefaultBaseUrls({geminiUrl:'https://gemini.google.com'});\n *\n * // Override the base URL for the Vertex AI API.\n * setDefaultBaseUrls({vertexUrl: 'https://vertexai.googleapis.com'});\n *\n * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'});\n * ```\n */\nexport function setDefaultBaseUrls(baseUrlParams: BaseUrlParameters) {\n  _defaultBaseGeminiUrl = baseUrlParams.geminiUrl;\n  _defaultBaseVertexUrl = baseUrlParams.vertexUrl;\n}\n\n/**\n * Returns the default base URLs for the Gemini API and Vertex AI API.\n */\nexport function getDefaultBaseUrls(): BaseUrlParameters {\n  return {\n    geminiUrl: _defaultBaseGeminiUrl,\n    vertexUrl: _defaultBaseVertexUrl,\n  };\n}\n\n/**\n * Returns the default base URL based on the following priority:\n *   1. Base URLs set via HttpOptions.\n *   2. Base URLs set via the latest call to setDefaultBaseUrls.\n *   3. Base URLs set via environment variables.\n */\nexport function getBaseUrl(\n  httpOptions: HttpOptions | undefined,\n  vertexai: boolean | undefined,\n  vertexBaseUrlFromEnv: string | undefined,\n  geminiBaseUrlFromEnv: string | undefined,\n): string | undefined {\n  if (!httpOptions?.baseUrl) {\n    const defaultBaseUrls = getDefaultBaseUrls();\n    if (vertexai) {\n      return defaultBaseUrls.vertexUrl ?? vertexBaseUrlFromEnv;\n    } else {\n      return defaultBaseUrls.geminiUrl ?? geminiBaseUrlFromEnv;\n    }\n  }\n\n  return httpOptions.baseUrl;\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport class BaseModule {}\n\nexport function formatMap(\n  templateString: string,\n  valueMap: Record<string, unknown>,\n): string {\n  // Use a regular expression to find all placeholders in the template string\n  const regex = /\\{([^}]+)\\}/g;\n\n  // Replace each placeholder with its corresponding value from the valueMap\n  return templateString.replace(regex, (match, key) => {\n    if (Object.prototype.hasOwnProperty.call(valueMap, key)) {\n      const value = valueMap[key];\n      // Convert the value to a string if it's not a string already\n      return value !== undefined && value !== null ? String(value) : '';\n    } else {\n      // Handle missing keys\n      throw new Error(`Key '${key}' not found in valueMap.`);\n    }\n  });\n}\n\nexport function setValueByPath(\n  data: Record<string, unknown>,\n  keys: string[],\n  value: unknown,\n): void {\n  for (let i = 0; i < keys.length - 1; i++) {\n    const key = keys[i];\n\n    if (key.endsWith('[]')) {\n      const keyName = key.slice(0, -2);\n      if (!(keyName in data)) {\n        if (Array.isArray(value)) {\n          data[keyName] = Array.from({length: value.length}, () => ({}));\n        } else {\n          throw new Error(`Value must be a list given an array path ${key}`);\n        }\n      }\n\n      if (Array.isArray(data[keyName])) {\n        const arrayData = data[keyName] as Array<unknown>;\n\n        if (Array.isArray(value)) {\n          for (let j = 0; j < arrayData.length; j++) {\n            const entry = arrayData[j] as Record<string, unknown>;\n            setValueByPath(entry, keys.slice(i + 1), value[j]);\n          }\n        } else {\n          for (const d of arrayData) {\n            setValueByPath(\n              d as Record<string, unknown>,\n              keys.slice(i + 1),\n              value,\n            );\n          }\n        }\n      }\n      return;\n    } else if (key.endsWith('[0]')) {\n      const keyName = key.slice(0, -3);\n      if (!(keyName in data)) {\n        data[keyName] = [{}];\n      }\n      const arrayData = (data as Record<string, unknown>)[keyName];\n      setValueByPath(\n        (arrayData as Array<Record<string, unknown>>)[0],\n        keys.slice(i + 1),\n        value,\n      );\n      return;\n    }\n\n    if (!data[key] || typeof data[key] !== 'object') {\n      data[key] = {};\n    }\n\n    data = data[key] as Record<string, unknown>;\n  }\n\n  const keyToSet = keys[keys.length - 1];\n  const existingData = data[keyToSet];\n\n  if (existingData !== undefined) {\n    if (\n      !value ||\n      (typeof value === 'object' && Object.keys(value).length === 0)\n    ) {\n      return;\n    }\n\n    if (value === existingData) {\n      return;\n    }\n\n    if (\n      typeof existingData === 'object' &&\n      typeof value === 'object' &&\n      existingData !== null &&\n      value !== null\n    ) {\n      Object.assign(existingData, value);\n    } else {\n      throw new Error(`Cannot set value for an existing key. Key: ${keyToSet}`);\n    }\n  } else {\n    if (\n      keyToSet === '_self' &&\n      typeof value === 'object' &&\n      value !== null &&\n      !Array.isArray(value)\n    ) {\n      const valueAsRecord = value as Record<string, unknown>;\n\n      Object.assign(data, valueAsRecord);\n    } else {\n      data[keyToSet] = value;\n    }\n  }\n}\n\nexport function getValueByPath(\n  data: unknown,\n  keys: string[],\n  defaultValue: unknown = undefined,\n): unknown {\n  try {\n    if (keys.length === 1 && keys[0] === '_self') {\n      return data;\n    }\n\n    for (let i = 0; i < keys.length; i++) {\n      if (typeof data !== 'object' || data === null) {\n        return defaultValue;\n      }\n\n      const key = keys[i];\n      if (key.endsWith('[]')) {\n        const keyName = key.slice(0, -2);\n        if (keyName in data) {\n          const arrayData = (data as Record<string, unknown>)[keyName];\n          if (!Array.isArray(arrayData)) {\n            return defaultValue;\n          }\n          return arrayData.map((d) =>\n            getValueByPath(d, keys.slice(i + 1), defaultValue),\n          );\n        } else {\n          return defaultValue;\n        }\n      } else {\n        data = (data as Record<string, unknown>)[key];\n      }\n    }\n\n    return data;\n  } catch (error) {\n    if (error instanceof TypeError) {\n      return defaultValue;\n    }\n    throw error;\n  }\n}\n\n/**\n * Moves values from source paths to destination paths.\n *\n * Examples:\n *   moveValueByPath(\n *     {'requests': [{'content': v1}, {'content': v2}]},\n *     {'requests[].*': 'requests[].request.*'}\n *   )\n *     -> {'requests': [{'request': {'content': v1}}, {'request': {'content': v2}}]}\n */\nexport function moveValueByPath(\n  data: unknown,\n  paths: Record<string, string>,\n): void {\n  for (const [sourcePath, destPath] of Object.entries(paths)) {\n    const sourceKeys = sourcePath.split('.');\n    const destKeys = destPath.split('.');\n\n    // Determine keys to exclude from wildcard to avoid cyclic references\n    const excludeKeys = new Set<string>();\n    let wildcardIdx = -1;\n    for (let i = 0; i < sourceKeys.length; i++) {\n      if (sourceKeys[i] === '*') {\n        wildcardIdx = i;\n        break;\n      }\n    }\n\n    if (wildcardIdx !== -1 && destKeys.length > wildcardIdx) {\n      // Extract the intermediate key between source and dest paths\n      // Example: source=['requests[]', '*'], dest=['requests[]', 'request', '*']\n      // We want to exclude 'request'\n      for (let i = wildcardIdx; i < destKeys.length; i++) {\n        const key = destKeys[i];\n        if (key !== '*' && !key.endsWith('[]') && !key.endsWith('[0]')) {\n          excludeKeys.add(key);\n        }\n      }\n    }\n\n    _moveValueRecursive(data, sourceKeys, destKeys, 0, excludeKeys);\n  }\n}\n\n/**\n * Recursively moves values from source path to destination path.\n */\nfunction _moveValueRecursive(\n  data: unknown,\n  sourceKeys: string[],\n  destKeys: string[],\n  keyIdx: number,\n  excludeKeys: Set<string>,\n): void {\n  if (keyIdx >= sourceKeys.length) {\n    return;\n  }\n\n  if (typeof data !== 'object' || data === null) {\n    return;\n  }\n\n  const key = sourceKeys[keyIdx];\n\n  if (key.endsWith('[]')) {\n    const keyName = key.slice(0, -2);\n    const dataRecord = data as Record<string, unknown>;\n    if (keyName in dataRecord && Array.isArray(dataRecord[keyName])) {\n      for (const item of dataRecord[keyName] as Array<unknown>) {\n        _moveValueRecursive(\n          item,\n          sourceKeys,\n          destKeys,\n          keyIdx + 1,\n          excludeKeys,\n        );\n      }\n    }\n  } else if (key === '*') {\n    // wildcard - move all fields\n    if (typeof data === 'object' && data !== null && !Array.isArray(data)) {\n      const dataRecord = data as Record<string, unknown>;\n      const keysToMove = Object.keys(dataRecord).filter(\n        (k) => !k.startsWith('_') && !excludeKeys.has(k),\n      );\n\n      const valuesToMove: Record<string, unknown> = {};\n      for (const k of keysToMove) {\n        valuesToMove[k] = dataRecord[k];\n      }\n\n      // Set values at destination\n      for (const [k, v] of Object.entries(valuesToMove)) {\n        const newDestKeys: string[] = [];\n        for (const dk of destKeys.slice(keyIdx)) {\n          if (dk === '*') {\n            newDestKeys.push(k);\n          } else {\n            newDestKeys.push(dk);\n          }\n        }\n        setValueByPath(dataRecord, newDestKeys, v);\n      }\n\n      for (const k of keysToMove) {\n        delete dataRecord[k];\n      }\n    }\n  } else {\n    // Navigate to next level\n    const dataRecord = data as Record<string, unknown>;\n    if (key in dataRecord) {\n      _moveValueRecursive(\n        dataRecord[key],\n        sourceKeys,\n        destKeys,\n        keyIdx + 1,\n        excludeKeys,\n      );\n    }\n  }\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport function tBytes(fromBytes: string | unknown): string {\n  if (typeof fromBytes !== 'string') {\n    throw new Error('fromImageBytes must be a string');\n  }\n  // TODO(b/389133914): Remove dummy bytes converter.\n  return fromBytes;\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport * as t from '../_base_transformers.js';\nimport * as common from '../_common.js';\nimport type * as types from '../types.js';\n\nexport function fetchPredictOperationParametersToMldev(\n  fromObject: types.FetchPredictOperationParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  if (common.getValueByPath(fromObject, ['operationName']) !== undefined) {\n    throw new Error('operationName parameter is not supported in Gemini API.');\n  }\n\n  if (common.getValueByPath(fromObject, ['resourceName']) !== undefined) {\n    throw new Error('resourceName parameter is not supported in Gemini API.');\n  }\n\n  if (common.getValueByPath(fromObject, ['config']) !== undefined) {\n    throw new Error('config parameter is not supported in Gemini API.');\n  }\n\n  return toObject;\n}\n\nexport function fetchPredictOperationParametersToVertex(\n  fromObject: types.FetchPredictOperationParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromOperationName = common.getValueByPath(fromObject, [\n    'operationName',\n  ]);\n  if (fromOperationName != null) {\n    common.setValueByPath(toObject, ['operationName'], fromOperationName);\n  }\n\n  const fromResourceName = common.getValueByPath(fromObject, ['resourceName']);\n  if (fromResourceName != null) {\n    common.setValueByPath(toObject, ['_url', 'resourceName'], fromResourceName);\n  }\n\n  return toObject;\n}\n\nexport function generateVideosOperationFromMldev(\n  fromObject: types.GenerateVideosOperation,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromName = common.getValueByPath(fromObject, ['name']);\n  if (fromName != null) {\n    common.setValueByPath(toObject, ['name'], fromName);\n  }\n\n  const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n  if (fromMetadata != null) {\n    common.setValueByPath(toObject, ['metadata'], fromMetadata);\n  }\n\n  const fromDone = common.getValueByPath(fromObject, ['done']);\n  if (fromDone != null) {\n    common.setValueByPath(toObject, ['done'], fromDone);\n  }\n\n  const fromError = common.getValueByPath(fromObject, ['error']);\n  if (fromError != null) {\n    common.setValueByPath(toObject, ['error'], fromError);\n  }\n\n  const fromResponse = common.getValueByPath(fromObject, [\n    'response',\n    'generateVideoResponse',\n  ]);\n  if (fromResponse != null) {\n    common.setValueByPath(\n      toObject,\n      ['response'],\n      generateVideosResponseFromMldev(fromResponse),\n    );\n  }\n\n  return toObject;\n}\n\nexport function generateVideosOperationFromVertex(\n  fromObject: types.GenerateVideosOperation,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromName = common.getValueByPath(fromObject, ['name']);\n  if (fromName != null) {\n    common.setValueByPath(toObject, ['name'], fromName);\n  }\n\n  const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n  if (fromMetadata != null) {\n    common.setValueByPath(toObject, ['metadata'], fromMetadata);\n  }\n\n  const fromDone = common.getValueByPath(fromObject, ['done']);\n  if (fromDone != null) {\n    common.setValueByPath(toObject, ['done'], fromDone);\n  }\n\n  const fromError = common.getValueByPath(fromObject, ['error']);\n  if (fromError != null) {\n    common.setValueByPath(toObject, ['error'], fromError);\n  }\n\n  const fromResponse = common.getValueByPath(fromObject, ['response']);\n  if (fromResponse != null) {\n    common.setValueByPath(\n      toObject,\n      ['response'],\n      generateVideosResponseFromVertex(fromResponse),\n    );\n  }\n\n  return toObject;\n}\n\nexport function generateVideosResponseFromMldev(\n  fromObject: types.GenerateVideosResponse,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromGeneratedVideos = common.getValueByPath(fromObject, [\n    'generatedSamples',\n  ]);\n  if (fromGeneratedVideos != null) {\n    let transformedList = fromGeneratedVideos;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return generatedVideoFromMldev(item);\n      });\n    }\n    common.setValueByPath(toObject, ['generatedVideos'], transformedList);\n  }\n\n  const fromRaiMediaFilteredCount = common.getValueByPath(fromObject, [\n    'raiMediaFilteredCount',\n  ]);\n  if (fromRaiMediaFilteredCount != null) {\n    common.setValueByPath(\n      toObject,\n      ['raiMediaFilteredCount'],\n      fromRaiMediaFilteredCount,\n    );\n  }\n\n  const fromRaiMediaFilteredReasons = common.getValueByPath(fromObject, [\n    'raiMediaFilteredReasons',\n  ]);\n  if (fromRaiMediaFilteredReasons != null) {\n    common.setValueByPath(\n      toObject,\n      ['raiMediaFilteredReasons'],\n      fromRaiMediaFilteredReasons,\n    );\n  }\n\n  return toObject;\n}\n\nexport function generateVideosResponseFromVertex(\n  fromObject: types.GenerateVideosResponse,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromGeneratedVideos = common.getValueByPath(fromObject, ['videos']);\n  if (fromGeneratedVideos != null) {\n    let transformedList = fromGeneratedVideos;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return generatedVideoFromVertex(item);\n      });\n    }\n    common.setValueByPath(toObject, ['generatedVideos'], transformedList);\n  }\n\n  const fromRaiMediaFilteredCount = common.getValueByPath(fromObject, [\n    'raiMediaFilteredCount',\n  ]);\n  if (fromRaiMediaFilteredCount != null) {\n    common.setValueByPath(\n      toObject,\n      ['raiMediaFilteredCount'],\n      fromRaiMediaFilteredCount,\n    );\n  }\n\n  const fromRaiMediaFilteredReasons = common.getValueByPath(fromObject, [\n    'raiMediaFilteredReasons',\n  ]);\n  if (fromRaiMediaFilteredReasons != null) {\n    common.setValueByPath(\n      toObject,\n      ['raiMediaFilteredReasons'],\n      fromRaiMediaFilteredReasons,\n    );\n  }\n\n  return toObject;\n}\n\nexport function generatedVideoFromMldev(\n  fromObject: types.GeneratedVideo,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromVideo = common.getValueByPath(fromObject, ['video']);\n  if (fromVideo != null) {\n    common.setValueByPath(toObject, ['video'], videoFromMldev(fromVideo));\n  }\n\n  return toObject;\n}\n\nexport function generatedVideoFromVertex(\n  fromObject: types.GeneratedVideo,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromVideo = common.getValueByPath(fromObject, ['_self']);\n  if (fromVideo != null) {\n    common.setValueByPath(toObject, ['video'], videoFromVertex(fromVideo));\n  }\n\n  return toObject;\n}\n\nexport function getOperationParametersToMldev(\n  fromObject: types.GetOperationParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromOperationName = common.getValueByPath(fromObject, [\n    'operationName',\n  ]);\n  if (fromOperationName != null) {\n    common.setValueByPath(\n      toObject,\n      ['_url', 'operationName'],\n      fromOperationName,\n    );\n  }\n\n  return toObject;\n}\n\nexport function getOperationParametersToVertex(\n  fromObject: types.GetOperationParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromOperationName = common.getValueByPath(fromObject, [\n    'operationName',\n  ]);\n  if (fromOperationName != null) {\n    common.setValueByPath(\n      toObject,\n      ['_url', 'operationName'],\n      fromOperationName,\n    );\n  }\n\n  return toObject;\n}\n\nexport function importFileOperationFromMldev(\n  fromObject: types.ImportFileOperation,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromName = common.getValueByPath(fromObject, ['name']);\n  if (fromName != null) {\n    common.setValueByPath(toObject, ['name'], fromName);\n  }\n\n  const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n  if (fromMetadata != null) {\n    common.setValueByPath(toObject, ['metadata'], fromMetadata);\n  }\n\n  const fromDone = common.getValueByPath(fromObject, ['done']);\n  if (fromDone != null) {\n    common.setValueByPath(toObject, ['done'], fromDone);\n  }\n\n  const fromError = common.getValueByPath(fromObject, ['error']);\n  if (fromError != null) {\n    common.setValueByPath(toObject, ['error'], fromError);\n  }\n\n  const fromResponse = common.getValueByPath(fromObject, ['response']);\n  if (fromResponse != null) {\n    common.setValueByPath(\n      toObject,\n      ['response'],\n      importFileResponseFromMldev(fromResponse),\n    );\n  }\n\n  return toObject;\n}\n\nexport function importFileResponseFromMldev(\n  fromObject: types.ImportFileResponse,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n    'sdkHttpResponse',\n  ]);\n  if (fromSdkHttpResponse != null) {\n    common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n  }\n\n  const fromParent = common.getValueByPath(fromObject, ['parent']);\n  if (fromParent != null) {\n    common.setValueByPath(toObject, ['parent'], fromParent);\n  }\n\n  const fromDocumentName = common.getValueByPath(fromObject, ['documentName']);\n  if (fromDocumentName != null) {\n    common.setValueByPath(toObject, ['documentName'], fromDocumentName);\n  }\n\n  return toObject;\n}\n\nexport function uploadToFileSearchStoreOperationFromMldev(\n  fromObject: types.UploadToFileSearchStoreOperation,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromName = common.getValueByPath(fromObject, ['name']);\n  if (fromName != null) {\n    common.setValueByPath(toObject, ['name'], fromName);\n  }\n\n  const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n  if (fromMetadata != null) {\n    common.setValueByPath(toObject, ['metadata'], fromMetadata);\n  }\n\n  const fromDone = common.getValueByPath(fromObject, ['done']);\n  if (fromDone != null) {\n    common.setValueByPath(toObject, ['done'], fromDone);\n  }\n\n  const fromError = common.getValueByPath(fromObject, ['error']);\n  if (fromError != null) {\n    common.setValueByPath(toObject, ['error'], fromError);\n  }\n\n  const fromResponse = common.getValueByPath(fromObject, ['response']);\n  if (fromResponse != null) {\n    common.setValueByPath(\n      toObject,\n      ['response'],\n      uploadToFileSearchStoreResponseFromMldev(fromResponse),\n    );\n  }\n\n  return toObject;\n}\n\nexport function uploadToFileSearchStoreResponseFromMldev(\n  fromObject: types.UploadToFileSearchStoreResponse,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n    'sdkHttpResponse',\n  ]);\n  if (fromSdkHttpResponse != null) {\n    common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n  }\n\n  const fromParent = common.getValueByPath(fromObject, ['parent']);\n  if (fromParent != null) {\n    common.setValueByPath(toObject, ['parent'], fromParent);\n  }\n\n  const fromDocumentName = common.getValueByPath(fromObject, ['documentName']);\n  if (fromDocumentName != null) {\n    common.setValueByPath(toObject, ['documentName'], fromDocumentName);\n  }\n\n  return toObject;\n}\n\nexport function videoFromMldev(\n  fromObject: types.Video,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromUri = common.getValueByPath(fromObject, ['uri']);\n  if (fromUri != null) {\n    common.setValueByPath(toObject, ['uri'], fromUri);\n  }\n\n  const fromVideoBytes = common.getValueByPath(fromObject, ['encodedVideo']);\n  if (fromVideoBytes != null) {\n    common.setValueByPath(toObject, ['videoBytes'], t.tBytes(fromVideoBytes));\n  }\n\n  const fromMimeType = common.getValueByPath(fromObject, ['encoding']);\n  if (fromMimeType != null) {\n    common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n  }\n\n  return toObject;\n}\n\nexport function videoFromVertex(\n  fromObject: types.Video,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromUri = common.getValueByPath(fromObject, ['gcsUri']);\n  if (fromUri != null) {\n    common.setValueByPath(toObject, ['uri'], fromUri);\n  }\n\n  const fromVideoBytes = common.getValueByPath(fromObject, [\n    'bytesBase64Encoded',\n  ]);\n  if (fromVideoBytes != null) {\n    common.setValueByPath(toObject, ['videoBytes'], t.tBytes(fromVideoBytes));\n  }\n\n  const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n  if (fromMimeType != null) {\n    common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n  }\n\n  return toObject;\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport type {ReferenceImageAPIInternal} from './_internal_types.js';\nimport {\n  generateVideosOperationFromMldev,\n  generateVideosOperationFromVertex,\n  importFileOperationFromMldev,\n  uploadToFileSearchStoreOperationFromMldev,\n} from './converters/_operations_converters.js';\n\n/** Outcome of the code execution. */\nexport enum Outcome {\n  /**\n   * Unspecified status. This value should not be used.\n   */\n  OUTCOME_UNSPECIFIED = 'OUTCOME_UNSPECIFIED',\n  /**\n   * Code execution completed successfully.\n   */\n  OUTCOME_OK = 'OUTCOME_OK',\n  /**\n   * Code execution finished but with a failure. `stderr` should contain the reason.\n   */\n  OUTCOME_FAILED = 'OUTCOME_FAILED',\n  /**\n   * Code execution ran for too long, and was cancelled. There may or may not be a partial output present.\n   */\n  OUTCOME_DEADLINE_EXCEEDED = 'OUTCOME_DEADLINE_EXCEEDED',\n}\n\n/** Programming language of the `code`. */\nexport enum Language {\n  /**\n   * Unspecified language. This value should not be used.\n   */\n  LANGUAGE_UNSPECIFIED = 'LANGUAGE_UNSPECIFIED',\n  /**\n   * Python >= 3.10, with numpy and simpy available.\n   */\n  PYTHON = 'PYTHON',\n}\n\n/** Specifies how the response should be scheduled in the conversation. */\nexport enum FunctionResponseScheduling {\n  /**\n   * This value is unused.\n   */\n  SCHEDULING_UNSPECIFIED = 'SCHEDULING_UNSPECIFIED',\n  /**\n   * Only add the result to the conversation context, do not interrupt or trigger generation.\n   */\n  SILENT = 'SILENT',\n  /**\n   * Add the result to the conversation context, and prompt to generate output without interrupting ongoing generation.\n   */\n  WHEN_IDLE = 'WHEN_IDLE',\n  /**\n   * Add the result to the conversation context, interrupt ongoing generation and prompt to generate output.\n   */\n  INTERRUPT = 'INTERRUPT',\n}\n\n/** The type of the data. */\nexport enum Type {\n  /**\n   * Not specified, should not be used.\n   */\n  TYPE_UNSPECIFIED = 'TYPE_UNSPECIFIED',\n  /**\n   * OpenAPI string type\n   */\n  STRING = 'STRING',\n  /**\n   * OpenAPI number type\n   */\n  NUMBER = 'NUMBER',\n  /**\n   * OpenAPI integer type\n   */\n  INTEGER = 'INTEGER',\n  /**\n   * OpenAPI boolean type\n   */\n  BOOLEAN = 'BOOLEAN',\n  /**\n   * OpenAPI array type\n   */\n  ARRAY = 'ARRAY',\n  /**\n   * OpenAPI object type\n   */\n  OBJECT = 'OBJECT',\n  /**\n   * Null type\n   */\n  NULL = 'NULL',\n}\n\n/** The mode of the predictor to be used in dynamic retrieval. */\nexport enum Mode {\n  /**\n   * Always trigger retrieval.\n   */\n  MODE_UNSPECIFIED = 'MODE_UNSPECIFIED',\n  /**\n   * Run retrieval only when system decides it is necessary.\n   */\n  MODE_DYNAMIC = 'MODE_DYNAMIC',\n}\n\n/** The API spec that the external API implements. This enum is not supported in Gemini API. */\nexport enum ApiSpec {\n  /**\n   * Unspecified API spec. This value should not be used.\n   */\n  API_SPEC_UNSPECIFIED = 'API_SPEC_UNSPECIFIED',\n  /**\n   * Simple search API spec.\n   */\n  SIMPLE_SEARCH = 'SIMPLE_SEARCH',\n  /**\n   * Elastic search API spec.\n   */\n  ELASTIC_SEARCH = 'ELASTIC_SEARCH',\n}\n\n/** Type of auth scheme. This enum is not supported in Gemini API. */\nexport enum AuthType {\n  AUTH_TYPE_UNSPECIFIED = 'AUTH_TYPE_UNSPECIFIED',\n  /**\n   * No Auth.\n   */\n  NO_AUTH = 'NO_AUTH',\n  /**\n   * API Key Auth.\n   */\n  API_KEY_AUTH = 'API_KEY_AUTH',\n  /**\n   * HTTP Basic Auth.\n   */\n  HTTP_BASIC_AUTH = 'HTTP_BASIC_AUTH',\n  /**\n   * Google Service Account Auth.\n   */\n  GOOGLE_SERVICE_ACCOUNT_AUTH = 'GOOGLE_SERVICE_ACCOUNT_AUTH',\n  /**\n   * OAuth auth.\n   */\n  OAUTH = 'OAUTH',\n  /**\n   * OpenID Connect (OIDC) Auth.\n   */\n  OIDC_AUTH = 'OIDC_AUTH',\n}\n\n/** The location of the API key. This enum is not supported in Gemini API. */\nexport enum HttpElementLocation {\n  HTTP_IN_UNSPECIFIED = 'HTTP_IN_UNSPECIFIED',\n  /**\n   * Element is in the HTTP request query.\n   */\n  HTTP_IN_QUERY = 'HTTP_IN_QUERY',\n  /**\n   * Element is in the HTTP request header.\n   */\n  HTTP_IN_HEADER = 'HTTP_IN_HEADER',\n  /**\n   * Element is in the HTTP request path.\n   */\n  HTTP_IN_PATH = 'HTTP_IN_PATH',\n  /**\n   * Element is in the HTTP request body.\n   */\n  HTTP_IN_BODY = 'HTTP_IN_BODY',\n  /**\n   * Element is in the HTTP request cookie.\n   */\n  HTTP_IN_COOKIE = 'HTTP_IN_COOKIE',\n}\n\n/** Sites with confidence level chosen & above this value will be blocked from the search results. This enum is not supported in Gemini API. */\nexport enum PhishBlockThreshold {\n  /**\n   * Defaults to unspecified.\n   */\n  PHISH_BLOCK_THRESHOLD_UNSPECIFIED = 'PHISH_BLOCK_THRESHOLD_UNSPECIFIED',\n  /**\n   * Blocks Low and above confidence URL that is risky.\n   */\n  BLOCK_LOW_AND_ABOVE = 'BLOCK_LOW_AND_ABOVE',\n  /**\n   * Blocks Medium and above confidence URL that is risky.\n   */\n  BLOCK_MEDIUM_AND_ABOVE = 'BLOCK_MEDIUM_AND_ABOVE',\n  /**\n   * Blocks High and above confidence URL that is risky.\n   */\n  BLOCK_HIGH_AND_ABOVE = 'BLOCK_HIGH_AND_ABOVE',\n  /**\n   * Blocks Higher and above confidence URL that is risky.\n   */\n  BLOCK_HIGHER_AND_ABOVE = 'BLOCK_HIGHER_AND_ABOVE',\n  /**\n   * Blocks Very high and above confidence URL that is risky.\n   */\n  BLOCK_VERY_HIGH_AND_ABOVE = 'BLOCK_VERY_HIGH_AND_ABOVE',\n  /**\n   * Blocks Extremely high confidence URL that is risky.\n   */\n  BLOCK_ONLY_EXTREMELY_HIGH = 'BLOCK_ONLY_EXTREMELY_HIGH',\n}\n\n/** The level of thoughts tokens that the model should generate. */\nexport enum ThinkingLevel {\n  /**\n   * Default value.\n   */\n  THINKING_LEVEL_UNSPECIFIED = 'THINKING_LEVEL_UNSPECIFIED',\n  /**\n   * Low thinking level.\n   */\n  LOW = 'LOW',\n  /**\n   * High thinking level.\n   */\n  HIGH = 'HIGH',\n}\n\n/** Harm category. */\nexport enum HarmCategory {\n  /**\n   * The harm category is unspecified.\n   */\n  HARM_CATEGORY_UNSPECIFIED = 'HARM_CATEGORY_UNSPECIFIED',\n  /**\n   * The harm category is harassment.\n   */\n  HARM_CATEGORY_HARASSMENT = 'HARM_CATEGORY_HARASSMENT',\n  /**\n   * The harm category is hate speech.\n   */\n  HARM_CATEGORY_HATE_SPEECH = 'HARM_CATEGORY_HATE_SPEECH',\n  /**\n   * The harm category is sexually explicit content.\n   */\n  HARM_CATEGORY_SEXUALLY_EXPLICIT = 'HARM_CATEGORY_SEXUALLY_EXPLICIT',\n  /**\n   * The harm category is dangerous content.\n   */\n  HARM_CATEGORY_DANGEROUS_CONTENT = 'HARM_CATEGORY_DANGEROUS_CONTENT',\n  /**\n   * Deprecated: Election filter is not longer supported. The harm category is civic integrity.\n   */\n  HARM_CATEGORY_CIVIC_INTEGRITY = 'HARM_CATEGORY_CIVIC_INTEGRITY',\n  /**\n   * The harm category is image hate. This enum value is not supported in Gemini API.\n   */\n  HARM_CATEGORY_IMAGE_HATE = 'HARM_CATEGORY_IMAGE_HATE',\n  /**\n   * The harm category is image dangerous content. This enum value is not supported in Gemini API.\n   */\n  HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT = 'HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT',\n  /**\n   * The harm category is image harassment. This enum value is not supported in Gemini API.\n   */\n  HARM_CATEGORY_IMAGE_HARASSMENT = 'HARM_CATEGORY_IMAGE_HARASSMENT',\n  /**\n   * The harm category is image sexually explicit content. This enum value is not supported in Gemini API.\n   */\n  HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT = 'HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT',\n  /**\n   * The harm category is for jailbreak prompts. This enum value is not supported in Gemini API.\n   */\n  HARM_CATEGORY_JAILBREAK = 'HARM_CATEGORY_JAILBREAK',\n}\n\n/** Specify if the threshold is used for probability or severity score. If not specified, the threshold is used for probability score. This enum is not supported in Gemini API. */\nexport enum HarmBlockMethod {\n  /**\n   * The harm block method is unspecified.\n   */\n  HARM_BLOCK_METHOD_UNSPECIFIED = 'HARM_BLOCK_METHOD_UNSPECIFIED',\n  /**\n   * The harm block method uses both probability and severity scores.\n   */\n  SEVERITY = 'SEVERITY',\n  /**\n   * The harm block method uses the probability score.\n   */\n  PROBABILITY = 'PROBABILITY',\n}\n\n/** The harm block threshold. */\nexport enum HarmBlockThreshold {\n  /**\n   * Unspecified harm block threshold.\n   */\n  HARM_BLOCK_THRESHOLD_UNSPECIFIED = 'HARM_BLOCK_THRESHOLD_UNSPECIFIED',\n  /**\n   * Block low threshold and above (i.e. block more).\n   */\n  BLOCK_LOW_AND_ABOVE = 'BLOCK_LOW_AND_ABOVE',\n  /**\n   * Block medium threshold and above.\n   */\n  BLOCK_MEDIUM_AND_ABOVE = 'BLOCK_MEDIUM_AND_ABOVE',\n  /**\n   * Block only high threshold (i.e. block less).\n   */\n  BLOCK_ONLY_HIGH = 'BLOCK_ONLY_HIGH',\n  /**\n   * Block none.\n   */\n  BLOCK_NONE = 'BLOCK_NONE',\n  /**\n   * Turn off the safety filter.\n   */\n  OFF = 'OFF',\n}\n\n/** Output only. The reason why the model stopped generating tokens.\n\nIf empty, the model has not stopped generating the tokens. */\nexport enum FinishReason {\n  /**\n   * The finish reason is unspecified.\n   */\n  FINISH_REASON_UNSPECIFIED = 'FINISH_REASON_UNSPECIFIED',\n  /**\n   * Token generation reached a natural stopping point or a configured stop sequence.\n   */\n  STOP = 'STOP',\n  /**\n   * Token generation reached the configured maximum output tokens.\n   */\n  MAX_TOKENS = 'MAX_TOKENS',\n  /**\n   * Token generation stopped because the content potentially contains safety violations. NOTE: When streaming, [content][] is empty if content filters blocks the output.\n   */\n  SAFETY = 'SAFETY',\n  /**\n   * The token generation stopped because of potential recitation.\n   */\n  RECITATION = 'RECITATION',\n  /**\n   * The token generation stopped because of using an unsupported language.\n   */\n  LANGUAGE = 'LANGUAGE',\n  /**\n   * All other reasons that stopped the token generation.\n   */\n  OTHER = 'OTHER',\n  /**\n   * Token generation stopped because the content contains forbidden terms.\n   */\n  BLOCKLIST = 'BLOCKLIST',\n  /**\n   * Token generation stopped for potentially containing prohibited content.\n   */\n  PROHIBITED_CONTENT = 'PROHIBITED_CONTENT',\n  /**\n   * Token generation stopped because the content potentially contains Sensitive Personally Identifiable Information (SPII).\n   */\n  SPII = 'SPII',\n  /**\n   * The function call generated by the model is invalid.\n   */\n  MALFORMED_FUNCTION_CALL = 'MALFORMED_FUNCTION_CALL',\n  /**\n   * Token generation stopped because generated images have safety violations.\n   */\n  IMAGE_SAFETY = 'IMAGE_SAFETY',\n  /**\n   * The tool call generated by the model is invalid.\n   */\n  UNEXPECTED_TOOL_CALL = 'UNEXPECTED_TOOL_CALL',\n  /**\n   * Image generation stopped because the generated images have prohibited content.\n   */\n  IMAGE_PROHIBITED_CONTENT = 'IMAGE_PROHIBITED_CONTENT',\n  /**\n   * The model was expected to generate an image, but none was generated.\n   */\n  NO_IMAGE = 'NO_IMAGE',\n  /**\n   * Image generation stopped because the generated image may be a recitation from a source.\n   */\n  IMAGE_RECITATION = 'IMAGE_RECITATION',\n  /**\n   * Image generation stopped for a reason not otherwise specified.\n   */\n  IMAGE_OTHER = 'IMAGE_OTHER',\n}\n\n/** Output only. Harm probability levels in the content. */\nexport enum HarmProbability {\n  /**\n   * Harm probability unspecified.\n   */\n  HARM_PROBABILITY_UNSPECIFIED = 'HARM_PROBABILITY_UNSPECIFIED',\n  /**\n   * Negligible level of harm.\n   */\n  NEGLIGIBLE = 'NEGLIGIBLE',\n  /**\n   * Low level of harm.\n   */\n  LOW = 'LOW',\n  /**\n   * Medium level of harm.\n   */\n  MEDIUM = 'MEDIUM',\n  /**\n   * High level of harm.\n   */\n  HIGH = 'HIGH',\n}\n\n/** Output only. Harm severity levels in the content. This enum is not supported in Gemini API. */\nexport enum HarmSeverity {\n  /**\n   * Harm severity unspecified.\n   */\n  HARM_SEVERITY_UNSPECIFIED = 'HARM_SEVERITY_UNSPECIFIED',\n  /**\n   * Negligible level of harm severity.\n   */\n  HARM_SEVERITY_NEGLIGIBLE = 'HARM_SEVERITY_NEGLIGIBLE',\n  /**\n   * Low level of harm severity.\n   */\n  HARM_SEVERITY_LOW = 'HARM_SEVERITY_LOW',\n  /**\n   * Medium level of harm severity.\n   */\n  HARM_SEVERITY_MEDIUM = 'HARM_SEVERITY_MEDIUM',\n  /**\n   * High level of harm severity.\n   */\n  HARM_SEVERITY_HIGH = 'HARM_SEVERITY_HIGH',\n}\n\n/** Status of the url retrieval. */\nexport enum UrlRetrievalStatus {\n  /**\n   * Default value. This value is unused.\n   */\n  URL_RETRIEVAL_STATUS_UNSPECIFIED = 'URL_RETRIEVAL_STATUS_UNSPECIFIED',\n  /**\n   * Url retrieval is successful.\n   */\n  URL_RETRIEVAL_STATUS_SUCCESS = 'URL_RETRIEVAL_STATUS_SUCCESS',\n  /**\n   * Url retrieval is failed due to error.\n   */\n  URL_RETRIEVAL_STATUS_ERROR = 'URL_RETRIEVAL_STATUS_ERROR',\n  /**\n   * Url retrieval is failed because the content is behind paywall. This enum value is not supported in Vertex AI.\n   */\n  URL_RETRIEVAL_STATUS_PAYWALL = 'URL_RETRIEVAL_STATUS_PAYWALL',\n  /**\n   * Url retrieval is failed because the content is unsafe. This enum value is not supported in Vertex AI.\n   */\n  URL_RETRIEVAL_STATUS_UNSAFE = 'URL_RETRIEVAL_STATUS_UNSAFE',\n}\n\n/** Output only. The reason why the prompt was blocked. */\nexport enum BlockedReason {\n  /**\n   * The blocked reason is unspecified.\n   */\n  BLOCKED_REASON_UNSPECIFIED = 'BLOCKED_REASON_UNSPECIFIED',\n  /**\n   * The prompt was blocked for safety reasons.\n   */\n  SAFETY = 'SAFETY',\n  /**\n   * The prompt was blocked for other reasons. For example, it may be due to the prompt's language, or because it contains other harmful content.\n   */\n  OTHER = 'OTHER',\n  /**\n   * The prompt was blocked because it contains a term from the terminology blocklist.\n   */\n  BLOCKLIST = 'BLOCKLIST',\n  /**\n   * The prompt was blocked because it contains prohibited content.\n   */\n  PROHIBITED_CONTENT = 'PROHIBITED_CONTENT',\n  /**\n   * The prompt was blocked because it contains content that is unsafe for image generation.\n   */\n  IMAGE_SAFETY = 'IMAGE_SAFETY',\n  /**\n   * The prompt was blocked by Model Armor. This enum value is not supported in Gemini API.\n   */\n  MODEL_ARMOR = 'MODEL_ARMOR',\n  /**\n   * The prompt was blocked as a jailbreak attempt. This enum value is not supported in Gemini API.\n   */\n  JAILBREAK = 'JAILBREAK',\n}\n\n/** Output only. The traffic type for this request. This enum is not supported in Gemini API. */\nexport enum TrafficType {\n  /**\n   * Unspecified request traffic type.\n   */\n  TRAFFIC_TYPE_UNSPECIFIED = 'TRAFFIC_TYPE_UNSPECIFIED',\n  /**\n   * The request was processed using Pay-As-You-Go quota.\n   */\n  ON_DEMAND = 'ON_DEMAND',\n  /**\n   * Type for Provisioned Throughput traffic.\n   */\n  PROVISIONED_THROUGHPUT = 'PROVISIONED_THROUGHPUT',\n}\n\n/** Server content modalities. */\nexport enum Modality {\n  /**\n   * The modality is unspecified.\n   */\n  MODALITY_UNSPECIFIED = 'MODALITY_UNSPECIFIED',\n  /**\n   * Indicates the model should return text\n   */\n  TEXT = 'TEXT',\n  /**\n   * Indicates the model should return images.\n   */\n  IMAGE = 'IMAGE',\n  /**\n   * Indicates the model should return audio.\n   */\n  AUDIO = 'AUDIO',\n}\n\n/** The media resolution to use. */\nexport enum MediaResolution {\n  /**\n   * Media resolution has not been set\n   */\n  MEDIA_RESOLUTION_UNSPECIFIED = 'MEDIA_RESOLUTION_UNSPECIFIED',\n  /**\n   * Media resolution set to low (64 tokens).\n   */\n  MEDIA_RESOLUTION_LOW = 'MEDIA_RESOLUTION_LOW',\n  /**\n   * Media resolution set to medium (256 tokens).\n   */\n  MEDIA_RESOLUTION_MEDIUM = 'MEDIA_RESOLUTION_MEDIUM',\n  /**\n   * Media resolution set to high (zoomed reframing with 256 tokens).\n   */\n  MEDIA_RESOLUTION_HIGH = 'MEDIA_RESOLUTION_HIGH',\n}\n\n/** Tuning mode. This enum is not supported in Gemini API. */\nexport enum TuningMode {\n  /**\n   * Tuning mode is unspecified.\n   */\n  TUNING_MODE_UNSPECIFIED = 'TUNING_MODE_UNSPECIFIED',\n  /**\n   * Full fine-tuning mode.\n   */\n  TUNING_MODE_FULL = 'TUNING_MODE_FULL',\n  /**\n   * PEFT adapter tuning mode.\n   */\n  TUNING_MODE_PEFT_ADAPTER = 'TUNING_MODE_PEFT_ADAPTER',\n}\n\n/** Adapter size for tuning. This enum is not supported in Gemini API. */\nexport enum AdapterSize {\n  /**\n   * Adapter size is unspecified.\n   */\n  ADAPTER_SIZE_UNSPECIFIED = 'ADAPTER_SIZE_UNSPECIFIED',\n  /**\n   * Adapter size 1.\n   */\n  ADAPTER_SIZE_ONE = 'ADAPTER_SIZE_ONE',\n  /**\n   * Adapter size 2.\n   */\n  ADAPTER_SIZE_TWO = 'ADAPTER_SIZE_TWO',\n  /**\n   * Adapter size 4.\n   */\n  ADAPTER_SIZE_FOUR = 'ADAPTER_SIZE_FOUR',\n  /**\n   * Adapter size 8.\n   */\n  ADAPTER_SIZE_EIGHT = 'ADAPTER_SIZE_EIGHT',\n  /**\n   * Adapter size 16.\n   */\n  ADAPTER_SIZE_SIXTEEN = 'ADAPTER_SIZE_SIXTEEN',\n  /**\n   * Adapter size 32.\n   */\n  ADAPTER_SIZE_THIRTY_TWO = 'ADAPTER_SIZE_THIRTY_TWO',\n}\n\n/** Job state. */\nexport enum JobState {\n  /**\n   * The job state is unspecified.\n   */\n  JOB_STATE_UNSPECIFIED = 'JOB_STATE_UNSPECIFIED',\n  /**\n   * The job has been just created or resumed and processing has not yet begun.\n   */\n  JOB_STATE_QUEUED = 'JOB_STATE_QUEUED',\n  /**\n   * The service is preparing to run the job.\n   */\n  JOB_STATE_PENDING = 'JOB_STATE_PENDING',\n  /**\n   * The job is in progress.\n   */\n  JOB_STATE_RUNNING = 'JOB_STATE_RUNNING',\n  /**\n   * The job completed successfully.\n   */\n  JOB_STATE_SUCCEEDED = 'JOB_STATE_SUCCEEDED',\n  /**\n   * The job failed.\n   */\n  JOB_STATE_FAILED = 'JOB_STATE_FAILED',\n  /**\n   * The job is being cancelled. From this state the job may only go to either `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`.\n   */\n  JOB_STATE_CANCELLING = 'JOB_STATE_CANCELLING',\n  /**\n   * The job has been cancelled.\n   */\n  JOB_STATE_CANCELLED = 'JOB_STATE_CANCELLED',\n  /**\n   * The job has been stopped, and can be resumed.\n   */\n  JOB_STATE_PAUSED = 'JOB_STATE_PAUSED',\n  /**\n   * The job has expired.\n   */\n  JOB_STATE_EXPIRED = 'JOB_STATE_EXPIRED',\n  /**\n   * The job is being updated. Only jobs in the `JOB_STATE_RUNNING` state can be updated. After updating, the job goes back to the `JOB_STATE_RUNNING` state.\n   */\n  JOB_STATE_UPDATING = 'JOB_STATE_UPDATING',\n  /**\n   * The job is partially succeeded, some results may be missing due to errors.\n   */\n  JOB_STATE_PARTIALLY_SUCCEEDED = 'JOB_STATE_PARTIALLY_SUCCEEDED',\n}\n\n/** The tuning task. Either I2V or T2V. This enum is not supported in Gemini API. */\nexport enum TuningTask {\n  /**\n   * Default value. This value is unused.\n   */\n  TUNING_TASK_UNSPECIFIED = 'TUNING_TASK_UNSPECIFIED',\n  /**\n   * Tuning task for image to video.\n   */\n  TUNING_TASK_I2V = 'TUNING_TASK_I2V',\n  /**\n   * Tuning task for text to video.\n   */\n  TUNING_TASK_T2V = 'TUNING_TASK_T2V',\n  /**\n   * Tuning task for reference to video.\n   */\n  TUNING_TASK_R2V = 'TUNING_TASK_R2V',\n}\n\n/** The tokenization quality used for given media. */\nexport enum PartMediaResolutionLevel {\n  /**\n   * Media resolution has not been set.\n   */\n  MEDIA_RESOLUTION_UNSPECIFIED = 'MEDIA_RESOLUTION_UNSPECIFIED',\n  /**\n   * Media resolution set to low.\n   */\n  MEDIA_RESOLUTION_LOW = 'MEDIA_RESOLUTION_LOW',\n  /**\n   * Media resolution set to medium.\n   */\n  MEDIA_RESOLUTION_MEDIUM = 'MEDIA_RESOLUTION_MEDIUM',\n  /**\n   * Media resolution set to high.\n   */\n  MEDIA_RESOLUTION_HIGH = 'MEDIA_RESOLUTION_HIGH',\n}\n\n/** Options for feature selection preference. */\nexport enum FeatureSelectionPreference {\n  FEATURE_SELECTION_PREFERENCE_UNSPECIFIED = 'FEATURE_SELECTION_PREFERENCE_UNSPECIFIED',\n  PRIORITIZE_QUALITY = 'PRIORITIZE_QUALITY',\n  BALANCED = 'BALANCED',\n  PRIORITIZE_COST = 'PRIORITIZE_COST',\n}\n\n/** Defines the function behavior. Defaults to `BLOCKING`. */\nexport enum Behavior {\n  /**\n   * This value is unused.\n   */\n  UNSPECIFIED = 'UNSPECIFIED',\n  /**\n   * If set, the system will wait to receive the function response before continuing the conversation.\n   */\n  BLOCKING = 'BLOCKING',\n  /**\n   * If set, the system will not wait to receive the function response. Instead, it will attempt to handle function responses as they become available while maintaining the conversation between the user and the model.\n   */\n  NON_BLOCKING = 'NON_BLOCKING',\n}\n\n/** Config for the dynamic retrieval config mode. */\nexport enum DynamicRetrievalConfigMode {\n  /**\n   * Always trigger retrieval.\n   */\n  MODE_UNSPECIFIED = 'MODE_UNSPECIFIED',\n  /**\n   * Run retrieval only when system decides it is necessary.\n   */\n  MODE_DYNAMIC = 'MODE_DYNAMIC',\n}\n\n/** The environment being operated. */\nexport enum Environment {\n  /**\n   * Defaults to browser.\n   */\n  ENVIRONMENT_UNSPECIFIED = 'ENVIRONMENT_UNSPECIFIED',\n  /**\n   * Operates in a web browser.\n   */\n  ENVIRONMENT_BROWSER = 'ENVIRONMENT_BROWSER',\n}\n\n/** Config for the function calling config mode. */\nexport enum FunctionCallingConfigMode {\n  /**\n   * The function calling config mode is unspecified. Should not be used.\n   */\n  MODE_UNSPECIFIED = 'MODE_UNSPECIFIED',\n  /**\n   * Default model behavior, model decides to predict either function calls or natural language response.\n   */\n  AUTO = 'AUTO',\n  /**\n   * Model is constrained to always predicting function calls only. If \"allowed_function_names\" are set, the predicted function calls will be limited to any one of \"allowed_function_names\", else the predicted function calls will be any one of the provided \"function_declarations\".\n   */\n  ANY = 'ANY',\n  /**\n   * Model will not predict any function calls. Model behavior is same as when not passing any function declarations.\n   */\n  NONE = 'NONE',\n  /**\n   * Model decides to predict either a function call or a natural language response, but will validate function calls with constrained decoding. If \"allowed_function_names\" are set, the predicted function call will be limited to any one of \"allowed_function_names\", else the predicted function call will be any one of the provided \"function_declarations\".\n   */\n  VALIDATED = 'VALIDATED',\n}\n\n/** Enum that controls the safety filter level for objectionable content. */\nexport enum SafetyFilterLevel {\n  BLOCK_LOW_AND_ABOVE = 'BLOCK_LOW_AND_ABOVE',\n  BLOCK_MEDIUM_AND_ABOVE = 'BLOCK_MEDIUM_AND_ABOVE',\n  BLOCK_ONLY_HIGH = 'BLOCK_ONLY_HIGH',\n  BLOCK_NONE = 'BLOCK_NONE',\n}\n\n/** Enum that controls the generation of people. */\nexport enum PersonGeneration {\n  /**\n   * Block generation of images of people.\n   */\n  DONT_ALLOW = 'DONT_ALLOW',\n  /**\n   * Generate images of adults, but not children.\n   */\n  ALLOW_ADULT = 'ALLOW_ADULT',\n  /**\n   * Generate images that include adults and children.\n   */\n  ALLOW_ALL = 'ALLOW_ALL',\n}\n\n/** Enum that specifies the language of the text in the prompt. */\nexport enum ImagePromptLanguage {\n  /**\n   * Auto-detect the language.\n   */\n  auto = 'auto',\n  /**\n   * English\n   */\n  en = 'en',\n  /**\n   * Japanese\n   */\n  ja = 'ja',\n  /**\n   * Korean\n   */\n  ko = 'ko',\n  /**\n   * Hindi\n   */\n  hi = 'hi',\n  /**\n   * Chinese\n   */\n  zh = 'zh',\n  /**\n   * Portuguese\n   */\n  pt = 'pt',\n  /**\n   * Spanish\n   */\n  es = 'es',\n}\n\n/** Enum representing the mask mode of a mask reference image. */\nexport enum MaskReferenceMode {\n  MASK_MODE_DEFAULT = 'MASK_MODE_DEFAULT',\n  MASK_MODE_USER_PROVIDED = 'MASK_MODE_USER_PROVIDED',\n  MASK_MODE_BACKGROUND = 'MASK_MODE_BACKGROUND',\n  MASK_MODE_FOREGROUND = 'MASK_MODE_FOREGROUND',\n  MASK_MODE_SEMANTIC = 'MASK_MODE_SEMANTIC',\n}\n\n/** Enum representing the control type of a control reference image. */\nexport enum ControlReferenceType {\n  CONTROL_TYPE_DEFAULT = 'CONTROL_TYPE_DEFAULT',\n  CONTROL_TYPE_CANNY = 'CONTROL_TYPE_CANNY',\n  CONTROL_TYPE_SCRIBBLE = 'CONTROL_TYPE_SCRIBBLE',\n  CONTROL_TYPE_FACE_MESH = 'CONTROL_TYPE_FACE_MESH',\n}\n\n/** Enum representing the subject type of a subject reference image. */\nexport enum SubjectReferenceType {\n  SUBJECT_TYPE_DEFAULT = 'SUBJECT_TYPE_DEFAULT',\n  SUBJECT_TYPE_PERSON = 'SUBJECT_TYPE_PERSON',\n  SUBJECT_TYPE_ANIMAL = 'SUBJECT_TYPE_ANIMAL',\n  SUBJECT_TYPE_PRODUCT = 'SUBJECT_TYPE_PRODUCT',\n}\n\n/** Enum representing the editing mode. */\nexport enum EditMode {\n  EDIT_MODE_DEFAULT = 'EDIT_MODE_DEFAULT',\n  EDIT_MODE_INPAINT_REMOVAL = 'EDIT_MODE_INPAINT_REMOVAL',\n  EDIT_MODE_INPAINT_INSERTION = 'EDIT_MODE_INPAINT_INSERTION',\n  EDIT_MODE_OUTPAINT = 'EDIT_MODE_OUTPAINT',\n  EDIT_MODE_CONTROLLED_EDITING = 'EDIT_MODE_CONTROLLED_EDITING',\n  EDIT_MODE_STYLE = 'EDIT_MODE_STYLE',\n  EDIT_MODE_BGSWAP = 'EDIT_MODE_BGSWAP',\n  EDIT_MODE_PRODUCT_IMAGE = 'EDIT_MODE_PRODUCT_IMAGE',\n}\n\n/** Enum that represents the segmentation mode. */\nexport enum SegmentMode {\n  FOREGROUND = 'FOREGROUND',\n  BACKGROUND = 'BACKGROUND',\n  PROMPT = 'PROMPT',\n  SEMANTIC = 'SEMANTIC',\n  INTERACTIVE = 'INTERACTIVE',\n}\n\n/** Enum for the reference type of a video generation reference image. */\nexport enum VideoGenerationReferenceType {\n  /**\n   * A reference image that provides assets to the generated video,\n      such as the scene, an object, a character, etc.\n   */\n  ASSET = 'ASSET',\n  /**\n   * A reference image that provides aesthetics including colors,\n      lighting, texture, etc., to be used as the style of the generated video,\n      such as 'anime', 'photography', 'origami', etc.\n   */\n  STYLE = 'STYLE',\n}\n\n/** Enum for the mask mode of a video generation mask. */\nexport enum VideoGenerationMaskMode {\n  /**\n   * The image mask contains a masked rectangular region which is\n      applied on the first frame of the input video. The object described in\n      the prompt is inserted into this region and will appear in subsequent\n      frames.\n   */\n  INSERT = 'INSERT',\n  /**\n   * The image mask is used to determine an object in the\n      first video frame to track. This object is removed from the video.\n   */\n  REMOVE = 'REMOVE',\n  /**\n   * The image mask is used to determine a region in the\n      video. Objects in this region will be removed.\n   */\n  REMOVE_STATIC = 'REMOVE_STATIC',\n  /**\n   * The image mask contains a masked rectangular region where\n      the input video will go. The remaining area will be generated. Video\n      masks are not supported.\n   */\n  OUTPAINT = 'OUTPAINT',\n}\n\n/** Enum that controls the compression quality of the generated videos. */\nexport enum VideoCompressionQuality {\n  /**\n   * Optimized video compression quality. This will produce videos\n      with a compressed, smaller file size.\n   */\n  OPTIMIZED = 'OPTIMIZED',\n  /**\n   * Lossless video compression quality. This will produce videos\n      with a larger file size.\n   */\n  LOSSLESS = 'LOSSLESS',\n}\n\n/** Enum representing the tuning method. */\nexport enum TuningMethod {\n  /**\n   * Supervised fine tuning.\n   */\n  SUPERVISED_FINE_TUNING = 'SUPERVISED_FINE_TUNING',\n  /**\n   * Preference optimization tuning.\n   */\n  PREFERENCE_TUNING = 'PREFERENCE_TUNING',\n}\n\n/** State for the lifecycle of a Document. */\nexport enum DocumentState {\n  STATE_UNSPECIFIED = 'STATE_UNSPECIFIED',\n  STATE_PENDING = 'STATE_PENDING',\n  STATE_ACTIVE = 'STATE_ACTIVE',\n  STATE_FAILED = 'STATE_FAILED',\n}\n\n/** State for the lifecycle of a File. */\nexport enum FileState {\n  STATE_UNSPECIFIED = 'STATE_UNSPECIFIED',\n  PROCESSING = 'PROCESSING',\n  ACTIVE = 'ACTIVE',\n  FAILED = 'FAILED',\n}\n\n/** Source of the File. */\nexport enum FileSource {\n  SOURCE_UNSPECIFIED = 'SOURCE_UNSPECIFIED',\n  UPLOADED = 'UPLOADED',\n  GENERATED = 'GENERATED',\n}\n\n/** The reason why the turn is complete. */\nexport enum TurnCompleteReason {\n  /**\n   * Default value. Reason is unspecified.\n   */\n  TURN_COMPLETE_REASON_UNSPECIFIED = 'TURN_COMPLETE_REASON_UNSPECIFIED',\n  /**\n   * The function call generated by the model is invalid.\n   */\n  MALFORMED_FUNCTION_CALL = 'MALFORMED_FUNCTION_CALL',\n  /**\n   * The response is rejected by the model.\n   */\n  RESPONSE_REJECTED = 'RESPONSE_REJECTED',\n  /**\n   * Needs more input from the user.\n   */\n  NEED_MORE_INPUT = 'NEED_MORE_INPUT',\n}\n\n/** Server content modalities. */\nexport enum MediaModality {\n  /**\n   * The modality is unspecified.\n   */\n  MODALITY_UNSPECIFIED = 'MODALITY_UNSPECIFIED',\n  /**\n   * Plain text.\n   */\n  TEXT = 'TEXT',\n  /**\n   * Images.\n   */\n  IMAGE = 'IMAGE',\n  /**\n   * Video.\n   */\n  VIDEO = 'VIDEO',\n  /**\n   * Audio.\n   */\n  AUDIO = 'AUDIO',\n  /**\n   * Document, e.g. PDF.\n   */\n  DOCUMENT = 'DOCUMENT',\n}\n\n/** The type of the VAD signal. */\nexport enum VadSignalType {\n  /**\n   * The default is VAD_SIGNAL_TYPE_UNSPECIFIED.\n   */\n  VAD_SIGNAL_TYPE_UNSPECIFIED = 'VAD_SIGNAL_TYPE_UNSPECIFIED',\n  /**\n   * Start of sentence signal.\n   */\n  VAD_SIGNAL_TYPE_SOS = 'VAD_SIGNAL_TYPE_SOS',\n  /**\n   * End of sentence signal.\n   */\n  VAD_SIGNAL_TYPE_EOS = 'VAD_SIGNAL_TYPE_EOS',\n}\n\n/** Start of speech sensitivity. */\nexport enum StartSensitivity {\n  /**\n   * The default is START_SENSITIVITY_LOW.\n   */\n  START_SENSITIVITY_UNSPECIFIED = 'START_SENSITIVITY_UNSPECIFIED',\n  /**\n   * Automatic detection will detect the start of speech more often.\n   */\n  START_SENSITIVITY_HIGH = 'START_SENSITIVITY_HIGH',\n  /**\n   * Automatic detection will detect the start of speech less often.\n   */\n  START_SENSITIVITY_LOW = 'START_SENSITIVITY_LOW',\n}\n\n/** End of speech sensitivity. */\nexport enum EndSensitivity {\n  /**\n   * The default is END_SENSITIVITY_LOW.\n   */\n  END_SENSITIVITY_UNSPECIFIED = 'END_SENSITIVITY_UNSPECIFIED',\n  /**\n   * Automatic detection ends speech more often.\n   */\n  END_SENSITIVITY_HIGH = 'END_SENSITIVITY_HIGH',\n  /**\n   * Automatic detection ends speech less often.\n   */\n  END_SENSITIVITY_LOW = 'END_SENSITIVITY_LOW',\n}\n\n/** The different ways of handling user activity. */\nexport enum ActivityHandling {\n  /**\n   * If unspecified, the default behavior is `START_OF_ACTIVITY_INTERRUPTS`.\n   */\n  ACTIVITY_HANDLING_UNSPECIFIED = 'ACTIVITY_HANDLING_UNSPECIFIED',\n  /**\n   * If true, start of activity will interrupt the model's response (also called \"barge in\"). The model's current response will be cut-off in the moment of the interruption. This is the default behavior.\n   */\n  START_OF_ACTIVITY_INTERRUPTS = 'START_OF_ACTIVITY_INTERRUPTS',\n  /**\n   * The model's response will not be interrupted.\n   */\n  NO_INTERRUPTION = 'NO_INTERRUPTION',\n}\n\n/** Options about which input is included in the user's turn. */\nexport enum TurnCoverage {\n  /**\n   * If unspecified, the default behavior is `TURN_INCLUDES_ONLY_ACTIVITY`.\n   */\n  TURN_COVERAGE_UNSPECIFIED = 'TURN_COVERAGE_UNSPECIFIED',\n  /**\n   * The users turn only includes activity since the last turn, excluding inactivity (e.g. silence on the audio stream). This is the default behavior.\n   */\n  TURN_INCLUDES_ONLY_ACTIVITY = 'TURN_INCLUDES_ONLY_ACTIVITY',\n  /**\n   * The users turn includes all realtime input since the last turn, including inactivity (e.g. silence on the audio stream).\n   */\n  TURN_INCLUDES_ALL_INPUT = 'TURN_INCLUDES_ALL_INPUT',\n}\n\n/** Scale of the generated music. */\nexport enum Scale {\n  /**\n   * Default value. This value is unused.\n   */\n  SCALE_UNSPECIFIED = 'SCALE_UNSPECIFIED',\n  /**\n   * C major or A minor.\n   */\n  C_MAJOR_A_MINOR = 'C_MAJOR_A_MINOR',\n  /**\n   * Db major or Bb minor.\n   */\n  D_FLAT_MAJOR_B_FLAT_MINOR = 'D_FLAT_MAJOR_B_FLAT_MINOR',\n  /**\n   * D major or B minor.\n   */\n  D_MAJOR_B_MINOR = 'D_MAJOR_B_MINOR',\n  /**\n   * Eb major or C minor\n   */\n  E_FLAT_MAJOR_C_MINOR = 'E_FLAT_MAJOR_C_MINOR',\n  /**\n   * E major or Db minor.\n   */\n  E_MAJOR_D_FLAT_MINOR = 'E_MAJOR_D_FLAT_MINOR',\n  /**\n   * F major or D minor.\n   */\n  F_MAJOR_D_MINOR = 'F_MAJOR_D_MINOR',\n  /**\n   * Gb major or Eb minor.\n   */\n  G_FLAT_MAJOR_E_FLAT_MINOR = 'G_FLAT_MAJOR_E_FLAT_MINOR',\n  /**\n   * G major or E minor.\n   */\n  G_MAJOR_E_MINOR = 'G_MAJOR_E_MINOR',\n  /**\n   * Ab major or F minor.\n   */\n  A_FLAT_MAJOR_F_MINOR = 'A_FLAT_MAJOR_F_MINOR',\n  /**\n   * A major or Gb minor.\n   */\n  A_MAJOR_G_FLAT_MINOR = 'A_MAJOR_G_FLAT_MINOR',\n  /**\n   * Bb major or G minor.\n   */\n  B_FLAT_MAJOR_G_MINOR = 'B_FLAT_MAJOR_G_MINOR',\n  /**\n   * B major or Ab minor.\n   */\n  B_MAJOR_A_FLAT_MINOR = 'B_MAJOR_A_FLAT_MINOR',\n}\n\n/** The mode of music generation. */\nexport enum MusicGenerationMode {\n  /**\n   * Rely on the server default generation mode.\n   */\n  MUSIC_GENERATION_MODE_UNSPECIFIED = 'MUSIC_GENERATION_MODE_UNSPECIFIED',\n  /**\n   * Steer text prompts to regions of latent space with higher quality\n      music.\n   */\n  QUALITY = 'QUALITY',\n  /**\n   * Steer text prompts to regions of latent space with a larger\n      diversity of music.\n   */\n  DIVERSITY = 'DIVERSITY',\n  /**\n   * Steer text prompts to regions of latent space more likely to\n      generate music with vocals.\n   */\n  VOCALIZATION = 'VOCALIZATION',\n}\n\n/** The playback control signal to apply to the music generation. */\nexport enum LiveMusicPlaybackControl {\n  /**\n   * This value is unused.\n   */\n  PLAYBACK_CONTROL_UNSPECIFIED = 'PLAYBACK_CONTROL_UNSPECIFIED',\n  /**\n   * Start generating the music.\n   */\n  PLAY = 'PLAY',\n  /**\n   * Hold the music generation. Use PLAY to resume from the current position.\n   */\n  PAUSE = 'PAUSE',\n  /**\n   * Stop the music generation and reset the context (prompts retained).\n      Use PLAY to restart the music generation.\n   */\n  STOP = 'STOP',\n  /**\n   * Reset the context of the music generation without stopping it.\n      Retains the current prompts and config.\n   */\n  RESET_CONTEXT = 'RESET_CONTEXT',\n}\n\n/** Media resolution for the input media. */\nexport declare interface PartMediaResolution {\n  /** The tokenization quality used for given media.\n   */\n  level?: PartMediaResolutionLevel;\n  /** Specifies the required sequence length for media tokenization.\n   */\n  numTokens?: number;\n}\n\n/** Result of executing the [ExecutableCode]. Only generated when using the [CodeExecution] tool, and always follows a `part` containing the [ExecutableCode]. */\nexport declare interface CodeExecutionResult {\n  /** Required. Outcome of the code execution. */\n  outcome?: Outcome;\n  /** Optional. Contains stdout when code execution is successful, stderr or other description otherwise. */\n  output?: string;\n}\n\n/** Code generated by the model that is meant to be executed, and the result returned to the model. Generated when using the [CodeExecution] tool, in which the code will be automatically executed, and a corresponding [CodeExecutionResult] will also be generated. */\nexport declare interface ExecutableCode {\n  /** Required. The code to be executed. */\n  code?: string;\n  /** Required. Programming language of the `code`. */\n  language?: Language;\n}\n\n/** URI based data. */\nexport declare interface FileData {\n  /** Optional. Display name of the file data. Used to provide a label or filename to distinguish file datas. This field is only returned in PromptMessage for prompt management. It is currently used in the Gemini GenerateContent calls only when server side tools (code_execution, google_search, and url_context) are enabled. This field is not supported in Gemini API. */\n  displayName?: string;\n  /** Required. URI. */\n  fileUri?: string;\n  /** Required. The IANA standard MIME type of the source data. */\n  mimeType?: string;\n}\n\n/** Partial argument value of the function call. This data type is not supported in Gemini API. */\nexport declare interface PartialArg {\n  /** Optional. Represents a null value. */\n  nullValue?: 'NULL_VALUE';\n  /** Optional. Represents a double value. */\n  numberValue?: number;\n  /** Optional. Represents a string value. */\n  stringValue?: string;\n  /** Optional. Represents a boolean value. */\n  boolValue?: boolean;\n  /** Required. A JSON Path (RFC 9535) to the argument being streamed. https://datatracker.ietf.org/doc/html/rfc9535. e.g. \"$.foo.bar[0].data\". */\n  jsonPath?: string;\n  /** Optional. Whether this is not the last part of the same json_path. If true, another PartialArg message for the current json_path is expected to follow. */\n  willContinue?: boolean;\n}\n\n/** A function call. */\nexport declare interface FunctionCall {\n  /** The unique id of the function call. If populated, the client to execute the\n   `function_call` and return the response with the matching `id`. */\n  id?: string;\n  /** Optional. The function parameters and values in JSON object format. See [FunctionDeclaration.parameters] for parameter details. */\n  args?: Record<string, unknown>;\n  /** Optional. The name of the function to call. Matches [FunctionDeclaration.name]. */\n  name?: string;\n  /** Optional. The partial argument value of the function call. If provided, represents the arguments/fields that are streamed incrementally. This field is not supported in Gemini API. */\n  partialArgs?: PartialArg[];\n  /** Optional. Whether this is the last part of the FunctionCall. If true, another partial message for the current FunctionCall is expected to follow. This field is not supported in Gemini API. */\n  willContinue?: boolean;\n}\n\n/** Raw media bytes for function response.\n\nText should not be sent as raw bytes, use the FunctionResponse.response\nfield. */\nexport class FunctionResponseBlob {\n  /** Required. The IANA standard MIME type of the source data. */\n  mimeType?: string;\n  /** Required. Inline media bytes.\n   * @remarks Encoded as base64 string. */\n  data?: string;\n  /** Optional. Display name of the blob.\n      Used to provide a label or filename to distinguish blobs. */\n  displayName?: string;\n}\n\n/** URI based data for function response. */\nexport class FunctionResponseFileData {\n  /** Required. URI. */\n  fileUri?: string;\n  /** Required. The IANA standard MIME type of the source data. */\n  mimeType?: string;\n  /** Optional. Display name of the file.\n      Used to provide a label or filename to distinguish files. */\n  displayName?: string;\n}\n\n/** A datatype containing media that is part of a `FunctionResponse` message.\n\nA `FunctionResponsePart` consists of data which has an associated datatype. A\n`FunctionResponsePart` can only contain one of the accepted types in\n`FunctionResponsePart.data`.\n\nA `FunctionResponsePart` must have a fixed IANA MIME type identifying the\ntype and subtype of the media if the `inline_data` field is filled with raw\nbytes. */\nexport class FunctionResponsePart {\n  /** Optional. Inline media bytes. */\n  inlineData?: FunctionResponseBlob;\n  /** Optional. URI based data. */\n  fileData?: FunctionResponseFileData;\n}\n/**\n * Creates a `FunctionResponsePart` object from a `base64` encoded `string`.\n */\nexport function createFunctionResponsePartFromBase64(\n  data: string,\n  mimeType: string,\n): FunctionResponsePart {\n  return {\n    inlineData: {\n      data: data,\n      mimeType: mimeType,\n    },\n  };\n}\n/**\n * Creates a `FunctionResponsePart` object from a `URI` string.\n */\nexport function createFunctionResponsePartFromUri(\n  uri: string,\n  mimeType: string,\n): FunctionResponsePart {\n  return {\n    fileData: {\n      fileUri: uri,\n      mimeType: mimeType,\n    },\n  };\n}\n\n/** A function response. */\nexport class FunctionResponse {\n  /** Signals that function call continues, and more responses will be returned, turning the function call into a generator. Is only applicable to NON_BLOCKING function calls (see FunctionDeclaration.behavior for details), ignored otherwise. If false, the default, future responses will not be considered. Is only applicable to NON_BLOCKING function calls, is ignored otherwise. If set to false, future responses will not be considered. It is allowed to return empty `response` with `will_continue=False` to signal that the function call is finished. */\n  willContinue?: boolean;\n  /** Specifies how the response should be scheduled in the conversation. Only applicable to NON_BLOCKING function calls, is ignored otherwise. Defaults to WHEN_IDLE. */\n  scheduling?: FunctionResponseScheduling;\n  /** List of parts that constitute a function response. Each part may\n      have a different IANA MIME type. */\n  parts?: FunctionResponsePart[];\n  /** Optional. The id of the function call this response is for. Populated by the client to match the corresponding function call `id`. */\n  id?: string;\n  /** Required. The name of the function to call. Matches [FunctionDeclaration.name] and [FunctionCall.name]. */\n  name?: string;\n  /** Required. The function response in JSON object format. Use \"output\" key to specify function output and \"error\" key to specify error details (if any). If \"output\" and \"error\" keys are not specified, then whole \"response\" is treated as function output. */\n  response?: Record<string, unknown>;\n}\n\n/** Content blob. */\nexport declare interface Blob {\n  /** Required. Raw bytes.\n   * @remarks Encoded as base64 string. */\n  data?: string;\n  /** Optional. Display name of the blob. Used to provide a label or filename to distinguish blobs. This field is only returned in PromptMessage for prompt management. It is currently used in the Gemini GenerateContent calls only when server side tools (code_execution, google_search, and url_context) are enabled. This field is not supported in Gemini API. */\n  displayName?: string;\n  /** Required. The IANA standard MIME type of the source data. */\n  mimeType?: string;\n}\n\n/** Metadata describes the input video content. */\nexport declare interface VideoMetadata {\n  /** Optional. The end offset of the video. */\n  endOffset?: string;\n  /** Optional. The frame rate of the video sent to the model. If not specified, the default value will be 1.0. The fps range is (0.0, 24.0]. */\n  fps?: number;\n  /** Optional. The start offset of the video. */\n  startOffset?: string;\n}\n\n/** A datatype containing media content.\n\nExactly one field within a Part should be set, representing the specific type\nof content being conveyed. Using multiple fields within the same `Part`\ninstance is considered invalid. */\nexport declare interface Part {\n  /** Media resolution for the input media.\n   */\n  mediaResolution?: PartMediaResolution;\n  /** Optional. Result of executing the [ExecutableCode]. */\n  codeExecutionResult?: CodeExecutionResult;\n  /** Optional. Code generated by the model that is meant to be executed. */\n  executableCode?: ExecutableCode;\n  /** Optional. URI based data. */\n  fileData?: FileData;\n  /** Optional. A predicted [FunctionCall] returned from the model that contains a string representing the [FunctionDeclaration.name] with the parameters and their values. */\n  functionCall?: FunctionCall;\n  /** Optional. The result output of a [FunctionCall] that contains a string representing the [FunctionDeclaration.name] and a structured JSON object containing any output from the function call. It is used as context to the model. */\n  functionResponse?: FunctionResponse;\n  /** Optional. Inlined bytes data. */\n  inlineData?: Blob;\n  /** Optional. Text part (can be code). */\n  text?: string;\n  /** Optional. Indicates if the part is thought from the model. */\n  thought?: boolean;\n  /** Optional. An opaque signature for the thought so it can be reused in subsequent requests.\n   * @remarks Encoded as base64 string. */\n  thoughtSignature?: string;\n  /** Optional. Video metadata. The metadata should only be specified while the video data is presented in inline_data or file_data. */\n  videoMetadata?: VideoMetadata;\n}\n/**\n * Creates a `Part` object from a `URI` string.\n */\nexport function createPartFromUri(\n  uri: string,\n  mimeType: string,\n  mediaResolution?: PartMediaResolutionLevel,\n): Part {\n  return {\n    fileData: {\n      fileUri: uri,\n      mimeType: mimeType,\n    },\n    ...(mediaResolution && {mediaResolution: {level: mediaResolution}}),\n  };\n}\n/**\n * Creates a `Part` object from a `text` string.\n */\nexport function createPartFromText(text: string): Part {\n  return {\n    text: text,\n  };\n}\n/**\n * Creates a `Part` object from a `FunctionCall` object.\n */\nexport function createPartFromFunctionCall(\n  name: string,\n  args: Record<string, unknown>,\n): Part {\n  return {\n    functionCall: {\n      name: name,\n      args: args,\n    },\n  };\n}\n/**\n * Creates a `Part` object from a `FunctionResponse` object.\n */\nexport function createPartFromFunctionResponse(\n  id: string,\n  name: string,\n  response: Record<string, unknown>,\n  parts: FunctionResponsePart[] = [],\n): Part {\n  return {\n    functionResponse: {\n      id: id,\n      name: name,\n      response: response,\n      ...(parts.length > 0 && {parts}),\n    },\n  };\n}\n/**\n * Creates a `Part` object from a `base64` encoded `string`.\n */\nexport function createPartFromBase64(\n  data: string,\n  mimeType: string,\n  mediaResolution?: PartMediaResolutionLevel,\n): Part {\n  return {\n    inlineData: {\n      data: data,\n      mimeType: mimeType,\n    },\n    ...(mediaResolution && {mediaResolution: {level: mediaResolution}}),\n  };\n}\n/**\n * Creates a `Part` object from the `outcome` and `output` of a `CodeExecutionResult` object.\n */\nexport function createPartFromCodeExecutionResult(\n  outcome: Outcome,\n  output: string,\n): Part {\n  return {\n    codeExecutionResult: {\n      outcome: outcome,\n      output: output,\n    },\n  };\n}\n/**\n * Creates a `Part` object from the `code` and `language` of an `ExecutableCode` object.\n */\nexport function createPartFromExecutableCode(\n  code: string,\n  language: Language,\n): Part {\n  return {\n    executableCode: {\n      code: code,\n      language: language,\n    },\n  };\n}\n\n/** Contains the multi-part content of a message. */\nexport declare interface Content {\n  /** List of parts that constitute a single message. Each part may have\n      a different IANA MIME type. */\n  parts?: Part[];\n  /** Optional. The producer of the content. Must be either 'user' or 'model'. Useful to set for multi-turn conversations, otherwise can be left blank or unset. */\n  role?: string;\n}\nfunction _isPart(obj: unknown): obj is Part {\n  if (typeof obj === 'object' && obj !== null) {\n    return (\n      'fileData' in obj ||\n      'text' in obj ||\n      'functionCall' in obj ||\n      'functionResponse' in obj ||\n      'inlineData' in obj ||\n      'videoMetadata' in obj ||\n      'codeExecutionResult' in obj ||\n      'executableCode' in obj\n    );\n  }\n  return false;\n}\nfunction _toParts(partOrString: PartListUnion | string): Part[] {\n  const parts: Part[] = [];\n  if (typeof partOrString === 'string') {\n    parts.push(createPartFromText(partOrString));\n  } else if (_isPart(partOrString)) {\n    parts.push(partOrString);\n  } else if (Array.isArray(partOrString)) {\n    if (partOrString.length === 0) {\n      throw new Error('partOrString cannot be an empty array');\n    }\n    for (const part of partOrString) {\n      if (typeof part === 'string') {\n        parts.push(createPartFromText(part));\n      } else if (_isPart(part)) {\n        parts.push(part);\n      } else {\n        throw new Error('element in PartUnion must be a Part object or string');\n      }\n    }\n  } else {\n    throw new Error('partOrString must be a Part object, string, or array');\n  }\n  return parts;\n}\n/**\n * Creates a `Content` object with a user role from a `PartListUnion` object or `string`.\n */\nexport function createUserContent(\n  partOrString: PartListUnion | string,\n): Content {\n  return {\n    role: 'user',\n    parts: _toParts(partOrString),\n  };\n}\n\n/**\n * Creates a `Content` object with a model role from a `PartListUnion` object or `string`.\n */\nexport function createModelContent(\n  partOrString: PartListUnion | string,\n): Content {\n  return {\n    role: 'model',\n    parts: _toParts(partOrString),\n  };\n}\n/** HTTP options to be used in each of the requests. */\nexport declare interface HttpOptions {\n  /** The base URL for the AI platform service endpoint. */\n  baseUrl?: string;\n  /** Specifies the version of the API to use. */\n  apiVersion?: string;\n  /** Additional HTTP headers to be sent with the request. */\n  headers?: Record<string, string>;\n  /** Timeout for the request in milliseconds. */\n  timeout?: number;\n  /** Extra parameters to add to the request body.\n      The structure must match the backend API's request structure.\n      - VertexAI backend API docs: https://cloud.google.com/vertex-ai/docs/reference/rest\n      - GeminiAPI backend API docs: https://ai.google.dev/api/rest */\n  extraBody?: Record<string, unknown>;\n}\n\n/** Schema is used to define the format of input/output data.\n\nRepresents a select subset of an [OpenAPI 3.0 schema\nobject](https://spec.openapis.org/oas/v3.0.3#schema-object). More fields may\nbe added in the future as needed. */\nexport declare interface Schema {\n  /** Optional. The value should be validated against any (one or more) of the subschemas in the list. */\n  anyOf?: Schema[];\n  /** Optional. Default value of the data. */\n  default?: unknown;\n  /** Optional. The description of the data. */\n  description?: string;\n  /** Optional. Possible values of the element of primitive type with enum format. Examples: 1. We can define direction as : {type:STRING, format:enum, enum:[\"EAST\", NORTH\", \"SOUTH\", \"WEST\"]} 2. We can define apartment number as : {type:INTEGER, format:enum, enum:[\"101\", \"201\", \"301\"]} */\n  enum?: string[];\n  /** Optional. Example of the object. Will only populated when the object is the root. */\n  example?: unknown;\n  /** Optional. The format of the data. Supported formats: for NUMBER type: \"float\", \"double\" for INTEGER type: \"int32\", \"int64\" for STRING type: \"email\", \"byte\", etc */\n  format?: string;\n  /** Optional. SCHEMA FIELDS FOR TYPE ARRAY Schema of the elements of Type.ARRAY. */\n  items?: Schema;\n  /** Optional. Maximum number of the elements for Type.ARRAY. */\n  maxItems?: string;\n  /** Optional. Maximum length of the Type.STRING */\n  maxLength?: string;\n  /** Optional. Maximum number of the properties for Type.OBJECT. */\n  maxProperties?: string;\n  /** Optional. Maximum value of the Type.INTEGER and Type.NUMBER */\n  maximum?: number;\n  /** Optional. Minimum number of the elements for Type.ARRAY. */\n  minItems?: string;\n  /** Optional. SCHEMA FIELDS FOR TYPE STRING Minimum length of the Type.STRING */\n  minLength?: string;\n  /** Optional. Minimum number of the properties for Type.OBJECT. */\n  minProperties?: string;\n  /** Optional. SCHEMA FIELDS FOR TYPE INTEGER and NUMBER Minimum value of the Type.INTEGER and Type.NUMBER */\n  minimum?: number;\n  /** Optional. Indicates if the value may be null. */\n  nullable?: boolean;\n  /** Optional. Pattern of the Type.STRING to restrict a string to a regular expression. */\n  pattern?: string;\n  /** Optional. SCHEMA FIELDS FOR TYPE OBJECT Properties of Type.OBJECT. */\n  properties?: Record<string, Schema>;\n  /** Optional. The order of the properties. Not a standard field in open api spec. Only used to support the order of the properties. */\n  propertyOrdering?: string[];\n  /** Optional. Required properties of Type.OBJECT. */\n  required?: string[];\n  /** Optional. The title of the Schema. */\n  title?: string;\n  /** Optional. The type of the data. */\n  type?: Type;\n}\n\n/** Config for model selection. */\nexport declare interface ModelSelectionConfig {\n  /** Options for feature selection preference. */\n  featureSelectionPreference?: FeatureSelectionPreference;\n}\n\n/** Defines a function that the model can generate JSON inputs for.\n\nThe inputs are based on `OpenAPI 3.0 specifications\n<https://spec.openapis.org/oas/v3.0.3>`_. */\nexport declare interface FunctionDeclaration {\n  /** Defines the function behavior. */\n  behavior?: Behavior;\n  /** Optional. Description and purpose of the function. Model uses it to decide how and whether to call the function. */\n  description?: string;\n  /** Required. The name of the function to call. Must start with a letter or an underscore. Must be a-z, A-Z, 0-9, or contain underscores, dots and dashes, with a maximum length of 64. */\n  name?: string;\n  /** Optional. Describes the parameters to this function in JSON Schema Object format. Reflects the Open API 3.03 Parameter Object. string Key: the name of the parameter. Parameter names are case sensitive. Schema Value: the Schema defining the type used for the parameter. For function with no parameters, this can be left unset. Parameter names must start with a letter or an underscore and must only contain chars a-z, A-Z, 0-9, or underscores with a maximum length of 64. Example with 1 required and 1 optional parameter: type: OBJECT properties: param1: type: STRING param2: type: INTEGER required: - param1 */\n  parameters?: Schema;\n  /** Optional. Describes the parameters to the function in JSON Schema format. The schema must describe an object where the properties are the parameters to the function. For example: ``` { \"type\": \"object\", \"properties\": { \"name\": { \"type\": \"string\" }, \"age\": { \"type\": \"integer\" } }, \"additionalProperties\": false, \"required\": [\"name\", \"age\"], \"propertyOrdering\": [\"name\", \"age\"] } ``` This field is mutually exclusive with `parameters`. */\n  parametersJsonSchema?: unknown;\n  /** Optional. Describes the output from this function in JSON Schema format. Reflects the Open API 3.03 Response Object. The Schema defines the type used for the response value of the function. */\n  response?: Schema;\n  /** Optional. Describes the output from this function in JSON Schema format. The value specified by the schema is the response value of the function. This field is mutually exclusive with `response`. */\n  responseJsonSchema?: unknown;\n}\n\n/** Describes the options to customize dynamic retrieval. */\nexport declare interface DynamicRetrievalConfig {\n  /** The mode of the predictor to be used in dynamic retrieval. */\n  mode?: DynamicRetrievalConfigMode;\n  /** Optional. The threshold to be used in dynamic retrieval. If not set, a system default value is used. */\n  dynamicThreshold?: number;\n}\n\n/** Tool to retrieve public web data for grounding, powered by Google. */\nexport declare interface GoogleSearchRetrieval {\n  /** Specifies the dynamic retrieval configuration for the given source. */\n  dynamicRetrievalConfig?: DynamicRetrievalConfig;\n}\n\n/** Tool to support computer use. */\nexport declare interface ComputerUse {\n  /** Required. The environment being operated. */\n  environment?: Environment;\n  /** By default, predefined functions are included in the final model call.\n    Some of them can be explicitly excluded from being automatically included.\n    This can serve two purposes:\n      1. Using a more restricted / different action space.\n      2. Improving the definitions / instructions of predefined functions. */\n  excludedPredefinedFunctions?: string[];\n}\n\n/** Tool to retrieve knowledge from the File Search Stores. */\nexport declare interface FileSearch {\n  /** The names of the file_search_stores to retrieve from.\n      Example: `fileSearchStores/my-file-search-store-123` */\n  fileSearchStoreNames?: string[];\n  /** The number of file search retrieval chunks to retrieve. */\n  topK?: number;\n  /** Metadata filter to apply to the file search retrieval documents. See https://google.aip.dev/160 for the syntax of the filter expression. */\n  metadataFilter?: string;\n}\n\n/** The API secret. This data type is not supported in Gemini API. */\nexport declare interface ApiAuthApiKeyConfig {\n  /** Required. The SecretManager secret version resource name storing API key. e.g. projects/{project}/secrets/{secret}/versions/{version} */\n  apiKeySecretVersion?: string;\n  /** The API key string. Either this or `api_key_secret_version` must be set. */\n  apiKeyString?: string;\n}\n\n/** The generic reusable api auth config. Deprecated. Please use AuthConfig (google/cloud/aiplatform/master/auth.proto) instead. This data type is not supported in Gemini API. */\nexport declare interface ApiAuth {\n  /** The API secret. */\n  apiKeyConfig?: ApiAuthApiKeyConfig;\n}\n\n/** Config for authentication with API key. This data type is not supported in Gemini API. */\nexport declare interface ApiKeyConfig {\n  /** Optional. The name of the SecretManager secret version resource storing the API key. Format: `projects/{project}/secrets/{secrete}/versions/{version}` - If both `api_key_secret` and `api_key_string` are specified, this field takes precedence over `api_key_string`. - If specified, the `secretmanager.versions.access` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the specified resource. */\n  apiKeySecret?: string;\n  /** Optional. The API key to be used in the request directly. */\n  apiKeyString?: string;\n  /** Optional. The location of the API key. */\n  httpElementLocation?: HttpElementLocation;\n  /** Optional. The parameter name of the API key. E.g. If the API request is \"https://example.com/act?api_key=\", \"api_key\" would be the parameter name. */\n  name?: string;\n}\n\n/** Config for Google Service Account Authentication. This data type is not supported in Gemini API. */\nexport declare interface AuthConfigGoogleServiceAccountConfig {\n  /** Optional. The service account that the extension execution service runs as. - If the service account is specified, the `iam.serviceAccounts.getAccessToken` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the specified service account. - If not specified, the Vertex AI Extension Service Agent will be used to execute the Extension. */\n  serviceAccount?: string;\n}\n\n/** Config for HTTP Basic Authentication. This data type is not supported in Gemini API. */\nexport declare interface AuthConfigHttpBasicAuthConfig {\n  /** Required. The name of the SecretManager secret version resource storing the base64 encoded credentials. Format: `projects/{project}/secrets/{secrete}/versions/{version}` - If specified, the `secretmanager.versions.access` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the specified resource. */\n  credentialSecret?: string;\n}\n\n/** Config for user oauth. This data type is not supported in Gemini API. */\nexport declare interface AuthConfigOauthConfig {\n  /** Access token for extension endpoint. Only used to propagate token from [[ExecuteExtensionRequest.runtime_auth_config]] at request time. */\n  accessToken?: string;\n  /** The service account used to generate access tokens for executing the Extension. - If the service account is specified, the `iam.serviceAccounts.getAccessToken` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the provided service account. */\n  serviceAccount?: string;\n}\n\n/** Config for user OIDC auth. This data type is not supported in Gemini API. */\nexport declare interface AuthConfigOidcConfig {\n  /** OpenID Connect formatted ID token for extension endpoint. Only used to propagate token from [[ExecuteExtensionRequest.runtime_auth_config]] at request time. */\n  idToken?: string;\n  /** The service account used to generate an OpenID Connect (OIDC)-compatible JWT token signed by the Google OIDC Provider (accounts.google.com) for extension endpoint (https://cloud.google.com/iam/docs/create-short-lived-credentials-direct#sa-credentials-oidc). - The audience for the token will be set to the URL in the server url defined in the OpenApi spec. - If the service account is provided, the service account should grant `iam.serviceAccounts.getOpenIdToken` permission to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents). */\n  serviceAccount?: string;\n}\n\n/** Auth configuration to run the extension. This data type is not supported in Gemini API. */\nexport declare interface AuthConfig {\n  /** Config for API key auth. */\n  apiKeyConfig?: ApiKeyConfig;\n  /** Type of auth scheme. */\n  authType?: AuthType;\n  /** Config for Google Service Account auth. */\n  googleServiceAccountConfig?: AuthConfigGoogleServiceAccountConfig;\n  /** Config for HTTP Basic auth. */\n  httpBasicAuthConfig?: AuthConfigHttpBasicAuthConfig;\n  /** Config for user oauth. */\n  oauthConfig?: AuthConfigOauthConfig;\n  /** Config for user OIDC auth. */\n  oidcConfig?: AuthConfigOidcConfig;\n}\n\n/** The search parameters to use for the ELASTIC_SEARCH spec. This data type is not supported in Gemini API. */\nexport declare interface ExternalApiElasticSearchParams {\n  /** The ElasticSearch index to use. */\n  index?: string;\n  /** Optional. Number of hits (chunks) to request. When specified, it is passed to Elasticsearch as the `num_hits` param. */\n  numHits?: number;\n  /** The ElasticSearch search template to use. */\n  searchTemplate?: string;\n}\n\n/** The search parameters to use for SIMPLE_SEARCH spec. This data type is not supported in Gemini API. */\nexport declare interface ExternalApiSimpleSearchParams {}\n\n/** Retrieve from data source powered by external API for grounding. The external API is not owned by Google, but need to follow the pre-defined API spec. This data type is not supported in Gemini API. */\nexport declare interface ExternalApi {\n  /** The authentication config to access the API. Deprecated. Please use auth_config instead. */\n  apiAuth?: ApiAuth;\n  /** The API spec that the external API implements. */\n  apiSpec?: ApiSpec;\n  /** The authentication config to access the API. */\n  authConfig?: AuthConfig;\n  /** Parameters for the elastic search API. */\n  elasticSearchParams?: ExternalApiElasticSearchParams;\n  /** The endpoint of the external API. The system will call the API at this endpoint to retrieve the data for grounding. Example: https://acme.com:443/search */\n  endpoint?: string;\n  /** Parameters for the simple search API. */\n  simpleSearchParams?: ExternalApiSimpleSearchParams;\n}\n\n/** Define data stores within engine to filter on in a search call and configurations for those data stores. For more information, see https://cloud.google.com/generative-ai-app-builder/docs/reference/rpc/google.cloud.discoveryengine.v1#datastorespec. This data type is not supported in Gemini API. */\nexport declare interface VertexAISearchDataStoreSpec {\n  /** Full resource name of DataStore, such as Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}` */\n  dataStore?: string;\n  /** Optional. Filter specification to filter documents in the data store specified by data_store field. For more information on filtering, see [Filtering](https://cloud.google.com/generative-ai-app-builder/docs/filter-search-metadata) */\n  filter?: string;\n}\n\n/** Retrieve from Vertex AI Search datastore or engine for grounding. datastore and engine are mutually exclusive. See https://cloud.google.com/products/agent-builder. This data type is not supported in Gemini API. */\nexport declare interface VertexAISearch {\n  /** Specifications that define the specific DataStores to be searched, along with configurations for those data stores. This is only considered for Engines with multiple data stores. It should only be set if engine is used. */\n  dataStoreSpecs?: VertexAISearchDataStoreSpec[];\n  /** Optional. Fully-qualified Vertex AI Search data store resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}` */\n  datastore?: string;\n  /** Optional. Fully-qualified Vertex AI Search engine resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/engines/{engine}` */\n  engine?: string;\n  /** Optional. Filter strings to be passed to the search API. */\n  filter?: string;\n  /** Optional. Number of search results to return per query. The default value is 10. The maximumm allowed value is 10. */\n  maxResults?: number;\n}\n\n/** The definition of the Rag resource. This data type is not supported in Gemini API. */\nexport declare interface VertexRagStoreRagResource {\n  /** Optional. RagCorpora resource name. Format: `projects/{project}/locations/{location}/ragCorpora/{rag_corpus}` */\n  ragCorpus?: string;\n  /** Optional. rag_file_id. The files should be in the same rag_corpus set in rag_corpus field. */\n  ragFileIds?: string[];\n}\n\n/** Config for filters. This data type is not supported in Gemini API. */\nexport declare interface RagRetrievalConfigFilter {\n  /** Optional. String for metadata filtering. */\n  metadataFilter?: string;\n  /** Optional. Only returns contexts with vector distance smaller than the threshold. */\n  vectorDistanceThreshold?: number;\n  /** Optional. Only returns contexts with vector similarity larger than the threshold. */\n  vectorSimilarityThreshold?: number;\n}\n\n/** Config for Hybrid Search. This data type is not supported in Gemini API. */\nexport declare interface RagRetrievalConfigHybridSearch {\n  /** Optional. Alpha value controls the weight between dense and sparse vector search results. The range is [0, 1], while 0 means sparse vector search only and 1 means dense vector search only. The default value is 0.5 which balances sparse and dense vector search equally. */\n  alpha?: number;\n}\n\n/** Config for LlmRanker. This data type is not supported in Gemini API. */\nexport declare interface RagRetrievalConfigRankingLlmRanker {\n  /** Optional. The model name used for ranking. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#supported-models). */\n  modelName?: string;\n}\n\n/** Config for Rank Service. This data type is not supported in Gemini API. */\nexport declare interface RagRetrievalConfigRankingRankService {\n  /** Optional. The model name of the rank service. Format: `semantic-ranker-512@latest` */\n  modelName?: string;\n}\n\n/** Config for ranking and reranking. This data type is not supported in Gemini API. */\nexport declare interface RagRetrievalConfigRanking {\n  /** Optional. Config for LlmRanker. */\n  llmRanker?: RagRetrievalConfigRankingLlmRanker;\n  /** Optional. Config for Rank Service. */\n  rankService?: RagRetrievalConfigRankingRankService;\n}\n\n/** Specifies the context retrieval config. This data type is not supported in Gemini API. */\nexport declare interface RagRetrievalConfig {\n  /** Optional. Config for filters. */\n  filter?: RagRetrievalConfigFilter;\n  /** Optional. Config for Hybrid Search. */\n  hybridSearch?: RagRetrievalConfigHybridSearch;\n  /** Optional. Config for ranking and reranking. */\n  ranking?: RagRetrievalConfigRanking;\n  /** Optional. The number of contexts to retrieve. */\n  topK?: number;\n}\n\n/** Retrieve from Vertex RAG Store for grounding. This data type is not supported in Gemini API. */\nexport declare interface VertexRagStore {\n  /** Optional. Deprecated. Please use rag_resources instead. */\n  ragCorpora?: string[];\n  /** Optional. The representation of the rag source. It can be used to specify corpus only or ragfiles. Currently only support one corpus or multiple files from one corpus. In the future we may open up multiple corpora support. */\n  ragResources?: VertexRagStoreRagResource[];\n  /** Optional. The retrieval config for the Rag query. */\n  ragRetrievalConfig?: RagRetrievalConfig;\n  /** Optional. Number of top k results to return from the selected corpora. */\n  similarityTopK?: number;\n  /** Optional. Currently only supported for Gemini Multimodal Live API. In Gemini Multimodal Live API, if `store_context` bool is specified, Gemini will leverage it to automatically memorize the interactions between the client and Gemini, and retrieve context when needed to augment the response generation for users' ongoing and future interactions. */\n  storeContext?: boolean;\n  /** Optional. Only return results with vector distance smaller than the threshold. */\n  vectorDistanceThreshold?: number;\n}\n\n/** Defines a retrieval tool that model can call to access external knowledge. This data type is not supported in Gemini API. */\nexport declare interface Retrieval {\n  /** Optional. Deprecated. This option is no longer supported. */\n  disableAttribution?: boolean;\n  /** Use data source powered by external API for grounding. */\n  externalApi?: ExternalApi;\n  /** Set to use data source powered by Vertex AI Search. */\n  vertexAiSearch?: VertexAISearch;\n  /** Set to use data source powered by Vertex RAG store. User data is uploaded via the VertexRagDataService. */\n  vertexRagStore?: VertexRagStore;\n}\n\n/** Tool that executes code generated by the model, and automatically returns the result to the model. See also [ExecutableCode]and [CodeExecutionResult] which are input and output to this tool. This data type is not supported in Gemini API. */\nexport declare interface ToolCodeExecution {}\n\n/** Tool to search public web data, powered by Vertex AI Search and Sec4 compliance. This data type is not supported in Gemini API. */\nexport declare interface EnterpriseWebSearch {\n  /** Optional. List of domains to be excluded from the search results. The default limit is 2000 domains. */\n  excludeDomains?: string[];\n  /** Optional. Sites with confidence level chosen & above this value will be blocked from the search results. */\n  blockingConfidence?: PhishBlockThreshold;\n}\n\n/** Tool to retrieve public maps data for grounding, powered by Google. */\nexport declare interface GoogleMaps {\n  /** The authentication config to access the API. Only API key is supported. This field is not supported in Gemini API. */\n  authConfig?: AuthConfig;\n  /** Optional. If true, include the widget context token in the response. */\n  enableWidget?: boolean;\n}\n\n/** Represents a time interval, encoded as a Timestamp start (inclusive) and a Timestamp end (exclusive). The start must be less than or equal to the end. When the start equals the end, the interval is empty (matches no time). When both start and end are unspecified, the interval matches any time. */\nexport declare interface Interval {\n  /** Optional. Exclusive end of the interval. If specified, a Timestamp matching this interval will have to be before the end. */\n  endTime?: string;\n  /** Optional. Inclusive start of the interval. If specified, a Timestamp matching this interval will have to be the same or after the start. */\n  startTime?: string;\n}\n\n/** GoogleSearch tool type. Tool to support Google Search in Model. Powered by Google. */\nexport declare interface GoogleSearch {\n  /** Optional. List of domains to be excluded from the search results. The default limit is 2000 domains. Example: [\"amazon.com\", \"facebook.com\"]. This field is not supported in Gemini API. */\n  excludeDomains?: string[];\n  /** Optional. Sites with confidence level chosen & above this value will be blocked from the search results. This field is not supported in Gemini API. */\n  blockingConfidence?: PhishBlockThreshold;\n  /** Optional. Filter search results to a specific time range. If customers set a start time, they must set an end time (and vice versa). This field is not supported in Vertex AI. */\n  timeRangeFilter?: Interval;\n}\n\n/** Tool to support URL context. */\nexport declare interface UrlContext {}\n\n/** Tool details of a tool that the model may use to generate a response. */\nexport declare interface Tool {\n  /** List of function declarations that the tool supports. */\n  functionDeclarations?: FunctionDeclaration[];\n  /** Optional. Retrieval tool type. System will always execute the provided retrieval tool(s) to get external knowledge to answer the prompt. Retrieval results are presented to the model for generation. This field is not supported in Gemini API. */\n  retrieval?: Retrieval;\n  /** Optional. Specialized retrieval tool that is powered by Google Search. */\n  googleSearchRetrieval?: GoogleSearchRetrieval;\n  /** Optional. Tool to support the model interacting directly with the\n      computer. If enabled, it automatically populates computer-use specific\n      Function Declarations. */\n  computerUse?: ComputerUse;\n  /** Optional. Tool to retrieve knowledge from the File Search Stores. */\n  fileSearch?: FileSearch;\n  /** Optional. CodeExecution tool type. Enables the model to execute code as part of generation. */\n  codeExecution?: ToolCodeExecution;\n  /** Optional. Tool to support searching public web data, powered by Vertex AI Search and Sec4 compliance. This field is not supported in Gemini API. */\n  enterpriseWebSearch?: EnterpriseWebSearch;\n  /** Optional. GoogleMaps tool type. Tool to support Google Maps in Model. */\n  googleMaps?: GoogleMaps;\n  /** Optional. GoogleSearch tool type. Tool to support Google Search in Model. Powered by Google. */\n  googleSearch?: GoogleSearch;\n  /** Optional. Tool to support URL context retrieval. */\n  urlContext?: UrlContext;\n}\n\n/** Function calling config. */\nexport declare interface FunctionCallingConfig {\n  /** Optional. Function calling mode. */\n  mode?: FunctionCallingConfigMode;\n  /** Optional. Function names to call. Only set when the Mode is ANY. Function names should match [FunctionDeclaration.name]. With mode set to ANY, model will predict a function call from the set of function names provided. */\n  allowedFunctionNames?: string[];\n  /** Optional. When set to true, arguments of a single function call will be streamed out in multiple parts/contents/responses. Partial parameter results will be returned in the [FunctionCall.partial_args] field. This field is not supported in Gemini API. */\n  streamFunctionCallArguments?: boolean;\n}\n\n/** An object that represents a latitude/longitude pair.\n\nThis is expressed as a pair of doubles to represent degrees latitude and\ndegrees longitude. Unless specified otherwise, this object must conform to the\n<a href=\"https://en.wikipedia.org/wiki/World_Geodetic_System#1984_version\">\nWGS84 standard</a>. Values must be within normalized ranges. */\nexport declare interface LatLng {\n  /** The latitude in degrees. It must be in the range [-90.0, +90.0]. */\n  latitude?: number;\n  /** The longitude in degrees. It must be in the range [-180.0, +180.0] */\n  longitude?: number;\n}\n\n/** Retrieval config.\n */\nexport declare interface RetrievalConfig {\n  /** Optional. The location of the user. */\n  latLng?: LatLng;\n  /** The language code of the user. */\n  languageCode?: string;\n}\n\n/** Tool config.\n\nThis config is shared for all tools provided in the request. */\nexport declare interface ToolConfig {\n  /** Optional. Function calling config. */\n  functionCallingConfig?: FunctionCallingConfig;\n  /** Optional. Retrieval config. */\n  retrievalConfig?: RetrievalConfig;\n}\n\n/** ReplicatedVoiceConfig is used to configure replicated voice. */\nexport declare interface ReplicatedVoiceConfig {\n  /** The mime type of the replicated voice.\n   */\n  mimeType?: string;\n  /** The sample audio of the replicated voice.\n      \n  * @remarks Encoded as base64 string. */\n  voiceSampleAudio?: string;\n}\n\n/** The configuration for the prebuilt speaker to use. */\nexport declare interface PrebuiltVoiceConfig {\n  /** The name of the preset voice to use. */\n  voiceName?: string;\n}\n\nexport declare interface VoiceConfig {\n  /** If true, the model will use a replicated voice for the response. */\n  replicatedVoiceConfig?: ReplicatedVoiceConfig;\n  /** The configuration for the prebuilt voice to use. */\n  prebuiltVoiceConfig?: PrebuiltVoiceConfig;\n}\n\n/** Configuration for a single speaker in a multi speaker setup. */\nexport declare interface SpeakerVoiceConfig {\n  /** Required. The name of the speaker. This should be the same as the speaker name used in the prompt. */\n  speaker?: string;\n  /** Required. The configuration for the voice of this speaker. */\n  voiceConfig?: VoiceConfig;\n}\n\n/** The configuration for the multi-speaker setup. This data type is not supported in Vertex AI. */\nexport declare interface MultiSpeakerVoiceConfig {\n  /** Required. All the enabled speaker voices. */\n  speakerVoiceConfigs?: SpeakerVoiceConfig[];\n}\n\nexport declare interface SpeechConfig {\n  /** Configuration for the voice of the response. */\n  voiceConfig?: VoiceConfig;\n  /** Optional. Language code (ISO 639. e.g. en-US) for the speech synthesization. */\n  languageCode?: string;\n  /** Optional. The configuration for the multi-speaker setup. It is mutually exclusive with the voice_config field. This field is not supported in Vertex AI. */\n  multiSpeakerVoiceConfig?: MultiSpeakerVoiceConfig;\n}\n\n/** The configuration for automatic function calling. */\nexport declare interface AutomaticFunctionCallingConfig {\n  /** Whether to disable automatic function calling.\n      If not set or set to False, will enable automatic function calling.\n      If set to True, will disable automatic function calling.\n       */\n  disable?: boolean;\n  /** If automatic function calling is enabled,\n      maximum number of remote calls for automatic function calling.\n      This number should be a positive integer.\n      If not set, SDK will set maximum number of remote calls to 10.\n       */\n  maximumRemoteCalls?: number;\n  /** If automatic function calling is enabled,\n      whether to ignore call history to the response.\n      If not set, SDK will set ignore_call_history to false,\n      and will append the call history to\n      GenerateContentResponse.automatic_function_calling_history.\n       */\n  ignoreCallHistory?: boolean;\n}\n\n/** The thinking features configuration. */\nexport declare interface ThinkingConfig {\n  /** Indicates whether to include thoughts in the response. If true, thoughts are returned only if the model supports thought and thoughts are available.\n   */\n  includeThoughts?: boolean;\n  /** Indicates the thinking budget in tokens. 0 is DISABLED. -1 is AUTOMATIC. The default values and allowed ranges are model dependent.\n   */\n  thinkingBudget?: number;\n  /** Optional. The level of thoughts tokens that the model should generate. */\n  thinkingLevel?: ThinkingLevel;\n}\n\n/** The image generation configuration to be used in GenerateContentConfig. */\nexport declare interface ImageConfig {\n  /** Aspect ratio of the generated images. Supported values are\n      \"1:1\", \"2:3\", \"3:2\", \"3:4\", \"4:3\", \"9:16\", \"16:9\", and \"21:9\". */\n  aspectRatio?: string;\n  /** Optional. Specifies the size of generated images. Supported\n      values are `1K`, `2K`, `4K`. If not specified, the model will use default\n      value `1K`. */\n  imageSize?: string;\n  /** MIME type of the generated image. This field is not\n      supported in Gemini API. */\n  outputMimeType?: string;\n  /** Compression quality of the generated image (for\n      ``image/jpeg`` only). This field is not supported in Gemini API. */\n  outputCompressionQuality?: number;\n}\n\n/** When automated routing is specified, the routing will be determined by the pretrained routing model and customer provided model routing preference. This data type is not supported in Gemini API. */\nexport declare interface GenerationConfigRoutingConfigAutoRoutingMode {\n  /** The model routing preference. */\n  modelRoutingPreference?:\n    | 'UNKNOWN'\n    | 'PRIORITIZE_QUALITY'\n    | 'BALANCED'\n    | 'PRIORITIZE_COST';\n}\n\n/** When manual routing is set, the specified model will be used directly. This data type is not supported in Gemini API. */\nexport declare interface GenerationConfigRoutingConfigManualRoutingMode {\n  /** The model name to use. Only the public LLM models are accepted. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#supported-models). */\n  modelName?: string;\n}\n\n/** The configuration for routing the request to a specific model. This data type is not supported in Gemini API. */\nexport declare interface GenerationConfigRoutingConfig {\n  /** Automated routing. */\n  autoMode?: GenerationConfigRoutingConfigAutoRoutingMode;\n  /** Manual routing. */\n  manualMode?: GenerationConfigRoutingConfigManualRoutingMode;\n}\n\n/** Safety settings. */\nexport declare interface SafetySetting {\n  /** Required. Harm category. */\n  category?: HarmCategory;\n  /** Optional. Specify if the threshold is used for probability or severity score. If not specified, the threshold is used for probability score. This field is not supported in Gemini API. */\n  method?: HarmBlockMethod;\n  /** Required. The harm block threshold. */\n  threshold?: HarmBlockThreshold;\n}\n\n/** Optional model configuration parameters.\n\nFor more information, see `Content generation parameters\n<https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/content-generation-parameters>`_. */\nexport declare interface GenerateContentConfig {\n  /** Used to override HTTP request options. */\n  httpOptions?: HttpOptions;\n  /** Abort signal which can be used to cancel the request.\n\n  NOTE: AbortSignal is a client-only operation. Using it to cancel an\n  operation will not cancel the request in the service. You will still\n  be charged usage for any applicable operations.\n       */\n  abortSignal?: AbortSignal;\n  /** Instructions for the model to steer it toward better performance.\n      For example, \"Answer as concisely as possible\" or \"Don't use technical\n      terms in your response\".\n       */\n  systemInstruction?: ContentUnion;\n  /** Value that controls the degree of randomness in token selection.\n      Lower temperatures are good for prompts that require a less open-ended or\n      creative response, while higher temperatures can lead to more diverse or\n      creative results.\n       */\n  temperature?: number;\n  /** Tokens are selected from the most to least probable until the sum\n      of their probabilities equals this value. Use a lower value for less\n      random responses and a higher value for more random responses.\n       */\n  topP?: number;\n  /** For each token selection step, the ``top_k`` tokens with the\n      highest probabilities are sampled. Then tokens are further filtered based\n      on ``top_p`` with the final token selected using temperature sampling. Use\n      a lower number for less random responses and a higher number for more\n      random responses.\n       */\n  topK?: number;\n  /** Number of response variations to return.\n   */\n  candidateCount?: number;\n  /** Maximum number of tokens that can be generated in the response.\n   */\n  maxOutputTokens?: number;\n  /** List of strings that tells the model to stop generating text if one\n      of the strings is encountered in the response.\n       */\n  stopSequences?: string[];\n  /** Whether to return the log probabilities of the tokens that were\n      chosen by the model at each step.\n       */\n  responseLogprobs?: boolean;\n  /** Number of top candidate tokens to return the log probabilities for\n      at each generation step.\n       */\n  logprobs?: number;\n  /** Positive values penalize tokens that already appear in the\n      generated text, increasing the probability of generating more diverse\n      content.\n       */\n  presencePenalty?: number;\n  /** Positive values penalize tokens that repeatedly appear in the\n      generated text, increasing the probability of generating more diverse\n      content.\n       */\n  frequencyPenalty?: number;\n  /** When ``seed`` is fixed to a specific number, the model makes a best\n      effort to provide the same response for repeated requests. By default, a\n      random number is used.\n       */\n  seed?: number;\n  /** Output response mimetype of the generated candidate text.\n      Supported mimetype:\n        - `text/plain`: (default) Text output.\n        - `application/json`: JSON response in the candidates.\n      The model needs to be prompted to output the appropriate response type,\n      otherwise the behavior is undefined.\n      This is a preview feature.\n       */\n  responseMimeType?: string;\n  /** The `Schema` object allows the definition of input and output data types.\n      These types can be objects, but also primitives and arrays.\n      Represents a select subset of an [OpenAPI 3.0 schema\n      object](https://spec.openapis.org/oas/v3.0.3#schema).\n      If set, a compatible response_mime_type must also be set.\n      Compatible mimetypes: `application/json`: Schema for JSON response.\n\n      If `response_schema` doesn't process your schema correctly, try using\n      `response_json_schema` instead.\n       */\n  responseSchema?: SchemaUnion;\n  /** Optional. Output schema of the generated response.\n      This is an alternative to `response_schema` that accepts [JSON\n      Schema](https://json-schema.org/). If set, `response_schema` must be\n      omitted, but `response_mime_type` is required. While the full JSON Schema\n      may be sent, not all features are supported. Specifically, only the\n      following properties are supported: - `$id` - `$defs` - `$ref` - `$anchor`\n      - `type` - `format` - `title` - `description` - `enum` (for strings and\n      numbers) - `items` - `prefixItems` - `minItems` - `maxItems` - `minimum` -\n      `maximum` - `anyOf` - `oneOf` (interpreted the same as `anyOf`) -\n      `properties` - `additionalProperties` - `required` The non-standard\n      `propertyOrdering` property may also be set. Cyclic references are\n      unrolled to a limited degree and, as such, may only be used within\n      non-required properties. (Nullable properties are not sufficient.) If\n      `$ref` is set on a sub-schema, no other properties, except for than those\n      starting as a `$`, may be set. */\n  responseJsonSchema?: unknown;\n  /** Configuration for model router requests.\n   */\n  routingConfig?: GenerationConfigRoutingConfig;\n  /** Configuration for model selection.\n   */\n  modelSelectionConfig?: ModelSelectionConfig;\n  /** Safety settings in the request to block unsafe content in the\n      response.\n       */\n  safetySettings?: SafetySetting[];\n  /** Code that enables the system to interact with external systems to\n      perform an action outside of the knowledge and scope of the model.\n       */\n  tools?: ToolListUnion;\n  /** Associates model output to a specific function call.\n   */\n  toolConfig?: ToolConfig;\n  /** Labels with user-defined metadata to break down billed charges. */\n  labels?: Record<string, string>;\n  /** Resource name of a context cache that can be used in subsequent\n      requests.\n       */\n  cachedContent?: string;\n  /** The requested modalities of the response. Represents the set of\n      modalities that the model can return.\n       */\n  responseModalities?: string[];\n  /** If specified, the media resolution specified will be used.\n   */\n  mediaResolution?: MediaResolution;\n  /** The speech generation configuration.\n   */\n  speechConfig?: SpeechConfigUnion;\n  /** If enabled, audio timestamp will be included in the request to the\n       model.\n       */\n  audioTimestamp?: boolean;\n  /** The configuration for automatic function calling.\n   */\n  automaticFunctionCalling?: AutomaticFunctionCallingConfig;\n  /** The thinking features configuration.\n   */\n  thinkingConfig?: ThinkingConfig;\n  /** The image generation configuration.\n   */\n  imageConfig?: ImageConfig;\n  /** Enables enhanced civic answers. It may not be available for all\n      models. This field is not supported in Vertex AI.\n       */\n  enableEnhancedCivicAnswers?: boolean;\n}\n\n/** Config for models.generate_content parameters. */\nexport declare interface GenerateContentParameters {\n  /** ID of the model to use. For a list of models, see `Google models\n    <https://cloud.google.com/vertex-ai/generative-ai/docs/learn/models>`_. */\n  model: string;\n  /** Content of the request.\n   */\n  contents: ContentListUnion;\n  /** Configuration that contains optional model parameters.\n   */\n  config?: GenerateContentConfig;\n}\n\n/** A wrapper class for the http response. */\nexport class HttpResponse {\n  /** Used to retain the processed HTTP headers in the response. */\n  headers?: Record<string, string>;\n  /**\n   * The original http response.\n   */\n  responseInternal: Response;\n\n  constructor(response: Response) {\n    // Process the headers.\n    const headers: Record<string, string> = {};\n    for (const pair of response.headers.entries()) {\n      headers[pair[0]] = pair[1];\n    }\n    this.headers = headers;\n\n    // Keep the original response.\n    this.responseInternal = response;\n  }\n\n  json(): Promise<unknown> {\n    return this.responseInternal.json();\n  }\n}\n\n/** Callbacks for the live API. */\nexport interface LiveCallbacks {\n  /**\n   * Called when the websocket connection is established.\n   */\n  onopen?: (() => void) | null;\n  /**\n   * Called when a message is received from the server.\n   */\n  onmessage: (e: LiveServerMessage) => void;\n  /**\n   * Called when an error occurs.\n   */\n  onerror?: ((e: ErrorEvent) => void) | null;\n  /**\n   * Called when the websocket connection is closed.\n   */\n  onclose?: ((e: CloseEvent) => void) | null;\n}\n\n/** Represents a whole or partial calendar date, such as a birthday. The time of day and time zone are either specified elsewhere or are insignificant. The date is relative to the Gregorian Calendar. This can represent one of the following: * A full date, with non-zero year, month, and day values. * A month and day, with a zero year (for example, an anniversary). * A year on its own, with a zero month and a zero day. * A year and month, with a zero day (for example, a credit card expiration date). Related types: * google.type.TimeOfDay * google.type.DateTime * google.protobuf.Timestamp. This data type is not supported in Gemini API. */\nexport declare interface GoogleTypeDate {\n  /** Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a year and month where the day isn't significant. */\n  day?: number;\n  /** Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day. */\n  month?: number;\n  /** Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year. */\n  year?: number;\n}\n\n/** Source attributions for content. This data type is not supported in Gemini API. */\nexport declare interface Citation {\n  /** Output only. End index into the content. */\n  endIndex?: number;\n  /** Output only. License of the attribution. */\n  license?: string;\n  /** Output only. Publication date of the attribution. */\n  publicationDate?: GoogleTypeDate;\n  /** Output only. Start index into the content. */\n  startIndex?: number;\n  /** Output only. Title of the attribution. */\n  title?: string;\n  /** Output only. Url reference of the attribution. */\n  uri?: string;\n}\n\n/** Citation information when the model quotes another source. */\nexport declare interface CitationMetadata {\n  /** Contains citation information when the model directly quotes, at\n      length, from another source. Can include traditional websites and code\n      repositories.\n       */\n  citations?: Citation[];\n}\n\n/** Author attribution for a photo or review. This data type is not supported in Gemini API. */\nexport declare interface GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution {\n  /** Name of the author of the Photo or Review. */\n  displayName?: string;\n  /** Profile photo URI of the author of the Photo or Review. */\n  photoUri?: string;\n  /** URI of the author of the Photo or Review. */\n  uri?: string;\n}\n\n/** Encapsulates a review snippet. This data type is not supported in Gemini API. */\nexport declare interface GroundingChunkMapsPlaceAnswerSourcesReviewSnippet {\n  /** This review's author. */\n  authorAttribution?: GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution;\n  /** A link where users can flag a problem with the review. */\n  flagContentUri?: string;\n  /** A link to show the review on Google Maps. */\n  googleMapsUri?: string;\n  /** A string of formatted recent time, expressing the review time relative to the current time in a form appropriate for the language and country. */\n  relativePublishTimeDescription?: string;\n  /** A reference representing this place review which may be used to look up this place review again. */\n  review?: string;\n  /** Id of the review referencing the place. */\n  reviewId?: string;\n  /** Title of the review. */\n  title?: string;\n}\n\n/** Sources used to generate the place answer. This data type is not supported in Gemini API. */\nexport declare interface GroundingChunkMapsPlaceAnswerSources {\n  /** A link where users can flag a problem with the generated answer. */\n  flagContentUri?: string;\n  /** Snippets of reviews that are used to generate the answer. */\n  reviewSnippets?: GroundingChunkMapsPlaceAnswerSourcesReviewSnippet[];\n}\n\n/** Chunk from Google Maps. This data type is not supported in Gemini API. */\nexport declare interface GroundingChunkMaps {\n  /** Sources used to generate the place answer. This includes review snippets and photos that were used to generate the answer, as well as uris to flag content. */\n  placeAnswerSources?: GroundingChunkMapsPlaceAnswerSources;\n  /** This Place's resource name, in `places/{place_id}` format. Can be used to look up the Place. */\n  placeId?: string;\n  /** Text of the place answer. */\n  text?: string;\n  /** Title of the place. */\n  title?: string;\n  /** URI reference of the place. */\n  uri?: string;\n}\n\n/** Represents where the chunk starts and ends in the document. This data type is not supported in Gemini API. */\nexport declare interface RagChunkPageSpan {\n  /** Page where chunk starts in the document. Inclusive. 1-indexed. */\n  firstPage?: number;\n  /** Page where chunk ends in the document. Inclusive. 1-indexed. */\n  lastPage?: number;\n}\n\n/** A RagChunk includes the content of a chunk of a RagFile, and associated metadata. This data type is not supported in Gemini API. */\nexport declare interface RagChunk {\n  /** If populated, represents where the chunk starts and ends in the document. */\n  pageSpan?: RagChunkPageSpan;\n  /** The content of the chunk. */\n  text?: string;\n}\n\n/** Chunk from context retrieved by the retrieval tools. This data type is not supported in Gemini API. */\nexport declare interface GroundingChunkRetrievedContext {\n  /** Output only. The full document name for the referenced Vertex AI Search document. */\n  documentName?: string;\n  /** Additional context for the RAG retrieval result. This is only populated when using the RAG retrieval tool. */\n  ragChunk?: RagChunk;\n  /** Text of the attribution. */\n  text?: string;\n  /** Title of the attribution. */\n  title?: string;\n  /** URI reference of the attribution. */\n  uri?: string;\n}\n\n/** Chunk from the web. */\nexport declare interface GroundingChunkWeb {\n  /** Domain of the (original) URI. This field is not supported in Gemini API. */\n  domain?: string;\n  /** Title of the chunk. */\n  title?: string;\n  /** URI reference of the chunk. */\n  uri?: string;\n}\n\n/** Grounding chunk. */\nexport declare interface GroundingChunk {\n  /** Grounding chunk from Google Maps. This field is not supported in Gemini API. */\n  maps?: GroundingChunkMaps;\n  /** Grounding chunk from context retrieved by the retrieval tools. This field is not supported in Gemini API. */\n  retrievedContext?: GroundingChunkRetrievedContext;\n  /** Grounding chunk from the web. */\n  web?: GroundingChunkWeb;\n}\n\n/** Segment of the content. */\nexport declare interface Segment {\n  /** Output only. End index in the given Part, measured in bytes. Offset from the start of the Part, exclusive, starting at zero. */\n  endIndex?: number;\n  /** Output only. The index of a Part object within its parent Content object. */\n  partIndex?: number;\n  /** Output only. Start index in the given Part, measured in bytes. Offset from the start of the Part, inclusive, starting at zero. */\n  startIndex?: number;\n  /** Output only. The text corresponding to the segment from the response. */\n  text?: string;\n}\n\n/** Grounding support. */\nexport declare interface GroundingSupport {\n  /** Confidence score of the support references. Ranges from 0 to 1. 1 is the most confident. For Gemini 2.0 and before, this list must have the same size as the grounding_chunk_indices. For Gemini 2.5 and after, this list will be empty and should be ignored. */\n  confidenceScores?: number[];\n  /** A list of indices (into 'grounding_chunk') specifying the citations associated with the claim. For instance [1,3,4] means that grounding_chunk[1], grounding_chunk[3], grounding_chunk[4] are the retrieved content attributed to the claim. */\n  groundingChunkIndices?: number[];\n  /** Segment of the content this support belongs to. */\n  segment?: Segment;\n}\n\n/** Metadata related to retrieval in the grounding flow. */\nexport declare interface RetrievalMetadata {\n  /** Optional. Score indicating how likely information from Google Search could help answer the prompt. The score is in the range `[0, 1]`, where 0 is the least likely and 1 is the most likely. This score is only populated when Google Search grounding and dynamic retrieval is enabled. It will be compared to the threshold to determine whether to trigger Google Search. */\n  googleSearchDynamicRetrievalScore?: number;\n}\n\n/** Google search entry point. */\nexport declare interface SearchEntryPoint {\n  /** Optional. Web content snippet that can be embedded in a web page or an app webview. */\n  renderedContent?: string;\n  /** Optional. Base64 encoded JSON representing array of tuple.\n   * @remarks Encoded as base64 string. */\n  sdkBlob?: string;\n}\n\n/** Source content flagging uri for a place or review. This is currently populated only for Google Maps grounding. This data type is not supported in Gemini API. */\nexport declare interface GroundingMetadataSourceFlaggingUri {\n  /** A link where users can flag a problem with the source (place or review). */\n  flagContentUri?: string;\n  /** Id of the place or review. */\n  sourceId?: string;\n}\n\n/** Metadata returned to client when grounding is enabled. */\nexport declare interface GroundingMetadata {\n  /** Optional. Output only. Resource name of the Google Maps widget context token to be used with the PlacesContextElement widget to render contextual data. This is populated only for Google Maps grounding. This field is not supported in Gemini API. */\n  googleMapsWidgetContextToken?: string;\n  /** List of supporting references retrieved from specified grounding source. */\n  groundingChunks?: GroundingChunk[];\n  /** Optional. List of grounding support. */\n  groundingSupports?: GroundingSupport[];\n  /** Optional. Output only. Retrieval metadata. */\n  retrievalMetadata?: RetrievalMetadata;\n  /** Optional. Queries executed by the retrieval tools. This field is not supported in Gemini API. */\n  retrievalQueries?: string[];\n  /** Optional. Google search entry for the following-up web searches. */\n  searchEntryPoint?: SearchEntryPoint;\n  /** Optional. Output only. List of source flagging uris. This is currently populated only for Google Maps grounding. This field is not supported in Gemini API. */\n  sourceFlaggingUris?: GroundingMetadataSourceFlaggingUri[];\n  /** Optional. Web search queries for the following-up web search. */\n  webSearchQueries?: string[];\n}\n\n/** Candidate for the logprobs token and score. */\nexport declare interface LogprobsResultCandidate {\n  /** The candidate's log probability. */\n  logProbability?: number;\n  /** The candidate's token string value. */\n  token?: string;\n  /** The candidate's token id value. */\n  tokenId?: number;\n}\n\n/** Candidates with top log probabilities at each decoding step. */\nexport declare interface LogprobsResultTopCandidates {\n  /** Sorted by log probability in descending order. */\n  candidates?: LogprobsResultCandidate[];\n}\n\n/** Logprobs Result */\nexport declare interface LogprobsResult {\n  /** Length = total number of decoding steps. The chosen candidates may or may not be in top_candidates. */\n  chosenCandidates?: LogprobsResultCandidate[];\n  /** Length = total number of decoding steps. */\n  topCandidates?: LogprobsResultTopCandidates[];\n}\n\n/** Safety rating corresponding to the generated content. */\nexport declare interface SafetyRating {\n  /** Output only. Indicates whether the content was filtered out because of this rating. */\n  blocked?: boolean;\n  /** Output only. Harm category. */\n  category?: HarmCategory;\n  /** Output only. The overwritten threshold for the safety category of Gemini 2.0 image out. If minors are detected in the output image, the threshold of each safety category will be overwritten if user sets a lower threshold. This field is not supported in Gemini API. */\n  overwrittenThreshold?: HarmBlockThreshold;\n  /** Output only. Harm probability levels in the content. */\n  probability?: HarmProbability;\n  /** Output only. Harm probability score. This field is not supported in Gemini API. */\n  probabilityScore?: number;\n  /** Output only. Harm severity levels in the content. This field is not supported in Gemini API. */\n  severity?: HarmSeverity;\n  /** Output only. Harm severity score. This field is not supported in Gemini API. */\n  severityScore?: number;\n}\n\n/** Context of the a single url retrieval. */\nexport declare interface UrlMetadata {\n  /** Retrieved url by the tool. */\n  retrievedUrl?: string;\n  /** Status of the url retrieval. */\n  urlRetrievalStatus?: UrlRetrievalStatus;\n}\n\n/** Metadata related to url context retrieval tool. */\nexport declare interface UrlContextMetadata {\n  /** Output only. List of url context. */\n  urlMetadata?: UrlMetadata[];\n}\n\n/** A response candidate generated from the model. */\nexport declare interface Candidate {\n  /** Contains the multi-part content of the response.\n   */\n  content?: Content;\n  /** Source attribution of the generated content.\n   */\n  citationMetadata?: CitationMetadata;\n  /** Describes the reason the model stopped generating tokens.\n   */\n  finishMessage?: string;\n  /** Number of tokens for this candidate.\n   */\n  tokenCount?: number;\n  /** The reason why the model stopped generating tokens.\n      If empty, the model has not stopped generating the tokens.\n       */\n  finishReason?: FinishReason;\n  /** Output only. Average log probability score of the candidate. */\n  avgLogprobs?: number;\n  /** Output only. Metadata specifies sources used to ground generated content. */\n  groundingMetadata?: GroundingMetadata;\n  /** Output only. Index of the candidate. */\n  index?: number;\n  /** Output only. Log-likelihood scores for the response tokens and top tokens */\n  logprobsResult?: LogprobsResult;\n  /** Output only. List of ratings for the safety of a response candidate. There is at most one rating per category. */\n  safetyRatings?: SafetyRating[];\n  /** Output only. Metadata related to url context retrieval tool. */\n  urlContextMetadata?: UrlContextMetadata;\n}\n\n/** Content filter results for a prompt sent in the request. Note: This is sent only in the first stream chunk and only if no candidates were generated due to content violations. */\nexport class GenerateContentResponsePromptFeedback {\n  /** Output only. The reason why the prompt was blocked. */\n  blockReason?: BlockedReason;\n  /** Output only. A readable message that explains the reason why the prompt was blocked. This field is not supported in Gemini API. */\n  blockReasonMessage?: string;\n  /** Output only. A list of safety ratings for the prompt. There is one rating per category. */\n  safetyRatings?: SafetyRating[];\n}\n\n/** Represents token counting info for a single modality. */\nexport declare interface ModalityTokenCount {\n  /** The modality associated with this token count. */\n  modality?: MediaModality;\n  /** Number of tokens. */\n  tokenCount?: number;\n}\n\n/** Usage metadata about the content generation request and response. This message provides a detailed breakdown of token usage and other relevant metrics. This data type is not supported in Gemini API. */\nexport class GenerateContentResponseUsageMetadata {\n  /** Output only. A detailed breakdown of the token count for each modality in the cached content. */\n  cacheTokensDetails?: ModalityTokenCount[];\n  /** Output only. The number of tokens in the cached content that was used for this request. */\n  cachedContentTokenCount?: number;\n  /** The total number of tokens in the generated candidates. */\n  candidatesTokenCount?: number;\n  /** Output only. A detailed breakdown of the token count for each modality in the generated candidates. */\n  candidatesTokensDetails?: ModalityTokenCount[];\n  /** The total number of tokens in the prompt. This includes any text, images, or other media provided in the request. When `cached_content` is set, this also includes the number of tokens in the cached content. */\n  promptTokenCount?: number;\n  /** Output only. A detailed breakdown of the token count for each modality in the prompt. */\n  promptTokensDetails?: ModalityTokenCount[];\n  /** Output only. The number of tokens that were part of the model's generated \"thoughts\" output, if applicable. */\n  thoughtsTokenCount?: number;\n  /** Output only. The number of tokens in the results from tool executions, which are provided back to the model as input, if applicable. */\n  toolUsePromptTokenCount?: number;\n  /** Output only. A detailed breakdown by modality of the token counts from the results of tool executions, which are provided back to the model as input. */\n  toolUsePromptTokensDetails?: ModalityTokenCount[];\n  /** The total number of tokens for the entire request. This is the sum of `prompt_token_count`, `candidates_token_count`, `tool_use_prompt_token_count`, and `thoughts_token_count`. */\n  totalTokenCount?: number;\n  /** Output only. The traffic type for this request. */\n  trafficType?: TrafficType;\n}\n\n/** Response message for PredictionService.GenerateContent. */\nexport class GenerateContentResponse {\n  /** Used to retain the full HTTP response. */\n  sdkHttpResponse?: HttpResponse;\n  /** Response variations returned by the model.\n   */\n  candidates?: Candidate[];\n  /** Timestamp when the request is made to the server.\n   */\n  createTime?: string;\n  /** The history of automatic function calling.\n   */\n  automaticFunctionCallingHistory?: Content[];\n  /** Output only. The model version used to generate the response. */\n  modelVersion?: string;\n  /** Output only. Content filter results for a prompt sent in the request. Note: Sent only in the first stream chunk. Only happens when no candidates were generated due to content violations. */\n  promptFeedback?: GenerateContentResponsePromptFeedback;\n  /** Output only. response_id is used to identify each response. It is the encoding of the event_id. */\n  responseId?: string;\n  /** Usage metadata about the response(s). */\n  usageMetadata?: GenerateContentResponseUsageMetadata;\n  /**\n   * Returns the concatenation of all text parts from the first candidate in the response.\n   *\n   * @remarks\n   * If there are multiple candidates in the response, the text from the first\n   * one will be returned.\n   * If there are non-text parts in the response, the concatenation of all text\n   * parts will be returned, and a warning will be logged.\n   * If there are thought parts in the response, the concatenation of all text\n   * parts excluding the thought parts will be returned.\n   *\n   * @example\n   * ```ts\n   * const response = await ai.models.generateContent({\n   *   model: 'gemini-2.0-flash',\n   *   contents:\n   *     'Why is the sky blue?',\n   * });\n   *\n   * console.debug(response.text);\n   * ```\n   */\n  get text(): string | undefined {\n    if (this.candidates?.[0]?.content?.parts?.length === 0) {\n      return undefined;\n    }\n    if (this.candidates && this.candidates.length > 1) {\n      console.warn(\n        'there are multiple candidates in the response, returning text from the first one.',\n      );\n    }\n    let text = '';\n    let anyTextPartText = false;\n    const nonTextParts = [];\n    for (const part of this.candidates?.[0]?.content?.parts ?? []) {\n      for (const [fieldName, fieldValue] of Object.entries(part)) {\n        if (\n          fieldName !== 'text' &&\n          fieldName !== 'thought' &&\n          fieldName !== 'thoughtSignature' &&\n          (fieldValue !== null || fieldValue !== undefined)\n        ) {\n          nonTextParts.push(fieldName);\n        }\n      }\n      if (typeof part.text === 'string') {\n        if (typeof part.thought === 'boolean' && part.thought) {\n          continue;\n        }\n        anyTextPartText = true;\n        text += part.text;\n      }\n    }\n    if (nonTextParts.length > 0) {\n      console.warn(\n        `there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`,\n      );\n    }\n    // part.text === '' is different from part.text is null\n    return anyTextPartText ? text : undefined;\n  }\n\n  /**\n   * Returns the concatenation of all inline data parts from the first candidate\n   * in the response.\n   *\n   * @remarks\n   * If there are multiple candidates in the response, the inline data from the\n   * first one will be returned. If there are non-inline data parts in the\n   * response, the concatenation of all inline data parts will be returned, and\n   * a warning will be logged.\n   */\n  get data(): string | undefined {\n    if (this.candidates?.[0]?.content?.parts?.length === 0) {\n      return undefined;\n    }\n    if (this.candidates && this.candidates.length > 1) {\n      console.warn(\n        'there are multiple candidates in the response, returning data from the first one.',\n      );\n    }\n    let data = '';\n    const nonDataParts = [];\n    for (const part of this.candidates?.[0]?.content?.parts ?? []) {\n      for (const [fieldName, fieldValue] of Object.entries(part)) {\n        if (\n          fieldName !== 'inlineData' &&\n          (fieldValue !== null || fieldValue !== undefined)\n        ) {\n          nonDataParts.push(fieldName);\n        }\n      }\n      if (part.inlineData && typeof part.inlineData.data === 'string') {\n        data += atob(part.inlineData.data);\n      }\n    }\n    if (nonDataParts.length > 0) {\n      console.warn(\n        `there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`,\n      );\n    }\n    return data.length > 0 ? btoa(data) : undefined;\n  }\n\n  /**\n   * Returns the function calls from the first candidate in the response.\n   *\n   * @remarks\n   * If there are multiple candidates in the response, the function calls from\n   * the first one will be returned.\n   * If there are no function calls in the response, undefined will be returned.\n   *\n   * @example\n   * ```ts\n   * const controlLightFunctionDeclaration: FunctionDeclaration = {\n   *   name: 'controlLight',\n   *   parameters: {\n   *   type: Type.OBJECT,\n   *   description: 'Set the brightness and color temperature of a room light.',\n   *   properties: {\n   *     brightness: {\n   *       type: Type.NUMBER,\n   *       description:\n   *         'Light level from 0 to 100. Zero is off and 100 is full brightness.',\n   *     },\n   *     colorTemperature: {\n   *       type: Type.STRING,\n   *       description:\n   *         'Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.',\n   *     },\n   *   },\n   *   required: ['brightness', 'colorTemperature'],\n   *  };\n   *  const response = await ai.models.generateContent({\n   *     model: 'gemini-2.0-flash',\n   *     contents: 'Dim the lights so the room feels cozy and warm.',\n   *     config: {\n   *       tools: [{functionDeclarations: [controlLightFunctionDeclaration]}],\n   *       toolConfig: {\n   *         functionCallingConfig: {\n   *           mode: FunctionCallingConfigMode.ANY,\n   *           allowedFunctionNames: ['controlLight'],\n   *         },\n   *       },\n   *     },\n   *   });\n   *  console.debug(JSON.stringify(response.functionCalls));\n   * ```\n   */\n  get functionCalls(): FunctionCall[] | undefined {\n    if (this.candidates?.[0]?.content?.parts?.length === 0) {\n      return undefined;\n    }\n    if (this.candidates && this.candidates.length > 1) {\n      console.warn(\n        'there are multiple candidates in the response, returning function calls from the first one.',\n      );\n    }\n    const functionCalls = this.candidates?.[0]?.content?.parts\n      ?.filter((part) => part.functionCall)\n      .map((part) => part.functionCall)\n      .filter(\n        (functionCall): functionCall is FunctionCall =>\n          functionCall !== undefined,\n      );\n    if (functionCalls?.length === 0) {\n      return undefined;\n    }\n    return functionCalls;\n  }\n  /**\n   * Returns the first executable code from the first candidate in the response.\n   *\n   * @remarks\n   * If there are multiple candidates in the response, the executable code from\n   * the first one will be returned.\n   * If there are no executable code in the response, undefined will be\n   * returned.\n   *\n   * @example\n   * ```ts\n   * const response = await ai.models.generateContent({\n   *   model: 'gemini-2.0-flash',\n   *   contents:\n   *     'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.'\n   *   config: {\n   *     tools: [{codeExecution: {}}],\n   *   },\n   * });\n   *\n   * console.debug(response.executableCode);\n   * ```\n   */\n  get executableCode(): string | undefined {\n    if (this.candidates?.[0]?.content?.parts?.length === 0) {\n      return undefined;\n    }\n    if (this.candidates && this.candidates.length > 1) {\n      console.warn(\n        'there are multiple candidates in the response, returning executable code from the first one.',\n      );\n    }\n    const executableCode = this.candidates?.[0]?.content?.parts\n      ?.filter((part) => part.executableCode)\n      .map((part) => part.executableCode)\n      .filter(\n        (executableCode): executableCode is ExecutableCode =>\n          executableCode !== undefined,\n      );\n    if (executableCode?.length === 0) {\n      return undefined;\n    }\n\n    return executableCode?.[0]?.code;\n  }\n  /**\n   * Returns the first code execution result from the first candidate in the response.\n   *\n   * @remarks\n   * If there are multiple candidates in the response, the code execution result from\n   * the first one will be returned.\n   * If there are no code execution result in the response, undefined will be returned.\n   *\n   * @example\n   * ```ts\n   * const response = await ai.models.generateContent({\n   *   model: 'gemini-2.0-flash',\n   *   contents:\n   *     'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.'\n   *   config: {\n   *     tools: [{codeExecution: {}}],\n   *   },\n   * });\n   *\n   * console.debug(response.codeExecutionResult);\n   * ```\n   */\n  get codeExecutionResult(): string | undefined {\n    if (this.candidates?.[0]?.content?.parts?.length === 0) {\n      return undefined;\n    }\n    if (this.candidates && this.candidates.length > 1) {\n      console.warn(\n        'there are multiple candidates in the response, returning code execution result from the first one.',\n      );\n    }\n    const codeExecutionResult = this.candidates?.[0]?.content?.parts\n      ?.filter((part) => part.codeExecutionResult)\n      .map((part) => part.codeExecutionResult)\n      .filter(\n        (codeExecutionResult): codeExecutionResult is CodeExecutionResult =>\n          codeExecutionResult !== undefined,\n      );\n    if (codeExecutionResult?.length === 0) {\n      return undefined;\n    }\n    return codeExecutionResult?.[0]?.output;\n  }\n}\n\nexport type ReferenceImage =\n  | RawReferenceImage\n  | MaskReferenceImage\n  | ControlReferenceImage\n  | StyleReferenceImage\n  | SubjectReferenceImage\n  | ContentReferenceImage;\n\n/** Parameters for the request to edit an image. */\nexport declare interface EditImageParameters {\n  /** The model to use. */\n  model: string;\n  /** A text description of the edit to apply to the image. */\n  prompt: string;\n  /** The reference images for Imagen 3 editing. */\n  referenceImages: ReferenceImage[];\n  /** Configuration for editing. */\n  config?: EditImageConfig;\n}\n\n/** Optional parameters for the embed_content method. */\nexport declare interface EmbedContentConfig {\n  /** Used to override HTTP request options. */\n  httpOptions?: HttpOptions;\n  /** Abort signal which can be used to cancel the request.\n\n  NOTE: AbortSignal is a client-only operation. Using it to cancel an\n  operation will not cancel the request in the service. You will still\n  be charged usage for any applicable operations.\n       */\n  abortSignal?: AbortSignal;\n  /** Type of task for which the embedding will be used.\n   */\n  taskType?: string;\n  /** Title for the text. Only applicable when TaskType is\n      `RETRIEVAL_DOCUMENT`.\n       */\n  title?: string;\n  /** Reduced dimension for the output embedding. If set,\n      excessive values in the output embedding are truncated from the end.\n      Supported by newer models since 2024 only. You cannot set this value if\n      using the earlier model (`models/embedding-001`).\n       */\n  outputDimensionality?: number;\n  /** Vertex API only. The MIME type of the input.\n   */\n  mimeType?: string;\n  /** Vertex API only. Whether to silently truncate inputs longer than\n      the max sequence length. If this option is set to false, oversized inputs\n      will lead to an INVALID_ARGUMENT error, similar to other text APIs.\n       */\n  autoTruncate?: boolean;\n}\n\n/** Parameters for the embed_content method. */\nexport declare interface EmbedContentParameters {\n  /** ID of the model to use. For a list of models, see `Google models\n    <https://cloud.google.com/vertex-ai/generative-ai/docs/learn/models>`_. */\n  model: string;\n  /** The content to embed. Only the `parts.text` fields will be counted.\n   */\n  contents: ContentListUnion;\n  /** Configuration that contains optional parameters.\n   */\n  config?: EmbedContentConfig;\n}\n\n/** Statistics of the input text associated with the result of content embedding. */\nexport declare interface ContentEmbeddingStatistics {\n  /** Vertex API only. If the input text was truncated due to having\n      a length longer than the allowed maximum input.\n       */\n  truncated?: boolean;\n  /** Vertex API only. Number of tokens of the input text.\n   */\n  tokenCount?: number;\n}\n\n/** The embedding generated from an input content. */\nexport declare interface ContentEmbedding {\n  /** A list of floats representing an embedding.\n   */\n  values?: number[];\n  /** Vertex API only. Statistics of the input text associated with this\n      embedding.\n       */\n  statistics?: ContentEmbeddingStatistics;\n}\n\n/** Request-level metadata for the Vertex Embed Content API. */\nexport declare interface EmbedContentMetadata {\n  /** Vertex API only. The total number of billable characters included\n      in the request.\n       */\n  billableCharacterCount?: number;\n}\n\n/** Response for the embed_content method. */\nexport class EmbedContentResponse {\n  /** Used to retain the full HTTP response. */\n  sdkHttpResponse?: HttpResponse;\n  /** The embeddings for each request, in the same order as provided in\n      the batch request.\n       */\n  embeddings?: ContentEmbedding[];\n  /** Vertex API only. Metadata about the request.\n   */\n  metadata?: EmbedContentMetadata;\n}\n\n/** The config for generating an images. */\nexport declare interface GenerateImagesConfig {\n  /** Used to override HTTP request options. */\n  httpOptions?: HttpOptions;\n  /** Abort signal which can be used to cancel the request.\n\n  NOTE: AbortSignal is a client-only operation. Using it to cancel an\n  operation will not cancel the request in the service. You will still\n  be charged usage for any applicable operations.\n       */\n  abortSignal?: AbortSignal;\n  /** Cloud Storage URI used to store the generated images. */\n  outputGcsUri?: string;\n  /** Description of what to discourage in the generated images. */\n  negativePrompt?: string;\n  /** Number of images to generate. */\n  numberOfImages?: number;\n  /** Aspect ratio of the generated images. Supported values are\n      \"1:1\", \"3:4\", \"4:3\", \"9:16\", and \"16:9\". */\n  aspectRatio?: string;\n  /** Controls how much the model adheres to the text prompt. Large\n      values increase output and prompt alignment, but may compromise image\n      quality. */\n  guidanceScale?: number;\n  /** Random seed for image generation. This is not available when\n      ``add_watermark`` is set to true. */\n  seed?: number;\n  /** Filter level for safety filtering. */\n  safetyFilterLevel?: SafetyFilterLevel;\n  /** Allows generation of people by the model. */\n  personGeneration?: PersonGeneration;\n  /** Whether to report the safety scores of each generated image and\n      the positive prompt in the response. */\n  includeSafetyAttributes?: boolean;\n  /** Whether to include the Responsible AI filter reason if the image\n      is filtered out of the response. */\n  includeRaiReason?: boolean;\n  /** Language of the text in the prompt. */\n  language?: ImagePromptLanguage;\n  /** MIME type of the generated image. */\n  outputMimeType?: string;\n  /** Compression quality of the generated image (for ``image/jpeg``\n      only). */\n  outputCompressionQuality?: number;\n  /** Whether to add a watermark to the generated images. */\n  addWatermark?: boolean;\n  /** User specified labels to track billing usage. */\n  labels?: Record<string, string>;\n  /** The size of the largest dimension of the generated image.\n      Supported sizes are 1K and 2K (not supported for Imagen 3 models). */\n  imageSize?: string;\n  /** Whether to use the prompt rewriting logic. */\n  enhancePrompt?: boolean;\n}\n\n/** The parameters for generating images. */\nexport declare interface GenerateImagesParameters {\n  /** ID of the model to use. For a list of models, see `Google models\n    <https://cloud.google.com/vertex-ai/generative-ai/docs/learn/models>`_. */\n  model: string;\n  /** Text prompt that typically describes the images to output.\n   */\n  prompt: string;\n  /** Configuration for generating images.\n   */\n  config?: GenerateImagesConfig;\n}\n\n/** An image. */\nexport declare interface Image {\n  /** The Cloud Storage URI of the image. ``Image`` can contain a value\n      for this field or the ``image_bytes`` field but not both. */\n  gcsUri?: string;\n  /** The image bytes data. ``Image`` can contain a value for this field\n      or the ``gcs_uri`` field but not both.\n  * @remarks Encoded as base64 string. */\n  imageBytes?: string;\n  /** The MIME type of the image. */\n  mimeType?: string;\n}\n\n/** Safety attributes of a GeneratedImage or the user-provided prompt. */\nexport declare interface SafetyAttributes {\n  /** List of RAI categories. */\n  categories?: string[];\n  /** List of scores of each categories. */\n  scores?: number[];\n  /** Internal use only. */\n  contentType?: string;\n}\n\n/** An output image. */\nexport declare interface GeneratedImage {\n  /** The output image data. */\n  image?: Image;\n  /** Responsible AI filter reason if the image is filtered out of the\n      response. */\n  raiFilteredReason?: string;\n  /** Safety attributes of the image. Lists of RAI categories and their\n      scores of each content. */\n  safetyAttributes?: SafetyAttributes;\n  /** The rewritten prompt used for the image generation if the prompt\n      enhancer is enabled. */\n  enhancedPrompt?: string;\n}\n\n/** The output images response. */\nexport class GenerateImagesResponse {\n  /** Used to retain the full HTTP response. */\n  sdkHttpResponse?: HttpResponse;\n  /** List of generated images. */\n  generatedImages?: GeneratedImage[];\n  /** Safety attributes of the positive prompt. Only populated if\n      ``include_safety_attributes`` is set to True. */\n  positivePromptSafetyAttributes?: SafetyAttributes;\n}\n\n/** Configuration for a Mask reference image. */\nexport declare interface MaskReferenceConfig {\n  /** Prompts the model to generate a mask instead of you needing to\n      provide one (unless MASK_MODE_USER_PROVIDED is used). */\n  maskMode?: MaskReferenceMode;\n  /** A list of up to 5 class ids to use for semantic segmentation.\n      Automatically creates an image mask based on specific objects. */\n  segmentationClasses?: number[];\n  /** Dilation percentage of the mask provided.\n      Float between 0 and 1. */\n  maskDilation?: number;\n}\n\n/** Configuration for a Control reference image. */\nexport declare interface ControlReferenceConfig {\n  /** The type of control reference image to use. */\n  controlType?: ControlReferenceType;\n  /** Defaults to False. When set to True, the control image will be\n      computed by the model based on the control type. When set to False,\n      the control image must be provided by the user. */\n  enableControlImageComputation?: boolean;\n}\n\n/** Configuration for a Style reference image. */\nexport declare interface StyleReferenceConfig {\n  /** A text description of the style to use for the generated image. */\n  styleDescription?: string;\n}\n\n/** Configuration for a Subject reference image. */\nexport declare interface SubjectReferenceConfig {\n  /** The subject type of a subject reference image. */\n  subjectType?: SubjectReferenceType;\n  /** Subject description for the image. */\n  subjectDescription?: string;\n}\n\n/** Configuration for editing an image. */\nexport declare interface EditImageConfig {\n  /** Used to override HTTP request options. */\n  httpOptions?: HttpOptions;\n  /** Abort signal which can be used to cancel the request.\n\n  NOTE: AbortSignal is a client-only operation. Using it to cancel an\n  operation will not cancel the request in the service. You will still\n  be charged usage for any applicable operations.\n       */\n  abortSignal?: AbortSignal;\n  /** Cloud Storage URI used to store the generated images. */\n  outputGcsUri?: string;\n  /** Description of what to discourage in the generated images. */\n  negativePrompt?: string;\n  /** Number of images to generate. */\n  numberOfImages?: number;\n  /** Aspect ratio of the generated images. Supported values are\n      \"1:1\", \"3:4\", \"4:3\", \"9:16\", and \"16:9\". */\n  aspectRatio?: string;\n  /** Controls how much the model adheres to the text prompt. Large\n      values increase output and prompt alignment, but may compromise image\n      quality. */\n  guidanceScale?: number;\n  /** Random seed for image generation. This is not available when\n      ``add_watermark`` is set to true. */\n  seed?: number;\n  /** Filter level for safety filtering. */\n  safetyFilterLevel?: SafetyFilterLevel;\n  /** Allows generation of people by the model. */\n  personGeneration?: PersonGeneration;\n  /** Whether to report the safety scores of each generated image and\n      the positive prompt in the response. */\n  includeSafetyAttributes?: boolean;\n  /** Whether to include the Responsible AI filter reason if the image\n      is filtered out of the response. */\n  includeRaiReason?: boolean;\n  /** Language of the text in the prompt. */\n  language?: ImagePromptLanguage;\n  /** MIME type of the generated image. */\n  outputMimeType?: string;\n  /** Compression quality of the generated image (for ``image/jpeg``\n      only). */\n  outputCompressionQuality?: number;\n  /** Whether to add a watermark to the generated images. */\n  addWatermark?: boolean;\n  /** User specified labels to track billing usage. */\n  labels?: Record<string, string>;\n  /** Describes the editing mode for the request. */\n  editMode?: EditMode;\n  /** The number of sampling steps. A higher value has better image\n      quality, while a lower value has better latency. */\n  baseSteps?: number;\n}\n\n/** Response for the request to edit an image. */\nexport class EditImageResponse {\n  /** Used to retain the full HTTP response. */\n  sdkHttpResponse?: HttpResponse;\n  /** Generated images. */\n  generatedImages?: GeneratedImage[];\n}\n\nexport class UpscaleImageResponse {\n  /** Used to retain the full HTTP response. */\n  sdkHttpResponse?: HttpResponse;\n  /** Generated images. */\n  generatedImages?: GeneratedImage[];\n}\n\n/** An image of the product. */\nexport declare interface ProductImage {\n  /** An image of the product to be recontextualized. */\n  productImage?: Image;\n}\n\n/** A set of source input(s) for image recontextualization. */\nexport declare interface RecontextImageSource {\n  /** A text prompt for guiding the model during image\n      recontextualization. Not supported for Virtual Try-On. */\n  prompt?: string;\n  /** Image of the person or subject who will be wearing the\n      product(s). */\n  personImage?: Image;\n  /** A list of product images. */\n  productImages?: ProductImage[];\n}\n\n/** Configuration for recontextualizing an image. */\nexport declare interface RecontextImageConfig {\n  /** Used to override HTTP request options. */\n  httpOptions?: HttpOptions;\n  /** Abort signal which can be used to cancel the request.\n\n  NOTE: AbortSignal is a client-only operation. Using it to cancel an\n  operation will not cancel the request in the service. You will still\n  be charged usage for any applicable operations.\n       */\n  abortSignal?: AbortSignal;\n  /** Number of images to generate. */\n  numberOfImages?: number;\n  /** The number of sampling steps. A higher value has better image\n      quality, while a lower value has better latency. */\n  baseSteps?: number;\n  /** Cloud Storage URI used to store the generated images. */\n  outputGcsUri?: string;\n  /** Random seed for image generation. */\n  seed?: number;\n  /** Filter level for safety filtering. */\n  safetyFilterLevel?: SafetyFilterLevel;\n  /** Whether allow to generate person images, and restrict to specific\n      ages. */\n  personGeneration?: PersonGeneration;\n  /** Whether to add a SynthID watermark to the generated images. */\n  addWatermark?: boolean;\n  /** MIME type of the generated image. */\n  outputMimeType?: string;\n  /** Compression quality of the generated image (for ``image/jpeg``\n      only). */\n  outputCompressionQuality?: number;\n  /** Whether to use the prompt rewriting logic. */\n  enhancePrompt?: boolean;\n  /** User specified labels to track billing usage. */\n  labels?: Record<string, string>;\n}\n\n/** The parameters for recontextualizing an image. */\nexport declare interface RecontextImageParameters {\n  /** ID of the model to use. For a list of models, see `Google models\n    <https://cloud.google.com/vertex-ai/generative-ai/docs/learn/models>`_. */\n  model: string;\n  /** A set of source input(s) for image recontextualization. */\n  source: RecontextImageSource;\n  /** Configuration for image recontextualization. */\n  config?: RecontextImageConfig;\n}\n\n/** The output images response. */\nexport class RecontextImageResponse {\n  /** List of generated images. */\n  generatedImages?: GeneratedImage[];\n}\n\n/** An image mask representing a brush scribble. */\nexport declare interface ScribbleImage {\n  /** The brush scribble to guide segmentation. Valid for the interactive mode. */\n  image?: Image;\n}\n\n/** A set of source input(s) for image segmentation. */\nexport declare interface SegmentImageSource {\n  /** A text prompt for guiding the model during image segmentation.\n      Required for prompt mode and semantic mode, disallowed for other modes. */\n  prompt?: string;\n  /** The image to be segmented. */\n  image?: Image;\n  /** The brush scribble to guide segmentation.\n      Required for the interactive mode, disallowed for other modes. */\n  scribbleImage?: ScribbleImage;\n}\n\n/** Configuration for segmenting an image. */\nexport declare interface SegmentImageConfig {\n  /** Used to override HTTP request options. */\n  httpOptions?: HttpOptions;\n  /** Abort signal which can be used to cancel the request.\n\n  NOTE: AbortSignal is a client-only operation. Using it to cancel an\n  operation will not cancel the request in the service. You will still\n  be charged usage for any applicable operations.\n       */\n  abortSignal?: AbortSignal;\n  /** The segmentation mode to use. */\n  mode?: SegmentMode;\n  /** The maximum number of predictions to return up to, by top\n      confidence score. */\n  maxPredictions?: number;\n  /** The confidence score threshold for the detections as a decimal\n      value. Only predictions with a confidence score higher than this\n      threshold will be returned. */\n  confidenceThreshold?: number;\n  /** A decimal value representing how much dilation to apply to the\n      masks. 0 for no dilation. 1.0 means the masked area covers the whole\n      image. */\n  maskDilation?: number;\n  /** The binary color threshold to apply to the masks. The threshold\n      can be set to a decimal value between 0 and 255 non-inclusive.\n      Set to -1 for no binary color thresholding. */\n  binaryColorThreshold?: number;\n  /** User specified labels to track billing usage. */\n  labels?: Record<string, string>;\n}\n\n/** The parameters for segmenting an image. */\nexport declare interface SegmentImageParameters {\n  /** ID of the model to use. For a list of models, see `Google models\n    <https://cloud.google.com/vertex-ai/generative-ai/docs/learn/models>`_. */\n  model: string;\n  /** A set of source input(s) for image segmentation. */\n  source: SegmentImageSource;\n  /** Configuration for image segmentation. */\n  config?: SegmentImageConfig;\n}\n\n/** An entity representing the segmented area. */\nexport declare interface EntityLabel {\n  /** The label of the segmented entity. */\n  label?: string;\n  /** The confidence score of the detected label. */\n  score?: number;\n}\n\n/** A generated image mask. */\nexport declare interface GeneratedImageMask {\n  /** The generated image mask. */\n  mask?: Image;\n  /** The detected entities on the segmented area. */\n  labels?: EntityLabel[];\n}\n\n/** The output images response. */\nexport class SegmentImageResponse {\n  /** List of generated image masks.\n   */\n  generatedMasks?: GeneratedImageMask[];\n}\n\n/** Optional parameters for models.get method. */\nexport declare interface GetModelConfig {\n  /** Used to override HTTP request options. */\n  httpOptions?: HttpOptions;\n  /** Abort signal which can be used to cancel the request.\n\n  NOTE: AbortSignal is a client-only operation. Using it to cancel an\n  operation will not cancel the request in the service. You will still\n  be charged usage for any applicable operations.\n       */\n  abortSignal?: AbortSignal;\n}\n\nexport declare interface GetModelParameters {\n  model: string;\n  /** Optional parameters for the request. */\n  config?: GetModelConfig;\n}\n\n/** An endpoint where you deploy models. */\nexport declare interface Endpoint {\n  /** Resource name of the endpoint. */\n  name?: string;\n  /** ID of the model that's deployed to the endpoint. */\n  deployedModelId?: string;\n}\n\n/** A tuned machine learning model. */\nexport declare interface TunedModelInfo {\n  /** ID of the base model that you want to tune. */\n  baseModel?: string;\n  /** Date and time when the base model was created. */\n  createTime?: string;\n  /** Date and time when the base model was last updated. */\n  updateTime?: string;\n}\n\n/** Describes the machine learning model version checkpoint. */\nexport declare interface Checkpoint {\n  /** The ID of the checkpoint.\n   */\n  checkpointId?: string;\n  /** The epoch of the checkpoint.\n   */\n  epoch?: string;\n  /** The step of the checkpoint.\n   */\n  step?: string;\n}\n\n/** A trained machine learning model. */\nexport declare interface Model {\n  /** Resource name of the model. */\n  name?: string;\n  /** Display name of the model. */\n  displayName?: string;\n  /** Description of the model. */\n  description?: string;\n  /** Version ID of the model. A new version is committed when a new\n      model version is uploaded or trained under an existing model ID. The\n      version ID is an auto-incrementing decimal number in string\n      representation. */\n  version?: string;\n  /** List of deployed models created from this base model. Note that a\n      model could have been deployed to endpoints in different locations. */\n  endpoints?: Endpoint[];\n  /** Labels with user-defined metadata to organize your models. */\n  labels?: Record<string, string>;\n  /** Information about the tuned model from the base model. */\n  tunedModelInfo?: TunedModelInfo;\n  /** The maximum number of input tokens that the model can handle. */\n  inputTokenLimit?: number;\n  /** The maximum number of output tokens that the model can generate. */\n  outputTokenLimit?: number;\n  /** List of actions that are supported by the model. */\n  supportedActions?: string[];\n  /** The default checkpoint id of a model version.\n   */\n  defaultCheckpointId?: string;\n  /** The checkpoints of the model. */\n  checkpoints?: Checkpoint[];\n  /** Temperature value used for sampling set when the dataset was saved.\n      This value is used to tune the degree of randomness. */\n  temperature?: number;\n  /** The maximum temperature value used for sampling set when the\n      dataset was saved. This value is used to tune the degree of randomness. */\n  maxTemperature?: number;\n  /** Optional. Specifies the nucleus sampling threshold. The model\n      considers only the smallest set of tokens whose cumulative probability is\n      at least `top_p`. This helps generate more diverse and less repetitive\n      responses. For example, a `top_p` of 0.9 means the model considers tokens\n      until the cumulative probability of the tokens to select from reaches 0.9.\n      It's recommended to adjust either temperature or `top_p`, but not both. */\n  topP?: number;\n  /** Optional. Specifies the top-k sampling threshold. The model\n      considers only the top k most probable tokens for the next token. This can\n      be useful for generating more coherent and less random text. For example,\n      a `top_k` of 40 means the model will choose the next word from the 40 most\n      likely words. */\n  topK?: number;\n  /** Whether the model supports thinking features. If true, thoughts are\n      returned only if the model supports thought and thoughts are available. */\n  thinking?: boolean;\n}\n\nexport declare interface ListModelsConfig {\n  /** Used to override HTTP request options. */\n  httpOptions?: HttpOptions;\n  /** Abort signal which can be used to cancel the request.\n\n  NOTE: AbortSignal is a client-only operation. Using it to cancel an\n  operation will not cancel the request in the service. You will still\n  be charged usage for any applicable operations.\n       */\n  abortSignal?: AbortSignal;\n  pageSize?: number;\n  pageToken?: string;\n  filter?: string;\n  /** Set true to list base models, false to list tuned models. */\n  queryBase?: boolean;\n}\n\nexport declare interface ListModelsParameters {\n  config?: ListModelsConfig;\n}\n\nexport class ListModelsResponse {\n  /** Used to retain the full HTTP response. */\n  sdkHttpResponse?: HttpResponse;\n  nextPageToken?: string;\n  models?: Model[];\n}\n\n/** Configuration for updating a tuned model. */\nexport declare interface UpdateModelConfig {\n  /** Used to override HTTP request options. */\n  httpOptions?: HttpOptions;\n  /** Abort signal which can be used to cancel the request.\n\n  NOTE: AbortSignal is a client-only operation. Using it to cancel an\n  operation will not cancel the request in the service. You will still\n  be charged usage for any applicable operations.\n       */\n  abortSignal?: AbortSignal;\n  displayName?: string;\n  description?: string;\n  defaultCheckpointId?: string;\n}\n\n/** Configuration for updating a tuned model. */\nexport declare interface UpdateModelParameters {\n  model: string;\n  config?: UpdateModelConfig;\n}\n\n/** Configuration for deleting a tuned model. */\nexport declare interface DeleteModelConfig {\n  /** Used to override HTTP request options. */\n  httpOptions?: HttpOptions;\n  /** Abort signal which can be used to cancel the request.\n\n  NOTE: AbortSignal is a client-only operation. Using it to cancel an\n  operation will not cancel the request in the service. You will still\n  be charged usage for any applicable operations.\n       */\n  abortSignal?: AbortSignal;\n}\n\n/** Parameters for deleting a tuned model. */\nexport declare interface DeleteModelParameters {\n  model: string;\n  /** Optional parameters for the request. */\n  config?: DeleteModelConfig;\n}\n\nexport class DeleteModelResponse {\n  /** Used to retain the full HTTP response. */\n  sdkHttpResponse?: HttpResponse;\n}\n\n/** Generation config. */\nexport declare interface GenerationConfig {\n  /** Optional. Config for model selection. */\n  modelSelectionConfig?: ModelSelectionConfig;\n  /** Output schema of the generated response. This is an alternative to\n      `response_schema` that accepts [JSON Schema](https://json-schema.org/).\n       */\n  responseJsonSchema?: unknown;\n  /** Optional. If enabled, audio timestamp will be included in the request to the model. This field is not supported in Gemini API. */\n  audioTimestamp?: boolean;\n  /** Optional. Number of candidates to generate. */\n  candidateCount?: number;\n  /** Optional. If enabled, the model will detect emotions and adapt its responses accordingly. This field is not supported in Gemini API. */\n  enableAffectiveDialog?: boolean;\n  /** Optional. Frequency penalties. */\n  frequencyPenalty?: number;\n  /** Optional. Logit probabilities. */\n  logprobs?: number;\n  /** Optional. The maximum number of output tokens to generate per message. */\n  maxOutputTokens?: number;\n  /** Optional. If specified, the media resolution specified will be used. */\n  mediaResolution?: MediaResolution;\n  /** Optional. Positive penalties. */\n  presencePenalty?: number;\n  /** Optional. If true, export the logprobs results in response. */\n  responseLogprobs?: boolean;\n  /** Optional. Output response mimetype of the generated candidate text. Supported mimetype: - `text/plain`: (default) Text output. - `application/json`: JSON response in the candidates. The model needs to be prompted to output the appropriate response type, otherwise the behavior is undefined. This is a preview feature. */\n  responseMimeType?: string;\n  /** Optional. The modalities of the response. */\n  responseModalities?: Modality[];\n  /** Optional. The `Schema` object allows the definition of input and output data types. These types can be objects, but also primitives and arrays. Represents a select subset of an [OpenAPI 3.0 schema object](https://spec.openapis.org/oas/v3.0.3#schema). If set, a compatible response_mime_type must also be set. Compatible mimetypes: `application/json`: Schema for JSON response. */\n  responseSchema?: Schema;\n  /** Optional. Routing configuration. This field is not supported in Gemini API. */\n  routingConfig?: GenerationConfigRoutingConfig;\n  /** Optional. Seed. */\n  seed?: number;\n  /** Optional. The speech generation config. */\n  speechConfig?: SpeechConfig;\n  /** Optional. Stop sequences. */\n  stopSequences?: string[];\n  /** Optional. Controls the randomness of predictions. */\n  temperature?: number;\n  /** Optional. Config for thinking features. An error will be returned if this field is set for models that don't support thinking. */\n  thinkingConfig?: ThinkingConfig;\n  /** Optional. If specified, top-k sampling will be used. */\n  topK?: number;\n  /** Optional. If specified, nucleus sampling will be used. */\n  topP?: number;\n  /** Optional. Enables enhanced civic answers. It may not be available for all models. This field is not supported in Vertex AI. */\n  enableEnhancedCivicAnswers?: boolean;\n}\n\n/** Config for the count_tokens method. */\nexport declare interface CountTokensConfig {\n  /** Used to override HTTP request options. */\n  httpOptions?: HttpOptions;\n  /** Abort signal which can be used to cancel the request.\n\n  NOTE: AbortSignal is a client-only operation. Using it to cancel an\n  operation will not cancel the request in the service. You will still\n  be charged usage for any applicable operations.\n       */\n  abortSignal?: AbortSignal;\n  /** Instructions for the model to steer it toward better performance.\n   */\n  systemInstruction?: ContentUnion;\n  /** Code that enables the system to interact with external systems to\n      perform an action outside of the knowledge and scope of the model.\n       */\n  tools?: Tool[];\n  /** Configuration that the model uses to generate the response. Not\n      supported by the Gemini Developer API.\n       */\n  generationConfig?: GenerationConfig;\n}\n\n/** Parameters for counting tokens. */\nexport declare interface CountTokensParameters {\n  /** ID of the model to use. For a list of models, see `Google models\n    <https://cloud.google.com/vertex-ai/generative-ai/docs/learn/models>`_. */\n  model: string;\n  /** Input content. */\n  contents: ContentListUnion;\n  /** Configuration for counting tokens. */\n  config?: CountTokensConfig;\n}\n\n/** Response for counting tokens. */\nexport class CountTokensResponse {\n  /** Used to retain the full HTTP response. */\n  sdkHttpResponse?: HttpResponse;\n  /** Total number of tokens. */\n  totalTokens?: number;\n  /** Number of tokens in the cached part of the prompt (the cached content). */\n  cachedContentTokenCount?: number;\n}\n\n/** Optional parameters for computing tokens. */\nexport declare interface ComputeTokensConfig {\n  /** Used to override HTTP request options. */\n  httpOptions?: HttpOptions;\n  /** Abort signal which can be used to cancel the request.\n\n  NOTE: AbortSignal is a client-only operation. Using it to cancel an\n  operation will not cancel the request in the service. You will still\n  be charged usage for any applicable operations.\n       */\n  abortSignal?: AbortSignal;\n}\n\n/** Parameters for computing tokens. */\nexport declare interface ComputeTokensParameters {\n  /** ID of the model to use. For a list of models, see `Google models\n    <https://cloud.google.com/vertex-ai/generative-ai/docs/learn/models>`_. */\n  model: string;\n  /** Input content. */\n  contents: ContentListUnion;\n  /** Optional parameters for the request.\n   */\n  config?: ComputeTokensConfig;\n}\n\n/** Tokens info with a list of tokens and the corresponding list of token ids. */\nexport declare interface TokensInfo {\n  /** Optional fields for the role from the corresponding Content. */\n  role?: string;\n  /** A list of token ids from the input. */\n  tokenIds?: string[];\n  /** A list of tokens from the input.\n   * @remarks Encoded as base64 string. */\n  tokens?: string[];\n}\n\n/** Response for computing tokens. */\nexport class ComputeTokensResponse {\n  /** Used to retain the full HTTP response. */\n  sdkHttpResponse?: HttpResponse;\n  /** Lists of tokens info from the input. A ComputeTokensRequest could have multiple instances with a prompt in each instance. We also need to return lists of tokens info for the request with multiple instances. */\n  tokensInfo?: TokensInfo[];\n}\n\n/** A generated video. */\nexport declare interface Video {\n  /** Path to another storage. */\n  uri?: string;\n  /** Video bytes.\n   * @remarks Encoded as base64 string. */\n  videoBytes?: string;\n  /** Video encoding, for example ``video/mp4``. */\n  mimeType?: string;\n}\n\n/** A set of source input(s) for video generation. */\nexport declare interface GenerateVideosSource {\n  /** The text prompt for generating the videos.\n      Optional if image or video is provided. */\n  prompt?: string;\n  /** The input image for generating the videos.\n      Optional if prompt is provided. Not allowed if video is provided. */\n  image?: Image;\n  /** The input video for video extension use cases.\n      Optional if prompt is provided. Not allowed if image is provided. */\n  video?: Video;\n}\n\n/** A reference image for video generation. */\nexport declare interface VideoGenerationReferenceImage {\n  /** The reference image. */\n  image?: Image;\n  /** The type of the reference image, which defines how the reference\n      image will be used to generate the video. */\n  referenceType?: VideoGenerationReferenceType;\n}\n\n/** A mask for video generation. */\nexport declare interface VideoGenerationMask {\n  /** The image mask to use for generating videos. */\n  image?: Image;\n  /** Describes how the mask will be used. Inpainting masks must\n      match the aspect ratio of the input video. Outpainting masks can be\n      either 9:16 or 16:9. */\n  maskMode?: VideoGenerationMaskMode;\n}\n\n/** Configuration for generating videos. */\nexport declare interface GenerateVideosConfig {\n  /** Used to override HTTP request options. */\n  httpOptions?: HttpOptions;\n  /** Abort signal which can be used to cancel the request.\n\n  NOTE: AbortSignal is a client-only operation. Using it to cancel an\n  operation will not cancel the request in the service. You will still\n  be charged usage for any applicable operations.\n       */\n  abortSignal?: AbortSignal;\n  /** Number of output videos. */\n  numberOfVideos?: number;\n  /** The gcs bucket where to save the generated videos. */\n  outputGcsUri?: string;\n  /** Frames per second for video generation. */\n  fps?: number;\n  /** Duration of the clip for video generation in seconds. */\n  durationSeconds?: number;\n  /** The RNG seed. If RNG seed is exactly same for each request with\n      unchanged inputs, the prediction results will be consistent. Otherwise,\n      a random RNG seed will be used each time to produce a different\n      result. */\n  seed?: number;\n  /** The aspect ratio for the generated video. 16:9 (landscape) and\n      9:16 (portrait) are supported. */\n  aspectRatio?: string;\n  /** The resolution for the generated video. 720p and 1080p are\n      supported. */\n  resolution?: string;\n  /** Whether allow to generate person videos, and restrict to specific\n      ages. Supported values are: dont_allow, allow_adult. */\n  personGeneration?: string;\n  /** The pubsub topic where to publish the video generation\n      progress. */\n  pubsubTopic?: string;\n  /** Explicitly state what should not be included in the generated\n      videos. */\n  negativePrompt?: string;\n  /** Whether to use the prompt rewriting logic. */\n  enhancePrompt?: boolean;\n  /** Whether to generate audio along with the video. */\n  generateAudio?: boolean;\n  /** Image to use as the last frame of generated videos.\n      Only supported for image to video use cases. */\n  lastFrame?: Image;\n  /** The images to use as the references to generate the videos.\n      If this field is provided, the text prompt field must also be provided.\n      The image, video, or last_frame field are not supported. Each image must\n      be associated with a type. Veo 2 supports up to 3 asset images *or* 1\n      style image. */\n  referenceImages?: VideoGenerationReferenceImage[];\n  /** The mask to use for generating videos. */\n  mask?: VideoGenerationMask;\n  /** Compression quality of the generated videos. */\n  compressionQuality?: VideoCompressionQuality;\n}\n\n/** Class that represents the parameters for generating videos. */\nexport declare interface GenerateVideosParameters {\n  /** ID of the model to use. For a list of models, see `Google models\n    <https://cloud.google.com/vertex-ai/generative-ai/docs/learn/models>`_. */\n  model: string;\n  /** The text prompt for generating the videos.\n      Optional if image or video is provided. */\n  prompt?: string;\n  /** The input image for generating the videos.\n      Optional if prompt is provided. Not allowed if video is provided. */\n  image?: Image;\n  /** The input video for video extension use cases.\n      Optional if prompt is provided. Not allowed if image is provided. */\n  video?: Video;\n  /** A set of source input(s) for video generation. */\n  source?: GenerateVideosSource;\n  /** Configuration for generating videos. */\n  config?: GenerateVideosConfig;\n}\n\n/** A generated video. */\nexport declare interface GeneratedVideo {\n  /** The output video */\n  video?: Video;\n}\n\n/** Response with generated videos. */\nexport class GenerateVideosResponse {\n  /** List of the generated videos */\n  generatedVideos?: GeneratedVideo[];\n  /** Returns if any videos were filtered due to RAI policies. */\n  raiMediaFilteredCount?: number;\n  /** Returns rai failure reasons if any. */\n  raiMediaFilteredReasons?: string[];\n}\n\n/** A long-running operation. */\nexport declare interface Operation<T> {\n  /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */\n  name?: string;\n  /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata.  Any method that returns a long-running operation should document the metadata type, if any. */\n  metadata?: Record<string, unknown>;\n  /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */\n  done?: boolean;\n  /** The error result of the operation in case of failure or cancellation. */\n  error?: Record<string, unknown>;\n  /** The response if the operation is successful. */\n  response?: T;\n  /**\n   * Instantiates an Operation of the same type as the one being called with the fields set from the API response.\n   * @internal\n   */\n  _fromAPIResponse({\n    apiResponse,\n    _isVertexAI,\n  }: OperationFromAPIResponseParameters): Operation<T>;\n}\n\n/** A video generation operation. */\nexport class GenerateVideosOperation\n  implements Operation<GenerateVideosResponse>\n{\n  /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */\n  name?: string;\n  /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata.  Any method that returns a long-running operation should document the metadata type, if any. */\n  metadata?: Record<string, unknown>;\n  /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */\n  done?: boolean;\n  /** The error result of the operation in case of failure or cancellation. */\n  error?: Record<string, unknown>;\n  /** The generated videos. */\n  response?: GenerateVideosResponse;\n\n  /**\n   * Instantiates an Operation of the same type as the one being called with the fields set from the API response.\n   * @internal\n   */\n  _fromAPIResponse({\n    apiResponse,\n    _isVertexAI,\n  }: OperationFromAPIResponseParameters): Operation<GenerateVideosResponse> {\n    const operation = new GenerateVideosOperation();\n    let response;\n    const op = apiResponse as unknown as GenerateVideosOperation;\n\n    if (_isVertexAI) {\n      response = generateVideosOperationFromVertex(op);\n    } else {\n      response = generateVideosOperationFromMldev(op);\n    }\n    Object.assign(operation, response);\n    return operation;\n  }\n  /** The full HTTP response. */\n  sdkHttpResponse?: HttpResponse;\n}\n\n/** Optional parameters for tunings.get method. */\nexport declare interface GetTuningJobConfig {\n  /** Used to override HTTP request options. */\n  httpOptions?: HttpOptions;\n  /** Abort signal which can be used to cancel the request.\n\n  NOTE: AbortSignal is a client-only operation. Using it to cancel an\n  operation will not cancel the request in the service. You will still\n  be charged usage for any applicable operations.\n       */\n  abortSignal?: AbortSignal;\n}\n\n/** Parameters for the get method. */\nexport declare interface GetTuningJobParameters {\n  name: string;\n  /** Optional parameters for the request. */\n  config?: GetTuningJobConfig;\n}\n\n/** TunedModelCheckpoint for the Tuned Model of a Tuning Job. */\nexport declare interface TunedModelCheckpoint {\n  /** The ID of the checkpoint.\n   */\n  checkpointId?: string;\n  /** The epoch of the checkpoint.\n   */\n  epoch?: string;\n  /** The step of the checkpoint.\n   */\n  step?: string;\n  /** The Endpoint resource name that the checkpoint is deployed to.\n      Format: `projects/{project}/locations/{location}/endpoints/{endpoint}`.\n       */\n  endpoint?: string;\n}\n\n/** TunedModel for the Tuned Model of a Tuning Job. */\nexport declare interface TunedModel {\n  /** Output only. The resource name of the TunedModel.\n      Format: `projects/{project}/locations/{location}/models/{model}@{version_id}`\n      When tuning from a base model, the version_id will be 1.\n      For continuous tuning, the version id will be incremented by 1 from the\n      last version id in the parent model. E.g., `projects/{project}/locations/{location}/models/{model}@{last_version_id + 1}`\n       */\n  model?: string;\n  /** Output only. A resource name of an Endpoint.\n      Format: `projects/{project}/locations/{location}/endpoints/{endpoint}`.\n       */\n  endpoint?: string;\n  /** The checkpoints associated with this TunedModel.\n      This field is only populated for tuning jobs that enable intermediate\n      checkpoints. */\n  checkpoints?: TunedModelCheckpoint[];\n}\n\n/** Hyperparameters for SFT. This data type is not supported in Gemini API. */\nexport declare interface SupervisedHyperParameters {\n  /** Optional. Adapter size for tuning. */\n  adapterSize?: AdapterSize;\n  /** Optional. Batch size for tuning. This feature is only available for open source models. */\n  batchSize?: string;\n  /** Optional. Number of complete passes the model makes over the entire training dataset during training. */\n  epochCount?: string;\n  /** Optional. Learning rate for tuning. Mutually exclusive with `learning_rate_multiplier`. This feature is only available for open source models. */\n  learningRate?: number;\n  /** Optional. Multiplier for adjusting the default learning rate. Mutually exclusive with `learning_rate`. This feature is only available for 1P models. */\n  learningRateMultiplier?: number;\n}\n\n/** Supervised tuning spec for tuning. */\nexport declare interface SupervisedTuningSpec {\n  /** Optional. If set to true, disable intermediate checkpoints for SFT and only the last checkpoint will be exported. Otherwise, enable intermediate checkpoints for SFT. Default is false. */\n  exportLastCheckpointOnly?: boolean;\n  /** Optional. Hyperparameters for SFT. */\n  hyperParameters?: SupervisedHyperParameters;\n  /** Required. Training dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset. */\n  trainingDatasetUri?: string;\n  /** Tuning mode. */\n  tuningMode?: TuningMode;\n  /** Optional. Validation dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset. */\n  validationDatasetUri?: string;\n}\n\n/** Hyperparameters for Preference Optimization. This data type is not supported in Gemini API. */\nexport declare interface PreferenceOptimizationHyperParameters {\n  /** Optional. Adapter size for preference optimization. */\n  adapterSize?: AdapterSize;\n  /** Optional. Weight for KL Divergence regularization. */\n  beta?: number;\n  /** Optional. Number of complete passes the model makes over the entire training dataset during training. */\n  epochCount?: string;\n  /** Optional. Multiplier for adjusting the default learning rate. */\n  learningRateMultiplier?: number;\n}\n\n/** Preference optimization tuning spec for tuning. */\nexport declare interface PreferenceOptimizationSpec {\n  /** Optional. If set to true, disable intermediate checkpoints for Preference Optimization and only the last checkpoint will be exported. Otherwise, enable intermediate checkpoints for Preference Optimization. Default is false. */\n  exportLastCheckpointOnly?: boolean;\n  /** Optional. Hyperparameters for Preference Optimization. */\n  hyperParameters?: PreferenceOptimizationHyperParameters;\n  /** Required. Cloud Storage path to file containing training dataset for preference optimization tuning. The dataset must be formatted as a JSONL file. */\n  trainingDatasetUri?: string;\n  /** Optional. Cloud Storage path to file containing validation dataset for preference optimization tuning. The dataset must be formatted as a JSONL file. */\n  validationDatasetUri?: string;\n}\n\n/** The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains three pieces of data: error code, error message, and error details. You can find out more about this error model and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors). This data type is not supported in Gemini API. */\nexport declare interface GoogleRpcStatus {\n  /** The status code, which should be an enum value of google.rpc.Code. */\n  code?: number;\n  /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */\n  details?: Record<string, unknown>[];\n  /** A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client. */\n  message?: string;\n}\n\n/** A pre-tuned model for continuous tuning. This data type is not supported in Gemini API. */\nexport declare interface PreTunedModel {\n  /** Output only. The name of the base model this PreTunedModel was tuned from. */\n  baseModel?: string;\n  /** Optional. The source checkpoint id. If not specified, the default checkpoint will be used. */\n  checkpointId?: string;\n  /** The resource name of the Model. E.g., a model resource name with a specified version id or alias: `projects/{project}/locations/{location}/models/{model}@{version_id}` `projects/{project}/locations/{location}/models/{model}@{alias}` Or, omit the version id to use the default version: `projects/{project}/locations/{location}/models/{model}` */\n  tunedModelName?: string;\n}\n\n/** Dataset bucket used to create a histogram for the distribution given a population of values. This data type is not supported in Gemini API. */\nexport declare interface DatasetDistributionDistributionBucket {\n  /** Output only. Number of values in the bucket. */\n  count?: string;\n  /** Output only. Left bound of the bucket. */\n  left?: number;\n  /** Output only. Right bound of the bucket. */\n  right?: number;\n}\n\n/** Distribution computed over a tuning dataset. This data type is not supported in Gemini API. */\nexport declare interface DatasetDistribution {\n  /** Output only. Defines the histogram bucket. */\n  buckets?: DatasetDistributionDistributionBucket[];\n  /** Output only. The maximum of the population values. */\n  max?: number;\n  /** Output only. The arithmetic mean of the values in the population. */\n  mean?: number;\n  /** Output only. The median of the values in the population. */\n  median?: number;\n  /** Output only. The minimum of the population values. */\n  min?: number;\n  /** Output only. The 5th percentile of the values in the population. */\n  p5?: number;\n  /** Output only. The 95th percentile of the values in the population. */\n  p95?: number;\n  /** Output only. Sum of a given population of values. */\n  sum?: number;\n}\n\n/** Statistics computed over a tuning dataset. This data type is not supported in Gemini API. */\nexport declare interface DatasetStats {\n  /** Output only. Number of billable characters in the tuning dataset. */\n  totalBillableCharacterCount?: string;\n  /** Output only. Number of tuning characters in the tuning dataset. */\n  totalTuningCharacterCount?: string;\n  /** Output only. Number of examples in the tuning dataset. */\n  tuningDatasetExampleCount?: string;\n  /** Output only. Number of tuning steps for this Tuning Job. */\n  tuningStepCount?: string;\n  /** Output only. Sample user messages in the training dataset uri. */\n  userDatasetExamples?: Content[];\n  /** Output only. Dataset distributions for the user input tokens. */\n  userInputTokenDistribution?: DatasetDistribution;\n  /** Output only. Dataset distributions for the messages per example. */\n  userMessagePerExampleDistribution?: DatasetDistribution;\n  /** Output only. Dataset distributions for the user output tokens. */\n  userOutputTokenDistribution?: DatasetDistribution;\n}\n\n/** Statistics computed for datasets used for distillation. This data type is not supported in Gemini API. */\nexport declare interface DistillationDataStats {\n  /** Output only. Statistics computed for the training dataset. */\n  trainingDatasetStats?: DatasetStats;\n}\n\n/** Completion and its preference score. This data type is not supported in Gemini API. */\nexport declare interface GeminiPreferenceExampleCompletion {\n  /** Single turn completion for the given prompt. */\n  completion?: Content;\n  /** The score for the given completion. */\n  score?: number;\n}\n\n/** Input example for preference optimization. This data type is not supported in Gemini API. */\nexport declare interface GeminiPreferenceExample {\n  /** List of completions for a given prompt. */\n  completions?: GeminiPreferenceExampleCompletion[];\n  /** Multi-turn contents that represents the Prompt. */\n  contents?: Content[];\n}\n\n/** Statistics computed for datasets used for preference optimization. This data type is not supported in Gemini API. */\nexport declare interface PreferenceOptimizationDataStats {\n  /** Output only. Dataset distributions for scores variance per example. */\n  scoreVariancePerExampleDistribution?: DatasetDistribution;\n  /** Output only. Dataset distributions for scores. */\n  scoresDistribution?: DatasetDistribution;\n  /** Output only. Number of billable tokens in the tuning dataset. */\n  totalBillableTokenCount?: string;\n  /** Output only. Number of examples in the tuning dataset. */\n  tuningDatasetExampleCount?: string;\n  /** Output only. Number of tuning steps for this Tuning Job. */\n  tuningStepCount?: string;\n  /** Output only. Sample user examples in the training dataset. */\n  userDatasetExamples?: GeminiPreferenceExample[];\n  /** Output only. Dataset distributions for the user input tokens. */\n  userInputTokenDistribution?: DatasetDistribution;\n  /** Output only. Dataset distributions for the user output tokens. */\n  userOutputTokenDistribution?: DatasetDistribution;\n}\n\n/** Dataset bucket used to create a histogram for the distribution given a population of values. This data type is not supported in Gemini API. */\nexport declare interface SupervisedTuningDatasetDistributionDatasetBucket {\n  /** Output only. Number of values in the bucket. */\n  count?: number;\n  /** Output only. Left bound of the bucket. */\n  left?: number;\n  /** Output only. Right bound of the bucket. */\n  right?: number;\n}\n\n/** Dataset distribution for Supervised Tuning. This data type is not supported in Gemini API. */\nexport declare interface SupervisedTuningDatasetDistribution {\n  /** Output only. Sum of a given population of values that are billable. */\n  billableSum?: string;\n  /** Output only. Defines the histogram bucket. */\n  buckets?: SupervisedTuningDatasetDistributionDatasetBucket[];\n  /** Output only. The maximum of the population values. */\n  max?: number;\n  /** Output only. The arithmetic mean of the values in the population. */\n  mean?: number;\n  /** Output only. The median of the values in the population. */\n  median?: number;\n  /** Output only. The minimum of the population values. */\n  min?: number;\n  /** Output only. The 5th percentile of the values in the population. */\n  p5?: number;\n  /** Output only. The 95th percentile of the values in the population. */\n  p95?: number;\n  /** Output only. Sum of a given population of values. */\n  sum?: string;\n}\n\n/** Tuning data statistics for Supervised Tuning. This data type is not supported in Gemini API. */\nexport declare interface SupervisedTuningDataStats {\n  /** Output only. For each index in `truncated_example_indices`, the user-facing reason why the example was dropped. */\n  droppedExampleReasons?: string[];\n  /** Output only. Number of billable characters in the tuning dataset. */\n  totalBillableCharacterCount?: string;\n  /** Output only. Number of billable tokens in the tuning dataset. */\n  totalBillableTokenCount?: string;\n  /** Output only. The number of examples in the dataset that have been dropped. An example can be dropped for reasons including: too many tokens, contains an invalid image, contains too many images, etc. */\n  totalTruncatedExampleCount?: string;\n  /** Output only. Number of tuning characters in the tuning dataset. */\n  totalTuningCharacterCount?: string;\n  /** Output only. A partial sample of the indices (starting from 1) of the dropped examples. */\n  truncatedExampleIndices?: string[];\n  /** Output only. Number of examples in the tuning dataset. */\n  tuningDatasetExampleCount?: string;\n  /** Output only. Number of tuning steps for this Tuning Job. */\n  tuningStepCount?: string;\n  /** Output only. Sample user messages in the training dataset uri. */\n  userDatasetExamples?: Content[];\n  /** Output only. Dataset distributions for the user input tokens. */\n  userInputTokenDistribution?: SupervisedTuningDatasetDistribution;\n  /** Output only. Dataset distributions for the messages per example. */\n  userMessagePerExampleDistribution?: SupervisedTuningDatasetDistribution;\n  /** Output only. Dataset distributions for the user output tokens. */\n  userOutputTokenDistribution?: SupervisedTuningDatasetDistribution;\n}\n\n/** The tuning data statistic values for TuningJob. This data type is not supported in Gemini API. */\nexport declare interface TuningDataStats {\n  /** Output only. Statistics for distillation. */\n  distillationDataStats?: DistillationDataStats;\n  /** Output only. Statistics for preference optimization. */\n  preferenceOptimizationDataStats?: PreferenceOptimizationDataStats;\n  /** The SFT Tuning data stats. */\n  supervisedTuningDataStats?: SupervisedTuningDataStats;\n}\n\n/** Represents a customer-managed encryption key spec that can be applied to a top-level resource. This data type is not supported in Gemini API. */\nexport declare interface EncryptionSpec {\n  /** Required. The Cloud KMS resource identifier of the customer managed encryption key used to protect a resource. Has the form: `projects/my-project/locations/my-region/keyRings/my-kr/cryptoKeys/my-key`. The key needs to be in the same region as where the compute resource is created. */\n  kmsKeyName?: string;\n}\n\n/** Tuning spec for Partner models. This data type is not supported in Gemini API. */\nexport declare interface PartnerModelTuningSpec {\n  /** Hyperparameters for tuning. The accepted hyper_parameters and their valid range of values will differ depending on the base model. */\n  hyperParameters?: Record<string, unknown>;\n  /** Required. Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */\n  trainingDatasetUri?: string;\n  /** Optional. Cloud Storage path to file containing validation dataset for tuning. The dataset must be formatted as a JSONL file. */\n  validationDatasetUri?: string;\n}\n\n/** Hyperparameters for Veo. This data type is not supported in Gemini API. */\nexport declare interface VeoHyperParameters {\n  /** Optional. Number of complete passes the model makes over the entire training dataset during training. */\n  epochCount?: string;\n  /** Optional. Multiplier for adjusting the default learning rate. */\n  learningRateMultiplier?: number;\n  /** Optional. The tuning task. Either I2V or T2V. */\n  tuningTask?: TuningTask;\n}\n\n/** Tuning Spec for Veo Model Tuning. This data type is not supported in Gemini API. */\nexport declare interface VeoTuningSpec {\n  /** Optional. Hyperparameters for Veo. */\n  hyperParameters?: VeoHyperParameters;\n  /** Required. Training dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset. */\n  trainingDatasetUri?: string;\n  /** Optional. Validation dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset. */\n  validationDatasetUri?: string;\n}\n\n/** A tuning job. */\nexport declare interface TuningJob {\n  /** Used to retain the full HTTP response. */\n  sdkHttpResponse?: HttpResponse;\n  /** Output only. Identifier. Resource name of a TuningJob. Format: `projects/{project}/locations/{location}/tuningJobs/{tuning_job}` */\n  name?: string;\n  /** Output only. The detailed state of the job. */\n  state?: JobState;\n  /** Output only. Time when the TuningJob was created. */\n  createTime?: string;\n  /** Output only. Time when the TuningJob for the first time entered the `JOB_STATE_RUNNING` state. */\n  startTime?: string;\n  /** Output only. Time when the TuningJob entered any of the following JobStates: `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED`, `JOB_STATE_CANCELLED`, `JOB_STATE_EXPIRED`. */\n  endTime?: string;\n  /** Output only. Time when the TuningJob was most recently updated. */\n  updateTime?: string;\n  /** Output only. Only populated when job's state is `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`. */\n  error?: GoogleRpcStatus;\n  /** Optional. The description of the TuningJob. */\n  description?: string;\n  /** The base model that is being tuned. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/tuning#supported_models). */\n  baseModel?: string;\n  /** Output only. The tuned model resources associated with this TuningJob. */\n  tunedModel?: TunedModel;\n  /** The pre-tuned model for continuous tuning. */\n  preTunedModel?: PreTunedModel;\n  /** Tuning Spec for Supervised Fine Tuning. */\n  supervisedTuningSpec?: SupervisedTuningSpec;\n  /** Tuning Spec for Preference Optimization. */\n  preferenceOptimizationSpec?: PreferenceOptimizationSpec;\n  /** Output only. The tuning data statistics associated with this TuningJob. */\n  tuningDataStats?: TuningDataStats;\n  /** Customer-managed encryption key options for a TuningJob. If this is set, then all resources created by the TuningJob will be encrypted with the provided encryption key. */\n  encryptionSpec?: EncryptionSpec;\n  /** Tuning Spec for open sourced and third party Partner models. */\n  partnerModelTuningSpec?: PartnerModelTuningSpec;\n  /** Optional. The user-provided path to custom model weights. Set this field to tune a custom model. The path must be a Cloud Storage directory that contains the model weights in .safetensors format along with associated model metadata files. If this field is set, the base_model field must still be set to indicate which base model the custom model is derived from. This feature is only available for open source models. */\n  customBaseModel?: string;\n  /** Output only. The Experiment associated with this TuningJob. */\n  experiment?: string;\n  /** Optional. The labels with user-defined metadata to organize TuningJob and generated resources such as Model and Endpoint. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels. */\n  labels?: Record<string, string>;\n  /** Optional. Cloud Storage path to the directory where tuning job outputs are written to. This field is only available and required for open source models. */\n  outputUri?: string;\n  /** Output only. The resource name of the PipelineJob associated with the TuningJob. Format: `projects/{project}/locations/{location}/pipelineJobs/{pipeline_job}`. */\n  pipelineJob?: string;\n  /** The service account that the tuningJob workload runs as. If not specified, the Vertex AI Secure Fine-Tuned Service Agent in the project will be used. See https://cloud.google.com/iam/docs/service-agents#vertex-ai-secure-fine-tuning-service-agent Users starting the pipeline must have the `iam.serviceAccounts.actAs` permission on this service account. */\n  serviceAccount?: string;\n  /** Optional. The display name of the TunedModel. The name can be up to 128 characters long and can consist of any UTF-8 characters. For continuous tuning, tuned_model_display_name will by default use the same display name as the pre-tuned model. If a new display name is provided, the tuning job will create a new model instead of a new version. */\n  tunedModelDisplayName?: string;\n  /** Tuning Spec for Veo Tuning. */\n  veoTuningSpec?: VeoTuningSpec;\n}\n\n/** Configuration for the list tuning jobs method. */\nexport declare interface ListTuningJobsConfig {\n  /** Used to override HTTP request options. */\n  httpOptions?: HttpOptions;\n  /** Abort signal which can be used to cancel the request.\n\n  NOTE: AbortSignal is a client-only operation. Using it to cancel an\n  operation will not cancel the request in the service. You will still\n  be charged usage for any applicable operations.\n       */\n  abortSignal?: AbortSignal;\n  pageSize?: number;\n  pageToken?: string;\n  filter?: string;\n}\n\n/** Parameters for the list tuning jobs method. */\nexport declare interface ListTuningJobsParameters {\n  config?: ListTuningJobsConfig;\n}\n\n/** Response for the list tuning jobs method. */\nexport class ListTuningJobsResponse {\n  /** Used to retain the full HTTP response. */\n  sdkHttpResponse?: HttpResponse;\n  /** A token to retrieve the next page of results. Pass to ListTuningJobsRequest.page_token to obtain that page. */\n  nextPageToken?: string;\n  /** List of TuningJobs in the requested page. */\n  tuningJobs?: TuningJob[];\n}\n\n/** Optional parameters for tunings.cancel method. */\nexport declare interface CancelTuningJobConfig {\n  /** Used to override HTTP request options. */\n  httpOptions?: HttpOptions;\n  /** Abort signal which can be used to cancel the request.\n\n  NOTE: AbortSignal is a client-only operation. Using it to cancel an\n  operation will not cancel the request in the service. You will still\n  be charged usage for any applicable operations.\n       */\n  abortSignal?: AbortSignal;\n}\n\n/** Parameters for the cancel method. */\nexport declare interface CancelTuningJobParameters {\n  /** The resource name of the tuning job. */\n  name: string;\n  /** Optional parameters for the request. */\n  config?: CancelTuningJobConfig;\n}\n\n/** Empty response for tunings.cancel method. */\nexport class CancelTuningJobResponse {\n  /** Used to retain the full HTTP response. */\n  sdkHttpResponse?: HttpResponse;\n}\n\n/** A single example for tuning. This data type is not supported in Vertex AI. */\nexport declare interface TuningExample {\n  /** Required. The expected model output. */\n  output?: string;\n  /** Optional. Text model input. */\n  textInput?: string;\n}\n\n/** Supervised fine-tuning training dataset. */\nexport declare interface TuningDataset {\n  /** GCS URI of the file containing training dataset in JSONL format. */\n  gcsUri?: string;\n  /** The resource name of the Vertex Multimodal Dataset that is used as training dataset. Example: 'projects/my-project-id-or-number/locations/my-location/datasets/my-dataset-id'. */\n  vertexDatasetResource?: string;\n  /** Inline examples with simple input/output text. */\n  examples?: TuningExample[];\n}\n\nexport declare interface TuningValidationDataset {\n  /** GCS URI of the file containing validation dataset in JSONL format. */\n  gcsUri?: string;\n  /** The resource name of the Vertex Multimodal Dataset that is used as validation dataset. Example: 'projects/my-project-id-or-number/locations/my-location/datasets/my-dataset-id'. */\n  vertexDatasetResource?: string;\n}\n\n/** Fine-tuning job creation request - optional fields. */\nexport declare interface CreateTuningJobConfig {\n  /** Used to override HTTP request options. */\n  httpOptions?: HttpOptions;\n  /** Abort signal which can be used to cancel the request.\n\n  NOTE: AbortSignal is a client-only operation. Using it to cancel an\n  operation will not cancel the request in the service. You will still\n  be charged usage for any applicable operations.\n       */\n  abortSignal?: AbortSignal;\n  /** The method to use for tuning (SUPERVISED_FINE_TUNING or PREFERENCE_TUNING). If not set, the default method (SFT) will be used. */\n  method?: TuningMethod;\n  /** Validation dataset for tuning. The dataset must be formatted as a JSONL file. */\n  validationDataset?: TuningValidationDataset;\n  /** The display name of the tuned Model. The name can be up to 128 characters long and can consist of any UTF-8 characters. */\n  tunedModelDisplayName?: string;\n  /** The description of the TuningJob */\n  description?: string;\n  /** Number of complete passes the model makes over the entire training dataset during training. */\n  epochCount?: number;\n  /** Multiplier for adjusting the default learning rate. */\n  learningRateMultiplier?: number;\n  /** If set to true, disable intermediate checkpoints and only the last checkpoint will be exported. Otherwise, enable intermediate checkpoints. */\n  exportLastCheckpointOnly?: boolean;\n  /** The optional checkpoint id of the pre-tuned model to use for tuning, if applicable. */\n  preTunedModelCheckpointId?: string;\n  /** Adapter size for tuning. */\n  adapterSize?: AdapterSize;\n  /** The batch size hyperparameter for tuning. If not set, a default of 4 or 16 will be used based on the number of training examples. */\n  batchSize?: number;\n  /** The learning rate hyperparameter for tuning. If not set, a default of 0.001 or 0.0002 will be calculated based on the number of training examples. */\n  learningRate?: number;\n  /** Optional. The labels with user-defined metadata to organize TuningJob and generated resources such as Model and Endpoint. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels. */\n  labels?: Record<string, string>;\n  /** Weight for KL Divergence regularization, Preference Optimization tuning only. */\n  beta?: number;\n}\n\n/** Fine-tuning job creation parameters - optional fields. */\nexport declare interface CreateTuningJobParametersPrivate {\n  /** The base model that is being tuned, e.g., \"gemini-2.5-flash\". */\n  baseModel?: string;\n  /** The PreTunedModel that is being tuned. */\n  preTunedModel?: PreTunedModel;\n  /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */\n  trainingDataset: TuningDataset;\n  /** Configuration for the tuning job. */\n  config?: CreateTuningJobConfig;\n}\n\n/** A long-running operation. */\nexport declare interface TuningOperation {\n  /** Used to retain the full HTTP response. */\n  sdkHttpResponse?: HttpResponse;\n  /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */\n  name?: string;\n  /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata.  Any method that returns a long-running operation should document the metadata type, if any. */\n  metadata?: Record<string, unknown>;\n  /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */\n  done?: boolean;\n  /** The error result of the operation in case of failure or cancellation. */\n  error?: Record<string, unknown>;\n}\n\n/** Optional configuration for cached content creation. */\nexport declare interface CreateCachedContentConfig {\n  /** Used to override HTTP request options. */\n  httpOptions?: HttpOptions;\n  /** Abort signal which can be used to cancel the request.\n\n  NOTE: AbortSignal is a client-only operation. Using it to cancel an\n  operation will not cancel the request in the service. You will still\n  be charged usage for any applicable operations.\n       */\n  abortSignal?: AbortSignal;\n  /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: \"3.5s\". */\n  ttl?: string;\n  /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */\n  expireTime?: string;\n  /** The user-generated meaningful display name of the cached content.\n   */\n  displayName?: string;\n  /** The content to cache.\n   */\n  contents?: ContentListUnion;\n  /** Developer set system instruction.\n   */\n  systemInstruction?: ContentUnion;\n  /** A list of `Tools` the model may use to generate the next response.\n   */\n  tools?: Tool[];\n  /** Configuration for the tools to use. This config is shared for all tools.\n   */\n  toolConfig?: ToolConfig;\n  /** The Cloud KMS resource identifier of the customer managed\n      encryption key used to protect a resource.\n      The key needs to be in the same region as where the compute resource is\n      created. See\n      https://cloud.google.com/vertex-ai/docs/general/cmek for more\n      details. If this is set, then all created CachedContent objects\n      will be encrypted with the provided encryption key.\n      Allowed formats: projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}\n       */\n  kmsKeyName?: string;\n}\n\n/** Parameters for caches.create method. */\nexport declare interface CreateCachedContentParameters {\n  /** ID of the model to use. Example: gemini-2.0-flash */\n  model: string;\n  /** Configuration that contains optional parameters.\n   */\n  config?: CreateCachedContentConfig;\n}\n\n/** Metadata on the usage of the cached content. */\nexport declare interface CachedContentUsageMetadata {\n  /** Duration of audio in seconds. This field is not supported in Gemini API. */\n  audioDurationSeconds?: number;\n  /** Number of images. This field is not supported in Gemini API. */\n  imageCount?: number;\n  /** Number of text characters. This field is not supported in Gemini API. */\n  textCount?: number;\n  /** Total number of tokens that the cached content consumes. */\n  totalTokenCount?: number;\n  /** Duration of video in seconds. This field is not supported in Gemini API. */\n  videoDurationSeconds?: number;\n}\n\n/** A resource used in LLM queries for users to explicitly specify what to cache. */\nexport declare interface CachedContent {\n  /** The server-generated resource name of the cached content. */\n  name?: string;\n  /** The user-generated meaningful display name of the cached content. */\n  displayName?: string;\n  /** The name of the publisher model to use for cached content. */\n  model?: string;\n  /** Creation time of the cache entry. */\n  createTime?: string;\n  /** When the cache entry was last updated in UTC time. */\n  updateTime?: string;\n  /** Expiration time of the cached content. */\n  expireTime?: string;\n  /** Metadata on the usage of the cached content. */\n  usageMetadata?: CachedContentUsageMetadata;\n}\n\n/** Optional parameters for caches.get method. */\nexport declare interface GetCachedContentConfig {\n  /** Used to override HTTP request options. */\n  httpOptions?: HttpOptions;\n  /** Abort signal which can be used to cancel the request.\n\n  NOTE: AbortSignal is a client-only operation. Using it to cancel an\n  operation will not cancel the request in the service. You will still\n  be charged usage for any applicable operations.\n       */\n  abortSignal?: AbortSignal;\n}\n\n/** Parameters for caches.get method. */\nexport declare interface GetCachedContentParameters {\n  /** The server-generated resource name of the cached content.\n   */\n  name: string;\n  /** Optional parameters for the request.\n   */\n  config?: GetCachedContentConfig;\n}\n\n/** Optional parameters for caches.delete method. */\nexport declare interface DeleteCachedContentConfig {\n  /** Used to override HTTP request options. */\n  httpOptions?: HttpOptions;\n  /** Abort signal which can be used to cancel the request.\n\n  NOTE: AbortSignal is a client-only operation. Using it to cancel an\n  operation will not cancel the request in the service. You will still\n  be charged usage for any applicable operations.\n       */\n  abortSignal?: AbortSignal;\n}\n\n/** Parameters for caches.delete method. */\nexport declare interface DeleteCachedContentParameters {\n  /** The server-generated resource name of the cached content.\n   */\n  name: string;\n  /** Optional parameters for the request.\n   */\n  config?: DeleteCachedContentConfig;\n}\n\n/** Empty response for caches.delete method. */\nexport class DeleteCachedContentResponse {\n  /** Used to retain the full HTTP response. */\n  sdkHttpResponse?: HttpResponse;\n}\n\n/** Optional parameters for caches.update method. */\nexport declare interface UpdateCachedContentConfig {\n  /** Used to override HTTP request options. */\n  httpOptions?: HttpOptions;\n  /** Abort signal which can be used to cancel the request.\n\n  NOTE: AbortSignal is a client-only operation. Using it to cancel an\n  operation will not cancel the request in the service. You will still\n  be charged usage for any applicable operations.\n       */\n  abortSignal?: AbortSignal;\n  /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: \"3.5s\". */\n  ttl?: string;\n  /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */\n  expireTime?: string;\n}\n\nexport declare interface UpdateCachedContentParameters {\n  /** The server-generated resource name of the cached content.\n   */\n  name: string;\n  /** Configuration that contains optional parameters.\n   */\n  config?: UpdateCachedContentConfig;\n}\n\n/** Config for caches.list method. */\nexport declare interface ListCachedContentsConfig {\n  /** Used to override HTTP request options. */\n  httpOptions?: HttpOptions;\n  /** Abort signal which can be used to cancel the request.\n\n  NOTE: AbortSignal is a client-only operation. Using it to cancel an\n  operation will not cancel the request in the service. You will still\n  be charged usage for any applicable operations.\n       */\n  abortSignal?: AbortSignal;\n  pageSize?: number;\n  pageToken?: string;\n}\n\n/** Parameters for caches.list method. */\nexport declare interface ListCachedContentsParameters {\n  /** Configuration that contains optional parameters.\n   */\n  config?: ListCachedContentsConfig;\n}\n\nexport class ListCachedContentsResponse {\n  /** Used to retain the full HTTP response. */\n  sdkHttpResponse?: HttpResponse;\n  nextPageToken?: string;\n  /** List of cached contents.\n   */\n  cachedContents?: CachedContent[];\n}\n\n/** Optional Config. */\nexport declare interface GetDocumentConfig {\n  /** Used to override HTTP request options. */\n  httpOptions?: HttpOptions;\n  /** Abort signal which can be used to cancel the request.\n\n  NOTE: AbortSignal is a client-only operation. Using it to cancel an\n  operation will not cancel the request in the service. You will still\n  be charged usage for any applicable operations.\n       */\n  abortSignal?: AbortSignal;\n}\n\n/** Parameters for documents.get. */\nexport declare interface GetDocumentParameters {\n  /** The resource name of the Document.\n    Example: fileSearchStores/file-search-store-foo/documents/documents-bar */\n  name: string;\n  /** Optional parameters for the request. */\n  config?: GetDocumentConfig;\n}\n\n/** User provided string values assigned to a single metadata key. This data type is not supported in Vertex AI. */\nexport declare interface StringList {\n  /** The string values of the metadata to store. */\n  values?: string[];\n}\n\n/** User provided metadata stored as key-value pairs. This data type is not supported in Vertex AI. */\nexport declare interface CustomMetadata {\n  /** Required. The key of the metadata to store. */\n  key?: string;\n  /** The numeric value of the metadata to store. */\n  numericValue?: number;\n  /** The StringList value of the metadata to store. */\n  stringListValue?: StringList;\n  /** The string value of the metadata to store. */\n  stringValue?: string;\n}\n\n/** A Document is a collection of Chunks. */\nexport declare interface Document {\n  /** The resource name of the Document.\n      Example: fileSearchStores/file-search-store-foo/documents/documents-bar */\n  name?: string;\n  /** The human-readable display name for the Document. */\n  displayName?: string;\n  /** The current state of the Document. */\n  state?: DocumentState;\n  /** The size of the Document in bytes. */\n  sizeBytes?: string;\n  /** The MIME type of the Document. */\n  mimeType?: string;\n  /** Output only. The Timestamp of when the `Document` was created. */\n  createTime?: string;\n  /** Optional. User provided custom metadata stored as key-value pairs used for querying. A `Document` can have a maximum of 20 `CustomMetadata`. */\n  customMetadata?: CustomMetadata[];\n  /** Output only. The Timestamp of when the `Document` was last updated. */\n  updateTime?: string;\n}\n\n/** Config for optional parameters. */\nexport declare interface DeleteDocumentConfig {\n  /** Used to override HTTP request options. */\n  httpOptions?: HttpOptions;\n  /** Abort signal which can be used to cancel the request.\n\n  NOTE: AbortSignal is a client-only operation. Using it to cancel an\n  operation will not cancel the request in the service. You will still\n  be charged usage for any applicable operations.\n       */\n  abortSignal?: AbortSignal;\n  /** If set to true, any `Chunk`s and objects related to this `Document` will\n      also be deleted.\n       */\n  force?: boolean;\n}\n\n/** Config for documents.delete parameters. */\nexport declare interface DeleteDocumentParameters {\n  /** The resource name of the Document.\n    Example: fileSearchStores/file-search-store-foo/documents/documents-bar */\n  name: string;\n  /** Optional parameters for the request. */\n  config?: DeleteDocumentConfig;\n}\n\n/** Config for optional parameters. */\nexport declare interface ListDocumentsConfig {\n  /** Used to override HTTP request options. */\n  httpOptions?: HttpOptions;\n  /** Abort signal which can be used to cancel the request.\n\n  NOTE: AbortSignal is a client-only operation. Using it to cancel an\n  operation will not cancel the request in the service. You will still\n  be charged usage for any applicable operations.\n       */\n  abortSignal?: AbortSignal;\n  pageSize?: number;\n  pageToken?: string;\n}\n\n/** Config for documents.list parameters. */\nexport declare interface ListDocumentsParameters {\n  /** The resource name of the FileSearchStores. Example: `fileSearchStore/file-search-store-foo` */\n  parent: string;\n  config?: ListDocumentsConfig;\n}\n\n/** Config for documents.list return value. */\nexport class ListDocumentsResponse {\n  /** Used to retain the full HTTP response. */\n  sdkHttpResponse?: HttpResponse;\n  /** A token, which can be sent as `page_token` to retrieve the next page. If this field is omitted, there are no more pages. */\n  nextPageToken?: string;\n  /** The returned `Document`s. */\n  documents?: Document[];\n}\n\n/** Optional parameters for creating a file search store. */\nexport declare interface CreateFileSearchStoreConfig {\n  /** Used to override HTTP request options. */\n  httpOptions?: HttpOptions;\n  /** Abort signal which can be used to cancel the request.\n\n  NOTE: AbortSignal is a client-only operation. Using it to cancel an\n  operation will not cancel the request in the service. You will still\n  be charged usage for any applicable operations.\n       */\n  abortSignal?: AbortSignal;\n  /** The human-readable display name for the file search store.\n   */\n  displayName?: string;\n}\n\n/** Config for file_search_stores.create parameters. */\nexport declare interface CreateFileSearchStoreParameters {\n  /** Optional parameters for creating a file search store.\n   */\n  config?: CreateFileSearchStoreConfig;\n}\n\n/** A collection of Documents. */\nexport declare interface FileSearchStore {\n  /** The resource name of the FileSearchStore. Example: `fileSearchStores/my-file-search-store-123` */\n  name?: string;\n  /** The human-readable display name for the FileSearchStore. */\n  displayName?: string;\n  /** The Timestamp of when the FileSearchStore was created. */\n  createTime?: string;\n  /** The Timestamp of when the FileSearchStore was last updated. */\n  updateTime?: string;\n  /** The number of documents in the FileSearchStore that are active and ready for retrieval. */\n  activeDocumentsCount?: string;\n  /** The number of documents in the FileSearchStore that are being processed. */\n  pendingDocumentsCount?: string;\n  /** The number of documents in the FileSearchStore that have failed processing. */\n  failedDocumentsCount?: string;\n  /** The size of raw bytes ingested into the FileSearchStore. This is the\n      total size of all the documents in the FileSearchStore. */\n  sizeBytes?: string;\n}\n\n/** Optional parameters for getting a FileSearchStore. */\nexport declare interface GetFileSearchStoreConfig {\n  /** Used to override HTTP request options. */\n  httpOptions?: HttpOptions;\n  /** Abort signal which can be used to cancel the request.\n\n  NOTE: AbortSignal is a client-only operation. Using it to cancel an\n  operation will not cancel the request in the service. You will still\n  be charged usage for any applicable operations.\n       */\n  abortSignal?: AbortSignal;\n}\n\n/** Config for file_search_stores.get parameters. */\nexport declare interface GetFileSearchStoreParameters {\n  /** The resource name of the FileSearchStore. Example: `fileSearchStores/my-file-search-store-123` */\n  name: string;\n  /** Optional parameters for the request. */\n  config?: GetFileSearchStoreConfig;\n}\n\n/** Optional parameters for deleting a FileSearchStore. */\nexport declare interface DeleteFileSearchStoreConfig {\n  /** Used to override HTTP request options. */\n  httpOptions?: HttpOptions;\n  /** Abort signal which can be used to cancel the request.\n\n  NOTE: AbortSignal is a client-only operation. Using it to cancel an\n  operation will not cancel the request in the service. You will still\n  be charged usage for any applicable operations.\n       */\n  abortSignal?: AbortSignal;\n  /** If set to true, any Documents and objects related to this FileSearchStore will also be deleted.\n      If false (the default), a FAILED_PRECONDITION error will be returned if\n      the FileSearchStore contains any Documents.\n       */\n  force?: boolean;\n}\n\n/** Config for file_search_stores.delete parameters. */\nexport declare interface DeleteFileSearchStoreParameters {\n  /** The resource name of the FileSearchStore. Example: `fileSearchStores/my-file-search-store-123` */\n  name: string;\n  /** Optional parameters for the request. */\n  config?: DeleteFileSearchStoreConfig;\n}\n\n/** Optional parameters for listing FileSearchStore. */\nexport declare interface ListFileSearchStoresConfig {\n  /** Used to override HTTP request options. */\n  httpOptions?: HttpOptions;\n  /** Abort signal which can be used to cancel the request.\n\n  NOTE: AbortSignal is a client-only operation. Using it to cancel an\n  operation will not cancel the request in the service. You will still\n  be charged usage for any applicable operations.\n       */\n  abortSignal?: AbortSignal;\n  pageSize?: number;\n  pageToken?: string;\n}\n\n/** Config for file_search_stores.list parameters. */\nexport declare interface ListFileSearchStoresParameters {\n  /** Optional parameters for the list request. */\n  config?: ListFileSearchStoresConfig;\n}\n\n/** Config for file_search_stores.list return value. */\nexport class ListFileSearchStoresResponse {\n  /** Used to retain the full HTTP response. */\n  sdkHttpResponse?: HttpResponse;\n  nextPageToken?: string;\n  /** The returned file search stores. */\n  fileSearchStores?: FileSearchStore[];\n}\n\n/** Configuration for a white space chunking algorithm. */\nexport declare interface WhiteSpaceConfig {\n  /** Maximum number of tokens per chunk. */\n  maxTokensPerChunk?: number;\n  /** Maximum number of overlapping tokens between two adjacent chunks. */\n  maxOverlapTokens?: number;\n}\n\n/** Config for telling the service how to chunk the file. */\nexport declare interface ChunkingConfig {\n  /** White space chunking configuration. */\n  whiteSpaceConfig?: WhiteSpaceConfig;\n}\n\n/** Optional parameters for uploading a file to a FileSearchStore. */\nexport declare interface UploadToFileSearchStoreConfig {\n  /** Used to override HTTP request options. */\n  httpOptions?: HttpOptions;\n  /** Abort signal which can be used to cancel the request.\n\n  NOTE: AbortSignal is a client-only operation. Using it to cancel an\n  operation will not cancel the request in the service. You will still\n  be charged usage for any applicable operations.\n       */\n  abortSignal?: AbortSignal;\n  /** MIME type of the file to be uploaded. If not provided, it will be inferred from the file extension. */\n  mimeType?: string;\n  /** Display name of the created document. */\n  displayName?: string;\n  /** User provided custom metadata stored as key-value pairs used for querying. */\n  customMetadata?: CustomMetadata[];\n  /** Config for telling the service how to chunk the file. */\n  chunkingConfig?: ChunkingConfig;\n}\n\n/** Generates the parameters for the private _upload_to_file_search_store method. */\nexport declare interface UploadToFileSearchStoreParameters {\n  /** The resource name of the FileSearchStore. Example: `fileSearchStores/my-file-search-store-123` */\n  fileSearchStoreName: string;\n  /** Used to override the default configuration. */\n  config?: UploadToFileSearchStoreConfig;\n}\n\n/** Response for the resumable upload method. */\nexport class UploadToFileSearchStoreResumableResponse {\n  /** Used to retain the full HTTP response. */\n  sdkHttpResponse?: HttpResponse;\n}\n\n/** Optional parameters for importing a file. */\nexport declare interface ImportFileConfig {\n  /** Used to override HTTP request options. */\n  httpOptions?: HttpOptions;\n  /** Abort signal which can be used to cancel the request.\n\n  NOTE: AbortSignal is a client-only operation. Using it to cancel an\n  operation will not cancel the request in the service. You will still\n  be charged usage for any applicable operations.\n       */\n  abortSignal?: AbortSignal;\n  /** User provided custom metadata stored as key-value pairs used for querying. */\n  customMetadata?: CustomMetadata[];\n  /** Config for telling the service how to chunk the file. */\n  chunkingConfig?: ChunkingConfig;\n}\n\n/** Config for file_search_stores.import_file parameters. */\nexport declare interface ImportFileParameters {\n  /** The resource name of the FileSearchStore. Example: `fileSearchStores/my-file-search-store-123` */\n  fileSearchStoreName: string;\n  /** The name of the File API File to import. Example: `files/abc-123` */\n  fileName: string;\n  /** Optional parameters for the request. */\n  config?: ImportFileConfig;\n}\n\n/** Response for ImportFile to import a File API file with a file search store. */\nexport class ImportFileResponse {\n  /** Used to retain the full HTTP response. */\n  sdkHttpResponse?: HttpResponse;\n  /** The name of the FileSearchStore containing Documents. */\n  parent?: string;\n  /** The identifier for the Document imported. */\n  documentName?: string;\n}\n\n/** Long-running operation for importing a file to a FileSearchStore. */\nexport class ImportFileOperation implements Operation<ImportFileResponse> {\n  /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */\n  name?: string;\n  /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata.  Any method that returns a long-running operation should document the metadata type, if any. */\n  metadata?: Record<string, unknown>;\n  /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */\n  done?: boolean;\n  /** The error result of the operation in case of failure or cancellation. */\n  error?: Record<string, unknown>;\n  /** The result of the ImportFile operation, available when the operation is done. */\n  response?: ImportFileResponse;\n\n  /**\n   * Instantiates an Operation of the same type as the one being called with the fields set from the API response.\n   * @internal\n   */\n  _fromAPIResponse({\n    apiResponse,\n    _isVertexAI,\n  }: OperationFromAPIResponseParameters): Operation<ImportFileResponse> {\n    const operation = new ImportFileOperation();\n\n    const op = apiResponse as unknown as ImportFileOperation;\n    const response = importFileOperationFromMldev(op);\n    Object.assign(operation, response);\n    return operation;\n  }\n  /** The full HTTP response. */\n  sdkHttpResponse?: HttpResponse;\n}\n\nexport /** Used to override the default configuration. */\ndeclare interface ListFilesConfig {\n  /** Used to override HTTP request options. */\n  httpOptions?: HttpOptions;\n  /** Abort signal which can be used to cancel the request.\n\n  NOTE: AbortSignal is a client-only operation. Using it to cancel an\n  operation will not cancel the request in the service. You will still\n  be charged usage for any applicable operations.\n       */\n  abortSignal?: AbortSignal;\n  pageSize?: number;\n  pageToken?: string;\n}\n\n/** Generates the parameters for the list method. */\nexport declare interface ListFilesParameters {\n  /** Used to override the default configuration. */\n  config?: ListFilesConfig;\n}\n\n/** Status of a File that uses a common error model. */\nexport declare interface FileStatus {\n  /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */\n  details?: Record<string, unknown>[];\n  /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */\n  message?: string;\n  /** The status code. 0 for OK, 1 for CANCELLED */\n  code?: number;\n}\n\n/** A file uploaded to the API. */\nexport declare interface File {\n  /** The `File` resource name. The ID (name excluding the \"files/\" prefix) can contain up to 40 characters that are lowercase alphanumeric or dashes (-). The ID cannot start or end with a dash. If the name is empty on create, a unique name will be generated. Example: `files/123-456` */\n  name?: string;\n  /** Optional. The human-readable display name for the `File`. The display name must be no more than 512 characters in length, including spaces. Example: 'Welcome Image' */\n  displayName?: string;\n  /** Output only. MIME type of the file. */\n  mimeType?: string;\n  /** Output only. Size of the file in bytes. */\n  sizeBytes?: string;\n  /** Output only. The timestamp of when the `File` was created. */\n  createTime?: string;\n  /** Output only. The timestamp of when the `File` will be deleted. Only set if the `File` is scheduled to expire. */\n  expirationTime?: string;\n  /** Output only. The timestamp of when the `File` was last updated. */\n  updateTime?: string;\n  /** Output only. SHA-256 hash of the uploaded bytes. The hash value is encoded in base64 format. */\n  sha256Hash?: string;\n  /** Output only. The URI of the `File`. */\n  uri?: string;\n  /** Output only. The URI of the `File`, only set for downloadable (generated) files. */\n  downloadUri?: string;\n  /** Output only. Processing state of the File. */\n  state?: FileState;\n  /** Output only. The source of the `File`. */\n  source?: FileSource;\n  /** Output only. Metadata for a video. */\n  videoMetadata?: Record<string, unknown>;\n  /** Output only. Error status if File processing failed. */\n  error?: FileStatus;\n}\n\n/** Response for the list files method. */\nexport class ListFilesResponse {\n  /** Used to retain the full HTTP response. */\n  sdkHttpResponse?: HttpResponse;\n  /** A token that can be sent as a `page_token` into a subsequent `ListFiles` call. */\n  nextPageToken?: string;\n  /** The list of `File`s. */\n  files?: File[];\n}\n\n/** Used to override the default configuration. */\nexport declare interface CreateFileConfig {\n  /** Used to override HTTP request options. */\n  httpOptions?: HttpOptions;\n  /** Abort signal which can be used to cancel the request.\n\n  NOTE: AbortSignal is a client-only operation. Using it to cancel an\n  operation will not cancel the request in the service. You will still\n  be charged usage for any applicable operations.\n       */\n  abortSignal?: AbortSignal;\n}\n\n/** Generates the parameters for the private _create method. */\nexport declare interface CreateFileParameters {\n  /** The file to be uploaded.\n            mime_type: (Required) The MIME type of the file. Must be provided.\n            name: (Optional) The name of the file in the destination (e.g.\n            'files/sample-image').\n            display_name: (Optional) The display name of the file.\n       */\n  file: File;\n  /** Used to override the default configuration. */\n  config?: CreateFileConfig;\n}\n\n/** Response for the create file method. */\nexport class CreateFileResponse {\n  /** Used to retain the full HTTP response. */\n  sdkHttpResponse?: HttpResponse;\n}\n\n/** Used to override the default configuration. */\nexport declare interface GetFileConfig {\n  /** Used to override HTTP request options. */\n  httpOptions?: HttpOptions;\n  /** Abort signal which can be used to cancel the request.\n\n  NOTE: AbortSignal is a client-only operation. Using it to cancel an\n  operation will not cancel the request in the service. You will still\n  be charged usage for any applicable operations.\n       */\n  abortSignal?: AbortSignal;\n}\n\n/** Generates the parameters for the get method. */\nexport declare interface GetFileParameters {\n  /** The name identifier for the file to retrieve. */\n  name: string;\n  /** Used to override the default configuration. */\n  config?: GetFileConfig;\n}\n\n/** Used to override the default configuration. */\nexport declare interface DeleteFileConfig {\n  /** Used to override HTTP request options. */\n  httpOptions?: HttpOptions;\n  /** Abort signal which can be used to cancel the request.\n\n  NOTE: AbortSignal is a client-only operation. Using it to cancel an\n  operation will not cancel the request in the service. You will still\n  be charged usage for any applicable operations.\n       */\n  abortSignal?: AbortSignal;\n}\n\n/** Generates the parameters for the get method. */\nexport declare interface DeleteFileParameters {\n  /** The name identifier for the file to be deleted. */\n  name: string;\n  /** Used to override the default configuration. */\n  config?: DeleteFileConfig;\n}\n\n/** Response for the delete file method. */\nexport class DeleteFileResponse {\n  /** Used to retain the full HTTP response. */\n  sdkHttpResponse?: HttpResponse;\n}\n\n/** Config for inlined request. */\nexport declare interface InlinedRequest {\n  /** ID of the model to use. For a list of models, see `Google models\n      <https://cloud.google.com/vertex-ai/generative-ai/docs/learn/models>`_. */\n  model?: string;\n  /** Content of the request.\n   */\n  contents?: ContentListUnion;\n  /** The metadata to be associated with the request. */\n  metadata?: Record<string, string>;\n  /** Configuration that contains optional model parameters.\n   */\n  config?: GenerateContentConfig;\n}\n\n/** Config for `src` parameter. */\nexport declare interface BatchJobSource {\n  /** Storage format of the input files. Must be one of:\n      'jsonl', 'bigquery'.\n       */\n  format?: string;\n  /** The Google Cloud Storage URIs to input files.\n   */\n  gcsUri?: string[];\n  /** The BigQuery URI to input table.\n   */\n  bigqueryUri?: string;\n  /** The Gemini Developer API's file resource name of the input data\n      (e.g. \"files/12345\").\n       */\n  fileName?: string;\n  /** The Gemini Developer API's inlined input data to run batch job.\n   */\n  inlinedRequests?: InlinedRequest[];\n}\n\n/** Job error. */\nexport declare interface JobError {\n  /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */\n  details?: string[];\n  /** The status code. */\n  code?: number;\n  /** A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the `details` field. */\n  message?: string;\n}\n\n/** Config for `inlined_responses` parameter. */\nexport class InlinedResponse {\n  /** The response to the request.\n   */\n  response?: GenerateContentResponse;\n  /** The error encountered while processing the request.\n   */\n  error?: JobError;\n}\n\n/** Config for `response` parameter. */\nexport class SingleEmbedContentResponse {\n  /** The response to the request.\n   */\n  embedding?: ContentEmbedding;\n  /** The error encountered while processing the request.\n   */\n  tokenCount?: string;\n}\n\n/** Config for `inlined_embedding_responses` parameter. */\nexport class InlinedEmbedContentResponse {\n  /** The response to the request.\n   */\n  response?: SingleEmbedContentResponse;\n  /** The error encountered while processing the request.\n   */\n  error?: JobError;\n}\n\n/** Config for `des` parameter. */\nexport declare interface BatchJobDestination {\n  /** Storage format of the output files. Must be one of:\n      'jsonl', 'bigquery'.\n       */\n  format?: string;\n  /** The Google Cloud Storage URI to the output file.\n   */\n  gcsUri?: string;\n  /** The BigQuery URI to the output table.\n   */\n  bigqueryUri?: string;\n  /** The Gemini Developer API's file resource name of the output data\n      (e.g. \"files/12345\"). The file will be a JSONL file with a single response\n      per line. The responses will be GenerateContentResponse messages formatted\n      as JSON. The responses will be written in the same order as the input\n      requests.\n       */\n  fileName?: string;\n  /** The responses to the requests in the batch. Returned when the batch was\n      built using inlined requests. The responses will be in the same order as\n      the input requests.\n       */\n  inlinedResponses?: InlinedResponse[];\n  /** The responses to the requests in the batch. Returned when the batch was\n      built using inlined requests. The responses will be in the same order as\n      the input requests.\n       */\n  inlinedEmbedContentResponses?: InlinedEmbedContentResponse[];\n}\n\n/** Config for optional parameters. */\nexport declare interface CreateBatchJobConfig {\n  /** Used to override HTTP request options. */\n  httpOptions?: HttpOptions;\n  /** Abort signal which can be used to cancel the request.\n\n  NOTE: AbortSignal is a client-only operation. Using it to cancel an\n  operation will not cancel the request in the service. You will still\n  be charged usage for any applicable operations.\n       */\n  abortSignal?: AbortSignal;\n  /** The user-defined name of this BatchJob.\n   */\n  displayName?: string;\n  /** GCS or BigQuery URI prefix for the output predictions. Example:\n      \"gs://path/to/output/data\" or \"bq://projectId.bqDatasetId.bqTableId\".\n       */\n  dest?: BatchJobDestinationUnion;\n}\n\n/** Config for batches.create parameters. */\nexport declare interface CreateBatchJobParameters {\n  /** The name of the model to produces the predictions via the BatchJob.\n   */\n  model?: string;\n  /** GCS URI(-s) or BigQuery URI to your input data to run batch job.\n      Example: \"gs://path/to/input/data\" or \"bq://projectId.bqDatasetId.bqTableId\".\n       */\n  src: BatchJobSourceUnion;\n  /** Optional parameters for creating a BatchJob.\n   */\n  config?: CreateBatchJobConfig;\n}\n\n/** Success and error statistics of processing multiple entities (for example, DataItems or structured data rows) in batch. This data type is not supported in Gemini API. */\nexport declare interface CompletionStats {\n  /** Output only. The number of entities for which any error was encountered. */\n  failedCount?: string;\n  /** Output only. In cases when enough errors are encountered a job, pipeline, or operation may be failed as a whole. Below is the number of entities for which the processing had not been finished (either in successful or failed state). Set to -1 if the number is unknown (for example, the operation failed before the total entity number could be collected). */\n  incompleteCount?: string;\n  /** Output only. The number of entities that had been processed successfully. */\n  successfulCount?: string;\n  /** Output only. The number of the successful forecast points that are generated by the forecasting model. This is ONLY used by the forecasting batch prediction. */\n  successfulForecastPointCount?: string;\n}\n\n/** Config for batches.create return value. */\nexport declare interface BatchJob {\n  /** The resource name of the BatchJob. Output only.\".\n   */\n  name?: string;\n  /** The display name of the BatchJob.\n   */\n  displayName?: string;\n  /** The state of the BatchJob.\n   */\n  state?: JobState;\n  /** Output only. Only populated when the job's state is JOB_STATE_FAILED or JOB_STATE_CANCELLED. */\n  error?: JobError;\n  /** The time when the BatchJob was created.\n   */\n  createTime?: string;\n  /** Output only. Time when the Job for the first time entered the `JOB_STATE_RUNNING` state. */\n  startTime?: string;\n  /** The time when the BatchJob was completed. This field is for Vertex AI only.\n   */\n  endTime?: string;\n  /** The time when the BatchJob was last updated.\n   */\n  updateTime?: string;\n  /** The name of the model that produces the predictions via the BatchJob.\n   */\n  model?: string;\n  /** Configuration for the input data. This field is for Vertex AI only.\n   */\n  src?: BatchJobSource;\n  /** Configuration for the output data.\n   */\n  dest?: BatchJobDestination;\n  /** Statistics on completed and failed prediction instances. This field is for Vertex AI only.\n   */\n  completionStats?: CompletionStats;\n}\n\n/** Parameters for the embed_content method. */\nexport declare interface EmbedContentBatch {\n  /** The content to embed. Only the `parts.text` fields will be counted.\n   */\n  contents?: ContentListUnion;\n  /** Configuration that contains optional parameters.\n   */\n  config?: EmbedContentConfig;\n}\n\nexport declare interface EmbeddingsBatchJobSource {\n  /** The Gemini Developer API's file resource name of the input data\n      (e.g. \"files/12345\").\n       */\n  fileName?: string;\n  /** The Gemini Developer API's inlined input data to run batch job.\n   */\n  inlinedRequests?: EmbedContentBatch;\n}\n\n/** Config for optional parameters. */\nexport declare interface CreateEmbeddingsBatchJobConfig {\n  /** Used to override HTTP request options. */\n  httpOptions?: HttpOptions;\n  /** Abort signal which can be used to cancel the request.\n\n  NOTE: AbortSignal is a client-only operation. Using it to cancel an\n  operation will not cancel the request in the service. You will still\n  be charged usage for any applicable operations.\n       */\n  abortSignal?: AbortSignal;\n  /** The user-defined name of this BatchJob.\n   */\n  displayName?: string;\n}\n\n/** Config for batches.create parameters. */\nexport declare interface CreateEmbeddingsBatchJobParameters {\n  /** The name of the model to produces the predictions via the BatchJob.\n   */\n  model?: string;\n  /** input data to run batch job\".\n   */\n  src: EmbeddingsBatchJobSource;\n  /** Optional parameters for creating a BatchJob.\n   */\n  config?: CreateEmbeddingsBatchJobConfig;\n}\n\n/** Optional parameters. */\nexport declare interface GetBatchJobConfig {\n  /** Used to override HTTP request options. */\n  httpOptions?: HttpOptions;\n  /** Abort signal which can be used to cancel the request.\n\n  NOTE: AbortSignal is a client-only operation. Using it to cancel an\n  operation will not cancel the request in the service. You will still\n  be charged usage for any applicable operations.\n       */\n  abortSignal?: AbortSignal;\n}\n\n/** Config for batches.get parameters. */\nexport declare interface GetBatchJobParameters {\n  /** A fully-qualified BatchJob resource name or ID.\n    Example: \"projects/.../locations/.../batchPredictionJobs/456\"\n    or \"456\" when project and location are initialized in the client.\n     */\n  name: string;\n  /** Optional parameters for the request. */\n  config?: GetBatchJobConfig;\n}\n\n/** Optional parameters. */\nexport declare interface CancelBatchJobConfig {\n  /** Used to override HTTP request options. */\n  httpOptions?: HttpOptions;\n  /** Abort signal which can be used to cancel the request.\n\n  NOTE: AbortSignal is a client-only operation. Using it to cancel an\n  operation will not cancel the request in the service. You will still\n  be charged usage for any applicable operations.\n       */\n  abortSignal?: AbortSignal;\n}\n\n/** Config for batches.cancel parameters. */\nexport declare interface CancelBatchJobParameters {\n  /** A fully-qualified BatchJob resource name or ID.\n    Example: \"projects/.../locations/.../batchPredictionJobs/456\"\n    or \"456\" when project and location are initialized in the client.\n     */\n  name: string;\n  /** Optional parameters for the request. */\n  config?: CancelBatchJobConfig;\n}\n\n/** Config for optional parameters. */\nexport declare interface ListBatchJobsConfig {\n  /** Used to override HTTP request options. */\n  httpOptions?: HttpOptions;\n  /** Abort signal which can be used to cancel the request.\n\n  NOTE: AbortSignal is a client-only operation. Using it to cancel an\n  operation will not cancel the request in the service. You will still\n  be charged usage for any applicable operations.\n       */\n  abortSignal?: AbortSignal;\n  pageSize?: number;\n  pageToken?: string;\n  filter?: string;\n}\n\n/** Config for batches.list parameters. */\nexport declare interface ListBatchJobsParameters {\n  config?: ListBatchJobsConfig;\n}\n\n/** Config for batches.list return value. */\nexport class ListBatchJobsResponse {\n  /** Used to retain the full HTTP response. */\n  sdkHttpResponse?: HttpResponse;\n  nextPageToken?: string;\n  batchJobs?: BatchJob[];\n}\n\n/** Optional parameters for models.get method. */\nexport declare interface DeleteBatchJobConfig {\n  /** Used to override HTTP request options. */\n  httpOptions?: HttpOptions;\n  /** Abort signal which can be used to cancel the request.\n\n  NOTE: AbortSignal is a client-only operation. Using it to cancel an\n  operation will not cancel the request in the service. You will still\n  be charged usage for any applicable operations.\n       */\n  abortSignal?: AbortSignal;\n}\n\n/** Config for batches.delete parameters. */\nexport declare interface DeleteBatchJobParameters {\n  /** A fully-qualified BatchJob resource name or ID.\n    Example: \"projects/.../locations/.../batchPredictionJobs/456\"\n    or \"456\" when project and location are initialized in the client.\n     */\n  name: string;\n  /** Optional parameters for the request. */\n  config?: DeleteBatchJobConfig;\n}\n\n/** The return value of delete operation. */\nexport declare interface DeleteResourceJob {\n  /** Used to retain the full HTTP response. */\n  sdkHttpResponse?: HttpResponse;\n  name?: string;\n  done?: boolean;\n  error?: JobError;\n}\n\nexport declare interface GetOperationConfig {\n  /** Used to override HTTP request options. */\n  httpOptions?: HttpOptions;\n  /** Abort signal which can be used to cancel the request.\n\n  NOTE: AbortSignal is a client-only operation. Using it to cancel an\n  operation will not cancel the request in the service. You will still\n  be charged usage for any applicable operations.\n       */\n  abortSignal?: AbortSignal;\n}\n\n/** Parameters for the GET method. */\nexport declare interface GetOperationParameters {\n  /** The server-assigned name for the operation. */\n  operationName: string;\n  /** Used to override the default configuration. */\n  config?: GetOperationConfig;\n}\n\nexport declare interface FetchPredictOperationConfig {\n  /** Used to override HTTP request options. */\n  httpOptions?: HttpOptions;\n  /** Abort signal which can be used to cancel the request.\n\n  NOTE: AbortSignal is a client-only operation. Using it to cancel an\n  operation will not cancel the request in the service. You will still\n  be charged usage for any applicable operations.\n       */\n  abortSignal?: AbortSignal;\n}\n\n/** Parameters for the fetchPredictOperation method. */\nexport declare interface FetchPredictOperationParameters {\n  /** The server-assigned name for the operation. */\n  operationName: string;\n  resourceName: string;\n  /** Used to override the default configuration. */\n  config?: FetchPredictOperationConfig;\n}\n\nexport declare interface TestTableItem {\n  /** The name of the test. This is used to derive the replay id. */\n  name?: string;\n  /** The parameters to the test. Use pydantic models. */\n  parameters?: Record<string, unknown>;\n  /** Expects an exception for MLDev matching the string. */\n  exceptionIfMldev?: string;\n  /** Expects an exception for Vertex matching the string. */\n  exceptionIfVertex?: string;\n  /** Use if you don't want to use the default replay id which is derived from the test name. */\n  overrideReplayId?: string;\n  /** True if the parameters contain an unsupported union type. This test  will be skipped for languages that do not support the union type. */\n  hasUnion?: boolean;\n  /** When set to a reason string, this test will be skipped in the API mode. Use this flag for tests that can not be reproduced with the real API. E.g. a test that deletes a resource. */\n  skipInApiMode?: string;\n  /** Keys to ignore when comparing the request and response. This is useful for tests that are not deterministic. */\n  ignoreKeys?: string[];\n}\n\nexport declare interface TestTableFile {\n  comment?: string;\n  testMethod?: string;\n  parameterNames?: string[];\n  testTable?: TestTableItem[];\n}\n\n/** Represents a single request in a replay. */\nexport declare interface ReplayRequest {\n  method?: string;\n  url?: string;\n  headers?: Record<string, string>;\n  bodySegments?: Record<string, unknown>[];\n}\n\n/** Represents a single response in a replay. */\nexport class ReplayResponse {\n  statusCode?: number;\n  headers?: Record<string, string>;\n  bodySegments?: Record<string, unknown>[];\n  sdkResponseSegments?: Record<string, unknown>[];\n}\n\n/** Represents a single interaction, request and response in a replay. */\nexport declare interface ReplayInteraction {\n  request?: ReplayRequest;\n  response?: ReplayResponse;\n}\n\n/** Represents a recorded session. */\nexport declare interface ReplayFile {\n  replayId?: string;\n  interactions?: ReplayInteraction[];\n}\n\n/** Used to override the default configuration. */\nexport declare interface UploadFileConfig {\n  /** Used to override HTTP request options. */\n  httpOptions?: HttpOptions;\n  /** Abort signal which can be used to cancel the request.\n\n  NOTE: AbortSignal is a client-only operation. Using it to cancel an\n  operation will not cancel the request in the service. You will still\n  be charged usage for any applicable operations.\n       */\n  abortSignal?: AbortSignal;\n  /** The name of the file in the destination (e.g., 'files/sample-image'. If not provided one will be generated. */\n  name?: string;\n  /** mime_type: The MIME type of the file. If not provided, it will be inferred from the file extension. */\n  mimeType?: string;\n  /** Optional display name of the file. */\n  displayName?: string;\n}\n\n/** Used to override the default configuration. */\nexport declare interface DownloadFileConfig {\n  /** Used to override HTTP request options. */\n  httpOptions?: HttpOptions;\n  /** Abort signal which can be used to cancel the request.\n\n  NOTE: AbortSignal is a client-only operation. Using it to cancel an\n  operation will not cancel the request in the service. You will still\n  be charged usage for any applicable operations.\n       */\n  abortSignal?: AbortSignal;\n}\n\n/** Parameters used to download a file. */\nexport declare interface DownloadFileParameters {\n  /** The file to download. It can be a file name, a file object or a generated video. */\n  file: DownloadableFileUnion;\n  /** Location where the file should be downloaded to. */\n  downloadPath: string;\n  /** Configuration to for the download operation. */\n  config?: DownloadFileConfig;\n}\n\n/** Configuration for upscaling an image.\n\nFor more information on this configuration, refer to\nthe `Imagen API reference documentation\n<https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/imagen-api>`_. */\nexport declare interface UpscaleImageConfig {\n  /** Used to override HTTP request options. */\n  httpOptions?: HttpOptions;\n  /** Abort signal which can be used to cancel the request.\n\n  NOTE: AbortSignal is a client-only operation. Using it to cancel an\n  operation will not cancel the request in the service. You will still\n  be charged usage for any applicable operations.\n       */\n  abortSignal?: AbortSignal;\n  /** Cloud Storage URI used to store the generated images. */\n  outputGcsUri?: string;\n  /** Filter level for safety filtering. */\n  safetyFilterLevel?: SafetyFilterLevel;\n  /** Allows generation of people by the model. */\n  personGeneration?: PersonGeneration;\n  /** Whether to include a reason for filtered-out images in the\n      response. */\n  includeRaiReason?: boolean;\n  /** The image format that the output should be saved as. */\n  outputMimeType?: string;\n  /** The level of compression. Only applicable if the\n      ``output_mime_type`` is ``image/jpeg``. */\n  outputCompressionQuality?: number;\n  /** Whether to add an image enhancing step before upscaling.\n      It is expected to suppress the noise and JPEG compression artifacts\n      from the input image. */\n  enhanceInputImage?: boolean;\n  /** With a higher image preservation factor, the original image\n      pixels are more respected. With a lower image preservation factor, the\n      output image will have be more different from the input image, but\n      with finer details and less noise. */\n  imagePreservationFactor?: number;\n  /** User specified labels to track billing usage. */\n  labels?: Record<string, string>;\n}\n\n/** User-facing config UpscaleImageParameters. */\nexport declare interface UpscaleImageParameters {\n  /** The model to use. */\n  model: string;\n  /** The input image to upscale. */\n  image: Image;\n  /** The factor to upscale the image (x2 or x4). */\n  upscaleFactor: string;\n  /** Configuration for upscaling. */\n  config?: UpscaleImageConfig;\n}\n\n/** A raw reference image.\n\nA raw reference image represents the base image to edit, provided by the user.\nIt can optionally be provided in addition to a mask reference image or\na style reference image. */\nexport class RawReferenceImage {\n  /** The reference image for the editing operation. */\n  referenceImage?: Image;\n  /** The id of the reference image. */\n  referenceId?: number;\n  /** The type of the reference image. Only set by the SDK. */\n  referenceType?: string;\n  /** Internal method to convert to ReferenceImageAPIInternal. */\n  toReferenceImageAPI(): ReferenceImageAPIInternal {\n    const referenceImageAPI = {\n      referenceType: 'REFERENCE_TYPE_RAW',\n      referenceImage: this.referenceImage,\n      referenceId: this.referenceId,\n    };\n    return referenceImageAPI;\n  }\n}\n\n/** A mask reference image.\n\nThis encapsulates either a mask image provided by the user and configs for\nthe user provided mask, or only config parameters for the model to generate\na mask.\n\nA mask image is an image whose non-zero values indicate where to edit the base\nimage. If the user provides a mask image, the mask must be in the same\ndimensions as the raw image. */\nexport class MaskReferenceImage {\n  /** The reference image for the editing operation. */\n  referenceImage?: Image;\n  /** The id of the reference image. */\n  referenceId?: number;\n  /** The type of the reference image. Only set by the SDK. */\n  referenceType?: string;\n  /** Configuration for the mask reference image. */\n  config?: MaskReferenceConfig;\n  /** Internal method to convert to ReferenceImageAPIInternal. */\n  toReferenceImageAPI(): ReferenceImageAPIInternal {\n    const referenceImageAPI = {\n      referenceType: 'REFERENCE_TYPE_MASK',\n      referenceImage: this.referenceImage,\n      referenceId: this.referenceId,\n      maskImageConfig: this.config,\n    };\n    return referenceImageAPI;\n  }\n}\n\n/** A control reference image.\n\nThe image of the control reference image is either a control image provided\nby the user, or a regular image which the backend will use to generate a\ncontrol image of. In the case of the latter, the\nenable_control_image_computation field in the config should be set to True.\n\nA control image is an image that represents a sketch image of areas for the\nmodel to fill in based on the prompt. */\nexport class ControlReferenceImage {\n  /** The reference image for the editing operation. */\n  referenceImage?: Image;\n  /** The id of the reference image. */\n  referenceId?: number;\n  /** The type of the reference image. Only set by the SDK. */\n  referenceType?: string;\n  /** Configuration for the control reference image. */\n  config?: ControlReferenceConfig;\n  /** Internal method to convert to ReferenceImageAPIInternal. */\n  toReferenceImageAPI(): ReferenceImageAPIInternal {\n    const referenceImageAPI = {\n      referenceType: 'REFERENCE_TYPE_CONTROL',\n      referenceImage: this.referenceImage,\n      referenceId: this.referenceId,\n      controlImageConfig: this.config,\n    };\n    return referenceImageAPI;\n  }\n}\n\n/** A style reference image.\n\nThis encapsulates a style reference image provided by the user, and\nadditionally optional config parameters for the style reference image.\n\nA raw reference image can also be provided as a destination for the style to\nbe applied to. */\nexport class StyleReferenceImage {\n  /** The reference image for the editing operation. */\n  referenceImage?: Image;\n  /** The id of the reference image. */\n  referenceId?: number;\n  /** The type of the reference image. Only set by the SDK. */\n  referenceType?: string;\n  /** Configuration for the style reference image. */\n  config?: StyleReferenceConfig;\n  /** Internal method to convert to ReferenceImageAPIInternal. */\n  toReferenceImageAPI(): ReferenceImageAPIInternal {\n    const referenceImageAPI = {\n      referenceType: 'REFERENCE_TYPE_STYLE',\n      referenceImage: this.referenceImage,\n      referenceId: this.referenceId,\n      styleImageConfig: this.config,\n    };\n    return referenceImageAPI;\n  }\n}\n\n/** A subject reference image.\n\nThis encapsulates a subject reference image provided by the user, and\nadditionally optional config parameters for the subject reference image.\n\nA raw reference image can also be provided as a destination for the subject to\nbe applied to. */\nexport class SubjectReferenceImage {\n  /** The reference image for the editing operation. */\n  referenceImage?: Image;\n  /** The id of the reference image. */\n  referenceId?: number;\n  /** The type of the reference image. Only set by the SDK. */\n  referenceType?: string;\n  /** Configuration for the subject reference image. */\n  config?: SubjectReferenceConfig;\n  /* Internal method to convert to ReferenceImageAPIInternal. */\n  toReferenceImageAPI(): ReferenceImageAPIInternal {\n    const referenceImageAPI = {\n      referenceType: 'REFERENCE_TYPE_SUBJECT',\n      referenceImage: this.referenceImage,\n      referenceId: this.referenceId,\n      subjectImageConfig: this.config,\n    };\n    return referenceImageAPI;\n  }\n}\n\n/** A content reference image.\n\nA content reference image represents a subject to reference (ex. person,\nproduct, animal) provided by the user. It can optionally be provided in\naddition to a style reference image (ex. background, style reference). */\nexport class ContentReferenceImage {\n  /** The reference image for the editing operation. */\n  referenceImage?: Image;\n  /** The id of the reference image. */\n  referenceId?: number;\n  /** The type of the reference image. Only set by the SDK. */\n  referenceType?: string;\n  /** Internal method to convert to ReferenceImageAPIInternal. */\n  toReferenceImageAPI(): ReferenceImageAPIInternal {\n    const referenceImageAPI = {\n      referenceType: 'REFERENCE_TYPE_CONTENT',\n      referenceImage: this.referenceImage,\n      referenceId: this.referenceId,\n    };\n    return referenceImageAPI;\n  }\n}\n\n/** Sent in response to a `LiveGenerateContentSetup` message from the client. */\nexport declare interface LiveServerSetupComplete {\n  /** The session id of the live session. */\n  sessionId?: string;\n}\n\n/** Audio transcription in Server Conent. */\nexport declare interface Transcription {\n  /** Transcription text.\n   */\n  text?: string;\n  /** The bool indicates the end of the transcription.\n   */\n  finished?: boolean;\n}\n\n/** Incremental server update generated by the model in response to client messages.\n\nContent is generated as quickly as possible, and not in real time. Clients\nmay choose to buffer and play it out in real time. */\nexport declare interface LiveServerContent {\n  /** The content that the model has generated as part of the current conversation with the user. */\n  modelTurn?: Content;\n  /** If true, indicates that the model is done generating. Generation will only start in response to additional client messages. Can be set alongside `content`, indicating that the `content` is the last in the turn. */\n  turnComplete?: boolean;\n  /** If true, indicates that a client message has interrupted current model generation. If the client is playing out the content in realtime, this is a good signal to stop and empty the current queue. */\n  interrupted?: boolean;\n  /** Metadata returned to client when grounding is enabled. */\n  groundingMetadata?: GroundingMetadata;\n  /** If true, indicates that the model is done generating. When model is\n      interrupted while generating there will be no generation_complete message\n      in interrupted turn, it will go through interrupted > turn_complete.\n      When model assumes realtime playback there will be delay between\n      generation_complete and turn_complete that is caused by model\n      waiting for playback to finish. If true, indicates that the model\n      has finished generating all content. This is a signal to the client\n      that it can stop sending messages. */\n  generationComplete?: boolean;\n  /** Input transcription. The transcription is independent to the model\n      turn which means it doesn’t imply any ordering between transcription and\n      model turn. */\n  inputTranscription?: Transcription;\n  /** Output transcription. The transcription is independent to the model\n      turn which means it doesn’t imply any ordering between transcription and\n      model turn.\n       */\n  outputTranscription?: Transcription;\n  /** Metadata related to url context retrieval tool. */\n  urlContextMetadata?: UrlContextMetadata;\n  /** Reason for the turn is complete. */\n  turnCompleteReason?: TurnCompleteReason;\n  /** If true, indicates that the model is not generating content because\n      it is waiting for more input from the user, e.g. because it expects the\n      user to continue talking. */\n  waitingForInput?: boolean;\n}\n\n/** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */\nexport declare interface LiveServerToolCall {\n  /** The function call to be executed. */\n  functionCalls?: FunctionCall[];\n}\n\n/** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled.\n\nIf there were side-effects to those tool calls, clients may attempt to undo\nthe tool calls. This message occurs only in cases where the clients interrupt\nserver turns. */\nexport declare interface LiveServerToolCallCancellation {\n  /** The ids of the tool calls to be cancelled. */\n  ids?: string[];\n}\n\n/** Usage metadata about response(s). */\nexport declare interface UsageMetadata {\n  /** Number of tokens in the prompt. When `cached_content` is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content. */\n  promptTokenCount?: number;\n  /** Number of tokens in the cached part of the prompt (the cached content). */\n  cachedContentTokenCount?: number;\n  /** Total number of tokens across all the generated response candidates. */\n  responseTokenCount?: number;\n  /** Number of tokens present in tool-use prompt(s). */\n  toolUsePromptTokenCount?: number;\n  /** Number of tokens of thoughts for thinking models. */\n  thoughtsTokenCount?: number;\n  /** Total token count for prompt, response candidates, and tool-use prompts(if present). */\n  totalTokenCount?: number;\n  /** List of modalities that were processed in the request input. */\n  promptTokensDetails?: ModalityTokenCount[];\n  /** List of modalities that were processed in the cache input. */\n  cacheTokensDetails?: ModalityTokenCount[];\n  /** List of modalities that were returned in the response. */\n  responseTokensDetails?: ModalityTokenCount[];\n  /** List of modalities that were processed in the tool-use prompt. */\n  toolUsePromptTokensDetails?: ModalityTokenCount[];\n  /** Traffic type. This shows whether a request consumes Pay-As-You-Go\n or Provisioned Throughput quota. */\n  trafficType?: TrafficType;\n}\n\n/** Server will not be able to service client soon. */\nexport declare interface LiveServerGoAway {\n  /** The remaining time before the connection will be terminated as ABORTED. The minimal time returned here is specified differently together with the rate limits for a given model. */\n  timeLeft?: string;\n}\n\n/** Update of the session resumption state.\n\nOnly sent if `session_resumption` was set in the connection config. */\nexport declare interface LiveServerSessionResumptionUpdate {\n  /** New handle that represents state that can be resumed. Empty if `resumable`=false. */\n  newHandle?: string;\n  /** True if session can be resumed at this point. It might be not possible to resume session at some points. In that case we send update empty new_handle and resumable=false. Example of such case could be model executing function calls or just generating. Resuming session (using previous session token) in such state will result in some data loss. */\n  resumable?: boolean;\n  /** Index of last message sent by client that is included in state represented by this SessionResumptionToken. Only sent when `SessionResumptionConfig.transparent` is set.\n\nPresence of this index allows users to transparently reconnect and avoid issue of losing some part of realtime audio input/video. If client wishes to temporarily disconnect (for example as result of receiving GoAway) they can do it without losing state by buffering messages sent since last `SessionResmumptionTokenUpdate`. This field will enable them to limit buffering (avoid keeping all requests in RAM).\n\nNote: This should not be used for when resuming a session at some time later -- in those cases partial audio and video frames arelikely not needed. */\n  lastConsumedClientMessageIndex?: string;\n}\n\nexport declare interface VoiceActivityDetectionSignal {\n  /** The type of the VAD signal. */\n  vadSignalType?: VadSignalType;\n}\n\n/** Response message for API call. */\nexport class LiveServerMessage {\n  /** Sent in response to a `LiveClientSetup` message from the client. */\n  setupComplete?: LiveServerSetupComplete;\n  /** Content generated by the model in response to client messages. */\n  serverContent?: LiveServerContent;\n  /** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */\n  toolCall?: LiveServerToolCall;\n  /** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled. */\n  toolCallCancellation?: LiveServerToolCallCancellation;\n  /** Usage metadata about model response(s). */\n  usageMetadata?: UsageMetadata;\n  /** Server will disconnect soon. */\n  goAway?: LiveServerGoAway;\n  /** Update of the session resumption state. */\n  sessionResumptionUpdate?: LiveServerSessionResumptionUpdate;\n  /** Voice activity detection signal. */\n  voiceActivityDetectionSignal?: VoiceActivityDetectionSignal;\n  /**\n   * Returns the concatenation of all text parts from the server content if present.\n   *\n   * @remarks\n   * If there are non-text parts in the response, the concatenation of all text\n   * parts will be returned, and a warning will be logged.\n   */\n  get text(): string | undefined {\n    let text = '';\n    let anyTextPartFound = false;\n    const nonTextParts = [];\n    for (const part of this.serverContent?.modelTurn?.parts ?? []) {\n      for (const [fieldName, fieldValue] of Object.entries(part)) {\n        if (\n          fieldName !== 'text' &&\n          fieldName !== 'thought' &&\n          fieldValue !== null\n        ) {\n          nonTextParts.push(fieldName);\n        }\n      }\n      if (typeof part.text === 'string') {\n        if (typeof part.thought === 'boolean' && part.thought) {\n          continue;\n        }\n        anyTextPartFound = true;\n        text += part.text;\n      }\n    }\n    if (nonTextParts.length > 0) {\n      console.warn(\n        `there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`,\n      );\n    }\n    // part.text === '' is different from part.text is null\n    return anyTextPartFound ? text : undefined;\n  }\n\n  /**\n   * Returns the concatenation of all inline data parts from the server content if present.\n   *\n   * @remarks\n   * If there are non-inline data parts in the\n   * response, the concatenation of all inline data parts will be returned, and\n   * a warning will be logged.\n   */\n  get data(): string | undefined {\n    let data = '';\n    const nonDataParts = [];\n    for (const part of this.serverContent?.modelTurn?.parts ?? []) {\n      for (const [fieldName, fieldValue] of Object.entries(part)) {\n        if (fieldName !== 'inlineData' && fieldValue !== null) {\n          nonDataParts.push(fieldName);\n        }\n      }\n      if (part.inlineData && typeof part.inlineData.data === 'string') {\n        data += atob(part.inlineData.data);\n      }\n    }\n    if (nonDataParts.length > 0) {\n      console.warn(\n        `there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`,\n      );\n    }\n    return data.length > 0 ? btoa(data) : undefined;\n  }\n}\n\n/** Parameters of the fromAPIResponse method of the Operation class. */\nexport declare interface OperationFromAPIResponseParameters {\n  /** The API response to be converted to an Operation. */\n  apiResponse: Record<string, unknown>;\n  /** Whether the API response is from Vertex AI. */\n  _isVertexAI: boolean;\n}\n\n/**\n * Config for thinking feature.\n *\n * @deprecated This interface will be deprecated. Please use `ThinkingConfig` instead.\n */\nexport declare interface GenerationConfigThinkingConfig\n  extends ThinkingConfig {}\n\n/** Configures automatic detection of activity. */\nexport declare interface AutomaticActivityDetection {\n  /** If enabled, detected voice and text input count as activity. If disabled, the client must send activity signals. */\n  disabled?: boolean;\n  /** Determines how likely speech is to be detected. */\n  startOfSpeechSensitivity?: StartSensitivity;\n  /** Determines how likely detected speech is ended. */\n  endOfSpeechSensitivity?: EndSensitivity;\n  /** The required duration of detected speech before start-of-speech is committed. The lower this value the more sensitive the start-of-speech detection is and the shorter speech can be recognized. However, this also increases the probability of false positives. */\n  prefixPaddingMs?: number;\n  /** The required duration of detected non-speech (e.g. silence) before end-of-speech is committed. The larger this value, the longer speech gaps can be without interrupting the user's activity but this will increase the model's latency. */\n  silenceDurationMs?: number;\n}\n\n/** Marks the end of user activity.\n\nThis can only be sent if automatic (i.e. server-side) activity detection is\ndisabled. */\nexport declare interface RealtimeInputConfig {\n  /** If not set, automatic activity detection is enabled by default. If automatic voice detection is disabled, the client must send activity signals. */\n  automaticActivityDetection?: AutomaticActivityDetection;\n  /** Defines what effect activity has. */\n  activityHandling?: ActivityHandling;\n  /** Defines which input is included in the user's turn. */\n  turnCoverage?: TurnCoverage;\n}\n\n/** Configuration of session resumption mechanism.\n\nIncluded in `LiveConnectConfig.session_resumption`. If included server\nwill send `LiveServerSessionResumptionUpdate` messages. */\nexport declare interface SessionResumptionConfig {\n  /** Session resumption handle of previous session (session to restore).\n\nIf not present new session will be started. */\n  handle?: string;\n  /** If set the server will send `last_consumed_client_message_index` in the `session_resumption_update` messages to allow for transparent reconnections. */\n  transparent?: boolean;\n}\n\n/** Context window will be truncated by keeping only suffix of it.\n\nContext window will always be cut at start of USER role turn. System\ninstructions and `BidiGenerateContentSetup.prefix_turns` will not be\nsubject to the sliding window mechanism, they will always stay at the\nbeginning of context window. */\nexport declare interface SlidingWindow {\n  /** Session reduction target -- how many tokens we should keep. Window shortening operation has some latency costs, so we should avoid running it on every turn. Should be < trigger_tokens. If not set, trigger_tokens/2 is assumed. */\n  targetTokens?: string;\n}\n\n/** Enables context window compression -- mechanism managing model context window so it does not exceed given length. */\nexport declare interface ContextWindowCompressionConfig {\n  /** Number of tokens (before running turn) that triggers context window compression mechanism. */\n  triggerTokens?: string;\n  /** Sliding window compression mechanism. */\n  slidingWindow?: SlidingWindow;\n}\n\n/** The audio transcription configuration in Setup. */\nexport declare interface AudioTranscriptionConfig {}\n\n/** Config for proactivity features. */\nexport declare interface ProactivityConfig {\n  /** If enabled, the model can reject responding to the last prompt. For\n        example, this allows the model to ignore out of context speech or to stay\n        silent if the user did not make a request, yet. */\n  proactiveAudio?: boolean;\n}\n\n/** Message contains configuration that will apply for the duration of the streaming session. */\nexport declare interface LiveClientSetup {\n  /** \n      The fully qualified name of the publisher model or tuned model endpoint to\n      use.\n       */\n  model?: string;\n  /** The generation configuration for the session.\n      Note: only a subset of fields are supported.\n       */\n  generationConfig?: GenerationConfig;\n  /** The user provided system instructions for the model.\n      Note: only text should be used in parts and content in each part will be\n      in a separate paragraph. */\n  systemInstruction?: ContentUnion;\n  /**  A list of `Tools` the model may use to generate the next response.\n\n      A `Tool` is a piece of code that enables the system to interact with\n      external systems to perform an action, or set of actions, outside of\n      knowledge and scope of the model. */\n  tools?: ToolListUnion;\n  /** Configures the realtime input behavior in BidiGenerateContent. */\n  realtimeInputConfig?: RealtimeInputConfig;\n  /** Configures session resumption mechanism.\n\n          If included server will send SessionResumptionUpdate messages. */\n  sessionResumption?: SessionResumptionConfig;\n  /** Configures context window compression mechanism.\n\n      If included, server will compress context window to fit into given length. */\n  contextWindowCompression?: ContextWindowCompressionConfig;\n  /** The transcription of the input aligns with the input audio language.\n   */\n  inputAudioTranscription?: AudioTranscriptionConfig;\n  /** The transcription of the output aligns with the language code\n      specified for the output audio.\n       */\n  outputAudioTranscription?: AudioTranscriptionConfig;\n  /** Configures the proactivity of the model. This allows the model to respond proactively to\n    the input and to ignore irrelevant input. */\n  proactivity?: ProactivityConfig;\n  /** Configures the explicit VAD signal. If enabled, the client will send\n      vad_signal to indicate the start and end of speech. This allows the server\n      to process the audio more efficiently. */\n  explicitVadSignal?: boolean;\n}\n\n/** Incremental update of the current conversation delivered from the client.\n\nAll the content here will unconditionally be appended to the conversation\nhistory and used as part of the prompt to the model to generate content.\n\nA message here will interrupt any current model generation. */\nexport declare interface LiveClientContent {\n  /** The content appended to the current conversation with the model.\n\n      For single-turn queries, this is a single instance. For multi-turn\n      queries, this is a repeated field that contains conversation history and\n      latest request.\n       */\n  turns?: Content[];\n  /** If true, indicates that the server content generation should start with\n  the currently accumulated prompt. Otherwise, the server will await\n  additional messages before starting generation. */\n  turnComplete?: boolean;\n}\n\n/** Marks the start of user activity.\n\nThis can only be sent if automatic (i.e. server-side) activity detection is\ndisabled. */\nexport declare interface ActivityStart {}\n\n/** Marks the end of user activity.\n\nThis can only be sent if automatic (i.e. server-side) activity detection is\ndisabled. */\nexport declare interface ActivityEnd {}\n\n/** User input that is sent in real time.\n\nThis is different from `LiveClientContent` in a few ways:\n\n  - Can be sent continuously without interruption to model generation.\n  - If there is a need to mix data interleaved across the\n    `LiveClientContent` and the `LiveClientRealtimeInput`, server attempts to\n    optimize for best response, but there are no guarantees.\n  - End of turn is not explicitly specified, but is rather derived from user\n    activity (for example, end of speech).\n  - Even before the end of turn, the data is processed incrementally\n    to optimize for a fast start of the response from the model.\n  - Is always assumed to be the user's input (cannot be used to populate\n    conversation history). */\nexport declare interface LiveClientRealtimeInput {\n  /** Inlined bytes data for media input. */\n  mediaChunks?: Blob[];\n  /** The realtime audio input stream. */\n  audio?: Blob;\n  /** \nIndicates that the audio stream has ended, e.g. because the microphone was\nturned off.\n\nThis should only be sent when automatic activity detection is enabled\n(which is the default).\n\nThe client can reopen the stream by sending an audio message.\n */\n  audioStreamEnd?: boolean;\n  /** The realtime video input stream. */\n  video?: Blob;\n  /** The realtime text input stream. */\n  text?: string;\n  /** Marks the start of user activity. */\n  activityStart?: ActivityStart;\n  /** Marks the end of user activity. */\n  activityEnd?: ActivityEnd;\n}\n\n/** Client generated response to a `ToolCall` received from the server.\n\nIndividual `FunctionResponse` objects are matched to the respective\n`FunctionCall` objects by the `id` field.\n\nNote that in the unary and server-streaming GenerateContent APIs function\ncalling happens by exchanging the `Content` parts, while in the bidi\nGenerateContent APIs function calling happens over this dedicated set of\nmessages. */\nexport class LiveClientToolResponse {\n  /** The response to the function calls. */\n  functionResponses?: FunctionResponse[];\n}\n\n/** Parameters for sending realtime input to the live API. */\nexport declare interface LiveSendRealtimeInputParameters {\n  /** Realtime input to send to the session. */\n  media?: BlobImageUnion;\n  /** The realtime audio input stream. */\n  audio?: Blob;\n  /** \nIndicates that the audio stream has ended, e.g. because the microphone was\nturned off.\n\nThis should only be sent when automatic activity detection is enabled\n(which is the default).\n\nThe client can reopen the stream by sending an audio message.\n */\n  audioStreamEnd?: boolean;\n  /** The realtime video input stream. */\n  video?: BlobImageUnion;\n  /** The realtime text input stream. */\n  text?: string;\n  /** Marks the start of user activity. */\n  activityStart?: ActivityStart;\n  /** Marks the end of user activity. */\n  activityEnd?: ActivityEnd;\n}\n\n/** Messages sent by the client in the API call. */\nexport declare interface LiveClientMessage {\n  /** Message to be sent by the system when connecting to the API. SDK users should not send this message. */\n  setup?: LiveClientSetup;\n  /** Incremental update of the current conversation delivered from the client. */\n  clientContent?: LiveClientContent;\n  /** User input that is sent in real time. */\n  realtimeInput?: LiveClientRealtimeInput;\n  /** Response to a `ToolCallMessage` received from the server. */\n  toolResponse?: LiveClientToolResponse;\n}\n\n/** Session config for the API connection. */\nexport declare interface LiveConnectConfig {\n  /** Used to override HTTP request options. */\n  httpOptions?: HttpOptions;\n  /** Abort signal which can be used to cancel the request.\n\n  NOTE: AbortSignal is a client-only operation. Using it to cancel an\n  operation will not cancel the request in the service. You will still\n  be charged usage for any applicable operations.\n       */\n  abortSignal?: AbortSignal;\n  /** The generation configuration for the session. */\n  generationConfig?: GenerationConfig;\n  /** The requested modalities of the response. Represents the set of\n      modalities that the model can return. Defaults to AUDIO if not specified.\n       */\n  responseModalities?: Modality[];\n  /** Value that controls the degree of randomness in token selection.\n      Lower temperatures are good for prompts that require a less open-ended or\n      creative response, while higher temperatures can lead to more diverse or\n      creative results.\n       */\n  temperature?: number;\n  /** Tokens are selected from the most to least probable until the sum\n      of their probabilities equals this value. Use a lower value for less\n      random responses and a higher value for more random responses.\n       */\n  topP?: number;\n  /** For each token selection step, the ``top_k`` tokens with the\n      highest probabilities are sampled. Then tokens are further filtered based\n      on ``top_p`` with the final token selected using temperature sampling. Use\n      a lower number for less random responses and a higher number for more\n      random responses.\n       */\n  topK?: number;\n  /** Maximum number of tokens that can be generated in the response.\n   */\n  maxOutputTokens?: number;\n  /** If specified, the media resolution specified will be used.\n   */\n  mediaResolution?: MediaResolution;\n  /** When ``seed`` is fixed to a specific number, the model makes a best\n      effort to provide the same response for repeated requests. By default, a\n      random number is used.\n       */\n  seed?: number;\n  /** The speech generation configuration.\n   */\n  speechConfig?: SpeechConfig;\n  /** Config for thinking features.\n      An error will be returned if this field is set for models that don't\n      support thinking.\n       */\n  thinkingConfig?: ThinkingConfig;\n  /** If enabled, the model will detect emotions and adapt its responses accordingly. */\n  enableAffectiveDialog?: boolean;\n  /** The user provided system instructions for the model.\n      Note: only text should be used in parts and content in each part will be\n      in a separate paragraph. */\n  systemInstruction?: ContentUnion;\n  /** A list of `Tools` the model may use to generate the next response.\n\n      A `Tool` is a piece of code that enables the system to interact with\n      external systems to perform an action, or set of actions, outside of\n      knowledge and scope of the model. */\n  tools?: ToolListUnion;\n  /** Configures session resumption mechanism.\n\nIf included the server will send SessionResumptionUpdate messages. */\n  sessionResumption?: SessionResumptionConfig;\n  /** The transcription of the input aligns with the input audio language.\n   */\n  inputAudioTranscription?: AudioTranscriptionConfig;\n  /** The transcription of the output aligns with the language code\n      specified for the output audio.\n       */\n  outputAudioTranscription?: AudioTranscriptionConfig;\n  /** Configures the realtime input behavior in BidiGenerateContent. */\n  realtimeInputConfig?: RealtimeInputConfig;\n  /** Configures context window compression mechanism.\n\n      If included, server will compress context window to fit into given length. */\n  contextWindowCompression?: ContextWindowCompressionConfig;\n  /** Configures the proactivity of the model. This allows the model to respond proactively to\n    the input and to ignore irrelevant input. */\n  proactivity?: ProactivityConfig;\n  /** Configures the explicit VAD signal. If enabled, the client will send\n      vad_signal to indicate the start and end of speech. This allows the server\n      to process the audio more efficiently. */\n  explicitVadSignal?: boolean;\n}\n\n/** Parameters for connecting to the live API. */\nexport declare interface LiveConnectParameters {\n  /** ID of the model to use. For a list of models, see `Google models\n    <https://cloud.google.com/vertex-ai/generative-ai/docs/learn/models>`_. */\n  model: string;\n  /** callbacks */\n  callbacks: LiveCallbacks;\n  /** Optional configuration parameters for the request.\n   */\n  config?: LiveConnectConfig;\n}\n\n/** Parameters for initializing a new chat session.\n\nThese parameters are used when creating a chat session with the\n`chats.create()` method. */\nexport declare interface CreateChatParameters {\n  /** The name of the model to use for the chat session.\n\n      For example: 'gemini-2.0-flash', 'gemini-2.0-flash-lite', etc. See Gemini API\n      docs to find the available models.\n       */\n  model: string;\n  /** Config for the entire chat session.\n\n      This config applies to all requests within the session\n      unless overridden by a per-request `config` in `SendMessageParameters`.\n       */\n  config?: GenerateContentConfig;\n  /** The initial conversation history for the chat session.\n\n      This allows you to start the chat with a pre-existing history. The history\n      must be a list of `Content` alternating between 'user' and 'model' roles.\n      It should start with a 'user' message.\n       */\n  history?: Content[];\n}\n\n/** Parameters for sending a message within a chat session.\n\nThese parameters are used with the `chat.sendMessage()` method. */\nexport declare interface SendMessageParameters {\n  /** The message to send to the model.\n\n      The SDK will combine all parts into a single 'user' content to send to\n      the model.\n       */\n  message: PartListUnion;\n  /**  Config for this specific request.\n\n      Please note that the per-request config does not change the chat level\n      config, nor inherit from it. If you intend to use some values from the\n      chat's default config, you must explicitly copy them into this per-request\n      config.\n       */\n  config?: GenerateContentConfig;\n}\n\n/** Parameters for sending client content to the live API. */\nexport declare interface LiveSendClientContentParameters {\n  /** Client content to send to the session. */\n  turns?: ContentListUnion;\n  /** If true, indicates that the server content generation should start with\n  the currently accumulated prompt. Otherwise, the server will await\n  additional messages before starting generation. */\n  turnComplete?: boolean;\n}\n\n/** Parameters for sending tool responses to the live API. */\nexport class LiveSendToolResponseParameters {\n  /** Tool responses to send to the session. */\n  functionResponses: FunctionResponse[] | FunctionResponse = [];\n}\n\n/** Message to be sent by the system when connecting to the API. */\nexport declare interface LiveMusicClientSetup {\n  /** The model's resource name. Format: `models/{model}`. */\n  model?: string;\n}\n\n/** Maps a prompt to a relative weight to steer music generation. */\nexport declare interface WeightedPrompt {\n  /** Text prompt. */\n  text?: string;\n  /** Weight of the prompt. The weight is used to control the relative\n      importance of the prompt. Higher weights are more important than lower\n      weights.\n\n      Weight must not be 0. Weights of all weighted_prompts in this\n      LiveMusicClientContent message will be normalized. */\n  weight?: number;\n}\n\n/** User input to start or steer the music. */\nexport declare interface LiveMusicClientContent {\n  /** Weighted prompts as the model input. */\n  weightedPrompts?: WeightedPrompt[];\n}\n\n/** Configuration for music generation. */\nexport declare interface LiveMusicGenerationConfig {\n  /** Controls the variance in audio generation. Higher values produce\n      higher variance. Range is [0.0, 3.0]. */\n  temperature?: number;\n  /** Controls how the model selects tokens for output. Samples the topK\n      tokens with the highest probabilities. Range is [1, 1000]. */\n  topK?: number;\n  /** Seeds audio generation. If not set, the request uses a randomly\n      generated seed. */\n  seed?: number;\n  /** Controls how closely the model follows prompts.\n      Higher guidance follows more closely, but will make transitions more\n      abrupt. Range is [0.0, 6.0]. */\n  guidance?: number;\n  /** Beats per minute. Range is [60, 200]. */\n  bpm?: number;\n  /** Density of sounds. Range is [0.0, 1.0]. */\n  density?: number;\n  /** Brightness of the music. Range is [0.0, 1.0]. */\n  brightness?: number;\n  /** Scale of the generated music. */\n  scale?: Scale;\n  /** Whether the audio output should contain bass. */\n  muteBass?: boolean;\n  /** Whether the audio output should contain drums. */\n  muteDrums?: boolean;\n  /** Whether the audio output should contain only bass and drums. */\n  onlyBassAndDrums?: boolean;\n  /** The mode of music generation. Default mode is QUALITY. */\n  musicGenerationMode?: MusicGenerationMode;\n}\n\n/** Messages sent by the client in the LiveMusicClientMessage call. */\nexport declare interface LiveMusicClientMessage {\n  /** Message to be sent in the first (and only in the first) `LiveMusicClientMessage`.\n      Clients should wait for a `LiveMusicSetupComplete` message before\n      sending any additional messages. */\n  setup?: LiveMusicClientSetup;\n  /** User input to influence music generation. */\n  clientContent?: LiveMusicClientContent;\n  /** Configuration for music generation. */\n  musicGenerationConfig?: LiveMusicGenerationConfig;\n  /** Playback control signal for the music generation. */\n  playbackControl?: LiveMusicPlaybackControl;\n}\n\n/** Sent in response to a `LiveMusicClientSetup` message from the client. */\nexport declare interface LiveMusicServerSetupComplete {}\n\n/** Prompts and config used for generating this audio chunk. */\nexport declare interface LiveMusicSourceMetadata {\n  /** Weighted prompts for generating this audio chunk. */\n  clientContent?: LiveMusicClientContent;\n  /** Music generation config for generating this audio chunk. */\n  musicGenerationConfig?: LiveMusicGenerationConfig;\n}\n\n/** Representation of an audio chunk. */\nexport declare interface AudioChunk {\n  /** Raw bytes of audio data.\n   * @remarks Encoded as base64 string. */\n  data?: string;\n  /** MIME type of the audio chunk. */\n  mimeType?: string;\n  /** Prompts and config used for generating this audio chunk. */\n  sourceMetadata?: LiveMusicSourceMetadata;\n}\n\n/** Server update generated by the model in response to client messages.\n\nContent is generated as quickly as possible, and not in real time.\nClients may choose to buffer and play it out in real time. */\nexport declare interface LiveMusicServerContent {\n  /** The audio chunks that the model has generated. */\n  audioChunks?: AudioChunk[];\n}\n\n/** A prompt that was filtered with the reason. */\nexport declare interface LiveMusicFilteredPrompt {\n  /** The text prompt that was filtered. */\n  text?: string;\n  /** The reason the prompt was filtered. */\n  filteredReason?: string;\n}\n\n/** Response message for the LiveMusicClientMessage call. */\nexport class LiveMusicServerMessage {\n  /** Message sent in response to a `LiveMusicClientSetup` message from the client.\n      Clients should wait for this message before sending any additional messages. */\n  setupComplete?: LiveMusicServerSetupComplete;\n  /** Content generated by the model in response to client messages. */\n  serverContent?: LiveMusicServerContent;\n  /** A prompt that was filtered with the reason. */\n  filteredPrompt?: LiveMusicFilteredPrompt;\n  /**\n   * Returns the first audio chunk from the server content, if present.\n   *\n   * @remarks\n   * If there are no audio chunks in the response, undefined will be returned.\n   */\n  get audioChunk(): AudioChunk | undefined {\n    if (\n      this.serverContent &&\n      this.serverContent.audioChunks &&\n      this.serverContent.audioChunks.length > 0\n    ) {\n      return this.serverContent.audioChunks[0];\n    }\n    return undefined;\n  }\n}\n\n/** Callbacks for the realtime music API. */\nexport interface LiveMusicCallbacks {\n  /**\n   * Called when a message is received from the server.\n   */\n  onmessage: (e: LiveMusicServerMessage) => void;\n  /**\n   * Called when an error occurs.\n   */\n  onerror?: ((e: ErrorEvent) => void) | null;\n  /**\n   * Called when the websocket connection is closed.\n   */\n  onclose?: ((e: CloseEvent) => void) | null;\n}\n\n/** Parameters for the upload file method. */\nexport interface UploadFileParameters {\n  /** The string path to the file to be uploaded or a Blob object. */\n  file: string | globalThis.Blob;\n  /** Configuration that contains optional parameters. */\n  config?: UploadFileConfig;\n}\n\n/** Parameters for the upload file to file search store method. */\nexport interface UploadToFileSearchStoreParameters {\n  /** The name of the file search store to upload. */\n  fileSearchStoreName: string;\n  /** The string path to the file to be uploaded or a Blob object. */\n  file: string | globalThis.Blob;\n  /** Configuration that contains optional parameters. */\n  config?: UploadToFileSearchStoreConfig;\n}\n\n/**\n * CallableTool is an invokable tool that can be executed with external\n * application (e.g., via Model Context Protocol) or local functions with\n * function calling.\n */\nexport interface CallableTool {\n  /**\n   * Returns tool that can be called by Gemini.\n   */\n  tool(): Promise<Tool>;\n  /**\n   * Executes the callable tool with the given function call arguments and\n   * returns the response parts from the tool execution.\n   */\n  callTool(functionCalls: FunctionCall[]): Promise<Part[]>;\n}\n\n/**\n * CallableToolConfig is the configuration for a callable tool.\n */\nexport interface CallableToolConfig {\n  /**\n   * Specifies the model's behavior after invoking this tool.\n   */\n  behavior?: Behavior;\n  /**\n   * Timeout for remote calls in milliseconds. Note this timeout applies only to\n   * tool remote calls, and not making HTTP requests to the API. */\n  timeout?: number;\n}\n\n/** Parameters for connecting to the live API. */\nexport declare interface LiveMusicConnectParameters {\n  /** The model's resource name. */\n  model: string;\n  /** Callbacks invoked on server events. */\n  callbacks: LiveMusicCallbacks;\n}\n\n/** Parameters for setting config for the live music API. */\nexport declare interface LiveMusicSetConfigParameters {\n  /** Configuration for music generation. */\n  musicGenerationConfig: LiveMusicGenerationConfig;\n}\n\n/** Parameters for setting weighted prompts for the live music API. */\nexport declare interface LiveMusicSetWeightedPromptsParameters {\n  /** A map of text prompts to weights to use for the generation request. */\n  weightedPrompts: WeightedPrompt[];\n}\n\n/** Config for auth_tokens.create parameters. */\nexport declare interface AuthToken {\n  /** The name of the auth token. */\n  name?: string;\n}\n\n/** Config for LiveConnectConstraints for Auth Token creation. */\nexport declare interface LiveConnectConstraints {\n  /** ID of the model to configure in the ephemeral token for Live API.\n      For a list of models, see `Gemini models\n      <https://ai.google.dev/gemini-api/docs/models>`. */\n  model?: string;\n  /** Configuration specific to Live API connections created using this token. */\n  config?: LiveConnectConfig;\n}\n\n/** Optional parameters. */\nexport declare interface CreateAuthTokenConfig {\n  /** Used to override HTTP request options. */\n  httpOptions?: HttpOptions;\n  /** Abort signal which can be used to cancel the request.\n\n  NOTE: AbortSignal is a client-only operation. Using it to cancel an\n  operation will not cancel the request in the service. You will still\n  be charged usage for any applicable operations.\n       */\n  abortSignal?: AbortSignal;\n  /** An optional time after which, when using the resulting token,\n      messages in Live API sessions will be rejected. (Gemini may\n      preemptively close the session after this time.)\n\n      If not set then this defaults to 30 minutes in the future. If set, this\n      value must be less than 20 hours in the future. */\n  expireTime?: string;\n  /** The time after which new Live API sessions using the token\n      resulting from this request will be rejected.\n\n      If not set this defaults to 60 seconds in the future. If set, this value\n      must be less than 20 hours in the future. */\n  newSessionExpireTime?: string;\n  /** The number of times the token can be used. If this value is zero\n      then no limit is applied. Default is 1. Resuming a Live API session does\n      not count as a use. */\n  uses?: number;\n  /** Configuration specific to Live API connections created using this token. */\n  liveConnectConstraints?: LiveConnectConstraints;\n  /** Additional fields to lock in the effective LiveConnectParameters. */\n  lockAdditionalFields?: string[];\n}\n\n/** Config for auth_tokens.create parameters. */\nexport declare interface CreateAuthTokenParameters {\n  /** Optional parameters for the request. */\n  config?: CreateAuthTokenConfig;\n}\n\n/** Parameters for the get method of the operations module. */\nexport declare interface OperationGetParameters<T, U extends Operation<T>> {\n  /** Used to override the default configuration. */\n  config?: GetOperationConfig;\n  /** The operation to be retrieved. */\n  operation: U;\n}\n\n/** Fine-tuning job creation parameters - optional fields. */\nexport declare interface CreateTuningJobParameters {\n  /** The base model that is being tuned, e.g., \"gemini-2.5-flash\". */\n  baseModel: string;\n  /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */\n  trainingDataset: TuningDataset;\n  /** Configuration for the tuning job. */\n  config?: CreateTuningJobConfig;\n}\n\n/** The response when long-running operation for uploading a file to a FileSearchStore complete. */\nexport class UploadToFileSearchStoreResponse {\n  /** Used to retain the full HTTP response. */\n  sdkHttpResponse?: HttpResponse;\n  /** The name of the FileSearchStore containing Documents. */\n  parent?: string;\n  /** The identifier for the Document imported. */\n  documentName?: string;\n}\n\n/** Long-running operation for uploading a file to a FileSearchStore. */\nexport class UploadToFileSearchStoreOperation\n  implements Operation<UploadToFileSearchStoreResponse>\n{\n  /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */\n  name?: string;\n  /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata.  Any method that returns a long-running operation should document the metadata type, if any. */\n  metadata?: Record<string, unknown>;\n  /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */\n  done?: boolean;\n  /** The error result of the operation in case of failure or cancellation. */\n  error?: Record<string, unknown>;\n  /** The result of the UploadToFileSearchStore operation, available when the operation is done. */\n  response?: UploadToFileSearchStoreResponse;\n\n  /**\n   * Instantiates an Operation of the same type as the one being called with the fields set from the API response.\n   * @internal\n   */\n  _fromAPIResponse({\n    apiResponse,\n    _isVertexAI,\n  }: OperationFromAPIResponseParameters): Operation<UploadToFileSearchStoreResponse> {\n    const operation = new UploadToFileSearchStoreOperation();\n\n    const op = apiResponse as unknown as UploadToFileSearchStoreOperation;\n    const response = uploadToFileSearchStoreOperationFromMldev(op);\n    Object.assign(operation, response);\n    return operation;\n  }\n  /** The full HTTP response. */\n  sdkHttpResponse?: HttpResponse;\n}\n\nexport type BlobImageUnion = Blob;\n\nexport type PartUnion = Part | string;\n\nexport type PartListUnion = PartUnion[] | PartUnion;\n\nexport type ContentUnion = Content | PartUnion[] | PartUnion;\n\nexport type ContentListUnion = Content | Content[] | PartUnion | PartUnion[];\n\nexport type SchemaUnion = Schema | unknown;\n\nexport type SpeechConfigUnion = SpeechConfig | string;\n\nexport type ToolUnion = Tool | CallableTool;\n\nexport type ToolListUnion = ToolUnion[];\n\nexport type DownloadableFileUnion = string | File | GeneratedVideo | Video;\n\nexport type BatchJobSourceUnion = BatchJobSource | InlinedRequest[] | string;\n\nexport type BatchJobDestinationUnion = BatchJobDestination | string;\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {Tool as McpTool} from '@modelcontextprotocol/sdk/types';\n\nimport {ApiClient} from './_api_client.js';\nimport * as baseTransformers from './_base_transformers.js';\nimport * as types from './types.js';\n\nexport function tModel(apiClient: ApiClient, model: string | unknown): string {\n  if (!model || typeof model !== 'string') {\n    throw new Error('model is required and must be a string');\n  }\n  if (model.includes('..') || model.includes('?') || model.includes('&')) {\n    throw new Error('invalid model parameter');\n  }\n\n  if (apiClient.isVertexAI()) {\n    if (\n      model.startsWith('publishers/') ||\n      model.startsWith('projects/') ||\n      model.startsWith('models/')\n    ) {\n      return model;\n    } else if (model.indexOf('/') >= 0) {\n      const parts = model.split('/', 2);\n      return `publishers/${parts[0]}/models/${parts[1]}`;\n    } else {\n      return `publishers/google/models/${model}`;\n    }\n  } else {\n    if (model.startsWith('models/') || model.startsWith('tunedModels/')) {\n      return model;\n    } else {\n      return `models/${model}`;\n    }\n  }\n}\n\nexport function tCachesModel(\n  apiClient: ApiClient,\n  model: string | unknown,\n): string {\n  const transformedModel = tModel(apiClient, model as string);\n  if (!transformedModel) {\n    return '';\n  }\n\n  if (transformedModel.startsWith('publishers/') && apiClient.isVertexAI()) {\n    // vertex caches only support model name start with projects.\n    return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/${transformedModel}`;\n  } else if (transformedModel.startsWith('models/') && apiClient.isVertexAI()) {\n    return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/publishers/google/${transformedModel}`;\n  } else {\n    return transformedModel;\n  }\n}\n\nexport function tBlobs(\n  blobs: types.BlobImageUnion | types.BlobImageUnion[],\n): types.Blob[] {\n  if (Array.isArray(blobs)) {\n    return blobs.map((blob) => tBlob(blob));\n  } else {\n    return [tBlob(blobs)];\n  }\n}\n\nexport function tBlob(blob: types.BlobImageUnion): types.Blob {\n  if (typeof blob === 'object' && blob !== null) {\n    return blob;\n  }\n\n  throw new Error(\n    `Could not parse input as Blob. Unsupported blob type: ${typeof blob}`,\n  );\n}\n\nexport function tImageBlob(blob: types.BlobImageUnion): types.Blob {\n  const transformedBlob = tBlob(blob);\n  if (\n    transformedBlob.mimeType &&\n    transformedBlob.mimeType.startsWith('image/')\n  ) {\n    return transformedBlob;\n  }\n  throw new Error(`Unsupported mime type: ${transformedBlob.mimeType!}`);\n}\n\nexport function tAudioBlob(blob: types.Blob): types.Blob {\n  const transformedBlob = tBlob(blob);\n  if (\n    transformedBlob.mimeType &&\n    transformedBlob.mimeType.startsWith('audio/')\n  ) {\n    return transformedBlob;\n  }\n  throw new Error(`Unsupported mime type: ${transformedBlob.mimeType!}`);\n}\n\nexport function tPart(origin?: types.PartUnion | null): types.Part {\n  if (origin === null || origin === undefined) {\n    throw new Error('PartUnion is required');\n  }\n  if (typeof origin === 'object') {\n    return origin;\n  }\n  if (typeof origin === 'string') {\n    return {text: origin};\n  }\n  throw new Error(`Unsupported part type: ${typeof origin}`);\n}\n\nexport function tParts(origin?: types.PartListUnion | null): types.Part[] {\n  if (\n    origin === null ||\n    origin === undefined ||\n    (Array.isArray(origin) && origin.length === 0)\n  ) {\n    throw new Error('PartListUnion is required');\n  }\n  if (Array.isArray(origin)) {\n    return origin.map((item) => tPart(item as types.PartUnion)!);\n  }\n  return [tPart(origin)!];\n}\n\nfunction _isContent(origin: unknown): boolean {\n  return (\n    origin !== null &&\n    origin !== undefined &&\n    typeof origin === 'object' &&\n    'parts' in origin &&\n    Array.isArray(origin.parts)\n  );\n}\n\nfunction _isFunctionCallPart(origin: unknown): boolean {\n  return (\n    origin !== null &&\n    origin !== undefined &&\n    typeof origin === 'object' &&\n    'functionCall' in origin\n  );\n}\n\nfunction _isFunctionResponsePart(origin: unknown): boolean {\n  return (\n    origin !== null &&\n    origin !== undefined &&\n    typeof origin === 'object' &&\n    'functionResponse' in origin\n  );\n}\n\nexport function tContent(origin?: types.ContentUnion): types.Content {\n  if (origin === null || origin === undefined) {\n    throw new Error('ContentUnion is required');\n  }\n  if (_isContent(origin)) {\n    // _isContent is a utility function that checks if the\n    // origin is a Content.\n    return origin as types.Content;\n  }\n\n  return {\n    role: 'user',\n    parts: tParts(origin as types.PartListUnion)!,\n  };\n}\n\nexport function tContentsForEmbed(\n  apiClient: ApiClient,\n  origin: types.ContentListUnion,\n): types.ContentUnion[] {\n  if (!origin) {\n    return [];\n  }\n  if (apiClient.isVertexAI() && Array.isArray(origin)) {\n    return origin.flatMap((item) => {\n      const content = tContent(item as types.ContentUnion);\n      if (\n        content.parts &&\n        content.parts.length > 0 &&\n        content.parts[0].text !== undefined\n      ) {\n        return [content.parts[0].text];\n      }\n      return [];\n    });\n  } else if (apiClient.isVertexAI()) {\n    const content = tContent(origin as types.ContentUnion);\n    if (\n      content.parts &&\n      content.parts.length > 0 &&\n      content.parts[0].text !== undefined\n    ) {\n      return [content.parts[0].text];\n    }\n    return [];\n  }\n  if (Array.isArray(origin)) {\n    return origin.map((item) => tContent(item as types.ContentUnion)!);\n  }\n  return [tContent(origin as types.ContentUnion)!];\n}\n\nexport function tContents(origin?: types.ContentListUnion): types.Content[] {\n  if (\n    origin === null ||\n    origin === undefined ||\n    (Array.isArray(origin) && origin.length === 0)\n  ) {\n    throw new Error('contents are required');\n  }\n  if (!Array.isArray(origin)) {\n    // If it's not an array, it's a single content or a single PartUnion.\n    if (_isFunctionCallPart(origin) || _isFunctionResponsePart(origin)) {\n      throw new Error(\n        'To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them',\n      );\n    }\n    return [tContent(origin as types.ContentUnion)];\n  }\n\n  const result: types.Content[] = [];\n  const accumulatedParts: types.PartUnion[] = [];\n  const isContentArray = _isContent(origin[0]);\n\n  for (const item of origin) {\n    const isContent = _isContent(item);\n\n    if (isContent != isContentArray) {\n      throw new Error(\n        'Mixing Content and Parts is not supported, please group the parts into a the appropriate Content objects and specify the roles for them',\n      );\n    }\n\n    if (isContent) {\n      // `isContent` contains the result of _isContent, which is a utility\n      // function that checks if the item is a Content.\n      result.push(item as types.Content);\n    } else if (_isFunctionCallPart(item) || _isFunctionResponsePart(item)) {\n      throw new Error(\n        'To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them',\n      );\n    } else {\n      accumulatedParts.push(item as types.PartUnion);\n    }\n  }\n\n  if (!isContentArray) {\n    result.push({role: 'user', parts: tParts(accumulatedParts)});\n  }\n  return result;\n}\n\n/*\nTransform the type field from an array of types to an array of anyOf fields.\nExample:\n  {type: ['STRING', 'NUMBER']}\nwill be transformed to\n  {anyOf: [{type: 'STRING'}, {type: 'NUMBER'}]}\n*/\nfunction flattenTypeArrayToAnyOf(\n  typeList: string[],\n  resultingSchema: types.Schema,\n) {\n  if (typeList.includes('null')) {\n    resultingSchema['nullable'] = true;\n  }\n  const listWithoutNull = typeList.filter((type) => type !== 'null');\n\n  if (listWithoutNull.length === 1) {\n    resultingSchema['type'] = Object.values(types.Type).includes(\n      listWithoutNull[0].toUpperCase() as types.Type,\n    )\n      ? (listWithoutNull[0].toUpperCase() as types.Type)\n      : types.Type.TYPE_UNSPECIFIED;\n  } else {\n    resultingSchema['anyOf'] = [];\n    for (const i of listWithoutNull) {\n      resultingSchema['anyOf'].push({\n        'type': Object.values(types.Type).includes(\n          i.toUpperCase() as types.Type,\n        )\n          ? (i.toUpperCase() as types.Type)\n          : types.Type.TYPE_UNSPECIFIED,\n      });\n    }\n  }\n}\n\nexport function processJsonSchema(\n  _jsonSchema: types.Schema | Record<string, unknown>,\n): types.Schema {\n  const genAISchema: types.Schema = {};\n  const schemaFieldNames = ['items'];\n  const listSchemaFieldNames = ['anyOf'];\n  const dictSchemaFieldNames = ['properties'];\n\n  if (_jsonSchema['type'] && _jsonSchema['anyOf']) {\n    throw new Error('type and anyOf cannot be both populated.');\n  }\n\n  /*\n  This is to handle the nullable array or object. The _jsonSchema will\n  be in the format of {anyOf: [{type: 'null'}, {type: 'object'}]}. The\n  logic is to check if anyOf has 2 elements and one of the element is null,\n  if so, the anyOf field is unnecessary, so we need to get rid of the anyOf\n  field and make the schema nullable. Then use the other element as the new\n  _jsonSchema for processing. This is because the backend doesn't have a null\n  type.\n  This has to be checked before we process any other fields.\n  For example:\n    const objectNullable = z.object({\n      nullableArray: z.array(z.string()).nullable(),\n    });\n  Will have the raw _jsonSchema as:\n  {\n    type: 'OBJECT',\n    properties: {\n        nullableArray: {\n           anyOf: [\n              {type: 'null'},\n              {\n                type: 'array',\n                items: {type: 'string'},\n              },\n            ],\n        }\n    },\n    required: [ 'nullableArray' ],\n  }\n  Will result in following schema compatible with Gemini API:\n    {\n      type: 'OBJECT',\n      properties: {\n         nullableArray: {\n            nullable: true,\n            type: 'ARRAY',\n            items: {type: 'string'},\n         }\n      },\n      required: [ 'nullableArray' ],\n    }\n  */\n  const incomingAnyOf = _jsonSchema['anyOf'] as Record<string, unknown>[];\n  if (incomingAnyOf != null && incomingAnyOf.length == 2) {\n    if (incomingAnyOf[0]!['type'] === 'null') {\n      genAISchema['nullable'] = true;\n      _jsonSchema = incomingAnyOf![1];\n    } else if (incomingAnyOf[1]!['type'] === 'null') {\n      genAISchema['nullable'] = true;\n      _jsonSchema = incomingAnyOf![0];\n    }\n  }\n\n  if (_jsonSchema['type'] instanceof Array) {\n    flattenTypeArrayToAnyOf(_jsonSchema['type'], genAISchema);\n  }\n\n  for (const [fieldName, fieldValue] of Object.entries(_jsonSchema)) {\n    // Skip if the fieldvalue is undefined or null.\n    if (fieldValue == null) {\n      continue;\n    }\n\n    if (fieldName == 'type') {\n      if (fieldValue === 'null') {\n        throw new Error(\n          'type: null can not be the only possible type for the field.',\n        );\n      }\n      if (fieldValue instanceof Array) {\n        // we have already handled the type field with array of types in the\n        // beginning of this function.\n        continue;\n      }\n      genAISchema['type'] = Object.values(types.Type).includes(\n        fieldValue.toUpperCase() as types.Type,\n      )\n        ? fieldValue.toUpperCase()\n        : types.Type.TYPE_UNSPECIFIED;\n    } else if (schemaFieldNames.includes(fieldName)) {\n      (genAISchema as Record<string, unknown>)[fieldName] =\n        processJsonSchema(fieldValue);\n    } else if (listSchemaFieldNames.includes(fieldName)) {\n      const listSchemaFieldValue: Array<types.Schema> = [];\n      for (const item of fieldValue) {\n        if (item['type'] == 'null') {\n          genAISchema['nullable'] = true;\n          continue;\n        }\n        listSchemaFieldValue.push(\n          processJsonSchema(item as Record<string, unknown>),\n        );\n      }\n      (genAISchema as Record<string, unknown>)[fieldName] =\n        listSchemaFieldValue;\n    } else if (dictSchemaFieldNames.includes(fieldName)) {\n      const dictSchemaFieldValue: Record<string, types.Schema> = {};\n      for (const [key, value] of Object.entries(\n        fieldValue as Record<string, unknown>,\n      )) {\n        dictSchemaFieldValue[key] = processJsonSchema(\n          value as Record<string, unknown>,\n        );\n      }\n      (genAISchema as Record<string, unknown>)[fieldName] =\n        dictSchemaFieldValue;\n    } else {\n      // additionalProperties is not included in JSONSchema, skipping it.\n      if (fieldName === 'additionalProperties') {\n        continue;\n      }\n      (genAISchema as Record<string, unknown>)[fieldName] = fieldValue;\n    }\n  }\n  return genAISchema;\n}\n\n// we take the unknown in the schema field because we want enable user to pass\n// the output of major schema declaration tools without casting. Tools such as\n// zodToJsonSchema, typebox, zodToJsonSchema function can return JsonSchema7Type\n// or object, see details in\n// https://github.com/StefanTerdell/zod-to-json-schema/blob/70525efe555cd226691e093d171370a3b10921d1/src/zodToJsonSchema.ts#L7\n// typebox can return unknown, see details in\n// https://github.com/sinclairzx81/typebox/blob/5a5431439f7d5ca6b494d0d18fbfd7b1a356d67c/src/type/create/type.ts#L35\n// Note: proper json schemas with the $schema field set never arrive to this\n// transformer. Schemas with $schema are routed to the equivalent API json\n// schema field.\nexport function tSchema(schema: types.Schema | unknown): types.Schema {\n  return processJsonSchema(schema as types.Schema);\n}\n\nexport function tSpeechConfig(\n  speechConfig: types.SpeechConfigUnion,\n): types.SpeechConfig {\n  if (typeof speechConfig === 'object') {\n    return speechConfig;\n  } else if (typeof speechConfig === 'string') {\n    return {\n      voiceConfig: {\n        prebuiltVoiceConfig: {\n          voiceName: speechConfig,\n        },\n      },\n    };\n  } else {\n    throw new Error(`Unsupported speechConfig type: ${typeof speechConfig}`);\n  }\n}\n\nexport function tLiveSpeechConfig(\n  speechConfig: types.SpeechConfig | object,\n): types.SpeechConfig {\n  if ('multiSpeakerVoiceConfig' in speechConfig) {\n    throw new Error(\n      'multiSpeakerVoiceConfig is not supported in the live API.',\n    );\n  }\n  return speechConfig;\n}\n\nexport function tTool(tool: types.Tool): types.Tool {\n  if (tool.functionDeclarations) {\n    for (const functionDeclaration of tool.functionDeclarations) {\n      if (functionDeclaration.parameters) {\n        if (!Object.keys(functionDeclaration.parameters).includes('$schema')) {\n          functionDeclaration.parameters = processJsonSchema(\n            functionDeclaration.parameters,\n          );\n        } else {\n          if (!functionDeclaration.parametersJsonSchema) {\n            functionDeclaration.parametersJsonSchema =\n              functionDeclaration.parameters;\n            delete functionDeclaration.parameters;\n          }\n        }\n      }\n      if (functionDeclaration.response) {\n        if (!Object.keys(functionDeclaration.response).includes('$schema')) {\n          functionDeclaration.response = processJsonSchema(\n            functionDeclaration.response,\n          );\n        } else {\n          if (!functionDeclaration.responseJsonSchema) {\n            functionDeclaration.responseJsonSchema =\n              functionDeclaration.response;\n            delete functionDeclaration.response;\n          }\n        }\n      }\n    }\n  }\n  return tool;\n}\n\nexport function tTools(tools: types.ToolListUnion | unknown): types.Tool[] {\n  // Check if the incoming type is defined.\n  if (tools === undefined || tools === null) {\n    throw new Error('tools is required');\n  }\n  if (!Array.isArray(tools)) {\n    throw new Error('tools is required and must be an array of Tools');\n  }\n  const result: types.Tool[] = [];\n  for (const tool of tools) {\n    result.push(tool as types.Tool);\n  }\n  return result;\n}\n\n/**\n * Prepends resource name with project, location, resource_prefix if needed.\n *\n * @param client The API client.\n * @param resourceName The resource name.\n * @param resourcePrefix The resource prefix.\n * @param splitsAfterPrefix The number of splits after the prefix.\n * @returns The completed resource name.\n *\n * Examples:\n *\n * ```\n * resource_name = '123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = True\n * client.project = 'bar'\n * client.location = 'us-west1'\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * returns: 'projects/bar/locations/us-west1/cachedContents/123'\n * ```\n *\n * ```\n * resource_name = 'projects/foo/locations/us-central1/cachedContents/123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = True\n * client.project = 'bar'\n * client.location = 'us-west1'\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * returns: 'projects/foo/locations/us-central1/cachedContents/123'\n * ```\n *\n * ```\n * resource_name = '123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = False\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * returns 'cachedContents/123'\n * ```\n *\n * ```\n * resource_name = 'some/wrong/cachedContents/resource/name/123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = False\n * # client.vertexai = True\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * -> 'some/wrong/resource/name/123'\n * ```\n */\nfunction resourceName(\n  client: ApiClient,\n  resourceName: string,\n  resourcePrefix: string,\n  splitsAfterPrefix: number = 1,\n): string {\n  const shouldAppendPrefix =\n    !resourceName.startsWith(`${resourcePrefix}/`) &&\n    resourceName.split('/').length === splitsAfterPrefix;\n  if (client.isVertexAI()) {\n    if (resourceName.startsWith('projects/')) {\n      return resourceName;\n    } else if (resourceName.startsWith('locations/')) {\n      return `projects/${client.getProject()}/${resourceName}`;\n    } else if (resourceName.startsWith(`${resourcePrefix}/`)) {\n      return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourceName}`;\n    } else if (shouldAppendPrefix) {\n      return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourcePrefix}/${resourceName}`;\n    } else {\n      return resourceName;\n    }\n  }\n  if (shouldAppendPrefix) {\n    return `${resourcePrefix}/${resourceName}`;\n  }\n  return resourceName;\n}\n\nexport function tCachedContentName(\n  apiClient: ApiClient,\n  name: string | unknown,\n): string {\n  if (typeof name !== 'string') {\n    throw new Error('name must be a string');\n  }\n  return resourceName(apiClient, name, 'cachedContents');\n}\n\nexport function tTuningJobStatus(status: string | unknown): string {\n  switch (status) {\n    case 'STATE_UNSPECIFIED':\n      return 'JOB_STATE_UNSPECIFIED';\n    case 'CREATING':\n      return 'JOB_STATE_RUNNING';\n    case 'ACTIVE':\n      return 'JOB_STATE_SUCCEEDED';\n    case 'FAILED':\n      return 'JOB_STATE_FAILED';\n    default:\n      return status as string;\n  }\n}\n\nexport function tBytes(fromImageBytes: string | unknown): string {\n  return baseTransformers.tBytes(fromImageBytes);\n}\n\nfunction _isFile(origin: unknown): boolean {\n  return (\n    origin !== null &&\n    origin !== undefined &&\n    typeof origin === 'object' &&\n    'name' in origin\n  );\n}\n\nexport function isGeneratedVideo(origin: unknown): boolean {\n  return (\n    origin !== null &&\n    origin !== undefined &&\n    typeof origin === 'object' &&\n    'video' in origin\n  );\n}\n\nexport function isVideo(origin: unknown): boolean {\n  return (\n    origin !== null &&\n    origin !== undefined &&\n    typeof origin === 'object' &&\n    'uri' in origin\n  );\n}\n\nexport function tFileName(\n  fromName: string | types.File | types.GeneratedVideo | types.Video,\n): string | undefined {\n  let name: string | undefined;\n\n  if (_isFile(fromName)) {\n    name = (fromName as types.File).name;\n  }\n  if (isVideo(fromName)) {\n    name = (fromName as types.Video).uri;\n    if (name === undefined) {\n      return undefined;\n    }\n  }\n  if (isGeneratedVideo(fromName)) {\n    name = (fromName as types.GeneratedVideo).video?.uri;\n    if (name === undefined) {\n      return undefined;\n    }\n  }\n  if (typeof fromName === 'string') {\n    name = fromName;\n  }\n\n  if (name === undefined) {\n    throw new Error('Could not extract file name from the provided input.');\n  }\n\n  if (name.startsWith('https://')) {\n    const suffix = name.split('files/')[1];\n    const match = suffix.match(/[a-z0-9]+/);\n    if (match === null) {\n      throw new Error(`Could not extract file name from URI ${name}`);\n    }\n    name = match[0];\n  } else if (name.startsWith('files/')) {\n    name = name.split('files/')[1];\n  }\n  return name;\n}\n\nexport function tModelsUrl(\n  apiClient: ApiClient,\n  baseModels: boolean | unknown,\n): string {\n  let res: string;\n  if (apiClient.isVertexAI()) {\n    res = baseModels ? 'publishers/google/models' : 'models';\n  } else {\n    res = baseModels ? 'models' : 'tunedModels';\n  }\n  return res;\n}\n\nexport function tExtractModels(response: unknown): Record<string, unknown>[] {\n  for (const key of ['models', 'tunedModels', 'publisherModels']) {\n    if (hasField(response, key)) {\n      return (response as Record<string, unknown>)[key] as Record<\n        string,\n        unknown\n      >[];\n    }\n  }\n  return [];\n}\n\nfunction hasField(data: unknown, fieldName: string): boolean {\n  return data !== null && typeof data === 'object' && fieldName in data;\n}\n\nexport function mcpToGeminiTool(\n  mcpTool: McpTool,\n  config: types.CallableToolConfig = {},\n): types.Tool {\n  const mcpToolSchema = mcpTool as Record<string, unknown>;\n  const functionDeclaration: Record<string, unknown> = {\n    name: mcpToolSchema['name'],\n    description: mcpToolSchema['description'],\n    parametersJsonSchema: mcpToolSchema['inputSchema'],\n  };\n  if (mcpToolSchema['outputSchema']) {\n    functionDeclaration['responseJsonSchema'] = mcpToolSchema['outputSchema'];\n  }\n  if (config.behavior) {\n    functionDeclaration['behavior'] = config.behavior;\n  }\n\n  const geminiTool = {\n    functionDeclarations: [\n      functionDeclaration as unknown as types.FunctionDeclaration,\n    ],\n  };\n\n  return geminiTool;\n}\n\n/**\n * Converts a list of MCP tools to a single Gemini tool with a list of function\n * declarations.\n */\nexport function mcpToolsToGeminiTool(\n  mcpTools: McpTool[],\n  config: types.CallableToolConfig = {},\n): types.Tool {\n  const functionDeclarations: types.FunctionDeclaration[] = [];\n  const toolNames = new Set<string>();\n  for (const mcpTool of mcpTools) {\n    const mcpToolName = mcpTool.name as string;\n    if (toolNames.has(mcpToolName)) {\n      throw new Error(\n        `Duplicate function name ${\n          mcpToolName\n        } found in MCP tools. Please ensure function names are unique.`,\n      );\n    }\n    toolNames.add(mcpToolName);\n    const geminiTool = mcpToGeminiTool(mcpTool, config);\n    if (geminiTool.functionDeclarations) {\n      functionDeclarations.push(...geminiTool.functionDeclarations);\n    }\n  }\n\n  return {functionDeclarations: functionDeclarations};\n}\n\n// Transforms a source input into a BatchJobSource object with validation.\nexport function tBatchJobSource(\n  client: ApiClient,\n  src: string | types.InlinedRequest[] | types.BatchJobSource,\n): types.BatchJobSource {\n  let sourceObj: types.BatchJobSource;\n\n  if (typeof src === 'string') {\n    if (client.isVertexAI()) {\n      if (src.startsWith('gs://')) {\n        sourceObj = {format: 'jsonl', gcsUri: [src]};\n      } else if (src.startsWith('bq://')) {\n        sourceObj = {format: 'bigquery', bigqueryUri: src};\n      } else {\n        throw new Error(`Unsupported string source for Vertex AI: ${src}`);\n      }\n    } else {\n      // MLDEV\n      if (src.startsWith('files/')) {\n        sourceObj = {fileName: src}; // Default to fileName for string input\n      } else {\n        throw new Error(`Unsupported string source for Gemini API: ${src}`);\n      }\n    }\n  } else if (Array.isArray(src)) {\n    if (client.isVertexAI()) {\n      throw new Error('InlinedRequest[] is not supported in Vertex AI.');\n    }\n    sourceObj = {inlinedRequests: src};\n  } else {\n    // It's already a BatchJobSource object\n    sourceObj = src;\n  }\n\n  // Validation logic\n  const vertexSourcesCount = [sourceObj.gcsUri, sourceObj.bigqueryUri].filter(\n    Boolean,\n  ).length;\n\n  const mldevSourcesCount = [\n    sourceObj.inlinedRequests,\n    sourceObj.fileName,\n  ].filter(Boolean).length;\n\n  if (client.isVertexAI()) {\n    if (mldevSourcesCount > 0 || vertexSourcesCount !== 1) {\n      throw new Error(\n        'Exactly one of `gcsUri` or `bigqueryUri` must be set for Vertex AI.',\n      );\n    }\n  } else {\n    // MLDEV\n    if (vertexSourcesCount > 0 || mldevSourcesCount !== 1) {\n      throw new Error(\n        'Exactly one of `inlinedRequests`, `fileName`, ' +\n          'must be set for Gemini API.',\n      );\n    }\n  }\n\n  return sourceObj;\n}\n\nexport function tEmbeddingBatchJobSource(\n  client: ApiClient,\n  src: types.EmbeddingsBatchJobSource,\n): types.EmbeddingsBatchJobSource {\n  if (client.isVertexAI()) {\n    throw new Error('Embedding batch jobs are not supported in Vertex AI.');\n  }\n\n  const sourceObj: types.EmbeddingsBatchJobSource = {...src};\n\n  const mldevSources =\n    Number(!!sourceObj.inlinedRequests) + Number(!!sourceObj.fileName);\n\n  if (mldevSources !== 1) {\n    throw new Error(\n      'Exactly one of `inlinedRequests` or `fileName` must be set for Embedding Batch Jobs in the Gemini API.',\n    );\n  }\n  return sourceObj;\n}\n\nexport function tBatchJobDestination(\n  dest: string | types.BatchJobDestination,\n): types.BatchJobDestination {\n  if (typeof dest !== 'string') {\n    return dest as types.BatchJobDestination;\n  }\n  const destString = dest as string;\n  if (destString.startsWith('gs://')) {\n    return {\n      format: 'jsonl',\n      gcsUri: destString,\n    };\n  } else if (destString.startsWith('bq://')) {\n    return {\n      format: 'bigquery',\n      bigqueryUri: destString,\n    };\n  } else {\n    throw new Error(`Unsupported destination: ${destString}`);\n  }\n}\n\nexport function tRecvBatchJobDestination(\n  dest: unknown,\n): types.BatchJobDestination {\n  // Ensure dest is a non-null object before proceeding.\n  if (typeof dest !== 'object' || dest === null) {\n    // If the input is not an object, it cannot be a valid BatchJobDestination\n    // based on the operations performed. Return it cast, or handle as an error.\n    // Casting an empty object might be a safe default.\n    return {} as types.BatchJobDestination;\n  }\n\n  // Cast to Record<string, unknown> to allow string property access.\n  const obj = dest as Record<string, unknown>;\n\n  // Safely access nested properties.\n  const inlineResponsesVal = obj['inlinedResponses'];\n  if (typeof inlineResponsesVal !== 'object' || inlineResponsesVal === null) {\n    return dest as types.BatchJobDestination;\n  }\n  const inlineResponsesObj = inlineResponsesVal as Record<string, unknown>;\n\n  const responsesArray = inlineResponsesObj['inlinedResponses'];\n  if (!Array.isArray(responsesArray) || responsesArray.length === 0) {\n    return dest as types.BatchJobDestination;\n  }\n\n  // Check if any response has the 'embedding' property.\n  let hasEmbedding = false;\n  for (const responseItem of responsesArray) {\n    if (typeof responseItem !== 'object' || responseItem === null) {\n      continue;\n    }\n    const responseItemObj = responseItem as Record<string, unknown>;\n\n    const responseVal = responseItemObj['response'];\n    if (typeof responseVal !== 'object' || responseVal === null) {\n      continue;\n    }\n    const responseObj = responseVal as Record<string, unknown>;\n\n    // Check for the existence of the 'embedding' key.\n    if (responseObj['embedding'] !== undefined) {\n      hasEmbedding = true;\n      break;\n    }\n  }\n\n  // Perform the transformation if an embedding was found.\n  if (hasEmbedding) {\n    obj['inlinedEmbedContentResponses'] = obj['inlinedResponses'];\n    delete obj['inlinedResponses'];\n  }\n\n  // Cast the (potentially) modified object to the target type.\n  return dest as types.BatchJobDestination;\n}\n\nexport function tBatchJobName(apiClient: ApiClient, name: unknown): string {\n  const nameString = name as string;\n  if (!apiClient.isVertexAI()) {\n    const mldevPattern = /batches\\/[^/]+$/;\n\n    if (mldevPattern.test(nameString)) {\n      return nameString.split('/').pop() as string;\n    } else {\n      throw new Error(`Invalid batch job name: ${nameString}.`);\n    }\n  }\n\n  const vertexPattern =\n    /^projects\\/[^/]+\\/locations\\/[^/]+\\/batchPredictionJobs\\/[^/]+$/;\n\n  if (vertexPattern.test(nameString)) {\n    return nameString.split('/').pop() as string;\n  } else if (/^\\d+$/.test(nameString)) {\n    return nameString;\n  } else {\n    throw new Error(`Invalid batch job name: ${nameString}.`);\n  }\n}\n\nexport function tJobState(state: unknown): string {\n  const stateString = state as string;\n  if (stateString === 'BATCH_STATE_UNSPECIFIED') {\n    return 'JOB_STATE_UNSPECIFIED';\n  } else if (stateString === 'BATCH_STATE_PENDING') {\n    return 'JOB_STATE_PENDING';\n  } else if (stateString === 'BATCH_STATE_RUNNING') {\n    return 'JOB_STATE_RUNNING';\n  } else if (stateString === 'BATCH_STATE_SUCCEEDED') {\n    return 'JOB_STATE_SUCCEEDED';\n  } else if (stateString === 'BATCH_STATE_FAILED') {\n    return 'JOB_STATE_FAILED';\n  } else if (stateString === 'BATCH_STATE_CANCELLED') {\n    return 'JOB_STATE_CANCELLED';\n  } else if (stateString === 'BATCH_STATE_EXPIRED') {\n    return 'JOB_STATE_EXPIRED';\n  } else {\n    return stateString;\n  }\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport type * as types from '../types.js';\n\nexport function batchJobDestinationFromMldev(\n  fromObject: types.BatchJobDestination,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromFileName = common.getValueByPath(fromObject, ['responsesFile']);\n  if (fromFileName != null) {\n    common.setValueByPath(toObject, ['fileName'], fromFileName);\n  }\n\n  const fromInlinedResponses = common.getValueByPath(fromObject, [\n    'inlinedResponses',\n    'inlinedResponses',\n  ]);\n  if (fromInlinedResponses != null) {\n    let transformedList = fromInlinedResponses;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return inlinedResponseFromMldev(item);\n      });\n    }\n    common.setValueByPath(toObject, ['inlinedResponses'], transformedList);\n  }\n\n  const fromInlinedEmbedContentResponses = common.getValueByPath(fromObject, [\n    'inlinedEmbedContentResponses',\n    'inlinedResponses',\n  ]);\n  if (fromInlinedEmbedContentResponses != null) {\n    let transformedList = fromInlinedEmbedContentResponses;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return item;\n      });\n    }\n    common.setValueByPath(\n      toObject,\n      ['inlinedEmbedContentResponses'],\n      transformedList,\n    );\n  }\n\n  return toObject;\n}\n\nexport function batchJobDestinationFromVertex(\n  fromObject: types.BatchJobDestination,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromFormat = common.getValueByPath(fromObject, ['predictionsFormat']);\n  if (fromFormat != null) {\n    common.setValueByPath(toObject, ['format'], fromFormat);\n  }\n\n  const fromGcsUri = common.getValueByPath(fromObject, [\n    'gcsDestination',\n    'outputUriPrefix',\n  ]);\n  if (fromGcsUri != null) {\n    common.setValueByPath(toObject, ['gcsUri'], fromGcsUri);\n  }\n\n  const fromBigqueryUri = common.getValueByPath(fromObject, [\n    'bigqueryDestination',\n    'outputUri',\n  ]);\n  if (fromBigqueryUri != null) {\n    common.setValueByPath(toObject, ['bigqueryUri'], fromBigqueryUri);\n  }\n\n  return toObject;\n}\n\nexport function batchJobDestinationToVertex(\n  fromObject: types.BatchJobDestination,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromFormat = common.getValueByPath(fromObject, ['format']);\n  if (fromFormat != null) {\n    common.setValueByPath(toObject, ['predictionsFormat'], fromFormat);\n  }\n\n  const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n  if (fromGcsUri != null) {\n    common.setValueByPath(\n      toObject,\n      ['gcsDestination', 'outputUriPrefix'],\n      fromGcsUri,\n    );\n  }\n\n  const fromBigqueryUri = common.getValueByPath(fromObject, ['bigqueryUri']);\n  if (fromBigqueryUri != null) {\n    common.setValueByPath(\n      toObject,\n      ['bigqueryDestination', 'outputUri'],\n      fromBigqueryUri,\n    );\n  }\n\n  if (common.getValueByPath(fromObject, ['fileName']) !== undefined) {\n    throw new Error('fileName parameter is not supported in Vertex AI.');\n  }\n\n  if (common.getValueByPath(fromObject, ['inlinedResponses']) !== undefined) {\n    throw new Error(\n      'inlinedResponses parameter is not supported in Vertex AI.',\n    );\n  }\n\n  if (\n    common.getValueByPath(fromObject, ['inlinedEmbedContentResponses']) !==\n    undefined\n  ) {\n    throw new Error(\n      'inlinedEmbedContentResponses parameter is not supported in Vertex AI.',\n    );\n  }\n\n  return toObject;\n}\n\nexport function batchJobFromMldev(\n  fromObject: types.BatchJob,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromName = common.getValueByPath(fromObject, ['name']);\n  if (fromName != null) {\n    common.setValueByPath(toObject, ['name'], fromName);\n  }\n\n  const fromDisplayName = common.getValueByPath(fromObject, [\n    'metadata',\n    'displayName',\n  ]);\n  if (fromDisplayName != null) {\n    common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n  }\n\n  const fromState = common.getValueByPath(fromObject, ['metadata', 'state']);\n  if (fromState != null) {\n    common.setValueByPath(toObject, ['state'], t.tJobState(fromState));\n  }\n\n  const fromCreateTime = common.getValueByPath(fromObject, [\n    'metadata',\n    'createTime',\n  ]);\n  if (fromCreateTime != null) {\n    common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n  }\n\n  const fromEndTime = common.getValueByPath(fromObject, [\n    'metadata',\n    'endTime',\n  ]);\n  if (fromEndTime != null) {\n    common.setValueByPath(toObject, ['endTime'], fromEndTime);\n  }\n\n  const fromUpdateTime = common.getValueByPath(fromObject, [\n    'metadata',\n    'updateTime',\n  ]);\n  if (fromUpdateTime != null) {\n    common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n  }\n\n  const fromModel = common.getValueByPath(fromObject, ['metadata', 'model']);\n  if (fromModel != null) {\n    common.setValueByPath(toObject, ['model'], fromModel);\n  }\n\n  const fromDest = common.getValueByPath(fromObject, ['metadata', 'output']);\n  if (fromDest != null) {\n    common.setValueByPath(\n      toObject,\n      ['dest'],\n      batchJobDestinationFromMldev(t.tRecvBatchJobDestination(fromDest)),\n    );\n  }\n\n  return toObject;\n}\n\nexport function batchJobFromVertex(\n  fromObject: types.BatchJob,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromName = common.getValueByPath(fromObject, ['name']);\n  if (fromName != null) {\n    common.setValueByPath(toObject, ['name'], fromName);\n  }\n\n  const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n  if (fromDisplayName != null) {\n    common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n  }\n\n  const fromState = common.getValueByPath(fromObject, ['state']);\n  if (fromState != null) {\n    common.setValueByPath(toObject, ['state'], t.tJobState(fromState));\n  }\n\n  const fromError = common.getValueByPath(fromObject, ['error']);\n  if (fromError != null) {\n    common.setValueByPath(toObject, ['error'], fromError);\n  }\n\n  const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n  if (fromCreateTime != null) {\n    common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n  }\n\n  const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n  if (fromStartTime != null) {\n    common.setValueByPath(toObject, ['startTime'], fromStartTime);\n  }\n\n  const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n  if (fromEndTime != null) {\n    common.setValueByPath(toObject, ['endTime'], fromEndTime);\n  }\n\n  const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n  if (fromUpdateTime != null) {\n    common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n  }\n\n  const fromModel = common.getValueByPath(fromObject, ['model']);\n  if (fromModel != null) {\n    common.setValueByPath(toObject, ['model'], fromModel);\n  }\n\n  const fromSrc = common.getValueByPath(fromObject, ['inputConfig']);\n  if (fromSrc != null) {\n    common.setValueByPath(toObject, ['src'], batchJobSourceFromVertex(fromSrc));\n  }\n\n  const fromDest = common.getValueByPath(fromObject, ['outputConfig']);\n  if (fromDest != null) {\n    common.setValueByPath(\n      toObject,\n      ['dest'],\n      batchJobDestinationFromVertex(t.tRecvBatchJobDestination(fromDest)),\n    );\n  }\n\n  const fromCompletionStats = common.getValueByPath(fromObject, [\n    'completionStats',\n  ]);\n  if (fromCompletionStats != null) {\n    common.setValueByPath(toObject, ['completionStats'], fromCompletionStats);\n  }\n\n  return toObject;\n}\n\nexport function batchJobSourceFromVertex(\n  fromObject: types.BatchJobSource,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromFormat = common.getValueByPath(fromObject, ['instancesFormat']);\n  if (fromFormat != null) {\n    common.setValueByPath(toObject, ['format'], fromFormat);\n  }\n\n  const fromGcsUri = common.getValueByPath(fromObject, ['gcsSource', 'uris']);\n  if (fromGcsUri != null) {\n    common.setValueByPath(toObject, ['gcsUri'], fromGcsUri);\n  }\n\n  const fromBigqueryUri = common.getValueByPath(fromObject, [\n    'bigquerySource',\n    'inputUri',\n  ]);\n  if (fromBigqueryUri != null) {\n    common.setValueByPath(toObject, ['bigqueryUri'], fromBigqueryUri);\n  }\n\n  return toObject;\n}\n\nexport function batchJobSourceToMldev(\n  apiClient: ApiClient,\n  fromObject: types.BatchJobSource,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  if (common.getValueByPath(fromObject, ['format']) !== undefined) {\n    throw new Error('format parameter is not supported in Gemini API.');\n  }\n\n  if (common.getValueByPath(fromObject, ['gcsUri']) !== undefined) {\n    throw new Error('gcsUri parameter is not supported in Gemini API.');\n  }\n\n  if (common.getValueByPath(fromObject, ['bigqueryUri']) !== undefined) {\n    throw new Error('bigqueryUri parameter is not supported in Gemini API.');\n  }\n\n  const fromFileName = common.getValueByPath(fromObject, ['fileName']);\n  if (fromFileName != null) {\n    common.setValueByPath(toObject, ['fileName'], fromFileName);\n  }\n\n  const fromInlinedRequests = common.getValueByPath(fromObject, [\n    'inlinedRequests',\n  ]);\n  if (fromInlinedRequests != null) {\n    let transformedList = fromInlinedRequests;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return inlinedRequestToMldev(apiClient, item);\n      });\n    }\n    common.setValueByPath(toObject, ['requests', 'requests'], transformedList);\n  }\n\n  return toObject;\n}\n\nexport function batchJobSourceToVertex(\n  fromObject: types.BatchJobSource,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromFormat = common.getValueByPath(fromObject, ['format']);\n  if (fromFormat != null) {\n    common.setValueByPath(toObject, ['instancesFormat'], fromFormat);\n  }\n\n  const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n  if (fromGcsUri != null) {\n    common.setValueByPath(toObject, ['gcsSource', 'uris'], fromGcsUri);\n  }\n\n  const fromBigqueryUri = common.getValueByPath(fromObject, ['bigqueryUri']);\n  if (fromBigqueryUri != null) {\n    common.setValueByPath(\n      toObject,\n      ['bigquerySource', 'inputUri'],\n      fromBigqueryUri,\n    );\n  }\n\n  if (common.getValueByPath(fromObject, ['fileName']) !== undefined) {\n    throw new Error('fileName parameter is not supported in Vertex AI.');\n  }\n\n  if (common.getValueByPath(fromObject, ['inlinedRequests']) !== undefined) {\n    throw new Error('inlinedRequests parameter is not supported in Vertex AI.');\n  }\n\n  return toObject;\n}\n\nexport function blobToMldev(fromObject: types.Blob): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromData = common.getValueByPath(fromObject, ['data']);\n  if (fromData != null) {\n    common.setValueByPath(toObject, ['data'], fromData);\n  }\n\n  if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n    throw new Error('displayName parameter is not supported in Gemini API.');\n  }\n\n  const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n  if (fromMimeType != null) {\n    common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n  }\n\n  return toObject;\n}\n\nexport function cancelBatchJobParametersToMldev(\n  apiClient: ApiClient,\n  fromObject: types.CancelBatchJobParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromName = common.getValueByPath(fromObject, ['name']);\n  if (fromName != null) {\n    common.setValueByPath(\n      toObject,\n      ['_url', 'name'],\n      t.tBatchJobName(apiClient, fromName),\n    );\n  }\n\n  return toObject;\n}\n\nexport function cancelBatchJobParametersToVertex(\n  apiClient: ApiClient,\n  fromObject: types.CancelBatchJobParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromName = common.getValueByPath(fromObject, ['name']);\n  if (fromName != null) {\n    common.setValueByPath(\n      toObject,\n      ['_url', 'name'],\n      t.tBatchJobName(apiClient, fromName),\n    );\n  }\n\n  return toObject;\n}\n\nexport function candidateFromMldev(\n  fromObject: types.Candidate,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromContent = common.getValueByPath(fromObject, ['content']);\n  if (fromContent != null) {\n    common.setValueByPath(toObject, ['content'], fromContent);\n  }\n\n  const fromCitationMetadata = common.getValueByPath(fromObject, [\n    'citationMetadata',\n  ]);\n  if (fromCitationMetadata != null) {\n    common.setValueByPath(\n      toObject,\n      ['citationMetadata'],\n      citationMetadataFromMldev(fromCitationMetadata),\n    );\n  }\n\n  const fromTokenCount = common.getValueByPath(fromObject, ['tokenCount']);\n  if (fromTokenCount != null) {\n    common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n  }\n\n  const fromFinishReason = common.getValueByPath(fromObject, ['finishReason']);\n  if (fromFinishReason != null) {\n    common.setValueByPath(toObject, ['finishReason'], fromFinishReason);\n  }\n\n  const fromAvgLogprobs = common.getValueByPath(fromObject, ['avgLogprobs']);\n  if (fromAvgLogprobs != null) {\n    common.setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs);\n  }\n\n  const fromGroundingMetadata = common.getValueByPath(fromObject, [\n    'groundingMetadata',\n  ]);\n  if (fromGroundingMetadata != null) {\n    common.setValueByPath(\n      toObject,\n      ['groundingMetadata'],\n      fromGroundingMetadata,\n    );\n  }\n\n  const fromIndex = common.getValueByPath(fromObject, ['index']);\n  if (fromIndex != null) {\n    common.setValueByPath(toObject, ['index'], fromIndex);\n  }\n\n  const fromLogprobsResult = common.getValueByPath(fromObject, [\n    'logprobsResult',\n  ]);\n  if (fromLogprobsResult != null) {\n    common.setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult);\n  }\n\n  const fromSafetyRatings = common.getValueByPath(fromObject, [\n    'safetyRatings',\n  ]);\n  if (fromSafetyRatings != null) {\n    let transformedList = fromSafetyRatings;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return item;\n      });\n    }\n    common.setValueByPath(toObject, ['safetyRatings'], transformedList);\n  }\n\n  const fromUrlContextMetadata = common.getValueByPath(fromObject, [\n    'urlContextMetadata',\n  ]);\n  if (fromUrlContextMetadata != null) {\n    common.setValueByPath(\n      toObject,\n      ['urlContextMetadata'],\n      fromUrlContextMetadata,\n    );\n  }\n\n  return toObject;\n}\n\nexport function citationMetadataFromMldev(\n  fromObject: types.CitationMetadata,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromCitations = common.getValueByPath(fromObject, ['citationSources']);\n  if (fromCitations != null) {\n    let transformedList = fromCitations;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return item;\n      });\n    }\n    common.setValueByPath(toObject, ['citations'], transformedList);\n  }\n\n  return toObject;\n}\n\nexport function contentToMldev(\n  fromObject: types.Content,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromParts = common.getValueByPath(fromObject, ['parts']);\n  if (fromParts != null) {\n    let transformedList = fromParts;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return partToMldev(item);\n      });\n    }\n    common.setValueByPath(toObject, ['parts'], transformedList);\n  }\n\n  const fromRole = common.getValueByPath(fromObject, ['role']);\n  if (fromRole != null) {\n    common.setValueByPath(toObject, ['role'], fromRole);\n  }\n\n  return toObject;\n}\n\nexport function createBatchJobConfigToMldev(\n  fromObject: types.CreateBatchJobConfig,\n  parentObject: Record<string, unknown>,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n  if (parentObject !== undefined && fromDisplayName != null) {\n    common.setValueByPath(\n      parentObject,\n      ['batch', 'displayName'],\n      fromDisplayName,\n    );\n  }\n\n  if (common.getValueByPath(fromObject, ['dest']) !== undefined) {\n    throw new Error('dest parameter is not supported in Gemini API.');\n  }\n\n  return toObject;\n}\n\nexport function createBatchJobConfigToVertex(\n  fromObject: types.CreateBatchJobConfig,\n  parentObject: Record<string, unknown>,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n  if (parentObject !== undefined && fromDisplayName != null) {\n    common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n  }\n\n  const fromDest = common.getValueByPath(fromObject, ['dest']);\n  if (parentObject !== undefined && fromDest != null) {\n    common.setValueByPath(\n      parentObject,\n      ['outputConfig'],\n      batchJobDestinationToVertex(t.tBatchJobDestination(fromDest)),\n    );\n  }\n\n  return toObject;\n}\n\nexport function createBatchJobParametersToMldev(\n  apiClient: ApiClient,\n  fromObject: types.CreateBatchJobParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromModel = common.getValueByPath(fromObject, ['model']);\n  if (fromModel != null) {\n    common.setValueByPath(\n      toObject,\n      ['_url', 'model'],\n      t.tModel(apiClient, fromModel),\n    );\n  }\n\n  const fromSrc = common.getValueByPath(fromObject, ['src']);\n  if (fromSrc != null) {\n    common.setValueByPath(\n      toObject,\n      ['batch', 'inputConfig'],\n      batchJobSourceToMldev(apiClient, t.tBatchJobSource(apiClient, fromSrc)),\n    );\n  }\n\n  const fromConfig = common.getValueByPath(fromObject, ['config']);\n  if (fromConfig != null) {\n    createBatchJobConfigToMldev(fromConfig, toObject);\n  }\n\n  return toObject;\n}\n\nexport function createBatchJobParametersToVertex(\n  apiClient: ApiClient,\n  fromObject: types.CreateBatchJobParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromModel = common.getValueByPath(fromObject, ['model']);\n  if (fromModel != null) {\n    common.setValueByPath(toObject, ['model'], t.tModel(apiClient, fromModel));\n  }\n\n  const fromSrc = common.getValueByPath(fromObject, ['src']);\n  if (fromSrc != null) {\n    common.setValueByPath(\n      toObject,\n      ['inputConfig'],\n      batchJobSourceToVertex(t.tBatchJobSource(apiClient, fromSrc)),\n    );\n  }\n\n  const fromConfig = common.getValueByPath(fromObject, ['config']);\n  if (fromConfig != null) {\n    createBatchJobConfigToVertex(fromConfig, toObject);\n  }\n\n  return toObject;\n}\n\nexport function createEmbeddingsBatchJobConfigToMldev(\n  fromObject: types.CreateEmbeddingsBatchJobConfig,\n  parentObject: Record<string, unknown>,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n  if (parentObject !== undefined && fromDisplayName != null) {\n    common.setValueByPath(\n      parentObject,\n      ['batch', 'displayName'],\n      fromDisplayName,\n    );\n  }\n\n  return toObject;\n}\n\nexport function createEmbeddingsBatchJobParametersToMldev(\n  apiClient: ApiClient,\n  fromObject: types.CreateEmbeddingsBatchJobParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromModel = common.getValueByPath(fromObject, ['model']);\n  if (fromModel != null) {\n    common.setValueByPath(\n      toObject,\n      ['_url', 'model'],\n      t.tModel(apiClient, fromModel),\n    );\n  }\n\n  const fromSrc = common.getValueByPath(fromObject, ['src']);\n  if (fromSrc != null) {\n    common.setValueByPath(\n      toObject,\n      ['batch', 'inputConfig'],\n      embeddingsBatchJobSourceToMldev(apiClient, fromSrc),\n    );\n  }\n\n  const fromConfig = common.getValueByPath(fromObject, ['config']);\n  if (fromConfig != null) {\n    createEmbeddingsBatchJobConfigToMldev(fromConfig, toObject);\n  }\n\n  return toObject;\n}\n\nexport function deleteBatchJobParametersToMldev(\n  apiClient: ApiClient,\n  fromObject: types.DeleteBatchJobParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromName = common.getValueByPath(fromObject, ['name']);\n  if (fromName != null) {\n    common.setValueByPath(\n      toObject,\n      ['_url', 'name'],\n      t.tBatchJobName(apiClient, fromName),\n    );\n  }\n\n  return toObject;\n}\n\nexport function deleteBatchJobParametersToVertex(\n  apiClient: ApiClient,\n  fromObject: types.DeleteBatchJobParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromName = common.getValueByPath(fromObject, ['name']);\n  if (fromName != null) {\n    common.setValueByPath(\n      toObject,\n      ['_url', 'name'],\n      t.tBatchJobName(apiClient, fromName),\n    );\n  }\n\n  return toObject;\n}\n\nexport function deleteResourceJobFromMldev(\n  fromObject: types.DeleteResourceJob,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n    'sdkHttpResponse',\n  ]);\n  if (fromSdkHttpResponse != null) {\n    common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n  }\n\n  const fromName = common.getValueByPath(fromObject, ['name']);\n  if (fromName != null) {\n    common.setValueByPath(toObject, ['name'], fromName);\n  }\n\n  const fromDone = common.getValueByPath(fromObject, ['done']);\n  if (fromDone != null) {\n    common.setValueByPath(toObject, ['done'], fromDone);\n  }\n\n  const fromError = common.getValueByPath(fromObject, ['error']);\n  if (fromError != null) {\n    common.setValueByPath(toObject, ['error'], fromError);\n  }\n\n  return toObject;\n}\n\nexport function deleteResourceJobFromVertex(\n  fromObject: types.DeleteResourceJob,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n    'sdkHttpResponse',\n  ]);\n  if (fromSdkHttpResponse != null) {\n    common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n  }\n\n  const fromName = common.getValueByPath(fromObject, ['name']);\n  if (fromName != null) {\n    common.setValueByPath(toObject, ['name'], fromName);\n  }\n\n  const fromDone = common.getValueByPath(fromObject, ['done']);\n  if (fromDone != null) {\n    common.setValueByPath(toObject, ['done'], fromDone);\n  }\n\n  const fromError = common.getValueByPath(fromObject, ['error']);\n  if (fromError != null) {\n    common.setValueByPath(toObject, ['error'], fromError);\n  }\n\n  return toObject;\n}\n\nexport function embedContentBatchToMldev(\n  apiClient: ApiClient,\n  fromObject: types.EmbedContentBatch,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromContents = common.getValueByPath(fromObject, ['contents']);\n  if (fromContents != null) {\n    let transformedList = t.tContentsForEmbed(apiClient, fromContents);\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return item;\n      });\n    }\n    common.setValueByPath(\n      toObject,\n      ['requests[]', 'request', 'content'],\n      transformedList,\n    );\n  }\n\n  const fromConfig = common.getValueByPath(fromObject, ['config']);\n  if (fromConfig != null) {\n    common.setValueByPath(\n      toObject,\n      ['_self'],\n      embedContentConfigToMldev(fromConfig, toObject),\n    );\n    common.moveValueByPath(toObject, {'requests[].*': 'requests[].request.*'});\n  }\n\n  return toObject;\n}\n\nexport function embedContentConfigToMldev(\n  fromObject: types.EmbedContentConfig,\n  parentObject: Record<string, unknown>,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromTaskType = common.getValueByPath(fromObject, ['taskType']);\n  if (parentObject !== undefined && fromTaskType != null) {\n    common.setValueByPath(\n      parentObject,\n      ['requests[]', 'taskType'],\n      fromTaskType,\n    );\n  }\n\n  const fromTitle = common.getValueByPath(fromObject, ['title']);\n  if (parentObject !== undefined && fromTitle != null) {\n    common.setValueByPath(parentObject, ['requests[]', 'title'], fromTitle);\n  }\n\n  const fromOutputDimensionality = common.getValueByPath(fromObject, [\n    'outputDimensionality',\n  ]);\n  if (parentObject !== undefined && fromOutputDimensionality != null) {\n    common.setValueByPath(\n      parentObject,\n      ['requests[]', 'outputDimensionality'],\n      fromOutputDimensionality,\n    );\n  }\n\n  if (common.getValueByPath(fromObject, ['mimeType']) !== undefined) {\n    throw new Error('mimeType parameter is not supported in Gemini API.');\n  }\n\n  if (common.getValueByPath(fromObject, ['autoTruncate']) !== undefined) {\n    throw new Error('autoTruncate parameter is not supported in Gemini API.');\n  }\n\n  return toObject;\n}\n\nexport function embeddingsBatchJobSourceToMldev(\n  apiClient: ApiClient,\n  fromObject: types.EmbeddingsBatchJobSource,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromFileName = common.getValueByPath(fromObject, ['fileName']);\n  if (fromFileName != null) {\n    common.setValueByPath(toObject, ['file_name'], fromFileName);\n  }\n\n  const fromInlinedRequests = common.getValueByPath(fromObject, [\n    'inlinedRequests',\n  ]);\n  if (fromInlinedRequests != null) {\n    common.setValueByPath(\n      toObject,\n      ['requests'],\n      embedContentBatchToMldev(apiClient, fromInlinedRequests),\n    );\n  }\n\n  return toObject;\n}\n\nexport function fileDataToMldev(\n  fromObject: types.FileData,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n    throw new Error('displayName parameter is not supported in Gemini API.');\n  }\n\n  const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n  if (fromFileUri != null) {\n    common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n  }\n\n  const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n  if (fromMimeType != null) {\n    common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n  }\n\n  return toObject;\n}\n\nexport function functionCallToMldev(\n  fromObject: types.FunctionCall,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromId = common.getValueByPath(fromObject, ['id']);\n  if (fromId != null) {\n    common.setValueByPath(toObject, ['id'], fromId);\n  }\n\n  const fromArgs = common.getValueByPath(fromObject, ['args']);\n  if (fromArgs != null) {\n    common.setValueByPath(toObject, ['args'], fromArgs);\n  }\n\n  const fromName = common.getValueByPath(fromObject, ['name']);\n  if (fromName != null) {\n    common.setValueByPath(toObject, ['name'], fromName);\n  }\n\n  if (common.getValueByPath(fromObject, ['partialArgs']) !== undefined) {\n    throw new Error('partialArgs parameter is not supported in Gemini API.');\n  }\n\n  if (common.getValueByPath(fromObject, ['willContinue']) !== undefined) {\n    throw new Error('willContinue parameter is not supported in Gemini API.');\n  }\n\n  return toObject;\n}\n\nexport function functionCallingConfigToMldev(\n  fromObject: types.FunctionCallingConfig,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromMode = common.getValueByPath(fromObject, ['mode']);\n  if (fromMode != null) {\n    common.setValueByPath(toObject, ['mode'], fromMode);\n  }\n\n  const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n    'allowedFunctionNames',\n  ]);\n  if (fromAllowedFunctionNames != null) {\n    common.setValueByPath(\n      toObject,\n      ['allowedFunctionNames'],\n      fromAllowedFunctionNames,\n    );\n  }\n\n  if (\n    common.getValueByPath(fromObject, ['streamFunctionCallArguments']) !==\n    undefined\n  ) {\n    throw new Error(\n      'streamFunctionCallArguments parameter is not supported in Gemini API.',\n    );\n  }\n\n  return toObject;\n}\n\nexport function generateContentConfigToMldev(\n  apiClient: ApiClient,\n  fromObject: types.GenerateContentConfig,\n  parentObject: Record<string, unknown>,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromSystemInstruction = common.getValueByPath(fromObject, [\n    'systemInstruction',\n  ]);\n  if (parentObject !== undefined && fromSystemInstruction != null) {\n    common.setValueByPath(\n      parentObject,\n      ['systemInstruction'],\n      contentToMldev(t.tContent(fromSystemInstruction)),\n    );\n  }\n\n  const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n  if (fromTemperature != null) {\n    common.setValueByPath(toObject, ['temperature'], fromTemperature);\n  }\n\n  const fromTopP = common.getValueByPath(fromObject, ['topP']);\n  if (fromTopP != null) {\n    common.setValueByPath(toObject, ['topP'], fromTopP);\n  }\n\n  const fromTopK = common.getValueByPath(fromObject, ['topK']);\n  if (fromTopK != null) {\n    common.setValueByPath(toObject, ['topK'], fromTopK);\n  }\n\n  const fromCandidateCount = common.getValueByPath(fromObject, [\n    'candidateCount',\n  ]);\n  if (fromCandidateCount != null) {\n    common.setValueByPath(toObject, ['candidateCount'], fromCandidateCount);\n  }\n\n  const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n    'maxOutputTokens',\n  ]);\n  if (fromMaxOutputTokens != null) {\n    common.setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens);\n  }\n\n  const fromStopSequences = common.getValueByPath(fromObject, [\n    'stopSequences',\n  ]);\n  if (fromStopSequences != null) {\n    common.setValueByPath(toObject, ['stopSequences'], fromStopSequences);\n  }\n\n  const fromResponseLogprobs = common.getValueByPath(fromObject, [\n    'responseLogprobs',\n  ]);\n  if (fromResponseLogprobs != null) {\n    common.setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs);\n  }\n\n  const fromLogprobs = common.getValueByPath(fromObject, ['logprobs']);\n  if (fromLogprobs != null) {\n    common.setValueByPath(toObject, ['logprobs'], fromLogprobs);\n  }\n\n  const fromPresencePenalty = common.getValueByPath(fromObject, [\n    'presencePenalty',\n  ]);\n  if (fromPresencePenalty != null) {\n    common.setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty);\n  }\n\n  const fromFrequencyPenalty = common.getValueByPath(fromObject, [\n    'frequencyPenalty',\n  ]);\n  if (fromFrequencyPenalty != null) {\n    common.setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty);\n  }\n\n  const fromSeed = common.getValueByPath(fromObject, ['seed']);\n  if (fromSeed != null) {\n    common.setValueByPath(toObject, ['seed'], fromSeed);\n  }\n\n  const fromResponseMimeType = common.getValueByPath(fromObject, [\n    'responseMimeType',\n  ]);\n  if (fromResponseMimeType != null) {\n    common.setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType);\n  }\n\n  const fromResponseSchema = common.getValueByPath(fromObject, [\n    'responseSchema',\n  ]);\n  if (fromResponseSchema != null) {\n    common.setValueByPath(\n      toObject,\n      ['responseSchema'],\n      t.tSchema(fromResponseSchema),\n    );\n  }\n\n  const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n    'responseJsonSchema',\n  ]);\n  if (fromResponseJsonSchema != null) {\n    common.setValueByPath(\n      toObject,\n      ['responseJsonSchema'],\n      fromResponseJsonSchema,\n    );\n  }\n\n  if (common.getValueByPath(fromObject, ['routingConfig']) !== undefined) {\n    throw new Error('routingConfig parameter is not supported in Gemini API.');\n  }\n\n  if (\n    common.getValueByPath(fromObject, ['modelSelectionConfig']) !== undefined\n  ) {\n    throw new Error(\n      'modelSelectionConfig parameter is not supported in Gemini API.',\n    );\n  }\n\n  const fromSafetySettings = common.getValueByPath(fromObject, [\n    'safetySettings',\n  ]);\n  if (parentObject !== undefined && fromSafetySettings != null) {\n    let transformedList = fromSafetySettings;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return safetySettingToMldev(item);\n      });\n    }\n    common.setValueByPath(parentObject, ['safetySettings'], transformedList);\n  }\n\n  const fromTools = common.getValueByPath(fromObject, ['tools']);\n  if (parentObject !== undefined && fromTools != null) {\n    let transformedList = t.tTools(fromTools);\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return toolToMldev(t.tTool(item));\n      });\n    }\n    common.setValueByPath(parentObject, ['tools'], transformedList);\n  }\n\n  const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n  if (parentObject !== undefined && fromToolConfig != null) {\n    common.setValueByPath(\n      parentObject,\n      ['toolConfig'],\n      toolConfigToMldev(fromToolConfig),\n    );\n  }\n\n  if (common.getValueByPath(fromObject, ['labels']) !== undefined) {\n    throw new Error('labels parameter is not supported in Gemini API.');\n  }\n\n  const fromCachedContent = common.getValueByPath(fromObject, [\n    'cachedContent',\n  ]);\n  if (parentObject !== undefined && fromCachedContent != null) {\n    common.setValueByPath(\n      parentObject,\n      ['cachedContent'],\n      t.tCachedContentName(apiClient, fromCachedContent),\n    );\n  }\n\n  const fromResponseModalities = common.getValueByPath(fromObject, [\n    'responseModalities',\n  ]);\n  if (fromResponseModalities != null) {\n    common.setValueByPath(\n      toObject,\n      ['responseModalities'],\n      fromResponseModalities,\n    );\n  }\n\n  const fromMediaResolution = common.getValueByPath(fromObject, [\n    'mediaResolution',\n  ]);\n  if (fromMediaResolution != null) {\n    common.setValueByPath(toObject, ['mediaResolution'], fromMediaResolution);\n  }\n\n  const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n  if (fromSpeechConfig != null) {\n    common.setValueByPath(\n      toObject,\n      ['speechConfig'],\n      t.tSpeechConfig(fromSpeechConfig),\n    );\n  }\n\n  if (common.getValueByPath(fromObject, ['audioTimestamp']) !== undefined) {\n    throw new Error('audioTimestamp parameter is not supported in Gemini API.');\n  }\n\n  const fromThinkingConfig = common.getValueByPath(fromObject, [\n    'thinkingConfig',\n  ]);\n  if (fromThinkingConfig != null) {\n    common.setValueByPath(toObject, ['thinkingConfig'], fromThinkingConfig);\n  }\n\n  const fromImageConfig = common.getValueByPath(fromObject, ['imageConfig']);\n  if (fromImageConfig != null) {\n    common.setValueByPath(\n      toObject,\n      ['imageConfig'],\n      imageConfigToMldev(fromImageConfig),\n    );\n  }\n\n  const fromEnableEnhancedCivicAnswers = common.getValueByPath(fromObject, [\n    'enableEnhancedCivicAnswers',\n  ]);\n  if (fromEnableEnhancedCivicAnswers != null) {\n    common.setValueByPath(\n      toObject,\n      ['enableEnhancedCivicAnswers'],\n      fromEnableEnhancedCivicAnswers,\n    );\n  }\n\n  return toObject;\n}\n\nexport function generateContentResponseFromMldev(\n  fromObject: types.GenerateContentResponse,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n    'sdkHttpResponse',\n  ]);\n  if (fromSdkHttpResponse != null) {\n    common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n  }\n\n  const fromCandidates = common.getValueByPath(fromObject, ['candidates']);\n  if (fromCandidates != null) {\n    let transformedList = fromCandidates;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return candidateFromMldev(item);\n      });\n    }\n    common.setValueByPath(toObject, ['candidates'], transformedList);\n  }\n\n  const fromModelVersion = common.getValueByPath(fromObject, ['modelVersion']);\n  if (fromModelVersion != null) {\n    common.setValueByPath(toObject, ['modelVersion'], fromModelVersion);\n  }\n\n  const fromPromptFeedback = common.getValueByPath(fromObject, [\n    'promptFeedback',\n  ]);\n  if (fromPromptFeedback != null) {\n    common.setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback);\n  }\n\n  const fromResponseId = common.getValueByPath(fromObject, ['responseId']);\n  if (fromResponseId != null) {\n    common.setValueByPath(toObject, ['responseId'], fromResponseId);\n  }\n\n  const fromUsageMetadata = common.getValueByPath(fromObject, [\n    'usageMetadata',\n  ]);\n  if (fromUsageMetadata != null) {\n    common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n  }\n\n  return toObject;\n}\n\nexport function getBatchJobParametersToMldev(\n  apiClient: ApiClient,\n  fromObject: types.GetBatchJobParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromName = common.getValueByPath(fromObject, ['name']);\n  if (fromName != null) {\n    common.setValueByPath(\n      toObject,\n      ['_url', 'name'],\n      t.tBatchJobName(apiClient, fromName),\n    );\n  }\n\n  return toObject;\n}\n\nexport function getBatchJobParametersToVertex(\n  apiClient: ApiClient,\n  fromObject: types.GetBatchJobParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromName = common.getValueByPath(fromObject, ['name']);\n  if (fromName != null) {\n    common.setValueByPath(\n      toObject,\n      ['_url', 'name'],\n      t.tBatchJobName(apiClient, fromName),\n    );\n  }\n\n  return toObject;\n}\n\nexport function googleMapsToMldev(\n  fromObject: types.GoogleMaps,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  if (common.getValueByPath(fromObject, ['authConfig']) !== undefined) {\n    throw new Error('authConfig parameter is not supported in Gemini API.');\n  }\n\n  const fromEnableWidget = common.getValueByPath(fromObject, ['enableWidget']);\n  if (fromEnableWidget != null) {\n    common.setValueByPath(toObject, ['enableWidget'], fromEnableWidget);\n  }\n\n  return toObject;\n}\n\nexport function googleSearchToMldev(\n  fromObject: types.GoogleSearch,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  if (common.getValueByPath(fromObject, ['excludeDomains']) !== undefined) {\n    throw new Error('excludeDomains parameter is not supported in Gemini API.');\n  }\n\n  if (common.getValueByPath(fromObject, ['blockingConfidence']) !== undefined) {\n    throw new Error(\n      'blockingConfidence parameter is not supported in Gemini API.',\n    );\n  }\n\n  const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n    'timeRangeFilter',\n  ]);\n  if (fromTimeRangeFilter != null) {\n    common.setValueByPath(toObject, ['timeRangeFilter'], fromTimeRangeFilter);\n  }\n\n  return toObject;\n}\n\nexport function imageConfigToMldev(\n  fromObject: types.ImageConfig,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n  if (fromAspectRatio != null) {\n    common.setValueByPath(toObject, ['aspectRatio'], fromAspectRatio);\n  }\n\n  const fromImageSize = common.getValueByPath(fromObject, ['imageSize']);\n  if (fromImageSize != null) {\n    common.setValueByPath(toObject, ['imageSize'], fromImageSize);\n  }\n\n  if (common.getValueByPath(fromObject, ['outputMimeType']) !== undefined) {\n    throw new Error('outputMimeType parameter is not supported in Gemini API.');\n  }\n\n  if (\n    common.getValueByPath(fromObject, ['outputCompressionQuality']) !==\n    undefined\n  ) {\n    throw new Error(\n      'outputCompressionQuality parameter is not supported in Gemini API.',\n    );\n  }\n\n  return toObject;\n}\n\nexport function inlinedRequestToMldev(\n  apiClient: ApiClient,\n  fromObject: types.InlinedRequest,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromModel = common.getValueByPath(fromObject, ['model']);\n  if (fromModel != null) {\n    common.setValueByPath(\n      toObject,\n      ['request', 'model'],\n      t.tModel(apiClient, fromModel),\n    );\n  }\n\n  const fromContents = common.getValueByPath(fromObject, ['contents']);\n  if (fromContents != null) {\n    let transformedList = t.tContents(fromContents);\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return contentToMldev(item);\n      });\n    }\n    common.setValueByPath(toObject, ['request', 'contents'], transformedList);\n  }\n\n  const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n  if (fromMetadata != null) {\n    common.setValueByPath(toObject, ['metadata'], fromMetadata);\n  }\n\n  const fromConfig = common.getValueByPath(fromObject, ['config']);\n  if (fromConfig != null) {\n    common.setValueByPath(\n      toObject,\n      ['request', 'generationConfig'],\n      generateContentConfigToMldev(\n        apiClient,\n        fromConfig,\n        common.getValueByPath(toObject, ['request'], {}) as Record<\n          string,\n          unknown\n        >,\n      ),\n    );\n  }\n\n  return toObject;\n}\n\nexport function inlinedResponseFromMldev(\n  fromObject: types.InlinedResponse,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromResponse = common.getValueByPath(fromObject, ['response']);\n  if (fromResponse != null) {\n    common.setValueByPath(\n      toObject,\n      ['response'],\n      generateContentResponseFromMldev(\n        fromResponse as types.GenerateContentResponse,\n      ),\n    );\n  }\n\n  const fromError = common.getValueByPath(fromObject, ['error']);\n  if (fromError != null) {\n    common.setValueByPath(toObject, ['error'], fromError);\n  }\n\n  return toObject;\n}\n\nexport function listBatchJobsConfigToMldev(\n  fromObject: types.ListBatchJobsConfig,\n  parentObject: Record<string, unknown>,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n  if (parentObject !== undefined && fromPageSize != null) {\n    common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n  }\n\n  const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n  if (parentObject !== undefined && fromPageToken != null) {\n    common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n  }\n\n  if (common.getValueByPath(fromObject, ['filter']) !== undefined) {\n    throw new Error('filter parameter is not supported in Gemini API.');\n  }\n\n  return toObject;\n}\n\nexport function listBatchJobsConfigToVertex(\n  fromObject: types.ListBatchJobsConfig,\n  parentObject: Record<string, unknown>,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n  if (parentObject !== undefined && fromPageSize != null) {\n    common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n  }\n\n  const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n  if (parentObject !== undefined && fromPageToken != null) {\n    common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n  }\n\n  const fromFilter = common.getValueByPath(fromObject, ['filter']);\n  if (parentObject !== undefined && fromFilter != null) {\n    common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n  }\n\n  return toObject;\n}\n\nexport function listBatchJobsParametersToMldev(\n  fromObject: types.ListBatchJobsParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromConfig = common.getValueByPath(fromObject, ['config']);\n  if (fromConfig != null) {\n    listBatchJobsConfigToMldev(fromConfig, toObject);\n  }\n\n  return toObject;\n}\n\nexport function listBatchJobsParametersToVertex(\n  fromObject: types.ListBatchJobsParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromConfig = common.getValueByPath(fromObject, ['config']);\n  if (fromConfig != null) {\n    listBatchJobsConfigToVertex(fromConfig, toObject);\n  }\n\n  return toObject;\n}\n\nexport function listBatchJobsResponseFromMldev(\n  fromObject: types.ListBatchJobsResponse,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n    'sdkHttpResponse',\n  ]);\n  if (fromSdkHttpResponse != null) {\n    common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n  }\n\n  const fromNextPageToken = common.getValueByPath(fromObject, [\n    'nextPageToken',\n  ]);\n  if (fromNextPageToken != null) {\n    common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n  }\n\n  const fromBatchJobs = common.getValueByPath(fromObject, ['operations']);\n  if (fromBatchJobs != null) {\n    let transformedList = fromBatchJobs;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return batchJobFromMldev(item);\n      });\n    }\n    common.setValueByPath(toObject, ['batchJobs'], transformedList);\n  }\n\n  return toObject;\n}\n\nexport function listBatchJobsResponseFromVertex(\n  fromObject: types.ListBatchJobsResponse,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n    'sdkHttpResponse',\n  ]);\n  if (fromSdkHttpResponse != null) {\n    common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n  }\n\n  const fromNextPageToken = common.getValueByPath(fromObject, [\n    'nextPageToken',\n  ]);\n  if (fromNextPageToken != null) {\n    common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n  }\n\n  const fromBatchJobs = common.getValueByPath(fromObject, [\n    'batchPredictionJobs',\n  ]);\n  if (fromBatchJobs != null) {\n    let transformedList = fromBatchJobs;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return batchJobFromVertex(item);\n      });\n    }\n    common.setValueByPath(toObject, ['batchJobs'], transformedList);\n  }\n\n  return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromMediaResolution = common.getValueByPath(fromObject, [\n    'mediaResolution',\n  ]);\n  if (fromMediaResolution != null) {\n    common.setValueByPath(toObject, ['mediaResolution'], fromMediaResolution);\n  }\n\n  const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n    'codeExecutionResult',\n  ]);\n  if (fromCodeExecutionResult != null) {\n    common.setValueByPath(\n      toObject,\n      ['codeExecutionResult'],\n      fromCodeExecutionResult,\n    );\n  }\n\n  const fromExecutableCode = common.getValueByPath(fromObject, [\n    'executableCode',\n  ]);\n  if (fromExecutableCode != null) {\n    common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n  }\n\n  const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n  if (fromFileData != null) {\n    common.setValueByPath(\n      toObject,\n      ['fileData'],\n      fileDataToMldev(fromFileData),\n    );\n  }\n\n  const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n  if (fromFunctionCall != null) {\n    common.setValueByPath(\n      toObject,\n      ['functionCall'],\n      functionCallToMldev(fromFunctionCall),\n    );\n  }\n\n  const fromFunctionResponse = common.getValueByPath(fromObject, [\n    'functionResponse',\n  ]);\n  if (fromFunctionResponse != null) {\n    common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n  }\n\n  const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n  if (fromInlineData != null) {\n    common.setValueByPath(\n      toObject,\n      ['inlineData'],\n      blobToMldev(fromInlineData),\n    );\n  }\n\n  const fromText = common.getValueByPath(fromObject, ['text']);\n  if (fromText != null) {\n    common.setValueByPath(toObject, ['text'], fromText);\n  }\n\n  const fromThought = common.getValueByPath(fromObject, ['thought']);\n  if (fromThought != null) {\n    common.setValueByPath(toObject, ['thought'], fromThought);\n  }\n\n  const fromThoughtSignature = common.getValueByPath(fromObject, [\n    'thoughtSignature',\n  ]);\n  if (fromThoughtSignature != null) {\n    common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n  }\n\n  const fromVideoMetadata = common.getValueByPath(fromObject, [\n    'videoMetadata',\n  ]);\n  if (fromVideoMetadata != null) {\n    common.setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata);\n  }\n\n  return toObject;\n}\n\nexport function safetySettingToMldev(\n  fromObject: types.SafetySetting,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromCategory = common.getValueByPath(fromObject, ['category']);\n  if (fromCategory != null) {\n    common.setValueByPath(toObject, ['category'], fromCategory);\n  }\n\n  if (common.getValueByPath(fromObject, ['method']) !== undefined) {\n    throw new Error('method parameter is not supported in Gemini API.');\n  }\n\n  const fromThreshold = common.getValueByPath(fromObject, ['threshold']);\n  if (fromThreshold != null) {\n    common.setValueByPath(toObject, ['threshold'], fromThreshold);\n  }\n\n  return toObject;\n}\n\nexport function toolConfigToMldev(\n  fromObject: types.ToolConfig,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n    'functionCallingConfig',\n  ]);\n  if (fromFunctionCallingConfig != null) {\n    common.setValueByPath(\n      toObject,\n      ['functionCallingConfig'],\n      functionCallingConfigToMldev(fromFunctionCallingConfig),\n    );\n  }\n\n  const fromRetrievalConfig = common.getValueByPath(fromObject, [\n    'retrievalConfig',\n  ]);\n  if (fromRetrievalConfig != null) {\n    common.setValueByPath(toObject, ['retrievalConfig'], fromRetrievalConfig);\n  }\n\n  return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n    'functionDeclarations',\n  ]);\n  if (fromFunctionDeclarations != null) {\n    let transformedList = fromFunctionDeclarations;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return item;\n      });\n    }\n    common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n  }\n\n  if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n    throw new Error('retrieval parameter is not supported in Gemini API.');\n  }\n\n  const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n    'googleSearchRetrieval',\n  ]);\n  if (fromGoogleSearchRetrieval != null) {\n    common.setValueByPath(\n      toObject,\n      ['googleSearchRetrieval'],\n      fromGoogleSearchRetrieval,\n    );\n  }\n\n  const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n  if (fromComputerUse != null) {\n    common.setValueByPath(toObject, ['computerUse'], fromComputerUse);\n  }\n\n  const fromFileSearch = common.getValueByPath(fromObject, ['fileSearch']);\n  if (fromFileSearch != null) {\n    common.setValueByPath(toObject, ['fileSearch'], fromFileSearch);\n  }\n\n  const fromCodeExecution = common.getValueByPath(fromObject, [\n    'codeExecution',\n  ]);\n  if (fromCodeExecution != null) {\n    common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n  }\n\n  if (\n    common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n  ) {\n    throw new Error(\n      'enterpriseWebSearch parameter is not supported in Gemini API.',\n    );\n  }\n\n  const fromGoogleMaps = common.getValueByPath(fromObject, ['googleMaps']);\n  if (fromGoogleMaps != null) {\n    common.setValueByPath(\n      toObject,\n      ['googleMaps'],\n      googleMapsToMldev(fromGoogleMaps),\n    );\n  }\n\n  const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n  if (fromGoogleSearch != null) {\n    common.setValueByPath(\n      toObject,\n      ['googleSearch'],\n      googleSearchToMldev(fromGoogleSearch),\n    );\n  }\n\n  const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n  if (fromUrlContext != null) {\n    common.setValueByPath(toObject, ['urlContext'], fromUrlContext);\n  }\n\n  return toObject;\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Pagers for the GenAI List APIs.\n */\n\nimport * as types from '../src/types';\n\nexport enum PagedItem {\n  PAGED_ITEM_BATCH_JOBS = 'batchJobs',\n  PAGED_ITEM_MODELS = 'models',\n  PAGED_ITEM_TUNING_JOBS = 'tuningJobs',\n  PAGED_ITEM_FILES = 'files',\n  PAGED_ITEM_CACHED_CONTENTS = 'cachedContents',\n  PAGED_ITEM_FILE_SEARCH_STORES = 'fileSearchStores',\n  PAGED_ITEM_DOCUMENTS = 'documents',\n}\n\nexport interface PagedItemConfig {\n  parent?: string;\n  config?: {\n    pageToken?: string;\n    pageSize?: number;\n  };\n}\n\ninterface PagedItemResponse<T> {\n  nextPageToken?: string;\n  sdkHttpResponse?: types.HttpResponse;\n  batchJobs?: T[];\n  models?: T[];\n  tuningJobs?: T[];\n  files?: T[];\n  cachedContents?: T[];\n  fileSearchStores?: T[];\n  documents?: T[];\n}\n\n/**\n * Pager class for iterating through paginated results.\n */\nexport class Pager<T> implements AsyncIterable<T> {\n  private nameInternal!: PagedItem;\n  private pageInternal: T[] = [];\n  private paramsInternal: PagedItemConfig = {};\n  private pageInternalSize!: number;\n  private sdkHttpResponseInternal?: types.HttpResponse;\n  protected requestInternal!: (\n    params: PagedItemConfig,\n  ) => Promise<PagedItemResponse<T>>;\n  protected idxInternal!: number;\n\n  constructor(\n    name: PagedItem,\n    request: (params: PagedItemConfig) => Promise<PagedItemResponse<T>>,\n    response: PagedItemResponse<T>,\n    params: PagedItemConfig,\n  ) {\n    this.requestInternal = request;\n    this.init(name, response, params);\n  }\n\n  private init(\n    name: PagedItem,\n    response: PagedItemResponse<T>,\n    params: PagedItemConfig,\n  ) {\n    this.nameInternal = name;\n    this.pageInternal = response[this.nameInternal] || [];\n\n    this.sdkHttpResponseInternal = response?.sdkHttpResponse;\n    this.idxInternal = 0;\n    let requestParams: PagedItemConfig = {config: {}};\n    if (!params || Object.keys(params).length === 0) {\n      requestParams = {config: {}};\n    } else if (typeof params === 'object') {\n      requestParams = {...params};\n    } else {\n      requestParams = params;\n    }\n    if (requestParams['config']) {\n      requestParams['config']['pageToken'] = response['nextPageToken'];\n    }\n    this.paramsInternal = requestParams;\n    this.pageInternalSize =\n      requestParams['config']?.['pageSize'] ?? this.pageInternal.length;\n  }\n\n  private initNextPage(response: PagedItemResponse<T>): void {\n    this.init(this.nameInternal, response, this.paramsInternal);\n  }\n\n  /**\n   * Returns the current page, which is a list of items.\n   *\n   * @remarks\n   * The first page is retrieved when the pager is created. The returned list of\n   * items could be a subset of the entire list.\n   */\n  get page(): T[] {\n    return this.pageInternal;\n  }\n\n  /**\n   * Returns the type of paged item (for example, ``batch_jobs``).\n   */\n  get name(): PagedItem {\n    return this.nameInternal;\n  }\n\n  /**\n   * Returns the length of the page fetched each time by this pager.\n   *\n   * @remarks\n   * The number of items in the page is less than or equal to the page length.\n   */\n  get pageSize(): number {\n    return this.pageInternalSize;\n  }\n\n  /**\n   * Returns the headers of the API response.\n   */\n  get sdkHttpResponse(): types.HttpResponse | undefined {\n    return this.sdkHttpResponseInternal;\n  }\n\n  /**\n   * Returns the parameters when making the API request for the next page.\n   *\n   * @remarks\n   * Parameters contain a set of optional configs that can be\n   * used to customize the API request. For example, the `pageToken` parameter\n   * contains the token to request the next page.\n   */\n  get params(): PagedItemConfig {\n    return this.paramsInternal;\n  }\n\n  /**\n   * Returns the total number of items in the current page.\n   */\n  get pageLength(): number {\n    return this.pageInternal.length;\n  }\n\n  /**\n   * Returns the item at the given index.\n   */\n  getItem(index: number): T {\n    return this.pageInternal[index];\n  }\n\n  /**\n   * Returns an async iterator that support iterating through all items\n   * retrieved from the API.\n   *\n   * @remarks\n   * The iterator will automatically fetch the next page if there are more items\n   * to fetch from the API.\n   *\n   * @example\n   *\n   * ```ts\n   * const pager = await ai.files.list({config: {pageSize: 10}});\n   * for await (const file of pager) {\n   *   console.log(file.name);\n   * }\n   * ```\n   */\n  [Symbol.asyncIterator](): AsyncIterator<T> {\n    return {\n      next: async () => {\n        if (this.idxInternal >= this.pageLength) {\n          if (this.hasNextPage()) {\n            await this.nextPage();\n          } else {\n            return {value: undefined, done: true};\n          }\n        }\n        const item = this.getItem(this.idxInternal);\n        this.idxInternal += 1;\n        return {value: item, done: false};\n      },\n      return: async () => {\n        return {value: undefined, done: true};\n      },\n    };\n  }\n\n  /**\n   * Fetches the next page of items. This makes a new API request.\n   *\n   * @throws {Error} If there are no more pages to fetch.\n   *\n   * @example\n   *\n   * ```ts\n   * const pager = await ai.files.list({config: {pageSize: 10}});\n   * let page = pager.page;\n   * while (true) {\n   *   for (const file of page) {\n   *     console.log(file.name);\n   *   }\n   *   if (!pager.hasNextPage()) {\n   *     break;\n   *   }\n   *   page = await pager.nextPage();\n   * }\n   * ```\n   */\n  async nextPage(): Promise<T[]> {\n    if (!this.hasNextPage()) {\n      throw new Error('No more pages to fetch.');\n    }\n    const response = await this.requestInternal(this.params);\n    this.initNextPage(response);\n    return this.page;\n  }\n\n  /**\n   * Returns true if there are more pages to fetch from the API.\n   */\n  hasNextPage(): boolean {\n    if (this.params['config']?.['pageToken'] !== undefined) {\n      return true;\n    }\n    return false;\n  }\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_batches_converters.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Batches extends BaseModule {\n  constructor(private readonly apiClient: ApiClient) {\n    super();\n  }\n\n  /**\n   * Lists batch jobs.\n   *\n   * @param params - The parameters for the list request.\n   * @return - A pager of batch jobs.\n   *\n   * @example\n   * ```ts\n   * const batchJobs = await ai.batches.list({config: {'pageSize': 2}});\n   * for await (const batchJob of batchJobs) {\n   *   console.log(batchJob);\n   * }\n   * ```\n   */\n  list = async (\n    params: types.ListBatchJobsParameters = {},\n  ): Promise<Pager<types.BatchJob>> => {\n    return new Pager<types.BatchJob>(\n      PagedItem.PAGED_ITEM_BATCH_JOBS,\n      (x: types.ListBatchJobsParameters) => this.listInternal(x),\n      await this.listInternal(params),\n      params,\n    );\n  };\n\n  /**\n   * Create batch job.\n   *\n   * @param params - The parameters for create batch job request.\n   * @return The created batch job.\n   *\n   * @example\n   * ```ts\n   * const response = await ai.batches.create({\n   *   model: 'gemini-2.0-flash',\n   *   src: {gcsUri: 'gs://bucket/path/to/file.jsonl', format: 'jsonl'},\n   *   config: {\n   *     dest: {gcsUri: 'gs://bucket/path/output/directory', format: 'jsonl'},\n   *   }\n   * });\n   * console.log(response);\n   * ```\n   */\n  create = async (\n    params: types.CreateBatchJobParameters,\n  ): Promise<types.BatchJob> => {\n    if (this.apiClient.isVertexAI()) {\n      // Format destination if not provided\n      // Cast params.src as Vertex AI path does not handle InlinedRequest[]\n      params.config = this.formatDestination(\n        params.src as string | types.BatchJobSource,\n        params.config,\n      );\n    }\n    return this.createInternal(params);\n  };\n\n  /**\n   * **Experimental** Creates an embedding batch job.\n   *\n   * @param params - The parameters for create embedding batch job request.\n   * @return The created batch job.\n   *\n   * @example\n   * ```ts\n   * const response = await ai.batches.createEmbeddings({\n   *   model: 'text-embedding-004',\n   *   src: {fileName: 'files/my_embedding_input'},\n   * });\n   * console.log(response);\n   * ```\n   */\n  createEmbeddings = async (\n    params: types.CreateEmbeddingsBatchJobParameters,\n  ): Promise<types.BatchJob> => {\n    console.warn(\n      'batches.createEmbeddings() is experimental and may change without notice.',\n    );\n\n    if (this.apiClient.isVertexAI()) {\n      throw new Error('Vertex AI does not support batches.createEmbeddings.');\n    }\n\n    return this.createEmbeddingsInternal(params);\n  };\n\n  // Helper function to handle inlined generate content requests\n  private createInlinedGenerateContentRequest(\n    params: types.CreateBatchJobParameters,\n  ): {path: string; body: Record<string, unknown>} {\n    const body = converters.createBatchJobParametersToMldev(\n      this.apiClient, // Use instance apiClient\n      params,\n    );\n\n    const urlParams = body['_url'] as Record<string, unknown>;\n    const path = common.formatMap('{model}:batchGenerateContent', urlParams);\n\n    const batch = body['batch'] as {[key: string]: unknown};\n    const inputConfig = batch['inputConfig'] as {[key: string]: unknown};\n    const requestsWrapper = inputConfig['requests'] as {\n      [key: string]: unknown;\n    };\n    const requests = requestsWrapper['requests'] as Array<{\n      [key: string]: unknown;\n    }>;\n    const newRequests = [];\n\n    for (const request of requests) {\n      const requestDict = {...request}; // Clone\n      if (requestDict['systemInstruction']) {\n        const systemInstructionValue = requestDict['systemInstruction'];\n        delete requestDict['systemInstruction'];\n        const requestContent = requestDict['request'] as {\n          [key: string]: unknown;\n        };\n        requestContent['systemInstruction'] = systemInstructionValue;\n        requestDict['request'] = requestContent;\n      }\n      newRequests.push(requestDict);\n    }\n    requestsWrapper['requests'] = newRequests;\n\n    delete body['config'];\n    delete body['_url'];\n    delete body['_query'];\n\n    return {path, body};\n  }\n\n  // Helper function to get the first GCS URI\n  private getGcsUri(src: string | types.BatchJobSource): string | undefined {\n    if (typeof src === 'string') {\n      return src.startsWith('gs://') ? src : undefined;\n    }\n    if (!Array.isArray(src) && src.gcsUri && src.gcsUri.length > 0) {\n      return src.gcsUri[0];\n    }\n    return undefined;\n  }\n\n  // Helper function to get the BigQuery URI\n  private getBigqueryUri(\n    src: string | types.BatchJobSource,\n  ): string | undefined {\n    if (typeof src === 'string') {\n      return src.startsWith('bq://') ? src : undefined;\n    }\n    if (!Array.isArray(src)) {\n      return src.bigqueryUri;\n    }\n    return undefined;\n  }\n\n  // Function to format the destination configuration for Vertex AI\n  private formatDestination(\n    src: string | types.BatchJobSource,\n    config?: types.CreateBatchJobConfig,\n  ): types.CreateBatchJobConfig {\n    const newConfig = config ? {...config} : {};\n\n    const timestampStr = Date.now().toString();\n\n    if (!newConfig.displayName) {\n      newConfig.displayName = `genaiBatchJob_${timestampStr}`;\n    }\n\n    if (newConfig.dest === undefined) {\n      const gcsUri = this.getGcsUri(src);\n      const bigqueryUri = this.getBigqueryUri(src);\n\n      if (gcsUri) {\n        if (gcsUri.endsWith('.jsonl')) {\n          // For .jsonl files, remove suffix and add /dest\n          newConfig.dest = `${gcsUri.slice(0, -6)}/dest`;\n        } else {\n          // Fallback for other GCS URIs\n          newConfig.dest = `${gcsUri}_dest_${timestampStr}`;\n        }\n      } else if (bigqueryUri) {\n        newConfig.dest = `${bigqueryUri}_dest_${timestampStr}`;\n      } else {\n        throw new Error(\n          'Unsupported source for Vertex AI: No GCS or BigQuery URI found.',\n        );\n      }\n    }\n    return newConfig;\n  }\n\n  /**\n   * Internal method to create batch job.\n   *\n   * @param params - The parameters for create batch job request.\n   * @return The created batch job.\n   *\n   */\n  private async createInternal(\n    params: types.CreateBatchJobParameters,\n  ): Promise<types.BatchJob> {\n    let response: Promise<types.BatchJob>;\n\n    let path: string = '';\n    let queryParams: Record<string, string> = {};\n    if (this.apiClient.isVertexAI()) {\n      const body = converters.createBatchJobParametersToVertex(\n        this.apiClient,\n        params,\n      );\n      path = common.formatMap(\n        'batchPredictionJobs',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'POST',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json();\n        }) as Promise<types.BatchJob>;\n\n      return response.then((apiResponse) => {\n        const resp = converters.batchJobFromVertex(apiResponse);\n\n        return resp as types.BatchJob;\n      });\n    } else {\n      const body = converters.createBatchJobParametersToMldev(\n        this.apiClient,\n        params,\n      );\n      path = common.formatMap(\n        '{model}:batchGenerateContent',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'POST',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json();\n        }) as Promise<types.BatchJob>;\n\n      return response.then((apiResponse) => {\n        const resp = converters.batchJobFromMldev(apiResponse);\n\n        return resp as types.BatchJob;\n      });\n    }\n  }\n\n  /**\n   * Internal method to create batch job.\n   *\n   * @param params - The parameters for create batch job request.\n   * @return The created batch job.\n   *\n   */\n  private async createEmbeddingsInternal(\n    params: types.CreateEmbeddingsBatchJobParameters,\n  ): Promise<types.BatchJob> {\n    let response: Promise<types.BatchJob>;\n\n    let path: string = '';\n    let queryParams: Record<string, string> = {};\n    if (this.apiClient.isVertexAI()) {\n      throw new Error(\n        'This method is only supported by the Gemini Developer API.',\n      );\n    } else {\n      const body = converters.createEmbeddingsBatchJobParametersToMldev(\n        this.apiClient,\n        params,\n      );\n      path = common.formatMap(\n        '{model}:asyncBatchEmbedContent',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'POST',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json();\n        }) as Promise<types.BatchJob>;\n\n      return response.then((apiResponse) => {\n        const resp = converters.batchJobFromMldev(apiResponse);\n\n        return resp as types.BatchJob;\n      });\n    }\n  }\n\n  /**\n   * Gets batch job configurations.\n   *\n   * @param params - The parameters for the get request.\n   * @return The batch job.\n   *\n   * @example\n   * ```ts\n   * await ai.batches.get({name: '...'}); // The server-generated resource name.\n   * ```\n   */\n  async get(params: types.GetBatchJobParameters): Promise<types.BatchJob> {\n    let response: Promise<types.BatchJob>;\n\n    let path: string = '';\n    let queryParams: Record<string, string> = {};\n    if (this.apiClient.isVertexAI()) {\n      const body = converters.getBatchJobParametersToVertex(\n        this.apiClient,\n        params,\n      );\n      path = common.formatMap(\n        'batchPredictionJobs/{name}',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'GET',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json();\n        }) as Promise<types.BatchJob>;\n\n      return response.then((apiResponse) => {\n        const resp = converters.batchJobFromVertex(apiResponse);\n\n        return resp as types.BatchJob;\n      });\n    } else {\n      const body = converters.getBatchJobParametersToMldev(\n        this.apiClient,\n        params,\n      );\n      path = common.formatMap(\n        'batches/{name}',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'GET',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json();\n        }) as Promise<types.BatchJob>;\n\n      return response.then((apiResponse) => {\n        const resp = converters.batchJobFromMldev(apiResponse);\n\n        return resp as types.BatchJob;\n      });\n    }\n  }\n\n  /**\n   * Cancels a batch job.\n   *\n   * @param params - The parameters for the cancel request.\n   * @return The empty response returned by the API.\n   *\n   * @example\n   * ```ts\n   * await ai.batches.cancel({name: '...'}); // The server-generated resource name.\n   * ```\n   */\n  async cancel(params: types.CancelBatchJobParameters): Promise<void> {\n    let path: string = '';\n    let queryParams: Record<string, string> = {};\n    if (this.apiClient.isVertexAI()) {\n      const body = converters.cancelBatchJobParametersToVertex(\n        this.apiClient,\n        params,\n      );\n      path = common.formatMap(\n        'batchPredictionJobs/{name}:cancel',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      await this.apiClient.request({\n        path: path,\n        queryParams: queryParams,\n        body: JSON.stringify(body),\n        httpMethod: 'POST',\n        httpOptions: params.config?.httpOptions,\n        abortSignal: params.config?.abortSignal,\n      });\n    } else {\n      const body = converters.cancelBatchJobParametersToMldev(\n        this.apiClient,\n        params,\n      );\n      path = common.formatMap(\n        'batches/{name}:cancel',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      await this.apiClient.request({\n        path: path,\n        queryParams: queryParams,\n        body: JSON.stringify(body),\n        httpMethod: 'POST',\n        httpOptions: params.config?.httpOptions,\n        abortSignal: params.config?.abortSignal,\n      });\n    }\n  }\n\n  private async listInternal(\n    params: types.ListBatchJobsParameters,\n  ): Promise<types.ListBatchJobsResponse> {\n    let response: Promise<types.ListBatchJobsResponse>;\n\n    let path: string = '';\n    let queryParams: Record<string, string> = {};\n    if (this.apiClient.isVertexAI()) {\n      const body = converters.listBatchJobsParametersToVertex(params);\n      path = common.formatMap(\n        'batchPredictionJobs',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'GET',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json().then((jsonResponse) => {\n            const response = jsonResponse as types.ListBatchJobsResponse;\n            response.sdkHttpResponse = {\n              headers: httpResponse.headers,\n            } as types.HttpResponse;\n            return response;\n          });\n        }) as Promise<types.ListBatchJobsResponse>;\n\n      return response.then((apiResponse) => {\n        const resp = converters.listBatchJobsResponseFromVertex(apiResponse);\n        const typedResp = new types.ListBatchJobsResponse();\n        Object.assign(typedResp, resp);\n        return typedResp;\n      });\n    } else {\n      const body = converters.listBatchJobsParametersToMldev(params);\n      path = common.formatMap(\n        'batches',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'GET',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json().then((jsonResponse) => {\n            const response = jsonResponse as types.ListBatchJobsResponse;\n            response.sdkHttpResponse = {\n              headers: httpResponse.headers,\n            } as types.HttpResponse;\n            return response;\n          });\n        }) as Promise<types.ListBatchJobsResponse>;\n\n      return response.then((apiResponse) => {\n        const resp = converters.listBatchJobsResponseFromMldev(apiResponse);\n        const typedResp = new types.ListBatchJobsResponse();\n        Object.assign(typedResp, resp);\n        return typedResp;\n      });\n    }\n  }\n\n  /**\n   * Deletes a batch job.\n   *\n   * @param params - The parameters for the delete request.\n   * @return The empty response returned by the API.\n   *\n   * @example\n   * ```ts\n   * await ai.batches.delete({name: '...'}); // The server-generated resource name.\n   * ```\n   */\n  async delete(\n    params: types.DeleteBatchJobParameters,\n  ): Promise<types.DeleteResourceJob> {\n    let response: Promise<types.DeleteResourceJob>;\n\n    let path: string = '';\n    let queryParams: Record<string, string> = {};\n    if (this.apiClient.isVertexAI()) {\n      const body = converters.deleteBatchJobParametersToVertex(\n        this.apiClient,\n        params,\n      );\n      path = common.formatMap(\n        'batchPredictionJobs/{name}',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'DELETE',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json().then((jsonResponse) => {\n            const response = jsonResponse as types.DeleteResourceJob;\n            response.sdkHttpResponse = {\n              headers: httpResponse.headers,\n            } as types.HttpResponse;\n            return response;\n          });\n        }) as Promise<types.DeleteResourceJob>;\n\n      return response.then((apiResponse) => {\n        const resp = converters.deleteResourceJobFromVertex(apiResponse);\n\n        return resp as types.DeleteResourceJob;\n      });\n    } else {\n      const body = converters.deleteBatchJobParametersToMldev(\n        this.apiClient,\n        params,\n      );\n      path = common.formatMap(\n        'batches/{name}',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'DELETE',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json().then((jsonResponse) => {\n            const response = jsonResponse as types.DeleteResourceJob;\n            response.sdkHttpResponse = {\n              headers: httpResponse.headers,\n            } as types.HttpResponse;\n            return response;\n          });\n        }) as Promise<types.DeleteResourceJob>;\n\n      return response.then((apiResponse) => {\n        const resp = converters.deleteResourceJobFromMldev(apiResponse);\n\n        return resp as types.DeleteResourceJob;\n      });\n    }\n  }\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport type * as types from '../types.js';\n\nexport function blobToMldev(fromObject: types.Blob): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromData = common.getValueByPath(fromObject, ['data']);\n  if (fromData != null) {\n    common.setValueByPath(toObject, ['data'], fromData);\n  }\n\n  if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n    throw new Error('displayName parameter is not supported in Gemini API.');\n  }\n\n  const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n  if (fromMimeType != null) {\n    common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n  }\n\n  return toObject;\n}\n\nexport function contentToMldev(\n  fromObject: types.Content,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromParts = common.getValueByPath(fromObject, ['parts']);\n  if (fromParts != null) {\n    let transformedList = fromParts;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return partToMldev(item);\n      });\n    }\n    common.setValueByPath(toObject, ['parts'], transformedList);\n  }\n\n  const fromRole = common.getValueByPath(fromObject, ['role']);\n  if (fromRole != null) {\n    common.setValueByPath(toObject, ['role'], fromRole);\n  }\n\n  return toObject;\n}\n\nexport function createCachedContentConfigToMldev(\n  fromObject: types.CreateCachedContentConfig,\n  parentObject: Record<string, unknown>,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n  if (parentObject !== undefined && fromTtl != null) {\n    common.setValueByPath(parentObject, ['ttl'], fromTtl);\n  }\n\n  const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n  if (parentObject !== undefined && fromExpireTime != null) {\n    common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n  }\n\n  const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n  if (parentObject !== undefined && fromDisplayName != null) {\n    common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n  }\n\n  const fromContents = common.getValueByPath(fromObject, ['contents']);\n  if (parentObject !== undefined && fromContents != null) {\n    let transformedList = t.tContents(fromContents);\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return contentToMldev(item);\n      });\n    }\n    common.setValueByPath(parentObject, ['contents'], transformedList);\n  }\n\n  const fromSystemInstruction = common.getValueByPath(fromObject, [\n    'systemInstruction',\n  ]);\n  if (parentObject !== undefined && fromSystemInstruction != null) {\n    common.setValueByPath(\n      parentObject,\n      ['systemInstruction'],\n      contentToMldev(t.tContent(fromSystemInstruction)),\n    );\n  }\n\n  const fromTools = common.getValueByPath(fromObject, ['tools']);\n  if (parentObject !== undefined && fromTools != null) {\n    let transformedList = fromTools;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return toolToMldev(item);\n      });\n    }\n    common.setValueByPath(parentObject, ['tools'], transformedList);\n  }\n\n  const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n  if (parentObject !== undefined && fromToolConfig != null) {\n    common.setValueByPath(\n      parentObject,\n      ['toolConfig'],\n      toolConfigToMldev(fromToolConfig),\n    );\n  }\n\n  if (common.getValueByPath(fromObject, ['kmsKeyName']) !== undefined) {\n    throw new Error('kmsKeyName parameter is not supported in Gemini API.');\n  }\n\n  return toObject;\n}\n\nexport function createCachedContentConfigToVertex(\n  fromObject: types.CreateCachedContentConfig,\n  parentObject: Record<string, unknown>,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n  if (parentObject !== undefined && fromTtl != null) {\n    common.setValueByPath(parentObject, ['ttl'], fromTtl);\n  }\n\n  const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n  if (parentObject !== undefined && fromExpireTime != null) {\n    common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n  }\n\n  const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n  if (parentObject !== undefined && fromDisplayName != null) {\n    common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n  }\n\n  const fromContents = common.getValueByPath(fromObject, ['contents']);\n  if (parentObject !== undefined && fromContents != null) {\n    let transformedList = t.tContents(fromContents);\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return item;\n      });\n    }\n    common.setValueByPath(parentObject, ['contents'], transformedList);\n  }\n\n  const fromSystemInstruction = common.getValueByPath(fromObject, [\n    'systemInstruction',\n  ]);\n  if (parentObject !== undefined && fromSystemInstruction != null) {\n    common.setValueByPath(\n      parentObject,\n      ['systemInstruction'],\n      t.tContent(fromSystemInstruction),\n    );\n  }\n\n  const fromTools = common.getValueByPath(fromObject, ['tools']);\n  if (parentObject !== undefined && fromTools != null) {\n    let transformedList = fromTools;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return toolToVertex(item);\n      });\n    }\n    common.setValueByPath(parentObject, ['tools'], transformedList);\n  }\n\n  const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n  if (parentObject !== undefined && fromToolConfig != null) {\n    common.setValueByPath(parentObject, ['toolConfig'], fromToolConfig);\n  }\n\n  const fromKmsKeyName = common.getValueByPath(fromObject, ['kmsKeyName']);\n  if (parentObject !== undefined && fromKmsKeyName != null) {\n    common.setValueByPath(\n      parentObject,\n      ['encryption_spec', 'kmsKeyName'],\n      fromKmsKeyName,\n    );\n  }\n\n  return toObject;\n}\n\nexport function createCachedContentParametersToMldev(\n  apiClient: ApiClient,\n  fromObject: types.CreateCachedContentParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromModel = common.getValueByPath(fromObject, ['model']);\n  if (fromModel != null) {\n    common.setValueByPath(\n      toObject,\n      ['model'],\n      t.tCachesModel(apiClient, fromModel),\n    );\n  }\n\n  const fromConfig = common.getValueByPath(fromObject, ['config']);\n  if (fromConfig != null) {\n    createCachedContentConfigToMldev(fromConfig, toObject);\n  }\n\n  return toObject;\n}\n\nexport function createCachedContentParametersToVertex(\n  apiClient: ApiClient,\n  fromObject: types.CreateCachedContentParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromModel = common.getValueByPath(fromObject, ['model']);\n  if (fromModel != null) {\n    common.setValueByPath(\n      toObject,\n      ['model'],\n      t.tCachesModel(apiClient, fromModel),\n    );\n  }\n\n  const fromConfig = common.getValueByPath(fromObject, ['config']);\n  if (fromConfig != null) {\n    createCachedContentConfigToVertex(fromConfig, toObject);\n  }\n\n  return toObject;\n}\n\nexport function deleteCachedContentParametersToMldev(\n  apiClient: ApiClient,\n  fromObject: types.DeleteCachedContentParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromName = common.getValueByPath(fromObject, ['name']);\n  if (fromName != null) {\n    common.setValueByPath(\n      toObject,\n      ['_url', 'name'],\n      t.tCachedContentName(apiClient, fromName),\n    );\n  }\n\n  return toObject;\n}\n\nexport function deleteCachedContentParametersToVertex(\n  apiClient: ApiClient,\n  fromObject: types.DeleteCachedContentParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromName = common.getValueByPath(fromObject, ['name']);\n  if (fromName != null) {\n    common.setValueByPath(\n      toObject,\n      ['_url', 'name'],\n      t.tCachedContentName(apiClient, fromName),\n    );\n  }\n\n  return toObject;\n}\n\nexport function deleteCachedContentResponseFromMldev(\n  fromObject: types.DeleteCachedContentResponse,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n    'sdkHttpResponse',\n  ]);\n  if (fromSdkHttpResponse != null) {\n    common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n  }\n\n  return toObject;\n}\n\nexport function deleteCachedContentResponseFromVertex(\n  fromObject: types.DeleteCachedContentResponse,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n    'sdkHttpResponse',\n  ]);\n  if (fromSdkHttpResponse != null) {\n    common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n  }\n\n  return toObject;\n}\n\nexport function fileDataToMldev(\n  fromObject: types.FileData,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n    throw new Error('displayName parameter is not supported in Gemini API.');\n  }\n\n  const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n  if (fromFileUri != null) {\n    common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n  }\n\n  const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n  if (fromMimeType != null) {\n    common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n  }\n\n  return toObject;\n}\n\nexport function functionCallToMldev(\n  fromObject: types.FunctionCall,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromId = common.getValueByPath(fromObject, ['id']);\n  if (fromId != null) {\n    common.setValueByPath(toObject, ['id'], fromId);\n  }\n\n  const fromArgs = common.getValueByPath(fromObject, ['args']);\n  if (fromArgs != null) {\n    common.setValueByPath(toObject, ['args'], fromArgs);\n  }\n\n  const fromName = common.getValueByPath(fromObject, ['name']);\n  if (fromName != null) {\n    common.setValueByPath(toObject, ['name'], fromName);\n  }\n\n  if (common.getValueByPath(fromObject, ['partialArgs']) !== undefined) {\n    throw new Error('partialArgs parameter is not supported in Gemini API.');\n  }\n\n  if (common.getValueByPath(fromObject, ['willContinue']) !== undefined) {\n    throw new Error('willContinue parameter is not supported in Gemini API.');\n  }\n\n  return toObject;\n}\n\nexport function functionCallingConfigToMldev(\n  fromObject: types.FunctionCallingConfig,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromMode = common.getValueByPath(fromObject, ['mode']);\n  if (fromMode != null) {\n    common.setValueByPath(toObject, ['mode'], fromMode);\n  }\n\n  const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n    'allowedFunctionNames',\n  ]);\n  if (fromAllowedFunctionNames != null) {\n    common.setValueByPath(\n      toObject,\n      ['allowedFunctionNames'],\n      fromAllowedFunctionNames,\n    );\n  }\n\n  if (\n    common.getValueByPath(fromObject, ['streamFunctionCallArguments']) !==\n    undefined\n  ) {\n    throw new Error(\n      'streamFunctionCallArguments parameter is not supported in Gemini API.',\n    );\n  }\n\n  return toObject;\n}\n\nexport function functionDeclarationToVertex(\n  fromObject: types.FunctionDeclaration,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  if (common.getValueByPath(fromObject, ['behavior']) !== undefined) {\n    throw new Error('behavior parameter is not supported in Vertex AI.');\n  }\n\n  const fromDescription = common.getValueByPath(fromObject, ['description']);\n  if (fromDescription != null) {\n    common.setValueByPath(toObject, ['description'], fromDescription);\n  }\n\n  const fromName = common.getValueByPath(fromObject, ['name']);\n  if (fromName != null) {\n    common.setValueByPath(toObject, ['name'], fromName);\n  }\n\n  const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n  if (fromParameters != null) {\n    common.setValueByPath(toObject, ['parameters'], fromParameters);\n  }\n\n  const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n    'parametersJsonSchema',\n  ]);\n  if (fromParametersJsonSchema != null) {\n    common.setValueByPath(\n      toObject,\n      ['parametersJsonSchema'],\n      fromParametersJsonSchema,\n    );\n  }\n\n  const fromResponse = common.getValueByPath(fromObject, ['response']);\n  if (fromResponse != null) {\n    common.setValueByPath(toObject, ['response'], fromResponse);\n  }\n\n  const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n    'responseJsonSchema',\n  ]);\n  if (fromResponseJsonSchema != null) {\n    common.setValueByPath(\n      toObject,\n      ['responseJsonSchema'],\n      fromResponseJsonSchema,\n    );\n  }\n\n  return toObject;\n}\n\nexport function getCachedContentParametersToMldev(\n  apiClient: ApiClient,\n  fromObject: types.GetCachedContentParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromName = common.getValueByPath(fromObject, ['name']);\n  if (fromName != null) {\n    common.setValueByPath(\n      toObject,\n      ['_url', 'name'],\n      t.tCachedContentName(apiClient, fromName),\n    );\n  }\n\n  return toObject;\n}\n\nexport function getCachedContentParametersToVertex(\n  apiClient: ApiClient,\n  fromObject: types.GetCachedContentParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromName = common.getValueByPath(fromObject, ['name']);\n  if (fromName != null) {\n    common.setValueByPath(\n      toObject,\n      ['_url', 'name'],\n      t.tCachedContentName(apiClient, fromName),\n    );\n  }\n\n  return toObject;\n}\n\nexport function googleMapsToMldev(\n  fromObject: types.GoogleMaps,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  if (common.getValueByPath(fromObject, ['authConfig']) !== undefined) {\n    throw new Error('authConfig parameter is not supported in Gemini API.');\n  }\n\n  const fromEnableWidget = common.getValueByPath(fromObject, ['enableWidget']);\n  if (fromEnableWidget != null) {\n    common.setValueByPath(toObject, ['enableWidget'], fromEnableWidget);\n  }\n\n  return toObject;\n}\n\nexport function googleSearchToMldev(\n  fromObject: types.GoogleSearch,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  if (common.getValueByPath(fromObject, ['excludeDomains']) !== undefined) {\n    throw new Error('excludeDomains parameter is not supported in Gemini API.');\n  }\n\n  if (common.getValueByPath(fromObject, ['blockingConfidence']) !== undefined) {\n    throw new Error(\n      'blockingConfidence parameter is not supported in Gemini API.',\n    );\n  }\n\n  const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n    'timeRangeFilter',\n  ]);\n  if (fromTimeRangeFilter != null) {\n    common.setValueByPath(toObject, ['timeRangeFilter'], fromTimeRangeFilter);\n  }\n\n  return toObject;\n}\n\nexport function listCachedContentsConfigToMldev(\n  fromObject: types.ListCachedContentsConfig,\n  parentObject: Record<string, unknown>,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n  if (parentObject !== undefined && fromPageSize != null) {\n    common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n  }\n\n  const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n  if (parentObject !== undefined && fromPageToken != null) {\n    common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n  }\n\n  return toObject;\n}\n\nexport function listCachedContentsConfigToVertex(\n  fromObject: types.ListCachedContentsConfig,\n  parentObject: Record<string, unknown>,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n  if (parentObject !== undefined && fromPageSize != null) {\n    common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n  }\n\n  const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n  if (parentObject !== undefined && fromPageToken != null) {\n    common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n  }\n\n  return toObject;\n}\n\nexport function listCachedContentsParametersToMldev(\n  fromObject: types.ListCachedContentsParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromConfig = common.getValueByPath(fromObject, ['config']);\n  if (fromConfig != null) {\n    listCachedContentsConfigToMldev(fromConfig, toObject);\n  }\n\n  return toObject;\n}\n\nexport function listCachedContentsParametersToVertex(\n  fromObject: types.ListCachedContentsParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromConfig = common.getValueByPath(fromObject, ['config']);\n  if (fromConfig != null) {\n    listCachedContentsConfigToVertex(fromConfig, toObject);\n  }\n\n  return toObject;\n}\n\nexport function listCachedContentsResponseFromMldev(\n  fromObject: types.ListCachedContentsResponse,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n    'sdkHttpResponse',\n  ]);\n  if (fromSdkHttpResponse != null) {\n    common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n  }\n\n  const fromNextPageToken = common.getValueByPath(fromObject, [\n    'nextPageToken',\n  ]);\n  if (fromNextPageToken != null) {\n    common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n  }\n\n  const fromCachedContents = common.getValueByPath(fromObject, [\n    'cachedContents',\n  ]);\n  if (fromCachedContents != null) {\n    let transformedList = fromCachedContents;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return item;\n      });\n    }\n    common.setValueByPath(toObject, ['cachedContents'], transformedList);\n  }\n\n  return toObject;\n}\n\nexport function listCachedContentsResponseFromVertex(\n  fromObject: types.ListCachedContentsResponse,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n    'sdkHttpResponse',\n  ]);\n  if (fromSdkHttpResponse != null) {\n    common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n  }\n\n  const fromNextPageToken = common.getValueByPath(fromObject, [\n    'nextPageToken',\n  ]);\n  if (fromNextPageToken != null) {\n    common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n  }\n\n  const fromCachedContents = common.getValueByPath(fromObject, [\n    'cachedContents',\n  ]);\n  if (fromCachedContents != null) {\n    let transformedList = fromCachedContents;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return item;\n      });\n    }\n    common.setValueByPath(toObject, ['cachedContents'], transformedList);\n  }\n\n  return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromMediaResolution = common.getValueByPath(fromObject, [\n    'mediaResolution',\n  ]);\n  if (fromMediaResolution != null) {\n    common.setValueByPath(toObject, ['mediaResolution'], fromMediaResolution);\n  }\n\n  const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n    'codeExecutionResult',\n  ]);\n  if (fromCodeExecutionResult != null) {\n    common.setValueByPath(\n      toObject,\n      ['codeExecutionResult'],\n      fromCodeExecutionResult,\n    );\n  }\n\n  const fromExecutableCode = common.getValueByPath(fromObject, [\n    'executableCode',\n  ]);\n  if (fromExecutableCode != null) {\n    common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n  }\n\n  const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n  if (fromFileData != null) {\n    common.setValueByPath(\n      toObject,\n      ['fileData'],\n      fileDataToMldev(fromFileData),\n    );\n  }\n\n  const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n  if (fromFunctionCall != null) {\n    common.setValueByPath(\n      toObject,\n      ['functionCall'],\n      functionCallToMldev(fromFunctionCall),\n    );\n  }\n\n  const fromFunctionResponse = common.getValueByPath(fromObject, [\n    'functionResponse',\n  ]);\n  if (fromFunctionResponse != null) {\n    common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n  }\n\n  const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n  if (fromInlineData != null) {\n    common.setValueByPath(\n      toObject,\n      ['inlineData'],\n      blobToMldev(fromInlineData),\n    );\n  }\n\n  const fromText = common.getValueByPath(fromObject, ['text']);\n  if (fromText != null) {\n    common.setValueByPath(toObject, ['text'], fromText);\n  }\n\n  const fromThought = common.getValueByPath(fromObject, ['thought']);\n  if (fromThought != null) {\n    common.setValueByPath(toObject, ['thought'], fromThought);\n  }\n\n  const fromThoughtSignature = common.getValueByPath(fromObject, [\n    'thoughtSignature',\n  ]);\n  if (fromThoughtSignature != null) {\n    common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n  }\n\n  const fromVideoMetadata = common.getValueByPath(fromObject, [\n    'videoMetadata',\n  ]);\n  if (fromVideoMetadata != null) {\n    common.setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata);\n  }\n\n  return toObject;\n}\n\nexport function toolConfigToMldev(\n  fromObject: types.ToolConfig,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n    'functionCallingConfig',\n  ]);\n  if (fromFunctionCallingConfig != null) {\n    common.setValueByPath(\n      toObject,\n      ['functionCallingConfig'],\n      functionCallingConfigToMldev(fromFunctionCallingConfig),\n    );\n  }\n\n  const fromRetrievalConfig = common.getValueByPath(fromObject, [\n    'retrievalConfig',\n  ]);\n  if (fromRetrievalConfig != null) {\n    common.setValueByPath(toObject, ['retrievalConfig'], fromRetrievalConfig);\n  }\n\n  return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n    'functionDeclarations',\n  ]);\n  if (fromFunctionDeclarations != null) {\n    let transformedList = fromFunctionDeclarations;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return item;\n      });\n    }\n    common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n  }\n\n  if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n    throw new Error('retrieval parameter is not supported in Gemini API.');\n  }\n\n  const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n    'googleSearchRetrieval',\n  ]);\n  if (fromGoogleSearchRetrieval != null) {\n    common.setValueByPath(\n      toObject,\n      ['googleSearchRetrieval'],\n      fromGoogleSearchRetrieval,\n    );\n  }\n\n  const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n  if (fromComputerUse != null) {\n    common.setValueByPath(toObject, ['computerUse'], fromComputerUse);\n  }\n\n  const fromFileSearch = common.getValueByPath(fromObject, ['fileSearch']);\n  if (fromFileSearch != null) {\n    common.setValueByPath(toObject, ['fileSearch'], fromFileSearch);\n  }\n\n  const fromCodeExecution = common.getValueByPath(fromObject, [\n    'codeExecution',\n  ]);\n  if (fromCodeExecution != null) {\n    common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n  }\n\n  if (\n    common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n  ) {\n    throw new Error(\n      'enterpriseWebSearch parameter is not supported in Gemini API.',\n    );\n  }\n\n  const fromGoogleMaps = common.getValueByPath(fromObject, ['googleMaps']);\n  if (fromGoogleMaps != null) {\n    common.setValueByPath(\n      toObject,\n      ['googleMaps'],\n      googleMapsToMldev(fromGoogleMaps),\n    );\n  }\n\n  const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n  if (fromGoogleSearch != null) {\n    common.setValueByPath(\n      toObject,\n      ['googleSearch'],\n      googleSearchToMldev(fromGoogleSearch),\n    );\n  }\n\n  const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n  if (fromUrlContext != null) {\n    common.setValueByPath(toObject, ['urlContext'], fromUrlContext);\n  }\n\n  return toObject;\n}\n\nexport function toolToVertex(fromObject: types.Tool): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n    'functionDeclarations',\n  ]);\n  if (fromFunctionDeclarations != null) {\n    let transformedList = fromFunctionDeclarations;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return functionDeclarationToVertex(item);\n      });\n    }\n    common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n  }\n\n  const fromRetrieval = common.getValueByPath(fromObject, ['retrieval']);\n  if (fromRetrieval != null) {\n    common.setValueByPath(toObject, ['retrieval'], fromRetrieval);\n  }\n\n  const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n    'googleSearchRetrieval',\n  ]);\n  if (fromGoogleSearchRetrieval != null) {\n    common.setValueByPath(\n      toObject,\n      ['googleSearchRetrieval'],\n      fromGoogleSearchRetrieval,\n    );\n  }\n\n  const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n  if (fromComputerUse != null) {\n    common.setValueByPath(toObject, ['computerUse'], fromComputerUse);\n  }\n\n  if (common.getValueByPath(fromObject, ['fileSearch']) !== undefined) {\n    throw new Error('fileSearch parameter is not supported in Vertex AI.');\n  }\n\n  const fromCodeExecution = common.getValueByPath(fromObject, [\n    'codeExecution',\n  ]);\n  if (fromCodeExecution != null) {\n    common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n  }\n\n  const fromEnterpriseWebSearch = common.getValueByPath(fromObject, [\n    'enterpriseWebSearch',\n  ]);\n  if (fromEnterpriseWebSearch != null) {\n    common.setValueByPath(\n      toObject,\n      ['enterpriseWebSearch'],\n      fromEnterpriseWebSearch,\n    );\n  }\n\n  const fromGoogleMaps = common.getValueByPath(fromObject, ['googleMaps']);\n  if (fromGoogleMaps != null) {\n    common.setValueByPath(toObject, ['googleMaps'], fromGoogleMaps);\n  }\n\n  const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n  if (fromGoogleSearch != null) {\n    common.setValueByPath(toObject, ['googleSearch'], fromGoogleSearch);\n  }\n\n  const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n  if (fromUrlContext != null) {\n    common.setValueByPath(toObject, ['urlContext'], fromUrlContext);\n  }\n\n  return toObject;\n}\n\nexport function updateCachedContentConfigToMldev(\n  fromObject: types.UpdateCachedContentConfig,\n  parentObject: Record<string, unknown>,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n  if (parentObject !== undefined && fromTtl != null) {\n    common.setValueByPath(parentObject, ['ttl'], fromTtl);\n  }\n\n  const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n  if (parentObject !== undefined && fromExpireTime != null) {\n    common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n  }\n\n  return toObject;\n}\n\nexport function updateCachedContentConfigToVertex(\n  fromObject: types.UpdateCachedContentConfig,\n  parentObject: Record<string, unknown>,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n  if (parentObject !== undefined && fromTtl != null) {\n    common.setValueByPath(parentObject, ['ttl'], fromTtl);\n  }\n\n  const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n  if (parentObject !== undefined && fromExpireTime != null) {\n    common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n  }\n\n  return toObject;\n}\n\nexport function updateCachedContentParametersToMldev(\n  apiClient: ApiClient,\n  fromObject: types.UpdateCachedContentParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromName = common.getValueByPath(fromObject, ['name']);\n  if (fromName != null) {\n    common.setValueByPath(\n      toObject,\n      ['_url', 'name'],\n      t.tCachedContentName(apiClient, fromName),\n    );\n  }\n\n  const fromConfig = common.getValueByPath(fromObject, ['config']);\n  if (fromConfig != null) {\n    updateCachedContentConfigToMldev(fromConfig, toObject);\n  }\n\n  return toObject;\n}\n\nexport function updateCachedContentParametersToVertex(\n  apiClient: ApiClient,\n  fromObject: types.UpdateCachedContentParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromName = common.getValueByPath(fromObject, ['name']);\n  if (fromName != null) {\n    common.setValueByPath(\n      toObject,\n      ['_url', 'name'],\n      t.tCachedContentName(apiClient, fromName),\n    );\n  }\n\n  const fromConfig = common.getValueByPath(fromObject, ['config']);\n  if (fromConfig != null) {\n    updateCachedContentConfigToVertex(fromConfig, toObject);\n  }\n\n  return toObject;\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_caches_converters.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Caches extends BaseModule {\n  constructor(private readonly apiClient: ApiClient) {\n    super();\n  }\n\n  /**\n   * Lists cached contents.\n   *\n   * @param params - The parameters for the list request.\n   * @return - A pager of cached contents.\n   *\n   * @example\n   * ```ts\n   * const cachedContents = await ai.caches.list({config: {'pageSize': 2}});\n   * for await (const cachedContent of cachedContents) {\n   *   console.log(cachedContent);\n   * }\n   * ```\n   */\n  list = async (\n    params: types.ListCachedContentsParameters = {},\n  ): Promise<Pager<types.CachedContent>> => {\n    return new Pager<types.CachedContent>(\n      PagedItem.PAGED_ITEM_CACHED_CONTENTS,\n      (x: types.ListCachedContentsParameters) => this.listInternal(x),\n      await this.listInternal(params),\n      params,\n    );\n  };\n\n  /**\n   * Creates a cached contents resource.\n   *\n   * @remarks\n   * Context caching is only supported for specific models. See [Gemini\n   * Developer API reference](https://ai.google.dev/gemini-api/docs/caching?lang=node/context-cac)\n   * and [Vertex AI reference](https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview#supported_models)\n   * for more information.\n   *\n   * @param params - The parameters for the create request.\n   * @return The created cached content.\n   *\n   * @example\n   * ```ts\n   * const contents = ...; // Initialize the content to cache.\n   * const response = await ai.caches.create({\n   *   model: 'gemini-2.0-flash-001',\n   *   config: {\n   *    'contents': contents,\n   *    'displayName': 'test cache',\n   *    'systemInstruction': 'What is the sum of the two pdfs?',\n   *    'ttl': '86400s',\n   *  }\n   * });\n   * ```\n   */\n  async create(\n    params: types.CreateCachedContentParameters,\n  ): Promise<types.CachedContent> {\n    let response: Promise<types.CachedContent>;\n\n    let path: string = '';\n    let queryParams: Record<string, string> = {};\n    if (this.apiClient.isVertexAI()) {\n      const body = converters.createCachedContentParametersToVertex(\n        this.apiClient,\n        params,\n      );\n      path = common.formatMap(\n        'cachedContents',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'POST',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json();\n        }) as Promise<types.CachedContent>;\n\n      return response.then((resp) => {\n        return resp as types.CachedContent;\n      });\n    } else {\n      const body = converters.createCachedContentParametersToMldev(\n        this.apiClient,\n        params,\n      );\n      path = common.formatMap(\n        'cachedContents',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'POST',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json();\n        }) as Promise<types.CachedContent>;\n\n      return response.then((resp) => {\n        return resp as types.CachedContent;\n      });\n    }\n  }\n\n  /**\n   * Gets cached content configurations.\n   *\n   * @param params - The parameters for the get request.\n   * @return The cached content.\n   *\n   * @example\n   * ```ts\n   * await ai.caches.get({name: '...'}); // The server-generated resource name.\n   * ```\n   */\n  async get(\n    params: types.GetCachedContentParameters,\n  ): Promise<types.CachedContent> {\n    let response: Promise<types.CachedContent>;\n\n    let path: string = '';\n    let queryParams: Record<string, string> = {};\n    if (this.apiClient.isVertexAI()) {\n      const body = converters.getCachedContentParametersToVertex(\n        this.apiClient,\n        params,\n      );\n      path = common.formatMap(\n        '{name}',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'GET',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json();\n        }) as Promise<types.CachedContent>;\n\n      return response.then((resp) => {\n        return resp as types.CachedContent;\n      });\n    } else {\n      const body = converters.getCachedContentParametersToMldev(\n        this.apiClient,\n        params,\n      );\n      path = common.formatMap(\n        '{name}',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'GET',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json();\n        }) as Promise<types.CachedContent>;\n\n      return response.then((resp) => {\n        return resp as types.CachedContent;\n      });\n    }\n  }\n\n  /**\n   * Deletes cached content.\n   *\n   * @param params - The parameters for the delete request.\n   * @return The empty response returned by the API.\n   *\n   * @example\n   * ```ts\n   * await ai.caches.delete({name: '...'}); // The server-generated resource name.\n   * ```\n   */\n  async delete(\n    params: types.DeleteCachedContentParameters,\n  ): Promise<types.DeleteCachedContentResponse> {\n    let response: Promise<types.DeleteCachedContentResponse>;\n\n    let path: string = '';\n    let queryParams: Record<string, string> = {};\n    if (this.apiClient.isVertexAI()) {\n      const body = converters.deleteCachedContentParametersToVertex(\n        this.apiClient,\n        params,\n      );\n      path = common.formatMap(\n        '{name}',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'DELETE',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json().then((jsonResponse) => {\n            const response = jsonResponse as types.DeleteCachedContentResponse;\n            response.sdkHttpResponse = {\n              headers: httpResponse.headers,\n            } as types.HttpResponse;\n            return response;\n          });\n        }) as Promise<types.DeleteCachedContentResponse>;\n\n      return response.then((apiResponse) => {\n        const resp =\n          converters.deleteCachedContentResponseFromVertex(apiResponse);\n        const typedResp = new types.DeleteCachedContentResponse();\n        Object.assign(typedResp, resp);\n        return typedResp;\n      });\n    } else {\n      const body = converters.deleteCachedContentParametersToMldev(\n        this.apiClient,\n        params,\n      );\n      path = common.formatMap(\n        '{name}',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'DELETE',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json().then((jsonResponse) => {\n            const response = jsonResponse as types.DeleteCachedContentResponse;\n            response.sdkHttpResponse = {\n              headers: httpResponse.headers,\n            } as types.HttpResponse;\n            return response;\n          });\n        }) as Promise<types.DeleteCachedContentResponse>;\n\n      return response.then((apiResponse) => {\n        const resp =\n          converters.deleteCachedContentResponseFromMldev(apiResponse);\n        const typedResp = new types.DeleteCachedContentResponse();\n        Object.assign(typedResp, resp);\n        return typedResp;\n      });\n    }\n  }\n\n  /**\n   * Updates cached content configurations.\n   *\n   * @param params - The parameters for the update request.\n   * @return The updated cached content.\n   *\n   * @example\n   * ```ts\n   * const response = await ai.caches.update({\n   *   name: '...',  // The server-generated resource name.\n   *   config: {'ttl': '7600s'}\n   * });\n   * ```\n   */\n  async update(\n    params: types.UpdateCachedContentParameters,\n  ): Promise<types.CachedContent> {\n    let response: Promise<types.CachedContent>;\n\n    let path: string = '';\n    let queryParams: Record<string, string> = {};\n    if (this.apiClient.isVertexAI()) {\n      const body = converters.updateCachedContentParametersToVertex(\n        this.apiClient,\n        params,\n      );\n      path = common.formatMap(\n        '{name}',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'PATCH',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json();\n        }) as Promise<types.CachedContent>;\n\n      return response.then((resp) => {\n        return resp as types.CachedContent;\n      });\n    } else {\n      const body = converters.updateCachedContentParametersToMldev(\n        this.apiClient,\n        params,\n      );\n      path = common.formatMap(\n        '{name}',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'PATCH',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json();\n        }) as Promise<types.CachedContent>;\n\n      return response.then((resp) => {\n        return resp as types.CachedContent;\n      });\n    }\n  }\n\n  private async listInternal(\n    params: types.ListCachedContentsParameters,\n  ): Promise<types.ListCachedContentsResponse> {\n    let response: Promise<types.ListCachedContentsResponse>;\n\n    let path: string = '';\n    let queryParams: Record<string, string> = {};\n    if (this.apiClient.isVertexAI()) {\n      const body = converters.listCachedContentsParametersToVertex(params);\n      path = common.formatMap(\n        'cachedContents',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'GET',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json().then((jsonResponse) => {\n            const response = jsonResponse as types.ListCachedContentsResponse;\n            response.sdkHttpResponse = {\n              headers: httpResponse.headers,\n            } as types.HttpResponse;\n            return response;\n          });\n        }) as Promise<types.ListCachedContentsResponse>;\n\n      return response.then((apiResponse) => {\n        const resp =\n          converters.listCachedContentsResponseFromVertex(apiResponse);\n        const typedResp = new types.ListCachedContentsResponse();\n        Object.assign(typedResp, resp);\n        return typedResp;\n      });\n    } else {\n      const body = converters.listCachedContentsParametersToMldev(params);\n      path = common.formatMap(\n        'cachedContents',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'GET',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json().then((jsonResponse) => {\n            const response = jsonResponse as types.ListCachedContentsResponse;\n            response.sdkHttpResponse = {\n              headers: httpResponse.headers,\n            } as types.HttpResponse;\n            return response;\n          });\n        }) as Promise<types.ListCachedContentsResponse>;\n\n      return response.then((apiResponse) => {\n        const resp =\n          converters.listCachedContentsResponseFromMldev(apiResponse);\n        const typedResp = new types.ListCachedContentsResponse();\n        Object.assign(typedResp, resp);\n        return typedResp;\n      });\n    }\n  }\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {ApiClient} from './_api_client.js';\nimport * as t from './_transformers.js';\nimport {Models} from './models.js';\nimport * as types from './types.js';\n\n/**\n * Returns true if the response is valid, false otherwise.\n */\nfunction isValidResponse(response: types.GenerateContentResponse): boolean {\n  if (response.candidates == undefined || response.candidates.length === 0) {\n    return false;\n  }\n  const content = response.candidates[0]?.content;\n  if (content === undefined) {\n    return false;\n  }\n  return isValidContent(content);\n}\n\nfunction isValidContent(content: types.Content): boolean {\n  if (content.parts === undefined || content.parts.length === 0) {\n    return false;\n  }\n  for (const part of content.parts) {\n    if (part === undefined || Object.keys(part).length === 0) {\n      return false;\n    }\n  }\n  return true;\n}\n\n/**\n * Validates the history contains the correct roles.\n *\n * @throws Error if the history does not start with a user turn.\n * @throws Error if the history contains an invalid role.\n */\nfunction validateHistory(history: types.Content[]) {\n  // Empty history is valid.\n  if (history.length === 0) {\n    return;\n  }\n  for (const content of history) {\n    if (content.role !== 'user' && content.role !== 'model') {\n      throw new Error(`Role must be user or model, but got ${content.role}.`);\n    }\n  }\n}\n\n/**\n * Extracts the curated (valid) history from a comprehensive history.\n *\n * @remarks\n * The model may sometimes generate invalid or empty contents(e.g., due to safty\n * filters or recitation). Extracting valid turns from the history\n * ensures that subsequent requests could be accpeted by the model.\n */\nfunction extractCuratedHistory(\n  comprehensiveHistory: types.Content[],\n): types.Content[] {\n  if (comprehensiveHistory === undefined || comprehensiveHistory.length === 0) {\n    return [];\n  }\n  const curatedHistory: types.Content[] = [];\n  const length = comprehensiveHistory.length;\n  let i = 0;\n  while (i < length) {\n    if (comprehensiveHistory[i].role === 'user') {\n      curatedHistory.push(comprehensiveHistory[i]);\n      i++;\n    } else {\n      const modelOutput: types.Content[] = [];\n      let isValid = true;\n      while (i < length && comprehensiveHistory[i].role === 'model') {\n        modelOutput.push(comprehensiveHistory[i]);\n        if (isValid && !isValidContent(comprehensiveHistory[i])) {\n          isValid = false;\n        }\n        i++;\n      }\n      if (isValid) {\n        curatedHistory.push(...modelOutput);\n      } else {\n        // Remove the last user input when model content is invalid.\n        curatedHistory.pop();\n      }\n    }\n  }\n  return curatedHistory;\n}\n\n/**\n * A utility class to create a chat session.\n */\nexport class Chats {\n  private readonly modelsModule: Models;\n  private readonly apiClient: ApiClient;\n\n  constructor(modelsModule: Models, apiClient: ApiClient) {\n    this.modelsModule = modelsModule;\n    this.apiClient = apiClient;\n  }\n\n  /**\n   * Creates a new chat session.\n   *\n   * @remarks\n   * The config in the params will be used for all requests within the chat\n   * session unless overridden by a per-request `config` in\n   * @see {@link types.SendMessageParameters#config}.\n   *\n   * @param params - Parameters for creating a chat session.\n   * @returns A new chat session.\n   *\n   * @example\n   * ```ts\n   * const chat = ai.chats.create({\n   *   model: 'gemini-2.0-flash'\n   *   config: {\n   *     temperature: 0.5,\n   *     maxOutputTokens: 1024,\n   *   }\n   * });\n   * ```\n   */\n  create(params: types.CreateChatParameters) {\n    return new Chat(\n      this.apiClient,\n      this.modelsModule,\n      params.model,\n      params.config,\n      // Deep copy the history to avoid mutating the history outside of the\n      // chat session.\n      structuredClone(params.history),\n    );\n  }\n}\n\n/**\n * Chat session that enables sending messages to the model with previous\n * conversation context.\n *\n * @remarks\n * The session maintains all the turns between user and model.\n */\nexport class Chat {\n  // A promise to represent the current state of the message being sent to the\n  // model.\n  private sendPromise: Promise<void> = Promise.resolve();\n\n  constructor(\n    private readonly apiClient: ApiClient,\n    private readonly modelsModule: Models,\n    private readonly model: string,\n    private readonly config: types.GenerateContentConfig = {},\n    private history: types.Content[] = [],\n  ) {\n    validateHistory(history);\n  }\n\n  /**\n   * Sends a message to the model and returns the response.\n   *\n   * @remarks\n   * This method will wait for the previous message to be processed before\n   * sending the next message.\n   *\n   * @see {@link Chat#sendMessageStream} for streaming method.\n   * @param params - parameters for sending messages within a chat session.\n   * @returns The model's response.\n   *\n   * @example\n   * ```ts\n   * const chat = ai.chats.create({model: 'gemini-2.0-flash'});\n   * const response = await chat.sendMessage({\n   *   message: 'Why is the sky blue?'\n   * });\n   * console.log(response.text);\n   * ```\n   */\n  async sendMessage(\n    params: types.SendMessageParameters,\n  ): Promise<types.GenerateContentResponse> {\n    await this.sendPromise;\n    const inputContent = t.tContent(params.message);\n    const responsePromise = this.modelsModule.generateContent({\n      model: this.model,\n      contents: this.getHistory(true).concat(inputContent),\n      config: params.config ?? this.config,\n    });\n    this.sendPromise = (async () => {\n      const response = await responsePromise;\n      const outputContent = response.candidates?.[0]?.content;\n\n      // Because the AFC input contains the entire curated chat history in\n      // addition to the new user input, we need to truncate the AFC history\n      // to deduplicate the existing chat history.\n      const fullAutomaticFunctionCallingHistory =\n        response.automaticFunctionCallingHistory;\n      const index = this.getHistory(true).length;\n\n      let automaticFunctionCallingHistory: types.Content[] = [];\n      if (fullAutomaticFunctionCallingHistory != null) {\n        automaticFunctionCallingHistory =\n          fullAutomaticFunctionCallingHistory.slice(index) ?? [];\n      }\n\n      const modelOutput = outputContent ? [outputContent] : [];\n      this.recordHistory(\n        inputContent,\n        modelOutput,\n        automaticFunctionCallingHistory,\n      );\n      return;\n    })();\n    await this.sendPromise.catch(() => {\n      // Resets sendPromise to avoid subsequent calls failing\n      this.sendPromise = Promise.resolve();\n    });\n    return responsePromise;\n  }\n\n  /**\n   * Sends a message to the model and returns the response in chunks.\n   *\n   * @remarks\n   * This method will wait for the previous message to be processed before\n   * sending the next message.\n   *\n   * @see {@link Chat#sendMessage} for non-streaming method.\n   * @param params - parameters for sending the message.\n   * @return The model's response.\n   *\n   * @example\n   * ```ts\n   * const chat = ai.chats.create({model: 'gemini-2.0-flash'});\n   * const response = await chat.sendMessageStream({\n   *   message: 'Why is the sky blue?'\n   * });\n   * for await (const chunk of response) {\n   *   console.log(chunk.text);\n   * }\n   * ```\n   */\n  async sendMessageStream(\n    params: types.SendMessageParameters,\n  ): Promise<AsyncGenerator<types.GenerateContentResponse>> {\n    await this.sendPromise;\n    const inputContent = t.tContent(params.message);\n    const streamResponse = this.modelsModule.generateContentStream({\n      model: this.model,\n      contents: this.getHistory(true).concat(inputContent),\n      config: params.config ?? this.config,\n    });\n    // Resolve the internal tracking of send completion promise - `sendPromise`\n    // for both success and failure response. The actual failure is still\n    // propagated by the `await streamResponse`.\n    this.sendPromise = streamResponse\n      .then(() => undefined)\n      .catch(() => undefined);\n    const response = await streamResponse;\n    const result = this.processStreamResponse(response, inputContent);\n    return result;\n  }\n\n  /**\n   * Returns the chat history.\n   *\n   * @remarks\n   * The history is a list of contents alternating between user and model.\n   *\n   * There are two types of history:\n   * - The `curated history` contains only the valid turns between user and\n   * model, which will be included in the subsequent requests sent to the model.\n   * - The `comprehensive history` contains all turns, including invalid or\n   *   empty model outputs, providing a complete record of the history.\n   *\n   * The history is updated after receiving the response from the model,\n   * for streaming response, it means receiving the last chunk of the response.\n   *\n   * The `comprehensive history` is returned by default. To get the `curated\n   * history`, set the `curated` parameter to `true`.\n   *\n   * @param curated - whether to return the curated history or the comprehensive\n   *     history.\n   * @return History contents alternating between user and model for the entire\n   *     chat session.\n   */\n  getHistory(curated: boolean = false): types.Content[] {\n    const history = curated\n      ? extractCuratedHistory(this.history)\n      : this.history;\n    // Deep copy the history to avoid mutating the history outside of the\n    // chat session.\n    return structuredClone(history);\n  }\n\n  private async *processStreamResponse(\n    streamResponse: AsyncGenerator<types.GenerateContentResponse>,\n    inputContent: types.Content,\n  ) {\n    const outputContent: types.Content[] = [];\n    for await (const chunk of streamResponse) {\n      if (isValidResponse(chunk)) {\n        const content = chunk.candidates?.[0]?.content;\n        if (content !== undefined) {\n          outputContent.push(content);\n        }\n      }\n      yield chunk;\n    }\n    this.recordHistory(inputContent, outputContent);\n  }\n\n  private recordHistory(\n    userInput: types.Content,\n    modelOutput: types.Content[],\n    automaticFunctionCallingHistory?: types.Content[],\n  ) {\n    let outputContents: types.Content[] = [];\n    if (\n      modelOutput.length > 0 &&\n      modelOutput.every((content) => content.role !== undefined)\n    ) {\n      outputContents = modelOutput;\n    } else {\n      // Appends an empty content when model returns empty response, so that the\n      // history is always alternating between user and model.\n      outputContents.push({\n        role: 'model',\n        parts: [],\n      } as types.Content);\n    }\n    if (\n      automaticFunctionCallingHistory &&\n      automaticFunctionCallingHistory.length > 0\n    ) {\n      this.history.push(\n        ...extractCuratedHistory(automaticFunctionCallingHistory!),\n      );\n    } else {\n      this.history.push(userInput);\n    }\n    this.history.push(...outputContents);\n  }\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Details for errors from calling the API.\n */\nexport interface ApiErrorInfo {\n  /** The error message. */\n  message: string;\n  /** The HTTP status code. */\n  status: number;\n}\n\n/**\n * API errors raised by the GenAI API.\n */\nexport class ApiError extends Error {\n  /** HTTP status code */\n  status: number;\n\n  constructor(options: ApiErrorInfo) {\n    super(options.message);\n    this.name = 'ApiError';\n    this.status = options.status;\n    Object.setPrototypeOf(this, ApiError.prototype);\n  }\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport type * as types from '../types.js';\n\nexport function createFileParametersToMldev(\n  fromObject: types.CreateFileParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromFile = common.getValueByPath(fromObject, ['file']);\n  if (fromFile != null) {\n    common.setValueByPath(toObject, ['file'], fromFile);\n  }\n\n  return toObject;\n}\n\nexport function createFileResponseFromMldev(\n  fromObject: types.CreateFileResponse,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n    'sdkHttpResponse',\n  ]);\n  if (fromSdkHttpResponse != null) {\n    common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n  }\n\n  return toObject;\n}\n\nexport function deleteFileParametersToMldev(\n  fromObject: types.DeleteFileParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromName = common.getValueByPath(fromObject, ['name']);\n  if (fromName != null) {\n    common.setValueByPath(toObject, ['_url', 'file'], t.tFileName(fromName));\n  }\n\n  return toObject;\n}\n\nexport function deleteFileResponseFromMldev(\n  fromObject: types.DeleteFileResponse,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n    'sdkHttpResponse',\n  ]);\n  if (fromSdkHttpResponse != null) {\n    common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n  }\n\n  return toObject;\n}\n\nexport function getFileParametersToMldev(\n  fromObject: types.GetFileParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromName = common.getValueByPath(fromObject, ['name']);\n  if (fromName != null) {\n    common.setValueByPath(toObject, ['_url', 'file'], t.tFileName(fromName));\n  }\n\n  return toObject;\n}\n\nexport function listFilesConfigToMldev(\n  fromObject: types.ListFilesConfig,\n  parentObject: Record<string, unknown>,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n  if (parentObject !== undefined && fromPageSize != null) {\n    common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n  }\n\n  const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n  if (parentObject !== undefined && fromPageToken != null) {\n    common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n  }\n\n  return toObject;\n}\n\nexport function listFilesParametersToMldev(\n  fromObject: types.ListFilesParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromConfig = common.getValueByPath(fromObject, ['config']);\n  if (fromConfig != null) {\n    listFilesConfigToMldev(fromConfig, toObject);\n  }\n\n  return toObject;\n}\n\nexport function listFilesResponseFromMldev(\n  fromObject: types.ListFilesResponse,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n    'sdkHttpResponse',\n  ]);\n  if (fromSdkHttpResponse != null) {\n    common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n  }\n\n  const fromNextPageToken = common.getValueByPath(fromObject, [\n    'nextPageToken',\n  ]);\n  if (fromNextPageToken != null) {\n    common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n  }\n\n  const fromFiles = common.getValueByPath(fromObject, ['files']);\n  if (fromFiles != null) {\n    let transformedList = fromFiles;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return item;\n      });\n    }\n    common.setValueByPath(toObject, ['files'], transformedList);\n  }\n\n  return toObject;\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_files_converters.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Files extends BaseModule {\n  constructor(private readonly apiClient: ApiClient) {\n    super();\n  }\n\n  /**\n   * Lists files.\n   *\n   * @param params - The parameters for the list request.\n   * @return - A pager of files.\n   *\n   * @example\n   * ```ts\n   * const files = await ai.files.list({config: {'pageSize': 2}});\n   * for await (const file of files) {\n   *   console.log(file);\n   * }\n   * ```\n   */\n  list = async (\n    params: types.ListFilesParameters = {},\n  ): Promise<Pager<types.File>> => {\n    return new Pager<types.File>(\n      PagedItem.PAGED_ITEM_FILES,\n      (x: types.ListFilesParameters) => this.listInternal(x),\n      await this.listInternal(params),\n      params,\n    );\n  };\n\n  /**\n   * Uploads a file asynchronously to the Gemini API.\n   * This method is not available in Vertex AI.\n   * Supported upload sources:\n   * - Node.js: File path (string) or Blob object.\n   * - Browser: Blob object (e.g., File).\n   *\n   * @remarks\n   * The `mimeType` can be specified in the `config` parameter. If omitted:\n   *  - For file path (string) inputs, the `mimeType` will be inferred from the\n   *     file extension.\n   *  - For Blob object inputs, the `mimeType` will be set to the Blob's `type`\n   *     property.\n   * Somex eamples for file extension to mimeType mapping:\n   * .txt -> text/plain\n   * .json -> application/json\n   * .jpg  -> image/jpeg\n   * .png -> image/png\n   * .mp3 -> audio/mpeg\n   * .mp4 -> video/mp4\n   *\n   * This section can contain multiple paragraphs and code examples.\n   *\n   * @param params - Optional parameters specified in the\n   *        `types.UploadFileParameters` interface.\n   *         @see {@link types.UploadFileParameters#config} for the optional\n   *         config in the parameters.\n   * @return A promise that resolves to a `types.File` object.\n   * @throws An error if called on a Vertex AI client.\n   * @throws An error if the `mimeType` is not provided and can not be inferred,\n   * the `mimeType` can be provided in the `params.config` parameter.\n   * @throws An error occurs if a suitable upload location cannot be established.\n   *\n   * @example\n   * The following code uploads a file to Gemini API.\n   *\n   * ```ts\n   * const file = await ai.files.upload({file: 'file.txt', config: {\n   *   mimeType: 'text/plain',\n   * }});\n   * console.log(file.name);\n   * ```\n   */\n  async upload(params: types.UploadFileParameters): Promise<types.File> {\n    if (this.apiClient.isVertexAI()) {\n      throw new Error(\n        'Vertex AI does not support uploading files. You can share files through a GCS bucket.',\n      );\n    }\n\n    return this.apiClient\n      .uploadFile(params.file, params.config)\n      .then((resp) => {\n        return resp as types.File;\n      });\n  }\n\n  /**\n   * Downloads a remotely stored file asynchronously to a location specified in\n   * the `params` object. This method only works on Node environment, to\n   * download files in the browser, use a browser compliant method like an <a>\n   * tag.\n   *\n   * @param params - The parameters for the download request.\n   *\n   * @example\n   * The following code downloads an example file named \"files/mehozpxf877d\" as\n   * \"file.txt\".\n   *\n   * ```ts\n   * await ai.files.download({file: file.name, downloadPath: 'file.txt'});\n   * ```\n   */\n\n  async download(params: types.DownloadFileParameters): Promise<void> {\n    await this.apiClient.downloadFile(params);\n  }\n\n  private async listInternal(\n    params: types.ListFilesParameters,\n  ): Promise<types.ListFilesResponse> {\n    let response: Promise<types.ListFilesResponse>;\n\n    let path: string = '';\n    let queryParams: Record<string, string> = {};\n    if (this.apiClient.isVertexAI()) {\n      throw new Error(\n        'This method is only supported by the Gemini Developer API.',\n      );\n    } else {\n      const body = converters.listFilesParametersToMldev(params);\n      path = common.formatMap('files', body['_url'] as Record<string, unknown>);\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'GET',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json().then((jsonResponse) => {\n            const response = jsonResponse as types.ListFilesResponse;\n            response.sdkHttpResponse = {\n              headers: httpResponse.headers,\n            } as types.HttpResponse;\n            return response;\n          });\n        }) as Promise<types.ListFilesResponse>;\n\n      return response.then((apiResponse) => {\n        const resp = converters.listFilesResponseFromMldev(apiResponse);\n        const typedResp = new types.ListFilesResponse();\n        Object.assign(typedResp, resp);\n        return typedResp;\n      });\n    }\n  }\n\n  private async createInternal(\n    params: types.CreateFileParameters,\n  ): Promise<types.CreateFileResponse> {\n    let response: Promise<types.CreateFileResponse>;\n\n    let path: string = '';\n    let queryParams: Record<string, string> = {};\n    if (this.apiClient.isVertexAI()) {\n      throw new Error(\n        'This method is only supported by the Gemini Developer API.',\n      );\n    } else {\n      const body = converters.createFileParametersToMldev(params);\n      path = common.formatMap(\n        'upload/v1beta/files',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'POST',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json();\n        }) as Promise<types.CreateFileResponse>;\n\n      return response.then((apiResponse) => {\n        const resp = converters.createFileResponseFromMldev(apiResponse);\n        const typedResp = new types.CreateFileResponse();\n        Object.assign(typedResp, resp);\n        return typedResp;\n      });\n    }\n  }\n\n  /**\n   * Retrieves the file information from the service.\n   *\n   * @param params - The parameters for the get request\n   * @return The Promise that resolves to the types.File object requested.\n   *\n   * @example\n   * ```ts\n   * const config: GetFileParameters = {\n   *   name: fileName,\n   * };\n   * file = await ai.files.get(config);\n   * console.log(file.name);\n   * ```\n   */\n  async get(params: types.GetFileParameters): Promise<types.File> {\n    let response: Promise<types.File>;\n\n    let path: string = '';\n    let queryParams: Record<string, string> = {};\n    if (this.apiClient.isVertexAI()) {\n      throw new Error(\n        'This method is only supported by the Gemini Developer API.',\n      );\n    } else {\n      const body = converters.getFileParametersToMldev(params);\n      path = common.formatMap(\n        'files/{file}',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'GET',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json();\n        }) as Promise<types.File>;\n\n      return response.then((resp) => {\n        return resp as types.File;\n      });\n    }\n  }\n\n  /**\n   * Deletes a remotely stored file.\n   *\n   * @param params - The parameters for the delete request.\n   * @return The DeleteFileResponse, the response for the delete method.\n   *\n   * @example\n   * The following code deletes an example file named \"files/mehozpxf877d\".\n   *\n   * ```ts\n   * await ai.files.delete({name: file.name});\n   * ```\n   */\n  async delete(\n    params: types.DeleteFileParameters,\n  ): Promise<types.DeleteFileResponse> {\n    let response: Promise<types.DeleteFileResponse>;\n\n    let path: string = '';\n    let queryParams: Record<string, string> = {};\n    if (this.apiClient.isVertexAI()) {\n      throw new Error(\n        'This method is only supported by the Gemini Developer API.',\n      );\n    } else {\n      const body = converters.deleteFileParametersToMldev(params);\n      path = common.formatMap(\n        'files/{file}',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'DELETE',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json().then((jsonResponse) => {\n            const response = jsonResponse as types.DeleteFileResponse;\n            response.sdkHttpResponse = {\n              headers: httpResponse.headers,\n            } as types.HttpResponse;\n            return response;\n          });\n        }) as Promise<types.DeleteFileResponse>;\n\n      return response.then((apiResponse) => {\n        const resp = converters.deleteFileResponseFromMldev(apiResponse);\n        const typedResp = new types.DeleteFileResponse();\n        Object.assign(typedResp, resp);\n        return typedResp;\n      });\n    }\n  }\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport type * as types from '../types.js';\n\nexport function blobToMldev(fromObject: types.Blob): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromData = common.getValueByPath(fromObject, ['data']);\n  if (fromData != null) {\n    common.setValueByPath(toObject, ['data'], fromData);\n  }\n\n  if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n    throw new Error('displayName parameter is not supported in Gemini API.');\n  }\n\n  const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n  if (fromMimeType != null) {\n    common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n  }\n\n  return toObject;\n}\n\nexport function contentToMldev(\n  fromObject: types.Content,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromParts = common.getValueByPath(fromObject, ['parts']);\n  if (fromParts != null) {\n    let transformedList = fromParts;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return partToMldev(item);\n      });\n    }\n    common.setValueByPath(toObject, ['parts'], transformedList);\n  }\n\n  const fromRole = common.getValueByPath(fromObject, ['role']);\n  if (fromRole != null) {\n    common.setValueByPath(toObject, ['role'], fromRole);\n  }\n\n  return toObject;\n}\n\nexport function fileDataToMldev(\n  fromObject: types.FileData,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n    throw new Error('displayName parameter is not supported in Gemini API.');\n  }\n\n  const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n  if (fromFileUri != null) {\n    common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n  }\n\n  const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n  if (fromMimeType != null) {\n    common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n  }\n\n  return toObject;\n}\n\nexport function functionCallToMldev(\n  fromObject: types.FunctionCall,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromId = common.getValueByPath(fromObject, ['id']);\n  if (fromId != null) {\n    common.setValueByPath(toObject, ['id'], fromId);\n  }\n\n  const fromArgs = common.getValueByPath(fromObject, ['args']);\n  if (fromArgs != null) {\n    common.setValueByPath(toObject, ['args'], fromArgs);\n  }\n\n  const fromName = common.getValueByPath(fromObject, ['name']);\n  if (fromName != null) {\n    common.setValueByPath(toObject, ['name'], fromName);\n  }\n\n  if (common.getValueByPath(fromObject, ['partialArgs']) !== undefined) {\n    throw new Error('partialArgs parameter is not supported in Gemini API.');\n  }\n\n  if (common.getValueByPath(fromObject, ['willContinue']) !== undefined) {\n    throw new Error('willContinue parameter is not supported in Gemini API.');\n  }\n\n  return toObject;\n}\n\nexport function functionDeclarationToVertex(\n  fromObject: types.FunctionDeclaration,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  if (common.getValueByPath(fromObject, ['behavior']) !== undefined) {\n    throw new Error('behavior parameter is not supported in Vertex AI.');\n  }\n\n  const fromDescription = common.getValueByPath(fromObject, ['description']);\n  if (fromDescription != null) {\n    common.setValueByPath(toObject, ['description'], fromDescription);\n  }\n\n  const fromName = common.getValueByPath(fromObject, ['name']);\n  if (fromName != null) {\n    common.setValueByPath(toObject, ['name'], fromName);\n  }\n\n  const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n  if (fromParameters != null) {\n    common.setValueByPath(toObject, ['parameters'], fromParameters);\n  }\n\n  const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n    'parametersJsonSchema',\n  ]);\n  if (fromParametersJsonSchema != null) {\n    common.setValueByPath(\n      toObject,\n      ['parametersJsonSchema'],\n      fromParametersJsonSchema,\n    );\n  }\n\n  const fromResponse = common.getValueByPath(fromObject, ['response']);\n  if (fromResponse != null) {\n    common.setValueByPath(toObject, ['response'], fromResponse);\n  }\n\n  const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n    'responseJsonSchema',\n  ]);\n  if (fromResponseJsonSchema != null) {\n    common.setValueByPath(\n      toObject,\n      ['responseJsonSchema'],\n      fromResponseJsonSchema,\n    );\n  }\n\n  return toObject;\n}\n\nexport function generationConfigToVertex(\n  fromObject: types.GenerationConfig,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromModelSelectionConfig = common.getValueByPath(fromObject, [\n    'modelSelectionConfig',\n  ]);\n  if (fromModelSelectionConfig != null) {\n    common.setValueByPath(toObject, ['modelConfig'], fromModelSelectionConfig);\n  }\n\n  const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n    'responseJsonSchema',\n  ]);\n  if (fromResponseJsonSchema != null) {\n    common.setValueByPath(\n      toObject,\n      ['responseJsonSchema'],\n      fromResponseJsonSchema,\n    );\n  }\n\n  const fromAudioTimestamp = common.getValueByPath(fromObject, [\n    'audioTimestamp',\n  ]);\n  if (fromAudioTimestamp != null) {\n    common.setValueByPath(toObject, ['audioTimestamp'], fromAudioTimestamp);\n  }\n\n  const fromCandidateCount = common.getValueByPath(fromObject, [\n    'candidateCount',\n  ]);\n  if (fromCandidateCount != null) {\n    common.setValueByPath(toObject, ['candidateCount'], fromCandidateCount);\n  }\n\n  const fromEnableAffectiveDialog = common.getValueByPath(fromObject, [\n    'enableAffectiveDialog',\n  ]);\n  if (fromEnableAffectiveDialog != null) {\n    common.setValueByPath(\n      toObject,\n      ['enableAffectiveDialog'],\n      fromEnableAffectiveDialog,\n    );\n  }\n\n  const fromFrequencyPenalty = common.getValueByPath(fromObject, [\n    'frequencyPenalty',\n  ]);\n  if (fromFrequencyPenalty != null) {\n    common.setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty);\n  }\n\n  const fromLogprobs = common.getValueByPath(fromObject, ['logprobs']);\n  if (fromLogprobs != null) {\n    common.setValueByPath(toObject, ['logprobs'], fromLogprobs);\n  }\n\n  const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n    'maxOutputTokens',\n  ]);\n  if (fromMaxOutputTokens != null) {\n    common.setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens);\n  }\n\n  const fromMediaResolution = common.getValueByPath(fromObject, [\n    'mediaResolution',\n  ]);\n  if (fromMediaResolution != null) {\n    common.setValueByPath(toObject, ['mediaResolution'], fromMediaResolution);\n  }\n\n  const fromPresencePenalty = common.getValueByPath(fromObject, [\n    'presencePenalty',\n  ]);\n  if (fromPresencePenalty != null) {\n    common.setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty);\n  }\n\n  const fromResponseLogprobs = common.getValueByPath(fromObject, [\n    'responseLogprobs',\n  ]);\n  if (fromResponseLogprobs != null) {\n    common.setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs);\n  }\n\n  const fromResponseMimeType = common.getValueByPath(fromObject, [\n    'responseMimeType',\n  ]);\n  if (fromResponseMimeType != null) {\n    common.setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType);\n  }\n\n  const fromResponseModalities = common.getValueByPath(fromObject, [\n    'responseModalities',\n  ]);\n  if (fromResponseModalities != null) {\n    common.setValueByPath(\n      toObject,\n      ['responseModalities'],\n      fromResponseModalities,\n    );\n  }\n\n  const fromResponseSchema = common.getValueByPath(fromObject, [\n    'responseSchema',\n  ]);\n  if (fromResponseSchema != null) {\n    common.setValueByPath(toObject, ['responseSchema'], fromResponseSchema);\n  }\n\n  const fromRoutingConfig = common.getValueByPath(fromObject, [\n    'routingConfig',\n  ]);\n  if (fromRoutingConfig != null) {\n    common.setValueByPath(toObject, ['routingConfig'], fromRoutingConfig);\n  }\n\n  const fromSeed = common.getValueByPath(fromObject, ['seed']);\n  if (fromSeed != null) {\n    common.setValueByPath(toObject, ['seed'], fromSeed);\n  }\n\n  const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n  if (fromSpeechConfig != null) {\n    common.setValueByPath(\n      toObject,\n      ['speechConfig'],\n      speechConfigToVertex(fromSpeechConfig),\n    );\n  }\n\n  const fromStopSequences = common.getValueByPath(fromObject, [\n    'stopSequences',\n  ]);\n  if (fromStopSequences != null) {\n    common.setValueByPath(toObject, ['stopSequences'], fromStopSequences);\n  }\n\n  const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n  if (fromTemperature != null) {\n    common.setValueByPath(toObject, ['temperature'], fromTemperature);\n  }\n\n  const fromThinkingConfig = common.getValueByPath(fromObject, [\n    'thinkingConfig',\n  ]);\n  if (fromThinkingConfig != null) {\n    common.setValueByPath(toObject, ['thinkingConfig'], fromThinkingConfig);\n  }\n\n  const fromTopK = common.getValueByPath(fromObject, ['topK']);\n  if (fromTopK != null) {\n    common.setValueByPath(toObject, ['topK'], fromTopK);\n  }\n\n  const fromTopP = common.getValueByPath(fromObject, ['topP']);\n  if (fromTopP != null) {\n    common.setValueByPath(toObject, ['topP'], fromTopP);\n  }\n\n  if (\n    common.getValueByPath(fromObject, ['enableEnhancedCivicAnswers']) !==\n    undefined\n  ) {\n    throw new Error(\n      'enableEnhancedCivicAnswers parameter is not supported in Vertex AI.',\n    );\n  }\n\n  return toObject;\n}\n\nexport function googleMapsToMldev(\n  fromObject: types.GoogleMaps,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  if (common.getValueByPath(fromObject, ['authConfig']) !== undefined) {\n    throw new Error('authConfig parameter is not supported in Gemini API.');\n  }\n\n  const fromEnableWidget = common.getValueByPath(fromObject, ['enableWidget']);\n  if (fromEnableWidget != null) {\n    common.setValueByPath(toObject, ['enableWidget'], fromEnableWidget);\n  }\n\n  return toObject;\n}\n\nexport function googleSearchToMldev(\n  fromObject: types.GoogleSearch,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  if (common.getValueByPath(fromObject, ['excludeDomains']) !== undefined) {\n    throw new Error('excludeDomains parameter is not supported in Gemini API.');\n  }\n\n  if (common.getValueByPath(fromObject, ['blockingConfidence']) !== undefined) {\n    throw new Error(\n      'blockingConfidence parameter is not supported in Gemini API.',\n    );\n  }\n\n  const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n    'timeRangeFilter',\n  ]);\n  if (fromTimeRangeFilter != null) {\n    common.setValueByPath(toObject, ['timeRangeFilter'], fromTimeRangeFilter);\n  }\n\n  return toObject;\n}\n\nexport function liveClientContentToMldev(\n  fromObject: types.LiveClientContent,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromTurns = common.getValueByPath(fromObject, ['turns']);\n  if (fromTurns != null) {\n    let transformedList = fromTurns;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return contentToMldev(item);\n      });\n    }\n    common.setValueByPath(toObject, ['turns'], transformedList);\n  }\n\n  const fromTurnComplete = common.getValueByPath(fromObject, ['turnComplete']);\n  if (fromTurnComplete != null) {\n    common.setValueByPath(toObject, ['turnComplete'], fromTurnComplete);\n  }\n\n  return toObject;\n}\n\nexport function liveClientMessageToMldev(\n  fromObject: types.LiveClientMessage,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromSetup = common.getValueByPath(fromObject, ['setup']);\n  if (fromSetup != null) {\n    common.setValueByPath(\n      toObject,\n      ['setup'],\n      liveClientSetupToMldev(fromSetup),\n    );\n  }\n\n  const fromClientContent = common.getValueByPath(fromObject, [\n    'clientContent',\n  ]);\n  if (fromClientContent != null) {\n    common.setValueByPath(\n      toObject,\n      ['clientContent'],\n      liveClientContentToMldev(fromClientContent),\n    );\n  }\n\n  const fromRealtimeInput = common.getValueByPath(fromObject, [\n    'realtimeInput',\n  ]);\n  if (fromRealtimeInput != null) {\n    common.setValueByPath(\n      toObject,\n      ['realtimeInput'],\n      liveClientRealtimeInputToMldev(fromRealtimeInput),\n    );\n  }\n\n  const fromToolResponse = common.getValueByPath(fromObject, ['toolResponse']);\n  if (fromToolResponse != null) {\n    common.setValueByPath(toObject, ['toolResponse'], fromToolResponse);\n  }\n\n  return toObject;\n}\n\nexport function liveClientMessageToVertex(\n  fromObject: types.LiveClientMessage,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromSetup = common.getValueByPath(fromObject, ['setup']);\n  if (fromSetup != null) {\n    common.setValueByPath(\n      toObject,\n      ['setup'],\n      liveClientSetupToVertex(fromSetup),\n    );\n  }\n\n  const fromClientContent = common.getValueByPath(fromObject, [\n    'clientContent',\n  ]);\n  if (fromClientContent != null) {\n    common.setValueByPath(toObject, ['clientContent'], fromClientContent);\n  }\n\n  const fromRealtimeInput = common.getValueByPath(fromObject, [\n    'realtimeInput',\n  ]);\n  if (fromRealtimeInput != null) {\n    common.setValueByPath(\n      toObject,\n      ['realtimeInput'],\n      liveClientRealtimeInputToVertex(fromRealtimeInput),\n    );\n  }\n\n  const fromToolResponse = common.getValueByPath(fromObject, ['toolResponse']);\n  if (fromToolResponse != null) {\n    common.setValueByPath(toObject, ['toolResponse'], fromToolResponse);\n  }\n\n  return toObject;\n}\n\nexport function liveClientRealtimeInputToMldev(\n  fromObject: types.LiveClientRealtimeInput,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromMediaChunks = common.getValueByPath(fromObject, ['mediaChunks']);\n  if (fromMediaChunks != null) {\n    let transformedList = fromMediaChunks;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return blobToMldev(item);\n      });\n    }\n    common.setValueByPath(toObject, ['mediaChunks'], transformedList);\n  }\n\n  const fromAudio = common.getValueByPath(fromObject, ['audio']);\n  if (fromAudio != null) {\n    common.setValueByPath(toObject, ['audio'], blobToMldev(fromAudio));\n  }\n\n  const fromAudioStreamEnd = common.getValueByPath(fromObject, [\n    'audioStreamEnd',\n  ]);\n  if (fromAudioStreamEnd != null) {\n    common.setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd);\n  }\n\n  const fromVideo = common.getValueByPath(fromObject, ['video']);\n  if (fromVideo != null) {\n    common.setValueByPath(toObject, ['video'], blobToMldev(fromVideo));\n  }\n\n  const fromText = common.getValueByPath(fromObject, ['text']);\n  if (fromText != null) {\n    common.setValueByPath(toObject, ['text'], fromText);\n  }\n\n  const fromActivityStart = common.getValueByPath(fromObject, [\n    'activityStart',\n  ]);\n  if (fromActivityStart != null) {\n    common.setValueByPath(toObject, ['activityStart'], fromActivityStart);\n  }\n\n  const fromActivityEnd = common.getValueByPath(fromObject, ['activityEnd']);\n  if (fromActivityEnd != null) {\n    common.setValueByPath(toObject, ['activityEnd'], fromActivityEnd);\n  }\n\n  return toObject;\n}\n\nexport function liveClientRealtimeInputToVertex(\n  fromObject: types.LiveClientRealtimeInput,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromMediaChunks = common.getValueByPath(fromObject, ['mediaChunks']);\n  if (fromMediaChunks != null) {\n    let transformedList = fromMediaChunks;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return item;\n      });\n    }\n    common.setValueByPath(toObject, ['mediaChunks'], transformedList);\n  }\n\n  const fromAudio = common.getValueByPath(fromObject, ['audio']);\n  if (fromAudio != null) {\n    common.setValueByPath(toObject, ['audio'], fromAudio);\n  }\n\n  if (common.getValueByPath(fromObject, ['audioStreamEnd']) !== undefined) {\n    throw new Error('audioStreamEnd parameter is not supported in Vertex AI.');\n  }\n\n  const fromVideo = common.getValueByPath(fromObject, ['video']);\n  if (fromVideo != null) {\n    common.setValueByPath(toObject, ['video'], fromVideo);\n  }\n\n  const fromText = common.getValueByPath(fromObject, ['text']);\n  if (fromText != null) {\n    common.setValueByPath(toObject, ['text'], fromText);\n  }\n\n  const fromActivityStart = common.getValueByPath(fromObject, [\n    'activityStart',\n  ]);\n  if (fromActivityStart != null) {\n    common.setValueByPath(toObject, ['activityStart'], fromActivityStart);\n  }\n\n  const fromActivityEnd = common.getValueByPath(fromObject, ['activityEnd']);\n  if (fromActivityEnd != null) {\n    common.setValueByPath(toObject, ['activityEnd'], fromActivityEnd);\n  }\n\n  return toObject;\n}\n\nexport function liveClientSetupToMldev(\n  fromObject: types.LiveClientSetup,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromModel = common.getValueByPath(fromObject, ['model']);\n  if (fromModel != null) {\n    common.setValueByPath(toObject, ['model'], fromModel);\n  }\n\n  const fromGenerationConfig = common.getValueByPath(fromObject, [\n    'generationConfig',\n  ]);\n  if (fromGenerationConfig != null) {\n    common.setValueByPath(toObject, ['generationConfig'], fromGenerationConfig);\n  }\n\n  const fromSystemInstruction = common.getValueByPath(fromObject, [\n    'systemInstruction',\n  ]);\n  if (fromSystemInstruction != null) {\n    common.setValueByPath(\n      toObject,\n      ['systemInstruction'],\n      contentToMldev(t.tContent(fromSystemInstruction)),\n    );\n  }\n\n  const fromTools = common.getValueByPath(fromObject, ['tools']);\n  if (fromTools != null) {\n    let transformedList = t.tTools(fromTools);\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return toolToMldev(t.tTool(item));\n      });\n    }\n    common.setValueByPath(toObject, ['tools'], transformedList);\n  }\n\n  const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n    'realtimeInputConfig',\n  ]);\n  if (fromRealtimeInputConfig != null) {\n    common.setValueByPath(\n      toObject,\n      ['realtimeInputConfig'],\n      fromRealtimeInputConfig,\n    );\n  }\n\n  const fromSessionResumption = common.getValueByPath(fromObject, [\n    'sessionResumption',\n  ]);\n  if (fromSessionResumption != null) {\n    common.setValueByPath(\n      toObject,\n      ['sessionResumption'],\n      sessionResumptionConfigToMldev(fromSessionResumption),\n    );\n  }\n\n  const fromContextWindowCompression = common.getValueByPath(fromObject, [\n    'contextWindowCompression',\n  ]);\n  if (fromContextWindowCompression != null) {\n    common.setValueByPath(\n      toObject,\n      ['contextWindowCompression'],\n      fromContextWindowCompression,\n    );\n  }\n\n  const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n    'inputAudioTranscription',\n  ]);\n  if (fromInputAudioTranscription != null) {\n    common.setValueByPath(\n      toObject,\n      ['inputAudioTranscription'],\n      fromInputAudioTranscription,\n    );\n  }\n\n  const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n    'outputAudioTranscription',\n  ]);\n  if (fromOutputAudioTranscription != null) {\n    common.setValueByPath(\n      toObject,\n      ['outputAudioTranscription'],\n      fromOutputAudioTranscription,\n    );\n  }\n\n  const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n  if (fromProactivity != null) {\n    common.setValueByPath(toObject, ['proactivity'], fromProactivity);\n  }\n\n  if (common.getValueByPath(fromObject, ['explicitVadSignal']) !== undefined) {\n    throw new Error(\n      'explicitVadSignal parameter is not supported in Gemini API.',\n    );\n  }\n\n  return toObject;\n}\n\nexport function liveClientSetupToVertex(\n  fromObject: types.LiveClientSetup,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromModel = common.getValueByPath(fromObject, ['model']);\n  if (fromModel != null) {\n    common.setValueByPath(toObject, ['model'], fromModel);\n  }\n\n  const fromGenerationConfig = common.getValueByPath(fromObject, [\n    'generationConfig',\n  ]);\n  if (fromGenerationConfig != null) {\n    common.setValueByPath(\n      toObject,\n      ['generationConfig'],\n      generationConfigToVertex(fromGenerationConfig),\n    );\n  }\n\n  const fromSystemInstruction = common.getValueByPath(fromObject, [\n    'systemInstruction',\n  ]);\n  if (fromSystemInstruction != null) {\n    common.setValueByPath(\n      toObject,\n      ['systemInstruction'],\n      t.tContent(fromSystemInstruction),\n    );\n  }\n\n  const fromTools = common.getValueByPath(fromObject, ['tools']);\n  if (fromTools != null) {\n    let transformedList = t.tTools(fromTools);\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return toolToVertex(t.tTool(item));\n      });\n    }\n    common.setValueByPath(toObject, ['tools'], transformedList);\n  }\n\n  const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n    'realtimeInputConfig',\n  ]);\n  if (fromRealtimeInputConfig != null) {\n    common.setValueByPath(\n      toObject,\n      ['realtimeInputConfig'],\n      fromRealtimeInputConfig,\n    );\n  }\n\n  const fromSessionResumption = common.getValueByPath(fromObject, [\n    'sessionResumption',\n  ]);\n  if (fromSessionResumption != null) {\n    common.setValueByPath(\n      toObject,\n      ['sessionResumption'],\n      fromSessionResumption,\n    );\n  }\n\n  const fromContextWindowCompression = common.getValueByPath(fromObject, [\n    'contextWindowCompression',\n  ]);\n  if (fromContextWindowCompression != null) {\n    common.setValueByPath(\n      toObject,\n      ['contextWindowCompression'],\n      fromContextWindowCompression,\n    );\n  }\n\n  const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n    'inputAudioTranscription',\n  ]);\n  if (fromInputAudioTranscription != null) {\n    common.setValueByPath(\n      toObject,\n      ['inputAudioTranscription'],\n      fromInputAudioTranscription,\n    );\n  }\n\n  const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n    'outputAudioTranscription',\n  ]);\n  if (fromOutputAudioTranscription != null) {\n    common.setValueByPath(\n      toObject,\n      ['outputAudioTranscription'],\n      fromOutputAudioTranscription,\n    );\n  }\n\n  const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n  if (fromProactivity != null) {\n    common.setValueByPath(toObject, ['proactivity'], fromProactivity);\n  }\n\n  const fromExplicitVadSignal = common.getValueByPath(fromObject, [\n    'explicitVadSignal',\n  ]);\n  if (fromExplicitVadSignal != null) {\n    common.setValueByPath(\n      toObject,\n      ['explicitVadSignal'],\n      fromExplicitVadSignal,\n    );\n  }\n\n  return toObject;\n}\n\nexport function liveConnectConfigToMldev(\n  fromObject: types.LiveConnectConfig,\n  parentObject: Record<string, unknown>,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromGenerationConfig = common.getValueByPath(fromObject, [\n    'generationConfig',\n  ]);\n  if (parentObject !== undefined && fromGenerationConfig != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'generationConfig'],\n      fromGenerationConfig,\n    );\n  }\n\n  const fromResponseModalities = common.getValueByPath(fromObject, [\n    'responseModalities',\n  ]);\n  if (parentObject !== undefined && fromResponseModalities != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'generationConfig', 'responseModalities'],\n      fromResponseModalities,\n    );\n  }\n\n  const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n  if (parentObject !== undefined && fromTemperature != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'generationConfig', 'temperature'],\n      fromTemperature,\n    );\n  }\n\n  const fromTopP = common.getValueByPath(fromObject, ['topP']);\n  if (parentObject !== undefined && fromTopP != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'generationConfig', 'topP'],\n      fromTopP,\n    );\n  }\n\n  const fromTopK = common.getValueByPath(fromObject, ['topK']);\n  if (parentObject !== undefined && fromTopK != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'generationConfig', 'topK'],\n      fromTopK,\n    );\n  }\n\n  const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n    'maxOutputTokens',\n  ]);\n  if (parentObject !== undefined && fromMaxOutputTokens != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'generationConfig', 'maxOutputTokens'],\n      fromMaxOutputTokens,\n    );\n  }\n\n  const fromMediaResolution = common.getValueByPath(fromObject, [\n    'mediaResolution',\n  ]);\n  if (parentObject !== undefined && fromMediaResolution != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'generationConfig', 'mediaResolution'],\n      fromMediaResolution,\n    );\n  }\n\n  const fromSeed = common.getValueByPath(fromObject, ['seed']);\n  if (parentObject !== undefined && fromSeed != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'generationConfig', 'seed'],\n      fromSeed,\n    );\n  }\n\n  const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n  if (parentObject !== undefined && fromSpeechConfig != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'generationConfig', 'speechConfig'],\n      t.tLiveSpeechConfig(fromSpeechConfig),\n    );\n  }\n\n  const fromThinkingConfig = common.getValueByPath(fromObject, [\n    'thinkingConfig',\n  ]);\n  if (parentObject !== undefined && fromThinkingConfig != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'generationConfig', 'thinkingConfig'],\n      fromThinkingConfig,\n    );\n  }\n\n  const fromEnableAffectiveDialog = common.getValueByPath(fromObject, [\n    'enableAffectiveDialog',\n  ]);\n  if (parentObject !== undefined && fromEnableAffectiveDialog != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'generationConfig', 'enableAffectiveDialog'],\n      fromEnableAffectiveDialog,\n    );\n  }\n\n  const fromSystemInstruction = common.getValueByPath(fromObject, [\n    'systemInstruction',\n  ]);\n  if (parentObject !== undefined && fromSystemInstruction != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'systemInstruction'],\n      contentToMldev(t.tContent(fromSystemInstruction)),\n    );\n  }\n\n  const fromTools = common.getValueByPath(fromObject, ['tools']);\n  if (parentObject !== undefined && fromTools != null) {\n    let transformedList = t.tTools(fromTools);\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return toolToMldev(t.tTool(item));\n      });\n    }\n    common.setValueByPath(parentObject, ['setup', 'tools'], transformedList);\n  }\n\n  const fromSessionResumption = common.getValueByPath(fromObject, [\n    'sessionResumption',\n  ]);\n  if (parentObject !== undefined && fromSessionResumption != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'sessionResumption'],\n      sessionResumptionConfigToMldev(fromSessionResumption),\n    );\n  }\n\n  const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n    'inputAudioTranscription',\n  ]);\n  if (parentObject !== undefined && fromInputAudioTranscription != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'inputAudioTranscription'],\n      fromInputAudioTranscription,\n    );\n  }\n\n  const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n    'outputAudioTranscription',\n  ]);\n  if (parentObject !== undefined && fromOutputAudioTranscription != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'outputAudioTranscription'],\n      fromOutputAudioTranscription,\n    );\n  }\n\n  const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n    'realtimeInputConfig',\n  ]);\n  if (parentObject !== undefined && fromRealtimeInputConfig != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'realtimeInputConfig'],\n      fromRealtimeInputConfig,\n    );\n  }\n\n  const fromContextWindowCompression = common.getValueByPath(fromObject, [\n    'contextWindowCompression',\n  ]);\n  if (parentObject !== undefined && fromContextWindowCompression != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'contextWindowCompression'],\n      fromContextWindowCompression,\n    );\n  }\n\n  const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n  if (parentObject !== undefined && fromProactivity != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'proactivity'],\n      fromProactivity,\n    );\n  }\n\n  if (common.getValueByPath(fromObject, ['explicitVadSignal']) !== undefined) {\n    throw new Error(\n      'explicitVadSignal parameter is not supported in Gemini API.',\n    );\n  }\n\n  return toObject;\n}\n\nexport function liveConnectConfigToVertex(\n  fromObject: types.LiveConnectConfig,\n  parentObject: Record<string, unknown>,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromGenerationConfig = common.getValueByPath(fromObject, [\n    'generationConfig',\n  ]);\n  if (parentObject !== undefined && fromGenerationConfig != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'generationConfig'],\n      generationConfigToVertex(fromGenerationConfig),\n    );\n  }\n\n  const fromResponseModalities = common.getValueByPath(fromObject, [\n    'responseModalities',\n  ]);\n  if (parentObject !== undefined && fromResponseModalities != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'generationConfig', 'responseModalities'],\n      fromResponseModalities,\n    );\n  }\n\n  const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n  if (parentObject !== undefined && fromTemperature != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'generationConfig', 'temperature'],\n      fromTemperature,\n    );\n  }\n\n  const fromTopP = common.getValueByPath(fromObject, ['topP']);\n  if (parentObject !== undefined && fromTopP != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'generationConfig', 'topP'],\n      fromTopP,\n    );\n  }\n\n  const fromTopK = common.getValueByPath(fromObject, ['topK']);\n  if (parentObject !== undefined && fromTopK != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'generationConfig', 'topK'],\n      fromTopK,\n    );\n  }\n\n  const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n    'maxOutputTokens',\n  ]);\n  if (parentObject !== undefined && fromMaxOutputTokens != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'generationConfig', 'maxOutputTokens'],\n      fromMaxOutputTokens,\n    );\n  }\n\n  const fromMediaResolution = common.getValueByPath(fromObject, [\n    'mediaResolution',\n  ]);\n  if (parentObject !== undefined && fromMediaResolution != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'generationConfig', 'mediaResolution'],\n      fromMediaResolution,\n    );\n  }\n\n  const fromSeed = common.getValueByPath(fromObject, ['seed']);\n  if (parentObject !== undefined && fromSeed != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'generationConfig', 'seed'],\n      fromSeed,\n    );\n  }\n\n  const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n  if (parentObject !== undefined && fromSpeechConfig != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'generationConfig', 'speechConfig'],\n      speechConfigToVertex(t.tLiveSpeechConfig(fromSpeechConfig)),\n    );\n  }\n\n  const fromThinkingConfig = common.getValueByPath(fromObject, [\n    'thinkingConfig',\n  ]);\n  if (parentObject !== undefined && fromThinkingConfig != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'generationConfig', 'thinkingConfig'],\n      fromThinkingConfig,\n    );\n  }\n\n  const fromEnableAffectiveDialog = common.getValueByPath(fromObject, [\n    'enableAffectiveDialog',\n  ]);\n  if (parentObject !== undefined && fromEnableAffectiveDialog != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'generationConfig', 'enableAffectiveDialog'],\n      fromEnableAffectiveDialog,\n    );\n  }\n\n  const fromSystemInstruction = common.getValueByPath(fromObject, [\n    'systemInstruction',\n  ]);\n  if (parentObject !== undefined && fromSystemInstruction != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'systemInstruction'],\n      t.tContent(fromSystemInstruction),\n    );\n  }\n\n  const fromTools = common.getValueByPath(fromObject, ['tools']);\n  if (parentObject !== undefined && fromTools != null) {\n    let transformedList = t.tTools(fromTools);\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return toolToVertex(t.tTool(item));\n      });\n    }\n    common.setValueByPath(parentObject, ['setup', 'tools'], transformedList);\n  }\n\n  const fromSessionResumption = common.getValueByPath(fromObject, [\n    'sessionResumption',\n  ]);\n  if (parentObject !== undefined && fromSessionResumption != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'sessionResumption'],\n      fromSessionResumption,\n    );\n  }\n\n  const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n    'inputAudioTranscription',\n  ]);\n  if (parentObject !== undefined && fromInputAudioTranscription != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'inputAudioTranscription'],\n      fromInputAudioTranscription,\n    );\n  }\n\n  const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n    'outputAudioTranscription',\n  ]);\n  if (parentObject !== undefined && fromOutputAudioTranscription != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'outputAudioTranscription'],\n      fromOutputAudioTranscription,\n    );\n  }\n\n  const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n    'realtimeInputConfig',\n  ]);\n  if (parentObject !== undefined && fromRealtimeInputConfig != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'realtimeInputConfig'],\n      fromRealtimeInputConfig,\n    );\n  }\n\n  const fromContextWindowCompression = common.getValueByPath(fromObject, [\n    'contextWindowCompression',\n  ]);\n  if (parentObject !== undefined && fromContextWindowCompression != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'contextWindowCompression'],\n      fromContextWindowCompression,\n    );\n  }\n\n  const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n  if (parentObject !== undefined && fromProactivity != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'proactivity'],\n      fromProactivity,\n    );\n  }\n\n  const fromExplicitVadSignal = common.getValueByPath(fromObject, [\n    'explicitVadSignal',\n  ]);\n  if (parentObject !== undefined && fromExplicitVadSignal != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'explicitVadSignal'],\n      fromExplicitVadSignal,\n    );\n  }\n\n  return toObject;\n}\n\nexport function liveConnectParametersToMldev(\n  apiClient: ApiClient,\n  fromObject: types.LiveConnectParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromModel = common.getValueByPath(fromObject, ['model']);\n  if (fromModel != null) {\n    common.setValueByPath(\n      toObject,\n      ['setup', 'model'],\n      t.tModel(apiClient, fromModel),\n    );\n  }\n\n  const fromConfig = common.getValueByPath(fromObject, ['config']);\n  if (fromConfig != null) {\n    common.setValueByPath(\n      toObject,\n      ['config'],\n      liveConnectConfigToMldev(fromConfig, toObject),\n    );\n  }\n\n  return toObject;\n}\n\nexport function liveConnectParametersToVertex(\n  apiClient: ApiClient,\n  fromObject: types.LiveConnectParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromModel = common.getValueByPath(fromObject, ['model']);\n  if (fromModel != null) {\n    common.setValueByPath(\n      toObject,\n      ['setup', 'model'],\n      t.tModel(apiClient, fromModel),\n    );\n  }\n\n  const fromConfig = common.getValueByPath(fromObject, ['config']);\n  if (fromConfig != null) {\n    common.setValueByPath(\n      toObject,\n      ['config'],\n      liveConnectConfigToVertex(fromConfig, toObject),\n    );\n  }\n\n  return toObject;\n}\n\nexport function liveMusicClientMessageToVertex(\n  fromObject: types.LiveMusicClientMessage,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  if (common.getValueByPath(fromObject, ['setup']) !== undefined) {\n    throw new Error('setup parameter is not supported in Vertex AI.');\n  }\n\n  if (common.getValueByPath(fromObject, ['clientContent']) !== undefined) {\n    throw new Error('clientContent parameter is not supported in Vertex AI.');\n  }\n\n  if (\n    common.getValueByPath(fromObject, ['musicGenerationConfig']) !== undefined\n  ) {\n    throw new Error(\n      'musicGenerationConfig parameter is not supported in Vertex AI.',\n    );\n  }\n\n  if (common.getValueByPath(fromObject, ['playbackControl']) !== undefined) {\n    throw new Error('playbackControl parameter is not supported in Vertex AI.');\n  }\n\n  return toObject;\n}\n\nexport function liveMusicConnectParametersToMldev(\n  fromObject: types.LiveMusicConnectParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromModel = common.getValueByPath(fromObject, ['model']);\n  if (fromModel != null) {\n    common.setValueByPath(toObject, ['setup', 'model'], fromModel);\n  }\n\n  const fromCallbacks = common.getValueByPath(fromObject, ['callbacks']);\n  if (fromCallbacks != null) {\n    common.setValueByPath(toObject, ['callbacks'], fromCallbacks);\n  }\n\n  return toObject;\n}\n\nexport function liveMusicConnectParametersToVertex(\n  fromObject: types.LiveMusicConnectParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  if (common.getValueByPath(fromObject, ['model']) !== undefined) {\n    throw new Error('model parameter is not supported in Vertex AI.');\n  }\n\n  if (common.getValueByPath(fromObject, ['callbacks']) !== undefined) {\n    throw new Error('callbacks parameter is not supported in Vertex AI.');\n  }\n\n  return toObject;\n}\n\nexport function liveMusicSetConfigParametersToMldev(\n  fromObject: types.LiveMusicSetConfigParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromMusicGenerationConfig = common.getValueByPath(fromObject, [\n    'musicGenerationConfig',\n  ]);\n  if (fromMusicGenerationConfig != null) {\n    common.setValueByPath(\n      toObject,\n      ['musicGenerationConfig'],\n      fromMusicGenerationConfig,\n    );\n  }\n\n  return toObject;\n}\n\nexport function liveMusicSetConfigParametersToVertex(\n  fromObject: types.LiveMusicSetConfigParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  if (\n    common.getValueByPath(fromObject, ['musicGenerationConfig']) !== undefined\n  ) {\n    throw new Error(\n      'musicGenerationConfig parameter is not supported in Vertex AI.',\n    );\n  }\n\n  return toObject;\n}\n\nexport function liveMusicSetWeightedPromptsParametersToMldev(\n  fromObject: types.LiveMusicSetWeightedPromptsParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromWeightedPrompts = common.getValueByPath(fromObject, [\n    'weightedPrompts',\n  ]);\n  if (fromWeightedPrompts != null) {\n    let transformedList = fromWeightedPrompts;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return item;\n      });\n    }\n    common.setValueByPath(toObject, ['weightedPrompts'], transformedList);\n  }\n\n  return toObject;\n}\n\nexport function liveMusicSetWeightedPromptsParametersToVertex(\n  fromObject: types.LiveMusicSetWeightedPromptsParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  if (common.getValueByPath(fromObject, ['weightedPrompts']) !== undefined) {\n    throw new Error('weightedPrompts parameter is not supported in Vertex AI.');\n  }\n\n  return toObject;\n}\n\nexport function liveSendRealtimeInputParametersToMldev(\n  fromObject: types.LiveSendRealtimeInputParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromMedia = common.getValueByPath(fromObject, ['media']);\n  if (fromMedia != null) {\n    let transformedList = t.tBlobs(fromMedia);\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return blobToMldev(item);\n      });\n    }\n    common.setValueByPath(toObject, ['mediaChunks'], transformedList);\n  }\n\n  const fromAudio = common.getValueByPath(fromObject, ['audio']);\n  if (fromAudio != null) {\n    common.setValueByPath(\n      toObject,\n      ['audio'],\n      blobToMldev(t.tAudioBlob(fromAudio)),\n    );\n  }\n\n  const fromAudioStreamEnd = common.getValueByPath(fromObject, [\n    'audioStreamEnd',\n  ]);\n  if (fromAudioStreamEnd != null) {\n    common.setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd);\n  }\n\n  const fromVideo = common.getValueByPath(fromObject, ['video']);\n  if (fromVideo != null) {\n    common.setValueByPath(\n      toObject,\n      ['video'],\n      blobToMldev(t.tImageBlob(fromVideo)),\n    );\n  }\n\n  const fromText = common.getValueByPath(fromObject, ['text']);\n  if (fromText != null) {\n    common.setValueByPath(toObject, ['text'], fromText);\n  }\n\n  const fromActivityStart = common.getValueByPath(fromObject, [\n    'activityStart',\n  ]);\n  if (fromActivityStart != null) {\n    common.setValueByPath(toObject, ['activityStart'], fromActivityStart);\n  }\n\n  const fromActivityEnd = common.getValueByPath(fromObject, ['activityEnd']);\n  if (fromActivityEnd != null) {\n    common.setValueByPath(toObject, ['activityEnd'], fromActivityEnd);\n  }\n\n  return toObject;\n}\n\nexport function liveSendRealtimeInputParametersToVertex(\n  fromObject: types.LiveSendRealtimeInputParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromMedia = common.getValueByPath(fromObject, ['media']);\n  if (fromMedia != null) {\n    let transformedList = t.tBlobs(fromMedia);\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return item;\n      });\n    }\n    common.setValueByPath(toObject, ['mediaChunks'], transformedList);\n  }\n\n  const fromAudio = common.getValueByPath(fromObject, ['audio']);\n  if (fromAudio != null) {\n    common.setValueByPath(toObject, ['audio'], t.tAudioBlob(fromAudio));\n  }\n\n  const fromAudioStreamEnd = common.getValueByPath(fromObject, [\n    'audioStreamEnd',\n  ]);\n  if (fromAudioStreamEnd != null) {\n    common.setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd);\n  }\n\n  const fromVideo = common.getValueByPath(fromObject, ['video']);\n  if (fromVideo != null) {\n    common.setValueByPath(toObject, ['video'], t.tImageBlob(fromVideo));\n  }\n\n  const fromText = common.getValueByPath(fromObject, ['text']);\n  if (fromText != null) {\n    common.setValueByPath(toObject, ['text'], fromText);\n  }\n\n  const fromActivityStart = common.getValueByPath(fromObject, [\n    'activityStart',\n  ]);\n  if (fromActivityStart != null) {\n    common.setValueByPath(toObject, ['activityStart'], fromActivityStart);\n  }\n\n  const fromActivityEnd = common.getValueByPath(fromObject, ['activityEnd']);\n  if (fromActivityEnd != null) {\n    common.setValueByPath(toObject, ['activityEnd'], fromActivityEnd);\n  }\n\n  return toObject;\n}\n\nexport function liveServerMessageFromVertex(\n  fromObject: types.LiveServerMessage,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromSetupComplete = common.getValueByPath(fromObject, [\n    'setupComplete',\n  ]);\n  if (fromSetupComplete != null) {\n    common.setValueByPath(toObject, ['setupComplete'], fromSetupComplete);\n  }\n\n  const fromServerContent = common.getValueByPath(fromObject, [\n    'serverContent',\n  ]);\n  if (fromServerContent != null) {\n    common.setValueByPath(toObject, ['serverContent'], fromServerContent);\n  }\n\n  const fromToolCall = common.getValueByPath(fromObject, ['toolCall']);\n  if (fromToolCall != null) {\n    common.setValueByPath(toObject, ['toolCall'], fromToolCall);\n  }\n\n  const fromToolCallCancellation = common.getValueByPath(fromObject, [\n    'toolCallCancellation',\n  ]);\n  if (fromToolCallCancellation != null) {\n    common.setValueByPath(\n      toObject,\n      ['toolCallCancellation'],\n      fromToolCallCancellation,\n    );\n  }\n\n  const fromUsageMetadata = common.getValueByPath(fromObject, [\n    'usageMetadata',\n  ]);\n  if (fromUsageMetadata != null) {\n    common.setValueByPath(\n      toObject,\n      ['usageMetadata'],\n      usageMetadataFromVertex(fromUsageMetadata),\n    );\n  }\n\n  const fromGoAway = common.getValueByPath(fromObject, ['goAway']);\n  if (fromGoAway != null) {\n    common.setValueByPath(toObject, ['goAway'], fromGoAway);\n  }\n\n  const fromSessionResumptionUpdate = common.getValueByPath(fromObject, [\n    'sessionResumptionUpdate',\n  ]);\n  if (fromSessionResumptionUpdate != null) {\n    common.setValueByPath(\n      toObject,\n      ['sessionResumptionUpdate'],\n      fromSessionResumptionUpdate,\n    );\n  }\n\n  const fromVoiceActivityDetectionSignal = common.getValueByPath(fromObject, [\n    'voiceActivityDetectionSignal',\n  ]);\n  if (fromVoiceActivityDetectionSignal != null) {\n    common.setValueByPath(\n      toObject,\n      ['voiceActivityDetectionSignal'],\n      fromVoiceActivityDetectionSignal,\n    );\n  }\n\n  return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromMediaResolution = common.getValueByPath(fromObject, [\n    'mediaResolution',\n  ]);\n  if (fromMediaResolution != null) {\n    common.setValueByPath(toObject, ['mediaResolution'], fromMediaResolution);\n  }\n\n  const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n    'codeExecutionResult',\n  ]);\n  if (fromCodeExecutionResult != null) {\n    common.setValueByPath(\n      toObject,\n      ['codeExecutionResult'],\n      fromCodeExecutionResult,\n    );\n  }\n\n  const fromExecutableCode = common.getValueByPath(fromObject, [\n    'executableCode',\n  ]);\n  if (fromExecutableCode != null) {\n    common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n  }\n\n  const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n  if (fromFileData != null) {\n    common.setValueByPath(\n      toObject,\n      ['fileData'],\n      fileDataToMldev(fromFileData),\n    );\n  }\n\n  const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n  if (fromFunctionCall != null) {\n    common.setValueByPath(\n      toObject,\n      ['functionCall'],\n      functionCallToMldev(fromFunctionCall),\n    );\n  }\n\n  const fromFunctionResponse = common.getValueByPath(fromObject, [\n    'functionResponse',\n  ]);\n  if (fromFunctionResponse != null) {\n    common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n  }\n\n  const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n  if (fromInlineData != null) {\n    common.setValueByPath(\n      toObject,\n      ['inlineData'],\n      blobToMldev(fromInlineData),\n    );\n  }\n\n  const fromText = common.getValueByPath(fromObject, ['text']);\n  if (fromText != null) {\n    common.setValueByPath(toObject, ['text'], fromText);\n  }\n\n  const fromThought = common.getValueByPath(fromObject, ['thought']);\n  if (fromThought != null) {\n    common.setValueByPath(toObject, ['thought'], fromThought);\n  }\n\n  const fromThoughtSignature = common.getValueByPath(fromObject, [\n    'thoughtSignature',\n  ]);\n  if (fromThoughtSignature != null) {\n    common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n  }\n\n  const fromVideoMetadata = common.getValueByPath(fromObject, [\n    'videoMetadata',\n  ]);\n  if (fromVideoMetadata != null) {\n    common.setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata);\n  }\n\n  return toObject;\n}\n\nexport function sessionResumptionConfigToMldev(\n  fromObject: types.SessionResumptionConfig,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromHandle = common.getValueByPath(fromObject, ['handle']);\n  if (fromHandle != null) {\n    common.setValueByPath(toObject, ['handle'], fromHandle);\n  }\n\n  if (common.getValueByPath(fromObject, ['transparent']) !== undefined) {\n    throw new Error('transparent parameter is not supported in Gemini API.');\n  }\n\n  return toObject;\n}\n\nexport function speechConfigToVertex(\n  fromObject: types.SpeechConfig,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n  if (fromVoiceConfig != null) {\n    common.setValueByPath(toObject, ['voiceConfig'], fromVoiceConfig);\n  }\n\n  const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n  if (fromLanguageCode != null) {\n    common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n  }\n\n  if (\n    common.getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined\n  ) {\n    throw new Error(\n      'multiSpeakerVoiceConfig parameter is not supported in Vertex AI.',\n    );\n  }\n\n  return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n    'functionDeclarations',\n  ]);\n  if (fromFunctionDeclarations != null) {\n    let transformedList = fromFunctionDeclarations;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return item;\n      });\n    }\n    common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n  }\n\n  if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n    throw new Error('retrieval parameter is not supported in Gemini API.');\n  }\n\n  const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n    'googleSearchRetrieval',\n  ]);\n  if (fromGoogleSearchRetrieval != null) {\n    common.setValueByPath(\n      toObject,\n      ['googleSearchRetrieval'],\n      fromGoogleSearchRetrieval,\n    );\n  }\n\n  const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n  if (fromComputerUse != null) {\n    common.setValueByPath(toObject, ['computerUse'], fromComputerUse);\n  }\n\n  const fromFileSearch = common.getValueByPath(fromObject, ['fileSearch']);\n  if (fromFileSearch != null) {\n    common.setValueByPath(toObject, ['fileSearch'], fromFileSearch);\n  }\n\n  const fromCodeExecution = common.getValueByPath(fromObject, [\n    'codeExecution',\n  ]);\n  if (fromCodeExecution != null) {\n    common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n  }\n\n  if (\n    common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n  ) {\n    throw new Error(\n      'enterpriseWebSearch parameter is not supported in Gemini API.',\n    );\n  }\n\n  const fromGoogleMaps = common.getValueByPath(fromObject, ['googleMaps']);\n  if (fromGoogleMaps != null) {\n    common.setValueByPath(\n      toObject,\n      ['googleMaps'],\n      googleMapsToMldev(fromGoogleMaps),\n    );\n  }\n\n  const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n  if (fromGoogleSearch != null) {\n    common.setValueByPath(\n      toObject,\n      ['googleSearch'],\n      googleSearchToMldev(fromGoogleSearch),\n    );\n  }\n\n  const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n  if (fromUrlContext != null) {\n    common.setValueByPath(toObject, ['urlContext'], fromUrlContext);\n  }\n\n  return toObject;\n}\n\nexport function toolToVertex(fromObject: types.Tool): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n    'functionDeclarations',\n  ]);\n  if (fromFunctionDeclarations != null) {\n    let transformedList = fromFunctionDeclarations;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return functionDeclarationToVertex(item);\n      });\n    }\n    common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n  }\n\n  const fromRetrieval = common.getValueByPath(fromObject, ['retrieval']);\n  if (fromRetrieval != null) {\n    common.setValueByPath(toObject, ['retrieval'], fromRetrieval);\n  }\n\n  const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n    'googleSearchRetrieval',\n  ]);\n  if (fromGoogleSearchRetrieval != null) {\n    common.setValueByPath(\n      toObject,\n      ['googleSearchRetrieval'],\n      fromGoogleSearchRetrieval,\n    );\n  }\n\n  const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n  if (fromComputerUse != null) {\n    common.setValueByPath(toObject, ['computerUse'], fromComputerUse);\n  }\n\n  if (common.getValueByPath(fromObject, ['fileSearch']) !== undefined) {\n    throw new Error('fileSearch parameter is not supported in Vertex AI.');\n  }\n\n  const fromCodeExecution = common.getValueByPath(fromObject, [\n    'codeExecution',\n  ]);\n  if (fromCodeExecution != null) {\n    common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n  }\n\n  const fromEnterpriseWebSearch = common.getValueByPath(fromObject, [\n    'enterpriseWebSearch',\n  ]);\n  if (fromEnterpriseWebSearch != null) {\n    common.setValueByPath(\n      toObject,\n      ['enterpriseWebSearch'],\n      fromEnterpriseWebSearch,\n    );\n  }\n\n  const fromGoogleMaps = common.getValueByPath(fromObject, ['googleMaps']);\n  if (fromGoogleMaps != null) {\n    common.setValueByPath(toObject, ['googleMaps'], fromGoogleMaps);\n  }\n\n  const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n  if (fromGoogleSearch != null) {\n    common.setValueByPath(toObject, ['googleSearch'], fromGoogleSearch);\n  }\n\n  const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n  if (fromUrlContext != null) {\n    common.setValueByPath(toObject, ['urlContext'], fromUrlContext);\n  }\n\n  return toObject;\n}\n\nexport function usageMetadataFromVertex(\n  fromObject: types.UsageMetadata,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromPromptTokenCount = common.getValueByPath(fromObject, [\n    'promptTokenCount',\n  ]);\n  if (fromPromptTokenCount != null) {\n    common.setValueByPath(toObject, ['promptTokenCount'], fromPromptTokenCount);\n  }\n\n  const fromCachedContentTokenCount = common.getValueByPath(fromObject, [\n    'cachedContentTokenCount',\n  ]);\n  if (fromCachedContentTokenCount != null) {\n    common.setValueByPath(\n      toObject,\n      ['cachedContentTokenCount'],\n      fromCachedContentTokenCount,\n    );\n  }\n\n  const fromResponseTokenCount = common.getValueByPath(fromObject, [\n    'candidatesTokenCount',\n  ]);\n  if (fromResponseTokenCount != null) {\n    common.setValueByPath(\n      toObject,\n      ['responseTokenCount'],\n      fromResponseTokenCount,\n    );\n  }\n\n  const fromToolUsePromptTokenCount = common.getValueByPath(fromObject, [\n    'toolUsePromptTokenCount',\n  ]);\n  if (fromToolUsePromptTokenCount != null) {\n    common.setValueByPath(\n      toObject,\n      ['toolUsePromptTokenCount'],\n      fromToolUsePromptTokenCount,\n    );\n  }\n\n  const fromThoughtsTokenCount = common.getValueByPath(fromObject, [\n    'thoughtsTokenCount',\n  ]);\n  if (fromThoughtsTokenCount != null) {\n    common.setValueByPath(\n      toObject,\n      ['thoughtsTokenCount'],\n      fromThoughtsTokenCount,\n    );\n  }\n\n  const fromTotalTokenCount = common.getValueByPath(fromObject, [\n    'totalTokenCount',\n  ]);\n  if (fromTotalTokenCount != null) {\n    common.setValueByPath(toObject, ['totalTokenCount'], fromTotalTokenCount);\n  }\n\n  const fromPromptTokensDetails = common.getValueByPath(fromObject, [\n    'promptTokensDetails',\n  ]);\n  if (fromPromptTokensDetails != null) {\n    let transformedList = fromPromptTokensDetails;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return item;\n      });\n    }\n    common.setValueByPath(toObject, ['promptTokensDetails'], transformedList);\n  }\n\n  const fromCacheTokensDetails = common.getValueByPath(fromObject, [\n    'cacheTokensDetails',\n  ]);\n  if (fromCacheTokensDetails != null) {\n    let transformedList = fromCacheTokensDetails;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return item;\n      });\n    }\n    common.setValueByPath(toObject, ['cacheTokensDetails'], transformedList);\n  }\n\n  const fromResponseTokensDetails = common.getValueByPath(fromObject, [\n    'candidatesTokensDetails',\n  ]);\n  if (fromResponseTokensDetails != null) {\n    let transformedList = fromResponseTokensDetails;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return item;\n      });\n    }\n    common.setValueByPath(toObject, ['responseTokensDetails'], transformedList);\n  }\n\n  const fromToolUsePromptTokensDetails = common.getValueByPath(fromObject, [\n    'toolUsePromptTokensDetails',\n  ]);\n  if (fromToolUsePromptTokensDetails != null) {\n    let transformedList = fromToolUsePromptTokensDetails;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return item;\n      });\n    }\n    common.setValueByPath(\n      toObject,\n      ['toolUsePromptTokensDetails'],\n      transformedList,\n    );\n  }\n\n  const fromTrafficType = common.getValueByPath(fromObject, ['trafficType']);\n  if (fromTrafficType != null) {\n    common.setValueByPath(toObject, ['trafficType'], fromTrafficType);\n  }\n\n  return toObject;\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport type * as _internal_types from '../_internal_types.js';\nimport * as t from '../_transformers.js';\nimport type * as types from '../types.js';\n\nexport function blobToMldev(fromObject: types.Blob): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromData = common.getValueByPath(fromObject, ['data']);\n  if (fromData != null) {\n    common.setValueByPath(toObject, ['data'], fromData);\n  }\n\n  if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n    throw new Error('displayName parameter is not supported in Gemini API.');\n  }\n\n  const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n  if (fromMimeType != null) {\n    common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n  }\n\n  return toObject;\n}\n\nexport function candidateFromMldev(\n  fromObject: types.Candidate,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromContent = common.getValueByPath(fromObject, ['content']);\n  if (fromContent != null) {\n    common.setValueByPath(toObject, ['content'], fromContent);\n  }\n\n  const fromCitationMetadata = common.getValueByPath(fromObject, [\n    'citationMetadata',\n  ]);\n  if (fromCitationMetadata != null) {\n    common.setValueByPath(\n      toObject,\n      ['citationMetadata'],\n      citationMetadataFromMldev(fromCitationMetadata),\n    );\n  }\n\n  const fromTokenCount = common.getValueByPath(fromObject, ['tokenCount']);\n  if (fromTokenCount != null) {\n    common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n  }\n\n  const fromFinishReason = common.getValueByPath(fromObject, ['finishReason']);\n  if (fromFinishReason != null) {\n    common.setValueByPath(toObject, ['finishReason'], fromFinishReason);\n  }\n\n  const fromAvgLogprobs = common.getValueByPath(fromObject, ['avgLogprobs']);\n  if (fromAvgLogprobs != null) {\n    common.setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs);\n  }\n\n  const fromGroundingMetadata = common.getValueByPath(fromObject, [\n    'groundingMetadata',\n  ]);\n  if (fromGroundingMetadata != null) {\n    common.setValueByPath(\n      toObject,\n      ['groundingMetadata'],\n      fromGroundingMetadata,\n    );\n  }\n\n  const fromIndex = common.getValueByPath(fromObject, ['index']);\n  if (fromIndex != null) {\n    common.setValueByPath(toObject, ['index'], fromIndex);\n  }\n\n  const fromLogprobsResult = common.getValueByPath(fromObject, [\n    'logprobsResult',\n  ]);\n  if (fromLogprobsResult != null) {\n    common.setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult);\n  }\n\n  const fromSafetyRatings = common.getValueByPath(fromObject, [\n    'safetyRatings',\n  ]);\n  if (fromSafetyRatings != null) {\n    let transformedList = fromSafetyRatings;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return item;\n      });\n    }\n    common.setValueByPath(toObject, ['safetyRatings'], transformedList);\n  }\n\n  const fromUrlContextMetadata = common.getValueByPath(fromObject, [\n    'urlContextMetadata',\n  ]);\n  if (fromUrlContextMetadata != null) {\n    common.setValueByPath(\n      toObject,\n      ['urlContextMetadata'],\n      fromUrlContextMetadata,\n    );\n  }\n\n  return toObject;\n}\n\nexport function citationMetadataFromMldev(\n  fromObject: types.CitationMetadata,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromCitations = common.getValueByPath(fromObject, ['citationSources']);\n  if (fromCitations != null) {\n    let transformedList = fromCitations;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return item;\n      });\n    }\n    common.setValueByPath(toObject, ['citations'], transformedList);\n  }\n\n  return toObject;\n}\n\nexport function computeTokensParametersToVertex(\n  apiClient: ApiClient,\n  fromObject: types.ComputeTokensParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromModel = common.getValueByPath(fromObject, ['model']);\n  if (fromModel != null) {\n    common.setValueByPath(\n      toObject,\n      ['_url', 'model'],\n      t.tModel(apiClient, fromModel),\n    );\n  }\n\n  const fromContents = common.getValueByPath(fromObject, ['contents']);\n  if (fromContents != null) {\n    let transformedList = t.tContents(fromContents);\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return item;\n      });\n    }\n    common.setValueByPath(toObject, ['contents'], transformedList);\n  }\n\n  return toObject;\n}\n\nexport function computeTokensResponseFromVertex(\n  fromObject: types.ComputeTokensResponse,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n    'sdkHttpResponse',\n  ]);\n  if (fromSdkHttpResponse != null) {\n    common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n  }\n\n  const fromTokensInfo = common.getValueByPath(fromObject, ['tokensInfo']);\n  if (fromTokensInfo != null) {\n    let transformedList = fromTokensInfo;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return item;\n      });\n    }\n    common.setValueByPath(toObject, ['tokensInfo'], transformedList);\n  }\n\n  return toObject;\n}\n\nexport function contentEmbeddingFromVertex(\n  fromObject: types.ContentEmbedding,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromValues = common.getValueByPath(fromObject, ['values']);\n  if (fromValues != null) {\n    common.setValueByPath(toObject, ['values'], fromValues);\n  }\n\n  const fromStatistics = common.getValueByPath(fromObject, ['statistics']);\n  if (fromStatistics != null) {\n    common.setValueByPath(\n      toObject,\n      ['statistics'],\n      contentEmbeddingStatisticsFromVertex(fromStatistics),\n    );\n  }\n\n  return toObject;\n}\n\nexport function contentEmbeddingStatisticsFromVertex(\n  fromObject: types.ContentEmbeddingStatistics,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromTruncated = common.getValueByPath(fromObject, ['truncated']);\n  if (fromTruncated != null) {\n    common.setValueByPath(toObject, ['truncated'], fromTruncated);\n  }\n\n  const fromTokenCount = common.getValueByPath(fromObject, ['token_count']);\n  if (fromTokenCount != null) {\n    common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n  }\n\n  return toObject;\n}\n\nexport function contentToMldev(\n  fromObject: types.Content,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromParts = common.getValueByPath(fromObject, ['parts']);\n  if (fromParts != null) {\n    let transformedList = fromParts;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return partToMldev(item);\n      });\n    }\n    common.setValueByPath(toObject, ['parts'], transformedList);\n  }\n\n  const fromRole = common.getValueByPath(fromObject, ['role']);\n  if (fromRole != null) {\n    common.setValueByPath(toObject, ['role'], fromRole);\n  }\n\n  return toObject;\n}\n\nexport function controlReferenceConfigToVertex(\n  fromObject: types.ControlReferenceConfig,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromControlType = common.getValueByPath(fromObject, ['controlType']);\n  if (fromControlType != null) {\n    common.setValueByPath(toObject, ['controlType'], fromControlType);\n  }\n\n  const fromEnableControlImageComputation = common.getValueByPath(fromObject, [\n    'enableControlImageComputation',\n  ]);\n  if (fromEnableControlImageComputation != null) {\n    common.setValueByPath(\n      toObject,\n      ['computeControl'],\n      fromEnableControlImageComputation,\n    );\n  }\n\n  return toObject;\n}\n\nexport function countTokensConfigToMldev(\n  fromObject: types.CountTokensConfig,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  if (common.getValueByPath(fromObject, ['systemInstruction']) !== undefined) {\n    throw new Error(\n      'systemInstruction parameter is not supported in Gemini API.',\n    );\n  }\n\n  if (common.getValueByPath(fromObject, ['tools']) !== undefined) {\n    throw new Error('tools parameter is not supported in Gemini API.');\n  }\n\n  if (common.getValueByPath(fromObject, ['generationConfig']) !== undefined) {\n    throw new Error(\n      'generationConfig parameter is not supported in Gemini API.',\n    );\n  }\n\n  return toObject;\n}\n\nexport function countTokensConfigToVertex(\n  fromObject: types.CountTokensConfig,\n  parentObject: Record<string, unknown>,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromSystemInstruction = common.getValueByPath(fromObject, [\n    'systemInstruction',\n  ]);\n  if (parentObject !== undefined && fromSystemInstruction != null) {\n    common.setValueByPath(\n      parentObject,\n      ['systemInstruction'],\n      t.tContent(fromSystemInstruction),\n    );\n  }\n\n  const fromTools = common.getValueByPath(fromObject, ['tools']);\n  if (parentObject !== undefined && fromTools != null) {\n    let transformedList = fromTools;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return toolToVertex(item);\n      });\n    }\n    common.setValueByPath(parentObject, ['tools'], transformedList);\n  }\n\n  const fromGenerationConfig = common.getValueByPath(fromObject, [\n    'generationConfig',\n  ]);\n  if (parentObject !== undefined && fromGenerationConfig != null) {\n    common.setValueByPath(\n      parentObject,\n      ['generationConfig'],\n      generationConfigToVertex(fromGenerationConfig),\n    );\n  }\n\n  return toObject;\n}\n\nexport function countTokensParametersToMldev(\n  apiClient: ApiClient,\n  fromObject: types.CountTokensParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromModel = common.getValueByPath(fromObject, ['model']);\n  if (fromModel != null) {\n    common.setValueByPath(\n      toObject,\n      ['_url', 'model'],\n      t.tModel(apiClient, fromModel),\n    );\n  }\n\n  const fromContents = common.getValueByPath(fromObject, ['contents']);\n  if (fromContents != null) {\n    let transformedList = t.tContents(fromContents);\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return contentToMldev(item);\n      });\n    }\n    common.setValueByPath(toObject, ['contents'], transformedList);\n  }\n\n  const fromConfig = common.getValueByPath(fromObject, ['config']);\n  if (fromConfig != null) {\n    countTokensConfigToMldev(fromConfig);\n  }\n\n  return toObject;\n}\n\nexport function countTokensParametersToVertex(\n  apiClient: ApiClient,\n  fromObject: types.CountTokensParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromModel = common.getValueByPath(fromObject, ['model']);\n  if (fromModel != null) {\n    common.setValueByPath(\n      toObject,\n      ['_url', 'model'],\n      t.tModel(apiClient, fromModel),\n    );\n  }\n\n  const fromContents = common.getValueByPath(fromObject, ['contents']);\n  if (fromContents != null) {\n    let transformedList = t.tContents(fromContents);\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return item;\n      });\n    }\n    common.setValueByPath(toObject, ['contents'], transformedList);\n  }\n\n  const fromConfig = common.getValueByPath(fromObject, ['config']);\n  if (fromConfig != null) {\n    countTokensConfigToVertex(fromConfig, toObject);\n  }\n\n  return toObject;\n}\n\nexport function countTokensResponseFromMldev(\n  fromObject: types.CountTokensResponse,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n    'sdkHttpResponse',\n  ]);\n  if (fromSdkHttpResponse != null) {\n    common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n  }\n\n  const fromTotalTokens = common.getValueByPath(fromObject, ['totalTokens']);\n  if (fromTotalTokens != null) {\n    common.setValueByPath(toObject, ['totalTokens'], fromTotalTokens);\n  }\n\n  const fromCachedContentTokenCount = common.getValueByPath(fromObject, [\n    'cachedContentTokenCount',\n  ]);\n  if (fromCachedContentTokenCount != null) {\n    common.setValueByPath(\n      toObject,\n      ['cachedContentTokenCount'],\n      fromCachedContentTokenCount,\n    );\n  }\n\n  return toObject;\n}\n\nexport function countTokensResponseFromVertex(\n  fromObject: types.CountTokensResponse,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n    'sdkHttpResponse',\n  ]);\n  if (fromSdkHttpResponse != null) {\n    common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n  }\n\n  const fromTotalTokens = common.getValueByPath(fromObject, ['totalTokens']);\n  if (fromTotalTokens != null) {\n    common.setValueByPath(toObject, ['totalTokens'], fromTotalTokens);\n  }\n\n  return toObject;\n}\n\nexport function deleteModelParametersToMldev(\n  apiClient: ApiClient,\n  fromObject: types.DeleteModelParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromModel = common.getValueByPath(fromObject, ['model']);\n  if (fromModel != null) {\n    common.setValueByPath(\n      toObject,\n      ['_url', 'name'],\n      t.tModel(apiClient, fromModel),\n    );\n  }\n\n  return toObject;\n}\n\nexport function deleteModelParametersToVertex(\n  apiClient: ApiClient,\n  fromObject: types.DeleteModelParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromModel = common.getValueByPath(fromObject, ['model']);\n  if (fromModel != null) {\n    common.setValueByPath(\n      toObject,\n      ['_url', 'name'],\n      t.tModel(apiClient, fromModel),\n    );\n  }\n\n  return toObject;\n}\n\nexport function deleteModelResponseFromMldev(\n  fromObject: types.DeleteModelResponse,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n    'sdkHttpResponse',\n  ]);\n  if (fromSdkHttpResponse != null) {\n    common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n  }\n\n  return toObject;\n}\n\nexport function deleteModelResponseFromVertex(\n  fromObject: types.DeleteModelResponse,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n    'sdkHttpResponse',\n  ]);\n  if (fromSdkHttpResponse != null) {\n    common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n  }\n\n  return toObject;\n}\n\nexport function editImageConfigToVertex(\n  fromObject: types.EditImageConfig,\n  parentObject: Record<string, unknown>,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n  if (parentObject !== undefined && fromOutputGcsUri != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'storageUri'],\n      fromOutputGcsUri,\n    );\n  }\n\n  const fromNegativePrompt = common.getValueByPath(fromObject, [\n    'negativePrompt',\n  ]);\n  if (parentObject !== undefined && fromNegativePrompt != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'negativePrompt'],\n      fromNegativePrompt,\n    );\n  }\n\n  const fromNumberOfImages = common.getValueByPath(fromObject, [\n    'numberOfImages',\n  ]);\n  if (parentObject !== undefined && fromNumberOfImages != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'sampleCount'],\n      fromNumberOfImages,\n    );\n  }\n\n  const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n  if (parentObject !== undefined && fromAspectRatio != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'aspectRatio'],\n      fromAspectRatio,\n    );\n  }\n\n  const fromGuidanceScale = common.getValueByPath(fromObject, [\n    'guidanceScale',\n  ]);\n  if (parentObject !== undefined && fromGuidanceScale != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'guidanceScale'],\n      fromGuidanceScale,\n    );\n  }\n\n  const fromSeed = common.getValueByPath(fromObject, ['seed']);\n  if (parentObject !== undefined && fromSeed != null) {\n    common.setValueByPath(parentObject, ['parameters', 'seed'], fromSeed);\n  }\n\n  const fromSafetyFilterLevel = common.getValueByPath(fromObject, [\n    'safetyFilterLevel',\n  ]);\n  if (parentObject !== undefined && fromSafetyFilterLevel != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'safetySetting'],\n      fromSafetyFilterLevel,\n    );\n  }\n\n  const fromPersonGeneration = common.getValueByPath(fromObject, [\n    'personGeneration',\n  ]);\n  if (parentObject !== undefined && fromPersonGeneration != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'personGeneration'],\n      fromPersonGeneration,\n    );\n  }\n\n  const fromIncludeSafetyAttributes = common.getValueByPath(fromObject, [\n    'includeSafetyAttributes',\n  ]);\n  if (parentObject !== undefined && fromIncludeSafetyAttributes != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'includeSafetyAttributes'],\n      fromIncludeSafetyAttributes,\n    );\n  }\n\n  const fromIncludeRaiReason = common.getValueByPath(fromObject, [\n    'includeRaiReason',\n  ]);\n  if (parentObject !== undefined && fromIncludeRaiReason != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'includeRaiReason'],\n      fromIncludeRaiReason,\n    );\n  }\n\n  const fromLanguage = common.getValueByPath(fromObject, ['language']);\n  if (parentObject !== undefined && fromLanguage != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'language'],\n      fromLanguage,\n    );\n  }\n\n  const fromOutputMimeType = common.getValueByPath(fromObject, [\n    'outputMimeType',\n  ]);\n  if (parentObject !== undefined && fromOutputMimeType != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'outputOptions', 'mimeType'],\n      fromOutputMimeType,\n    );\n  }\n\n  const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n    'outputCompressionQuality',\n  ]);\n  if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'outputOptions', 'compressionQuality'],\n      fromOutputCompressionQuality,\n    );\n  }\n\n  const fromAddWatermark = common.getValueByPath(fromObject, ['addWatermark']);\n  if (parentObject !== undefined && fromAddWatermark != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'addWatermark'],\n      fromAddWatermark,\n    );\n  }\n\n  const fromLabels = common.getValueByPath(fromObject, ['labels']);\n  if (parentObject !== undefined && fromLabels != null) {\n    common.setValueByPath(parentObject, ['labels'], fromLabels);\n  }\n\n  const fromEditMode = common.getValueByPath(fromObject, ['editMode']);\n  if (parentObject !== undefined && fromEditMode != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'editMode'],\n      fromEditMode,\n    );\n  }\n\n  const fromBaseSteps = common.getValueByPath(fromObject, ['baseSteps']);\n  if (parentObject !== undefined && fromBaseSteps != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'editConfig', 'baseSteps'],\n      fromBaseSteps,\n    );\n  }\n\n  return toObject;\n}\n\nexport function editImageParametersInternalToVertex(\n  apiClient: ApiClient,\n  fromObject: _internal_types.EditImageParametersInternal,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromModel = common.getValueByPath(fromObject, ['model']);\n  if (fromModel != null) {\n    common.setValueByPath(\n      toObject,\n      ['_url', 'model'],\n      t.tModel(apiClient, fromModel),\n    );\n  }\n\n  const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n  if (fromPrompt != null) {\n    common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n  }\n\n  const fromReferenceImages = common.getValueByPath(fromObject, [\n    'referenceImages',\n  ]);\n  if (fromReferenceImages != null) {\n    let transformedList = fromReferenceImages;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return referenceImageAPIInternalToVertex(item);\n      });\n    }\n    common.setValueByPath(\n      toObject,\n      ['instances[0]', 'referenceImages'],\n      transformedList,\n    );\n  }\n\n  const fromConfig = common.getValueByPath(fromObject, ['config']);\n  if (fromConfig != null) {\n    editImageConfigToVertex(fromConfig, toObject);\n  }\n\n  return toObject;\n}\n\nexport function editImageResponseFromVertex(\n  fromObject: types.EditImageResponse,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n    'sdkHttpResponse',\n  ]);\n  if (fromSdkHttpResponse != null) {\n    common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n  }\n\n  const fromGeneratedImages = common.getValueByPath(fromObject, [\n    'predictions',\n  ]);\n  if (fromGeneratedImages != null) {\n    let transformedList = fromGeneratedImages;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return generatedImageFromVertex(item);\n      });\n    }\n    common.setValueByPath(toObject, ['generatedImages'], transformedList);\n  }\n\n  return toObject;\n}\n\nexport function embedContentConfigToMldev(\n  fromObject: types.EmbedContentConfig,\n  parentObject: Record<string, unknown>,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromTaskType = common.getValueByPath(fromObject, ['taskType']);\n  if (parentObject !== undefined && fromTaskType != null) {\n    common.setValueByPath(\n      parentObject,\n      ['requests[]', 'taskType'],\n      fromTaskType,\n    );\n  }\n\n  const fromTitle = common.getValueByPath(fromObject, ['title']);\n  if (parentObject !== undefined && fromTitle != null) {\n    common.setValueByPath(parentObject, ['requests[]', 'title'], fromTitle);\n  }\n\n  const fromOutputDimensionality = common.getValueByPath(fromObject, [\n    'outputDimensionality',\n  ]);\n  if (parentObject !== undefined && fromOutputDimensionality != null) {\n    common.setValueByPath(\n      parentObject,\n      ['requests[]', 'outputDimensionality'],\n      fromOutputDimensionality,\n    );\n  }\n\n  if (common.getValueByPath(fromObject, ['mimeType']) !== undefined) {\n    throw new Error('mimeType parameter is not supported in Gemini API.');\n  }\n\n  if (common.getValueByPath(fromObject, ['autoTruncate']) !== undefined) {\n    throw new Error('autoTruncate parameter is not supported in Gemini API.');\n  }\n\n  return toObject;\n}\n\nexport function embedContentConfigToVertex(\n  fromObject: types.EmbedContentConfig,\n  parentObject: Record<string, unknown>,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromTaskType = common.getValueByPath(fromObject, ['taskType']);\n  if (parentObject !== undefined && fromTaskType != null) {\n    common.setValueByPath(\n      parentObject,\n      ['instances[]', 'task_type'],\n      fromTaskType,\n    );\n  }\n\n  const fromTitle = common.getValueByPath(fromObject, ['title']);\n  if (parentObject !== undefined && fromTitle != null) {\n    common.setValueByPath(parentObject, ['instances[]', 'title'], fromTitle);\n  }\n\n  const fromOutputDimensionality = common.getValueByPath(fromObject, [\n    'outputDimensionality',\n  ]);\n  if (parentObject !== undefined && fromOutputDimensionality != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'outputDimensionality'],\n      fromOutputDimensionality,\n    );\n  }\n\n  const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n  if (parentObject !== undefined && fromMimeType != null) {\n    common.setValueByPath(\n      parentObject,\n      ['instances[]', 'mimeType'],\n      fromMimeType,\n    );\n  }\n\n  const fromAutoTruncate = common.getValueByPath(fromObject, ['autoTruncate']);\n  if (parentObject !== undefined && fromAutoTruncate != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'autoTruncate'],\n      fromAutoTruncate,\n    );\n  }\n\n  return toObject;\n}\n\nexport function embedContentParametersToMldev(\n  apiClient: ApiClient,\n  fromObject: types.EmbedContentParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromModel = common.getValueByPath(fromObject, ['model']);\n  if (fromModel != null) {\n    common.setValueByPath(\n      toObject,\n      ['_url', 'model'],\n      t.tModel(apiClient, fromModel),\n    );\n  }\n\n  const fromContents = common.getValueByPath(fromObject, ['contents']);\n  if (fromContents != null) {\n    let transformedList = t.tContentsForEmbed(apiClient, fromContents);\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return item;\n      });\n    }\n    common.setValueByPath(toObject, ['requests[]', 'content'], transformedList);\n  }\n\n  const fromConfig = common.getValueByPath(fromObject, ['config']);\n  if (fromConfig != null) {\n    embedContentConfigToMldev(fromConfig, toObject);\n  }\n\n  const fromModelForEmbedContent = common.getValueByPath(fromObject, ['model']);\n  if (fromModelForEmbedContent !== undefined) {\n    common.setValueByPath(\n      toObject,\n      ['requests[]', 'model'],\n      t.tModel(apiClient, fromModelForEmbedContent),\n    );\n  }\n\n  return toObject;\n}\n\nexport function embedContentParametersToVertex(\n  apiClient: ApiClient,\n  fromObject: types.EmbedContentParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromModel = common.getValueByPath(fromObject, ['model']);\n  if (fromModel != null) {\n    common.setValueByPath(\n      toObject,\n      ['_url', 'model'],\n      t.tModel(apiClient, fromModel),\n    );\n  }\n\n  const fromContents = common.getValueByPath(fromObject, ['contents']);\n  if (fromContents != null) {\n    let transformedList = t.tContentsForEmbed(apiClient, fromContents);\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return item;\n      });\n    }\n    common.setValueByPath(\n      toObject,\n      ['instances[]', 'content'],\n      transformedList,\n    );\n  }\n\n  const fromConfig = common.getValueByPath(fromObject, ['config']);\n  if (fromConfig != null) {\n    embedContentConfigToVertex(fromConfig, toObject);\n  }\n\n  return toObject;\n}\n\nexport function embedContentResponseFromMldev(\n  fromObject: types.EmbedContentResponse,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n    'sdkHttpResponse',\n  ]);\n  if (fromSdkHttpResponse != null) {\n    common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n  }\n\n  const fromEmbeddings = common.getValueByPath(fromObject, ['embeddings']);\n  if (fromEmbeddings != null) {\n    let transformedList = fromEmbeddings;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return item;\n      });\n    }\n    common.setValueByPath(toObject, ['embeddings'], transformedList);\n  }\n\n  const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n  if (fromMetadata != null) {\n    common.setValueByPath(toObject, ['metadata'], fromMetadata);\n  }\n\n  return toObject;\n}\n\nexport function embedContentResponseFromVertex(\n  fromObject: types.EmbedContentResponse,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n    'sdkHttpResponse',\n  ]);\n  if (fromSdkHttpResponse != null) {\n    common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n  }\n\n  const fromEmbeddings = common.getValueByPath(fromObject, [\n    'predictions[]',\n    'embeddings',\n  ]);\n  if (fromEmbeddings != null) {\n    let transformedList = fromEmbeddings;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return contentEmbeddingFromVertex(item);\n      });\n    }\n    common.setValueByPath(toObject, ['embeddings'], transformedList);\n  }\n\n  const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n  if (fromMetadata != null) {\n    common.setValueByPath(toObject, ['metadata'], fromMetadata);\n  }\n\n  return toObject;\n}\n\nexport function endpointFromVertex(\n  fromObject: types.Endpoint,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromName = common.getValueByPath(fromObject, ['endpoint']);\n  if (fromName != null) {\n    common.setValueByPath(toObject, ['name'], fromName);\n  }\n\n  const fromDeployedModelId = common.getValueByPath(fromObject, [\n    'deployedModelId',\n  ]);\n  if (fromDeployedModelId != null) {\n    common.setValueByPath(toObject, ['deployedModelId'], fromDeployedModelId);\n  }\n\n  return toObject;\n}\n\nexport function fileDataToMldev(\n  fromObject: types.FileData,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n    throw new Error('displayName parameter is not supported in Gemini API.');\n  }\n\n  const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n  if (fromFileUri != null) {\n    common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n  }\n\n  const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n  if (fromMimeType != null) {\n    common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n  }\n\n  return toObject;\n}\n\nexport function functionCallToMldev(\n  fromObject: types.FunctionCall,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromId = common.getValueByPath(fromObject, ['id']);\n  if (fromId != null) {\n    common.setValueByPath(toObject, ['id'], fromId);\n  }\n\n  const fromArgs = common.getValueByPath(fromObject, ['args']);\n  if (fromArgs != null) {\n    common.setValueByPath(toObject, ['args'], fromArgs);\n  }\n\n  const fromName = common.getValueByPath(fromObject, ['name']);\n  if (fromName != null) {\n    common.setValueByPath(toObject, ['name'], fromName);\n  }\n\n  if (common.getValueByPath(fromObject, ['partialArgs']) !== undefined) {\n    throw new Error('partialArgs parameter is not supported in Gemini API.');\n  }\n\n  if (common.getValueByPath(fromObject, ['willContinue']) !== undefined) {\n    throw new Error('willContinue parameter is not supported in Gemini API.');\n  }\n\n  return toObject;\n}\n\nexport function functionCallingConfigToMldev(\n  fromObject: types.FunctionCallingConfig,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromMode = common.getValueByPath(fromObject, ['mode']);\n  if (fromMode != null) {\n    common.setValueByPath(toObject, ['mode'], fromMode);\n  }\n\n  const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n    'allowedFunctionNames',\n  ]);\n  if (fromAllowedFunctionNames != null) {\n    common.setValueByPath(\n      toObject,\n      ['allowedFunctionNames'],\n      fromAllowedFunctionNames,\n    );\n  }\n\n  if (\n    common.getValueByPath(fromObject, ['streamFunctionCallArguments']) !==\n    undefined\n  ) {\n    throw new Error(\n      'streamFunctionCallArguments parameter is not supported in Gemini API.',\n    );\n  }\n\n  return toObject;\n}\n\nexport function functionDeclarationToVertex(\n  fromObject: types.FunctionDeclaration,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  if (common.getValueByPath(fromObject, ['behavior']) !== undefined) {\n    throw new Error('behavior parameter is not supported in Vertex AI.');\n  }\n\n  const fromDescription = common.getValueByPath(fromObject, ['description']);\n  if (fromDescription != null) {\n    common.setValueByPath(toObject, ['description'], fromDescription);\n  }\n\n  const fromName = common.getValueByPath(fromObject, ['name']);\n  if (fromName != null) {\n    common.setValueByPath(toObject, ['name'], fromName);\n  }\n\n  const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n  if (fromParameters != null) {\n    common.setValueByPath(toObject, ['parameters'], fromParameters);\n  }\n\n  const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n    'parametersJsonSchema',\n  ]);\n  if (fromParametersJsonSchema != null) {\n    common.setValueByPath(\n      toObject,\n      ['parametersJsonSchema'],\n      fromParametersJsonSchema,\n    );\n  }\n\n  const fromResponse = common.getValueByPath(fromObject, ['response']);\n  if (fromResponse != null) {\n    common.setValueByPath(toObject, ['response'], fromResponse);\n  }\n\n  const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n    'responseJsonSchema',\n  ]);\n  if (fromResponseJsonSchema != null) {\n    common.setValueByPath(\n      toObject,\n      ['responseJsonSchema'],\n      fromResponseJsonSchema,\n    );\n  }\n\n  return toObject;\n}\n\nexport function generateContentConfigToMldev(\n  apiClient: ApiClient,\n  fromObject: types.GenerateContentConfig,\n  parentObject: Record<string, unknown>,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromSystemInstruction = common.getValueByPath(fromObject, [\n    'systemInstruction',\n  ]);\n  if (parentObject !== undefined && fromSystemInstruction != null) {\n    common.setValueByPath(\n      parentObject,\n      ['systemInstruction'],\n      contentToMldev(t.tContent(fromSystemInstruction)),\n    );\n  }\n\n  const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n  if (fromTemperature != null) {\n    common.setValueByPath(toObject, ['temperature'], fromTemperature);\n  }\n\n  const fromTopP = common.getValueByPath(fromObject, ['topP']);\n  if (fromTopP != null) {\n    common.setValueByPath(toObject, ['topP'], fromTopP);\n  }\n\n  const fromTopK = common.getValueByPath(fromObject, ['topK']);\n  if (fromTopK != null) {\n    common.setValueByPath(toObject, ['topK'], fromTopK);\n  }\n\n  const fromCandidateCount = common.getValueByPath(fromObject, [\n    'candidateCount',\n  ]);\n  if (fromCandidateCount != null) {\n    common.setValueByPath(toObject, ['candidateCount'], fromCandidateCount);\n  }\n\n  const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n    'maxOutputTokens',\n  ]);\n  if (fromMaxOutputTokens != null) {\n    common.setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens);\n  }\n\n  const fromStopSequences = common.getValueByPath(fromObject, [\n    'stopSequences',\n  ]);\n  if (fromStopSequences != null) {\n    common.setValueByPath(toObject, ['stopSequences'], fromStopSequences);\n  }\n\n  const fromResponseLogprobs = common.getValueByPath(fromObject, [\n    'responseLogprobs',\n  ]);\n  if (fromResponseLogprobs != null) {\n    common.setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs);\n  }\n\n  const fromLogprobs = common.getValueByPath(fromObject, ['logprobs']);\n  if (fromLogprobs != null) {\n    common.setValueByPath(toObject, ['logprobs'], fromLogprobs);\n  }\n\n  const fromPresencePenalty = common.getValueByPath(fromObject, [\n    'presencePenalty',\n  ]);\n  if (fromPresencePenalty != null) {\n    common.setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty);\n  }\n\n  const fromFrequencyPenalty = common.getValueByPath(fromObject, [\n    'frequencyPenalty',\n  ]);\n  if (fromFrequencyPenalty != null) {\n    common.setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty);\n  }\n\n  const fromSeed = common.getValueByPath(fromObject, ['seed']);\n  if (fromSeed != null) {\n    common.setValueByPath(toObject, ['seed'], fromSeed);\n  }\n\n  const fromResponseMimeType = common.getValueByPath(fromObject, [\n    'responseMimeType',\n  ]);\n  if (fromResponseMimeType != null) {\n    common.setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType);\n  }\n\n  const fromResponseSchema = common.getValueByPath(fromObject, [\n    'responseSchema',\n  ]);\n  if (fromResponseSchema != null) {\n    common.setValueByPath(\n      toObject,\n      ['responseSchema'],\n      t.tSchema(fromResponseSchema),\n    );\n  }\n\n  const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n    'responseJsonSchema',\n  ]);\n  if (fromResponseJsonSchema != null) {\n    common.setValueByPath(\n      toObject,\n      ['responseJsonSchema'],\n      fromResponseJsonSchema,\n    );\n  }\n\n  if (common.getValueByPath(fromObject, ['routingConfig']) !== undefined) {\n    throw new Error('routingConfig parameter is not supported in Gemini API.');\n  }\n\n  if (\n    common.getValueByPath(fromObject, ['modelSelectionConfig']) !== undefined\n  ) {\n    throw new Error(\n      'modelSelectionConfig parameter is not supported in Gemini API.',\n    );\n  }\n\n  const fromSafetySettings = common.getValueByPath(fromObject, [\n    'safetySettings',\n  ]);\n  if (parentObject !== undefined && fromSafetySettings != null) {\n    let transformedList = fromSafetySettings;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return safetySettingToMldev(item);\n      });\n    }\n    common.setValueByPath(parentObject, ['safetySettings'], transformedList);\n  }\n\n  const fromTools = common.getValueByPath(fromObject, ['tools']);\n  if (parentObject !== undefined && fromTools != null) {\n    let transformedList = t.tTools(fromTools);\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return toolToMldev(t.tTool(item));\n      });\n    }\n    common.setValueByPath(parentObject, ['tools'], transformedList);\n  }\n\n  const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n  if (parentObject !== undefined && fromToolConfig != null) {\n    common.setValueByPath(\n      parentObject,\n      ['toolConfig'],\n      toolConfigToMldev(fromToolConfig),\n    );\n  }\n\n  if (common.getValueByPath(fromObject, ['labels']) !== undefined) {\n    throw new Error('labels parameter is not supported in Gemini API.');\n  }\n\n  const fromCachedContent = common.getValueByPath(fromObject, [\n    'cachedContent',\n  ]);\n  if (parentObject !== undefined && fromCachedContent != null) {\n    common.setValueByPath(\n      parentObject,\n      ['cachedContent'],\n      t.tCachedContentName(apiClient, fromCachedContent),\n    );\n  }\n\n  const fromResponseModalities = common.getValueByPath(fromObject, [\n    'responseModalities',\n  ]);\n  if (fromResponseModalities != null) {\n    common.setValueByPath(\n      toObject,\n      ['responseModalities'],\n      fromResponseModalities,\n    );\n  }\n\n  const fromMediaResolution = common.getValueByPath(fromObject, [\n    'mediaResolution',\n  ]);\n  if (fromMediaResolution != null) {\n    common.setValueByPath(toObject, ['mediaResolution'], fromMediaResolution);\n  }\n\n  const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n  if (fromSpeechConfig != null) {\n    common.setValueByPath(\n      toObject,\n      ['speechConfig'],\n      t.tSpeechConfig(fromSpeechConfig),\n    );\n  }\n\n  if (common.getValueByPath(fromObject, ['audioTimestamp']) !== undefined) {\n    throw new Error('audioTimestamp parameter is not supported in Gemini API.');\n  }\n\n  const fromThinkingConfig = common.getValueByPath(fromObject, [\n    'thinkingConfig',\n  ]);\n  if (fromThinkingConfig != null) {\n    common.setValueByPath(toObject, ['thinkingConfig'], fromThinkingConfig);\n  }\n\n  const fromImageConfig = common.getValueByPath(fromObject, ['imageConfig']);\n  if (fromImageConfig != null) {\n    common.setValueByPath(\n      toObject,\n      ['imageConfig'],\n      imageConfigToMldev(fromImageConfig),\n    );\n  }\n\n  const fromEnableEnhancedCivicAnswers = common.getValueByPath(fromObject, [\n    'enableEnhancedCivicAnswers',\n  ]);\n  if (fromEnableEnhancedCivicAnswers != null) {\n    common.setValueByPath(\n      toObject,\n      ['enableEnhancedCivicAnswers'],\n      fromEnableEnhancedCivicAnswers,\n    );\n  }\n\n  return toObject;\n}\n\nexport function generateContentConfigToVertex(\n  apiClient: ApiClient,\n  fromObject: types.GenerateContentConfig,\n  parentObject: Record<string, unknown>,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromSystemInstruction = common.getValueByPath(fromObject, [\n    'systemInstruction',\n  ]);\n  if (parentObject !== undefined && fromSystemInstruction != null) {\n    common.setValueByPath(\n      parentObject,\n      ['systemInstruction'],\n      t.tContent(fromSystemInstruction),\n    );\n  }\n\n  const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n  if (fromTemperature != null) {\n    common.setValueByPath(toObject, ['temperature'], fromTemperature);\n  }\n\n  const fromTopP = common.getValueByPath(fromObject, ['topP']);\n  if (fromTopP != null) {\n    common.setValueByPath(toObject, ['topP'], fromTopP);\n  }\n\n  const fromTopK = common.getValueByPath(fromObject, ['topK']);\n  if (fromTopK != null) {\n    common.setValueByPath(toObject, ['topK'], fromTopK);\n  }\n\n  const fromCandidateCount = common.getValueByPath(fromObject, [\n    'candidateCount',\n  ]);\n  if (fromCandidateCount != null) {\n    common.setValueByPath(toObject, ['candidateCount'], fromCandidateCount);\n  }\n\n  const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n    'maxOutputTokens',\n  ]);\n  if (fromMaxOutputTokens != null) {\n    common.setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens);\n  }\n\n  const fromStopSequences = common.getValueByPath(fromObject, [\n    'stopSequences',\n  ]);\n  if (fromStopSequences != null) {\n    common.setValueByPath(toObject, ['stopSequences'], fromStopSequences);\n  }\n\n  const fromResponseLogprobs = common.getValueByPath(fromObject, [\n    'responseLogprobs',\n  ]);\n  if (fromResponseLogprobs != null) {\n    common.setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs);\n  }\n\n  const fromLogprobs = common.getValueByPath(fromObject, ['logprobs']);\n  if (fromLogprobs != null) {\n    common.setValueByPath(toObject, ['logprobs'], fromLogprobs);\n  }\n\n  const fromPresencePenalty = common.getValueByPath(fromObject, [\n    'presencePenalty',\n  ]);\n  if (fromPresencePenalty != null) {\n    common.setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty);\n  }\n\n  const fromFrequencyPenalty = common.getValueByPath(fromObject, [\n    'frequencyPenalty',\n  ]);\n  if (fromFrequencyPenalty != null) {\n    common.setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty);\n  }\n\n  const fromSeed = common.getValueByPath(fromObject, ['seed']);\n  if (fromSeed != null) {\n    common.setValueByPath(toObject, ['seed'], fromSeed);\n  }\n\n  const fromResponseMimeType = common.getValueByPath(fromObject, [\n    'responseMimeType',\n  ]);\n  if (fromResponseMimeType != null) {\n    common.setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType);\n  }\n\n  const fromResponseSchema = common.getValueByPath(fromObject, [\n    'responseSchema',\n  ]);\n  if (fromResponseSchema != null) {\n    common.setValueByPath(\n      toObject,\n      ['responseSchema'],\n      t.tSchema(fromResponseSchema),\n    );\n  }\n\n  const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n    'responseJsonSchema',\n  ]);\n  if (fromResponseJsonSchema != null) {\n    common.setValueByPath(\n      toObject,\n      ['responseJsonSchema'],\n      fromResponseJsonSchema,\n    );\n  }\n\n  const fromRoutingConfig = common.getValueByPath(fromObject, [\n    'routingConfig',\n  ]);\n  if (fromRoutingConfig != null) {\n    common.setValueByPath(toObject, ['routingConfig'], fromRoutingConfig);\n  }\n\n  const fromModelSelectionConfig = common.getValueByPath(fromObject, [\n    'modelSelectionConfig',\n  ]);\n  if (fromModelSelectionConfig != null) {\n    common.setValueByPath(toObject, ['modelConfig'], fromModelSelectionConfig);\n  }\n\n  const fromSafetySettings = common.getValueByPath(fromObject, [\n    'safetySettings',\n  ]);\n  if (parentObject !== undefined && fromSafetySettings != null) {\n    let transformedList = fromSafetySettings;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return item;\n      });\n    }\n    common.setValueByPath(parentObject, ['safetySettings'], transformedList);\n  }\n\n  const fromTools = common.getValueByPath(fromObject, ['tools']);\n  if (parentObject !== undefined && fromTools != null) {\n    let transformedList = t.tTools(fromTools);\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return toolToVertex(t.tTool(item));\n      });\n    }\n    common.setValueByPath(parentObject, ['tools'], transformedList);\n  }\n\n  const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n  if (parentObject !== undefined && fromToolConfig != null) {\n    common.setValueByPath(parentObject, ['toolConfig'], fromToolConfig);\n  }\n\n  const fromLabels = common.getValueByPath(fromObject, ['labels']);\n  if (parentObject !== undefined && fromLabels != null) {\n    common.setValueByPath(parentObject, ['labels'], fromLabels);\n  }\n\n  const fromCachedContent = common.getValueByPath(fromObject, [\n    'cachedContent',\n  ]);\n  if (parentObject !== undefined && fromCachedContent != null) {\n    common.setValueByPath(\n      parentObject,\n      ['cachedContent'],\n      t.tCachedContentName(apiClient, fromCachedContent),\n    );\n  }\n\n  const fromResponseModalities = common.getValueByPath(fromObject, [\n    'responseModalities',\n  ]);\n  if (fromResponseModalities != null) {\n    common.setValueByPath(\n      toObject,\n      ['responseModalities'],\n      fromResponseModalities,\n    );\n  }\n\n  const fromMediaResolution = common.getValueByPath(fromObject, [\n    'mediaResolution',\n  ]);\n  if (fromMediaResolution != null) {\n    common.setValueByPath(toObject, ['mediaResolution'], fromMediaResolution);\n  }\n\n  const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n  if (fromSpeechConfig != null) {\n    common.setValueByPath(\n      toObject,\n      ['speechConfig'],\n      speechConfigToVertex(t.tSpeechConfig(fromSpeechConfig)),\n    );\n  }\n\n  const fromAudioTimestamp = common.getValueByPath(fromObject, [\n    'audioTimestamp',\n  ]);\n  if (fromAudioTimestamp != null) {\n    common.setValueByPath(toObject, ['audioTimestamp'], fromAudioTimestamp);\n  }\n\n  const fromThinkingConfig = common.getValueByPath(fromObject, [\n    'thinkingConfig',\n  ]);\n  if (fromThinkingConfig != null) {\n    common.setValueByPath(toObject, ['thinkingConfig'], fromThinkingConfig);\n  }\n\n  const fromImageConfig = common.getValueByPath(fromObject, ['imageConfig']);\n  if (fromImageConfig != null) {\n    common.setValueByPath(\n      toObject,\n      ['imageConfig'],\n      imageConfigToVertex(fromImageConfig),\n    );\n  }\n\n  if (\n    common.getValueByPath(fromObject, ['enableEnhancedCivicAnswers']) !==\n    undefined\n  ) {\n    throw new Error(\n      'enableEnhancedCivicAnswers parameter is not supported in Vertex AI.',\n    );\n  }\n\n  return toObject;\n}\n\nexport function generateContentParametersToMldev(\n  apiClient: ApiClient,\n  fromObject: types.GenerateContentParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromModel = common.getValueByPath(fromObject, ['model']);\n  if (fromModel != null) {\n    common.setValueByPath(\n      toObject,\n      ['_url', 'model'],\n      t.tModel(apiClient, fromModel),\n    );\n  }\n\n  const fromContents = common.getValueByPath(fromObject, ['contents']);\n  if (fromContents != null) {\n    let transformedList = t.tContents(fromContents);\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return contentToMldev(item);\n      });\n    }\n    common.setValueByPath(toObject, ['contents'], transformedList);\n  }\n\n  const fromConfig = common.getValueByPath(fromObject, ['config']);\n  if (fromConfig != null) {\n    common.setValueByPath(\n      toObject,\n      ['generationConfig'],\n      generateContentConfigToMldev(apiClient, fromConfig, toObject),\n    );\n  }\n\n  return toObject;\n}\n\nexport function generateContentParametersToVertex(\n  apiClient: ApiClient,\n  fromObject: types.GenerateContentParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromModel = common.getValueByPath(fromObject, ['model']);\n  if (fromModel != null) {\n    common.setValueByPath(\n      toObject,\n      ['_url', 'model'],\n      t.tModel(apiClient, fromModel),\n    );\n  }\n\n  const fromContents = common.getValueByPath(fromObject, ['contents']);\n  if (fromContents != null) {\n    let transformedList = t.tContents(fromContents);\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return item;\n      });\n    }\n    common.setValueByPath(toObject, ['contents'], transformedList);\n  }\n\n  const fromConfig = common.getValueByPath(fromObject, ['config']);\n  if (fromConfig != null) {\n    common.setValueByPath(\n      toObject,\n      ['generationConfig'],\n      generateContentConfigToVertex(apiClient, fromConfig, toObject),\n    );\n  }\n\n  return toObject;\n}\n\nexport function generateContentResponseFromMldev(\n  fromObject: types.GenerateContentResponse,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n    'sdkHttpResponse',\n  ]);\n  if (fromSdkHttpResponse != null) {\n    common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n  }\n\n  const fromCandidates = common.getValueByPath(fromObject, ['candidates']);\n  if (fromCandidates != null) {\n    let transformedList = fromCandidates;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return candidateFromMldev(item);\n      });\n    }\n    common.setValueByPath(toObject, ['candidates'], transformedList);\n  }\n\n  const fromModelVersion = common.getValueByPath(fromObject, ['modelVersion']);\n  if (fromModelVersion != null) {\n    common.setValueByPath(toObject, ['modelVersion'], fromModelVersion);\n  }\n\n  const fromPromptFeedback = common.getValueByPath(fromObject, [\n    'promptFeedback',\n  ]);\n  if (fromPromptFeedback != null) {\n    common.setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback);\n  }\n\n  const fromResponseId = common.getValueByPath(fromObject, ['responseId']);\n  if (fromResponseId != null) {\n    common.setValueByPath(toObject, ['responseId'], fromResponseId);\n  }\n\n  const fromUsageMetadata = common.getValueByPath(fromObject, [\n    'usageMetadata',\n  ]);\n  if (fromUsageMetadata != null) {\n    common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n  }\n\n  return toObject;\n}\n\nexport function generateContentResponseFromVertex(\n  fromObject: types.GenerateContentResponse,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n    'sdkHttpResponse',\n  ]);\n  if (fromSdkHttpResponse != null) {\n    common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n  }\n\n  const fromCandidates = common.getValueByPath(fromObject, ['candidates']);\n  if (fromCandidates != null) {\n    let transformedList = fromCandidates;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return item;\n      });\n    }\n    common.setValueByPath(toObject, ['candidates'], transformedList);\n  }\n\n  const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n  if (fromCreateTime != null) {\n    common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n  }\n\n  const fromModelVersion = common.getValueByPath(fromObject, ['modelVersion']);\n  if (fromModelVersion != null) {\n    common.setValueByPath(toObject, ['modelVersion'], fromModelVersion);\n  }\n\n  const fromPromptFeedback = common.getValueByPath(fromObject, [\n    'promptFeedback',\n  ]);\n  if (fromPromptFeedback != null) {\n    common.setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback);\n  }\n\n  const fromResponseId = common.getValueByPath(fromObject, ['responseId']);\n  if (fromResponseId != null) {\n    common.setValueByPath(toObject, ['responseId'], fromResponseId);\n  }\n\n  const fromUsageMetadata = common.getValueByPath(fromObject, [\n    'usageMetadata',\n  ]);\n  if (fromUsageMetadata != null) {\n    common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n  }\n\n  return toObject;\n}\n\nexport function generateImagesConfigToMldev(\n  fromObject: types.GenerateImagesConfig,\n  parentObject: Record<string, unknown>,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  if (common.getValueByPath(fromObject, ['outputGcsUri']) !== undefined) {\n    throw new Error('outputGcsUri parameter is not supported in Gemini API.');\n  }\n\n  if (common.getValueByPath(fromObject, ['negativePrompt']) !== undefined) {\n    throw new Error('negativePrompt parameter is not supported in Gemini API.');\n  }\n\n  const fromNumberOfImages = common.getValueByPath(fromObject, [\n    'numberOfImages',\n  ]);\n  if (parentObject !== undefined && fromNumberOfImages != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'sampleCount'],\n      fromNumberOfImages,\n    );\n  }\n\n  const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n  if (parentObject !== undefined && fromAspectRatio != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'aspectRatio'],\n      fromAspectRatio,\n    );\n  }\n\n  const fromGuidanceScale = common.getValueByPath(fromObject, [\n    'guidanceScale',\n  ]);\n  if (parentObject !== undefined && fromGuidanceScale != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'guidanceScale'],\n      fromGuidanceScale,\n    );\n  }\n\n  if (common.getValueByPath(fromObject, ['seed']) !== undefined) {\n    throw new Error('seed parameter is not supported in Gemini API.');\n  }\n\n  const fromSafetyFilterLevel = common.getValueByPath(fromObject, [\n    'safetyFilterLevel',\n  ]);\n  if (parentObject !== undefined && fromSafetyFilterLevel != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'safetySetting'],\n      fromSafetyFilterLevel,\n    );\n  }\n\n  const fromPersonGeneration = common.getValueByPath(fromObject, [\n    'personGeneration',\n  ]);\n  if (parentObject !== undefined && fromPersonGeneration != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'personGeneration'],\n      fromPersonGeneration,\n    );\n  }\n\n  const fromIncludeSafetyAttributes = common.getValueByPath(fromObject, [\n    'includeSafetyAttributes',\n  ]);\n  if (parentObject !== undefined && fromIncludeSafetyAttributes != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'includeSafetyAttributes'],\n      fromIncludeSafetyAttributes,\n    );\n  }\n\n  const fromIncludeRaiReason = common.getValueByPath(fromObject, [\n    'includeRaiReason',\n  ]);\n  if (parentObject !== undefined && fromIncludeRaiReason != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'includeRaiReason'],\n      fromIncludeRaiReason,\n    );\n  }\n\n  const fromLanguage = common.getValueByPath(fromObject, ['language']);\n  if (parentObject !== undefined && fromLanguage != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'language'],\n      fromLanguage,\n    );\n  }\n\n  const fromOutputMimeType = common.getValueByPath(fromObject, [\n    'outputMimeType',\n  ]);\n  if (parentObject !== undefined && fromOutputMimeType != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'outputOptions', 'mimeType'],\n      fromOutputMimeType,\n    );\n  }\n\n  const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n    'outputCompressionQuality',\n  ]);\n  if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'outputOptions', 'compressionQuality'],\n      fromOutputCompressionQuality,\n    );\n  }\n\n  if (common.getValueByPath(fromObject, ['addWatermark']) !== undefined) {\n    throw new Error('addWatermark parameter is not supported in Gemini API.');\n  }\n\n  if (common.getValueByPath(fromObject, ['labels']) !== undefined) {\n    throw new Error('labels parameter is not supported in Gemini API.');\n  }\n\n  const fromImageSize = common.getValueByPath(fromObject, ['imageSize']);\n  if (parentObject !== undefined && fromImageSize != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'sampleImageSize'],\n      fromImageSize,\n    );\n  }\n\n  if (common.getValueByPath(fromObject, ['enhancePrompt']) !== undefined) {\n    throw new Error('enhancePrompt parameter is not supported in Gemini API.');\n  }\n\n  return toObject;\n}\n\nexport function generateImagesConfigToVertex(\n  fromObject: types.GenerateImagesConfig,\n  parentObject: Record<string, unknown>,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n  if (parentObject !== undefined && fromOutputGcsUri != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'storageUri'],\n      fromOutputGcsUri,\n    );\n  }\n\n  const fromNegativePrompt = common.getValueByPath(fromObject, [\n    'negativePrompt',\n  ]);\n  if (parentObject !== undefined && fromNegativePrompt != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'negativePrompt'],\n      fromNegativePrompt,\n    );\n  }\n\n  const fromNumberOfImages = common.getValueByPath(fromObject, [\n    'numberOfImages',\n  ]);\n  if (parentObject !== undefined && fromNumberOfImages != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'sampleCount'],\n      fromNumberOfImages,\n    );\n  }\n\n  const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n  if (parentObject !== undefined && fromAspectRatio != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'aspectRatio'],\n      fromAspectRatio,\n    );\n  }\n\n  const fromGuidanceScale = common.getValueByPath(fromObject, [\n    'guidanceScale',\n  ]);\n  if (parentObject !== undefined && fromGuidanceScale != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'guidanceScale'],\n      fromGuidanceScale,\n    );\n  }\n\n  const fromSeed = common.getValueByPath(fromObject, ['seed']);\n  if (parentObject !== undefined && fromSeed != null) {\n    common.setValueByPath(parentObject, ['parameters', 'seed'], fromSeed);\n  }\n\n  const fromSafetyFilterLevel = common.getValueByPath(fromObject, [\n    'safetyFilterLevel',\n  ]);\n  if (parentObject !== undefined && fromSafetyFilterLevel != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'safetySetting'],\n      fromSafetyFilterLevel,\n    );\n  }\n\n  const fromPersonGeneration = common.getValueByPath(fromObject, [\n    'personGeneration',\n  ]);\n  if (parentObject !== undefined && fromPersonGeneration != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'personGeneration'],\n      fromPersonGeneration,\n    );\n  }\n\n  const fromIncludeSafetyAttributes = common.getValueByPath(fromObject, [\n    'includeSafetyAttributes',\n  ]);\n  if (parentObject !== undefined && fromIncludeSafetyAttributes != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'includeSafetyAttributes'],\n      fromIncludeSafetyAttributes,\n    );\n  }\n\n  const fromIncludeRaiReason = common.getValueByPath(fromObject, [\n    'includeRaiReason',\n  ]);\n  if (parentObject !== undefined && fromIncludeRaiReason != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'includeRaiReason'],\n      fromIncludeRaiReason,\n    );\n  }\n\n  const fromLanguage = common.getValueByPath(fromObject, ['language']);\n  if (parentObject !== undefined && fromLanguage != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'language'],\n      fromLanguage,\n    );\n  }\n\n  const fromOutputMimeType = common.getValueByPath(fromObject, [\n    'outputMimeType',\n  ]);\n  if (parentObject !== undefined && fromOutputMimeType != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'outputOptions', 'mimeType'],\n      fromOutputMimeType,\n    );\n  }\n\n  const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n    'outputCompressionQuality',\n  ]);\n  if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'outputOptions', 'compressionQuality'],\n      fromOutputCompressionQuality,\n    );\n  }\n\n  const fromAddWatermark = common.getValueByPath(fromObject, ['addWatermark']);\n  if (parentObject !== undefined && fromAddWatermark != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'addWatermark'],\n      fromAddWatermark,\n    );\n  }\n\n  const fromLabels = common.getValueByPath(fromObject, ['labels']);\n  if (parentObject !== undefined && fromLabels != null) {\n    common.setValueByPath(parentObject, ['labels'], fromLabels);\n  }\n\n  const fromImageSize = common.getValueByPath(fromObject, ['imageSize']);\n  if (parentObject !== undefined && fromImageSize != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'sampleImageSize'],\n      fromImageSize,\n    );\n  }\n\n  const fromEnhancePrompt = common.getValueByPath(fromObject, [\n    'enhancePrompt',\n  ]);\n  if (parentObject !== undefined && fromEnhancePrompt != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'enhancePrompt'],\n      fromEnhancePrompt,\n    );\n  }\n\n  return toObject;\n}\n\nexport function generateImagesParametersToMldev(\n  apiClient: ApiClient,\n  fromObject: types.GenerateImagesParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromModel = common.getValueByPath(fromObject, ['model']);\n  if (fromModel != null) {\n    common.setValueByPath(\n      toObject,\n      ['_url', 'model'],\n      t.tModel(apiClient, fromModel),\n    );\n  }\n\n  const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n  if (fromPrompt != null) {\n    common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n  }\n\n  const fromConfig = common.getValueByPath(fromObject, ['config']);\n  if (fromConfig != null) {\n    generateImagesConfigToMldev(fromConfig, toObject);\n  }\n\n  return toObject;\n}\n\nexport function generateImagesParametersToVertex(\n  apiClient: ApiClient,\n  fromObject: types.GenerateImagesParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromModel = common.getValueByPath(fromObject, ['model']);\n  if (fromModel != null) {\n    common.setValueByPath(\n      toObject,\n      ['_url', 'model'],\n      t.tModel(apiClient, fromModel),\n    );\n  }\n\n  const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n  if (fromPrompt != null) {\n    common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n  }\n\n  const fromConfig = common.getValueByPath(fromObject, ['config']);\n  if (fromConfig != null) {\n    generateImagesConfigToVertex(fromConfig, toObject);\n  }\n\n  return toObject;\n}\n\nexport function generateImagesResponseFromMldev(\n  fromObject: types.GenerateImagesResponse,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n    'sdkHttpResponse',\n  ]);\n  if (fromSdkHttpResponse != null) {\n    common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n  }\n\n  const fromGeneratedImages = common.getValueByPath(fromObject, [\n    'predictions',\n  ]);\n  if (fromGeneratedImages != null) {\n    let transformedList = fromGeneratedImages;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return generatedImageFromMldev(item);\n      });\n    }\n    common.setValueByPath(toObject, ['generatedImages'], transformedList);\n  }\n\n  const fromPositivePromptSafetyAttributes = common.getValueByPath(fromObject, [\n    'positivePromptSafetyAttributes',\n  ]);\n  if (fromPositivePromptSafetyAttributes != null) {\n    common.setValueByPath(\n      toObject,\n      ['positivePromptSafetyAttributes'],\n      safetyAttributesFromMldev(fromPositivePromptSafetyAttributes),\n    );\n  }\n\n  return toObject;\n}\n\nexport function generateImagesResponseFromVertex(\n  fromObject: types.GenerateImagesResponse,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n    'sdkHttpResponse',\n  ]);\n  if (fromSdkHttpResponse != null) {\n    common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n  }\n\n  const fromGeneratedImages = common.getValueByPath(fromObject, [\n    'predictions',\n  ]);\n  if (fromGeneratedImages != null) {\n    let transformedList = fromGeneratedImages;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return generatedImageFromVertex(item);\n      });\n    }\n    common.setValueByPath(toObject, ['generatedImages'], transformedList);\n  }\n\n  const fromPositivePromptSafetyAttributes = common.getValueByPath(fromObject, [\n    'positivePromptSafetyAttributes',\n  ]);\n  if (fromPositivePromptSafetyAttributes != null) {\n    common.setValueByPath(\n      toObject,\n      ['positivePromptSafetyAttributes'],\n      safetyAttributesFromVertex(fromPositivePromptSafetyAttributes),\n    );\n  }\n\n  return toObject;\n}\n\nexport function generateVideosConfigToMldev(\n  fromObject: types.GenerateVideosConfig,\n  parentObject: Record<string, unknown>,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromNumberOfVideos = common.getValueByPath(fromObject, [\n    'numberOfVideos',\n  ]);\n  if (parentObject !== undefined && fromNumberOfVideos != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'sampleCount'],\n      fromNumberOfVideos,\n    );\n  }\n\n  if (common.getValueByPath(fromObject, ['outputGcsUri']) !== undefined) {\n    throw new Error('outputGcsUri parameter is not supported in Gemini API.');\n  }\n\n  if (common.getValueByPath(fromObject, ['fps']) !== undefined) {\n    throw new Error('fps parameter is not supported in Gemini API.');\n  }\n\n  const fromDurationSeconds = common.getValueByPath(fromObject, [\n    'durationSeconds',\n  ]);\n  if (parentObject !== undefined && fromDurationSeconds != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'durationSeconds'],\n      fromDurationSeconds,\n    );\n  }\n\n  if (common.getValueByPath(fromObject, ['seed']) !== undefined) {\n    throw new Error('seed parameter is not supported in Gemini API.');\n  }\n\n  const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n  if (parentObject !== undefined && fromAspectRatio != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'aspectRatio'],\n      fromAspectRatio,\n    );\n  }\n\n  const fromResolution = common.getValueByPath(fromObject, ['resolution']);\n  if (parentObject !== undefined && fromResolution != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'resolution'],\n      fromResolution,\n    );\n  }\n\n  const fromPersonGeneration = common.getValueByPath(fromObject, [\n    'personGeneration',\n  ]);\n  if (parentObject !== undefined && fromPersonGeneration != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'personGeneration'],\n      fromPersonGeneration,\n    );\n  }\n\n  if (common.getValueByPath(fromObject, ['pubsubTopic']) !== undefined) {\n    throw new Error('pubsubTopic parameter is not supported in Gemini API.');\n  }\n\n  const fromNegativePrompt = common.getValueByPath(fromObject, [\n    'negativePrompt',\n  ]);\n  if (parentObject !== undefined && fromNegativePrompt != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'negativePrompt'],\n      fromNegativePrompt,\n    );\n  }\n\n  const fromEnhancePrompt = common.getValueByPath(fromObject, [\n    'enhancePrompt',\n  ]);\n  if (parentObject !== undefined && fromEnhancePrompt != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'enhancePrompt'],\n      fromEnhancePrompt,\n    );\n  }\n\n  if (common.getValueByPath(fromObject, ['generateAudio']) !== undefined) {\n    throw new Error('generateAudio parameter is not supported in Gemini API.');\n  }\n\n  const fromLastFrame = common.getValueByPath(fromObject, ['lastFrame']);\n  if (parentObject !== undefined && fromLastFrame != null) {\n    common.setValueByPath(\n      parentObject,\n      ['instances[0]', 'lastFrame'],\n      imageToMldev(fromLastFrame),\n    );\n  }\n\n  const fromReferenceImages = common.getValueByPath(fromObject, [\n    'referenceImages',\n  ]);\n  if (parentObject !== undefined && fromReferenceImages != null) {\n    let transformedList = fromReferenceImages;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return videoGenerationReferenceImageToMldev(item);\n      });\n    }\n    common.setValueByPath(\n      parentObject,\n      ['instances[0]', 'referenceImages'],\n      transformedList,\n    );\n  }\n\n  if (common.getValueByPath(fromObject, ['mask']) !== undefined) {\n    throw new Error('mask parameter is not supported in Gemini API.');\n  }\n\n  if (common.getValueByPath(fromObject, ['compressionQuality']) !== undefined) {\n    throw new Error(\n      'compressionQuality parameter is not supported in Gemini API.',\n    );\n  }\n\n  return toObject;\n}\n\nexport function generateVideosConfigToVertex(\n  fromObject: types.GenerateVideosConfig,\n  parentObject: Record<string, unknown>,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromNumberOfVideos = common.getValueByPath(fromObject, [\n    'numberOfVideos',\n  ]);\n  if (parentObject !== undefined && fromNumberOfVideos != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'sampleCount'],\n      fromNumberOfVideos,\n    );\n  }\n\n  const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n  if (parentObject !== undefined && fromOutputGcsUri != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'storageUri'],\n      fromOutputGcsUri,\n    );\n  }\n\n  const fromFps = common.getValueByPath(fromObject, ['fps']);\n  if (parentObject !== undefined && fromFps != null) {\n    common.setValueByPath(parentObject, ['parameters', 'fps'], fromFps);\n  }\n\n  const fromDurationSeconds = common.getValueByPath(fromObject, [\n    'durationSeconds',\n  ]);\n  if (parentObject !== undefined && fromDurationSeconds != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'durationSeconds'],\n      fromDurationSeconds,\n    );\n  }\n\n  const fromSeed = common.getValueByPath(fromObject, ['seed']);\n  if (parentObject !== undefined && fromSeed != null) {\n    common.setValueByPath(parentObject, ['parameters', 'seed'], fromSeed);\n  }\n\n  const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n  if (parentObject !== undefined && fromAspectRatio != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'aspectRatio'],\n      fromAspectRatio,\n    );\n  }\n\n  const fromResolution = common.getValueByPath(fromObject, ['resolution']);\n  if (parentObject !== undefined && fromResolution != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'resolution'],\n      fromResolution,\n    );\n  }\n\n  const fromPersonGeneration = common.getValueByPath(fromObject, [\n    'personGeneration',\n  ]);\n  if (parentObject !== undefined && fromPersonGeneration != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'personGeneration'],\n      fromPersonGeneration,\n    );\n  }\n\n  const fromPubsubTopic = common.getValueByPath(fromObject, ['pubsubTopic']);\n  if (parentObject !== undefined && fromPubsubTopic != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'pubsubTopic'],\n      fromPubsubTopic,\n    );\n  }\n\n  const fromNegativePrompt = common.getValueByPath(fromObject, [\n    'negativePrompt',\n  ]);\n  if (parentObject !== undefined && fromNegativePrompt != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'negativePrompt'],\n      fromNegativePrompt,\n    );\n  }\n\n  const fromEnhancePrompt = common.getValueByPath(fromObject, [\n    'enhancePrompt',\n  ]);\n  if (parentObject !== undefined && fromEnhancePrompt != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'enhancePrompt'],\n      fromEnhancePrompt,\n    );\n  }\n\n  const fromGenerateAudio = common.getValueByPath(fromObject, [\n    'generateAudio',\n  ]);\n  if (parentObject !== undefined && fromGenerateAudio != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'generateAudio'],\n      fromGenerateAudio,\n    );\n  }\n\n  const fromLastFrame = common.getValueByPath(fromObject, ['lastFrame']);\n  if (parentObject !== undefined && fromLastFrame != null) {\n    common.setValueByPath(\n      parentObject,\n      ['instances[0]', 'lastFrame'],\n      imageToVertex(fromLastFrame),\n    );\n  }\n\n  const fromReferenceImages = common.getValueByPath(fromObject, [\n    'referenceImages',\n  ]);\n  if (parentObject !== undefined && fromReferenceImages != null) {\n    let transformedList = fromReferenceImages;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return videoGenerationReferenceImageToVertex(item);\n      });\n    }\n    common.setValueByPath(\n      parentObject,\n      ['instances[0]', 'referenceImages'],\n      transformedList,\n    );\n  }\n\n  const fromMask = common.getValueByPath(fromObject, ['mask']);\n  if (parentObject !== undefined && fromMask != null) {\n    common.setValueByPath(\n      parentObject,\n      ['instances[0]', 'mask'],\n      videoGenerationMaskToVertex(fromMask),\n    );\n  }\n\n  const fromCompressionQuality = common.getValueByPath(fromObject, [\n    'compressionQuality',\n  ]);\n  if (parentObject !== undefined && fromCompressionQuality != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'compressionQuality'],\n      fromCompressionQuality,\n    );\n  }\n\n  return toObject;\n}\n\nexport function generateVideosOperationFromMldev(\n  fromObject: types.GenerateVideosOperation,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromName = common.getValueByPath(fromObject, ['name']);\n  if (fromName != null) {\n    common.setValueByPath(toObject, ['name'], fromName);\n  }\n\n  const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n  if (fromMetadata != null) {\n    common.setValueByPath(toObject, ['metadata'], fromMetadata);\n  }\n\n  const fromDone = common.getValueByPath(fromObject, ['done']);\n  if (fromDone != null) {\n    common.setValueByPath(toObject, ['done'], fromDone);\n  }\n\n  const fromError = common.getValueByPath(fromObject, ['error']);\n  if (fromError != null) {\n    common.setValueByPath(toObject, ['error'], fromError);\n  }\n\n  const fromResponse = common.getValueByPath(fromObject, [\n    'response',\n    'generateVideoResponse',\n  ]);\n  if (fromResponse != null) {\n    common.setValueByPath(\n      toObject,\n      ['response'],\n      generateVideosResponseFromMldev(fromResponse),\n    );\n  }\n\n  return toObject;\n}\n\nexport function generateVideosOperationFromVertex(\n  fromObject: types.GenerateVideosOperation,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromName = common.getValueByPath(fromObject, ['name']);\n  if (fromName != null) {\n    common.setValueByPath(toObject, ['name'], fromName);\n  }\n\n  const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n  if (fromMetadata != null) {\n    common.setValueByPath(toObject, ['metadata'], fromMetadata);\n  }\n\n  const fromDone = common.getValueByPath(fromObject, ['done']);\n  if (fromDone != null) {\n    common.setValueByPath(toObject, ['done'], fromDone);\n  }\n\n  const fromError = common.getValueByPath(fromObject, ['error']);\n  if (fromError != null) {\n    common.setValueByPath(toObject, ['error'], fromError);\n  }\n\n  const fromResponse = common.getValueByPath(fromObject, ['response']);\n  if (fromResponse != null) {\n    common.setValueByPath(\n      toObject,\n      ['response'],\n      generateVideosResponseFromVertex(fromResponse),\n    );\n  }\n\n  return toObject;\n}\n\nexport function generateVideosParametersToMldev(\n  apiClient: ApiClient,\n  fromObject: types.GenerateVideosParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromModel = common.getValueByPath(fromObject, ['model']);\n  if (fromModel != null) {\n    common.setValueByPath(\n      toObject,\n      ['_url', 'model'],\n      t.tModel(apiClient, fromModel),\n    );\n  }\n\n  const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n  if (fromPrompt != null) {\n    common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n  }\n\n  const fromImage = common.getValueByPath(fromObject, ['image']);\n  if (fromImage != null) {\n    common.setValueByPath(\n      toObject,\n      ['instances[0]', 'image'],\n      imageToMldev(fromImage),\n    );\n  }\n\n  const fromVideo = common.getValueByPath(fromObject, ['video']);\n  if (fromVideo != null) {\n    common.setValueByPath(\n      toObject,\n      ['instances[0]', 'video'],\n      videoToMldev(fromVideo),\n    );\n  }\n\n  const fromSource = common.getValueByPath(fromObject, ['source']);\n  if (fromSource != null) {\n    generateVideosSourceToMldev(fromSource, toObject);\n  }\n\n  const fromConfig = common.getValueByPath(fromObject, ['config']);\n  if (fromConfig != null) {\n    generateVideosConfigToMldev(fromConfig, toObject);\n  }\n\n  return toObject;\n}\n\nexport function generateVideosParametersToVertex(\n  apiClient: ApiClient,\n  fromObject: types.GenerateVideosParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromModel = common.getValueByPath(fromObject, ['model']);\n  if (fromModel != null) {\n    common.setValueByPath(\n      toObject,\n      ['_url', 'model'],\n      t.tModel(apiClient, fromModel),\n    );\n  }\n\n  const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n  if (fromPrompt != null) {\n    common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n  }\n\n  const fromImage = common.getValueByPath(fromObject, ['image']);\n  if (fromImage != null) {\n    common.setValueByPath(\n      toObject,\n      ['instances[0]', 'image'],\n      imageToVertex(fromImage),\n    );\n  }\n\n  const fromVideo = common.getValueByPath(fromObject, ['video']);\n  if (fromVideo != null) {\n    common.setValueByPath(\n      toObject,\n      ['instances[0]', 'video'],\n      videoToVertex(fromVideo),\n    );\n  }\n\n  const fromSource = common.getValueByPath(fromObject, ['source']);\n  if (fromSource != null) {\n    generateVideosSourceToVertex(fromSource, toObject);\n  }\n\n  const fromConfig = common.getValueByPath(fromObject, ['config']);\n  if (fromConfig != null) {\n    generateVideosConfigToVertex(fromConfig, toObject);\n  }\n\n  return toObject;\n}\n\nexport function generateVideosResponseFromMldev(\n  fromObject: types.GenerateVideosResponse,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromGeneratedVideos = common.getValueByPath(fromObject, [\n    'generatedSamples',\n  ]);\n  if (fromGeneratedVideos != null) {\n    let transformedList = fromGeneratedVideos;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return generatedVideoFromMldev(item);\n      });\n    }\n    common.setValueByPath(toObject, ['generatedVideos'], transformedList);\n  }\n\n  const fromRaiMediaFilteredCount = common.getValueByPath(fromObject, [\n    'raiMediaFilteredCount',\n  ]);\n  if (fromRaiMediaFilteredCount != null) {\n    common.setValueByPath(\n      toObject,\n      ['raiMediaFilteredCount'],\n      fromRaiMediaFilteredCount,\n    );\n  }\n\n  const fromRaiMediaFilteredReasons = common.getValueByPath(fromObject, [\n    'raiMediaFilteredReasons',\n  ]);\n  if (fromRaiMediaFilteredReasons != null) {\n    common.setValueByPath(\n      toObject,\n      ['raiMediaFilteredReasons'],\n      fromRaiMediaFilteredReasons,\n    );\n  }\n\n  return toObject;\n}\n\nexport function generateVideosResponseFromVertex(\n  fromObject: types.GenerateVideosResponse,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromGeneratedVideos = common.getValueByPath(fromObject, ['videos']);\n  if (fromGeneratedVideos != null) {\n    let transformedList = fromGeneratedVideos;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return generatedVideoFromVertex(item);\n      });\n    }\n    common.setValueByPath(toObject, ['generatedVideos'], transformedList);\n  }\n\n  const fromRaiMediaFilteredCount = common.getValueByPath(fromObject, [\n    'raiMediaFilteredCount',\n  ]);\n  if (fromRaiMediaFilteredCount != null) {\n    common.setValueByPath(\n      toObject,\n      ['raiMediaFilteredCount'],\n      fromRaiMediaFilteredCount,\n    );\n  }\n\n  const fromRaiMediaFilteredReasons = common.getValueByPath(fromObject, [\n    'raiMediaFilteredReasons',\n  ]);\n  if (fromRaiMediaFilteredReasons != null) {\n    common.setValueByPath(\n      toObject,\n      ['raiMediaFilteredReasons'],\n      fromRaiMediaFilteredReasons,\n    );\n  }\n\n  return toObject;\n}\n\nexport function generateVideosSourceToMldev(\n  fromObject: types.GenerateVideosSource,\n  parentObject: Record<string, unknown>,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n  if (parentObject !== undefined && fromPrompt != null) {\n    common.setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt);\n  }\n\n  const fromImage = common.getValueByPath(fromObject, ['image']);\n  if (parentObject !== undefined && fromImage != null) {\n    common.setValueByPath(\n      parentObject,\n      ['instances[0]', 'image'],\n      imageToMldev(fromImage),\n    );\n  }\n\n  const fromVideo = common.getValueByPath(fromObject, ['video']);\n  if (parentObject !== undefined && fromVideo != null) {\n    common.setValueByPath(\n      parentObject,\n      ['instances[0]', 'video'],\n      videoToMldev(fromVideo),\n    );\n  }\n\n  return toObject;\n}\n\nexport function generateVideosSourceToVertex(\n  fromObject: types.GenerateVideosSource,\n  parentObject: Record<string, unknown>,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n  if (parentObject !== undefined && fromPrompt != null) {\n    common.setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt);\n  }\n\n  const fromImage = common.getValueByPath(fromObject, ['image']);\n  if (parentObject !== undefined && fromImage != null) {\n    common.setValueByPath(\n      parentObject,\n      ['instances[0]', 'image'],\n      imageToVertex(fromImage),\n    );\n  }\n\n  const fromVideo = common.getValueByPath(fromObject, ['video']);\n  if (parentObject !== undefined && fromVideo != null) {\n    common.setValueByPath(\n      parentObject,\n      ['instances[0]', 'video'],\n      videoToVertex(fromVideo),\n    );\n  }\n\n  return toObject;\n}\n\nexport function generatedImageFromMldev(\n  fromObject: types.GeneratedImage,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromImage = common.getValueByPath(fromObject, ['_self']);\n  if (fromImage != null) {\n    common.setValueByPath(toObject, ['image'], imageFromMldev(fromImage));\n  }\n\n  const fromRaiFilteredReason = common.getValueByPath(fromObject, [\n    'raiFilteredReason',\n  ]);\n  if (fromRaiFilteredReason != null) {\n    common.setValueByPath(\n      toObject,\n      ['raiFilteredReason'],\n      fromRaiFilteredReason,\n    );\n  }\n\n  const fromSafetyAttributes = common.getValueByPath(fromObject, ['_self']);\n  if (fromSafetyAttributes != null) {\n    common.setValueByPath(\n      toObject,\n      ['safetyAttributes'],\n      safetyAttributesFromMldev(fromSafetyAttributes),\n    );\n  }\n\n  return toObject;\n}\n\nexport function generatedImageFromVertex(\n  fromObject: types.GeneratedImage,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromImage = common.getValueByPath(fromObject, ['_self']);\n  if (fromImage != null) {\n    common.setValueByPath(toObject, ['image'], imageFromVertex(fromImage));\n  }\n\n  const fromRaiFilteredReason = common.getValueByPath(fromObject, [\n    'raiFilteredReason',\n  ]);\n  if (fromRaiFilteredReason != null) {\n    common.setValueByPath(\n      toObject,\n      ['raiFilteredReason'],\n      fromRaiFilteredReason,\n    );\n  }\n\n  const fromSafetyAttributes = common.getValueByPath(fromObject, ['_self']);\n  if (fromSafetyAttributes != null) {\n    common.setValueByPath(\n      toObject,\n      ['safetyAttributes'],\n      safetyAttributesFromVertex(fromSafetyAttributes),\n    );\n  }\n\n  const fromEnhancedPrompt = common.getValueByPath(fromObject, ['prompt']);\n  if (fromEnhancedPrompt != null) {\n    common.setValueByPath(toObject, ['enhancedPrompt'], fromEnhancedPrompt);\n  }\n\n  return toObject;\n}\n\nexport function generatedImageMaskFromVertex(\n  fromObject: types.GeneratedImageMask,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromMask = common.getValueByPath(fromObject, ['_self']);\n  if (fromMask != null) {\n    common.setValueByPath(toObject, ['mask'], imageFromVertex(fromMask));\n  }\n\n  const fromLabels = common.getValueByPath(fromObject, ['labels']);\n  if (fromLabels != null) {\n    let transformedList = fromLabels;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return item;\n      });\n    }\n    common.setValueByPath(toObject, ['labels'], transformedList);\n  }\n\n  return toObject;\n}\n\nexport function generatedVideoFromMldev(\n  fromObject: types.GeneratedVideo,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromVideo = common.getValueByPath(fromObject, ['video']);\n  if (fromVideo != null) {\n    common.setValueByPath(toObject, ['video'], videoFromMldev(fromVideo));\n  }\n\n  return toObject;\n}\n\nexport function generatedVideoFromVertex(\n  fromObject: types.GeneratedVideo,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromVideo = common.getValueByPath(fromObject, ['_self']);\n  if (fromVideo != null) {\n    common.setValueByPath(toObject, ['video'], videoFromVertex(fromVideo));\n  }\n\n  return toObject;\n}\n\nexport function generationConfigToVertex(\n  fromObject: types.GenerationConfig,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromModelSelectionConfig = common.getValueByPath(fromObject, [\n    'modelSelectionConfig',\n  ]);\n  if (fromModelSelectionConfig != null) {\n    common.setValueByPath(toObject, ['modelConfig'], fromModelSelectionConfig);\n  }\n\n  const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n    'responseJsonSchema',\n  ]);\n  if (fromResponseJsonSchema != null) {\n    common.setValueByPath(\n      toObject,\n      ['responseJsonSchema'],\n      fromResponseJsonSchema,\n    );\n  }\n\n  const fromAudioTimestamp = common.getValueByPath(fromObject, [\n    'audioTimestamp',\n  ]);\n  if (fromAudioTimestamp != null) {\n    common.setValueByPath(toObject, ['audioTimestamp'], fromAudioTimestamp);\n  }\n\n  const fromCandidateCount = common.getValueByPath(fromObject, [\n    'candidateCount',\n  ]);\n  if (fromCandidateCount != null) {\n    common.setValueByPath(toObject, ['candidateCount'], fromCandidateCount);\n  }\n\n  const fromEnableAffectiveDialog = common.getValueByPath(fromObject, [\n    'enableAffectiveDialog',\n  ]);\n  if (fromEnableAffectiveDialog != null) {\n    common.setValueByPath(\n      toObject,\n      ['enableAffectiveDialog'],\n      fromEnableAffectiveDialog,\n    );\n  }\n\n  const fromFrequencyPenalty = common.getValueByPath(fromObject, [\n    'frequencyPenalty',\n  ]);\n  if (fromFrequencyPenalty != null) {\n    common.setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty);\n  }\n\n  const fromLogprobs = common.getValueByPath(fromObject, ['logprobs']);\n  if (fromLogprobs != null) {\n    common.setValueByPath(toObject, ['logprobs'], fromLogprobs);\n  }\n\n  const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n    'maxOutputTokens',\n  ]);\n  if (fromMaxOutputTokens != null) {\n    common.setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens);\n  }\n\n  const fromMediaResolution = common.getValueByPath(fromObject, [\n    'mediaResolution',\n  ]);\n  if (fromMediaResolution != null) {\n    common.setValueByPath(toObject, ['mediaResolution'], fromMediaResolution);\n  }\n\n  const fromPresencePenalty = common.getValueByPath(fromObject, [\n    'presencePenalty',\n  ]);\n  if (fromPresencePenalty != null) {\n    common.setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty);\n  }\n\n  const fromResponseLogprobs = common.getValueByPath(fromObject, [\n    'responseLogprobs',\n  ]);\n  if (fromResponseLogprobs != null) {\n    common.setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs);\n  }\n\n  const fromResponseMimeType = common.getValueByPath(fromObject, [\n    'responseMimeType',\n  ]);\n  if (fromResponseMimeType != null) {\n    common.setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType);\n  }\n\n  const fromResponseModalities = common.getValueByPath(fromObject, [\n    'responseModalities',\n  ]);\n  if (fromResponseModalities != null) {\n    common.setValueByPath(\n      toObject,\n      ['responseModalities'],\n      fromResponseModalities,\n    );\n  }\n\n  const fromResponseSchema = common.getValueByPath(fromObject, [\n    'responseSchema',\n  ]);\n  if (fromResponseSchema != null) {\n    common.setValueByPath(toObject, ['responseSchema'], fromResponseSchema);\n  }\n\n  const fromRoutingConfig = common.getValueByPath(fromObject, [\n    'routingConfig',\n  ]);\n  if (fromRoutingConfig != null) {\n    common.setValueByPath(toObject, ['routingConfig'], fromRoutingConfig);\n  }\n\n  const fromSeed = common.getValueByPath(fromObject, ['seed']);\n  if (fromSeed != null) {\n    common.setValueByPath(toObject, ['seed'], fromSeed);\n  }\n\n  const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n  if (fromSpeechConfig != null) {\n    common.setValueByPath(\n      toObject,\n      ['speechConfig'],\n      speechConfigToVertex(fromSpeechConfig),\n    );\n  }\n\n  const fromStopSequences = common.getValueByPath(fromObject, [\n    'stopSequences',\n  ]);\n  if (fromStopSequences != null) {\n    common.setValueByPath(toObject, ['stopSequences'], fromStopSequences);\n  }\n\n  const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n  if (fromTemperature != null) {\n    common.setValueByPath(toObject, ['temperature'], fromTemperature);\n  }\n\n  const fromThinkingConfig = common.getValueByPath(fromObject, [\n    'thinkingConfig',\n  ]);\n  if (fromThinkingConfig != null) {\n    common.setValueByPath(toObject, ['thinkingConfig'], fromThinkingConfig);\n  }\n\n  const fromTopK = common.getValueByPath(fromObject, ['topK']);\n  if (fromTopK != null) {\n    common.setValueByPath(toObject, ['topK'], fromTopK);\n  }\n\n  const fromTopP = common.getValueByPath(fromObject, ['topP']);\n  if (fromTopP != null) {\n    common.setValueByPath(toObject, ['topP'], fromTopP);\n  }\n\n  if (\n    common.getValueByPath(fromObject, ['enableEnhancedCivicAnswers']) !==\n    undefined\n  ) {\n    throw new Error(\n      'enableEnhancedCivicAnswers parameter is not supported in Vertex AI.',\n    );\n  }\n\n  return toObject;\n}\n\nexport function getModelParametersToMldev(\n  apiClient: ApiClient,\n  fromObject: types.GetModelParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromModel = common.getValueByPath(fromObject, ['model']);\n  if (fromModel != null) {\n    common.setValueByPath(\n      toObject,\n      ['_url', 'name'],\n      t.tModel(apiClient, fromModel),\n    );\n  }\n\n  return toObject;\n}\n\nexport function getModelParametersToVertex(\n  apiClient: ApiClient,\n  fromObject: types.GetModelParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromModel = common.getValueByPath(fromObject, ['model']);\n  if (fromModel != null) {\n    common.setValueByPath(\n      toObject,\n      ['_url', 'name'],\n      t.tModel(apiClient, fromModel),\n    );\n  }\n\n  return toObject;\n}\n\nexport function googleMapsToMldev(\n  fromObject: types.GoogleMaps,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  if (common.getValueByPath(fromObject, ['authConfig']) !== undefined) {\n    throw new Error('authConfig parameter is not supported in Gemini API.');\n  }\n\n  const fromEnableWidget = common.getValueByPath(fromObject, ['enableWidget']);\n  if (fromEnableWidget != null) {\n    common.setValueByPath(toObject, ['enableWidget'], fromEnableWidget);\n  }\n\n  return toObject;\n}\n\nexport function googleSearchToMldev(\n  fromObject: types.GoogleSearch,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  if (common.getValueByPath(fromObject, ['excludeDomains']) !== undefined) {\n    throw new Error('excludeDomains parameter is not supported in Gemini API.');\n  }\n\n  if (common.getValueByPath(fromObject, ['blockingConfidence']) !== undefined) {\n    throw new Error(\n      'blockingConfidence parameter is not supported in Gemini API.',\n    );\n  }\n\n  const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n    'timeRangeFilter',\n  ]);\n  if (fromTimeRangeFilter != null) {\n    common.setValueByPath(toObject, ['timeRangeFilter'], fromTimeRangeFilter);\n  }\n\n  return toObject;\n}\n\nexport function imageConfigToMldev(\n  fromObject: types.ImageConfig,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n  if (fromAspectRatio != null) {\n    common.setValueByPath(toObject, ['aspectRatio'], fromAspectRatio);\n  }\n\n  const fromImageSize = common.getValueByPath(fromObject, ['imageSize']);\n  if (fromImageSize != null) {\n    common.setValueByPath(toObject, ['imageSize'], fromImageSize);\n  }\n\n  if (common.getValueByPath(fromObject, ['outputMimeType']) !== undefined) {\n    throw new Error('outputMimeType parameter is not supported in Gemini API.');\n  }\n\n  if (\n    common.getValueByPath(fromObject, ['outputCompressionQuality']) !==\n    undefined\n  ) {\n    throw new Error(\n      'outputCompressionQuality parameter is not supported in Gemini API.',\n    );\n  }\n\n  return toObject;\n}\n\nexport function imageConfigToVertex(\n  fromObject: types.ImageConfig,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n  if (fromAspectRatio != null) {\n    common.setValueByPath(toObject, ['aspectRatio'], fromAspectRatio);\n  }\n\n  const fromImageSize = common.getValueByPath(fromObject, ['imageSize']);\n  if (fromImageSize != null) {\n    common.setValueByPath(toObject, ['imageSize'], fromImageSize);\n  }\n\n  const fromOutputMimeType = common.getValueByPath(fromObject, [\n    'outputMimeType',\n  ]);\n  if (fromOutputMimeType != null) {\n    common.setValueByPath(\n      toObject,\n      ['imageOutputOptions', 'mimeType'],\n      fromOutputMimeType,\n    );\n  }\n\n  const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n    'outputCompressionQuality',\n  ]);\n  if (fromOutputCompressionQuality != null) {\n    common.setValueByPath(\n      toObject,\n      ['imageOutputOptions', 'compressionQuality'],\n      fromOutputCompressionQuality,\n    );\n  }\n\n  return toObject;\n}\n\nexport function imageFromMldev(\n  fromObject: types.Image,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromImageBytes = common.getValueByPath(fromObject, [\n    'bytesBase64Encoded',\n  ]);\n  if (fromImageBytes != null) {\n    common.setValueByPath(toObject, ['imageBytes'], t.tBytes(fromImageBytes));\n  }\n\n  const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n  if (fromMimeType != null) {\n    common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n  }\n\n  return toObject;\n}\n\nexport function imageFromVertex(\n  fromObject: types.Image,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n  if (fromGcsUri != null) {\n    common.setValueByPath(toObject, ['gcsUri'], fromGcsUri);\n  }\n\n  const fromImageBytes = common.getValueByPath(fromObject, [\n    'bytesBase64Encoded',\n  ]);\n  if (fromImageBytes != null) {\n    common.setValueByPath(toObject, ['imageBytes'], t.tBytes(fromImageBytes));\n  }\n\n  const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n  if (fromMimeType != null) {\n    common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n  }\n\n  return toObject;\n}\n\nexport function imageToMldev(fromObject: types.Image): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  if (common.getValueByPath(fromObject, ['gcsUri']) !== undefined) {\n    throw new Error('gcsUri parameter is not supported in Gemini API.');\n  }\n\n  const fromImageBytes = common.getValueByPath(fromObject, ['imageBytes']);\n  if (fromImageBytes != null) {\n    common.setValueByPath(\n      toObject,\n      ['bytesBase64Encoded'],\n      t.tBytes(fromImageBytes),\n    );\n  }\n\n  const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n  if (fromMimeType != null) {\n    common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n  }\n\n  return toObject;\n}\n\nexport function imageToVertex(\n  fromObject: types.Image,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n  if (fromGcsUri != null) {\n    common.setValueByPath(toObject, ['gcsUri'], fromGcsUri);\n  }\n\n  const fromImageBytes = common.getValueByPath(fromObject, ['imageBytes']);\n  if (fromImageBytes != null) {\n    common.setValueByPath(\n      toObject,\n      ['bytesBase64Encoded'],\n      t.tBytes(fromImageBytes),\n    );\n  }\n\n  const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n  if (fromMimeType != null) {\n    common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n  }\n\n  return toObject;\n}\n\nexport function listModelsConfigToMldev(\n  apiClient: ApiClient,\n  fromObject: types.ListModelsConfig,\n  parentObject: Record<string, unknown>,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n  if (parentObject !== undefined && fromPageSize != null) {\n    common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n  }\n\n  const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n  if (parentObject !== undefined && fromPageToken != null) {\n    common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n  }\n\n  const fromFilter = common.getValueByPath(fromObject, ['filter']);\n  if (parentObject !== undefined && fromFilter != null) {\n    common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n  }\n\n  const fromQueryBase = common.getValueByPath(fromObject, ['queryBase']);\n  if (parentObject !== undefined && fromQueryBase != null) {\n    common.setValueByPath(\n      parentObject,\n      ['_url', 'models_url'],\n      t.tModelsUrl(apiClient, fromQueryBase),\n    );\n  }\n\n  return toObject;\n}\n\nexport function listModelsConfigToVertex(\n  apiClient: ApiClient,\n  fromObject: types.ListModelsConfig,\n  parentObject: Record<string, unknown>,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n  if (parentObject !== undefined && fromPageSize != null) {\n    common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n  }\n\n  const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n  if (parentObject !== undefined && fromPageToken != null) {\n    common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n  }\n\n  const fromFilter = common.getValueByPath(fromObject, ['filter']);\n  if (parentObject !== undefined && fromFilter != null) {\n    common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n  }\n\n  const fromQueryBase = common.getValueByPath(fromObject, ['queryBase']);\n  if (parentObject !== undefined && fromQueryBase != null) {\n    common.setValueByPath(\n      parentObject,\n      ['_url', 'models_url'],\n      t.tModelsUrl(apiClient, fromQueryBase),\n    );\n  }\n\n  return toObject;\n}\n\nexport function listModelsParametersToMldev(\n  apiClient: ApiClient,\n  fromObject: types.ListModelsParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromConfig = common.getValueByPath(fromObject, ['config']);\n  if (fromConfig != null) {\n    listModelsConfigToMldev(apiClient, fromConfig, toObject);\n  }\n\n  return toObject;\n}\n\nexport function listModelsParametersToVertex(\n  apiClient: ApiClient,\n  fromObject: types.ListModelsParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromConfig = common.getValueByPath(fromObject, ['config']);\n  if (fromConfig != null) {\n    listModelsConfigToVertex(apiClient, fromConfig, toObject);\n  }\n\n  return toObject;\n}\n\nexport function listModelsResponseFromMldev(\n  fromObject: types.ListModelsResponse,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n    'sdkHttpResponse',\n  ]);\n  if (fromSdkHttpResponse != null) {\n    common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n  }\n\n  const fromNextPageToken = common.getValueByPath(fromObject, [\n    'nextPageToken',\n  ]);\n  if (fromNextPageToken != null) {\n    common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n  }\n\n  const fromModels = common.getValueByPath(fromObject, ['_self']);\n  if (fromModels != null) {\n    let transformedList = t.tExtractModels(fromModels);\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return modelFromMldev(item);\n      });\n    }\n    common.setValueByPath(toObject, ['models'], transformedList);\n  }\n\n  return toObject;\n}\n\nexport function listModelsResponseFromVertex(\n  fromObject: types.ListModelsResponse,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n    'sdkHttpResponse',\n  ]);\n  if (fromSdkHttpResponse != null) {\n    common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n  }\n\n  const fromNextPageToken = common.getValueByPath(fromObject, [\n    'nextPageToken',\n  ]);\n  if (fromNextPageToken != null) {\n    common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n  }\n\n  const fromModels = common.getValueByPath(fromObject, ['_self']);\n  if (fromModels != null) {\n    let transformedList = t.tExtractModels(fromModels);\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return modelFromVertex(item);\n      });\n    }\n    common.setValueByPath(toObject, ['models'], transformedList);\n  }\n\n  return toObject;\n}\n\nexport function maskReferenceConfigToVertex(\n  fromObject: types.MaskReferenceConfig,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromMaskMode = common.getValueByPath(fromObject, ['maskMode']);\n  if (fromMaskMode != null) {\n    common.setValueByPath(toObject, ['maskMode'], fromMaskMode);\n  }\n\n  const fromSegmentationClasses = common.getValueByPath(fromObject, [\n    'segmentationClasses',\n  ]);\n  if (fromSegmentationClasses != null) {\n    common.setValueByPath(toObject, ['maskClasses'], fromSegmentationClasses);\n  }\n\n  const fromMaskDilation = common.getValueByPath(fromObject, ['maskDilation']);\n  if (fromMaskDilation != null) {\n    common.setValueByPath(toObject, ['dilation'], fromMaskDilation);\n  }\n\n  return toObject;\n}\n\nexport function modelFromMldev(\n  fromObject: types.Model,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromName = common.getValueByPath(fromObject, ['name']);\n  if (fromName != null) {\n    common.setValueByPath(toObject, ['name'], fromName);\n  }\n\n  const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n  if (fromDisplayName != null) {\n    common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n  }\n\n  const fromDescription = common.getValueByPath(fromObject, ['description']);\n  if (fromDescription != null) {\n    common.setValueByPath(toObject, ['description'], fromDescription);\n  }\n\n  const fromVersion = common.getValueByPath(fromObject, ['version']);\n  if (fromVersion != null) {\n    common.setValueByPath(toObject, ['version'], fromVersion);\n  }\n\n  const fromTunedModelInfo = common.getValueByPath(fromObject, ['_self']);\n  if (fromTunedModelInfo != null) {\n    common.setValueByPath(\n      toObject,\n      ['tunedModelInfo'],\n      tunedModelInfoFromMldev(fromTunedModelInfo),\n    );\n  }\n\n  const fromInputTokenLimit = common.getValueByPath(fromObject, [\n    'inputTokenLimit',\n  ]);\n  if (fromInputTokenLimit != null) {\n    common.setValueByPath(toObject, ['inputTokenLimit'], fromInputTokenLimit);\n  }\n\n  const fromOutputTokenLimit = common.getValueByPath(fromObject, [\n    'outputTokenLimit',\n  ]);\n  if (fromOutputTokenLimit != null) {\n    common.setValueByPath(toObject, ['outputTokenLimit'], fromOutputTokenLimit);\n  }\n\n  const fromSupportedActions = common.getValueByPath(fromObject, [\n    'supportedGenerationMethods',\n  ]);\n  if (fromSupportedActions != null) {\n    common.setValueByPath(toObject, ['supportedActions'], fromSupportedActions);\n  }\n\n  const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n  if (fromTemperature != null) {\n    common.setValueByPath(toObject, ['temperature'], fromTemperature);\n  }\n\n  const fromMaxTemperature = common.getValueByPath(fromObject, [\n    'maxTemperature',\n  ]);\n  if (fromMaxTemperature != null) {\n    common.setValueByPath(toObject, ['maxTemperature'], fromMaxTemperature);\n  }\n\n  const fromTopP = common.getValueByPath(fromObject, ['topP']);\n  if (fromTopP != null) {\n    common.setValueByPath(toObject, ['topP'], fromTopP);\n  }\n\n  const fromTopK = common.getValueByPath(fromObject, ['topK']);\n  if (fromTopK != null) {\n    common.setValueByPath(toObject, ['topK'], fromTopK);\n  }\n\n  const fromThinking = common.getValueByPath(fromObject, ['thinking']);\n  if (fromThinking != null) {\n    common.setValueByPath(toObject, ['thinking'], fromThinking);\n  }\n\n  return toObject;\n}\n\nexport function modelFromVertex(\n  fromObject: types.Model,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromName = common.getValueByPath(fromObject, ['name']);\n  if (fromName != null) {\n    common.setValueByPath(toObject, ['name'], fromName);\n  }\n\n  const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n  if (fromDisplayName != null) {\n    common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n  }\n\n  const fromDescription = common.getValueByPath(fromObject, ['description']);\n  if (fromDescription != null) {\n    common.setValueByPath(toObject, ['description'], fromDescription);\n  }\n\n  const fromVersion = common.getValueByPath(fromObject, ['versionId']);\n  if (fromVersion != null) {\n    common.setValueByPath(toObject, ['version'], fromVersion);\n  }\n\n  const fromEndpoints = common.getValueByPath(fromObject, ['deployedModels']);\n  if (fromEndpoints != null) {\n    let transformedList = fromEndpoints;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return endpointFromVertex(item);\n      });\n    }\n    common.setValueByPath(toObject, ['endpoints'], transformedList);\n  }\n\n  const fromLabels = common.getValueByPath(fromObject, ['labels']);\n  if (fromLabels != null) {\n    common.setValueByPath(toObject, ['labels'], fromLabels);\n  }\n\n  const fromTunedModelInfo = common.getValueByPath(fromObject, ['_self']);\n  if (fromTunedModelInfo != null) {\n    common.setValueByPath(\n      toObject,\n      ['tunedModelInfo'],\n      tunedModelInfoFromVertex(fromTunedModelInfo),\n    );\n  }\n\n  const fromDefaultCheckpointId = common.getValueByPath(fromObject, [\n    'defaultCheckpointId',\n  ]);\n  if (fromDefaultCheckpointId != null) {\n    common.setValueByPath(\n      toObject,\n      ['defaultCheckpointId'],\n      fromDefaultCheckpointId,\n    );\n  }\n\n  const fromCheckpoints = common.getValueByPath(fromObject, ['checkpoints']);\n  if (fromCheckpoints != null) {\n    let transformedList = fromCheckpoints;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return item;\n      });\n    }\n    common.setValueByPath(toObject, ['checkpoints'], transformedList);\n  }\n\n  return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromMediaResolution = common.getValueByPath(fromObject, [\n    'mediaResolution',\n  ]);\n  if (fromMediaResolution != null) {\n    common.setValueByPath(toObject, ['mediaResolution'], fromMediaResolution);\n  }\n\n  const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n    'codeExecutionResult',\n  ]);\n  if (fromCodeExecutionResult != null) {\n    common.setValueByPath(\n      toObject,\n      ['codeExecutionResult'],\n      fromCodeExecutionResult,\n    );\n  }\n\n  const fromExecutableCode = common.getValueByPath(fromObject, [\n    'executableCode',\n  ]);\n  if (fromExecutableCode != null) {\n    common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n  }\n\n  const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n  if (fromFileData != null) {\n    common.setValueByPath(\n      toObject,\n      ['fileData'],\n      fileDataToMldev(fromFileData),\n    );\n  }\n\n  const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n  if (fromFunctionCall != null) {\n    common.setValueByPath(\n      toObject,\n      ['functionCall'],\n      functionCallToMldev(fromFunctionCall),\n    );\n  }\n\n  const fromFunctionResponse = common.getValueByPath(fromObject, [\n    'functionResponse',\n  ]);\n  if (fromFunctionResponse != null) {\n    common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n  }\n\n  const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n  if (fromInlineData != null) {\n    common.setValueByPath(\n      toObject,\n      ['inlineData'],\n      blobToMldev(fromInlineData),\n    );\n  }\n\n  const fromText = common.getValueByPath(fromObject, ['text']);\n  if (fromText != null) {\n    common.setValueByPath(toObject, ['text'], fromText);\n  }\n\n  const fromThought = common.getValueByPath(fromObject, ['thought']);\n  if (fromThought != null) {\n    common.setValueByPath(toObject, ['thought'], fromThought);\n  }\n\n  const fromThoughtSignature = common.getValueByPath(fromObject, [\n    'thoughtSignature',\n  ]);\n  if (fromThoughtSignature != null) {\n    common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n  }\n\n  const fromVideoMetadata = common.getValueByPath(fromObject, [\n    'videoMetadata',\n  ]);\n  if (fromVideoMetadata != null) {\n    common.setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata);\n  }\n\n  return toObject;\n}\n\nexport function productImageToVertex(\n  fromObject: types.ProductImage,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromProductImage = common.getValueByPath(fromObject, ['productImage']);\n  if (fromProductImage != null) {\n    common.setValueByPath(toObject, ['image'], imageToVertex(fromProductImage));\n  }\n\n  return toObject;\n}\n\nexport function recontextImageConfigToVertex(\n  fromObject: types.RecontextImageConfig,\n  parentObject: Record<string, unknown>,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromNumberOfImages = common.getValueByPath(fromObject, [\n    'numberOfImages',\n  ]);\n  if (parentObject !== undefined && fromNumberOfImages != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'sampleCount'],\n      fromNumberOfImages,\n    );\n  }\n\n  const fromBaseSteps = common.getValueByPath(fromObject, ['baseSteps']);\n  if (parentObject !== undefined && fromBaseSteps != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'baseSteps'],\n      fromBaseSteps,\n    );\n  }\n\n  const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n  if (parentObject !== undefined && fromOutputGcsUri != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'storageUri'],\n      fromOutputGcsUri,\n    );\n  }\n\n  const fromSeed = common.getValueByPath(fromObject, ['seed']);\n  if (parentObject !== undefined && fromSeed != null) {\n    common.setValueByPath(parentObject, ['parameters', 'seed'], fromSeed);\n  }\n\n  const fromSafetyFilterLevel = common.getValueByPath(fromObject, [\n    'safetyFilterLevel',\n  ]);\n  if (parentObject !== undefined && fromSafetyFilterLevel != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'safetySetting'],\n      fromSafetyFilterLevel,\n    );\n  }\n\n  const fromPersonGeneration = common.getValueByPath(fromObject, [\n    'personGeneration',\n  ]);\n  if (parentObject !== undefined && fromPersonGeneration != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'personGeneration'],\n      fromPersonGeneration,\n    );\n  }\n\n  const fromAddWatermark = common.getValueByPath(fromObject, ['addWatermark']);\n  if (parentObject !== undefined && fromAddWatermark != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'addWatermark'],\n      fromAddWatermark,\n    );\n  }\n\n  const fromOutputMimeType = common.getValueByPath(fromObject, [\n    'outputMimeType',\n  ]);\n  if (parentObject !== undefined && fromOutputMimeType != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'outputOptions', 'mimeType'],\n      fromOutputMimeType,\n    );\n  }\n\n  const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n    'outputCompressionQuality',\n  ]);\n  if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'outputOptions', 'compressionQuality'],\n      fromOutputCompressionQuality,\n    );\n  }\n\n  const fromEnhancePrompt = common.getValueByPath(fromObject, [\n    'enhancePrompt',\n  ]);\n  if (parentObject !== undefined && fromEnhancePrompt != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'enhancePrompt'],\n      fromEnhancePrompt,\n    );\n  }\n\n  const fromLabels = common.getValueByPath(fromObject, ['labels']);\n  if (parentObject !== undefined && fromLabels != null) {\n    common.setValueByPath(parentObject, ['labels'], fromLabels);\n  }\n\n  return toObject;\n}\n\nexport function recontextImageParametersToVertex(\n  apiClient: ApiClient,\n  fromObject: types.RecontextImageParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromModel = common.getValueByPath(fromObject, ['model']);\n  if (fromModel != null) {\n    common.setValueByPath(\n      toObject,\n      ['_url', 'model'],\n      t.tModel(apiClient, fromModel),\n    );\n  }\n\n  const fromSource = common.getValueByPath(fromObject, ['source']);\n  if (fromSource != null) {\n    recontextImageSourceToVertex(fromSource, toObject);\n  }\n\n  const fromConfig = common.getValueByPath(fromObject, ['config']);\n  if (fromConfig != null) {\n    recontextImageConfigToVertex(fromConfig, toObject);\n  }\n\n  return toObject;\n}\n\nexport function recontextImageResponseFromVertex(\n  fromObject: types.RecontextImageResponse,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromGeneratedImages = common.getValueByPath(fromObject, [\n    'predictions',\n  ]);\n  if (fromGeneratedImages != null) {\n    let transformedList = fromGeneratedImages;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return generatedImageFromVertex(item);\n      });\n    }\n    common.setValueByPath(toObject, ['generatedImages'], transformedList);\n  }\n\n  return toObject;\n}\n\nexport function recontextImageSourceToVertex(\n  fromObject: types.RecontextImageSource,\n  parentObject: Record<string, unknown>,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n  if (parentObject !== undefined && fromPrompt != null) {\n    common.setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt);\n  }\n\n  const fromPersonImage = common.getValueByPath(fromObject, ['personImage']);\n  if (parentObject !== undefined && fromPersonImage != null) {\n    common.setValueByPath(\n      parentObject,\n      ['instances[0]', 'personImage', 'image'],\n      imageToVertex(fromPersonImage),\n    );\n  }\n\n  const fromProductImages = common.getValueByPath(fromObject, [\n    'productImages',\n  ]);\n  if (parentObject !== undefined && fromProductImages != null) {\n    let transformedList = fromProductImages;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return productImageToVertex(item);\n      });\n    }\n    common.setValueByPath(\n      parentObject,\n      ['instances[0]', 'productImages'],\n      transformedList,\n    );\n  }\n\n  return toObject;\n}\n\nexport function referenceImageAPIInternalToVertex(\n  fromObject: _internal_types.ReferenceImageAPIInternal,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromReferenceImage = common.getValueByPath(fromObject, [\n    'referenceImage',\n  ]);\n  if (fromReferenceImage != null) {\n    common.setValueByPath(\n      toObject,\n      ['referenceImage'],\n      imageToVertex(fromReferenceImage),\n    );\n  }\n\n  const fromReferenceId = common.getValueByPath(fromObject, ['referenceId']);\n  if (fromReferenceId != null) {\n    common.setValueByPath(toObject, ['referenceId'], fromReferenceId);\n  }\n\n  const fromReferenceType = common.getValueByPath(fromObject, [\n    'referenceType',\n  ]);\n  if (fromReferenceType != null) {\n    common.setValueByPath(toObject, ['referenceType'], fromReferenceType);\n  }\n\n  const fromMaskImageConfig = common.getValueByPath(fromObject, [\n    'maskImageConfig',\n  ]);\n  if (fromMaskImageConfig != null) {\n    common.setValueByPath(\n      toObject,\n      ['maskImageConfig'],\n      maskReferenceConfigToVertex(fromMaskImageConfig),\n    );\n  }\n\n  const fromControlImageConfig = common.getValueByPath(fromObject, [\n    'controlImageConfig',\n  ]);\n  if (fromControlImageConfig != null) {\n    common.setValueByPath(\n      toObject,\n      ['controlImageConfig'],\n      controlReferenceConfigToVertex(fromControlImageConfig),\n    );\n  }\n\n  const fromStyleImageConfig = common.getValueByPath(fromObject, [\n    'styleImageConfig',\n  ]);\n  if (fromStyleImageConfig != null) {\n    common.setValueByPath(toObject, ['styleImageConfig'], fromStyleImageConfig);\n  }\n\n  const fromSubjectImageConfig = common.getValueByPath(fromObject, [\n    'subjectImageConfig',\n  ]);\n  if (fromSubjectImageConfig != null) {\n    common.setValueByPath(\n      toObject,\n      ['subjectImageConfig'],\n      fromSubjectImageConfig,\n    );\n  }\n\n  return toObject;\n}\n\nexport function safetyAttributesFromMldev(\n  fromObject: types.SafetyAttributes,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromCategories = common.getValueByPath(fromObject, [\n    'safetyAttributes',\n    'categories',\n  ]);\n  if (fromCategories != null) {\n    common.setValueByPath(toObject, ['categories'], fromCategories);\n  }\n\n  const fromScores = common.getValueByPath(fromObject, [\n    'safetyAttributes',\n    'scores',\n  ]);\n  if (fromScores != null) {\n    common.setValueByPath(toObject, ['scores'], fromScores);\n  }\n\n  const fromContentType = common.getValueByPath(fromObject, ['contentType']);\n  if (fromContentType != null) {\n    common.setValueByPath(toObject, ['contentType'], fromContentType);\n  }\n\n  return toObject;\n}\n\nexport function safetyAttributesFromVertex(\n  fromObject: types.SafetyAttributes,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromCategories = common.getValueByPath(fromObject, [\n    'safetyAttributes',\n    'categories',\n  ]);\n  if (fromCategories != null) {\n    common.setValueByPath(toObject, ['categories'], fromCategories);\n  }\n\n  const fromScores = common.getValueByPath(fromObject, [\n    'safetyAttributes',\n    'scores',\n  ]);\n  if (fromScores != null) {\n    common.setValueByPath(toObject, ['scores'], fromScores);\n  }\n\n  const fromContentType = common.getValueByPath(fromObject, ['contentType']);\n  if (fromContentType != null) {\n    common.setValueByPath(toObject, ['contentType'], fromContentType);\n  }\n\n  return toObject;\n}\n\nexport function safetySettingToMldev(\n  fromObject: types.SafetySetting,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromCategory = common.getValueByPath(fromObject, ['category']);\n  if (fromCategory != null) {\n    common.setValueByPath(toObject, ['category'], fromCategory);\n  }\n\n  if (common.getValueByPath(fromObject, ['method']) !== undefined) {\n    throw new Error('method parameter is not supported in Gemini API.');\n  }\n\n  const fromThreshold = common.getValueByPath(fromObject, ['threshold']);\n  if (fromThreshold != null) {\n    common.setValueByPath(toObject, ['threshold'], fromThreshold);\n  }\n\n  return toObject;\n}\n\nexport function scribbleImageToVertex(\n  fromObject: types.ScribbleImage,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromImage = common.getValueByPath(fromObject, ['image']);\n  if (fromImage != null) {\n    common.setValueByPath(toObject, ['image'], imageToVertex(fromImage));\n  }\n\n  return toObject;\n}\n\nexport function segmentImageConfigToVertex(\n  fromObject: types.SegmentImageConfig,\n  parentObject: Record<string, unknown>,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromMode = common.getValueByPath(fromObject, ['mode']);\n  if (parentObject !== undefined && fromMode != null) {\n    common.setValueByPath(parentObject, ['parameters', 'mode'], fromMode);\n  }\n\n  const fromMaxPredictions = common.getValueByPath(fromObject, [\n    'maxPredictions',\n  ]);\n  if (parentObject !== undefined && fromMaxPredictions != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'maxPredictions'],\n      fromMaxPredictions,\n    );\n  }\n\n  const fromConfidenceThreshold = common.getValueByPath(fromObject, [\n    'confidenceThreshold',\n  ]);\n  if (parentObject !== undefined && fromConfidenceThreshold != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'confidenceThreshold'],\n      fromConfidenceThreshold,\n    );\n  }\n\n  const fromMaskDilation = common.getValueByPath(fromObject, ['maskDilation']);\n  if (parentObject !== undefined && fromMaskDilation != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'maskDilation'],\n      fromMaskDilation,\n    );\n  }\n\n  const fromBinaryColorThreshold = common.getValueByPath(fromObject, [\n    'binaryColorThreshold',\n  ]);\n  if (parentObject !== undefined && fromBinaryColorThreshold != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'binaryColorThreshold'],\n      fromBinaryColorThreshold,\n    );\n  }\n\n  const fromLabels = common.getValueByPath(fromObject, ['labels']);\n  if (parentObject !== undefined && fromLabels != null) {\n    common.setValueByPath(parentObject, ['labels'], fromLabels);\n  }\n\n  return toObject;\n}\n\nexport function segmentImageParametersToVertex(\n  apiClient: ApiClient,\n  fromObject: types.SegmentImageParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromModel = common.getValueByPath(fromObject, ['model']);\n  if (fromModel != null) {\n    common.setValueByPath(\n      toObject,\n      ['_url', 'model'],\n      t.tModel(apiClient, fromModel),\n    );\n  }\n\n  const fromSource = common.getValueByPath(fromObject, ['source']);\n  if (fromSource != null) {\n    segmentImageSourceToVertex(fromSource, toObject);\n  }\n\n  const fromConfig = common.getValueByPath(fromObject, ['config']);\n  if (fromConfig != null) {\n    segmentImageConfigToVertex(fromConfig, toObject);\n  }\n\n  return toObject;\n}\n\nexport function segmentImageResponseFromVertex(\n  fromObject: types.SegmentImageResponse,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromGeneratedMasks = common.getValueByPath(fromObject, ['predictions']);\n  if (fromGeneratedMasks != null) {\n    let transformedList = fromGeneratedMasks;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return generatedImageMaskFromVertex(item);\n      });\n    }\n    common.setValueByPath(toObject, ['generatedMasks'], transformedList);\n  }\n\n  return toObject;\n}\n\nexport function segmentImageSourceToVertex(\n  fromObject: types.SegmentImageSource,\n  parentObject: Record<string, unknown>,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n  if (parentObject !== undefined && fromPrompt != null) {\n    common.setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt);\n  }\n\n  const fromImage = common.getValueByPath(fromObject, ['image']);\n  if (parentObject !== undefined && fromImage != null) {\n    common.setValueByPath(\n      parentObject,\n      ['instances[0]', 'image'],\n      imageToVertex(fromImage),\n    );\n  }\n\n  const fromScribbleImage = common.getValueByPath(fromObject, [\n    'scribbleImage',\n  ]);\n  if (parentObject !== undefined && fromScribbleImage != null) {\n    common.setValueByPath(\n      parentObject,\n      ['instances[0]', 'scribble'],\n      scribbleImageToVertex(fromScribbleImage),\n    );\n  }\n\n  return toObject;\n}\n\nexport function speechConfigToVertex(\n  fromObject: types.SpeechConfig,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n  if (fromVoiceConfig != null) {\n    common.setValueByPath(toObject, ['voiceConfig'], fromVoiceConfig);\n  }\n\n  const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n  if (fromLanguageCode != null) {\n    common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n  }\n\n  if (\n    common.getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined\n  ) {\n    throw new Error(\n      'multiSpeakerVoiceConfig parameter is not supported in Vertex AI.',\n    );\n  }\n\n  return toObject;\n}\n\nexport function toolConfigToMldev(\n  fromObject: types.ToolConfig,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n    'functionCallingConfig',\n  ]);\n  if (fromFunctionCallingConfig != null) {\n    common.setValueByPath(\n      toObject,\n      ['functionCallingConfig'],\n      functionCallingConfigToMldev(fromFunctionCallingConfig),\n    );\n  }\n\n  const fromRetrievalConfig = common.getValueByPath(fromObject, [\n    'retrievalConfig',\n  ]);\n  if (fromRetrievalConfig != null) {\n    common.setValueByPath(toObject, ['retrievalConfig'], fromRetrievalConfig);\n  }\n\n  return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n    'functionDeclarations',\n  ]);\n  if (fromFunctionDeclarations != null) {\n    let transformedList = fromFunctionDeclarations;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return item;\n      });\n    }\n    common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n  }\n\n  if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n    throw new Error('retrieval parameter is not supported in Gemini API.');\n  }\n\n  const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n    'googleSearchRetrieval',\n  ]);\n  if (fromGoogleSearchRetrieval != null) {\n    common.setValueByPath(\n      toObject,\n      ['googleSearchRetrieval'],\n      fromGoogleSearchRetrieval,\n    );\n  }\n\n  const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n  if (fromComputerUse != null) {\n    common.setValueByPath(toObject, ['computerUse'], fromComputerUse);\n  }\n\n  const fromFileSearch = common.getValueByPath(fromObject, ['fileSearch']);\n  if (fromFileSearch != null) {\n    common.setValueByPath(toObject, ['fileSearch'], fromFileSearch);\n  }\n\n  const fromCodeExecution = common.getValueByPath(fromObject, [\n    'codeExecution',\n  ]);\n  if (fromCodeExecution != null) {\n    common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n  }\n\n  if (\n    common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n  ) {\n    throw new Error(\n      'enterpriseWebSearch parameter is not supported in Gemini API.',\n    );\n  }\n\n  const fromGoogleMaps = common.getValueByPath(fromObject, ['googleMaps']);\n  if (fromGoogleMaps != null) {\n    common.setValueByPath(\n      toObject,\n      ['googleMaps'],\n      googleMapsToMldev(fromGoogleMaps),\n    );\n  }\n\n  const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n  if (fromGoogleSearch != null) {\n    common.setValueByPath(\n      toObject,\n      ['googleSearch'],\n      googleSearchToMldev(fromGoogleSearch),\n    );\n  }\n\n  const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n  if (fromUrlContext != null) {\n    common.setValueByPath(toObject, ['urlContext'], fromUrlContext);\n  }\n\n  return toObject;\n}\n\nexport function toolToVertex(fromObject: types.Tool): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n    'functionDeclarations',\n  ]);\n  if (fromFunctionDeclarations != null) {\n    let transformedList = fromFunctionDeclarations;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return functionDeclarationToVertex(item);\n      });\n    }\n    common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n  }\n\n  const fromRetrieval = common.getValueByPath(fromObject, ['retrieval']);\n  if (fromRetrieval != null) {\n    common.setValueByPath(toObject, ['retrieval'], fromRetrieval);\n  }\n\n  const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n    'googleSearchRetrieval',\n  ]);\n  if (fromGoogleSearchRetrieval != null) {\n    common.setValueByPath(\n      toObject,\n      ['googleSearchRetrieval'],\n      fromGoogleSearchRetrieval,\n    );\n  }\n\n  const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n  if (fromComputerUse != null) {\n    common.setValueByPath(toObject, ['computerUse'], fromComputerUse);\n  }\n\n  if (common.getValueByPath(fromObject, ['fileSearch']) !== undefined) {\n    throw new Error('fileSearch parameter is not supported in Vertex AI.');\n  }\n\n  const fromCodeExecution = common.getValueByPath(fromObject, [\n    'codeExecution',\n  ]);\n  if (fromCodeExecution != null) {\n    common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n  }\n\n  const fromEnterpriseWebSearch = common.getValueByPath(fromObject, [\n    'enterpriseWebSearch',\n  ]);\n  if (fromEnterpriseWebSearch != null) {\n    common.setValueByPath(\n      toObject,\n      ['enterpriseWebSearch'],\n      fromEnterpriseWebSearch,\n    );\n  }\n\n  const fromGoogleMaps = common.getValueByPath(fromObject, ['googleMaps']);\n  if (fromGoogleMaps != null) {\n    common.setValueByPath(toObject, ['googleMaps'], fromGoogleMaps);\n  }\n\n  const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n  if (fromGoogleSearch != null) {\n    common.setValueByPath(toObject, ['googleSearch'], fromGoogleSearch);\n  }\n\n  const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n  if (fromUrlContext != null) {\n    common.setValueByPath(toObject, ['urlContext'], fromUrlContext);\n  }\n\n  return toObject;\n}\n\nexport function tunedModelInfoFromMldev(\n  fromObject: types.TunedModelInfo,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n  if (fromBaseModel != null) {\n    common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n  }\n\n  const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n  if (fromCreateTime != null) {\n    common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n  }\n\n  const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n  if (fromUpdateTime != null) {\n    common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n  }\n\n  return toObject;\n}\n\nexport function tunedModelInfoFromVertex(\n  fromObject: types.TunedModelInfo,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromBaseModel = common.getValueByPath(fromObject, [\n    'labels',\n    'google-vertex-llm-tuning-base-model-id',\n  ]);\n  if (fromBaseModel != null) {\n    common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n  }\n\n  const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n  if (fromCreateTime != null) {\n    common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n  }\n\n  const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n  if (fromUpdateTime != null) {\n    common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n  }\n\n  return toObject;\n}\n\nexport function updateModelConfigToMldev(\n  fromObject: types.UpdateModelConfig,\n  parentObject: Record<string, unknown>,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n  if (parentObject !== undefined && fromDisplayName != null) {\n    common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n  }\n\n  const fromDescription = common.getValueByPath(fromObject, ['description']);\n  if (parentObject !== undefined && fromDescription != null) {\n    common.setValueByPath(parentObject, ['description'], fromDescription);\n  }\n\n  const fromDefaultCheckpointId = common.getValueByPath(fromObject, [\n    'defaultCheckpointId',\n  ]);\n  if (parentObject !== undefined && fromDefaultCheckpointId != null) {\n    common.setValueByPath(\n      parentObject,\n      ['defaultCheckpointId'],\n      fromDefaultCheckpointId,\n    );\n  }\n\n  return toObject;\n}\n\nexport function updateModelConfigToVertex(\n  fromObject: types.UpdateModelConfig,\n  parentObject: Record<string, unknown>,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n  if (parentObject !== undefined && fromDisplayName != null) {\n    common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n  }\n\n  const fromDescription = common.getValueByPath(fromObject, ['description']);\n  if (parentObject !== undefined && fromDescription != null) {\n    common.setValueByPath(parentObject, ['description'], fromDescription);\n  }\n\n  const fromDefaultCheckpointId = common.getValueByPath(fromObject, [\n    'defaultCheckpointId',\n  ]);\n  if (parentObject !== undefined && fromDefaultCheckpointId != null) {\n    common.setValueByPath(\n      parentObject,\n      ['defaultCheckpointId'],\n      fromDefaultCheckpointId,\n    );\n  }\n\n  return toObject;\n}\n\nexport function updateModelParametersToMldev(\n  apiClient: ApiClient,\n  fromObject: types.UpdateModelParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromModel = common.getValueByPath(fromObject, ['model']);\n  if (fromModel != null) {\n    common.setValueByPath(\n      toObject,\n      ['_url', 'name'],\n      t.tModel(apiClient, fromModel),\n    );\n  }\n\n  const fromConfig = common.getValueByPath(fromObject, ['config']);\n  if (fromConfig != null) {\n    updateModelConfigToMldev(fromConfig, toObject);\n  }\n\n  return toObject;\n}\n\nexport function updateModelParametersToVertex(\n  apiClient: ApiClient,\n  fromObject: types.UpdateModelParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromModel = common.getValueByPath(fromObject, ['model']);\n  if (fromModel != null) {\n    common.setValueByPath(\n      toObject,\n      ['_url', 'model'],\n      t.tModel(apiClient, fromModel),\n    );\n  }\n\n  const fromConfig = common.getValueByPath(fromObject, ['config']);\n  if (fromConfig != null) {\n    updateModelConfigToVertex(fromConfig, toObject);\n  }\n\n  return toObject;\n}\n\nexport function upscaleImageAPIConfigInternalToVertex(\n  fromObject: _internal_types.UpscaleImageAPIConfigInternal,\n  parentObject: Record<string, unknown>,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n  if (parentObject !== undefined && fromOutputGcsUri != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'storageUri'],\n      fromOutputGcsUri,\n    );\n  }\n\n  const fromSafetyFilterLevel = common.getValueByPath(fromObject, [\n    'safetyFilterLevel',\n  ]);\n  if (parentObject !== undefined && fromSafetyFilterLevel != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'safetySetting'],\n      fromSafetyFilterLevel,\n    );\n  }\n\n  const fromPersonGeneration = common.getValueByPath(fromObject, [\n    'personGeneration',\n  ]);\n  if (parentObject !== undefined && fromPersonGeneration != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'personGeneration'],\n      fromPersonGeneration,\n    );\n  }\n\n  const fromIncludeRaiReason = common.getValueByPath(fromObject, [\n    'includeRaiReason',\n  ]);\n  if (parentObject !== undefined && fromIncludeRaiReason != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'includeRaiReason'],\n      fromIncludeRaiReason,\n    );\n  }\n\n  const fromOutputMimeType = common.getValueByPath(fromObject, [\n    'outputMimeType',\n  ]);\n  if (parentObject !== undefined && fromOutputMimeType != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'outputOptions', 'mimeType'],\n      fromOutputMimeType,\n    );\n  }\n\n  const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n    'outputCompressionQuality',\n  ]);\n  if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'outputOptions', 'compressionQuality'],\n      fromOutputCompressionQuality,\n    );\n  }\n\n  const fromEnhanceInputImage = common.getValueByPath(fromObject, [\n    'enhanceInputImage',\n  ]);\n  if (parentObject !== undefined && fromEnhanceInputImage != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'upscaleConfig', 'enhanceInputImage'],\n      fromEnhanceInputImage,\n    );\n  }\n\n  const fromImagePreservationFactor = common.getValueByPath(fromObject, [\n    'imagePreservationFactor',\n  ]);\n  if (parentObject !== undefined && fromImagePreservationFactor != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'upscaleConfig', 'imagePreservationFactor'],\n      fromImagePreservationFactor,\n    );\n  }\n\n  const fromLabels = common.getValueByPath(fromObject, ['labels']);\n  if (parentObject !== undefined && fromLabels != null) {\n    common.setValueByPath(parentObject, ['labels'], fromLabels);\n  }\n\n  const fromNumberOfImages = common.getValueByPath(fromObject, [\n    'numberOfImages',\n  ]);\n  if (parentObject !== undefined && fromNumberOfImages != null) {\n    common.setValueByPath(\n      parentObject,\n      ['parameters', 'sampleCount'],\n      fromNumberOfImages,\n    );\n  }\n\n  const fromMode = common.getValueByPath(fromObject, ['mode']);\n  if (parentObject !== undefined && fromMode != null) {\n    common.setValueByPath(parentObject, ['parameters', 'mode'], fromMode);\n  }\n\n  return toObject;\n}\n\nexport function upscaleImageAPIParametersInternalToVertex(\n  apiClient: ApiClient,\n  fromObject: _internal_types.UpscaleImageAPIParametersInternal,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromModel = common.getValueByPath(fromObject, ['model']);\n  if (fromModel != null) {\n    common.setValueByPath(\n      toObject,\n      ['_url', 'model'],\n      t.tModel(apiClient, fromModel),\n    );\n  }\n\n  const fromImage = common.getValueByPath(fromObject, ['image']);\n  if (fromImage != null) {\n    common.setValueByPath(\n      toObject,\n      ['instances[0]', 'image'],\n      imageToVertex(fromImage),\n    );\n  }\n\n  const fromUpscaleFactor = common.getValueByPath(fromObject, [\n    'upscaleFactor',\n  ]);\n  if (fromUpscaleFactor != null) {\n    common.setValueByPath(\n      toObject,\n      ['parameters', 'upscaleConfig', 'upscaleFactor'],\n      fromUpscaleFactor,\n    );\n  }\n\n  const fromConfig = common.getValueByPath(fromObject, ['config']);\n  if (fromConfig != null) {\n    upscaleImageAPIConfigInternalToVertex(fromConfig, toObject);\n  }\n\n  return toObject;\n}\n\nexport function upscaleImageResponseFromVertex(\n  fromObject: types.UpscaleImageResponse,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n    'sdkHttpResponse',\n  ]);\n  if (fromSdkHttpResponse != null) {\n    common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n  }\n\n  const fromGeneratedImages = common.getValueByPath(fromObject, [\n    'predictions',\n  ]);\n  if (fromGeneratedImages != null) {\n    let transformedList = fromGeneratedImages;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return generatedImageFromVertex(item);\n      });\n    }\n    common.setValueByPath(toObject, ['generatedImages'], transformedList);\n  }\n\n  return toObject;\n}\n\nexport function videoFromMldev(\n  fromObject: types.Video,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromUri = common.getValueByPath(fromObject, ['uri']);\n  if (fromUri != null) {\n    common.setValueByPath(toObject, ['uri'], fromUri);\n  }\n\n  const fromVideoBytes = common.getValueByPath(fromObject, ['encodedVideo']);\n  if (fromVideoBytes != null) {\n    common.setValueByPath(toObject, ['videoBytes'], t.tBytes(fromVideoBytes));\n  }\n\n  const fromMimeType = common.getValueByPath(fromObject, ['encoding']);\n  if (fromMimeType != null) {\n    common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n  }\n\n  return toObject;\n}\n\nexport function videoFromVertex(\n  fromObject: types.Video,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromUri = common.getValueByPath(fromObject, ['gcsUri']);\n  if (fromUri != null) {\n    common.setValueByPath(toObject, ['uri'], fromUri);\n  }\n\n  const fromVideoBytes = common.getValueByPath(fromObject, [\n    'bytesBase64Encoded',\n  ]);\n  if (fromVideoBytes != null) {\n    common.setValueByPath(toObject, ['videoBytes'], t.tBytes(fromVideoBytes));\n  }\n\n  const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n  if (fromMimeType != null) {\n    common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n  }\n\n  return toObject;\n}\n\nexport function videoGenerationMaskToVertex(\n  fromObject: types.VideoGenerationMask,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromImage = common.getValueByPath(fromObject, ['image']);\n  if (fromImage != null) {\n    common.setValueByPath(toObject, ['_self'], imageToVertex(fromImage));\n  }\n\n  const fromMaskMode = common.getValueByPath(fromObject, ['maskMode']);\n  if (fromMaskMode != null) {\n    common.setValueByPath(toObject, ['maskMode'], fromMaskMode);\n  }\n\n  return toObject;\n}\n\nexport function videoGenerationReferenceImageToMldev(\n  fromObject: types.VideoGenerationReferenceImage,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromImage = common.getValueByPath(fromObject, ['image']);\n  if (fromImage != null) {\n    common.setValueByPath(toObject, ['image'], imageToMldev(fromImage));\n  }\n\n  const fromReferenceType = common.getValueByPath(fromObject, [\n    'referenceType',\n  ]);\n  if (fromReferenceType != null) {\n    common.setValueByPath(toObject, ['referenceType'], fromReferenceType);\n  }\n\n  return toObject;\n}\n\nexport function videoGenerationReferenceImageToVertex(\n  fromObject: types.VideoGenerationReferenceImage,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromImage = common.getValueByPath(fromObject, ['image']);\n  if (fromImage != null) {\n    common.setValueByPath(toObject, ['image'], imageToVertex(fromImage));\n  }\n\n  const fromReferenceType = common.getValueByPath(fromObject, [\n    'referenceType',\n  ]);\n  if (fromReferenceType != null) {\n    common.setValueByPath(toObject, ['referenceType'], fromReferenceType);\n  }\n\n  return toObject;\n}\n\nexport function videoToMldev(fromObject: types.Video): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromUri = common.getValueByPath(fromObject, ['uri']);\n  if (fromUri != null) {\n    common.setValueByPath(toObject, ['uri'], fromUri);\n  }\n\n  const fromVideoBytes = common.getValueByPath(fromObject, ['videoBytes']);\n  if (fromVideoBytes != null) {\n    common.setValueByPath(toObject, ['encodedVideo'], t.tBytes(fromVideoBytes));\n  }\n\n  const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n  if (fromMimeType != null) {\n    common.setValueByPath(toObject, ['encoding'], fromMimeType);\n  }\n\n  return toObject;\n}\n\nexport function videoToVertex(\n  fromObject: types.Video,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromUri = common.getValueByPath(fromObject, ['uri']);\n  if (fromUri != null) {\n    common.setValueByPath(toObject, ['gcsUri'], fromUri);\n  }\n\n  const fromVideoBytes = common.getValueByPath(fromObject, ['videoBytes']);\n  if (fromVideoBytes != null) {\n    common.setValueByPath(\n      toObject,\n      ['bytesBase64Encoded'],\n      t.tBytes(fromVideoBytes),\n    );\n  }\n\n  const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n  if (fromMimeType != null) {\n    common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n  }\n\n  return toObject;\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport * as common from '../_common.js';\nimport type * as types from '../types.js';\n\nexport function createFileSearchStoreConfigToMldev(\n  fromObject: types.CreateFileSearchStoreConfig,\n  parentObject: Record<string, unknown>,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n  if (parentObject !== undefined && fromDisplayName != null) {\n    common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n  }\n\n  return toObject;\n}\n\nexport function createFileSearchStoreParametersToMldev(\n  fromObject: types.CreateFileSearchStoreParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromConfig = common.getValueByPath(fromObject, ['config']);\n  if (fromConfig != null) {\n    createFileSearchStoreConfigToMldev(fromConfig, toObject);\n  }\n\n  return toObject;\n}\n\nexport function deleteFileSearchStoreConfigToMldev(\n  fromObject: types.DeleteFileSearchStoreConfig,\n  parentObject: Record<string, unknown>,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromForce = common.getValueByPath(fromObject, ['force']);\n  if (parentObject !== undefined && fromForce != null) {\n    common.setValueByPath(parentObject, ['_query', 'force'], fromForce);\n  }\n\n  return toObject;\n}\n\nexport function deleteFileSearchStoreParametersToMldev(\n  fromObject: types.DeleteFileSearchStoreParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromName = common.getValueByPath(fromObject, ['name']);\n  if (fromName != null) {\n    common.setValueByPath(toObject, ['_url', 'name'], fromName);\n  }\n\n  const fromConfig = common.getValueByPath(fromObject, ['config']);\n  if (fromConfig != null) {\n    deleteFileSearchStoreConfigToMldev(fromConfig, toObject);\n  }\n\n  return toObject;\n}\n\nexport function getFileSearchStoreParametersToMldev(\n  fromObject: types.GetFileSearchStoreParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromName = common.getValueByPath(fromObject, ['name']);\n  if (fromName != null) {\n    common.setValueByPath(toObject, ['_url', 'name'], fromName);\n  }\n\n  return toObject;\n}\n\nexport function importFileConfigToMldev(\n  fromObject: types.ImportFileConfig,\n  parentObject: Record<string, unknown>,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromCustomMetadata = common.getValueByPath(fromObject, [\n    'customMetadata',\n  ]);\n  if (parentObject !== undefined && fromCustomMetadata != null) {\n    let transformedList = fromCustomMetadata;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return item;\n      });\n    }\n    common.setValueByPath(parentObject, ['customMetadata'], transformedList);\n  }\n\n  const fromChunkingConfig = common.getValueByPath(fromObject, [\n    'chunkingConfig',\n  ]);\n  if (parentObject !== undefined && fromChunkingConfig != null) {\n    common.setValueByPath(parentObject, ['chunkingConfig'], fromChunkingConfig);\n  }\n\n  return toObject;\n}\n\nexport function importFileOperationFromMldev(\n  fromObject: types.ImportFileOperation,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromName = common.getValueByPath(fromObject, ['name']);\n  if (fromName != null) {\n    common.setValueByPath(toObject, ['name'], fromName);\n  }\n\n  const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n  if (fromMetadata != null) {\n    common.setValueByPath(toObject, ['metadata'], fromMetadata);\n  }\n\n  const fromDone = common.getValueByPath(fromObject, ['done']);\n  if (fromDone != null) {\n    common.setValueByPath(toObject, ['done'], fromDone);\n  }\n\n  const fromError = common.getValueByPath(fromObject, ['error']);\n  if (fromError != null) {\n    common.setValueByPath(toObject, ['error'], fromError);\n  }\n\n  const fromResponse = common.getValueByPath(fromObject, ['response']);\n  if (fromResponse != null) {\n    common.setValueByPath(\n      toObject,\n      ['response'],\n      importFileResponseFromMldev(fromResponse),\n    );\n  }\n\n  return toObject;\n}\n\nexport function importFileParametersToMldev(\n  fromObject: types.ImportFileParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromFileSearchStoreName = common.getValueByPath(fromObject, [\n    'fileSearchStoreName',\n  ]);\n  if (fromFileSearchStoreName != null) {\n    common.setValueByPath(\n      toObject,\n      ['_url', 'file_search_store_name'],\n      fromFileSearchStoreName,\n    );\n  }\n\n  const fromFileName = common.getValueByPath(fromObject, ['fileName']);\n  if (fromFileName != null) {\n    common.setValueByPath(toObject, ['fileName'], fromFileName);\n  }\n\n  const fromConfig = common.getValueByPath(fromObject, ['config']);\n  if (fromConfig != null) {\n    importFileConfigToMldev(fromConfig, toObject);\n  }\n\n  return toObject;\n}\n\nexport function importFileResponseFromMldev(\n  fromObject: types.ImportFileResponse,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n    'sdkHttpResponse',\n  ]);\n  if (fromSdkHttpResponse != null) {\n    common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n  }\n\n  const fromParent = common.getValueByPath(fromObject, ['parent']);\n  if (fromParent != null) {\n    common.setValueByPath(toObject, ['parent'], fromParent);\n  }\n\n  const fromDocumentName = common.getValueByPath(fromObject, ['documentName']);\n  if (fromDocumentName != null) {\n    common.setValueByPath(toObject, ['documentName'], fromDocumentName);\n  }\n\n  return toObject;\n}\n\nexport function listFileSearchStoresConfigToMldev(\n  fromObject: types.ListFileSearchStoresConfig,\n  parentObject: Record<string, unknown>,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n  if (parentObject !== undefined && fromPageSize != null) {\n    common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n  }\n\n  const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n  if (parentObject !== undefined && fromPageToken != null) {\n    common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n  }\n\n  return toObject;\n}\n\nexport function listFileSearchStoresParametersToMldev(\n  fromObject: types.ListFileSearchStoresParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromConfig = common.getValueByPath(fromObject, ['config']);\n  if (fromConfig != null) {\n    listFileSearchStoresConfigToMldev(fromConfig, toObject);\n  }\n\n  return toObject;\n}\n\nexport function listFileSearchStoresResponseFromMldev(\n  fromObject: types.ListFileSearchStoresResponse,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n    'sdkHttpResponse',\n  ]);\n  if (fromSdkHttpResponse != null) {\n    common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n  }\n\n  const fromNextPageToken = common.getValueByPath(fromObject, [\n    'nextPageToken',\n  ]);\n  if (fromNextPageToken != null) {\n    common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n  }\n\n  const fromFileSearchStores = common.getValueByPath(fromObject, [\n    'fileSearchStores',\n  ]);\n  if (fromFileSearchStores != null) {\n    let transformedList = fromFileSearchStores;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return item;\n      });\n    }\n    common.setValueByPath(toObject, ['fileSearchStores'], transformedList);\n  }\n\n  return toObject;\n}\n\nexport function uploadToFileSearchStoreConfigToMldev(\n  fromObject: types.UploadToFileSearchStoreConfig,\n  parentObject: Record<string, unknown>,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n  if (parentObject !== undefined && fromMimeType != null) {\n    common.setValueByPath(parentObject, ['mimeType'], fromMimeType);\n  }\n\n  const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n  if (parentObject !== undefined && fromDisplayName != null) {\n    common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n  }\n\n  const fromCustomMetadata = common.getValueByPath(fromObject, [\n    'customMetadata',\n  ]);\n  if (parentObject !== undefined && fromCustomMetadata != null) {\n    let transformedList = fromCustomMetadata;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return item;\n      });\n    }\n    common.setValueByPath(parentObject, ['customMetadata'], transformedList);\n  }\n\n  const fromChunkingConfig = common.getValueByPath(fromObject, [\n    'chunkingConfig',\n  ]);\n  if (parentObject !== undefined && fromChunkingConfig != null) {\n    common.setValueByPath(parentObject, ['chunkingConfig'], fromChunkingConfig);\n  }\n\n  return toObject;\n}\n\nexport function uploadToFileSearchStoreParametersToMldev(\n  fromObject: types.UploadToFileSearchStoreParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromFileSearchStoreName = common.getValueByPath(fromObject, [\n    'fileSearchStoreName',\n  ]);\n  if (fromFileSearchStoreName != null) {\n    common.setValueByPath(\n      toObject,\n      ['_url', 'file_search_store_name'],\n      fromFileSearchStoreName,\n    );\n  }\n\n  const fromConfig = common.getValueByPath(fromObject, ['config']);\n  if (fromConfig != null) {\n    uploadToFileSearchStoreConfigToMldev(fromConfig, toObject);\n  }\n\n  return toObject;\n}\n\nexport function uploadToFileSearchStoreResumableResponseFromMldev(\n  fromObject: types.UploadToFileSearchStoreResumableResponse,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n    'sdkHttpResponse',\n  ]);\n  if (fromSdkHttpResponse != null) {\n    common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n  }\n\n  return toObject;\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {Auth} from './_auth.js';\nimport * as common from './_common.js';\nimport {Downloader} from './_downloader.js';\nimport {Uploader} from './_uploader.js';\nimport {uploadToFileSearchStoreConfigToMldev} from './converters/_filesearchstores_converters.js';\nimport {ApiError} from './errors.js';\nimport * as types from './types.js';\n\nconst CONTENT_TYPE_HEADER = 'Content-Type';\nconst SERVER_TIMEOUT_HEADER = 'X-Server-Timeout';\nconst USER_AGENT_HEADER = 'User-Agent';\nexport const GOOGLE_API_CLIENT_HEADER = 'x-goog-api-client';\nexport const SDK_VERSION = '1.33.0'; // x-release-please-version\nconst LIBRARY_LABEL = `google-genai-sdk/${SDK_VERSION}`;\nconst VERTEX_AI_API_DEFAULT_VERSION = 'v1beta1';\nconst GOOGLE_AI_API_DEFAULT_VERSION = 'v1beta';\n\n/**\n * Options for initializing the ApiClient. The ApiClient uses the parameters\n * for authentication purposes as well as to infer if SDK should send the\n * request to Vertex AI or Gemini API.\n */\nexport interface ApiClientInitOptions {\n  /**\n   * The object used for adding authentication headers to API requests.\n   */\n  auth: Auth;\n  /**\n   * The uploader to use for uploading files. This field is required for\n   * creating a client, will be set through the Node_client or Web_client.\n   */\n  uploader: Uploader;\n  /**\n   * Optional. The downloader to use for downloading files. This field is\n   * required for creating a client, will be set through the Node_client or\n   * Web_client.\n   */\n  downloader: Downloader;\n  /**\n   * Optional. The Google Cloud project ID for Vertex AI users.\n   * It is not the numeric project name.\n   * If not provided, SDK will try to resolve it from runtime environment.\n   */\n  project?: string;\n  /**\n   * Optional. The Google Cloud project location for Vertex AI users.\n   * If not provided, SDK will try to resolve it from runtime environment.\n   */\n  location?: string;\n  /**\n   * The API Key. This is required for Gemini API users.\n   */\n  apiKey?: string;\n  /**\n   * Optional. Set to true if you intend to call Vertex AI endpoints.\n   * If unset, default SDK behavior is to call Gemini API.\n   */\n  vertexai?: boolean;\n  /**\n   * Optional. The API version for the endpoint.\n   * If unset, SDK will choose a default api version.\n   */\n  apiVersion?: string;\n  /**\n   * Optional. A set of customizable configuration for HTTP requests.\n   */\n  httpOptions?: types.HttpOptions;\n  /**\n   * Optional. An extra string to append at the end of the User-Agent header.\n   *\n   * This can be used to e.g specify the runtime and its version.\n   */\n  userAgentExtra?: string;\n}\n\n/**\n * Represents the necessary information to send a request to an API endpoint.\n * This interface defines the structure for constructing and executing HTTP\n * requests.\n */\nexport interface HttpRequest {\n  /**\n   * URL path from the modules, this path is appended to the base API URL to\n   * form the complete request URL.\n   *\n   * If you wish to set full URL, use httpOptions.baseUrl instead. Example to\n   * set full URL in the request:\n   *\n   * const request: HttpRequest = {\n   *   path: '',\n   *   httpOptions: {\n   *     baseUrl: 'https://<custom-full-url>',\n   *     apiVersion: '',\n   *   },\n   *   httpMethod: 'GET',\n   * };\n   *\n   * The result URL will be: https://<custom-full-url>\n   *\n   */\n  path: string;\n  /**\n   * Optional query parameters to be appended to the request URL.\n   */\n  queryParams?: Record<string, string>;\n  /**\n   * Optional request body in json string or Blob format, GET request doesn't\n   * need a request body.\n   */\n  body?: string | Blob;\n  /**\n   * The HTTP method to be used for the request.\n   */\n  httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE';\n  /**\n   * Optional set of customizable configuration for HTTP requests.\n   */\n  httpOptions?: types.HttpOptions;\n  /**\n   * Optional abort signal which can be used to cancel the request.\n   */\n  abortSignal?: AbortSignal;\n}\n\n/**\n * The ApiClient class is used to send requests to the Gemini API or Vertex AI\n * endpoints.\n */\nexport class ApiClient {\n  readonly clientOptions: ApiClientInitOptions;\n\n  constructor(opts: ApiClientInitOptions) {\n    this.clientOptions = {\n      ...opts,\n      project: opts.project,\n      location: opts.location,\n      apiKey: opts.apiKey,\n      vertexai: opts.vertexai,\n    };\n\n    const initHttpOptions: types.HttpOptions = {};\n\n    if (this.clientOptions.vertexai) {\n      initHttpOptions.apiVersion =\n        this.clientOptions.apiVersion ?? VERTEX_AI_API_DEFAULT_VERSION;\n      initHttpOptions.baseUrl = this.baseUrlFromProjectLocation();\n      this.normalizeAuthParameters();\n    } else {\n      // Gemini API\n      initHttpOptions.apiVersion =\n        this.clientOptions.apiVersion ?? GOOGLE_AI_API_DEFAULT_VERSION;\n      initHttpOptions.baseUrl = `https://generativelanguage.googleapis.com/`;\n    }\n\n    initHttpOptions.headers = this.getDefaultHeaders();\n\n    this.clientOptions.httpOptions = initHttpOptions;\n\n    if (opts.httpOptions) {\n      this.clientOptions.httpOptions = this.patchHttpOptions(\n        initHttpOptions,\n        opts.httpOptions,\n      );\n    }\n  }\n\n  /**\n   * Determines the base URL for Vertex AI based on project and location.\n   * Uses the global endpoint if location is 'global' or if project/location\n   * are not specified (implying API key usage).\n   * @private\n   */\n  private baseUrlFromProjectLocation(): string {\n    if (\n      this.clientOptions.project &&\n      this.clientOptions.location &&\n      this.clientOptions.location !== 'global'\n    ) {\n      // Regional endpoint\n      return `https://${this.clientOptions.location}-aiplatform.googleapis.com/`;\n    }\n    // Global endpoint (covers 'global' location and API key usage)\n    return `https://aiplatform.googleapis.com/`;\n  }\n\n  /**\n   * Normalizes authentication parameters for Vertex AI.\n   * If project and location are provided, API key is cleared.\n   * If project and location are not provided (implying API key usage),\n   * project and location are cleared.\n   * @private\n   */\n  private normalizeAuthParameters(): void {\n    if (this.clientOptions.project && this.clientOptions.location) {\n      // Using project/location for auth, clear potential API key\n      this.clientOptions.apiKey = undefined;\n      return;\n    }\n    // Using API key for auth (or no auth provided yet), clear project/location\n    this.clientOptions.project = undefined;\n    this.clientOptions.location = undefined;\n  }\n\n  isVertexAI(): boolean {\n    return this.clientOptions.vertexai ?? false;\n  }\n\n  getProject() {\n    return this.clientOptions.project;\n  }\n\n  getLocation() {\n    return this.clientOptions.location;\n  }\n\n  getApiVersion() {\n    if (\n      this.clientOptions.httpOptions &&\n      this.clientOptions.httpOptions.apiVersion !== undefined\n    ) {\n      return this.clientOptions.httpOptions.apiVersion;\n    }\n    throw new Error('API version is not set.');\n  }\n\n  getBaseUrl() {\n    if (\n      this.clientOptions.httpOptions &&\n      this.clientOptions.httpOptions.baseUrl !== undefined\n    ) {\n      return this.clientOptions.httpOptions.baseUrl;\n    }\n    throw new Error('Base URL is not set.');\n  }\n\n  getRequestUrl() {\n    return this.getRequestUrlInternal(this.clientOptions.httpOptions);\n  }\n\n  getHeaders() {\n    if (\n      this.clientOptions.httpOptions &&\n      this.clientOptions.httpOptions.headers !== undefined\n    ) {\n      return this.clientOptions.httpOptions.headers;\n    } else {\n      throw new Error('Headers are not set.');\n    }\n  }\n\n  private getRequestUrlInternal(httpOptions?: types.HttpOptions) {\n    if (\n      !httpOptions ||\n      httpOptions.baseUrl === undefined ||\n      httpOptions.apiVersion === undefined\n    ) {\n      throw new Error('HTTP options are not correctly set.');\n    }\n    const baseUrl = httpOptions.baseUrl.endsWith('/')\n      ? httpOptions.baseUrl.slice(0, -1)\n      : httpOptions.baseUrl;\n    const urlElement: Array<string> = [baseUrl];\n    if (httpOptions.apiVersion && httpOptions.apiVersion !== '') {\n      urlElement.push(httpOptions.apiVersion);\n    }\n    return urlElement.join('/');\n  }\n\n  getBaseResourcePath() {\n    return `projects/${this.clientOptions.project}/locations/${\n      this.clientOptions.location\n    }`;\n  }\n\n  getApiKey() {\n    return this.clientOptions.apiKey;\n  }\n\n  getWebsocketBaseUrl() {\n    const baseUrl = this.getBaseUrl();\n    const urlParts = new URL(baseUrl);\n    urlParts.protocol = urlParts.protocol == 'http:' ? 'ws' : 'wss';\n    return urlParts.toString();\n  }\n\n  setBaseUrl(url: string) {\n    if (this.clientOptions.httpOptions) {\n      this.clientOptions.httpOptions.baseUrl = url;\n    } else {\n      throw new Error('HTTP options are not correctly set.');\n    }\n  }\n\n  private constructUrl(\n    path: string,\n    httpOptions: types.HttpOptions,\n    prependProjectLocation: boolean,\n  ): URL {\n    const urlElement: Array<string> = [this.getRequestUrlInternal(httpOptions)];\n    if (prependProjectLocation) {\n      urlElement.push(this.getBaseResourcePath());\n    }\n    if (path !== '') {\n      urlElement.push(path);\n    }\n    const url = new URL(`${urlElement.join('/')}`);\n\n    return url;\n  }\n\n  private shouldPrependVertexProjectPath(request: HttpRequest): boolean {\n    if (this.clientOptions.apiKey) {\n      return false;\n    }\n    if (!this.clientOptions.vertexai) {\n      return false;\n    }\n    if (request.path.startsWith('projects/')) {\n      // Assume the path already starts with\n      // `projects/<project>/location/<location>`.\n      return false;\n    }\n    if (\n      request.httpMethod === 'GET' &&\n      request.path.startsWith('publishers/google/models')\n    ) {\n      // These paths are used by Vertex's models.get and models.list\n      // calls. For base models Vertex does not accept a project/location\n      // prefix (for tuned model the prefix is required).\n      return false;\n    }\n    return true;\n  }\n\n  async request(request: HttpRequest): Promise<types.HttpResponse> {\n    let patchedHttpOptions = this.clientOptions.httpOptions!;\n    if (request.httpOptions) {\n      patchedHttpOptions = this.patchHttpOptions(\n        this.clientOptions.httpOptions!,\n        request.httpOptions,\n      );\n    }\n\n    const prependProjectLocation = this.shouldPrependVertexProjectPath(request);\n    const url = this.constructUrl(\n      request.path,\n      patchedHttpOptions,\n      prependProjectLocation,\n    );\n    if (request.queryParams) {\n      for (const [key, value] of Object.entries(request.queryParams)) {\n        url.searchParams.append(key, String(value));\n      }\n    }\n    let requestInit: RequestInit = {};\n    if (request.httpMethod === 'GET') {\n      if (request.body && request.body !== '{}') {\n        throw new Error(\n          'Request body should be empty for GET request, but got non empty request body',\n        );\n      }\n    } else {\n      requestInit.body = request.body;\n    }\n    requestInit = await this.includeExtraHttpOptionsToRequestInit(\n      requestInit,\n      patchedHttpOptions,\n      url.toString(),\n      request.abortSignal,\n    );\n    return this.unaryApiCall(url, requestInit, request.httpMethod);\n  }\n\n  private patchHttpOptions(\n    baseHttpOptions: types.HttpOptions,\n    requestHttpOptions: types.HttpOptions,\n  ): types.HttpOptions {\n    const patchedHttpOptions = JSON.parse(\n      JSON.stringify(baseHttpOptions),\n    ) as types.HttpOptions;\n\n    for (const [key, value] of Object.entries(requestHttpOptions)) {\n      // Records compile to objects.\n      if (typeof value === 'object') {\n        // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type\n        // because expression of type 'string' can't be used to index type\n        // 'HttpOptions'.\n        patchedHttpOptions[key] = {...patchedHttpOptions[key], ...value};\n      } else if (value !== undefined) {\n        // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type\n        // because expression of type 'string' can't be used to index type\n        // 'HttpOptions'.\n        patchedHttpOptions[key] = value;\n      }\n    }\n    return patchedHttpOptions;\n  }\n\n  async requestStream(\n    request: HttpRequest,\n  ): Promise<AsyncGenerator<types.HttpResponse>> {\n    let patchedHttpOptions = this.clientOptions.httpOptions!;\n    if (request.httpOptions) {\n      patchedHttpOptions = this.patchHttpOptions(\n        this.clientOptions.httpOptions!,\n        request.httpOptions,\n      );\n    }\n\n    const prependProjectLocation = this.shouldPrependVertexProjectPath(request);\n    const url = this.constructUrl(\n      request.path,\n      patchedHttpOptions,\n      prependProjectLocation,\n    );\n    if (!url.searchParams.has('alt') || url.searchParams.get('alt') !== 'sse') {\n      url.searchParams.set('alt', 'sse');\n    }\n    let requestInit: RequestInit = {};\n    requestInit.body = request.body;\n    requestInit = await this.includeExtraHttpOptionsToRequestInit(\n      requestInit,\n      patchedHttpOptions,\n      url.toString(),\n      request.abortSignal,\n    );\n    return this.streamApiCall(url, requestInit, request.httpMethod);\n  }\n\n  private async includeExtraHttpOptionsToRequestInit(\n    requestInit: RequestInit,\n    httpOptions: types.HttpOptions,\n    url: string,\n    abortSignal?: AbortSignal,\n  ): Promise<RequestInit> {\n    if ((httpOptions && httpOptions.timeout) || abortSignal) {\n      const abortController = new AbortController();\n      const signal = abortController.signal;\n      if (httpOptions.timeout && httpOptions?.timeout > 0) {\n        const timeoutHandle = setTimeout(\n          () => abortController.abort(),\n          httpOptions.timeout,\n        );\n        if (\n          timeoutHandle &&\n          typeof (timeoutHandle as unknown as NodeJS.Timeout).unref ===\n            'function'\n        ) {\n          // call unref to prevent nodejs process from hanging, see\n          // https://nodejs.org/api/timers.html#timeoutunref\n          timeoutHandle.unref();\n        }\n      }\n      if (abortSignal) {\n        abortSignal.addEventListener('abort', () => {\n          abortController.abort();\n        });\n      }\n      requestInit.signal = signal;\n    }\n    if (httpOptions && httpOptions.extraBody !== null) {\n      includeExtraBodyToRequestInit(\n        requestInit,\n        httpOptions.extraBody as Record<string, unknown>,\n      );\n    }\n    requestInit.headers = await this.getHeadersInternal(httpOptions, url);\n    return requestInit;\n  }\n\n  private async unaryApiCall(\n    url: URL,\n    requestInit: RequestInit,\n    httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE',\n  ): Promise<types.HttpResponse> {\n    return this.apiCall(url.toString(), {\n      ...requestInit,\n      method: httpMethod,\n    })\n      .then(async (response) => {\n        await throwErrorIfNotOK(response);\n        return new types.HttpResponse(response);\n      })\n      .catch((e) => {\n        if (e instanceof Error) {\n          throw e;\n        } else {\n          throw new Error(JSON.stringify(e));\n        }\n      });\n  }\n\n  private async streamApiCall(\n    url: URL,\n    requestInit: RequestInit,\n    httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE',\n  ): Promise<AsyncGenerator<types.HttpResponse>> {\n    return this.apiCall(url.toString(), {\n      ...requestInit,\n      method: httpMethod,\n    })\n      .then(async (response) => {\n        await throwErrorIfNotOK(response);\n        return this.processStreamResponse(response);\n      })\n      .catch((e) => {\n        if (e instanceof Error) {\n          throw e;\n        } else {\n          throw new Error(JSON.stringify(e));\n        }\n      });\n  }\n\n  async *processStreamResponse(\n    response: Response,\n  ): AsyncGenerator<types.HttpResponse> {\n    const reader = response?.body?.getReader();\n    const decoder = new TextDecoder('utf-8');\n    if (!reader) {\n      throw new Error('Response body is empty');\n    }\n\n    try {\n      let buffer = '';\n      const dataPrefix = 'data:';\n      const delimiters = ['\\n\\n', '\\r\\r', '\\r\\n\\r\\n'];\n\n      while (true) {\n        const {done, value} = await reader.read();\n        if (done) {\n          if (buffer.trim().length > 0) {\n            throw new Error('Incomplete JSON segment at the end');\n          }\n          break;\n        }\n        const chunkString = decoder.decode(value, {stream: true});\n\n        // Parse and throw an error if the chunk contains an error.\n        try {\n          const chunkJson = JSON.parse(chunkString) as Record<string, unknown>;\n          if ('error' in chunkJson) {\n            const errorJson = JSON.parse(\n              JSON.stringify(chunkJson['error']),\n            ) as Record<string, unknown>;\n            const status = errorJson['status'] as string;\n            const code = errorJson['code'] as number;\n            const errorMessage = `got status: ${status}. ${JSON.stringify(\n              chunkJson,\n            )}`;\n            if (code >= 400 && code < 600) {\n              const apiError = new ApiError({\n                message: errorMessage,\n                status: code,\n              });\n              throw apiError;\n            }\n          }\n        } catch (e: unknown) {\n          const error = e as Error;\n          if (error.name === 'ApiError') {\n            throw e;\n          }\n        }\n        buffer += chunkString;\n\n        let delimiterIndex = -1;\n        let delimiterLength = 0;\n\n        while (true) {\n          delimiterIndex = -1;\n          delimiterLength = 0;\n\n          for (const delimiter of delimiters) {\n            const index = buffer.indexOf(delimiter);\n            if (\n              index !== -1 &&\n              (delimiterIndex === -1 || index < delimiterIndex)\n            ) {\n              delimiterIndex = index;\n              delimiterLength = delimiter.length;\n            }\n          }\n\n          if (delimiterIndex === -1) {\n            break; // No complete event in buffer\n          }\n\n          const eventString = buffer.substring(0, delimiterIndex);\n          buffer = buffer.substring(delimiterIndex + delimiterLength);\n\n          const trimmedEvent = eventString.trim();\n\n          if (trimmedEvent.startsWith(dataPrefix)) {\n            const processedChunkString = trimmedEvent\n              .substring(dataPrefix.length)\n              .trim();\n            try {\n              const partialResponse = new Response(processedChunkString, {\n                headers: response?.headers,\n                status: response?.status,\n                statusText: response?.statusText,\n              });\n              yield new types.HttpResponse(partialResponse);\n            } catch (e) {\n              throw new Error(\n                `exception parsing stream chunk ${processedChunkString}. ${e}`,\n              );\n            }\n          }\n        }\n      }\n    } finally {\n      reader.releaseLock();\n    }\n  }\n  private async apiCall(\n    url: string,\n    requestInit: RequestInit,\n  ): Promise<Response> {\n    return fetch(url, requestInit).catch((e) => {\n      throw new Error(`exception ${e} sending request`);\n    });\n  }\n\n  getDefaultHeaders(): Record<string, string> {\n    const headers: Record<string, string> = {};\n\n    const versionHeaderValue =\n      LIBRARY_LABEL + ' ' + this.clientOptions.userAgentExtra;\n\n    headers[USER_AGENT_HEADER] = versionHeaderValue;\n    headers[GOOGLE_API_CLIENT_HEADER] = versionHeaderValue;\n    headers[CONTENT_TYPE_HEADER] = 'application/json';\n\n    return headers;\n  }\n\n  private async getHeadersInternal(\n    httpOptions: types.HttpOptions | undefined,\n    url: string,\n  ): Promise<Headers> {\n    const headers = new Headers();\n    if (httpOptions && httpOptions.headers) {\n      for (const [key, value] of Object.entries(httpOptions.headers)) {\n        headers.append(key, value);\n      }\n      // Append a timeout header if it is set, note that the timeout option is\n      // in milliseconds but the header is in seconds.\n      if (httpOptions.timeout && httpOptions.timeout > 0) {\n        headers.append(\n          SERVER_TIMEOUT_HEADER,\n          String(Math.ceil(httpOptions.timeout / 1000)),\n        );\n      }\n    }\n    await this.clientOptions.auth.addAuthHeaders(headers, url);\n    return headers;\n  }\n\n  private getFileName(file: string | Blob): string {\n    let fileName: string = '';\n    if (typeof file === 'string') {\n      fileName = file.replace(/[/\\\\]+$/, '');\n      fileName = fileName.split(/[/\\\\]/).pop() ?? '';\n    }\n    return fileName;\n  }\n\n  /**\n   * Uploads a file asynchronously using Gemini API only, this is not supported\n   * in Vertex AI.\n   *\n   * @param file The string path to the file to be uploaded or a Blob object.\n   * @param config Optional parameters specified in the `UploadFileConfig`\n   *     interface. @see {@link types.UploadFileConfig}\n   * @return A promise that resolves to a `File` object.\n   * @throws An error if called on a Vertex AI client.\n   * @throws An error if the `mimeType` is not provided and can not be inferred,\n   */\n  async uploadFile(\n    file: string | Blob,\n    config?: types.UploadFileConfig,\n  ): Promise<types.File> {\n    const fileToUpload: types.File = {};\n    if (config != null) {\n      fileToUpload.mimeType = config.mimeType;\n      fileToUpload.name = config.name;\n      fileToUpload.displayName = config.displayName;\n    }\n\n    if (fileToUpload.name && !fileToUpload.name.startsWith('files/')) {\n      fileToUpload.name = `files/${fileToUpload.name}`;\n    }\n\n    const uploader = this.clientOptions.uploader;\n    const fileStat = await uploader.stat(file);\n    fileToUpload.sizeBytes = String(fileStat.size);\n    const mimeType = config?.mimeType ?? fileStat.type;\n    if (mimeType === undefined || mimeType === '') {\n      throw new Error(\n        'Can not determine mimeType. Please provide mimeType in the config.',\n      );\n    }\n    fileToUpload.mimeType = mimeType;\n    const body: Record<string, unknown> = {\n      file: fileToUpload,\n    };\n    const fileName = this.getFileName(file);\n    const path = common.formatMap(\n      'upload/v1beta/files',\n      body['_url'] as Record<string, unknown>,\n    );\n    const uploadUrl = await this.fetchUploadUrl(\n      path,\n      fileToUpload.sizeBytes,\n      fileToUpload.mimeType,\n      fileName,\n      body,\n      config?.httpOptions,\n    );\n    return uploader.upload(file, uploadUrl, this);\n  }\n\n  /**\n   * Uploads a file to a given file search store asynchronously using Gemini API only, this is not supported\n   * in Vertex AI.\n   *\n   * @param fileSearchStoreName The name of the file search store to upload the file to.\n   * @param file The string path to the file to be uploaded or a Blob object.\n   * @param config Optional parameters specified in the `UploadFileConfig`\n   *     interface. @see {@link UploadFileConfig}\n   * @return A promise that resolves to a `File` object.\n   * @throws An error if called on a Vertex AI client.\n   * @throws An error if the `mimeType` is not provided and can not be inferred,\n   */\n  async uploadFileToFileSearchStore(\n    fileSearchStoreName: string,\n    file: string | Blob,\n    config?: types.UploadToFileSearchStoreConfig,\n  ): Promise<types.UploadToFileSearchStoreOperation> {\n    const uploader = this.clientOptions.uploader;\n    const fileStat = await uploader.stat(file);\n    const sizeBytes = String(fileStat.size);\n    const mimeType = config?.mimeType ?? fileStat.type;\n    if (mimeType === undefined || mimeType === '') {\n      throw new Error(\n        'Can not determine mimeType. Please provide mimeType in the config.',\n      );\n    }\n    const path = `upload/v1beta/${fileSearchStoreName}:uploadToFileSearchStore`;\n    const fileName = this.getFileName(file);\n    const body: Record<string, unknown> = {};\n    if (config != null) {\n      uploadToFileSearchStoreConfigToMldev(config, body);\n    }\n    const uploadUrl = await this.fetchUploadUrl(\n      path,\n      sizeBytes,\n      mimeType,\n      fileName,\n      body,\n      config?.httpOptions,\n    );\n    return uploader.uploadToFileSearchStore(file, uploadUrl, this);\n  }\n\n  /**\n   * Downloads a file asynchronously to the specified path.\n   *\n   * @params params - The parameters for the download request, see {@link\n   * types.DownloadFileParameters}\n   */\n  async downloadFile(params: types.DownloadFileParameters): Promise<void> {\n    const downloader = this.clientOptions.downloader;\n    await downloader.download(params, this);\n  }\n\n  private async fetchUploadUrl(\n    path: string,\n    sizeBytes: string,\n    mimeType: string,\n    fileName: string,\n    body: Record<string, unknown>,\n    configHttpOptions?: types.HttpOptions,\n  ): Promise<string> {\n    let httpOptions: types.HttpOptions = {};\n    if (configHttpOptions) {\n      httpOptions = configHttpOptions;\n    } else {\n      httpOptions = {\n        apiVersion: '', // api-version is set in the path.\n        headers: {\n          'Content-Type': 'application/json',\n          'X-Goog-Upload-Protocol': 'resumable',\n          'X-Goog-Upload-Command': 'start',\n          'X-Goog-Upload-Header-Content-Length': `${sizeBytes}`,\n          'X-Goog-Upload-Header-Content-Type': `${mimeType}`,\n          ...(fileName ? {'X-Goog-Upload-File-Name': fileName} : {}),\n        },\n      };\n    }\n\n    const httpResponse = await this.request({\n      path,\n      body: JSON.stringify(body),\n      httpMethod: 'POST',\n      httpOptions,\n    });\n\n    if (!httpResponse || !httpResponse?.headers) {\n      throw new Error(\n        'Server did not return an HttpResponse or the returned HttpResponse did not have headers.',\n      );\n    }\n\n    const uploadUrl: string | undefined =\n      httpResponse?.headers?.['x-goog-upload-url'];\n    if (uploadUrl === undefined) {\n      throw new Error(\n        'Failed to get upload url. Server did not return the x-google-upload-url in the headers',\n      );\n    }\n    return uploadUrl;\n  }\n}\n\nasync function throwErrorIfNotOK(response: Response | undefined) {\n  if (response === undefined) {\n    throw new Error('response is undefined');\n  }\n  if (!response.ok) {\n    const status: number = response.status;\n    let errorBody: Record<string, unknown>;\n    if (response.headers.get('content-type')?.includes('application/json')) {\n      errorBody = await response.json();\n    } else {\n      errorBody = {\n        error: {\n          message: await response.text(),\n          code: response.status,\n          status: response.statusText,\n        },\n      };\n    }\n    const errorMessage = JSON.stringify(errorBody);\n    if (status >= 400 && status < 600) {\n      const apiError = new ApiError({\n        message: errorMessage,\n        status: status,\n      });\n      throw apiError;\n    }\n    throw new Error(errorMessage);\n  }\n}\n\n/**\n * Recursively updates the `requestInit.body` with values from an `extraBody` object.\n *\n * If `requestInit.body` is a string, it's assumed to be JSON and will be parsed.\n * The `extraBody` is then deeply merged into this parsed object.\n * If `requestInit.body` is a Blob, `extraBody` will be ignored, and a warning logged,\n * as merging structured data into an opaque Blob is not supported.\n *\n * The function does not enforce that updated values from `extraBody` have the\n * same type as existing values in `requestInit.body`. Type mismatches during\n * the merge will result in a warning, but the value from `extraBody` will overwrite\n * the original. `extraBody` users are responsible for ensuring `extraBody` has the correct structure.\n *\n * @param requestInit The RequestInit object whose body will be updated.\n * @param extraBody The object containing updates to be merged into `requestInit.body`.\n */\nexport function includeExtraBodyToRequestInit(\n  requestInit: RequestInit,\n  extraBody: Record<string, unknown>,\n) {\n  if (!extraBody || Object.keys(extraBody).length === 0) {\n    return;\n  }\n\n  if (requestInit.body instanceof Blob) {\n    console.warn(\n      'includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.',\n    );\n    return;\n  }\n\n  let currentBodyObject: Record<string, unknown> = {};\n\n  // If adding new type to HttpRequest.body, please check the code below to\n  // see if we need to update the logic.\n  if (typeof requestInit.body === 'string' && requestInit.body.length > 0) {\n    try {\n      const parsedBody = JSON.parse(requestInit.body);\n      if (\n        typeof parsedBody === 'object' &&\n        parsedBody !== null &&\n        !Array.isArray(parsedBody)\n      ) {\n        currentBodyObject = parsedBody as Record<string, unknown>;\n      } else {\n        console.warn(\n          'includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.',\n        );\n        return;\n      }\n      /*  eslint-disable-next-line @typescript-eslint/no-unused-vars */\n    } catch (e) {\n      console.warn(\n        'includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.',\n      );\n      return;\n    }\n  }\n\n  function deepMerge(\n    target: Record<string, unknown>,\n    source: Record<string, unknown>,\n  ): Record<string, unknown> {\n    const output = {...target};\n    for (const key in source) {\n      if (Object.prototype.hasOwnProperty.call(source, key)) {\n        const sourceValue = source[key];\n        const targetValue = output[key];\n        if (\n          sourceValue &&\n          typeof sourceValue === 'object' &&\n          !Array.isArray(sourceValue) &&\n          targetValue &&\n          typeof targetValue === 'object' &&\n          !Array.isArray(targetValue)\n        ) {\n          output[key] = deepMerge(\n            targetValue as Record<string, unknown>,\n            sourceValue as Record<string, unknown>,\n          );\n        } else {\n          if (\n            targetValue &&\n            sourceValue &&\n            typeof targetValue !== typeof sourceValue\n          ) {\n            console.warn(\n              `includeExtraBodyToRequestInit:deepMerge: Type mismatch for key \"${key}\". Original type: ${typeof targetValue}, New type: ${typeof sourceValue}. Overwriting.`,\n            );\n          }\n          output[key] = sourceValue;\n        }\n      }\n    }\n    return output;\n  }\n\n  const mergedBody = deepMerge(currentBodyObject, extraBody);\n  requestInit.body = JSON.stringify(mergedBody);\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {Client as McpClient} from '@modelcontextprotocol/sdk/client/index.js';\nimport type {Tool as McpTool} from '@modelcontextprotocol/sdk/types.js';\n\nimport {GOOGLE_API_CLIENT_HEADER} from '../_api_client.js';\nimport {mcpToolsToGeminiTool} from '../_transformers.js';\nimport {\n  CallableTool,\n  CallableToolConfig,\n  FunctionCall,\n  Part,\n  Tool,\n  ToolListUnion,\n} from '../types.js';\n\n// TODO: b/416041229 - Determine how to retrieve the MCP package version.\nexport const MCP_LABEL = 'mcp_used/unknown';\n\n// Whether MCP tool usage is detected from mcpToTool. This is used for\n// telemetry.\nlet hasMcpToolUsageFromMcpToTool = false;\n\n// Checks whether the list of tools contains any MCP tools.\nexport function hasMcpToolUsage(tools: ToolListUnion): boolean {\n  for (const tool of tools) {\n    if (isMcpCallableTool(tool)) {\n      return true;\n    }\n    if (typeof tool === 'object' && 'inputSchema' in tool) {\n      return true;\n    }\n  }\n\n  return hasMcpToolUsageFromMcpToTool;\n}\n\n// Sets the MCP version label in the Google API client header.\nexport function setMcpUsageHeader(headers: Record<string, string>) {\n  const existingHeader = headers[GOOGLE_API_CLIENT_HEADER] ?? '';\n  headers[GOOGLE_API_CLIENT_HEADER] = (\n    existingHeader + ` ${MCP_LABEL}`\n  ).trimStart();\n}\n\n// Returns true if the object is a MCP CallableTool, otherwise false.\nfunction isMcpCallableTool(object: unknown): boolean {\n  return (\n    object !== null &&\n    typeof object === 'object' &&\n    object instanceof McpCallableTool\n  );\n}\n\n// List all tools from the MCP client.\nasync function* listAllTools(\n  mcpClient: McpClient,\n  maxTools: number = 100,\n): AsyncGenerator<McpTool> {\n  let cursor: string | undefined = undefined;\n  let numTools = 0;\n  while (numTools < maxTools) {\n    const t = await mcpClient.listTools({cursor});\n    for (const tool of t.tools) {\n      yield tool;\n      numTools++;\n    }\n    if (!t.nextCursor) {\n      break;\n    }\n    cursor = t.nextCursor;\n  }\n}\n\n/**\n * McpCallableTool can be used for model inference and invoking MCP clients with\n * given function call arguments.\n *\n * @experimental Built-in MCP support is an experimental feature, may change in future\n * versions.\n */\nexport class McpCallableTool implements CallableTool {\n  private readonly mcpClients;\n  private mcpTools: McpTool[] = [];\n  private functionNameToMcpClient: Record<string, McpClient> = {};\n  private readonly config: CallableToolConfig;\n\n  private constructor(\n    mcpClients: McpClient[] = [],\n    config: CallableToolConfig,\n  ) {\n    this.mcpClients = mcpClients;\n    this.config = config;\n  }\n\n  /**\n   * Creates a McpCallableTool.\n   */\n  public static create(\n    mcpClients: McpClient[],\n    config: CallableToolConfig,\n  ): McpCallableTool {\n    return new McpCallableTool(mcpClients, config);\n  }\n\n  /**\n   * Validates the function names are not duplicate and initialize the function\n   * name to MCP client mapping.\n   *\n   * @throws {Error} if the MCP tools from the MCP clients have duplicate tool\n   *     names.\n   */\n  async initialize() {\n    if (this.mcpTools.length > 0) {\n      return;\n    }\n\n    const functionMap: Record<string, McpClient> = {};\n    const mcpTools: McpTool[] = [];\n    for (const mcpClient of this.mcpClients) {\n      for await (const mcpTool of listAllTools(mcpClient)) {\n        mcpTools.push(mcpTool);\n        const mcpToolName = mcpTool.name as string;\n        if (functionMap[mcpToolName]) {\n          throw new Error(\n            `Duplicate function name ${\n              mcpToolName\n            } found in MCP tools. Please ensure function names are unique.`,\n          );\n        }\n        functionMap[mcpToolName] = mcpClient;\n      }\n    }\n    this.mcpTools = mcpTools;\n    this.functionNameToMcpClient = functionMap;\n  }\n\n  public async tool(): Promise<Tool> {\n    await this.initialize();\n    return mcpToolsToGeminiTool(this.mcpTools, this.config);\n  }\n\n  public async callTool(functionCalls: FunctionCall[]): Promise<Part[]> {\n    await this.initialize();\n    const functionCallResponseParts: Part[] = [];\n    for (const functionCall of functionCalls) {\n      if (functionCall.name! in this.functionNameToMcpClient) {\n        const mcpClient = this.functionNameToMcpClient[functionCall.name!];\n        let requestOptions = undefined;\n        // TODO: b/424238654 - Add support for finer grained timeout control.\n        if (this.config.timeout) {\n          requestOptions = {\n            timeout: this.config.timeout,\n          };\n        }\n        const callToolResponse = await mcpClient.callTool(\n          {\n            name: functionCall.name!,\n            arguments: functionCall.args,\n          },\n          // Set the result schema to undefined to allow MCP to rely on the\n          // default schema.\n          undefined,\n          requestOptions,\n        );\n        functionCallResponseParts.push({\n          functionResponse: {\n            name: functionCall.name,\n            response: callToolResponse.isError\n              ? {error: callToolResponse}\n              : (callToolResponse as Record<string, unknown>),\n          },\n        });\n      }\n    }\n    return functionCallResponseParts;\n  }\n}\n\nfunction isMcpClient(client: unknown): client is McpClient {\n  return (\n    client !== null &&\n    typeof client === 'object' &&\n    'listTools' in client &&\n    typeof client.listTools === 'function'\n  );\n}\n\n/**\n * Creates a McpCallableTool from MCP clients and an optional config.\n *\n * The callable tool can invoke the MCP clients with given function call\n * arguments. (often for automatic function calling).\n * Use the config to modify tool parameters such as behavior.\n *\n * @experimental Built-in MCP support is an experimental feature, may change in future\n * versions.\n */\nexport function mcpToTool(\n  ...args: [...McpClient[], CallableToolConfig | McpClient]\n): CallableTool {\n  // Set MCP usage for telemetry.\n  hasMcpToolUsageFromMcpToTool = true;\n  if (args.length === 0) {\n    throw new Error('No MCP clients provided');\n  }\n  const maybeConfig = args[args.length - 1];\n  if (isMcpClient(maybeConfig)) {\n    return McpCallableTool.create(args as McpClient[], {});\n  }\n  return McpCallableTool.create(\n    args.slice(0, args.length - 1) as McpClient[],\n    maybeConfig,\n  );\n}\n\n/**\n * Sets the MCP tool usage flag from calling mcpToTool. This is used for\n * telemetry.\n */\nexport function setMcpToolUsageFromMcpToTool(mcpToolUsage: boolean) {\n  hasMcpToolUsageFromMcpToTool = mcpToolUsage;\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Live music client.\n *\n * @experimental\n */\n\nimport {ApiClient} from './_api_client.js';\nimport {Auth} from './_auth.js';\nimport * as t from './_transformers.js';\nimport {WebSocket, WebSocketCallbacks, WebSocketFactory} from './_websocket.js';\nimport * as converters from './converters/_live_converters.js';\nimport * as types from './types.js';\n\n/**\n * Handles incoming messages from the WebSocket.\n *\n * @remarks\n * This function is responsible for parsing incoming messages, transforming them\n * into LiveMusicServerMessage, and then calling the onmessage callback.\n * Note that the first message which is received from the server is a\n * setupComplete message.\n *\n * @param apiClient The ApiClient instance.\n * @param onmessage The user-provided onmessage callback (if any).\n * @param event The MessageEvent from the WebSocket.\n */\nasync function handleWebSocketMessage(\n  apiClient: ApiClient,\n  onmessage: (msg: types.LiveMusicServerMessage) => void,\n  event: MessageEvent,\n): Promise<void> {\n  const serverMessage: types.LiveMusicServerMessage =\n    new types.LiveMusicServerMessage();\n  let data: types.LiveMusicServerMessage;\n  if (event.data instanceof Blob) {\n    data = JSON.parse(await event.data.text()) as types.LiveMusicServerMessage;\n  } else {\n    data = JSON.parse(event.data) as types.LiveMusicServerMessage;\n  }\n  Object.assign(serverMessage, data);\n  onmessage(serverMessage);\n}\n\n/**\n   LiveMusic class encapsulates the configuration for live music\n   generation via Lyria Live models.\n\n   @experimental\n  */\nexport class LiveMusic {\n  constructor(\n    private readonly apiClient: ApiClient,\n    private readonly auth: Auth,\n    private readonly webSocketFactory: WebSocketFactory,\n  ) {}\n\n  /**\n     Establishes a connection to the specified model and returns a\n     LiveMusicSession object representing that connection.\n\n     @experimental\n\n     @remarks\n\n     @param params - The parameters for establishing a connection to the model.\n     @return A live session.\n\n     @example\n     ```ts\n     let model = 'models/lyria-realtime-exp';\n     const session = await ai.live.music.connect({\n       model: model,\n       callbacks: {\n         onmessage: (e: MessageEvent) => {\n           console.log('Received message from the server: %s\\n', debug(e.data));\n         },\n         onerror: (e: ErrorEvent) => {\n           console.log('Error occurred: %s\\n', debug(e.error));\n         },\n         onclose: (e: CloseEvent) => {\n           console.log('Connection closed.');\n         },\n       },\n     });\n     ```\n    */\n  async connect(\n    params: types.LiveMusicConnectParameters,\n  ): Promise<LiveMusicSession> {\n    if (this.apiClient.isVertexAI()) {\n      throw new Error('Live music is not supported for Vertex AI.');\n    }\n    console.warn(\n      'Live music generation is experimental and may change in future versions.',\n    );\n\n    const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl();\n    const apiVersion = this.apiClient.getApiVersion();\n    const headers = mapToHeaders(this.apiClient.getDefaultHeaders());\n    const apiKey = this.apiClient.getApiKey();\n    const url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${\n      apiVersion\n    }.GenerativeService.BidiGenerateMusic?key=${apiKey}`;\n\n    let onopenResolve: (value: unknown) => void = () => {};\n    const onopenPromise = new Promise((resolve: (value: unknown) => void) => {\n      onopenResolve = resolve;\n    });\n\n    const callbacks: types.LiveMusicCallbacks = params.callbacks;\n\n    const onopenAwaitedCallback = function () {\n      onopenResolve({});\n    };\n\n    const apiClient = this.apiClient;\n    const websocketCallbacks: WebSocketCallbacks = {\n      onopen: onopenAwaitedCallback,\n      onmessage: (event: MessageEvent) => {\n        void handleWebSocketMessage(apiClient, callbacks.onmessage, event);\n      },\n      onerror:\n        callbacks?.onerror ??\n        function (e: ErrorEvent) {\n          void e;\n        },\n      onclose:\n        callbacks?.onclose ??\n        function (e: CloseEvent) {\n          void e;\n        },\n    };\n\n    const conn = this.webSocketFactory.create(\n      url,\n      headersToMap(headers),\n      websocketCallbacks,\n    );\n    conn.connect();\n    // Wait for the websocket to open before sending requests.\n    await onopenPromise;\n\n    const model = t.tModel(this.apiClient, params.model);\n    const setup = {model};\n    const clientMessage = {setup};\n    conn.send(JSON.stringify(clientMessage));\n\n    return new LiveMusicSession(conn, this.apiClient);\n  }\n}\n\n/**\n   Represents a connection to the API.\n\n   @experimental\n  */\nexport class LiveMusicSession {\n  constructor(\n    readonly conn: WebSocket,\n    private readonly apiClient: ApiClient,\n  ) {}\n\n  /**\n    Sets inputs to steer music generation. Updates the session's current\n    weighted prompts.\n\n    @param params - Contains one property, `weightedPrompts`.\n\n      - `weightedPrompts` to send to the model; weights are normalized to\n        sum to 1.0.\n\n    @experimental\n   */\n  async setWeightedPrompts(\n    params: types.LiveMusicSetWeightedPromptsParameters,\n  ) {\n    if (\n      !params.weightedPrompts ||\n      Object.keys(params.weightedPrompts).length === 0\n    ) {\n      throw new Error(\n        'Weighted prompts must be set and contain at least one entry.',\n      );\n    }\n    const clientContent =\n      converters.liveMusicSetWeightedPromptsParametersToMldev(params);\n    this.conn.send(JSON.stringify({clientContent}));\n  }\n\n  /**\n    Sets a configuration to the model. Updates the session's current\n    music generation config.\n\n    @param params - Contains one property, `musicGenerationConfig`.\n\n      - `musicGenerationConfig` to set in the model. Passing an empty or\n    undefined config to the model will reset the config to defaults.\n\n    @experimental\n   */\n  async setMusicGenerationConfig(params: types.LiveMusicSetConfigParameters) {\n    if (!params.musicGenerationConfig) {\n      params.musicGenerationConfig = {};\n    }\n    const setConfigParameters =\n      converters.liveMusicSetConfigParametersToMldev(params);\n    this.conn.send(JSON.stringify(setConfigParameters));\n  }\n\n  private sendPlaybackControl(playbackControl: types.LiveMusicPlaybackControl) {\n    const clientMessage = {playbackControl};\n    this.conn.send(JSON.stringify(clientMessage));\n  }\n\n  /**\n   * Start the music stream.\n   *\n   * @experimental\n   */\n  play() {\n    this.sendPlaybackControl(types.LiveMusicPlaybackControl.PLAY);\n  }\n\n  /**\n   * Temporarily halt the music stream. Use `play` to resume from the current\n   * position.\n   *\n   * @experimental\n   */\n  pause() {\n    this.sendPlaybackControl(types.LiveMusicPlaybackControl.PAUSE);\n  }\n\n  /**\n   * Stop the music stream and reset the state. Retains the current prompts\n   * and config.\n   *\n   * @experimental\n   */\n  stop() {\n    this.sendPlaybackControl(types.LiveMusicPlaybackControl.STOP);\n  }\n\n  /**\n   * Resets the context of the music generation without stopping it.\n   * Retains the current prompts and config.\n   *\n   * @experimental\n   */\n  resetContext() {\n    this.sendPlaybackControl(types.LiveMusicPlaybackControl.RESET_CONTEXT);\n  }\n\n  /**\n     Terminates the WebSocket connection.\n\n     @experimental\n   */\n  close() {\n    this.conn.close();\n  }\n}\n\n// Converts an headers object to a \"map\" object as expected by the WebSocket\n// constructor. We use this as the Auth interface works with Headers objects\n// while the WebSocket constructor takes a map.\nfunction headersToMap(headers: Headers): Record<string, string> {\n  const headerMap: Record<string, string> = {};\n  headers.forEach((value, key) => {\n    headerMap[key] = value;\n  });\n  return headerMap;\n}\n\n// Converts a \"map\" object to a headers object. We use this as the Auth\n// interface works with Headers objects while the API client default headers\n// returns a map.\nfunction mapToHeaders(map: Record<string, string>): Headers {\n  const headers = new Headers();\n  for (const [key, value] of Object.entries(map)) {\n    headers.append(key, value);\n  }\n  return headers;\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Live client.\n *\n * @experimental\n */\n\nimport {ApiClient} from './_api_client.js';\nimport {Auth} from './_auth.js';\nimport * as t from './_transformers.js';\nimport {WebSocket, WebSocketCallbacks, WebSocketFactory} from './_websocket.js';\nimport * as converters from './converters/_live_converters.js';\nimport {contentToMldev} from './converters/_models_converters.js';\nimport {hasMcpToolUsage, setMcpUsageHeader} from './mcp/_mcp.js';\nimport {LiveMusic} from './music.js';\nimport * as types from './types.js';\n\nconst FUNCTION_RESPONSE_REQUIRES_ID =\n  'FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.';\n\n/**\n * Handles incoming messages from the WebSocket.\n *\n * @remarks\n * This function is responsible for parsing incoming messages, transforming them\n * into LiveServerMessages, and then calling the onmessage callback. Note that\n * the first message which is received from the server is a setupComplete\n * message.\n *\n * @param apiClient The ApiClient instance.\n * @param onmessage The user-provided onmessage callback (if any).\n * @param event The MessageEvent from the WebSocket.\n */\nasync function handleWebSocketMessage(\n  apiClient: ApiClient,\n  onmessage: (msg: types.LiveServerMessage) => void,\n  event: MessageEvent,\n): Promise<void> {\n  const serverMessage: types.LiveServerMessage = new types.LiveServerMessage();\n  let jsonData: string;\n  if (event.data instanceof Blob) {\n    jsonData = await event.data.text();\n  } else if (event.data instanceof ArrayBuffer) {\n    jsonData = new TextDecoder().decode(event.data);\n  } else {\n    jsonData = event.data;\n  }\n\n  const data = JSON.parse(jsonData) as types.LiveServerMessage;\n\n  if (apiClient.isVertexAI()) {\n    const resp = converters.liveServerMessageFromVertex(data);\n    Object.assign(serverMessage, resp);\n  } else {\n    const resp = data;\n    Object.assign(serverMessage, resp);\n  }\n\n  onmessage(serverMessage);\n}\n\n/**\n   Live class encapsulates the configuration for live interaction with the\n   Generative Language API. It embeds ApiClient for general API settings.\n\n   @experimental\n  */\nexport class Live {\n  public readonly music: LiveMusic;\n\n  constructor(\n    private readonly apiClient: ApiClient,\n    private readonly auth: Auth,\n    private readonly webSocketFactory: WebSocketFactory,\n  ) {\n    this.music = new LiveMusic(\n      this.apiClient,\n      this.auth,\n      this.webSocketFactory,\n    );\n  }\n\n  /**\n     Establishes a connection to the specified model with the given\n     configuration and returns a Session object representing that connection.\n\n     @experimental Built-in MCP support is an experimental feature, may change in\n     future versions.\n\n     @remarks\n\n     @param params - The parameters for establishing a connection to the model.\n     @return A live session.\n\n     @example\n     ```ts\n     let model: string;\n     if (GOOGLE_GENAI_USE_VERTEXAI) {\n       model = 'gemini-2.0-flash-live-preview-04-09';\n     } else {\n       model = 'gemini-live-2.5-flash-preview';\n     }\n     const session = await ai.live.connect({\n       model: model,\n       config: {\n         responseModalities: [Modality.AUDIO],\n       },\n       callbacks: {\n         onopen: () => {\n           console.log('Connected to the socket.');\n         },\n         onmessage: (e: MessageEvent) => {\n           console.log('Received message from the server: %s\\n', debug(e.data));\n         },\n         onerror: (e: ErrorEvent) => {\n           console.log('Error occurred: %s\\n', debug(e.error));\n         },\n         onclose: (e: CloseEvent) => {\n           console.log('Connection closed.');\n         },\n       },\n     });\n     ```\n    */\n  async connect(params: types.LiveConnectParameters): Promise<Session> {\n    // TODO: b/404946746 - Support per request HTTP options.\n    if (params.config && params.config.httpOptions) {\n      throw new Error(\n        'The Live module does not support httpOptions at request-level in' +\n          ' LiveConnectConfig yet. Please use the client-level httpOptions' +\n          ' configuration instead.',\n      );\n    }\n    const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl();\n    const apiVersion = this.apiClient.getApiVersion();\n    let url: string;\n    const clientHeaders = this.apiClient.getHeaders();\n    if (\n      params.config &&\n      params.config.tools &&\n      hasMcpToolUsage(params.config.tools)\n    ) {\n      setMcpUsageHeader(clientHeaders);\n    }\n    const headers = mapToHeaders(clientHeaders);\n    if (this.apiClient.isVertexAI()) {\n      url = `${websocketBaseUrl}/ws/google.cloud.aiplatform.${\n        apiVersion\n      }.LlmBidiService/BidiGenerateContent`;\n      await this.auth.addAuthHeaders(headers, url);\n    } else {\n      const apiKey = this.apiClient.getApiKey();\n\n      let method = 'BidiGenerateContent';\n      let keyName = 'key';\n      if (apiKey?.startsWith('auth_tokens/')) {\n        console.warn(\n          'Warning: Ephemeral token support is experimental and may change in future versions.',\n        );\n        if (apiVersion !== 'v1alpha') {\n          console.warn(\n            \"Warning: The SDK's ephemeral token support is in v1alpha only. Please use const ai = new GoogleGenAI({apiKey: token.name, httpOptions: { apiVersion: 'v1alpha' }}); before session connection.\",\n          );\n        }\n        method = 'BidiGenerateContentConstrained';\n        keyName = 'access_token';\n      }\n\n      url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${\n        apiVersion\n      }.GenerativeService.${method}?${keyName}=${apiKey}`;\n    }\n\n    let onopenResolve: (value: unknown) => void = () => {};\n    const onopenPromise = new Promise((resolve: (value: unknown) => void) => {\n      onopenResolve = resolve;\n    });\n\n    const callbacks: types.LiveCallbacks = params.callbacks;\n\n    const onopenAwaitedCallback = function () {\n      callbacks?.onopen?.();\n      onopenResolve({});\n    };\n\n    const apiClient = this.apiClient;\n\n    const websocketCallbacks: WebSocketCallbacks = {\n      onopen: onopenAwaitedCallback,\n      onmessage: (event: MessageEvent) => {\n        void handleWebSocketMessage(apiClient, callbacks.onmessage, event);\n      },\n      onerror:\n        callbacks?.onerror ??\n        function (e: ErrorEvent) {\n          void e;\n        },\n      onclose:\n        callbacks?.onclose ??\n        function (e: CloseEvent) {\n          void e;\n        },\n    };\n\n    const conn = this.webSocketFactory.create(\n      url,\n      headersToMap(headers),\n      websocketCallbacks,\n    );\n    conn.connect();\n    // Wait for the websocket to open before sending requests.\n    await onopenPromise;\n\n    let transformedModel = t.tModel(this.apiClient, params.model);\n    if (\n      this.apiClient.isVertexAI() &&\n      transformedModel.startsWith('publishers/')\n    ) {\n      const project = this.apiClient.getProject();\n      const location = this.apiClient.getLocation();\n      transformedModel =\n        `projects/${project}/locations/${location}/` + transformedModel;\n    }\n\n    let clientMessage: Record<string, unknown> = {};\n\n    if (\n      this.apiClient.isVertexAI() &&\n      params.config?.responseModalities === undefined\n    ) {\n      // Set default to AUDIO to align with MLDev API.\n      if (params.config === undefined) {\n        params.config = {responseModalities: [types.Modality.AUDIO]};\n      } else {\n        params.config.responseModalities = [types.Modality.AUDIO];\n      }\n    }\n    if (params.config?.generationConfig) {\n      // Raise deprecation warning for generationConfig.\n      console.warn(\n        'Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. This will become an error in a future version (not before Q3 2025).',\n      );\n    }\n    const inputTools = params.config?.tools ?? [];\n    const convertedTools: types.Tool[] = [];\n    for (const tool of inputTools) {\n      if (this.isCallableTool(tool)) {\n        const callableTool = tool as types.CallableTool;\n        convertedTools.push(await callableTool.tool());\n      } else {\n        convertedTools.push(tool as types.Tool);\n      }\n    }\n    if (convertedTools.length > 0) {\n      params.config!.tools = convertedTools;\n    }\n    const liveConnectParameters: types.LiveConnectParameters = {\n      model: transformedModel,\n      config: params.config,\n      callbacks: params.callbacks,\n    };\n    if (this.apiClient.isVertexAI()) {\n      clientMessage = converters.liveConnectParametersToVertex(\n        this.apiClient,\n        liveConnectParameters,\n      );\n    } else {\n      clientMessage = converters.liveConnectParametersToMldev(\n        this.apiClient,\n        liveConnectParameters,\n      );\n    }\n    delete clientMessage['config'];\n    conn.send(JSON.stringify(clientMessage));\n    return new Session(conn, this.apiClient);\n  }\n\n  // TODO: b/416041229 - Abstract this method to a common place.\n  private isCallableTool(tool: types.ToolUnion): boolean {\n    return 'callTool' in tool && typeof tool.callTool === 'function';\n  }\n}\n\nconst defaultLiveSendClientContentParamerters: types.LiveSendClientContentParameters =\n  {\n    turnComplete: true,\n  };\n\n/**\n   Represents a connection to the API.\n\n   @experimental\n  */\nexport class Session {\n  constructor(\n    readonly conn: WebSocket,\n    private readonly apiClient: ApiClient,\n  ) {}\n\n  private tLiveClientContent(\n    apiClient: ApiClient,\n    params: types.LiveSendClientContentParameters,\n  ): types.LiveClientMessage {\n    if (params.turns !== null && params.turns !== undefined) {\n      let contents: types.Content[] = [];\n      try {\n        contents = t.tContents(params.turns as types.ContentListUnion);\n        if (!apiClient.isVertexAI()) {\n          contents = contents.map((item) => contentToMldev(item));\n        }\n      } catch {\n        throw new Error(\n          `Failed to parse client content \"turns\", type: '${typeof params.turns}'`,\n        );\n      }\n      return {\n        clientContent: {turns: contents, turnComplete: params.turnComplete},\n      };\n    }\n\n    return {\n      clientContent: {turnComplete: params.turnComplete},\n    };\n  }\n\n  private tLiveClienttToolResponse(\n    apiClient: ApiClient,\n    params: types.LiveSendToolResponseParameters,\n  ): types.LiveClientMessage {\n    let functionResponses: types.FunctionResponse[] = [];\n\n    if (params.functionResponses == null) {\n      throw new Error('functionResponses is required.');\n    }\n\n    if (!Array.isArray(params.functionResponses)) {\n      functionResponses = [params.functionResponses];\n    } else {\n      functionResponses = params.functionResponses;\n    }\n\n    if (functionResponses.length === 0) {\n      throw new Error('functionResponses is required.');\n    }\n\n    for (const functionResponse of functionResponses) {\n      if (\n        typeof functionResponse !== 'object' ||\n        functionResponse === null ||\n        !('name' in functionResponse) ||\n        !('response' in functionResponse)\n      ) {\n        throw new Error(\n          `Could not parse function response, type '${typeof functionResponse}'.`,\n        );\n      }\n      if (!apiClient.isVertexAI() && !('id' in functionResponse)) {\n        throw new Error(FUNCTION_RESPONSE_REQUIRES_ID);\n      }\n    }\n\n    const clientMessage: types.LiveClientMessage = {\n      toolResponse: {functionResponses: functionResponses},\n    };\n    return clientMessage;\n  }\n\n  /**\n    Send a message over the established connection.\n\n    @param params - Contains two **optional** properties, `turns` and\n        `turnComplete`.\n\n      - `turns` will be converted to a `Content[]`\n      - `turnComplete: true` [default] indicates that you are done sending\n        content and expect a response. If `turnComplete: false`, the server\n        will wait for additional messages before starting generation.\n\n    @experimental\n\n    @remarks\n    There are two ways to send messages to the live API:\n    `sendClientContent` and `sendRealtimeInput`.\n\n    `sendClientContent` messages are added to the model context **in order**.\n    Having a conversation using `sendClientContent` messages is roughly\n    equivalent to using the `Chat.sendMessageStream`, except that the state of\n    the `chat` history is stored on the API server instead of locally.\n\n    Because of `sendClientContent`'s order guarantee, the model cannot respons\n    as quickly to `sendClientContent` messages as to `sendRealtimeInput`\n    messages. This makes the biggest difference when sending objects that have\n    significant preprocessing time (typically images).\n\n    The `sendClientContent` message sends a `Content[]`\n    which has more options than the `Blob` sent by `sendRealtimeInput`.\n\n    So the main use-cases for `sendClientContent` over `sendRealtimeInput` are:\n\n    - Sending anything that can't be represented as a `Blob` (text,\n    `sendClientContent({turns=\"Hello?\"}`)).\n    - Managing turns when not using audio input and voice activity detection.\n      (`sendClientContent({turnComplete:true})` or the short form\n    `sendClientContent()`)\n    - Prefilling a conversation context\n      ```\n      sendClientContent({\n          turns: [\n            Content({role:user, parts:...}),\n            Content({role:user, parts:...}),\n            ...\n          ]\n      })\n      ```\n    @experimental\n   */\n  sendClientContent(params: types.LiveSendClientContentParameters) {\n    params = {\n      ...defaultLiveSendClientContentParamerters,\n      ...params,\n    };\n\n    const clientMessage: types.LiveClientMessage = this.tLiveClientContent(\n      this.apiClient,\n      params,\n    );\n    this.conn.send(JSON.stringify(clientMessage));\n  }\n\n  /**\n    Send a realtime message over the established connection.\n\n    @param params - Contains one property, `media`.\n\n      - `media` will be converted to a `Blob`\n\n    @experimental\n\n    @remarks\n    Use `sendRealtimeInput` for realtime audio chunks and video frames (images).\n\n    With `sendRealtimeInput` the api will respond to audio automatically\n    based on voice activity detection (VAD).\n\n    `sendRealtimeInput` is optimized for responsivness at the expense of\n    deterministic ordering guarantees. Audio and video tokens are to the\n    context when they become available.\n\n    Note: The Call signature expects a `Blob` object, but only a subset\n    of audio and image mimetypes are allowed.\n   */\n  sendRealtimeInput(params: types.LiveSendRealtimeInputParameters) {\n    let clientMessage: types.LiveClientMessage = {};\n\n    if (this.apiClient.isVertexAI()) {\n      clientMessage = {\n        'realtimeInput':\n          converters.liveSendRealtimeInputParametersToVertex(params),\n      };\n    } else {\n      clientMessage = {\n        'realtimeInput':\n          converters.liveSendRealtimeInputParametersToMldev(params),\n      };\n    }\n    this.conn.send(JSON.stringify(clientMessage));\n  }\n\n  /**\n    Send a function response message over the established connection.\n\n    @param params - Contains property `functionResponses`.\n\n      - `functionResponses` will be converted to a `functionResponses[]`\n\n    @remarks\n    Use `sendFunctionResponse` to reply to `LiveServerToolCall` from the server.\n\n    Use {@link types.LiveConnectConfig#tools} to configure the callable functions.\n\n    @experimental\n   */\n  sendToolResponse(params: types.LiveSendToolResponseParameters) {\n    if (params.functionResponses == null) {\n      throw new Error('Tool response parameters are required.');\n    }\n\n    const clientMessage: types.LiveClientMessage =\n      this.tLiveClienttToolResponse(this.apiClient, params);\n    this.conn.send(JSON.stringify(clientMessage));\n  }\n\n  /**\n     Terminates the WebSocket connection.\n\n     @experimental\n\n     @example\n     ```ts\n     let model: string;\n     if (GOOGLE_GENAI_USE_VERTEXAI) {\n       model = 'gemini-2.0-flash-live-preview-04-09';\n     } else {\n       model = 'gemini-live-2.5-flash-preview';\n     }\n     const session = await ai.live.connect({\n       model: model,\n       config: {\n         responseModalities: [Modality.AUDIO],\n       }\n     });\n\n     session.close();\n     ```\n   */\n  close() {\n    this.conn.close();\n  }\n}\n\n// Converts an headers object to a \"map\" object as expected by the WebSocket\n// constructor. We use this as the Auth interface works with Headers objects\n// while the WebSocket constructor takes a map.\nfunction headersToMap(headers: Headers): Record<string, string> {\n  const headerMap: Record<string, string> = {};\n  headers.forEach((value, key) => {\n    headerMap[key] = value;\n  });\n  return headerMap;\n}\n\n// Converts a \"map\" object to a headers object. We use this as the Auth\n// interface works with Headers objects while the API client default headers\n// returns a map.\nfunction mapToHeaders(map: Record<string, string>): Headers {\n  const headers = new Headers();\n  for (const [key, value] of Object.entries(map)) {\n    headers.append(key, value);\n  }\n  return headers;\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport * as types from './types.js';\n\nexport const DEFAULT_MAX_REMOTE_CALLS = 10;\n\n/** Returns whether automatic function calling is disabled. */\nexport function shouldDisableAfc(\n  config: types.GenerateContentConfig | undefined,\n): boolean {\n  if (config?.automaticFunctionCalling?.disable) {\n    return true;\n  }\n\n  let callableToolsPresent = false;\n  for (const tool of config?.tools ?? []) {\n    if (isCallableTool(tool)) {\n      callableToolsPresent = true;\n      break;\n    }\n  }\n  if (!callableToolsPresent) {\n    return true;\n  }\n\n  const maxCalls = config?.automaticFunctionCalling?.maximumRemoteCalls;\n  if (\n    (maxCalls && (maxCalls < 0 || !Number.isInteger(maxCalls))) ||\n    maxCalls == 0\n  ) {\n    console.warn(\n      'Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a valid integer value greater than 0. maximumRemoteCalls provided:',\n      maxCalls,\n    );\n    return true;\n  }\n  return false;\n}\n\nexport function isCallableTool(tool: types.ToolUnion): boolean {\n  return 'callTool' in tool && typeof tool.callTool === 'function';\n}\n\n// Checks whether the list of tools contains any CallableTools. Will return true\n// if there is at least one CallableTool.\nexport function hasCallableTools(\n  params: types.GenerateContentParameters,\n): boolean {\n  return params.config?.tools?.some((tool) => isCallableTool(tool)) ?? false;\n}\n\n/**\n * Returns the indexes of the tools that are not compatible with AFC.\n */\nexport function findAfcIncompatibleToolIndexes(\n  params?: types.GenerateContentParameters,\n): number[] {\n  // Use number[] for an array of numbers in TypeScript\n  const afcIncompatibleToolIndexes: number[] = [];\n  if (!params?.config?.tools) {\n    return afcIncompatibleToolIndexes;\n  }\n  params.config.tools.forEach((tool, index) => {\n    if (isCallableTool(tool)) {\n      return;\n    }\n    const geminiTool = tool as types.Tool;\n    if (\n      geminiTool.functionDeclarations &&\n      geminiTool.functionDeclarations.length > 0\n    ) {\n      afcIncompatibleToolIndexes.push(index);\n    }\n  });\n\n  return afcIncompatibleToolIndexes;\n}\n\n/**\n * Returns whether to append automatic function calling history to the\n * response.\n */\nexport function shouldAppendAfcHistory(\n  config: types.GenerateContentConfig | undefined,\n): boolean {\n  return !config?.automaticFunctionCalling?.ignoreCallHistory;\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport * as afc from './_afc.js';\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as _internal_types from './_internal_types.js';\nimport {tContents} from './_transformers.js';\nimport * as converters from './converters/_models_converters.js';\nimport * as mcp from './mcp/_mcp.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Models extends BaseModule {\n  constructor(private readonly apiClient: ApiClient) {\n    super();\n  }\n\n  /**\n   * Makes an API request to generate content with a given model.\n   *\n   * For the `model` parameter, supported formats for Vertex AI API include:\n   * - The Gemini model ID, for example: 'gemini-2.0-flash'\n   * - The full resource name starts with 'projects/', for example:\n   *  'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash'\n   * - The partial resource name with 'publishers/', for example:\n   *  'publishers/google/models/gemini-2.0-flash' or\n   *  'publishers/meta/models/llama-3.1-405b-instruct-maas'\n   * - `/` separated publisher and model name, for example:\n   * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas'\n   *\n   * For the `model` parameter, supported formats for Gemini API include:\n   * - The Gemini model ID, for example: 'gemini-2.0-flash'\n   * - The model name starts with 'models/', for example:\n   *  'models/gemini-2.0-flash'\n   * - For tuned models, the model name starts with 'tunedModels/',\n   * for example:\n   * 'tunedModels/1234567890123456789'\n   *\n   * Some models support multimodal input and output.\n   *\n   * @param params - The parameters for generating content.\n   * @return The response from generating content.\n   *\n   * @example\n   * ```ts\n   * const response = await ai.models.generateContent({\n   *   model: 'gemini-2.0-flash',\n   *   contents: 'why is the sky blue?',\n   *   config: {\n   *     candidateCount: 2,\n   *   }\n   * });\n   * console.log(response);\n   * ```\n   */\n  generateContent = async (\n    params: types.GenerateContentParameters,\n  ): Promise<types.GenerateContentResponse> => {\n    const transformedParams = await this.processParamsMaybeAddMcpUsage(params);\n    this.maybeMoveToResponseJsonSchem(params);\n    if (!afc.hasCallableTools(params) || afc.shouldDisableAfc(params.config)) {\n      return await this.generateContentInternal(transformedParams);\n    }\n\n    const incompatibleToolIndexes = afc.findAfcIncompatibleToolIndexes(params);\n    if (incompatibleToolIndexes.length > 0) {\n      const formattedIndexes = incompatibleToolIndexes\n        .map((index: number) => `tools[${index}]`)\n        .join(', ');\n      throw new Error(\n        `Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations is not yet supported. Incompatible tools found at ${formattedIndexes}.`,\n      );\n    }\n\n    let response: types.GenerateContentResponse;\n    let functionResponseContent: types.Content;\n    const automaticFunctionCallingHistory: types.Content[] = tContents(\n      transformedParams.contents,\n    );\n    const maxRemoteCalls =\n      transformedParams.config?.automaticFunctionCalling?.maximumRemoteCalls ??\n      afc.DEFAULT_MAX_REMOTE_CALLS;\n    let remoteCalls = 0;\n    while (remoteCalls < maxRemoteCalls) {\n      response = await this.generateContentInternal(transformedParams);\n      if (!response.functionCalls || response.functionCalls!.length === 0) {\n        break;\n      }\n\n      const responseContent: types.Content = response.candidates![0].content!;\n      const functionResponseParts: types.Part[] = [];\n      for (const tool of params.config?.tools ?? []) {\n        if (afc.isCallableTool(tool)) {\n          const callableTool = tool as types.CallableTool;\n          const parts = await callableTool.callTool(response.functionCalls!);\n          functionResponseParts.push(...parts);\n        }\n      }\n\n      remoteCalls++;\n\n      functionResponseContent = {\n        role: 'user',\n        parts: functionResponseParts,\n      };\n\n      transformedParams.contents = tContents(transformedParams.contents);\n      (transformedParams.contents as types.Content[]).push(responseContent);\n      (transformedParams.contents as types.Content[]).push(\n        functionResponseContent,\n      );\n\n      if (afc.shouldAppendAfcHistory(transformedParams.config)) {\n        automaticFunctionCallingHistory.push(responseContent);\n        automaticFunctionCallingHistory.push(functionResponseContent);\n      }\n    }\n    if (afc.shouldAppendAfcHistory(transformedParams.config)) {\n      response!.automaticFunctionCallingHistory =\n        automaticFunctionCallingHistory;\n    }\n    return response!;\n  };\n\n  /**\n   * This logic is needed for GenerateContentConfig only.\n   * Previously we made GenerateContentConfig.responseSchema field to accept\n   * unknown. Since v1.9.0, we switch to use backend JSON schema support.\n   * To maintain backward compatibility, we move the data that was treated as\n   * JSON schema from the responseSchema field to the responseJsonSchema field.\n   */\n  private maybeMoveToResponseJsonSchem(\n    params: types.GenerateContentParameters,\n  ): void {\n    if (params.config && params.config.responseSchema) {\n      if (!params.config.responseJsonSchema) {\n        if (Object.keys(params.config.responseSchema).includes('$schema')) {\n          params.config.responseJsonSchema = params.config.responseSchema;\n          delete params.config.responseSchema;\n        }\n      }\n    }\n    return;\n  }\n\n  /**\n   * Makes an API request to generate content with a given model and yields the\n   * response in chunks.\n   *\n   * For the `model` parameter, supported formats for Vertex AI API include:\n   * - The Gemini model ID, for example: 'gemini-2.0-flash'\n   * - The full resource name starts with 'projects/', for example:\n   *  'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash'\n   * - The partial resource name with 'publishers/', for example:\n   *  'publishers/google/models/gemini-2.0-flash' or\n   *  'publishers/meta/models/llama-3.1-405b-instruct-maas'\n   * - `/` separated publisher and model name, for example:\n   * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas'\n   *\n   * For the `model` parameter, supported formats for Gemini API include:\n   * - The Gemini model ID, for example: 'gemini-2.0-flash'\n   * - The model name starts with 'models/', for example:\n   *  'models/gemini-2.0-flash'\n   * - For tuned models, the model name starts with 'tunedModels/',\n   * for example:\n   *  'tunedModels/1234567890123456789'\n   *\n   * Some models support multimodal input and output.\n   *\n   * @param params - The parameters for generating content with streaming response.\n   * @return The response from generating content.\n   *\n   * @example\n   * ```ts\n   * const response = await ai.models.generateContentStream({\n   *   model: 'gemini-2.0-flash',\n   *   contents: 'why is the sky blue?',\n   *   config: {\n   *     maxOutputTokens: 200,\n   *   }\n   * });\n   * for await (const chunk of response) {\n   *   console.log(chunk);\n   * }\n   * ```\n   */\n  generateContentStream = async (\n    params: types.GenerateContentParameters,\n  ): Promise<AsyncGenerator<types.GenerateContentResponse>> => {\n    this.maybeMoveToResponseJsonSchem(params);\n    if (afc.shouldDisableAfc(params.config)) {\n      const transformedParams =\n        await this.processParamsMaybeAddMcpUsage(params);\n      return await this.generateContentStreamInternal(transformedParams);\n    }\n    const incompatibleToolIndexes = afc.findAfcIncompatibleToolIndexes(params);\n    if (incompatibleToolIndexes.length > 0) {\n      const formattedIndexes = incompatibleToolIndexes\n        .map((index: number) => `tools[${index}]`)\n        .join(', ');\n      throw new Error(\n        `Incompatible tools found at ${formattedIndexes}. Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations\" is not yet supported.`,\n      );\n    }\n\n    // With tool compatibility confirmed, validate that the configuration are\n    // compatible with each other and raise an error if invalid.\n    const streamFunctionCall =\n      params?.config?.toolConfig?.functionCallingConfig\n        ?.streamFunctionCallArguments;\n    const disableAfc = params?.config?.automaticFunctionCalling?.disable;\n\n    if (streamFunctionCall && !disableAfc) {\n      throw new Error(\n        \"Running in streaming mode with 'streamFunctionCallArguments' enabled, \" +\n          'this feature is not compatible with automatic function calling (AFC). ' +\n          \"Please set 'config.automaticFunctionCalling.disable' to true to disable AFC \" +\n          \"or leave 'config.toolConfig.functionCallingConfig.streamFunctionCallArguments' \" +\n          'to be undefined or set to false to disable streaming function call arguments feature.',\n      );\n    }\n\n    return await this.processAfcStream(params);\n  };\n\n  /**\n   * Transforms the CallableTools in the parameters to be simply Tools, it\n   * copies the params into a new object and replaces the tools, it does not\n   * modify the original params. Also sets the MCP usage header if there are\n   * MCP tools in the parameters.\n   */\n  private async processParamsMaybeAddMcpUsage(\n    params: types.GenerateContentParameters,\n  ): Promise<types.GenerateContentParameters> {\n    const tools = params.config?.tools;\n    if (!tools) {\n      return params;\n    }\n    const transformedTools = await Promise.all(\n      tools.map(async (tool) => {\n        if (afc.isCallableTool(tool)) {\n          const callableTool = tool as types.CallableTool;\n          return await callableTool.tool();\n        }\n        return tool;\n      }),\n    );\n    const newParams: types.GenerateContentParameters = {\n      model: params.model,\n      contents: params.contents,\n      config: {\n        ...params.config,\n        tools: transformedTools,\n      },\n    };\n    newParams.config!.tools = transformedTools;\n\n    if (\n      params.config &&\n      params.config.tools &&\n      mcp.hasMcpToolUsage(params.config.tools)\n    ) {\n      const headers = params.config.httpOptions?.headers ?? {};\n      let newHeaders = {...headers};\n      if (Object.keys(newHeaders).length === 0) {\n        newHeaders = this.apiClient.getDefaultHeaders();\n      }\n      mcp.setMcpUsageHeader(newHeaders);\n      newParams.config!.httpOptions = {\n        ...params.config.httpOptions,\n        headers: newHeaders,\n      };\n    }\n    return newParams;\n  }\n\n  private async initAfcToolsMap(\n    params: types.GenerateContentParameters,\n  ): Promise<Map<string, types.CallableTool>> {\n    const afcTools: Map<string, types.CallableTool> = new Map();\n    for (const tool of params.config?.tools ?? []) {\n      if (afc.isCallableTool(tool)) {\n        const callableTool = tool as types.CallableTool;\n        const toolDeclaration = await callableTool.tool();\n        for (const declaration of toolDeclaration.functionDeclarations ?? []) {\n          if (!declaration.name) {\n            throw new Error('Function declaration name is required.');\n          }\n          if (afcTools.has(declaration.name)) {\n            throw new Error(\n              `Duplicate tool declaration name: ${declaration.name}`,\n            );\n          }\n          afcTools.set(declaration.name, callableTool);\n        }\n      }\n    }\n    return afcTools;\n  }\n\n  private async processAfcStream(\n    params: types.GenerateContentParameters,\n  ): Promise<AsyncGenerator<types.GenerateContentResponse>> {\n    const maxRemoteCalls =\n      params.config?.automaticFunctionCalling?.maximumRemoteCalls ??\n      afc.DEFAULT_MAX_REMOTE_CALLS;\n    let wereFunctionsCalled = false;\n    let remoteCallCount = 0;\n    const afcToolsMap = await this.initAfcToolsMap(params);\n    return (async function* (\n      models: Models,\n      afcTools: Map<string, types.CallableTool>,\n      params: types.GenerateContentParameters,\n    ) {\n      while (remoteCallCount < maxRemoteCalls) {\n        if (wereFunctionsCalled) {\n          remoteCallCount++;\n          wereFunctionsCalled = false;\n        }\n        const transformedParams =\n          await models.processParamsMaybeAddMcpUsage(params);\n        const response =\n          await models.generateContentStreamInternal(transformedParams);\n\n        const functionResponses: types.Part[] = [];\n        const responseContents: types.Content[] = [];\n\n        for await (const chunk of response) {\n          yield chunk;\n          if (chunk.candidates && chunk.candidates[0]?.content) {\n            responseContents.push(chunk.candidates[0].content);\n            for (const part of chunk.candidates[0].content.parts ?? []) {\n              if (remoteCallCount < maxRemoteCalls && part.functionCall) {\n                if (!part.functionCall.name) {\n                  throw new Error(\n                    'Function call name was not returned by the model.',\n                  );\n                }\n                if (!afcTools.has(part.functionCall.name)) {\n                  throw new Error(\n                    `Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${afcTools.keys()}, mising tool: ${\n                      part.functionCall.name\n                    }`,\n                  );\n                } else {\n                  const responseParts = await afcTools\n                    .get(part.functionCall.name)!\n                    .callTool([part.functionCall]);\n                  functionResponses.push(...responseParts);\n                }\n              }\n            }\n          }\n        }\n\n        if (functionResponses.length > 0) {\n          wereFunctionsCalled = true;\n          const typedResponseChunk = new types.GenerateContentResponse();\n          typedResponseChunk.candidates = [\n            {\n              content: {\n                role: 'user',\n                parts: functionResponses,\n              },\n            },\n          ];\n\n          yield typedResponseChunk;\n\n          const newContents: types.Content[] = [];\n          newContents.push(...responseContents);\n          newContents.push({\n            role: 'user',\n            parts: functionResponses,\n          });\n          const updatedContents = tContents(params.contents).concat(\n            newContents,\n          );\n\n          params.contents = updatedContents;\n        } else {\n          break;\n        }\n      }\n    })(this, afcToolsMap, params);\n  }\n\n  /**\n   * Generates an image based on a text description and configuration.\n   *\n   * @param params - The parameters for generating images.\n   * @return The response from the API.\n   *\n   * @example\n   * ```ts\n   * const response = await client.models.generateImages({\n   *  model: 'imagen-3.0-generate-002',\n   *  prompt: 'Robot holding a red skateboard',\n   *  config: {\n   *    numberOfImages: 1,\n   *    includeRaiReason: true,\n   *  },\n   * });\n   * console.log(response?.generatedImages?.[0]?.image?.imageBytes);\n   * ```\n   */\n  generateImages = async (\n    params: types.GenerateImagesParameters,\n  ): Promise<types.GenerateImagesResponse> => {\n    return await this.generateImagesInternal(params).then((apiResponse) => {\n      let positivePromptSafetyAttributes;\n      const generatedImages = [];\n\n      if (apiResponse?.generatedImages) {\n        for (const generatedImage of apiResponse.generatedImages) {\n          if (\n            generatedImage &&\n            generatedImage?.safetyAttributes &&\n            generatedImage?.safetyAttributes?.contentType === 'Positive Prompt'\n          ) {\n            positivePromptSafetyAttributes = generatedImage?.safetyAttributes;\n          } else {\n            generatedImages.push(generatedImage);\n          }\n        }\n      }\n      let response: types.GenerateImagesResponse;\n\n      if (positivePromptSafetyAttributes) {\n        response = {\n          generatedImages: generatedImages,\n          positivePromptSafetyAttributes: positivePromptSafetyAttributes,\n          sdkHttpResponse: apiResponse.sdkHttpResponse,\n        };\n      } else {\n        response = {\n          generatedImages: generatedImages,\n          sdkHttpResponse: apiResponse.sdkHttpResponse,\n        };\n      }\n      return response;\n    });\n  };\n\n  list = async (\n    params?: types.ListModelsParameters,\n  ): Promise<Pager<types.Model>> => {\n    const defaultConfig: types.ListModelsConfig = {\n      queryBase: true,\n    };\n    const actualConfig: types.ListModelsConfig = {\n      ...defaultConfig,\n      ...params?.config,\n    };\n    const actualParams: types.ListModelsParameters = {\n      config: actualConfig,\n    };\n\n    if (this.apiClient.isVertexAI()) {\n      if (!actualParams.config!.queryBase) {\n        if (actualParams.config?.filter) {\n          throw new Error(\n            'Filtering tuned models list for Vertex AI is not currently supported',\n          );\n        } else {\n          actualParams.config!.filter = 'labels.tune-type:*';\n        }\n      }\n    }\n\n    return new Pager<types.Model>(\n      PagedItem.PAGED_ITEM_MODELS,\n      (x: types.ListModelsParameters) => this.listInternal(x),\n      await this.listInternal(actualParams),\n      actualParams,\n    );\n  };\n\n  /**\n   * Edits an image based on a prompt, list of reference images, and configuration.\n   *\n   * @param params - The parameters for editing an image.\n   * @return The response from the API.\n   *\n   * @example\n   * ```ts\n   * const response = await client.models.editImage({\n   *  model: 'imagen-3.0-capability-001',\n   *  prompt: 'Generate an image containing a mug with the product logo [1] visible on the side of the mug.',\n   *  referenceImages: [subjectReferenceImage]\n   *  config: {\n   *    numberOfImages: 1,\n   *    includeRaiReason: true,\n   *  },\n   * });\n   * console.log(response?.generatedImages?.[0]?.image?.imageBytes);\n   * ```\n   */\n  editImage = async (\n    params: types.EditImageParameters,\n  ): Promise<types.EditImageResponse> => {\n    const paramsInternal: _internal_types.EditImageParametersInternal = {\n      model: params.model,\n      prompt: params.prompt,\n      referenceImages: [],\n      config: params.config,\n    };\n    if (params.referenceImages) {\n      if (params.referenceImages) {\n        paramsInternal.referenceImages = params.referenceImages.map((img) =>\n          img.toReferenceImageAPI(),\n        );\n      }\n    }\n    return await this.editImageInternal(paramsInternal);\n  };\n\n  /**\n   * Upscales an image based on an image, upscale factor, and configuration.\n   * Only supported in Vertex AI currently.\n   *\n   * @param params - The parameters for upscaling an image.\n   * @return The response from the API.\n   *\n   * @example\n   * ```ts\n   * const response = await client.models.upscaleImage({\n   *  model: 'imagen-3.0-generate-002',\n   *  image: image,\n   *  upscaleFactor: 'x2',\n   *  config: {\n   *    includeRaiReason: true,\n   *  },\n   * });\n   * console.log(response?.generatedImages?.[0]?.image?.imageBytes);\n   * ```\n   */\n  upscaleImage = async (\n    params: types.UpscaleImageParameters,\n  ): Promise<types.UpscaleImageResponse> => {\n    let apiConfig: _internal_types.UpscaleImageAPIConfigInternal = {\n      numberOfImages: 1,\n      mode: 'upscale',\n    };\n\n    if (params.config) {\n      apiConfig = {...apiConfig, ...params.config};\n    }\n\n    const apiParams: _internal_types.UpscaleImageAPIParametersInternal = {\n      model: params.model,\n      image: params.image,\n      upscaleFactor: params.upscaleFactor,\n      config: apiConfig,\n    };\n    return await this.upscaleImageInternal(apiParams);\n  };\n\n  /**\n   *  Generates videos based on a text description and configuration.\n   *\n   * @param params - The parameters for generating videos.\n   * @return A Promise<GenerateVideosOperation> which allows you to track the progress and eventually retrieve the generated videos using the operations.get method.\n   *\n   * @example\n   * ```ts\n   * const operation = await ai.models.generateVideos({\n   *  model: 'veo-2.0-generate-001',\n   *  source: {\n   *    prompt: 'A neon hologram of a cat driving at top speed',\n   *  },\n   *  config: {\n   *    numberOfVideos: 1\n   * });\n   *\n   * while (!operation.done) {\n   *   await new Promise(resolve => setTimeout(resolve, 10000));\n   *   operation = await ai.operations.getVideosOperation({operation: operation});\n   * }\n   *\n   * console.log(operation.response?.generatedVideos?.[0]?.video?.uri);\n   * ```\n   */\n\n  generateVideos = async (\n    params: types.GenerateVideosParameters,\n  ): Promise<types.GenerateVideosOperation> => {\n    if ((params.prompt || params.image || params.video) && params.source) {\n      throw new Error(\n        'Source and prompt/image/video are mutually exclusive. Please only use source.',\n      );\n    }\n    // Gemini API does not support video bytes.\n    if (!this.apiClient.isVertexAI()) {\n      if (params.video?.uri && params.video?.videoBytes) {\n        params.video = {\n          uri: params.video.uri,\n          mimeType: params.video.mimeType,\n        };\n      } else if (\n        params.source?.video?.uri &&\n        params.source?.video?.videoBytes\n      ) {\n        params.source.video = {\n          uri: params.source.video.uri,\n          mimeType: params.source.video.mimeType,\n        };\n      }\n    }\n    return await this.generateVideosInternal(params);\n  };\n\n  private async generateContentInternal(\n    params: types.GenerateContentParameters,\n  ): Promise<types.GenerateContentResponse> {\n    let response: Promise<types.GenerateContentResponse>;\n\n    let path: string = '';\n    let queryParams: Record<string, string> = {};\n    if (this.apiClient.isVertexAI()) {\n      const body = converters.generateContentParametersToVertex(\n        this.apiClient,\n        params,\n      );\n      path = common.formatMap(\n        '{model}:generateContent',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'POST',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json().then((jsonResponse) => {\n            const response = jsonResponse as types.GenerateContentResponse;\n            response.sdkHttpResponse = {\n              headers: httpResponse.headers,\n            } as types.HttpResponse;\n            return response;\n          });\n        }) as Promise<types.GenerateContentResponse>;\n\n      return response.then((apiResponse) => {\n        const resp = converters.generateContentResponseFromVertex(apiResponse);\n        const typedResp = new types.GenerateContentResponse();\n        Object.assign(typedResp, resp);\n        return typedResp;\n      });\n    } else {\n      const body = converters.generateContentParametersToMldev(\n        this.apiClient,\n        params,\n      );\n      path = common.formatMap(\n        '{model}:generateContent',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'POST',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json().then((jsonResponse) => {\n            const response = jsonResponse as types.GenerateContentResponse;\n            response.sdkHttpResponse = {\n              headers: httpResponse.headers,\n            } as types.HttpResponse;\n            return response;\n          });\n        }) as Promise<types.GenerateContentResponse>;\n\n      return response.then((apiResponse) => {\n        const resp = converters.generateContentResponseFromMldev(apiResponse);\n        const typedResp = new types.GenerateContentResponse();\n        Object.assign(typedResp, resp);\n        return typedResp;\n      });\n    }\n  }\n\n  private async generateContentStreamInternal(\n    params: types.GenerateContentParameters,\n  ): Promise<AsyncGenerator<types.GenerateContentResponse>> {\n    let response: Promise<AsyncGenerator<types.HttpResponse>>;\n\n    let path: string = '';\n    let queryParams: Record<string, string> = {};\n    if (this.apiClient.isVertexAI()) {\n      const body = converters.generateContentParametersToVertex(\n        this.apiClient,\n        params,\n      );\n      path = common.formatMap(\n        '{model}:streamGenerateContent?alt=sse',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      const apiClient = this.apiClient;\n      response = apiClient.requestStream({\n        path: path,\n        queryParams: queryParams,\n        body: JSON.stringify(body),\n        httpMethod: 'POST',\n        httpOptions: params.config?.httpOptions,\n        abortSignal: params.config?.abortSignal,\n      }) as Promise<AsyncGenerator<types.HttpResponse>>;\n\n      return response.then(async function* (\n        apiResponse: AsyncGenerator<types.HttpResponse>,\n      ) {\n        for await (const chunk of apiResponse) {\n          const resp = converters.generateContentResponseFromVertex(\n            (await chunk.json()) as types.GenerateContentResponse,\n          );\n\n          resp['sdkHttpResponse'] = {\n            headers: chunk.headers,\n          } as types.HttpResponse;\n\n          const typedResp = new types.GenerateContentResponse();\n          Object.assign(typedResp, resp);\n          yield typedResp;\n        }\n      });\n    } else {\n      const body = converters.generateContentParametersToMldev(\n        this.apiClient,\n        params,\n      );\n      path = common.formatMap(\n        '{model}:streamGenerateContent?alt=sse',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      const apiClient = this.apiClient;\n      response = apiClient.requestStream({\n        path: path,\n        queryParams: queryParams,\n        body: JSON.stringify(body),\n        httpMethod: 'POST',\n        httpOptions: params.config?.httpOptions,\n        abortSignal: params.config?.abortSignal,\n      }) as Promise<AsyncGenerator<types.HttpResponse>>;\n\n      return response.then(async function* (\n        apiResponse: AsyncGenerator<types.HttpResponse>,\n      ) {\n        for await (const chunk of apiResponse) {\n          const resp = converters.generateContentResponseFromMldev(\n            (await chunk.json()) as types.GenerateContentResponse,\n          );\n\n          resp['sdkHttpResponse'] = {\n            headers: chunk.headers,\n          } as types.HttpResponse;\n\n          const typedResp = new types.GenerateContentResponse();\n          Object.assign(typedResp, resp);\n          yield typedResp;\n        }\n      });\n    }\n  }\n\n  /**\n   * Calculates embeddings for the given contents. Only text is supported.\n   *\n   * @param params - The parameters for embedding contents.\n   * @return The response from the API.\n   *\n   * @example\n   * ```ts\n   * const response = await ai.models.embedContent({\n   *  model: 'text-embedding-004',\n   *  contents: [\n   *    'What is your name?',\n   *    'What is your favorite color?',\n   *  ],\n   *  config: {\n   *    outputDimensionality: 64,\n   *  },\n   * });\n   * console.log(response);\n   * ```\n   */\n  async embedContent(\n    params: types.EmbedContentParameters,\n  ): Promise<types.EmbedContentResponse> {\n    let response: Promise<types.EmbedContentResponse>;\n\n    let path: string = '';\n    let queryParams: Record<string, string> = {};\n    if (this.apiClient.isVertexAI()) {\n      const body = converters.embedContentParametersToVertex(\n        this.apiClient,\n        params,\n      );\n      path = common.formatMap(\n        '{model}:predict',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'POST',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json().then((jsonResponse) => {\n            const response = jsonResponse as types.EmbedContentResponse;\n            response.sdkHttpResponse = {\n              headers: httpResponse.headers,\n            } as types.HttpResponse;\n            return response;\n          });\n        }) as Promise<types.EmbedContentResponse>;\n\n      return response.then((apiResponse) => {\n        const resp = converters.embedContentResponseFromVertex(apiResponse);\n        const typedResp = new types.EmbedContentResponse();\n        Object.assign(typedResp, resp);\n        return typedResp;\n      });\n    } else {\n      const body = converters.embedContentParametersToMldev(\n        this.apiClient,\n        params,\n      );\n      path = common.formatMap(\n        '{model}:batchEmbedContents',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'POST',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json().then((jsonResponse) => {\n            const response = jsonResponse as types.EmbedContentResponse;\n            response.sdkHttpResponse = {\n              headers: httpResponse.headers,\n            } as types.HttpResponse;\n            return response;\n          });\n        }) as Promise<types.EmbedContentResponse>;\n\n      return response.then((apiResponse) => {\n        const resp = converters.embedContentResponseFromMldev(apiResponse);\n        const typedResp = new types.EmbedContentResponse();\n        Object.assign(typedResp, resp);\n        return typedResp;\n      });\n    }\n  }\n\n  /**\n   * Private method for generating images.\n   */\n  private async generateImagesInternal(\n    params: types.GenerateImagesParameters,\n  ): Promise<types.GenerateImagesResponse> {\n    let response: Promise<types.GenerateImagesResponse>;\n\n    let path: string = '';\n    let queryParams: Record<string, string> = {};\n    if (this.apiClient.isVertexAI()) {\n      const body = converters.generateImagesParametersToVertex(\n        this.apiClient,\n        params,\n      );\n      path = common.formatMap(\n        '{model}:predict',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'POST',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json().then((jsonResponse) => {\n            const response = jsonResponse as types.GenerateImagesResponse;\n            response.sdkHttpResponse = {\n              headers: httpResponse.headers,\n            } as types.HttpResponse;\n            return response;\n          });\n        }) as Promise<types.GenerateImagesResponse>;\n\n      return response.then((apiResponse) => {\n        const resp = converters.generateImagesResponseFromVertex(apiResponse);\n        const typedResp = new types.GenerateImagesResponse();\n        Object.assign(typedResp, resp);\n        return typedResp;\n      });\n    } else {\n      const body = converters.generateImagesParametersToMldev(\n        this.apiClient,\n        params,\n      );\n      path = common.formatMap(\n        '{model}:predict',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'POST',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json().then((jsonResponse) => {\n            const response = jsonResponse as types.GenerateImagesResponse;\n            response.sdkHttpResponse = {\n              headers: httpResponse.headers,\n            } as types.HttpResponse;\n            return response;\n          });\n        }) as Promise<types.GenerateImagesResponse>;\n\n      return response.then((apiResponse) => {\n        const resp = converters.generateImagesResponseFromMldev(apiResponse);\n        const typedResp = new types.GenerateImagesResponse();\n        Object.assign(typedResp, resp);\n        return typedResp;\n      });\n    }\n  }\n\n  /**\n   * Private method for editing an image.\n   */\n  private async editImageInternal(\n    params: _internal_types.EditImageParametersInternal,\n  ): Promise<types.EditImageResponse> {\n    let response: Promise<types.EditImageResponse>;\n\n    let path: string = '';\n    let queryParams: Record<string, string> = {};\n    if (this.apiClient.isVertexAI()) {\n      const body = converters.editImageParametersInternalToVertex(\n        this.apiClient,\n        params,\n      );\n      path = common.formatMap(\n        '{model}:predict',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'POST',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json().then((jsonResponse) => {\n            const response = jsonResponse as types.EditImageResponse;\n            response.sdkHttpResponse = {\n              headers: httpResponse.headers,\n            } as types.HttpResponse;\n            return response;\n          });\n        }) as Promise<types.EditImageResponse>;\n\n      return response.then((apiResponse) => {\n        const resp = converters.editImageResponseFromVertex(apiResponse);\n        const typedResp = new types.EditImageResponse();\n        Object.assign(typedResp, resp);\n        return typedResp;\n      });\n    } else {\n      throw new Error('This method is only supported by the Vertex AI.');\n    }\n  }\n\n  /**\n   * Private method for upscaling an image.\n   */\n  private async upscaleImageInternal(\n    params: _internal_types.UpscaleImageAPIParametersInternal,\n  ): Promise<types.UpscaleImageResponse> {\n    let response: Promise<types.UpscaleImageResponse>;\n\n    let path: string = '';\n    let queryParams: Record<string, string> = {};\n    if (this.apiClient.isVertexAI()) {\n      const body = converters.upscaleImageAPIParametersInternalToVertex(\n        this.apiClient,\n        params,\n      );\n      path = common.formatMap(\n        '{model}:predict',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'POST',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json().then((jsonResponse) => {\n            const response = jsonResponse as types.UpscaleImageResponse;\n            response.sdkHttpResponse = {\n              headers: httpResponse.headers,\n            } as types.HttpResponse;\n            return response;\n          });\n        }) as Promise<types.UpscaleImageResponse>;\n\n      return response.then((apiResponse) => {\n        const resp = converters.upscaleImageResponseFromVertex(apiResponse);\n        const typedResp = new types.UpscaleImageResponse();\n        Object.assign(typedResp, resp);\n        return typedResp;\n      });\n    } else {\n      throw new Error('This method is only supported by the Vertex AI.');\n    }\n  }\n\n  /**\n   * Recontextualizes an image.\n   *\n   * There are two types of recontextualization currently supported:\n   * 1) Imagen Product Recontext - Generate images of products in new scenes\n   *    and contexts.\n   * 2) Virtual Try-On: Generate images of persons modeling fashion products.\n   *\n   * @param params - The parameters for recontextualizing an image.\n   * @return The response from the API.\n   *\n   * @example\n   * ```ts\n   * const response1 = await ai.models.recontextImage({\n   *  model: 'imagen-product-recontext-preview-06-30',\n   *  source: {\n   *    prompt: 'In a modern kitchen setting.',\n   *    productImages: [productImage],\n   *  },\n   *  config: {\n   *    numberOfImages: 1,\n   *  },\n   * });\n   * console.log(response1?.generatedImages?.[0]?.image?.imageBytes);\n   *\n   * const response2 = await ai.models.recontextImage({\n   *  model: 'virtual-try-on-preview-08-04',\n   *  source: {\n   *    personImage: personImage,\n   *    productImages: [productImage],\n   *  },\n   *  config: {\n   *    numberOfImages: 1,\n   *  },\n   * });\n   * console.log(response2?.generatedImages?.[0]?.image?.imageBytes);\n   * ```\n   */\n  async recontextImage(\n    params: types.RecontextImageParameters,\n  ): Promise<types.RecontextImageResponse> {\n    let response: Promise<types.RecontextImageResponse>;\n\n    let path: string = '';\n    let queryParams: Record<string, string> = {};\n    if (this.apiClient.isVertexAI()) {\n      const body = converters.recontextImageParametersToVertex(\n        this.apiClient,\n        params,\n      );\n      path = common.formatMap(\n        '{model}:predict',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'POST',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json();\n        }) as Promise<types.RecontextImageResponse>;\n\n      return response.then((apiResponse) => {\n        const resp = converters.recontextImageResponseFromVertex(apiResponse);\n        const typedResp = new types.RecontextImageResponse();\n        Object.assign(typedResp, resp);\n        return typedResp;\n      });\n    } else {\n      throw new Error('This method is only supported by the Vertex AI.');\n    }\n  }\n\n  /**\n   * Segments an image, creating a mask of a specified area.\n   *\n   * @param params - The parameters for segmenting an image.\n   * @return The response from the API.\n   *\n   * @example\n   * ```ts\n   * const response = await ai.models.segmentImage({\n   *  model: 'image-segmentation-001',\n   *  source: {\n   *    image: image,\n   *  },\n   *  config: {\n   *    mode: 'foreground',\n   *  },\n   * });\n   * console.log(response?.generatedMasks?.[0]?.mask?.imageBytes);\n   * ```\n   */\n  async segmentImage(\n    params: types.SegmentImageParameters,\n  ): Promise<types.SegmentImageResponse> {\n    let response: Promise<types.SegmentImageResponse>;\n\n    let path: string = '';\n    let queryParams: Record<string, string> = {};\n    if (this.apiClient.isVertexAI()) {\n      const body = converters.segmentImageParametersToVertex(\n        this.apiClient,\n        params,\n      );\n      path = common.formatMap(\n        '{model}:predict',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'POST',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json();\n        }) as Promise<types.SegmentImageResponse>;\n\n      return response.then((apiResponse) => {\n        const resp = converters.segmentImageResponseFromVertex(apiResponse);\n        const typedResp = new types.SegmentImageResponse();\n        Object.assign(typedResp, resp);\n        return typedResp;\n      });\n    } else {\n      throw new Error('This method is only supported by the Vertex AI.');\n    }\n  }\n\n  /**\n   * Fetches information about a model by name.\n   *\n   * @example\n   * ```ts\n   * const modelInfo = await ai.models.get({model: 'gemini-2.0-flash'});\n   * ```\n   */\n  async get(params: types.GetModelParameters): Promise<types.Model> {\n    let response: Promise<types.Model>;\n\n    let path: string = '';\n    let queryParams: Record<string, string> = {};\n    if (this.apiClient.isVertexAI()) {\n      const body = converters.getModelParametersToVertex(\n        this.apiClient,\n        params,\n      );\n      path = common.formatMap(\n        '{name}',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'GET',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json();\n        }) as Promise<types.Model>;\n\n      return response.then((apiResponse) => {\n        const resp = converters.modelFromVertex(apiResponse);\n\n        return resp as types.Model;\n      });\n    } else {\n      const body = converters.getModelParametersToMldev(this.apiClient, params);\n      path = common.formatMap(\n        '{name}',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'GET',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json();\n        }) as Promise<types.Model>;\n\n      return response.then((apiResponse) => {\n        const resp = converters.modelFromMldev(apiResponse);\n\n        return resp as types.Model;\n      });\n    }\n  }\n\n  private async listInternal(\n    params: types.ListModelsParameters,\n  ): Promise<types.ListModelsResponse> {\n    let response: Promise<types.ListModelsResponse>;\n\n    let path: string = '';\n    let queryParams: Record<string, string> = {};\n    if (this.apiClient.isVertexAI()) {\n      const body = converters.listModelsParametersToVertex(\n        this.apiClient,\n        params,\n      );\n      path = common.formatMap(\n        '{models_url}',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'GET',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json().then((jsonResponse) => {\n            const response = jsonResponse as types.ListModelsResponse;\n            response.sdkHttpResponse = {\n              headers: httpResponse.headers,\n            } as types.HttpResponse;\n            return response;\n          });\n        }) as Promise<types.ListModelsResponse>;\n\n      return response.then((apiResponse) => {\n        const resp = converters.listModelsResponseFromVertex(apiResponse);\n        const typedResp = new types.ListModelsResponse();\n        Object.assign(typedResp, resp);\n        return typedResp;\n      });\n    } else {\n      const body = converters.listModelsParametersToMldev(\n        this.apiClient,\n        params,\n      );\n      path = common.formatMap(\n        '{models_url}',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'GET',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json().then((jsonResponse) => {\n            const response = jsonResponse as types.ListModelsResponse;\n            response.sdkHttpResponse = {\n              headers: httpResponse.headers,\n            } as types.HttpResponse;\n            return response;\n          });\n        }) as Promise<types.ListModelsResponse>;\n\n      return response.then((apiResponse) => {\n        const resp = converters.listModelsResponseFromMldev(apiResponse);\n        const typedResp = new types.ListModelsResponse();\n        Object.assign(typedResp, resp);\n        return typedResp;\n      });\n    }\n  }\n\n  /**\n   * Updates a tuned model by its name.\n   *\n   * @param params - The parameters for updating the model.\n   * @return The response from the API.\n   *\n   * @example\n   * ```ts\n   * const response = await ai.models.update({\n   *   model: 'tuned-model-name',\n   *   config: {\n   *     displayName: 'New display name',\n   *     description: 'New description',\n   *   },\n   * });\n   * ```\n   */\n  async update(params: types.UpdateModelParameters): Promise<types.Model> {\n    let response: Promise<types.Model>;\n\n    let path: string = '';\n    let queryParams: Record<string, string> = {};\n    if (this.apiClient.isVertexAI()) {\n      const body = converters.updateModelParametersToVertex(\n        this.apiClient,\n        params,\n      );\n      path = common.formatMap(\n        '{model}',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'PATCH',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json();\n        }) as Promise<types.Model>;\n\n      return response.then((apiResponse) => {\n        const resp = converters.modelFromVertex(apiResponse);\n\n        return resp as types.Model;\n      });\n    } else {\n      const body = converters.updateModelParametersToMldev(\n        this.apiClient,\n        params,\n      );\n      path = common.formatMap(\n        '{name}',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'PATCH',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json();\n        }) as Promise<types.Model>;\n\n      return response.then((apiResponse) => {\n        const resp = converters.modelFromMldev(apiResponse);\n\n        return resp as types.Model;\n      });\n    }\n  }\n\n  /**\n   * Deletes a tuned model by its name.\n   *\n   * @param params - The parameters for deleting the model.\n   * @return The response from the API.\n   *\n   * @example\n   * ```ts\n   * const response = await ai.models.delete({model: 'tuned-model-name'});\n   * ```\n   */\n  async delete(\n    params: types.DeleteModelParameters,\n  ): Promise<types.DeleteModelResponse> {\n    let response: Promise<types.DeleteModelResponse>;\n\n    let path: string = '';\n    let queryParams: Record<string, string> = {};\n    if (this.apiClient.isVertexAI()) {\n      const body = converters.deleteModelParametersToVertex(\n        this.apiClient,\n        params,\n      );\n      path = common.formatMap(\n        '{name}',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'DELETE',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json().then((jsonResponse) => {\n            const response = jsonResponse as types.DeleteModelResponse;\n            response.sdkHttpResponse = {\n              headers: httpResponse.headers,\n            } as types.HttpResponse;\n            return response;\n          });\n        }) as Promise<types.DeleteModelResponse>;\n\n      return response.then((apiResponse) => {\n        const resp = converters.deleteModelResponseFromVertex(apiResponse);\n        const typedResp = new types.DeleteModelResponse();\n        Object.assign(typedResp, resp);\n        return typedResp;\n      });\n    } else {\n      const body = converters.deleteModelParametersToMldev(\n        this.apiClient,\n        params,\n      );\n      path = common.formatMap(\n        '{name}',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'DELETE',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json().then((jsonResponse) => {\n            const response = jsonResponse as types.DeleteModelResponse;\n            response.sdkHttpResponse = {\n              headers: httpResponse.headers,\n            } as types.HttpResponse;\n            return response;\n          });\n        }) as Promise<types.DeleteModelResponse>;\n\n      return response.then((apiResponse) => {\n        const resp = converters.deleteModelResponseFromMldev(apiResponse);\n        const typedResp = new types.DeleteModelResponse();\n        Object.assign(typedResp, resp);\n        return typedResp;\n      });\n    }\n  }\n\n  /**\n   * Counts the number of tokens in the given contents. Multimodal input is\n   * supported for Gemini models.\n   *\n   * @param params - The parameters for counting tokens.\n   * @return The response from the API.\n   *\n   * @example\n   * ```ts\n   * const response = await ai.models.countTokens({\n   *  model: 'gemini-2.0-flash',\n   *  contents: 'The quick brown fox jumps over the lazy dog.'\n   * });\n   * console.log(response);\n   * ```\n   */\n  async countTokens(\n    params: types.CountTokensParameters,\n  ): Promise<types.CountTokensResponse> {\n    let response: Promise<types.CountTokensResponse>;\n\n    let path: string = '';\n    let queryParams: Record<string, string> = {};\n    if (this.apiClient.isVertexAI()) {\n      const body = converters.countTokensParametersToVertex(\n        this.apiClient,\n        params,\n      );\n      path = common.formatMap(\n        '{model}:countTokens',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'POST',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json().then((jsonResponse) => {\n            const response = jsonResponse as types.CountTokensResponse;\n            response.sdkHttpResponse = {\n              headers: httpResponse.headers,\n            } as types.HttpResponse;\n            return response;\n          });\n        }) as Promise<types.CountTokensResponse>;\n\n      return response.then((apiResponse) => {\n        const resp = converters.countTokensResponseFromVertex(apiResponse);\n        const typedResp = new types.CountTokensResponse();\n        Object.assign(typedResp, resp);\n        return typedResp;\n      });\n    } else {\n      const body = converters.countTokensParametersToMldev(\n        this.apiClient,\n        params,\n      );\n      path = common.formatMap(\n        '{model}:countTokens',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'POST',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json().then((jsonResponse) => {\n            const response = jsonResponse as types.CountTokensResponse;\n            response.sdkHttpResponse = {\n              headers: httpResponse.headers,\n            } as types.HttpResponse;\n            return response;\n          });\n        }) as Promise<types.CountTokensResponse>;\n\n      return response.then((apiResponse) => {\n        const resp = converters.countTokensResponseFromMldev(apiResponse);\n        const typedResp = new types.CountTokensResponse();\n        Object.assign(typedResp, resp);\n        return typedResp;\n      });\n    }\n  }\n\n  /**\n   * Given a list of contents, returns a corresponding TokensInfo containing\n   * the list of tokens and list of token ids.\n   *\n   * This method is not supported by the Gemini Developer API.\n   *\n   * @param params - The parameters for computing tokens.\n   * @return The response from the API.\n   *\n   * @example\n   * ```ts\n   * const response = await ai.models.computeTokens({\n   *  model: 'gemini-2.0-flash',\n   *  contents: 'What is your name?'\n   * });\n   * console.log(response);\n   * ```\n   */\n  async computeTokens(\n    params: types.ComputeTokensParameters,\n  ): Promise<types.ComputeTokensResponse> {\n    let response: Promise<types.ComputeTokensResponse>;\n\n    let path: string = '';\n    let queryParams: Record<string, string> = {};\n    if (this.apiClient.isVertexAI()) {\n      const body = converters.computeTokensParametersToVertex(\n        this.apiClient,\n        params,\n      );\n      path = common.formatMap(\n        '{model}:computeTokens',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'POST',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json().then((jsonResponse) => {\n            const response = jsonResponse as types.ComputeTokensResponse;\n            response.sdkHttpResponse = {\n              headers: httpResponse.headers,\n            } as types.HttpResponse;\n            return response;\n          });\n        }) as Promise<types.ComputeTokensResponse>;\n\n      return response.then((apiResponse) => {\n        const resp = converters.computeTokensResponseFromVertex(apiResponse);\n        const typedResp = new types.ComputeTokensResponse();\n        Object.assign(typedResp, resp);\n        return typedResp;\n      });\n    } else {\n      throw new Error('This method is only supported by the Vertex AI.');\n    }\n  }\n\n  /**\n   * Private method for generating videos.\n   */\n  private async generateVideosInternal(\n    params: types.GenerateVideosParameters,\n  ): Promise<types.GenerateVideosOperation> {\n    let response: Promise<types.GenerateVideosOperation>;\n\n    let path: string = '';\n    let queryParams: Record<string, string> = {};\n    if (this.apiClient.isVertexAI()) {\n      const body = converters.generateVideosParametersToVertex(\n        this.apiClient,\n        params,\n      );\n      path = common.formatMap(\n        '{model}:predictLongRunning',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'POST',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json();\n        }) as Promise<types.GenerateVideosOperation>;\n\n      return response.then((apiResponse) => {\n        const resp = converters.generateVideosOperationFromVertex(apiResponse);\n        const typedResp = new types.GenerateVideosOperation();\n        Object.assign(typedResp, resp);\n        return typedResp;\n      });\n    } else {\n      const body = converters.generateVideosParametersToMldev(\n        this.apiClient,\n        params,\n      );\n      path = common.formatMap(\n        '{model}:predictLongRunning',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'POST',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json();\n        }) as Promise<types.GenerateVideosOperation>;\n\n      return response.then((apiResponse) => {\n        const resp = converters.generateVideosOperationFromMldev(apiResponse);\n        const typedResp = new types.GenerateVideosOperation();\n        Object.assign(typedResp, resp);\n        return typedResp;\n      });\n    }\n  }\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_operations_converters.js';\nimport * as types from './types.js';\n\nexport class Operations extends BaseModule {\n  constructor(private readonly apiClient: ApiClient) {\n    super();\n  }\n\n  /**\n   * Gets the status of a long-running operation.\n   *\n   * @param parameters The parameters for the get operation request.\n   * @return The updated Operation object, with the latest status or result.\n   */\n  async getVideosOperation(\n    parameters: types.OperationGetParameters<\n      types.GenerateVideosResponse,\n      types.GenerateVideosOperation\n    >,\n  ): Promise<types.GenerateVideosOperation> {\n    const operation = parameters.operation;\n    const config = parameters.config;\n\n    if (operation.name === undefined || operation.name === '') {\n      throw new Error('Operation name is required.');\n    }\n\n    if (this.apiClient.isVertexAI()) {\n      const resourceName = operation.name.split('/operations/')[0];\n      let httpOptions: types.HttpOptions | undefined = undefined;\n\n      if (config && 'httpOptions' in config) {\n        httpOptions = config.httpOptions;\n      }\n\n      const rawOperation = await this.fetchPredictVideosOperationInternal({\n        operationName: operation.name,\n        resourceName: resourceName,\n        config: {httpOptions: httpOptions},\n      });\n\n      return operation._fromAPIResponse({\n        apiResponse: rawOperation,\n        _isVertexAI: true,\n      });\n    } else {\n      const rawOperation = await this.getVideosOperationInternal({\n        operationName: operation.name,\n        config: config,\n      });\n      return operation._fromAPIResponse({\n        apiResponse: rawOperation,\n        _isVertexAI: false,\n      });\n    }\n  }\n\n  /**\n   * Gets the status of a long-running operation.\n   *\n   * @param parameters The parameters for the get operation request.\n   * @return The updated Operation object, with the latest status or result.\n   */\n  async get<T, U extends types.Operation<T>>(\n    parameters: types.OperationGetParameters<T, U>,\n  ): Promise<types.Operation<T>> {\n    const operation = parameters.operation;\n    const config = parameters.config;\n\n    if (operation.name === undefined || operation.name === '') {\n      throw new Error('Operation name is required.');\n    }\n\n    if (this.apiClient.isVertexAI()) {\n      const resourceName = operation.name.split('/operations/')[0];\n      let httpOptions: types.HttpOptions | undefined = undefined;\n\n      if (config && 'httpOptions' in config) {\n        httpOptions = config.httpOptions;\n      }\n\n      const rawOperation = await this.fetchPredictVideosOperationInternal({\n        operationName: operation.name,\n        resourceName: resourceName,\n        config: {httpOptions: httpOptions},\n      });\n\n      return operation._fromAPIResponse({\n        apiResponse: rawOperation,\n        _isVertexAI: true,\n      });\n    } else {\n      const rawOperation = await this.getVideosOperationInternal({\n        operationName: operation.name,\n        config: config,\n      });\n      return operation._fromAPIResponse({\n        apiResponse: rawOperation,\n        _isVertexAI: false,\n      });\n    }\n  }\n\n  private async getVideosOperationInternal(\n    params: types.GetOperationParameters,\n  ): Promise<Record<string, unknown>> {\n    let response: Promise<Record<string, unknown>>;\n\n    let path: string = '';\n    let queryParams: Record<string, string> = {};\n    if (this.apiClient.isVertexAI()) {\n      const body = converters.getOperationParametersToVertex(params);\n      path = common.formatMap(\n        '{operationName}',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'GET',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json();\n        }) as Promise<Record<string, unknown>>;\n\n      return response;\n    } else {\n      const body = converters.getOperationParametersToMldev(params);\n      path = common.formatMap(\n        '{operationName}',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'GET',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json();\n        }) as Promise<Record<string, unknown>>;\n\n      return response;\n    }\n  }\n\n  private async fetchPredictVideosOperationInternal(\n    params: types.FetchPredictOperationParameters,\n  ): Promise<Record<string, unknown>> {\n    let response: Promise<Record<string, unknown>>;\n\n    let path: string = '';\n    let queryParams: Record<string, string> = {};\n    if (this.apiClient.isVertexAI()) {\n      const body = converters.fetchPredictOperationParametersToVertex(params);\n      path = common.formatMap(\n        '{resourceName}:fetchPredictOperation',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'POST',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json();\n        }) as Promise<Record<string, unknown>>;\n\n      return response;\n    } else {\n      throw new Error('This method is only supported by the Vertex AI.');\n    }\n  }\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport type * as types from '../types.js';\n\nexport function blobToMldev(fromObject: types.Blob): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromData = common.getValueByPath(fromObject, ['data']);\n  if (fromData != null) {\n    common.setValueByPath(toObject, ['data'], fromData);\n  }\n\n  if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n    throw new Error('displayName parameter is not supported in Gemini API.');\n  }\n\n  const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n  if (fromMimeType != null) {\n    common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n  }\n\n  return toObject;\n}\n\nexport function contentToMldev(\n  fromObject: types.Content,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromParts = common.getValueByPath(fromObject, ['parts']);\n  if (fromParts != null) {\n    let transformedList = fromParts;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return partToMldev(item);\n      });\n    }\n    common.setValueByPath(toObject, ['parts'], transformedList);\n  }\n\n  const fromRole = common.getValueByPath(fromObject, ['role']);\n  if (fromRole != null) {\n    common.setValueByPath(toObject, ['role'], fromRole);\n  }\n\n  return toObject;\n}\n\nexport function createAuthTokenConfigToMldev(\n  apiClient: ApiClient,\n  fromObject: types.CreateAuthTokenConfig,\n  parentObject: Record<string, unknown>,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n  if (parentObject !== undefined && fromExpireTime != null) {\n    common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n  }\n\n  const fromNewSessionExpireTime = common.getValueByPath(fromObject, [\n    'newSessionExpireTime',\n  ]);\n  if (parentObject !== undefined && fromNewSessionExpireTime != null) {\n    common.setValueByPath(\n      parentObject,\n      ['newSessionExpireTime'],\n      fromNewSessionExpireTime,\n    );\n  }\n\n  const fromUses = common.getValueByPath(fromObject, ['uses']);\n  if (parentObject !== undefined && fromUses != null) {\n    common.setValueByPath(parentObject, ['uses'], fromUses);\n  }\n\n  const fromLiveConnectConstraints = common.getValueByPath(fromObject, [\n    'liveConnectConstraints',\n  ]);\n  if (parentObject !== undefined && fromLiveConnectConstraints != null) {\n    common.setValueByPath(\n      parentObject,\n      ['bidiGenerateContentSetup'],\n      liveConnectConstraintsToMldev(apiClient, fromLiveConnectConstraints),\n    );\n  }\n\n  const fromLockAdditionalFields = common.getValueByPath(fromObject, [\n    'lockAdditionalFields',\n  ]);\n  if (parentObject !== undefined && fromLockAdditionalFields != null) {\n    common.setValueByPath(\n      parentObject,\n      ['fieldMask'],\n      fromLockAdditionalFields,\n    );\n  }\n\n  return toObject;\n}\n\nexport function createAuthTokenParametersToMldev(\n  apiClient: ApiClient,\n  fromObject: types.CreateAuthTokenParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromConfig = common.getValueByPath(fromObject, ['config']);\n  if (fromConfig != null) {\n    common.setValueByPath(\n      toObject,\n      ['config'],\n      createAuthTokenConfigToMldev(apiClient, fromConfig, toObject),\n    );\n  }\n\n  return toObject;\n}\n\nexport function createAuthTokenParametersToVertex(\n  fromObject: types.CreateAuthTokenParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  if (common.getValueByPath(fromObject, ['config']) !== undefined) {\n    throw new Error('config parameter is not supported in Vertex AI.');\n  }\n\n  return toObject;\n}\n\nexport function fileDataToMldev(\n  fromObject: types.FileData,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n    throw new Error('displayName parameter is not supported in Gemini API.');\n  }\n\n  const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n  if (fromFileUri != null) {\n    common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n  }\n\n  const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n  if (fromMimeType != null) {\n    common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n  }\n\n  return toObject;\n}\n\nexport function functionCallToMldev(\n  fromObject: types.FunctionCall,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromId = common.getValueByPath(fromObject, ['id']);\n  if (fromId != null) {\n    common.setValueByPath(toObject, ['id'], fromId);\n  }\n\n  const fromArgs = common.getValueByPath(fromObject, ['args']);\n  if (fromArgs != null) {\n    common.setValueByPath(toObject, ['args'], fromArgs);\n  }\n\n  const fromName = common.getValueByPath(fromObject, ['name']);\n  if (fromName != null) {\n    common.setValueByPath(toObject, ['name'], fromName);\n  }\n\n  if (common.getValueByPath(fromObject, ['partialArgs']) !== undefined) {\n    throw new Error('partialArgs parameter is not supported in Gemini API.');\n  }\n\n  if (common.getValueByPath(fromObject, ['willContinue']) !== undefined) {\n    throw new Error('willContinue parameter is not supported in Gemini API.');\n  }\n\n  return toObject;\n}\n\nexport function googleMapsToMldev(\n  fromObject: types.GoogleMaps,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  if (common.getValueByPath(fromObject, ['authConfig']) !== undefined) {\n    throw new Error('authConfig parameter is not supported in Gemini API.');\n  }\n\n  const fromEnableWidget = common.getValueByPath(fromObject, ['enableWidget']);\n  if (fromEnableWidget != null) {\n    common.setValueByPath(toObject, ['enableWidget'], fromEnableWidget);\n  }\n\n  return toObject;\n}\n\nexport function googleSearchToMldev(\n  fromObject: types.GoogleSearch,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  if (common.getValueByPath(fromObject, ['excludeDomains']) !== undefined) {\n    throw new Error('excludeDomains parameter is not supported in Gemini API.');\n  }\n\n  if (common.getValueByPath(fromObject, ['blockingConfidence']) !== undefined) {\n    throw new Error(\n      'blockingConfidence parameter is not supported in Gemini API.',\n    );\n  }\n\n  const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n    'timeRangeFilter',\n  ]);\n  if (fromTimeRangeFilter != null) {\n    common.setValueByPath(toObject, ['timeRangeFilter'], fromTimeRangeFilter);\n  }\n\n  return toObject;\n}\n\nexport function liveConnectConfigToMldev(\n  fromObject: types.LiveConnectConfig,\n  parentObject: Record<string, unknown>,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromGenerationConfig = common.getValueByPath(fromObject, [\n    'generationConfig',\n  ]);\n  if (parentObject !== undefined && fromGenerationConfig != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'generationConfig'],\n      fromGenerationConfig,\n    );\n  }\n\n  const fromResponseModalities = common.getValueByPath(fromObject, [\n    'responseModalities',\n  ]);\n  if (parentObject !== undefined && fromResponseModalities != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'generationConfig', 'responseModalities'],\n      fromResponseModalities,\n    );\n  }\n\n  const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n  if (parentObject !== undefined && fromTemperature != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'generationConfig', 'temperature'],\n      fromTemperature,\n    );\n  }\n\n  const fromTopP = common.getValueByPath(fromObject, ['topP']);\n  if (parentObject !== undefined && fromTopP != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'generationConfig', 'topP'],\n      fromTopP,\n    );\n  }\n\n  const fromTopK = common.getValueByPath(fromObject, ['topK']);\n  if (parentObject !== undefined && fromTopK != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'generationConfig', 'topK'],\n      fromTopK,\n    );\n  }\n\n  const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n    'maxOutputTokens',\n  ]);\n  if (parentObject !== undefined && fromMaxOutputTokens != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'generationConfig', 'maxOutputTokens'],\n      fromMaxOutputTokens,\n    );\n  }\n\n  const fromMediaResolution = common.getValueByPath(fromObject, [\n    'mediaResolution',\n  ]);\n  if (parentObject !== undefined && fromMediaResolution != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'generationConfig', 'mediaResolution'],\n      fromMediaResolution,\n    );\n  }\n\n  const fromSeed = common.getValueByPath(fromObject, ['seed']);\n  if (parentObject !== undefined && fromSeed != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'generationConfig', 'seed'],\n      fromSeed,\n    );\n  }\n\n  const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n  if (parentObject !== undefined && fromSpeechConfig != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'generationConfig', 'speechConfig'],\n      t.tLiveSpeechConfig(fromSpeechConfig),\n    );\n  }\n\n  const fromThinkingConfig = common.getValueByPath(fromObject, [\n    'thinkingConfig',\n  ]);\n  if (parentObject !== undefined && fromThinkingConfig != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'generationConfig', 'thinkingConfig'],\n      fromThinkingConfig,\n    );\n  }\n\n  const fromEnableAffectiveDialog = common.getValueByPath(fromObject, [\n    'enableAffectiveDialog',\n  ]);\n  if (parentObject !== undefined && fromEnableAffectiveDialog != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'generationConfig', 'enableAffectiveDialog'],\n      fromEnableAffectiveDialog,\n    );\n  }\n\n  const fromSystemInstruction = common.getValueByPath(fromObject, [\n    'systemInstruction',\n  ]);\n  if (parentObject !== undefined && fromSystemInstruction != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'systemInstruction'],\n      contentToMldev(t.tContent(fromSystemInstruction)),\n    );\n  }\n\n  const fromTools = common.getValueByPath(fromObject, ['tools']);\n  if (parentObject !== undefined && fromTools != null) {\n    let transformedList = t.tTools(fromTools);\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return toolToMldev(t.tTool(item));\n      });\n    }\n    common.setValueByPath(parentObject, ['setup', 'tools'], transformedList);\n  }\n\n  const fromSessionResumption = common.getValueByPath(fromObject, [\n    'sessionResumption',\n  ]);\n  if (parentObject !== undefined && fromSessionResumption != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'sessionResumption'],\n      sessionResumptionConfigToMldev(fromSessionResumption),\n    );\n  }\n\n  const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n    'inputAudioTranscription',\n  ]);\n  if (parentObject !== undefined && fromInputAudioTranscription != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'inputAudioTranscription'],\n      fromInputAudioTranscription,\n    );\n  }\n\n  const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n    'outputAudioTranscription',\n  ]);\n  if (parentObject !== undefined && fromOutputAudioTranscription != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'outputAudioTranscription'],\n      fromOutputAudioTranscription,\n    );\n  }\n\n  const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n    'realtimeInputConfig',\n  ]);\n  if (parentObject !== undefined && fromRealtimeInputConfig != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'realtimeInputConfig'],\n      fromRealtimeInputConfig,\n    );\n  }\n\n  const fromContextWindowCompression = common.getValueByPath(fromObject, [\n    'contextWindowCompression',\n  ]);\n  if (parentObject !== undefined && fromContextWindowCompression != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'contextWindowCompression'],\n      fromContextWindowCompression,\n    );\n  }\n\n  const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n  if (parentObject !== undefined && fromProactivity != null) {\n    common.setValueByPath(\n      parentObject,\n      ['setup', 'proactivity'],\n      fromProactivity,\n    );\n  }\n\n  if (common.getValueByPath(fromObject, ['explicitVadSignal']) !== undefined) {\n    throw new Error(\n      'explicitVadSignal parameter is not supported in Gemini API.',\n    );\n  }\n\n  return toObject;\n}\n\nexport function liveConnectConstraintsToMldev(\n  apiClient: ApiClient,\n  fromObject: types.LiveConnectConstraints,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromModel = common.getValueByPath(fromObject, ['model']);\n  if (fromModel != null) {\n    common.setValueByPath(\n      toObject,\n      ['setup', 'model'],\n      t.tModel(apiClient, fromModel),\n    );\n  }\n\n  const fromConfig = common.getValueByPath(fromObject, ['config']);\n  if (fromConfig != null) {\n    common.setValueByPath(\n      toObject,\n      ['config'],\n      liveConnectConfigToMldev(fromConfig, toObject),\n    );\n  }\n\n  return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromMediaResolution = common.getValueByPath(fromObject, [\n    'mediaResolution',\n  ]);\n  if (fromMediaResolution != null) {\n    common.setValueByPath(toObject, ['mediaResolution'], fromMediaResolution);\n  }\n\n  const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n    'codeExecutionResult',\n  ]);\n  if (fromCodeExecutionResult != null) {\n    common.setValueByPath(\n      toObject,\n      ['codeExecutionResult'],\n      fromCodeExecutionResult,\n    );\n  }\n\n  const fromExecutableCode = common.getValueByPath(fromObject, [\n    'executableCode',\n  ]);\n  if (fromExecutableCode != null) {\n    common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n  }\n\n  const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n  if (fromFileData != null) {\n    common.setValueByPath(\n      toObject,\n      ['fileData'],\n      fileDataToMldev(fromFileData),\n    );\n  }\n\n  const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n  if (fromFunctionCall != null) {\n    common.setValueByPath(\n      toObject,\n      ['functionCall'],\n      functionCallToMldev(fromFunctionCall),\n    );\n  }\n\n  const fromFunctionResponse = common.getValueByPath(fromObject, [\n    'functionResponse',\n  ]);\n  if (fromFunctionResponse != null) {\n    common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n  }\n\n  const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n  if (fromInlineData != null) {\n    common.setValueByPath(\n      toObject,\n      ['inlineData'],\n      blobToMldev(fromInlineData),\n    );\n  }\n\n  const fromText = common.getValueByPath(fromObject, ['text']);\n  if (fromText != null) {\n    common.setValueByPath(toObject, ['text'], fromText);\n  }\n\n  const fromThought = common.getValueByPath(fromObject, ['thought']);\n  if (fromThought != null) {\n    common.setValueByPath(toObject, ['thought'], fromThought);\n  }\n\n  const fromThoughtSignature = common.getValueByPath(fromObject, [\n    'thoughtSignature',\n  ]);\n  if (fromThoughtSignature != null) {\n    common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n  }\n\n  const fromVideoMetadata = common.getValueByPath(fromObject, [\n    'videoMetadata',\n  ]);\n  if (fromVideoMetadata != null) {\n    common.setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata);\n  }\n\n  return toObject;\n}\n\nexport function sessionResumptionConfigToMldev(\n  fromObject: types.SessionResumptionConfig,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromHandle = common.getValueByPath(fromObject, ['handle']);\n  if (fromHandle != null) {\n    common.setValueByPath(toObject, ['handle'], fromHandle);\n  }\n\n  if (common.getValueByPath(fromObject, ['transparent']) !== undefined) {\n    throw new Error('transparent parameter is not supported in Gemini API.');\n  }\n\n  return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n    'functionDeclarations',\n  ]);\n  if (fromFunctionDeclarations != null) {\n    let transformedList = fromFunctionDeclarations;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return item;\n      });\n    }\n    common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n  }\n\n  if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n    throw new Error('retrieval parameter is not supported in Gemini API.');\n  }\n\n  const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n    'googleSearchRetrieval',\n  ]);\n  if (fromGoogleSearchRetrieval != null) {\n    common.setValueByPath(\n      toObject,\n      ['googleSearchRetrieval'],\n      fromGoogleSearchRetrieval,\n    );\n  }\n\n  const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n  if (fromComputerUse != null) {\n    common.setValueByPath(toObject, ['computerUse'], fromComputerUse);\n  }\n\n  const fromFileSearch = common.getValueByPath(fromObject, ['fileSearch']);\n  if (fromFileSearch != null) {\n    common.setValueByPath(toObject, ['fileSearch'], fromFileSearch);\n  }\n\n  const fromCodeExecution = common.getValueByPath(fromObject, [\n    'codeExecution',\n  ]);\n  if (fromCodeExecution != null) {\n    common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n  }\n\n  if (\n    common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n  ) {\n    throw new Error(\n      'enterpriseWebSearch parameter is not supported in Gemini API.',\n    );\n  }\n\n  const fromGoogleMaps = common.getValueByPath(fromObject, ['googleMaps']);\n  if (fromGoogleMaps != null) {\n    common.setValueByPath(\n      toObject,\n      ['googleMaps'],\n      googleMapsToMldev(fromGoogleMaps),\n    );\n  }\n\n  const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n  if (fromGoogleSearch != null) {\n    common.setValueByPath(\n      toObject,\n      ['googleSearch'],\n      googleSearchToMldev(fromGoogleSearch),\n    );\n  }\n\n  const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n  if (fromUrlContext != null) {\n    common.setValueByPath(toObject, ['urlContext'], fromUrlContext);\n  }\n\n  return toObject;\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_tokens_converters.js';\nimport * as types from './types.js';\n\n/**\n * Returns a comma-separated list of field masks from a given object.\n *\n * @param setup The object to extract field masks from.\n * @return A comma-separated list of field masks.\n */\nfunction getFieldMasks(setup: Record<string, unknown>): string {\n  const fields: string[] = [];\n\n  for (const key in setup) {\n    if (Object.prototype.hasOwnProperty.call(setup, key)) {\n      const value = setup[key];\n      // 2nd layer, recursively get field masks see TODO(b/418290100)\n      if (\n        typeof value === 'object' &&\n        value != null &&\n        Object.keys(value).length > 0\n      ) {\n        const field = Object.keys(value).map((kk) => `${key}.${kk}`);\n        fields.push(...field);\n      } else {\n        fields.push(key); // 1st layer\n      }\n    }\n  }\n\n  return fields.join(',');\n}\n\n/**\n * Converts bidiGenerateContentSetup.\n * @param requestDict - The request dictionary.\n * @param config - The configuration object.\n * @return - The modified request dictionary.\n */\nfunction convertBidiSetupToTokenSetup(\n  requestDict: Record<string, unknown>,\n  config?: {lockAdditionalFields?: string[]},\n): Record<string, unknown> {\n  // Convert bidiGenerateContentSetup from bidiGenerateContentSetup.setup.\n  let setupForMaskGeneration: Record<string, unknown> | null = null;\n  const bidiGenerateContentSetupValue = requestDict['bidiGenerateContentSetup'];\n  if (\n    typeof bidiGenerateContentSetupValue === 'object' &&\n    bidiGenerateContentSetupValue !== null &&\n    'setup' in bidiGenerateContentSetupValue\n  ) {\n    // Now we know bidiGenerateContentSetupValue is an object and has a 'setup'\n    // property.\n    const innerSetup = (bidiGenerateContentSetupValue as {setup: unknown})\n      .setup;\n\n    if (typeof innerSetup === 'object' && innerSetup !== null) {\n      // Valid inner setup found.\n      requestDict['bidiGenerateContentSetup'] = innerSetup;\n      setupForMaskGeneration = innerSetup as Record<string, unknown>;\n    } else {\n      // `bidiGenerateContentSetupValue.setup` is not a valid object; treat as\n      // if bidiGenerateContentSetup is invalid.\n      delete requestDict['bidiGenerateContentSetup'];\n    }\n  } else if (bidiGenerateContentSetupValue !== undefined) {\n    // `bidiGenerateContentSetup` exists but not in the expected\n    // shape {setup: {...}}; treat as invalid.\n    delete requestDict['bidiGenerateContentSetup'];\n  }\n\n  const preExistingFieldMask = requestDict['fieldMask'];\n  // Handle mask generation setup.\n  if (setupForMaskGeneration) {\n    const generatedMaskFromBidi = getFieldMasks(setupForMaskGeneration);\n\n    if (\n      Array.isArray(config?.lockAdditionalFields) &&\n      config?.lockAdditionalFields.length === 0\n    ) {\n      // Case 1: lockAdditionalFields is an empty array. Lock only fields from\n      // bidi setup.\n      if (generatedMaskFromBidi) {\n        // Only assign if mask is not empty\n        requestDict['fieldMask'] = generatedMaskFromBidi;\n      } else {\n        delete requestDict['fieldMask']; // If mask is empty, effectively no\n        // specific fields locked by bidi\n      }\n    } else if (\n      config?.lockAdditionalFields &&\n      config.lockAdditionalFields.length > 0 &&\n      preExistingFieldMask !== null &&\n      Array.isArray(preExistingFieldMask) &&\n      preExistingFieldMask.length > 0\n    ) {\n      // Case 2: Lock fields from bidi setup + additional fields\n      // (preExistingFieldMask).\n\n      const generationConfigFields = [\n        'temperature',\n        'topK',\n        'topP',\n        'maxOutputTokens',\n        'responseModalities',\n        'seed',\n        'speechConfig',\n      ];\n\n      let mappedFieldsFromPreExisting: string[] = [];\n      if (preExistingFieldMask.length > 0) {\n        mappedFieldsFromPreExisting = preExistingFieldMask.map((field) => {\n          if (generationConfigFields.includes(field)) {\n            return `generationConfig.${field}`;\n          }\n          return field; // Keep original field name if not in\n          // generationConfigFields\n        });\n      }\n\n      const finalMaskParts: string[] = [];\n      if (generatedMaskFromBidi) {\n        finalMaskParts.push(generatedMaskFromBidi);\n      }\n      if (mappedFieldsFromPreExisting.length > 0) {\n        finalMaskParts.push(...mappedFieldsFromPreExisting);\n      }\n\n      if (finalMaskParts.length > 0) {\n        requestDict['fieldMask'] = finalMaskParts.join(',');\n      } else {\n        // If no fields from bidi and no valid additional fields from\n        // pre-existing mask.\n        delete requestDict['fieldMask'];\n      }\n    } else {\n      // Case 3: \"Lock all fields\" (meaning, don't send a field_mask, let server\n      // defaults apply or all are mutable). This is hit if:\n      //  - `config.lockAdditionalFields` is undefined.\n      //  - `config.lockAdditionalFields` is non-empty, BUT\n      //  `preExistingFieldMask` is null, not a string, or an empty string.\n      delete requestDict['fieldMask'];\n    }\n  } else {\n    // No valid `bidiGenerateContentSetup` was found or extracted.\n    // \"Lock additional null fields if any\".\n    if (\n      preExistingFieldMask !== null &&\n      Array.isArray(preExistingFieldMask) &&\n      preExistingFieldMask.length > 0\n    ) {\n      // If there's a pre-existing field mask, it's a string, and it's not\n      // empty, then we should lock all fields.\n      requestDict['fieldMask'] = preExistingFieldMask.join(',');\n    } else {\n      delete requestDict['fieldMask'];\n    }\n  }\n\n  return requestDict;\n}\n\nexport class Tokens extends BaseModule {\n  constructor(private readonly apiClient: ApiClient) {\n    super();\n  }\n  /**\n   * Creates an ephemeral auth token resource.\n   *\n   * @experimental\n   *\n   * @remarks\n   * Ephemeral auth tokens is only supported in the Gemini Developer API.\n   * It can be used for the session connection to the Live constrained API.\n   * Support in v1alpha only.\n   *\n   * @param params - The parameters for the create request.\n   * @return The created auth token.\n   *\n   * @example\n   * ```ts\n   * const ai = new GoogleGenAI({\n   *     apiKey: token.name,\n   *     httpOptions: { apiVersion: 'v1alpha' }  // Support in v1alpha only.\n   * });\n   *\n   * // Case 1: If LiveEphemeralParameters is unset, unlock LiveConnectConfig\n   * // when using the token in Live API sessions. Each session connection can\n   * // use a different configuration.\n   * const config: CreateAuthTokenConfig = {\n   *     uses: 3,\n   *     expireTime: '2025-05-01T00:00:00Z',\n   * }\n   * const token = await ai.tokens.create(config);\n   *\n   * // Case 2: If LiveEphemeralParameters is set, lock all fields in\n   * // LiveConnectConfig when using the token in Live API sessions. For\n   * // example, changing `outputAudioTranscription` in the Live API\n   * // connection will be ignored by the API.\n   * const config: CreateAuthTokenConfig =\n   *     uses: 3,\n   *     expireTime: '2025-05-01T00:00:00Z',\n   *     LiveEphemeralParameters: {\n   *        model: 'gemini-2.0-flash-001',\n   *        config: {\n   *           'responseModalities': ['AUDIO'],\n   *           'systemInstruction': 'Always answer in English.',\n   *        }\n   *     }\n   * }\n   * const token = await ai.tokens.create(config);\n   *\n   * // Case 3: If LiveEphemeralParameters is set and lockAdditionalFields is\n   * // set, lock LiveConnectConfig with set and additional fields (e.g.\n   * // responseModalities, systemInstruction, temperature in this example) when\n   * // using the token in Live API sessions.\n   * const config: CreateAuthTokenConfig =\n   *     uses: 3,\n   *     expireTime: '2025-05-01T00:00:00Z',\n   *     LiveEphemeralParameters: {\n   *        model: 'gemini-2.0-flash-001',\n   *        config: {\n   *           'responseModalities': ['AUDIO'],\n   *           'systemInstruction': 'Always answer in English.',\n   *        }\n   *     },\n   *     lockAdditionalFields: ['temperature'],\n   * }\n   * const token = await ai.tokens.create(config);\n   *\n   * // Case 4: If LiveEphemeralParameters is set and lockAdditionalFields is\n   * // empty array, lock LiveConnectConfig with set fields (e.g.\n   * // responseModalities, systemInstruction in this example) when using the\n   * // token in Live API sessions.\n   * const config: CreateAuthTokenConfig =\n   *     uses: 3,\n   *     expireTime: '2025-05-01T00:00:00Z',\n   *     LiveEphemeralParameters: {\n   *        model: 'gemini-2.0-flash-001',\n   *        config: {\n   *           'responseModalities': ['AUDIO'],\n   *           'systemInstruction': 'Always answer in English.',\n   *        }\n   *     },\n   *     lockAdditionalFields: [],\n   * }\n   * const token = await ai.tokens.create(config);\n   * ```\n   */\n\n  async create(\n    params: types.CreateAuthTokenParameters,\n  ): Promise<types.AuthToken> {\n    let response: Promise<types.AuthToken>;\n    let path: string = '';\n    let queryParams: Record<string, string> = {};\n    if (this.apiClient.isVertexAI()) {\n      throw new Error(\n        'The client.tokens.create method is only supported by the Gemini Developer API.',\n      );\n    } else {\n      const body = converters.createAuthTokenParametersToMldev(\n        this.apiClient,\n        params,\n      );\n      path = common.formatMap(\n        'auth_tokens',\n        body['_url'] as Record<string, unknown>,\n      );\n\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['config'];\n      delete body['_url'];\n      delete body['_query'];\n\n      const transformedBody = convertBidiSetupToTokenSetup(body, params.config);\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(transformedBody),\n          httpMethod: 'POST',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json();\n        }) as Promise<types.AuthToken>;\n\n      return response.then((resp) => {\n        return resp as types.AuthToken;\n      });\n    }\n  }\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport * as common from '../_common.js';\nimport type * as types from '../types.js';\n\nexport function deleteDocumentConfigToMldev(\n  fromObject: types.DeleteDocumentConfig,\n  parentObject: Record<string, unknown>,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromForce = common.getValueByPath(fromObject, ['force']);\n  if (parentObject !== undefined && fromForce != null) {\n    common.setValueByPath(parentObject, ['_query', 'force'], fromForce);\n  }\n\n  return toObject;\n}\n\nexport function deleteDocumentParametersToMldev(\n  fromObject: types.DeleteDocumentParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromName = common.getValueByPath(fromObject, ['name']);\n  if (fromName != null) {\n    common.setValueByPath(toObject, ['_url', 'name'], fromName);\n  }\n\n  const fromConfig = common.getValueByPath(fromObject, ['config']);\n  if (fromConfig != null) {\n    deleteDocumentConfigToMldev(fromConfig, toObject);\n  }\n\n  return toObject;\n}\n\nexport function getDocumentParametersToMldev(\n  fromObject: types.GetDocumentParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromName = common.getValueByPath(fromObject, ['name']);\n  if (fromName != null) {\n    common.setValueByPath(toObject, ['_url', 'name'], fromName);\n  }\n\n  return toObject;\n}\n\nexport function listDocumentsConfigToMldev(\n  fromObject: types.ListDocumentsConfig,\n  parentObject: Record<string, unknown>,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n  if (parentObject !== undefined && fromPageSize != null) {\n    common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n  }\n\n  const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n  if (parentObject !== undefined && fromPageToken != null) {\n    common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n  }\n\n  return toObject;\n}\n\nexport function listDocumentsParametersToMldev(\n  fromObject: types.ListDocumentsParameters,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromParent = common.getValueByPath(fromObject, ['parent']);\n  if (fromParent != null) {\n    common.setValueByPath(toObject, ['_url', 'parent'], fromParent);\n  }\n\n  const fromConfig = common.getValueByPath(fromObject, ['config']);\n  if (fromConfig != null) {\n    listDocumentsConfigToMldev(fromConfig, toObject);\n  }\n\n  return toObject;\n}\n\nexport function listDocumentsResponseFromMldev(\n  fromObject: types.ListDocumentsResponse,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n    'sdkHttpResponse',\n  ]);\n  if (fromSdkHttpResponse != null) {\n    common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n  }\n\n  const fromNextPageToken = common.getValueByPath(fromObject, [\n    'nextPageToken',\n  ]);\n  if (fromNextPageToken != null) {\n    common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n  }\n\n  const fromDocuments = common.getValueByPath(fromObject, ['documents']);\n  if (fromDocuments != null) {\n    let transformedList = fromDocuments;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return item;\n      });\n    }\n    common.setValueByPath(toObject, ['documents'], transformedList);\n  }\n\n  return toObject;\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_documents_converters.js';\nimport {PagedItem, PagedItemConfig, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Documents extends BaseModule {\n  constructor(private readonly apiClient: ApiClient) {\n    super();\n  }\n\n  /**\n   * Lists documents.\n   *\n   * @param params - The parameters for the list request.\n   * @return - A pager of documents.\n   *\n   * @example\n   * ```ts\n   * const documents = await ai.documents.list({parent:'rag_store_name', config: {'pageSize': 2}});\n   * for await (const document of documents) {\n   *   console.log(document);\n   * }\n   * ```\n   */\n\n  list = async (\n    params: types.ListDocumentsParameters,\n  ): Promise<Pager<types.Document>> => {\n    return new Pager<types.Document>(\n      PagedItem.PAGED_ITEM_DOCUMENTS,\n      (x: PagedItemConfig) =>\n        this.listInternal({parent: params.parent, config: x.config}),\n      await this.listInternal(params),\n      params,\n    );\n  };\n\n  /**\n   * Gets a Document.\n   *\n   * @param params - The parameters for getting a document.\n   * @return Document.\n   */\n\n  async get(params: types.GetDocumentParameters): Promise<types.Document> {\n    let response: Promise<types.Document>;\n\n    let path: string = '';\n    let queryParams: Record<string, string> = {};\n    if (this.apiClient.isVertexAI()) {\n      throw new Error(\n        'This method is only supported by the Gemini Developer API.',\n      );\n    } else {\n      const body = converters.getDocumentParametersToMldev(params);\n      path = common.formatMap(\n        '{name}',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'GET',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json();\n        }) as Promise<types.Document>;\n\n      return response.then((resp) => {\n        return resp as types.Document;\n      });\n    }\n  }\n\n  /**\n   * Deletes a Document.\n   *\n   * @param params - The parameters for deleting a document.\n   */\n\n  async delete(params: types.DeleteDocumentParameters): Promise<void> {\n    let path: string = '';\n    let queryParams: Record<string, string> = {};\n    if (this.apiClient.isVertexAI()) {\n      throw new Error(\n        'This method is only supported by the Gemini Developer API.',\n      );\n    } else {\n      const body = converters.deleteDocumentParametersToMldev(params);\n      path = common.formatMap(\n        '{name}',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      await this.apiClient.request({\n        path: path,\n        queryParams: queryParams,\n        body: JSON.stringify(body),\n        httpMethod: 'DELETE',\n        httpOptions: params.config?.httpOptions,\n        abortSignal: params.config?.abortSignal,\n      });\n    }\n  }\n\n  private async listInternal(\n    params: types.ListDocumentsParameters,\n  ): Promise<types.ListDocumentsResponse> {\n    let response: Promise<types.ListDocumentsResponse>;\n\n    let path: string = '';\n    let queryParams: Record<string, string> = {};\n    if (this.apiClient.isVertexAI()) {\n      throw new Error(\n        'This method is only supported by the Gemini Developer API.',\n      );\n    } else {\n      const body = converters.listDocumentsParametersToMldev(params);\n      path = common.formatMap(\n        '{parent}/documents',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'GET',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json();\n        }) as Promise<types.ListDocumentsResponse>;\n\n      return response.then((apiResponse) => {\n        const resp = converters.listDocumentsResponseFromMldev(apiResponse);\n        const typedResp = new types.ListDocumentsResponse();\n        Object.assign(typedResp, resp);\n        return typedResp;\n      });\n    }\n  }\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_filesearchstores_converters.js';\nimport {Documents} from './documents.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class FileSearchStores extends BaseModule {\n  constructor(\n    private readonly apiClient: ApiClient,\n    public readonly documents: Documents = new Documents(apiClient),\n  ) {\n    super();\n  }\n\n  /**\n   * Lists file search stores.\n   *\n   * @param params - The parameters for the list request.\n   * @return - A pager of file search stores.\n   *\n   * @example\n   * ```ts\n   * const fileSearchStores = await ai.fileSearchStores.list({config: {'pageSize': 2}});\n   * for await (const fileSearchStore of fileSearchStores) {\n   *   console.log(fileSearchStore);\n   * }\n   * ```\n   */\n\n  list = async (\n    params: types.ListFileSearchStoresParameters = {},\n  ): Promise<Pager<types.FileSearchStore>> => {\n    return new Pager<types.FileSearchStore>(\n      PagedItem.PAGED_ITEM_FILE_SEARCH_STORES,\n      (x: types.ListFileSearchStoresParameters) => this.listInternal(x),\n      await this.listInternal(params),\n      params,\n    );\n  };\n\n  /**\n   * Uploads a file asynchronously to a given File Search Store.\n   * This method is not available in Vertex AI.\n   * Supported upload sources:\n   * - Node.js: File path (string) or Blob object.\n   * - Browser: Blob object (e.g., File).\n   *\n   * @remarks\n   * The `mimeType` can be specified in the `config` parameter. If omitted:\n   *  - For file path (string) inputs, the `mimeType` will be inferred from the\n   *     file extension.\n   *  - For Blob object inputs, the `mimeType` will be set to the Blob's `type`\n   *     property.\n   *\n   * This section can contain multiple paragraphs and code examples.\n   *\n   * @param params - Optional parameters specified in the\n   *        `types.UploadToFileSearchStoreParameters` interface.\n   *         @see {@link types.UploadToFileSearchStoreParameters#config} for the optional\n   *         config in the parameters.\n   * @return A promise that resolves to a long running operation.\n   * @throws An error if called on a Vertex AI client.\n   * @throws An error if the `mimeType` is not provided and can not be inferred,\n   * the `mimeType` can be provided in the `params.config` parameter.\n   * @throws An error occurs if a suitable upload location cannot be established.\n   *\n   * @example\n   * The following code uploads a file to a given file search store.\n   *\n   * ```ts\n   * const operation = await ai.fileSearchStores.upload({fileSearchStoreName: 'fileSearchStores/foo-bar', file: 'file.txt', config: {\n   *   mimeType: 'text/plain',\n   * }});\n   * console.log(operation.name);\n   * ```\n   */\n  async uploadToFileSearchStore(\n    params: types.UploadToFileSearchStoreParameters,\n  ): Promise<types.UploadToFileSearchStoreOperation> {\n    if (this.apiClient.isVertexAI()) {\n      throw new Error(\n        'Vertex AI does not support uploading files to a file search store.',\n      );\n    }\n\n    return this.apiClient.uploadFileToFileSearchStore(\n      params.fileSearchStoreName,\n      params.file,\n      params.config,\n    );\n  }\n\n  /**\n   * Creates a File Search Store.\n   *\n   * @param params - The parameters for creating a File Search Store.\n   * @return FileSearchStore.\n   */\n\n  async create(\n    params: types.CreateFileSearchStoreParameters,\n  ): Promise<types.FileSearchStore> {\n    let response: Promise<types.FileSearchStore>;\n\n    let path: string = '';\n    let queryParams: Record<string, string> = {};\n    if (this.apiClient.isVertexAI()) {\n      throw new Error(\n        'This method is only supported by the Gemini Developer API.',\n      );\n    } else {\n      const body = converters.createFileSearchStoreParametersToMldev(params);\n      path = common.formatMap(\n        'fileSearchStores',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'POST',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json();\n        }) as Promise<types.FileSearchStore>;\n\n      return response.then((resp) => {\n        return resp as types.FileSearchStore;\n      });\n    }\n  }\n\n  /**\n   * Gets a File Search Store.\n   *\n   * @param params - The parameters for getting a File Search Store.\n   * @return FileSearchStore.\n   */\n\n  async get(\n    params: types.GetFileSearchStoreParameters,\n  ): Promise<types.FileSearchStore> {\n    let response: Promise<types.FileSearchStore>;\n\n    let path: string = '';\n    let queryParams: Record<string, string> = {};\n    if (this.apiClient.isVertexAI()) {\n      throw new Error(\n        'This method is only supported by the Gemini Developer API.',\n      );\n    } else {\n      const body = converters.getFileSearchStoreParametersToMldev(params);\n      path = common.formatMap(\n        '{name}',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'GET',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json();\n        }) as Promise<types.FileSearchStore>;\n\n      return response.then((resp) => {\n        return resp as types.FileSearchStore;\n      });\n    }\n  }\n\n  /**\n   * Deletes a File Search Store.\n   *\n   * @param params - The parameters for deleting a File Search Store.\n   */\n\n  async delete(params: types.DeleteFileSearchStoreParameters): Promise<void> {\n    let path: string = '';\n    let queryParams: Record<string, string> = {};\n    if (this.apiClient.isVertexAI()) {\n      throw new Error(\n        'This method is only supported by the Gemini Developer API.',\n      );\n    } else {\n      const body = converters.deleteFileSearchStoreParametersToMldev(params);\n      path = common.formatMap(\n        '{name}',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      await this.apiClient.request({\n        path: path,\n        queryParams: queryParams,\n        body: JSON.stringify(body),\n        httpMethod: 'DELETE',\n        httpOptions: params.config?.httpOptions,\n        abortSignal: params.config?.abortSignal,\n      });\n    }\n  }\n\n  private async listInternal(\n    params: types.ListFileSearchStoresParameters,\n  ): Promise<types.ListFileSearchStoresResponse> {\n    let response: Promise<types.ListFileSearchStoresResponse>;\n\n    let path: string = '';\n    let queryParams: Record<string, string> = {};\n    if (this.apiClient.isVertexAI()) {\n      throw new Error(\n        'This method is only supported by the Gemini Developer API.',\n      );\n    } else {\n      const body = converters.listFileSearchStoresParametersToMldev(params);\n      path = common.formatMap(\n        'fileSearchStores',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'GET',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json();\n        }) as Promise<types.ListFileSearchStoresResponse>;\n\n      return response.then((apiResponse) => {\n        const resp =\n          converters.listFileSearchStoresResponseFromMldev(apiResponse);\n        const typedResp = new types.ListFileSearchStoresResponse();\n        Object.assign(typedResp, resp);\n        return typedResp;\n      });\n    }\n  }\n\n  private async uploadToFileSearchStoreInternal(\n    params: types.UploadToFileSearchStoreParameters,\n  ): Promise<types.UploadToFileSearchStoreResumableResponse> {\n    let response: Promise<types.UploadToFileSearchStoreResumableResponse>;\n\n    let path: string = '';\n    let queryParams: Record<string, string> = {};\n    if (this.apiClient.isVertexAI()) {\n      throw new Error(\n        'This method is only supported by the Gemini Developer API.',\n      );\n    } else {\n      const body = converters.uploadToFileSearchStoreParametersToMldev(params);\n      path = common.formatMap(\n        'upload/v1beta/{file_search_store_name}:uploadToFileSearchStore',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'POST',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json();\n        }) as Promise<types.UploadToFileSearchStoreResumableResponse>;\n\n      return response.then((apiResponse) => {\n        const resp =\n          converters.uploadToFileSearchStoreResumableResponseFromMldev(\n            apiResponse,\n          );\n        const typedResp = new types.UploadToFileSearchStoreResumableResponse();\n        Object.assign(typedResp, resp);\n        return typedResp;\n      });\n    }\n  }\n\n  /**\n   * Imports a File from File Service to a FileSearchStore.\n   *\n   * This is a long-running operation, see aip.dev/151\n   *\n   * @param params - The parameters for importing a file to a file search store.\n   * @return ImportFileOperation.\n   */\n\n  async importFile(\n    params: types.ImportFileParameters,\n  ): Promise<types.ImportFileOperation> {\n    let response: Promise<types.ImportFileOperation>;\n\n    let path: string = '';\n    let queryParams: Record<string, string> = {};\n    if (this.apiClient.isVertexAI()) {\n      throw new Error(\n        'This method is only supported by the Gemini Developer API.',\n      );\n    } else {\n      const body = converters.importFileParametersToMldev(params);\n      path = common.formatMap(\n        '{file_search_store_name}:importFile',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'POST',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json();\n        }) as Promise<types.ImportFileOperation>;\n\n      return response.then((apiResponse) => {\n        const resp = converters.importFileOperationFromMldev(apiResponse);\n        const typedResp = new types.ImportFileOperation();\n        Object.assign(typedResp, resp);\n        return typedResp;\n      });\n    }\n  }\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\n/**\n * https://stackoverflow.com/a/2117523\n */\nlet uuid4Internal = function (): string {\n  const { crypto } = globalThis as any;\n  if (crypto?.randomUUID) {\n    uuid4Internal = crypto.randomUUID.bind(crypto);\n    return crypto.randomUUID();\n  }\n  const u8 = new Uint8Array(1);\n  const randomByte = crypto ? () => crypto.getRandomValues(u8)[0]! : () => (Math.random() * 0xff) & 0xff;\n  return '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, (c) =>\n    (+c ^ (randomByte() & (15 >> (+c / 4)))).toString(16),\n  );\n};\n\nexport const uuid4 = (): string => uuid4Internal();\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nexport function isAbortError(err: unknown) {\n  return (\n    typeof err === 'object' &&\n    err !== null &&\n    // Spec-compliant fetch implementations\n    (('name' in err && (err as any).name === 'AbortError') ||\n      // Expo fetch\n      ('message' in err && String((err as any).message).includes('FetchRequestCanceledException')))\n  );\n}\n\nexport const castToError = (err: any): Error => {\n  if (err instanceof Error) return err;\n  if (typeof err === 'object' && err !== null) {\n    try {\n      if (Object.prototype.toString.call(err) === '[object Error]') {\n        // @ts-ignore - not all envs have native support for cause yet\n        const error = new Error(err.message, err.cause ? { cause: err.cause } : {});\n        if (err.stack) error.stack = err.stack;\n        // @ts-ignore - not all envs have native support for cause yet\n        if (err.cause && !error.cause) error.cause = err.cause;\n        if (err.name) error.name = err.name;\n        return error;\n      }\n    } catch {}\n    try {\n      return new Error(JSON.stringify(err));\n    } catch {}\n  }\n  return new Error(err);\n};\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { castToError } from '../internal/errors.js';\n\nexport class GeminiNextGenAPIClientError extends Error {}\n\nexport class APIError<\n  TStatus extends number | undefined = number | undefined,\n  THeaders extends Headers | undefined = Headers | undefined,\n  TError extends Object | undefined = Object | undefined,\n> extends GeminiNextGenAPIClientError {\n  /** HTTP status for the response that caused the error */\n  readonly status: TStatus;\n  /** HTTP headers for the response that caused the error */\n  readonly headers: THeaders;\n  /** JSON body of the response that caused the error */\n  readonly error: TError;\n\n  constructor(status: TStatus, error: TError, message: string | undefined, headers: THeaders) {\n    super(`${APIError.makeMessage(status, error, message)}`);\n    this.status = status;\n    this.headers = headers;\n    this.error = error;\n  }\n\n  private static makeMessage(status: number | undefined, error: any, message: string | undefined) {\n    const msg =\n      error?.message ?\n        typeof error.message === 'string' ?\n          error.message\n        : JSON.stringify(error.message)\n      : error ? JSON.stringify(error)\n      : message;\n\n    if (status && msg) {\n      return `${status} ${msg}`;\n    }\n    if (status) {\n      return `${status} status code (no body)`;\n    }\n    if (msg) {\n      return msg;\n    }\n    return '(no status code or body)';\n  }\n\n  static generate(\n    status: number | undefined,\n    errorResponse: Object | undefined,\n    message: string | undefined,\n    headers: Headers | undefined,\n  ): APIError {\n    if (!status || !headers) {\n      return new APIConnectionError({ message, cause: castToError(errorResponse) });\n    }\n\n    const error = errorResponse as Record<string, any>;\n\n    if (status === 400) {\n      return new BadRequestError(status, error, message, headers);\n    }\n\n    if (status === 401) {\n      return new AuthenticationError(status, error, message, headers);\n    }\n\n    if (status === 403) {\n      return new PermissionDeniedError(status, error, message, headers);\n    }\n\n    if (status === 404) {\n      return new NotFoundError(status, error, message, headers);\n    }\n\n    if (status === 409) {\n      return new ConflictError(status, error, message, headers);\n    }\n\n    if (status === 422) {\n      return new UnprocessableEntityError(status, error, message, headers);\n    }\n\n    if (status === 429) {\n      return new RateLimitError(status, error, message, headers);\n    }\n\n    if (status >= 500) {\n      return new InternalServerError(status, error, message, headers);\n    }\n\n    return new APIError(status, error, message, headers);\n  }\n}\n\nexport class APIUserAbortError extends APIError<undefined, undefined, undefined> {\n  constructor({ message }: { message?: string } = {}) {\n    super(undefined, undefined, message || 'Request was aborted.', undefined);\n  }\n}\n\nexport class APIConnectionError extends APIError<undefined, undefined, undefined> {\n  constructor({ message, cause }: { message?: string | undefined; cause?: Error | undefined }) {\n    super(undefined, undefined, message || 'Connection error.', undefined);\n    // in some environments the 'cause' property is already declared\n    // @ts-ignore\n    if (cause) this.cause = cause;\n  }\n}\n\nexport class APIConnectionTimeoutError extends APIConnectionError {\n  constructor({ message }: { message?: string } = {}) {\n    super({ message: message ?? 'Request timed out.' });\n  }\n}\n\nexport class BadRequestError extends APIError<400, Headers> {}\n\nexport class AuthenticationError extends APIError<401, Headers> {}\n\nexport class PermissionDeniedError extends APIError<403, Headers> {}\n\nexport class NotFoundError extends APIError<404, Headers> {}\n\nexport class ConflictError extends APIError<409, Headers> {}\n\nexport class UnprocessableEntityError extends APIError<422, Headers> {}\n\nexport class RateLimitError extends APIError<429, Headers> {}\n\nexport class InternalServerError extends APIError<number, Headers> {}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { GeminiNextGenAPIClientError } from '../../core/error.js';\n\n// https://url.spec.whatwg.org/#url-scheme-string\nconst startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i;\n\nexport const isAbsoluteURL = (url: string): boolean => {\n  return startsWithSchemeRegexp.test(url);\n};\n\nlet isArrayInternal = (val: unknown): val is unknown[] => (\n  (isArrayInternal = Array.isArray), isArrayInternal(val)\n);\nexport const isArray = isArrayInternal;\nlet isReadonlyArrayInternal = isArray as (val: unknown) => val is readonly unknown[];\nexport const isReadonlyArray = isReadonlyArrayInternal;\n\n/** Returns an object if the given value isn't an object, otherwise returns as-is */\nexport function maybeObj(x: unknown): object {\n  if (typeof x !== 'object') {\n    return {};\n  }\n\n  return x ?? {};\n}\n\n// https://stackoverflow.com/a/34491287\nexport function isEmptyObj(obj: Object | null | undefined): boolean {\n  if (!obj) return true;\n  for (const _k in obj) return false;\n  return true;\n}\n\n// https://eslint.org/docs/latest/rules/no-prototype-builtins\nexport function hasOwn<T extends object = object>(obj: T, key: PropertyKey): key is keyof T {\n  return Object.prototype.hasOwnProperty.call(obj, key);\n}\n\nexport function isObj(obj: unknown): obj is Record<string, unknown> {\n  return obj != null && typeof obj === 'object' && !Array.isArray(obj);\n}\n\nexport const ensurePresent = <T>(value: T | null | undefined): T => {\n  if (value == null) {\n    throw new GeminiNextGenAPIClientError(`Expected a value to be given but received ${value} instead.`);\n  }\n\n  return value;\n};\n\nexport const validatePositiveInteger = (name: string, n: unknown): number => {\n  if (typeof n !== 'number' || !Number.isInteger(n)) {\n    throw new GeminiNextGenAPIClientError(`${name} must be an integer`);\n  }\n  if (n < 0) {\n    throw new GeminiNextGenAPIClientError(`${name} must be a positive integer`);\n  }\n  return n;\n};\n\nexport const coerceInteger = (value: unknown): number => {\n  if (typeof value === 'number') return Math.round(value);\n  if (typeof value === 'string') return parseInt(value, 10);\n\n  throw new GeminiNextGenAPIClientError(`Could not coerce ${value} (type: ${typeof value}) into a number`);\n};\n\nexport const coerceFloat = (value: unknown): number => {\n  if (typeof value === 'number') return value;\n  if (typeof value === 'string') return parseFloat(value);\n\n  throw new GeminiNextGenAPIClientError(`Could not coerce ${value} (type: ${typeof value}) into a number`);\n};\n\nexport const coerceBoolean = (value: unknown): boolean => {\n  if (typeof value === 'boolean') return value;\n  if (typeof value === 'string') return value === 'true';\n  return Boolean(value);\n};\n\nexport const maybeCoerceInteger = (value: unknown): number | undefined => {\n  if (value == null) {\n    return undefined;\n  }\n  return coerceInteger(value);\n};\n\nexport const maybeCoerceFloat = (value: unknown): number | undefined => {\n  if (value == null) {\n    return undefined;\n  }\n  return coerceFloat(value);\n};\n\nexport const maybeCoerceBoolean = (value: unknown): boolean | undefined => {\n  if (value == null) {\n    return undefined;\n  }\n  return coerceBoolean(value);\n};\n\nexport const safeJSON = (text: string) => {\n  try {\n    return JSON.parse(text);\n  } catch (err) {\n    return undefined;\n  }\n};\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nexport const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport const VERSION = '0.0.1';\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { VERSION } from '../version.js';\n\nexport const isRunningInBrowser = () => {\n  return (\n    // @ts-ignore\n    (typeof window !== 'undefined' &&\n    // @ts-ignore\n    typeof window.document !== 'undefined' && typeof navigator !== 'undefined')\n  );\n};\n\ntype DetectedPlatform = 'deno' | 'node' | 'edge' | 'unknown';\n\n/**\n * Note this does not detect 'browser'; for that, use getBrowserInfo().\n */\nfunction getDetectedPlatform(): DetectedPlatform {\n  if (typeof Deno !== 'undefined' && Deno.build != null) {\n    return 'deno';\n  }\n  if (typeof EdgeRuntime !== 'undefined') {\n    return 'edge';\n  }\n  if (\n    Object.prototype.toString.call(\n      typeof (globalThis as any).process !== 'undefined' ? (globalThis as any).process : 0,\n    ) === '[object process]'\n  ) {\n    return 'node';\n  }\n  return 'unknown';\n}\n\ndeclare const Deno: any;\ndeclare const EdgeRuntime: any;\ntype Arch = 'x32' | 'x64' | 'arm' | 'arm64' | `other:${string}` | 'unknown';\ntype PlatformName =\n  | 'MacOS'\n  | 'Linux'\n  | 'Windows'\n  | 'FreeBSD'\n  | 'OpenBSD'\n  | 'iOS'\n  | 'Android'\n  | `Other:${string}`\n  | 'Unknown';\ntype Browser = 'ie' | 'edge' | 'chrome' | 'firefox' | 'safari';\ntype PlatformProperties = {\n  'X-Stainless-Lang': 'js';\n  'X-Stainless-Package-Version': string;\n  'X-Stainless-OS': PlatformName;\n  'X-Stainless-Arch': Arch;\n  'X-Stainless-Runtime': 'node' | 'deno' | 'edge' | `browser:${Browser}` | 'unknown';\n  'X-Stainless-Runtime-Version': string;\n};\nconst getPlatformProperties = (): PlatformProperties => {\n  const detectedPlatform = getDetectedPlatform();\n  if (detectedPlatform === 'deno') {\n    return {\n      'X-Stainless-Lang': 'js',\n      'X-Stainless-Package-Version': VERSION,\n      'X-Stainless-OS': normalizePlatform(Deno.build.os),\n      'X-Stainless-Arch': normalizeArch(Deno.build.arch),\n      'X-Stainless-Runtime': 'deno',\n      'X-Stainless-Runtime-Version':\n        typeof Deno.version === 'string' ? Deno.version : Deno.version?.deno ?? 'unknown',\n    };\n  }\n  if (typeof EdgeRuntime !== 'undefined') {\n    return {\n      'X-Stainless-Lang': 'js',\n      'X-Stainless-Package-Version': VERSION,\n      'X-Stainless-OS': 'Unknown',\n      'X-Stainless-Arch': `other:${EdgeRuntime}`,\n      'X-Stainless-Runtime': 'edge',\n      'X-Stainless-Runtime-Version': (globalThis as any).process.version,\n    };\n  }\n  // Check if Node.js\n  if (detectedPlatform === 'node') {\n    return {\n      'X-Stainless-Lang': 'js',\n      'X-Stainless-Package-Version': VERSION,\n      'X-Stainless-OS': normalizePlatform((globalThis as any).process.platform ?? 'unknown'),\n      'X-Stainless-Arch': normalizeArch((globalThis as any).process.arch ?? 'unknown'),\n      'X-Stainless-Runtime': 'node',\n      'X-Stainless-Runtime-Version': (globalThis as any).process.version ?? 'unknown',\n    };\n  }\n\n  const browserInfo = getBrowserInfo();\n  if (browserInfo) {\n    return {\n      'X-Stainless-Lang': 'js',\n      'X-Stainless-Package-Version': VERSION,\n      'X-Stainless-OS': 'Unknown',\n      'X-Stainless-Arch': 'unknown',\n      'X-Stainless-Runtime': `browser:${browserInfo.browser}`,\n      'X-Stainless-Runtime-Version': browserInfo.version,\n    };\n  }\n\n  // TODO add support for Cloudflare workers, etc.\n  return {\n    'X-Stainless-Lang': 'js',\n    'X-Stainless-Package-Version': VERSION,\n    'X-Stainless-OS': 'Unknown',\n    'X-Stainless-Arch': 'unknown',\n    'X-Stainless-Runtime': 'unknown',\n    'X-Stainless-Runtime-Version': 'unknown',\n  };\n};\n\ntype BrowserInfo = {\n  browser: Browser;\n  version: string;\n};\n\ndeclare const navigator: { userAgent: string } | undefined;\n\n// Note: modified from https://github.com/JS-DevTools/host-environment/blob/b1ab79ecde37db5d6e163c050e54fe7d287d7c92/src/isomorphic.browser.ts\nfunction getBrowserInfo(): BrowserInfo | null {\n  if (typeof navigator === 'undefined' || !navigator) {\n    return null;\n  }\n\n  // NOTE: The order matters here!\n  const browserPatterns = [\n    { key: 'edge' as const, pattern: /Edge(?:\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/ },\n    { key: 'ie' as const, pattern: /MSIE(?:\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/ },\n    { key: 'ie' as const, pattern: /Trident(?:.*rv\\:(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/ },\n    { key: 'chrome' as const, pattern: /Chrome(?:\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/ },\n    { key: 'firefox' as const, pattern: /Firefox(?:\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/ },\n    { key: 'safari' as const, pattern: /(?:Version\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?(?:\\W+Mobile\\S*)?\\W+Safari/ },\n  ];\n\n  // Find the FIRST matching browser\n  for (const { key, pattern } of browserPatterns) {\n    const match = pattern.exec(navigator.userAgent);\n    if (match) {\n      const major = match[1] || 0;\n      const minor = match[2] || 0;\n      const patch = match[3] || 0;\n\n      return { browser: key, version: `${major}.${minor}.${patch}` };\n    }\n  }\n\n  return null;\n}\n\nconst normalizeArch = (arch: string): Arch => {\n  // Node docs:\n  // - https://nodejs.org/api/process.html#processarch\n  // Deno docs:\n  // - https://doc.deno.land/deno/stable/~/Deno.build\n  if (arch === 'x32') return 'x32';\n  if (arch === 'x86_64' || arch === 'x64') return 'x64';\n  if (arch === 'arm') return 'arm';\n  if (arch === 'aarch64' || arch === 'arm64') return 'arm64';\n  if (arch) return `other:${arch}`;\n  return 'unknown';\n};\n\nconst normalizePlatform = (platform: string): PlatformName => {\n  // Node platforms:\n  // - https://nodejs.org/api/process.html#processplatform\n  // Deno platforms:\n  // - https://doc.deno.land/deno/stable/~/Deno.build\n  // - https://github.com/denoland/deno/issues/14799\n\n  platform = platform.toLowerCase();\n\n  // NOTE: this iOS check is untested and may not work\n  // Node does not work natively on IOS, there is a fork at\n  // https://github.com/nodejs-mobile/nodejs-mobile\n  // however it is unknown at the time of writing how to detect if it is running\n  if (platform.includes('ios')) return 'iOS';\n  if (platform === 'android') return 'Android';\n  if (platform === 'darwin') return 'MacOS';\n  if (platform === 'win32') return 'Windows';\n  if (platform === 'freebsd') return 'FreeBSD';\n  if (platform === 'openbsd') return 'OpenBSD';\n  if (platform === 'linux') return 'Linux';\n  if (platform) return `Other:${platform}`;\n  return 'Unknown';\n};\n\nlet _platformHeaders: PlatformProperties;\nexport const getPlatformHeaders = () => {\n  return (_platformHeaders ??= getPlatformProperties());\n};\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\n/**\n * This module provides internal shims and utility functions for environments where certain Node.js or global types may not be available.\n *\n * These are used to ensure we can provide a consistent behaviour between different JavaScript environments and good error\n * messages in cases where an environment isn't fully supported.\n */\n\nimport type { Fetch } from './builtin-types.js';\nimport type { ReadableStream } from './shim-types.js';\n\nexport function getDefaultFetch(): Fetch {\n  if (typeof fetch !== 'undefined') {\n    return fetch as any;\n  }\n\n  throw new Error(\n    '`fetch` is not defined as a global; Either pass `fetch` to the client, `new GeminiNextGenAPIClient({ fetch })` or polyfill the global, `globalThis.fetch = fetch`',\n  );\n}\n\ntype ReadableStreamArgs = ConstructorParameters<typeof ReadableStream>;\n\nexport function makeReadableStream(...args: ReadableStreamArgs): ReadableStream {\n  const ReadableStream = (globalThis as any).ReadableStream;\n  if (typeof ReadableStream === 'undefined') {\n    // Note: All of the platforms / runtimes we officially support already define\n    // `ReadableStream` as a global, so this should only ever be hit on unsupported runtimes.\n    throw new Error(\n      '`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`',\n    );\n  }\n\n  return new ReadableStream(...args);\n}\n\nexport function ReadableStreamFrom<T>(iterable: Iterable<T> | AsyncIterable<T>): ReadableStream<T> {\n  let iter: AsyncIterator<T> | Iterator<T> =\n    Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator]();\n\n  return makeReadableStream({\n    start() {},\n    async pull(controller: any) {\n      const { done, value } = await iter.next();\n      if (done) {\n        controller.close();\n      } else {\n        controller.enqueue(value);\n      }\n    },\n    async cancel() {\n      await iter.return?.();\n    },\n  });\n}\n\n/**\n * Most browsers don't yet have async iterable support for ReadableStream,\n * and Node has a very different way of reading bytes from its \"ReadableStream\".\n *\n * This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490\n */\nexport function ReadableStreamToAsyncIterable<T>(stream: any): AsyncIterableIterator<T> {\n  if (stream[Symbol.asyncIterator]) return stream;\n\n  const reader = stream.getReader();\n  return {\n    async next() {\n      try {\n        const result = await reader.read();\n        if (result?.done) reader.releaseLock(); // release lock when stream becomes closed\n        return result;\n      } catch (e) {\n        reader.releaseLock(); // release lock when stream becomes errored\n        throw e;\n      }\n    },\n    async return() {\n      const cancelPromise = reader.cancel();\n      reader.releaseLock();\n      await cancelPromise;\n      return { done: true, value: undefined };\n    },\n    [Symbol.asyncIterator]() {\n      return this;\n    },\n  };\n}\n\n/**\n * Cancels a ReadableStream we don't need to consume.\n * See https://undici.nodejs.org/#/?id=garbage-collection\n */\nexport async function CancelReadableStream(stream: any): Promise<void> {\n  if (stream === null || typeof stream !== 'object') return;\n\n  if (stream[Symbol.asyncIterator]) {\n    await stream[Symbol.asyncIterator]().return?.();\n    return;\n  }\n\n  const reader = stream.getReader();\n  const cancelPromise = reader.cancel();\n  reader.releaseLock();\n  await cancelPromise;\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { NullableHeaders } from './headers.js';\n\nimport type { BodyInit } from './builtin-types.js';\nimport { Stream } from '../core/streaming.js';\nimport type { HTTPMethod, MergedRequestInit } from './types.js';\nimport { type HeadersLike } from './headers.js';\n\nexport type FinalRequestOptions = RequestOptions & { method: HTTPMethod; path: string };\n\nexport type RequestOptions = {\n  /**\n   * The HTTP method for the request (e.g., 'get', 'post', 'put', 'delete').\n   */\n  method?: HTTPMethod;\n\n  /**\n   * The URL path for the request.\n   *\n   * @example \"/v1/foo\"\n   */\n  path?: string;\n\n  /**\n   * Query parameters to include in the request URL.\n   */\n  query?: object | undefined | null;\n\n  /**\n   * The request body. Can be a string, JSON object, FormData, or other supported types.\n   */\n  body?: unknown;\n\n  /**\n   * HTTP headers to include with the request. Can be a Headers object, plain object, or array of tuples.\n   */\n  headers?: HeadersLike;\n\n  /**\n   * The maximum number of times that the client will retry a request in case of a\n   * temporary failure, like a network error or a 5XX error from the server.\n   *\n   * @default 2\n   */\n  maxRetries?: number;\n\n  stream?: boolean | undefined;\n\n  /**\n   * The maximum amount of time (in milliseconds) that the client should wait for a response\n   * from the server before timing out a single request.\n   *\n   * @unit milliseconds\n   */\n  timeout?: number;\n\n  /**\n   * Additional `RequestInit` options to be passed to the underlying `fetch` call.\n   * These options will be merged with the client's default fetch options.\n   */\n  fetchOptions?: MergedRequestInit;\n\n  /**\n   * An AbortSignal that can be used to cancel the request.\n   */\n  signal?: AbortSignal | undefined | null;\n\n  /**\n   * A unique key for this request to enable idempotency.\n   */\n  idempotencyKey?: string;\n\n  /**\n   * Override the default base URL for this specific request.\n   */\n  defaultBaseURL?: string | undefined;\n\n  __binaryResponse?: boolean | undefined;\n  __streamClass?: typeof Stream;\n};\n\nexport type EncodedContent = { bodyHeaders: HeadersLike; body: BodyInit };\nexport type RequestEncoder = (request: { headers: NullableHeaders; body: unknown }) => EncodedContent;\n\nexport const FallbackEncoder: RequestEncoder = ({ headers, body }) => {\n  return {\n    bodyHeaders: {\n      'content-type': 'application/json',\n    },\n    body: JSON.stringify(body),\n  };\n};\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { type RequestOptions } from './request-options.js';\nimport type { FilePropertyBag, Fetch } from './builtin-types.js';\nimport type { BaseGeminiNextGenAPIClient } from '../client.js';\nimport { ReadableStreamFrom } from './shims.js';\n\nexport type BlobPart = string | ArrayBuffer | ArrayBufferView | Blob | DataView;\ntype FsReadStream = AsyncIterable<Uint8Array> & { path: string | { toString(): string } };\n\n// https://github.com/oven-sh/bun/issues/5980\ninterface BunFile extends Blob {\n  readonly name?: string | undefined;\n}\n\nexport const checkFileSupport = () => {\n  if (typeof File === 'undefined') {\n    const { process } = globalThis as any;\n    const isOldNode =\n      typeof process?.versions?.node === 'string' && parseInt(process.versions.node.split('.')) < 20;\n    throw new Error(\n      '`File` is not defined as a global, which is required for file uploads.' +\n        (isOldNode ?\n          \" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.\"\n        : ''),\n    );\n  }\n};\n\n/**\n * Typically, this is a native \"File\" class.\n *\n * We provide the {@link toFile} utility to convert a variety of objects\n * into the File class.\n *\n * For convenience, you can also pass a fetch Response, or in Node,\n * the result of fs.createReadStream().\n */\nexport type Uploadable = File | Response | FsReadStream | BunFile;\n\n/**\n * Construct a `File` instance. This is used to ensure a helpful error is thrown\n * for environments that don't define a global `File` yet.\n */\nexport function makeFile(\n  fileBits: BlobPart[],\n  fileName: string | undefined,\n  options?: FilePropertyBag,\n): File {\n  checkFileSupport();\n  return new File(fileBits as any, fileName ?? 'unknown_file', options);\n}\n\nexport function getName(value: any): string | undefined {\n  return ((\n    (typeof value === 'object' &&\n      value !== null &&\n      (('name' in value && value.name && String(value.name)) ||\n        ('url' in value && value.url && String(value.url)) ||\n        ('filename' in value && value.filename && String(value.filename)) ||\n        ('path' in value && value.path && String(value.path)))) ||\n    ''\n  )\n    .split(/[\\\\/]/)\n    .pop() || undefined);\n}\n\nexport const isAsyncIterable = (value: any): value is AsyncIterable<any> =>\n  value != null && typeof value === 'object' && typeof value[Symbol.asyncIterator] === 'function';\n\n/**\n * Returns a multipart/form-data request if any part of the given request body contains a File / Blob value.\n * Otherwise returns the request as is.\n */\nexport const maybeMultipartFormRequestOptions = async (\n  opts: RequestOptions,\n  fetch: BaseGeminiNextGenAPIClient | Fetch,\n): Promise<RequestOptions> => {\n  if (!hasUploadableValue(opts.body)) return opts;\n\n  return { ...opts, body: await createForm(opts.body, fetch) };\n};\n\ntype MultipartFormRequestOptions = Omit<RequestOptions, 'body'> & { body: unknown };\n\nexport const multipartFormRequestOptions = async (\n  opts: MultipartFormRequestOptions,\n  fetch: BaseGeminiNextGenAPIClient | Fetch,\n): Promise<RequestOptions> => {\n  return { ...opts, body: await createForm(opts.body, fetch) };\n};\n\nconst supportsFormDataMap = /* @__PURE__ */ new WeakMap<Fetch, Promise<boolean>>();\n\n/**\n * node-fetch doesn't support the global FormData object in recent node versions. Instead of sending\n * properly-encoded form data, it just stringifies the object, resulting in a request body of \"[object FormData]\".\n * This function detects if the fetch function provided supports the global FormData object to avoid\n * confusing error messages later on.\n */\nfunction supportsFormData(fetchObject: BaseGeminiNextGenAPIClient | Fetch): Promise<boolean> {\n  const fetch: Fetch = typeof fetchObject === 'function' ? fetchObject : (fetchObject as any).fetch;\n  const cached = supportsFormDataMap.get(fetch);\n  if (cached) return cached;\n  const promise = (async () => {\n    try {\n      const FetchResponse = (\n        'Response' in fetch ?\n          fetch.Response\n        : (await fetch('data:,')).constructor) as typeof Response;\n      const data = new FormData();\n      if (data.toString() === (await new FetchResponse(data).text())) {\n        return false;\n      }\n      return true;\n    } catch {\n      // avoid false negatives\n      return true;\n    }\n  })();\n  supportsFormDataMap.set(fetch, promise);\n  return promise;\n}\n\nexport const createForm = async <T = Record<string, unknown>>(\n  body: T | undefined,\n  fetch: BaseGeminiNextGenAPIClient | Fetch,\n): Promise<FormData> => {\n  if (!(await supportsFormData(fetch))) {\n    throw new TypeError(\n      'The provided fetch function does not support file uploads with the current global FormData class.',\n    );\n  }\n  const form = new FormData();\n  await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value)));\n  return form;\n};\n\n// We check for Blob not File because Bun.File doesn't inherit from File,\n// but they both inherit from Blob and have a `name` property at runtime.\nconst isNamedBlob = (value: unknown): value is Blob => value instanceof Blob && 'name' in value;\n\nconst isUploadable = (value: unknown) =>\n  typeof value === 'object' &&\n  value !== null &&\n  (value instanceof Response || isAsyncIterable(value) || isNamedBlob(value));\n\nconst hasUploadableValue = (value: unknown): boolean => {\n  if (isUploadable(value)) return true;\n  if (Array.isArray(value)) return value.some(hasUploadableValue);\n  if (value && typeof value === 'object') {\n    for (const k in value) {\n      if (hasUploadableValue((value as any)[k])) return true;\n    }\n  }\n  return false;\n};\n\nconst addFormValue = async (form: FormData, key: string, value: unknown): Promise<void> => {\n  if (value === undefined) return;\n  if (value == null) {\n    throw new TypeError(\n      `Received null for \"${key}\"; to pass null in FormData, you must use the string 'null'`,\n    );\n  }\n\n  // TODO: make nested formats configurable\n  if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n    form.append(key, String(value));\n  } else if (value instanceof Response) {\n    form.append(key, makeFile([await value.blob()], getName(value)));\n  } else if (isAsyncIterable(value)) {\n    form.append(key, makeFile([await new Response(ReadableStreamFrom(value)).blob()], getName(value)));\n  } else if (isNamedBlob(value)) {\n    form.append(key, value, getName(value));\n  } else if (Array.isArray(value)) {\n    await Promise.all(value.map((entry) => addFormValue(form, key + '[]', entry)));\n  } else if (typeof value === 'object') {\n    await Promise.all(\n      Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop)),\n    );\n  } else {\n    throw new TypeError(\n      `Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`,\n    );\n  }\n};\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { BlobPart, getName, makeFile, isAsyncIterable } from './uploads.js';\nimport type { FilePropertyBag } from './builtin-types.js';\nimport { checkFileSupport } from './uploads.js';\n\nexport type BlobLikePart = string | ArrayBuffer | ArrayBufferView | BlobLike | DataView;\n\n/**\n * Intended to match DOM Blob, node-fetch Blob, node:buffer Blob, etc.\n * Don't add arrayBuffer here, node-fetch doesn't have it\n */\nexport interface BlobLike {\n  /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) */\n  readonly size: number;\n  /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) */\n  readonly type: string;\n  /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) */\n  text(): Promise<string>;\n  /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) */\n  slice(start?: number, end?: number): BlobLike;\n}\n\n/**\n * This check adds the arrayBuffer() method type because it is available and used at runtime\n */\nconst isBlobLike = (value: any): value is BlobLike & { arrayBuffer(): Promise<ArrayBuffer> } =>\n  value != null &&\n  typeof value === 'object' &&\n  typeof value.size === 'number' &&\n  typeof value.type === 'string' &&\n  typeof value.text === 'function' &&\n  typeof value.slice === 'function' &&\n  typeof value.arrayBuffer === 'function';\n\n/**\n * Intended to match DOM File, node:buffer File, undici File, etc.\n */\ninterface FileLike extends BlobLike {\n  /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) */\n  readonly lastModified: number;\n  /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) */\n  readonly name?: string | undefined;\n}\n\n/**\n * This check adds the arrayBuffer() method type because it is available and used at runtime\n */\nconst isFileLike = (value: any): value is FileLike & { arrayBuffer(): Promise<ArrayBuffer> } =>\n  value != null &&\n  typeof value === 'object' &&\n  typeof value.name === 'string' &&\n  typeof value.lastModified === 'number' &&\n  isBlobLike(value);\n\n/**\n * Intended to match DOM Response, node-fetch Response, undici Response, etc.\n */\nexport interface ResponseLike {\n  url: string;\n  blob(): Promise<BlobLike>;\n}\n\nconst isResponseLike = (value: any): value is ResponseLike =>\n  value != null &&\n  typeof value === 'object' &&\n  typeof value.url === 'string' &&\n  typeof value.blob === 'function';\n\nexport type ToFileInput =\n  | FileLike\n  | ResponseLike\n  | Exclude<BlobLikePart, string>\n  | AsyncIterable<BlobLikePart>;\n\n/**\n * Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats\n * @param value the raw content of the file. Can be an {@link Uploadable}, BlobLikePart, or AsyncIterable of BlobLikeParts\n * @param {string=} name the name of the file. If omitted, toFile will try to determine a file name from bits if possible\n * @param {Object=} options additional properties\n * @param {string=} options.type the MIME type of the content\n * @param {number=} options.lastModified the last modified timestamp\n * @returns a {@link File} with the given properties\n */\nexport async function toFile(\n  value: ToFileInput | PromiseLike<ToFileInput>,\n  name?: string | null | undefined,\n  options?: FilePropertyBag | undefined,\n): Promise<File> {\n  checkFileSupport();\n\n  // If it's a promise, resolve it.\n  value = await value;\n\n  // If we've been given a `File` we don't need to do anything\n  if (isFileLike(value)) {\n    if (value instanceof File) {\n      return value;\n    }\n    return makeFile([await value.arrayBuffer()], value.name);\n  }\n\n  if (isResponseLike(value)) {\n    const blob = await value.blob();\n    name ||= new URL(value.url).pathname.split(/[\\\\/]/).pop();\n\n    return makeFile(await getBytes(blob), name, options);\n  }\n\n  const parts = await getBytes(value);\n\n  name ||= getName(value);\n\n  if (!options?.type) {\n    const type = parts.find((part) => typeof part === 'object' && 'type' in part && part.type);\n    if (typeof type === 'string') {\n      options = { ...options, type };\n    }\n  }\n\n  return makeFile(parts, name, options);\n}\n\nasync function getBytes(value: BlobLikePart | AsyncIterable<BlobLikePart>): Promise<Array<BlobPart>> {\n  let parts: Array<BlobPart> = [];\n  if (\n    typeof value === 'string' ||\n    ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc.\n    value instanceof ArrayBuffer\n  ) {\n    parts.push(value);\n  } else if (isBlobLike(value)) {\n    parts.push(value instanceof Blob ? value : await value.arrayBuffer());\n  } else if (\n    isAsyncIterable(value) // includes Readable, ReadableStream, etc.\n  ) {\n    for await (const chunk of value) {\n      parts.push(...(await getBytes(chunk as BlobLikePart))); // TODO, consider validating?\n    }\n  } else {\n    const constructor = value?.constructor?.name;\n    throw new Error(\n      `Unexpected data type: ${typeof value}${\n        constructor ? `; constructor: ${constructor}` : ''\n      }${propsForError(value)}`,\n    );\n  }\n\n  return parts;\n}\n\nfunction propsForError(value: unknown): string {\n  if (typeof value !== 'object' || value === null) return '';\n  const props = Object.getOwnPropertyNames(value);\n  return `; props: [${props.map((p) => `\"${p}\"`).join(', ')}]`;\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { BaseGeminiNextGenAPIClient } from '../client.js';\n\nexport abstract class APIResource {\n  /**\n   * The key path from the client. For example, a resource accessible as `client.resource.subresource` would\n   * have a property `static override readonly _key = Object.freeze(['resource', 'subresource'] as const);`.\n   */\n  static readonly _key: readonly string[] = [];\n  protected _client: BaseGeminiNextGenAPIClient;\n\n  constructor(client: BaseGeminiNextGenAPIClient) {\n    this._client = client;\n  }\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { GeminiNextGenAPIClientError } from '../../core/error.js';\n\n/**\n * Percent-encode everything that isn't safe to have in a path without encoding safe chars.\n *\n * Taken from https://datatracker.ietf.org/doc/html/rfc3986#section-3.3:\n * > unreserved  = ALPHA / DIGIT / \"-\" / \".\" / \"_\" / \"~\"\n * > sub-delims  = \"!\" / \"$\" / \"&\" / \"'\" / \"(\" / \")\" / \"*\" / \"+\" / \",\" / \";\" / \"=\"\n * > pchar       = unreserved / pct-encoded / sub-delims / \":\" / \"@\"\n */\nexport function encodeURIPath(str: string) {\n  return str.replace(/[^A-Za-z0-9\\-._~!$&'()*+,;=:@]+/g, encodeURIComponent);\n}\n\nconst EMPTY = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null));\n\nexport const createPathTagFunction = (pathEncoder = encodeURIPath) =>\n  (function path(statics: readonly string[], ...params: readonly unknown[]): string {\n    // If there are no params, no processing is needed.\n    if (statics.length === 1) return statics[0]!;\n\n    let postPath = false;\n    const invalidSegments = [];\n    const path = statics.reduce((previousValue, currentValue, index) => {\n      if (/[?#]/.test(currentValue)) {\n        postPath = true;\n      }\n      const value = params[index];\n      let encoded = (postPath ? encodeURIComponent : pathEncoder)('' + value);\n      if (\n        index !== params.length &&\n        (value == null ||\n          (typeof value === 'object' &&\n            // handle values from other realms\n            value.toString ===\n              Object.getPrototypeOf(Object.getPrototypeOf((value as any).hasOwnProperty ?? EMPTY) ?? EMPTY)\n                ?.toString))\n      ) {\n        encoded = value + '';\n        invalidSegments.push({\n          start: previousValue.length + currentValue.length,\n          length: encoded.length,\n          error: `Value of type ${Object.prototype.toString\n            .call(value)\n            .slice(8, -1)} is not a valid path parameter`,\n        });\n      }\n      return previousValue + currentValue + (index === params.length ? '' : encoded);\n    }, '');\n\n    const pathOnly = path.split(/[?#]/, 1)[0]!;\n    const invalidSegmentPattern = /(?<=^|\\/)(?:\\.|%2e){1,2}(?=\\/|$)/gi;\n    let match;\n\n    // Find all invalid segments\n    while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) {\n      invalidSegments.push({\n        start: match.index,\n        length: match[0].length,\n        error: `Value \"${match[0]}\" can\\'t be safely passed as a path parameter`,\n      });\n    }\n\n    invalidSegments.sort((a, b) => a.start - b.start);\n\n    if (invalidSegments.length > 0) {\n      let lastEnd = 0;\n      const underline = invalidSegments.reduce((acc, segment) => {\n        const spaces = ' '.repeat(segment.start - lastEnd);\n        const arrows = '^'.repeat(segment.length);\n        lastEnd = segment.start + segment.length;\n        return acc + spaces + arrows;\n      }, '');\n\n      throw new GeminiNextGenAPIClientError(\n        `Path parameters result in path with invalid segments:\\n${invalidSegments\n          .map((e) => e.error)\n          .join('\\n')}\\n${path}\\n${underline}`,\n      );\n    }\n\n    return path;\n  });\n\n/**\n * URI-encodes path params and ensures no unsafe /./ or /../ path segments are introduced.\n */\nexport const path = /* @__PURE__ */ createPathTagFunction(encodeURIPath);\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { APIResource } from '../core/resource.js';\nimport * as Errors from '../core/error.js';\nimport * as InteractionsAPI from './interactions.js';\nimport { APIPromise } from '../core/api-promise.js';\nimport { Stream } from '../core/streaming.js';\nimport { RequestOptions } from '../internal/request-options.js';\nimport { path } from '../internal/utils/path.js';\n\nexport class BaseInteractions extends APIResource {\n  static override readonly _key: readonly ['interactions'] = Object.freeze(['interactions'] as const);\n\n  /**\n   * Creates a new interaction.\n   *\n   * @example\n   * ```ts\n   * const interaction = await client.interactions.create({\n   *   input: 'string',\n   *   model: 'gemini-2.5-pro',\n   * });\n   * ```\n   */\n  create(params: CreateModelInteractionParamsNonStreaming, options?: RequestOptions): APIPromise<Interaction>;\n  create(\n    params: CreateModelInteractionParamsStreaming,\n    options?: RequestOptions,\n  ): APIPromise<Stream<InteractionSSEEvent>>;\n  create(params: CreateAgentInteractionParamsNonStreaming, options?: RequestOptions): APIPromise<Interaction>;\n  create(\n    params: CreateAgentInteractionParamsStreaming,\n    options?: RequestOptions,\n  ): APIPromise<Stream<InteractionSSEEvent>>;\n  create(\n    params: BaseCreateModelInteractionParams | BaseCreateAgentInteractionParams,\n    options?: RequestOptions,\n  ): APIPromise<Stream<InteractionSSEEvent> | Interaction>;\n  create(\n    params: InteractionCreateParams,\n    options?: RequestOptions,\n  ): APIPromise<Interaction> | APIPromise<Stream<InteractionSSEEvent>> {\n    const { api_version = this._client.apiVersion, ...body } = params;\n    if ('model' in body && 'agent_config' in body) {\n      throw new Errors.GeminiNextGenAPIClientError(\n        `Invalid request: specified \\`model\\` and \\`agent_config\\`. If specifying \\`model\\`, use \\`generation_config\\`.`,\n      );\n    }\n    if ('agent' in body && 'generation_config' in body) {\n      throw new Errors.GeminiNextGenAPIClientError(\n        `Invalid request: specified \\`agent\\` and \\`generation_config\\`. If specifying \\`agent\\`, use \\`agent_config\\`.`,\n      );\n    }\n    return this._client.post(path`/${api_version}/interactions`, {\n      body,\n      ...options,\n      stream: params.stream ?? false,\n    }) as APIPromise<Interaction> | APIPromise<Stream<InteractionSSEEvent>>;\n  }\n\n  /**\n   * Deletes the interaction by id.\n   *\n   * @example\n   * ```ts\n   * const interaction = await client.interactions.delete('id');\n   * ```\n   */\n  delete(\n    id: string,\n    params: InteractionDeleteParams | null | undefined = {},\n    options?: RequestOptions,\n  ): APIPromise<unknown> {\n    const { api_version = this._client.apiVersion } = params ?? {};\n    return this._client.delete(path`/${api_version}/interactions/${id}`, options);\n  }\n\n  /**\n   * Cancels an interaction by id. This only applies to background interactions that are still running.\n   *\n   * @example\n   * ```ts\n   * const interaction = await client.interactions.cancel('id');\n   * ```\n   */\n  cancel(\n    id: string,\n    params: InteractionCancelParams | null | undefined = {},\n    options?: RequestOptions,\n  ): APIPromise<Interaction> {\n    const { api_version = this._client.apiVersion } = params ?? {};\n    return this._client.post(path`/${api_version}/interactions/${id}/cancel`, options);\n  }\n\n  /**\n   * Retrieves the full details of a single interaction based on its `Interaction.id`.\n   *\n   * @example\n   * ```ts\n   * const interaction = await client.interactions.get('id');\n   * ```\n   */\n  get(\n    id: string,\n    params?: InteractionGetParamsNonStreaming,\n    options?: RequestOptions,\n  ): APIPromise<Interaction>;\n  get(\n    id: string,\n    params: InteractionGetParamsStreaming,\n    options?: RequestOptions,\n  ): APIPromise<Stream<InteractionSSEEvent>>;\n  get(\n    id: string,\n    params?: InteractionGetParamsBase | undefined,\n    options?: RequestOptions,\n  ): APIPromise<Stream<InteractionSSEEvent> | Interaction>;\n  get(\n    id: string,\n    params: InteractionGetParams | undefined = {},\n    options?: RequestOptions,\n  ): APIPromise<Interaction> | APIPromise<Stream<InteractionSSEEvent>> {\n    const { api_version = this._client.apiVersion, ...query } = params ?? {};\n    return this._client.get(path`/${api_version}/interactions/${id}`, {\n      query,\n      ...options,\n      stream: params?.stream ?? false,\n    }) as APIPromise<Interaction> | APIPromise<Stream<InteractionSSEEvent>>;\n  }\n}\nexport class Interactions extends BaseInteractions {}\n\n/**\n * The configuration for allowed tools.\n */\nexport interface AllowedTools {\n  /**\n   * The mode of the tool choice.\n   */\n  mode?: ToolChoiceType;\n\n  /**\n   * The names of the allowed tools.\n   */\n  tools?: Array<string>;\n}\n\n/**\n * Citation information for model-generated content.\n */\nexport interface Annotation {\n  /**\n   * End of the attributed segment, exclusive.\n   */\n  end_index?: number;\n\n  /**\n   * Source attributed for a portion of the text. Could be a URL, title, or\n   * other identifier.\n   */\n  source?: string;\n\n  /**\n   * Start of segment of the response that is attributed to this source.\n   *\n   * Index indicates the start of the segment, measured in bytes.\n   */\n  start_index?: number;\n}\n\n/**\n * An audio content block.\n */\nexport interface AudioContent {\n  /**\n   * Used as the OpenAPI type discriminator for the content oneof.\n   */\n  type: 'audio';\n\n  data?: string;\n\n  /**\n   * The mime type of the audio.\n   */\n  mime_type?: AudioMimeType;\n\n  uri?: string;\n}\n\n/**\n * The mime type of the audio.\n */\nexport type AudioMimeType =\n  | 'audio/wav'\n  | 'audio/mp3'\n  | 'audio/aiff'\n  | 'audio/aac'\n  | 'audio/ogg'\n  | 'audio/flac'\n  | (string & {});\n\n/**\n * The arguments to pass to the code execution.\n */\nexport interface CodeExecutionCallArguments {\n  /**\n   * The code to be executed.\n   */\n  code?: string;\n\n  /**\n   * Programming language of the `code`.\n   */\n  language?: 'python';\n}\n\n/**\n * Code execution content.\n */\nexport interface CodeExecutionCallContent {\n  /**\n   * Used as the OpenAPI type discriminator for the content oneof.\n   */\n  type: 'code_execution_call';\n\n  /**\n   * A unique ID for this specific tool call.\n   */\n  id?: string;\n\n  /**\n   * The arguments to pass to the code execution.\n   */\n  arguments?: CodeExecutionCallArguments;\n}\n\n/**\n * Code execution result content.\n */\nexport interface CodeExecutionResultContent {\n  /**\n   * Used as the OpenAPI type discriminator for the content oneof.\n   */\n  type: 'code_execution_result';\n\n  /**\n   * ID to match the ID from the code execution call block.\n   */\n  call_id?: string;\n\n  /**\n   * Whether the code execution resulted in an error.\n   */\n  is_error?: boolean;\n\n  /**\n   * The output of the code execution.\n   */\n  result?: string;\n\n  /**\n   * A signature hash for backend validation.\n   */\n  signature?: string;\n}\n\nexport interface ContentDelta {\n  delta?:\n    | ContentDelta.TextDelta\n    | ContentDelta.ImageDelta\n    | ContentDelta.AudioDelta\n    | ContentDelta.DocumentDelta\n    | ContentDelta.VideoDelta\n    | ContentDelta.ThoughtSummaryDelta\n    | ContentDelta.ThoughtSignatureDelta\n    | ContentDelta.FunctionCallDelta\n    | ContentDelta.FunctionResultDelta\n    | ContentDelta.CodeExecutionCallDelta\n    | ContentDelta.CodeExecutionResultDelta\n    | ContentDelta.URLContextCallDelta\n    | ContentDelta.URLContextResultDelta\n    | ContentDelta.GoogleSearchCallDelta\n    | ContentDelta.GoogleSearchResultDelta\n    | ContentDelta.MCPServerToolCallDelta\n    | ContentDelta.MCPServerToolResultDelta\n    | ContentDelta.FileSearchResultDelta;\n\n  /**\n   * The event_id token to be used to resume the interaction stream, from\n   * this event.\n   */\n  event_id?: string;\n\n  event_type?: 'content.delta';\n\n  index?: number;\n}\n\nexport namespace ContentDelta {\n  export interface TextDelta {\n    /**\n     * Used as the OpenAPI type discriminator for the content oneof.\n     */\n    type: 'text';\n\n    /**\n     * Citation information for model-generated content.\n     */\n    annotations?: Array<InteractionsAPI.Annotation>;\n\n    text?: string;\n  }\n\n  export interface ImageDelta {\n    /**\n     * Used as the OpenAPI type discriminator for the content oneof.\n     */\n    type: 'image';\n\n    data?: string;\n\n    /**\n     * The mime type of the image.\n     */\n    mime_type?: InteractionsAPI.ImageMimeType;\n\n    /**\n     * The resolution of the media.\n     */\n    resolution?: 'low' | 'medium' | 'high';\n\n    uri?: string;\n  }\n\n  export interface AudioDelta {\n    /**\n     * Used as the OpenAPI type discriminator for the content oneof.\n     */\n    type: 'audio';\n\n    data?: string;\n\n    /**\n     * The mime type of the audio.\n     */\n    mime_type?: InteractionsAPI.AudioMimeType;\n\n    uri?: string;\n  }\n\n  export interface DocumentDelta {\n    /**\n     * Used as the OpenAPI type discriminator for the content oneof.\n     */\n    type: 'document';\n\n    data?: string;\n\n    mime_type?: string;\n\n    uri?: string;\n  }\n\n  export interface VideoDelta {\n    /**\n     * Used as the OpenAPI type discriminator for the content oneof.\n     */\n    type: 'video';\n\n    data?: string;\n\n    /**\n     * The mime type of the video.\n     */\n    mime_type?: InteractionsAPI.VideoMimeType;\n\n    /**\n     * The resolution of the media.\n     */\n    resolution?: 'low' | 'medium' | 'high';\n\n    uri?: string;\n  }\n\n  export interface ThoughtSummaryDelta {\n    /**\n     * Used as the OpenAPI type discriminator for the content oneof.\n     */\n    type: 'thought_summary';\n\n    /**\n     * A text content block.\n     */\n    content?: InteractionsAPI.TextContent | InteractionsAPI.ImageContent;\n  }\n\n  export interface ThoughtSignatureDelta {\n    /**\n     * Used as the OpenAPI type discriminator for the content oneof.\n     */\n    type: 'thought_signature';\n\n    /**\n     * Signature to match the backend source to be part of the generation.\n     */\n    signature?: string;\n  }\n\n  export interface FunctionCallDelta {\n    /**\n     * Used as the OpenAPI type discriminator for the content oneof.\n     */\n    type: 'function_call';\n\n    /**\n     * A unique ID for this specific tool call.\n     */\n    id?: string;\n\n    arguments?: { [key: string]: unknown };\n\n    name?: string;\n  }\n\n  export interface FunctionResultDelta {\n    /**\n     * Used as the OpenAPI type discriminator for the content oneof.\n     */\n    type: 'function_result';\n\n    /**\n     * ID to match the ID from the function call block.\n     */\n    call_id?: string;\n\n    is_error?: boolean;\n\n    name?: string;\n\n    /**\n     * Tool call result delta.\n     */\n    result?: FunctionResultDelta.Items | string;\n  }\n\n  export namespace FunctionResultDelta {\n    export interface Items {\n      items?: Array<string | InteractionsAPI.ImageContent>;\n    }\n  }\n\n  export interface CodeExecutionCallDelta {\n    /**\n     * Used as the OpenAPI type discriminator for the content oneof.\n     */\n    type: 'code_execution_call';\n\n    /**\n     * A unique ID for this specific tool call.\n     */\n    id?: string;\n\n    /**\n     * The arguments to pass to the code execution.\n     */\n    arguments?: InteractionsAPI.CodeExecutionCallArguments;\n  }\n\n  export interface CodeExecutionResultDelta {\n    /**\n     * Used as the OpenAPI type discriminator for the content oneof.\n     */\n    type: 'code_execution_result';\n\n    /**\n     * ID to match the ID from the function call block.\n     */\n    call_id?: string;\n\n    is_error?: boolean;\n\n    result?: string;\n\n    signature?: string;\n  }\n\n  export interface URLContextCallDelta {\n    /**\n     * Used as the OpenAPI type discriminator for the content oneof.\n     */\n    type: 'url_context_call';\n\n    /**\n     * A unique ID for this specific tool call.\n     */\n    id?: string;\n\n    /**\n     * The arguments to pass to the URL context.\n     */\n    arguments?: InteractionsAPI.URLContextCallArguments;\n  }\n\n  export interface URLContextResultDelta {\n    /**\n     * Used as the OpenAPI type discriminator for the content oneof.\n     */\n    type: 'url_context_result';\n\n    /**\n     * ID to match the ID from the function call block.\n     */\n    call_id?: string;\n\n    is_error?: boolean;\n\n    result?: Array<InteractionsAPI.URLContextResult>;\n\n    signature?: string;\n  }\n\n  export interface GoogleSearchCallDelta {\n    /**\n     * Used as the OpenAPI type discriminator for the content oneof.\n     */\n    type: 'google_search_call';\n\n    /**\n     * A unique ID for this specific tool call.\n     */\n    id?: string;\n\n    /**\n     * The arguments to pass to Google Search.\n     */\n    arguments?: InteractionsAPI.GoogleSearchCallArguments;\n  }\n\n  export interface GoogleSearchResultDelta {\n    /**\n     * Used as the OpenAPI type discriminator for the content oneof.\n     */\n    type: 'google_search_result';\n\n    /**\n     * ID to match the ID from the function call block.\n     */\n    call_id?: string;\n\n    is_error?: boolean;\n\n    result?: Array<InteractionsAPI.GoogleSearchResult>;\n\n    signature?: string;\n  }\n\n  export interface MCPServerToolCallDelta {\n    /**\n     * Used as the OpenAPI type discriminator for the content oneof.\n     */\n    type: 'mcp_server_tool_call';\n\n    /**\n     * A unique ID for this specific tool call.\n     */\n    id?: string;\n\n    arguments?: { [key: string]: unknown };\n\n    name?: string;\n\n    server_name?: string;\n  }\n\n  export interface MCPServerToolResultDelta {\n    /**\n     * Used as the OpenAPI type discriminator for the content oneof.\n     */\n    type: 'mcp_server_tool_result';\n\n    /**\n     * ID to match the ID from the function call block.\n     */\n    call_id?: string;\n\n    name?: string;\n\n    /**\n     * Tool call result delta.\n     */\n    result?: MCPServerToolResultDelta.Items | string;\n\n    server_name?: string;\n  }\n\n  export namespace MCPServerToolResultDelta {\n    export interface Items {\n      items?: Array<string | InteractionsAPI.ImageContent>;\n    }\n  }\n\n  export interface FileSearchResultDelta {\n    /**\n     * Used as the OpenAPI type discriminator for the content oneof.\n     */\n    type: 'file_search_result';\n\n    result?: Array<FileSearchResultDelta.Result>;\n  }\n\n  export namespace FileSearchResultDelta {\n    /**\n     * The result of the File Search.\n     */\n    export interface Result {\n      /**\n       * The name of the file search store.\n       */\n      file_search_store?: string;\n\n      /**\n       * The text of the search result.\n       */\n      text?: string;\n\n      /**\n       * The title of the search result.\n       */\n      title?: string;\n    }\n  }\n}\n\nexport interface ContentStart {\n  /**\n   * The content of the response.\n   */\n  content?:\n    | TextContent\n    | ImageContent\n    | AudioContent\n    | DocumentContent\n    | VideoContent\n    | ThoughtContent\n    | FunctionCallContent\n    | FunctionResultContent\n    | CodeExecutionCallContent\n    | CodeExecutionResultContent\n    | URLContextCallContent\n    | URLContextResultContent\n    | GoogleSearchCallContent\n    | GoogleSearchResultContent\n    | MCPServerToolCallContent\n    | MCPServerToolResultContent\n    | FileSearchResultContent;\n\n  /**\n   * The event_id token to be used to resume the interaction stream, from\n   * this event.\n   */\n  event_id?: string;\n\n  event_type?: 'content.start';\n\n  index?: number;\n}\n\nexport interface ContentStop {\n  /**\n   * The event_id token to be used to resume the interaction stream, from\n   * this event.\n   */\n  event_id?: string;\n\n  event_type?: 'content.stop';\n\n  index?: number;\n}\n\n/**\n * Configuration for the Deep Research agent.\n */\nexport interface DeepResearchAgentConfig {\n  /**\n   * Whether to include thought summaries in the response.\n   */\n  thinking_summaries?: 'auto' | 'none';\n\n  /**\n   * Used as the OpenAPI type discriminator for the content oneof.\n   */\n  type?: 'deep-research';\n}\n\n/**\n * A document content block.\n */\nexport interface DocumentContent {\n  /**\n   * Used as the OpenAPI type discriminator for the content oneof.\n   */\n  type: 'document';\n\n  data?: string;\n\n  mime_type?: string;\n\n  uri?: string;\n}\n\n/**\n * Configuration for dynamic agents.\n */\nexport interface DynamicAgentConfig {\n  /**\n   * Used as the OpenAPI type discriminator for the content oneof.\n   */\n  type?: 'dynamic';\n\n  [k: string]: unknown;\n}\n\nexport interface ErrorEvent {\n  /**\n   * Error message from an interaction.\n   */\n  error?: ErrorEvent.Error;\n\n  /**\n   * The event_id token to be used to resume the interaction stream, from\n   * this event.\n   */\n  event_id?: string;\n\n  event_type?: 'error';\n}\n\nexport namespace ErrorEvent {\n  /**\n   * Error message from an interaction.\n   */\n  export interface Error {\n    /**\n     * A URI that identifies the error type.\n     */\n    code?: string;\n\n    /**\n     * A human-readable error message.\n     */\n    message?: string;\n  }\n}\n\n/**\n * File Search result content.\n */\nexport interface FileSearchResultContent {\n  /**\n   * Used as the OpenAPI type discriminator for the content oneof.\n   */\n  type: 'file_search_result';\n\n  /**\n   * The results of the File Search.\n   */\n  result?: Array<FileSearchResultContent.Result>;\n}\n\nexport namespace FileSearchResultContent {\n  /**\n   * The result of the File Search.\n   */\n  export interface Result {\n    /**\n     * The name of the file search store.\n     */\n    file_search_store?: string;\n\n    /**\n     * The text of the search result.\n     */\n    text?: string;\n\n    /**\n     * The title of the search result.\n     */\n    title?: string;\n  }\n}\n\n/**\n * A tool that can be used by the model.\n */\nexport interface Function {\n  type: 'function';\n\n  /**\n   * A description of the function.\n   */\n  description?: string;\n\n  /**\n   * The name of the function.\n   */\n  name?: string;\n\n  /**\n   * The JSON Schema for the function's parameters.\n   */\n  parameters?: unknown;\n}\n\n/**\n * A function tool call content block.\n */\nexport interface FunctionCallContent {\n  /**\n   * A unique ID for this specific tool call.\n   */\n  id: string;\n\n  /**\n   * The arguments to pass to the function.\n   */\n  arguments: { [key: string]: unknown };\n\n  /**\n   * The name of the tool to call.\n   */\n  name: string;\n\n  /**\n   * Used as the OpenAPI type discriminator for the content oneof.\n   */\n  type: 'function_call';\n}\n\n/**\n * A function tool result content block.\n */\nexport interface FunctionResultContent {\n  /**\n   * ID to match the ID from the function call block.\n   */\n  call_id: string;\n\n  /**\n   * The result of the tool call.\n   */\n  result: FunctionResultContent.Items | unknown | string;\n\n  /**\n   * Used as the OpenAPI type discriminator for the content oneof.\n   */\n  type: 'function_result';\n\n  /**\n   * Whether the tool call resulted in an error.\n   */\n  is_error?: boolean;\n\n  /**\n   * The name of the tool that was called.\n   */\n  name?: string;\n}\n\nexport namespace FunctionResultContent {\n  export interface Items {\n    items?: Array<string | InteractionsAPI.ImageContent>;\n  }\n}\n\n/**\n * Configuration parameters for model interactions.\n */\nexport interface GenerationConfig {\n  /**\n   * The maximum number of tokens to include in the response.\n   */\n  max_output_tokens?: number;\n\n  /**\n   * Seed used in decoding for reproducibility.\n   */\n  seed?: number;\n\n  /**\n   * Configuration for speech interaction.\n   */\n  speech_config?: Array<SpeechConfig>;\n\n  /**\n   * A list of character sequences that will stop output interaction.\n   */\n  stop_sequences?: Array<string>;\n\n  /**\n   * Controls the randomness of the output.\n   */\n  temperature?: number;\n\n  /**\n   * The level of thought tokens that the model should generate.\n   */\n  thinking_level?: ThinkingLevel;\n\n  /**\n   * Whether to include thought summaries in the response.\n   */\n  thinking_summaries?: 'auto' | 'none';\n\n  /**\n   * The tool choice for the interaction.\n   */\n  tool_choice?: ToolChoice;\n\n  /**\n   * The maximum cumulative probability of tokens to consider when sampling.\n   */\n  top_p?: number;\n}\n\n/**\n * The arguments to pass to Google Search.\n */\nexport interface GoogleSearchCallArguments {\n  /**\n   * Web search queries for the following-up web search.\n   */\n  queries?: Array<string>;\n}\n\n/**\n * Google Search content.\n */\nexport interface GoogleSearchCallContent {\n  /**\n   * Used as the OpenAPI type discriminator for the content oneof.\n   */\n  type: 'google_search_call';\n\n  /**\n   * A unique ID for this specific tool call.\n   */\n  id?: string;\n\n  /**\n   * The arguments to pass to Google Search.\n   */\n  arguments?: GoogleSearchCallArguments;\n}\n\n/**\n * The result of the Google Search.\n */\nexport interface GoogleSearchResult {\n  /**\n   * Web content snippet that can be embedded in a web page or an app webview.\n   */\n  rendered_content?: string;\n\n  /**\n   * Title of the search result.\n   */\n  title?: string;\n\n  /**\n   * URI reference of the search result.\n   */\n  url?: string;\n}\n\n/**\n * Google Search result content.\n */\nexport interface GoogleSearchResultContent {\n  /**\n   * Used as the OpenAPI type discriminator for the content oneof.\n   */\n  type: 'google_search_result';\n\n  /**\n   * ID to match the ID from the google search call block.\n   */\n  call_id?: string;\n\n  /**\n   * Whether the Google Search resulted in an error.\n   */\n  is_error?: boolean;\n\n  /**\n   * The results of the Google Search.\n   */\n  result?: Array<GoogleSearchResult>;\n\n  /**\n   * The signature of the Google Search result.\n   */\n  signature?: string;\n}\n\n/**\n * An image content block.\n */\nexport interface ImageContent {\n  /**\n   * Used as the OpenAPI type discriminator for the content oneof.\n   */\n  type: 'image';\n\n  data?: string;\n\n  /**\n   * The mime type of the image.\n   */\n  mime_type?: ImageMimeType;\n\n  /**\n   * The resolution of the media.\n   */\n  resolution?: 'low' | 'medium' | 'high';\n\n  uri?: string;\n}\n\n/**\n * The mime type of the image.\n */\nexport type ImageMimeType =\n  | 'image/png'\n  | 'image/jpeg'\n  | 'image/webp'\n  | 'image/heic'\n  | 'image/heif'\n  | (string & {});\n\n/**\n * The Interaction resource.\n */\nexport interface Interaction {\n  /**\n   * Output only. A unique identifier for the interaction completion.\n   */\n  id: string;\n\n  /**\n   * Output only. The status of the interaction.\n   */\n  status: 'in_progress' | 'requires_action' | 'completed' | 'failed' | 'cancelled';\n\n  /**\n   * The name of the `Agent` used for generating the interaction.\n   */\n  agent?: (string & {}) | 'deep-research-pro-preview-12-2025';\n\n  /**\n   * Output only. The time at which the response was created in ISO 8601 format\n   * (YYYY-MM-DDThh:mm:ssZ).\n   */\n  created?: string;\n\n  /**\n   * The name of the `Model` used for generating the interaction.\n   */\n  model?: Model;\n\n  /**\n   * Output only. The object type of the interaction. Always set to `interaction`.\n   */\n  object?: 'interaction';\n\n  /**\n   * Output only. Responses from the model.\n   */\n  outputs?: Array<\n    | TextContent\n    | ImageContent\n    | AudioContent\n    | DocumentContent\n    | VideoContent\n    | ThoughtContent\n    | FunctionCallContent\n    | FunctionResultContent\n    | CodeExecutionCallContent\n    | CodeExecutionResultContent\n    | URLContextCallContent\n    | URLContextResultContent\n    | GoogleSearchCallContent\n    | GoogleSearchResultContent\n    | MCPServerToolCallContent\n    | MCPServerToolResultContent\n    | FileSearchResultContent\n  >;\n\n  /**\n   * The ID of the previous interaction, if any.\n   */\n  previous_interaction_id?: string;\n\n  /**\n   * Output only. The role of the interaction.\n   */\n  role?: string;\n\n  /**\n   * Output only. The time at which the response was last updated in ISO 8601 format\n   * (YYYY-MM-DDThh:mm:ssZ).\n   */\n  updated?: string;\n\n  /**\n   * Output only. Statistics on the interaction request's token usage.\n   */\n  usage?: Usage;\n}\n\nexport interface InteractionEvent {\n  /**\n   * The event_id token to be used to resume the interaction stream, from\n   * this event.\n   */\n  event_id?: string;\n\n  event_type?: 'interaction.start' | 'interaction.complete';\n\n  /**\n   * The Interaction resource.\n   */\n  interaction?: Interaction;\n}\n\nexport type InteractionSSEEvent =\n  | InteractionEvent\n  | InteractionStatusUpdate\n  | ContentStart\n  | ContentDelta\n  | ContentStop\n  | ErrorEvent;\n\nexport interface InteractionStatusUpdate {\n  /**\n   * The event_id token to be used to resume the interaction stream, from\n   * this event.\n   */\n  event_id?: string;\n\n  event_type?: 'interaction.status_update';\n\n  interaction_id?: string;\n\n  status?: 'in_progress' | 'requires_action' | 'completed' | 'failed' | 'cancelled';\n}\n\n/**\n * MCPServer tool call content.\n */\nexport interface MCPServerToolCallContent {\n  /**\n   * A unique ID for this specific tool call.\n   */\n  id: string;\n\n  /**\n   * The JSON object of arguments for the function.\n   */\n  arguments: { [key: string]: unknown };\n\n  /**\n   * The name of the tool which was called.\n   */\n  name: string;\n\n  /**\n   * The name of the used MCP server.\n   */\n  server_name: string;\n\n  /**\n   * Used as the OpenAPI type discriminator for the content oneof.\n   */\n  type: 'mcp_server_tool_call';\n}\n\n/**\n * MCPServer tool result content.\n */\nexport interface MCPServerToolResultContent {\n  /**\n   * ID to match the ID from the MCP server tool call block.\n   */\n  call_id: string;\n\n  /**\n   * The result of the tool call.\n   */\n  result: MCPServerToolResultContent.Items | unknown | string;\n\n  /**\n   * Used as the OpenAPI type discriminator for the content oneof.\n   */\n  type: 'mcp_server_tool_result';\n\n  /**\n   * Name of the tool which is called for this specific tool call.\n   */\n  name?: string;\n\n  /**\n   * The name of the used MCP server.\n   */\n  server_name?: string;\n}\n\nexport namespace MCPServerToolResultContent {\n  export interface Items {\n    items?: Array<string | InteractionsAPI.ImageContent>;\n  }\n}\n\n/**\n * The model that will complete your prompt.\\n\\nSee [models](https://ai.google.dev/gemini-api/docs/models) for additional details.\n */\nexport type Model =\n  | 'gemini-2.5-pro'\n  | 'gemini-2.5-flash'\n  | 'gemini-2.5-flash-preview-09-2025'\n  | 'gemini-2.5-flash-lite'\n  | 'gemini-2.5-flash-lite-preview-09-2025'\n  | 'gemini-2.5-flash-preview-native-audio-dialog'\n  | 'gemini-2.5-flash-image-preview'\n  | 'gemini-2.5-pro-preview-tts'\n  | 'gemini-3-pro-preview'\n  | (string & {});\n\n/**\n * The configuration for speech interaction.\n */\nexport interface SpeechConfig {\n  /**\n   * The language of the speech.\n   */\n  language?: string;\n\n  /**\n   * The speaker's name, it should match the speaker name given in the prompt.\n   */\n  speaker?: string;\n\n  /**\n   * The voice of the speaker.\n   */\n  voice?: string;\n}\n\n/**\n * A text content block.\n */\nexport interface TextContent {\n  /**\n   * Used as the OpenAPI type discriminator for the content oneof.\n   */\n  type: 'text';\n\n  /**\n   * Citation information for model-generated content.\n   */\n  annotations?: Array<Annotation>;\n\n  /**\n   * The text content.\n   */\n  text?: string;\n}\n\nexport type ThinkingLevel = 'low' | 'high';\n\n/**\n * A thought content block.\n */\nexport interface ThoughtContent {\n  /**\n   * Used as the OpenAPI type discriminator for the content oneof.\n   */\n  type: 'thought';\n\n  /**\n   * Signature to match the backend source to be part of the generation.\n   */\n  signature?: string;\n\n  /**\n   * A summary of the thought.\n   */\n  summary?: Array<TextContent | ImageContent>;\n}\n\n/**\n * A tool that can be used by the model.\n */\nexport type Tool =\n  | Function\n  | Tool.GoogleSearch\n  | Tool.CodeExecution\n  | Tool.URLContext\n  | Tool.ComputerUse\n  | Tool.MCPServer\n  | Tool.FileSearch;\n\nexport namespace Tool {\n  /**\n   * A tool that can be used by the model to search Google.\n   */\n  export interface GoogleSearch {\n    type: 'google_search';\n  }\n\n  /**\n   * A tool that can be used by the model to execute code.\n   */\n  export interface CodeExecution {\n    type: 'code_execution';\n  }\n\n  /**\n   * A tool that can be used by the model to fetch URL context.\n   */\n  export interface URLContext {\n    type: 'url_context';\n  }\n\n  /**\n   * A tool that can be used by the model to interact with the computer.\n   */\n  export interface ComputerUse {\n    type: 'computer_use';\n\n    /**\n     * The environment being operated.\n     */\n    environment?: 'browser';\n\n    /**\n     * The list of predefined functions that are excluded from the model call.\n     */\n    excludedPredefinedFunctions?: Array<string>;\n  }\n\n  /**\n   * A MCPServer is a server that can be called by the model to perform actions.\n   */\n  export interface MCPServer {\n    type: 'mcp_server';\n\n    /**\n     * The allowed tools.\n     */\n    allowed_tools?: Array<InteractionsAPI.AllowedTools>;\n\n    /**\n     * Optional: Fields for authentication headers, timeouts, etc., if needed.\n     */\n    headers?: { [key: string]: string };\n\n    /**\n     * The name of the MCPServer.\n     */\n    name?: string;\n\n    /**\n     * The full URL for the MCPServer endpoint.\n     * Example: \"https://api.example.com/mcp\"\n     */\n    url?: string;\n  }\n\n  /**\n   * A tool that can be used by the model to search files.\n   */\n  export interface FileSearch {\n    type: 'file_search';\n\n    /**\n     * The file search store names to search.\n     */\n    file_search_store_names?: Array<string>;\n\n    /**\n     * Metadata filter to apply to the semantic retrieval documents and chunks.\n     */\n    metadata_filter?: string;\n\n    /**\n     * The number of semantic retrieval chunks to retrieve.\n     */\n    top_k?: number;\n  }\n}\n\n/**\n * The configuration for tool choice.\n */\nexport type ToolChoice = ToolChoiceType | ToolChoiceConfig;\n\nexport interface ToolChoiceConfig {\n  /**\n   * The configuration for allowed tools.\n   */\n  allowed_tools?: AllowedTools;\n}\n\nexport type ToolChoiceType = 'auto' | 'any' | 'none' | 'validated';\n\nexport interface Turn {\n  /**\n   * The content of the turn.\n   */\n  content?:\n    | string\n    | Array<\n        | TextContent\n        | ImageContent\n        | AudioContent\n        | DocumentContent\n        | VideoContent\n        | ThoughtContent\n        | FunctionCallContent\n        | FunctionResultContent\n        | CodeExecutionCallContent\n        | CodeExecutionResultContent\n        | URLContextCallContent\n        | URLContextResultContent\n        | GoogleSearchCallContent\n        | GoogleSearchResultContent\n        | MCPServerToolCallContent\n        | MCPServerToolResultContent\n        | FileSearchResultContent\n      >;\n\n  /**\n   * The originator of this turn. Must be user for input or model for\n   * model output.\n   */\n  role?: string;\n}\n\n/**\n * The arguments to pass to the URL context.\n */\nexport interface URLContextCallArguments {\n  /**\n   * The URLs to fetch.\n   */\n  urls?: Array<string>;\n}\n\n/**\n * URL context content.\n */\nexport interface URLContextCallContent {\n  /**\n   * Used as the OpenAPI type discriminator for the content oneof.\n   */\n  type: 'url_context_call';\n\n  /**\n   * A unique ID for this specific tool call.\n   */\n  id?: string;\n\n  /**\n   * The arguments to pass to the URL context.\n   */\n  arguments?: URLContextCallArguments;\n}\n\n/**\n * The result of the URL context.\n */\nexport interface URLContextResult {\n  /**\n   * The status of the URL retrieval.\n   */\n  status?: 'success' | 'error' | 'paywall' | 'unsafe';\n\n  /**\n   * The URL that was fetched.\n   */\n  url?: string;\n}\n\n/**\n * URL context result content.\n */\nexport interface URLContextResultContent {\n  /**\n   * Used as the OpenAPI type discriminator for the content oneof.\n   */\n  type: 'url_context_result';\n\n  /**\n   * ID to match the ID from the url context call block.\n   */\n  call_id?: string;\n\n  /**\n   * Whether the URL context resulted in an error.\n   */\n  is_error?: boolean;\n\n  /**\n   * The results of the URL context.\n   */\n  result?: Array<URLContextResult>;\n\n  /**\n   * The signature of the URL context result.\n   */\n  signature?: string;\n}\n\n/**\n * Statistics on the interaction request's token usage.\n */\nexport interface Usage {\n  /**\n   * A breakdown of cached token usage by modality.\n   */\n  cached_tokens_by_modality?: Array<Usage.CachedTokensByModality>;\n\n  /**\n   * A breakdown of input token usage by modality.\n   */\n  input_tokens_by_modality?: Array<Usage.InputTokensByModality>;\n\n  /**\n   * A breakdown of output token usage by modality.\n   */\n  output_tokens_by_modality?: Array<Usage.OutputTokensByModality>;\n\n  /**\n   * A breakdown of tool-use token usage by modality.\n   */\n  tool_use_tokens_by_modality?: Array<Usage.ToolUseTokensByModality>;\n\n  /**\n   * Number of tokens in the cached part of the prompt (the cached content).\n   */\n  total_cached_tokens?: number;\n\n  /**\n   * Number of tokens in the prompt (context).\n   */\n  total_input_tokens?: number;\n\n  /**\n   * Total number of tokens across all the generated responses.\n   */\n  total_output_tokens?: number;\n\n  /**\n   * Number of tokens of thoughts for thinking models.\n   */\n  total_reasoning_tokens?: number;\n\n  /**\n   * Total token count for the interaction request (prompt + responses + other\n   * internal tokens).\n   */\n  total_tokens?: number;\n\n  /**\n   * Number of tokens present in tool-use prompt(s).\n   */\n  total_tool_use_tokens?: number;\n}\n\nexport namespace Usage {\n  /**\n   * The token count for a single response modality.\n   */\n  export interface CachedTokensByModality {\n    /**\n     * The modality associated with the token count.\n     */\n    modality?: 'text' | 'image' | 'audio';\n\n    /**\n     * Number of tokens for the modality.\n     */\n    tokens?: number;\n  }\n\n  /**\n   * The token count for a single response modality.\n   */\n  export interface InputTokensByModality {\n    /**\n     * The modality associated with the token count.\n     */\n    modality?: 'text' | 'image' | 'audio';\n\n    /**\n     * Number of tokens for the modality.\n     */\n    tokens?: number;\n  }\n\n  /**\n   * The token count for a single response modality.\n   */\n  export interface OutputTokensByModality {\n    /**\n     * The modality associated with the token count.\n     */\n    modality?: 'text' | 'image' | 'audio';\n\n    /**\n     * Number of tokens for the modality.\n     */\n    tokens?: number;\n  }\n\n  /**\n   * The token count for a single response modality.\n   */\n  export interface ToolUseTokensByModality {\n    /**\n     * The modality associated with the token count.\n     */\n    modality?: 'text' | 'image' | 'audio';\n\n    /**\n     * Number of tokens for the modality.\n     */\n    tokens?: number;\n  }\n}\n\n/**\n * A video content block.\n */\nexport interface VideoContent {\n  /**\n   * Used as the OpenAPI type discriminator for the content oneof.\n   */\n  type: 'video';\n\n  data?: string;\n\n  /**\n   * The mime type of the video.\n   */\n  mime_type?: VideoMimeType;\n\n  /**\n   * The resolution of the media.\n   */\n  resolution?: 'low' | 'medium' | 'high';\n\n  uri?: string;\n}\n\n/**\n * The mime type of the video.\n */\nexport type VideoMimeType =\n  | 'video/mp4'\n  | 'video/mpeg'\n  | 'video/mov'\n  | 'video/avi'\n  | 'video/x-flv'\n  | 'video/mpg'\n  | 'video/webm'\n  | 'video/wmv'\n  | 'video/3gpp'\n  | (string & {});\n\nexport type InteractionDeleteResponse = unknown;\n\nexport type InteractionCreateParams =\n  | CreateModelInteractionParamsNonStreaming\n  | CreateModelInteractionParamsStreaming\n  | CreateAgentInteractionParamsNonStreaming\n  | CreateAgentInteractionParamsStreaming;\n\nexport interface BaseCreateModelInteractionParams {\n  /**\n   * Body param: The inputs for the interaction.\n   */\n  input:\n    | string\n    | Array<\n        | TextContent\n        | ImageContent\n        | AudioContent\n        | DocumentContent\n        | VideoContent\n        | ThoughtContent\n        | FunctionCallContent\n        | FunctionResultContent\n        | CodeExecutionCallContent\n        | CodeExecutionResultContent\n        | URLContextCallContent\n        | URLContextResultContent\n        | GoogleSearchCallContent\n        | GoogleSearchResultContent\n        | MCPServerToolCallContent\n        | MCPServerToolResultContent\n        | FileSearchResultContent\n      >\n    | Array<Turn>\n    | TextContent\n    | ImageContent\n    | AudioContent\n    | DocumentContent\n    | VideoContent\n    | ThoughtContent\n    | FunctionCallContent\n    | FunctionResultContent\n    | CodeExecutionCallContent\n    | CodeExecutionResultContent\n    | URLContextCallContent\n    | URLContextResultContent\n    | GoogleSearchCallContent\n    | GoogleSearchResultContent\n    | MCPServerToolCallContent\n    | MCPServerToolResultContent\n    | FileSearchResultContent;\n\n  /**\n   * Body param: The name of the `Model` used for generating the interaction.\n   */\n  model: Model;\n\n  /**\n   * Path param: Which version of the API to use.\n   */\n  api_version?: string;\n\n  /**\n   * Body param: Whether to run the model interaction in the background.\n   */\n  background?: boolean;\n\n  /**\n   * Body param: Input only. Configuration parameters for the model interaction.\n   */\n  generation_config?: GenerationConfig;\n\n  /**\n   * Body param: The ID of the previous interaction, if any.\n   */\n  previous_interaction_id?: string;\n\n  /**\n   * Body param: Enforces that the generated response is a JSON object that complies with\n   * the JSON schema specified in this field.\n   */\n  response_format?: unknown;\n\n  /**\n   * Body param: The mime type of the response. This is required if response_format is set.\n   */\n  response_mime_type?: string;\n\n  /**\n   * Body param: The requested modalities of the response (TEXT, IMAGE, AUDIO).\n   */\n  response_modalities?: Array<'text' | 'image' | 'audio'>;\n\n  /**\n   * Body param: Input only. Whether to store the response and request for later retrieval.\n   */\n  store?: boolean;\n\n  /**\n   * Body param: Input only. Whether the interaction will be streamed.\n   */\n  stream?: boolean;\n\n  /**\n   * Body param: System instruction for the interaction.\n   */\n  system_instruction?: string;\n\n  /**\n   * Body param: A list of tool declarations the model may call during interaction.\n   */\n  tools?: Array<Tool>;\n}\n\nexport interface BaseCreateAgentInteractionParams {\n  /**\n   * Body param: The name of the `Agent` used for generating the interaction.\n   */\n  agent: (string & {}) | 'deep-research-pro-preview-12-2025';\n\n  /**\n   * Body param: The inputs for the interaction.\n   */\n  input:\n    | string\n    | Array<\n        | TextContent\n        | ImageContent\n        | AudioContent\n        | DocumentContent\n        | VideoContent\n        | ThoughtContent\n        | FunctionCallContent\n        | FunctionResultContent\n        | CodeExecutionCallContent\n        | CodeExecutionResultContent\n        | URLContextCallContent\n        | URLContextResultContent\n        | GoogleSearchCallContent\n        | GoogleSearchResultContent\n        | MCPServerToolCallContent\n        | MCPServerToolResultContent\n        | FileSearchResultContent\n      >\n    | Array<Turn>\n    | TextContent\n    | ImageContent\n    | AudioContent\n    | DocumentContent\n    | VideoContent\n    | ThoughtContent\n    | FunctionCallContent\n    | FunctionResultContent\n    | CodeExecutionCallContent\n    | CodeExecutionResultContent\n    | URLContextCallContent\n    | URLContextResultContent\n    | GoogleSearchCallContent\n    | GoogleSearchResultContent\n    | MCPServerToolCallContent\n    | MCPServerToolResultContent\n    | FileSearchResultContent;\n\n  /**\n   * Path param: Which version of the API to use.\n   */\n  api_version?: string;\n\n  /**\n   * Body param: Configuration for the agent.\n   */\n  agent_config?: DynamicAgentConfig | DeepResearchAgentConfig;\n\n  /**\n   * Body param: Whether to run the model interaction in the background.\n   */\n  background?: boolean;\n\n  /**\n   * Body param: The ID of the previous interaction, if any.\n   */\n  previous_interaction_id?: string;\n\n  /**\n   * Body param: Enforces that the generated response is a JSON object that complies with\n   * the JSON schema specified in this field.\n   */\n  response_format?: unknown;\n\n  /**\n   * Body param: The mime type of the response. This is required if response_format is set.\n   */\n  response_mime_type?: string;\n\n  /**\n   * Body param: The requested modalities of the response (TEXT, IMAGE, AUDIO).\n   */\n  response_modalities?: Array<'text' | 'image' | 'audio'>;\n\n  /**\n   * Body param: Input only. Whether to store the response and request for later retrieval.\n   */\n  store?: boolean;\n\n  /**\n   * Body param: Input only. Whether the interaction will be streamed.\n   */\n  stream?: boolean;\n\n  /**\n   * Body param: System instruction for the interaction.\n   */\n  system_instruction?: string;\n\n  /**\n   * Body param: A list of tool declarations the model may call during interaction.\n   */\n  tools?: Array<Tool>;\n}\n\nexport interface CreateModelInteractionParamsNonStreaming extends BaseCreateModelInteractionParams {\n  /**\n   * Body param: Input only. Whether the interaction will be streamed.\n   */\n  stream?: false;\n}\n\nexport interface CreateModelInteractionParamsStreaming extends BaseCreateModelInteractionParams {\n  /**\n   * Body param: Input only. Whether the interaction will be streamed.\n   */\n  stream: true;\n}\n\nexport interface CreateAgentInteractionParamsNonStreaming extends BaseCreateAgentInteractionParams {\n  /**\n   * Body param: Input only. Whether the interaction will be streamed.\n   */\n  stream?: false;\n}\n\nexport interface CreateAgentInteractionParamsStreaming extends BaseCreateAgentInteractionParams {\n  /**\n   * Body param: Input only. Whether the interaction will be streamed.\n   */\n  stream: true;\n}\n\nexport interface InteractionDeleteParams {\n  /**\n   * Which version of the API to use.\n   */\n  api_version?: string;\n}\n\nexport interface InteractionCancelParams {\n  /**\n   * Which version of the API to use.\n   */\n  api_version?: string;\n}\n\nexport type InteractionGetParams = InteractionGetParamsNonStreaming | InteractionGetParamsStreaming;\n\nexport interface InteractionGetParamsBase {\n  /**\n   * Path param: Which version of the API to use.\n   */\n  api_version?: string;\n\n  /**\n   * Query param: Optional. If set, resumes the interaction stream from the next chunk after the event marked by the event id. Can only be used if `stream` is true.\n   */\n  last_event_id?: string;\n\n  /**\n   * Query param: If set to true, the generated content will be streamed incrementally.\n   */\n  stream?: boolean;\n}\n\nexport namespace InteractionGetParams {\n  export type InteractionGetParamsNonStreaming = InteractionsAPI.InteractionGetParamsNonStreaming;\n  export type InteractionGetParamsStreaming = InteractionsAPI.InteractionGetParamsStreaming;\n}\n\nexport interface InteractionGetParamsNonStreaming extends InteractionGetParamsBase {\n  /**\n   * Query param: If set to true, the generated content will be streamed incrementally.\n   */\n  stream?: false;\n}\n\nexport interface InteractionGetParamsStreaming extends InteractionGetParamsBase {\n  /**\n   * Query param: If set to true, the generated content will be streamed incrementally.\n   */\n  stream: true;\n}\n\nexport declare namespace Interactions {\n  export {\n    type AllowedTools as AllowedTools,\n    type Annotation as Annotation,\n    type AudioContent as AudioContent,\n    type AudioMimeType as AudioMimeType,\n    type CodeExecutionCallArguments as CodeExecutionCallArguments,\n    type CodeExecutionCallContent as CodeExecutionCallContent,\n    type CodeExecutionResultContent as CodeExecutionResultContent,\n    type ContentDelta as ContentDelta,\n    type ContentStart as ContentStart,\n    type ContentStop as ContentStop,\n    type DeepResearchAgentConfig as DeepResearchAgentConfig,\n    type DocumentContent as DocumentContent,\n    type DynamicAgentConfig as DynamicAgentConfig,\n    type ErrorEvent as ErrorEvent,\n    type FileSearchResultContent as FileSearchResultContent,\n    type Function as Function,\n    type FunctionCallContent as FunctionCallContent,\n    type FunctionResultContent as FunctionResultContent,\n    type GenerationConfig as GenerationConfig,\n    type GoogleSearchCallArguments as GoogleSearchCallArguments,\n    type GoogleSearchCallContent as GoogleSearchCallContent,\n    type GoogleSearchResult as GoogleSearchResult,\n    type GoogleSearchResultContent as GoogleSearchResultContent,\n    type ImageContent as ImageContent,\n    type ImageMimeType as ImageMimeType,\n    type Interaction as Interaction,\n    type InteractionEvent as InteractionEvent,\n    type InteractionSSEEvent as InteractionSSEEvent,\n    type InteractionStatusUpdate as InteractionStatusUpdate,\n    type MCPServerToolCallContent as MCPServerToolCallContent,\n    type MCPServerToolResultContent as MCPServerToolResultContent,\n    type Model as Model,\n    type SpeechConfig as SpeechConfig,\n    type TextContent as TextContent,\n    type ThinkingLevel as ThinkingLevel,\n    type ThoughtContent as ThoughtContent,\n    type Tool as Tool,\n    type ToolChoice as ToolChoice,\n    type ToolChoiceConfig as ToolChoiceConfig,\n    type ToolChoiceType as ToolChoiceType,\n    type Turn as Turn,\n    type URLContextCallArguments as URLContextCallArguments,\n    type URLContextCallContent as URLContextCallContent,\n    type URLContextResult as URLContextResult,\n    type URLContextResultContent as URLContextResultContent,\n    type Usage as Usage,\n    type VideoContent as VideoContent,\n    type VideoMimeType as VideoMimeType,\n    type InteractionDeleteResponse as InteractionDeleteResponse,\n    type InteractionCreateParams as InteractionCreateParams,\n    type CreateModelInteractionParamsNonStreaming as CreateModelInteractionParamsNonStreaming,\n    type CreateModelInteractionParamsStreaming as CreateModelInteractionParamsStreaming,\n    type CreateAgentInteractionParamsNonStreaming as CreateAgentInteractionParamsNonStreaming,\n    type CreateAgentInteractionParamsStreaming as CreateAgentInteractionParamsStreaming,\n    type InteractionDeleteParams as InteractionDeleteParams,\n    type InteractionCancelParams as InteractionCancelParams,\n    type InteractionGetParams as InteractionGetParams,\n    type InteractionGetParamsNonStreaming as InteractionGetParamsNonStreaming,\n    type InteractionGetParamsStreaming as InteractionGetParamsStreaming,\n  };\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport function concatBytes(buffers: Uint8Array[]): Uint8Array {\n  let length = 0;\n  for (const buffer of buffers) {\n    length += buffer.length;\n  }\n  const output = new Uint8Array(length);\n  let index = 0;\n  for (const buffer of buffers) {\n    output.set(buffer, index);\n    index += buffer.length;\n  }\n\n  return output;\n}\n\nlet encodeUTF8_: (str: string) => Uint8Array;\nexport function encodeUTF8(str: string) {\n  let encoder;\n  return (\n    encodeUTF8_ ??\n    ((encoder = new (globalThis as any).TextEncoder()), (encodeUTF8_ = encoder.encode.bind(encoder)))\n  )(str);\n}\n\nlet decodeUTF8_: (bytes: Uint8Array) => string;\nexport function decodeUTF8(bytes: Uint8Array) {\n  let decoder;\n  return (\n    decodeUTF8_ ??\n    ((decoder = new (globalThis as any).TextDecoder()), (decodeUTF8_ = decoder.decode.bind(decoder)))\n  )(bytes);\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { concatBytes, decodeUTF8, encodeUTF8 } from '../utils/bytes.js';\n\nexport type Bytes = string | ArrayBuffer | Uint8Array | null | undefined;\n\n/**\n * A re-implementation of httpx's `LineDecoder` in Python that handles incrementally\n * reading lines from text.\n *\n * https://github.com/encode/httpx/blob/920333ea98118e9cf617f246905d7b202510941c/httpx/_decoders.py#L258\n */\nexport class LineDecoder {\n  // prettier-ignore\n  static NEWLINE_CHARS = new Set(['\\n', '\\r']);\n  static NEWLINE_REGEXP = /\\r\\n|[\\n\\r]/g;\n\n  private buffer: Uint8Array;\n  private carriageReturnIndex: number | null;\n\n  constructor() {\n    this.buffer = new Uint8Array();\n    this.carriageReturnIndex = null;\n  }\n\n  decode(chunk: Bytes): string[] {\n    if (chunk == null) {\n      return [];\n    }\n\n    const binaryChunk =\n      chunk instanceof ArrayBuffer ? new Uint8Array(chunk)\n      : typeof chunk === 'string' ? encodeUTF8(chunk)\n      : chunk;\n\n    this.buffer = concatBytes([this.buffer, binaryChunk]);\n\n    const lines: string[] = [];\n    let patternIndex;\n    while ((patternIndex = findNewlineIndex(this.buffer, this.carriageReturnIndex)) != null) {\n      if (patternIndex.carriage && this.carriageReturnIndex == null) {\n        // skip until we either get a corresponding `\\n`, a new `\\r` or nothing\n        this.carriageReturnIndex = patternIndex.index;\n        continue;\n      }\n\n      // we got double \\r or \\rtext\\n\n      if (\n        this.carriageReturnIndex != null &&\n        (patternIndex.index !== this.carriageReturnIndex + 1 || patternIndex.carriage)\n      ) {\n        lines.push(decodeUTF8(this.buffer.subarray(0, this.carriageReturnIndex - 1)));\n        this.buffer = this.buffer.subarray(this.carriageReturnIndex);\n        this.carriageReturnIndex = null;\n        continue;\n      }\n\n      const endIndex =\n        this.carriageReturnIndex !== null ? patternIndex.preceding - 1 : patternIndex.preceding;\n\n      const line = decodeUTF8(this.buffer.subarray(0, endIndex));\n      lines.push(line);\n\n      this.buffer = this.buffer.subarray(patternIndex.index);\n      this.carriageReturnIndex = null;\n    }\n\n    return lines;\n  }\n\n  flush(): string[] {\n    if (!this.buffer.length) {\n      return [];\n    }\n    return this.decode('\\n');\n  }\n}\n\n/**\n * This function searches the buffer for the end patterns, (\\r or \\n)\n * and returns an object with the index preceding the matched newline and the\n * index after the newline char. `null` is returned if no new line is found.\n *\n * ```ts\n * findNewLineIndex('abc\\ndef') -> { preceding: 2, index: 3 }\n * ```\n */\nfunction findNewlineIndex(\n  buffer: Uint8Array,\n  startIndex: number | null,\n): { preceding: number; index: number; carriage: boolean } | null {\n  const newline = 0x0a; // \\n\n  const carriage = 0x0d; // \\r\n\n  for (let i = startIndex ?? 0; i < buffer.length; i++) {\n    if (buffer[i] === newline) {\n      return { preceding: i, index: i + 1, carriage: false };\n    }\n\n    if (buffer[i] === carriage) {\n      return { preceding: i, index: i + 1, carriage: true };\n    }\n  }\n\n  return null;\n}\n\nexport function findDoubleNewlineIndex(buffer: Uint8Array): number {\n  // This function searches the buffer for the end patterns (\\r\\r, \\n\\n, \\r\\n\\r\\n)\n  // and returns the index right after the first occurrence of any pattern,\n  // or -1 if none of the patterns are found.\n  const newline = 0x0a; // \\n\n  const carriage = 0x0d; // \\r\n\n  for (let i = 0; i < buffer.length - 1; i++) {\n    if (buffer[i] === newline && buffer[i + 1] === newline) {\n      // \\n\\n\n      return i + 2;\n    }\n    if (buffer[i] === carriage && buffer[i + 1] === carriage) {\n      // \\r\\r\n      return i + 2;\n    }\n    if (\n      buffer[i] === carriage &&\n      buffer[i + 1] === newline &&\n      i + 3 < buffer.length &&\n      buffer[i + 2] === carriage &&\n      buffer[i + 3] === newline\n    ) {\n      // \\r\\n\\r\\n\n      return i + 4;\n    }\n  }\n\n  return -1;\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { hasOwn } from './values.js';\nimport { type BaseGeminiNextGenAPIClient } from '../../client.js';\nimport { RequestOptions } from '../request-options.js';\n\ntype LogFn = (message: string, ...rest: unknown[]) => void;\nexport type Logger = {\n  error: LogFn;\n  warn: LogFn;\n  info: LogFn;\n  debug: LogFn;\n};\nexport type LogLevel = 'off' | 'error' | 'warn' | 'info' | 'debug';\n\nconst levelNumbers = {\n  off: 0,\n  error: 200,\n  warn: 300,\n  info: 400,\n  debug: 500,\n};\n\nexport const parseLogLevel = (\n  maybeLevel: string | undefined,\n  sourceName: string,\n  client: BaseGeminiNextGenAPIClient,\n): LogLevel | undefined => {\n  if (!maybeLevel) {\n    return undefined;\n  }\n  if (hasOwn(levelNumbers, maybeLevel)) {\n    return maybeLevel;\n  }\n  loggerFor(client).warn(\n    `${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(\n      Object.keys(levelNumbers),\n    )}`,\n  );\n  return undefined;\n};\n\nfunction noop() {}\n\nfunction makeLogFn(fnLevel: keyof Logger, logger: Logger | undefined, logLevel: LogLevel) {\n  if (!logger || levelNumbers[fnLevel] > levelNumbers[logLevel]) {\n    return noop;\n  } else {\n    // Don't wrap logger functions, we want the stacktrace intact!\n    return logger[fnLevel].bind(logger);\n  }\n}\n\nconst noopLogger = {\n  error: noop,\n  warn: noop,\n  info: noop,\n  debug: noop,\n};\n\nlet cachedLoggers = /* @__PURE__ */ new WeakMap<Logger, [LogLevel, Logger]>();\n\nexport function loggerFor(client: BaseGeminiNextGenAPIClient): Logger {\n  const logger = client.logger;\n  const logLevel = client.logLevel ?? 'off';\n  if (!logger) {\n    return noopLogger;\n  }\n\n  const cachedLogger = cachedLoggers.get(logger);\n  if (cachedLogger && cachedLogger[0] === logLevel) {\n    return cachedLogger[1];\n  }\n\n  const levelLogger = {\n    error: makeLogFn('error', logger, logLevel),\n    warn: makeLogFn('warn', logger, logLevel),\n    info: makeLogFn('info', logger, logLevel),\n    debug: makeLogFn('debug', logger, logLevel),\n  };\n\n  cachedLoggers.set(logger, [logLevel, levelLogger]);\n\n  return levelLogger;\n}\n\nexport const formatRequestDetails = (details: {\n  options?: RequestOptions | undefined;\n  headers?: Headers | Record<string, string> | undefined;\n  retryOfRequestLogID?: string | undefined;\n  retryOf?: string | undefined;\n  url?: string | undefined;\n  status?: number | undefined;\n  method?: string | undefined;\n  durationMs?: number | undefined;\n  message?: unknown;\n  body?: unknown;\n}) => {\n  if (details.options) {\n    details.options = { ...details.options };\n    delete details.options['headers']; // redundant + leaks internals\n  }\n  if (details.headers) {\n    details.headers = Object.fromEntries(\n      (details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(\n        ([name, value]) => [\n          name,\n          (\n            name.toLowerCase() === 'x-goog-api-key' ||\n            name.toLowerCase() === 'authorization' ||\n            name.toLowerCase() === 'cookie' ||\n            name.toLowerCase() === 'set-cookie'\n          ) ?\n            '***'\n          : value,\n        ],\n      ),\n    );\n  }\n  if ('retryOfRequestLogID' in details) {\n    if (details.retryOfRequestLogID) {\n      details.retryOf = details.retryOfRequestLogID;\n    }\n    delete details.retryOfRequestLogID;\n  }\n  return details;\n};\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { GeminiNextGenAPIClientError } from './error.js';\nimport { type ReadableStream } from '../internal/shim-types.js';\nimport { makeReadableStream } from '../internal/shims.js';\nimport { findDoubleNewlineIndex, LineDecoder } from '../internal/decoders/line.js';\nimport { ReadableStreamToAsyncIterable } from '../internal/shims.js';\nimport { isAbortError } from '../internal/errors.js';\nimport { encodeUTF8 } from '../internal/utils/bytes.js';\nimport { loggerFor } from '../internal/utils/log.js';\nimport type { BaseGeminiNextGenAPIClient } from '../client.js';\n\ntype Bytes = string | ArrayBuffer | Uint8Array | null | undefined;\n\nexport type ServerSentEvent = {\n  event: string | null;\n  data: string;\n  raw: string[];\n};\n\nexport class Stream<Item> implements AsyncIterable<Item> {\n  controller: AbortController;\n  private client: BaseGeminiNextGenAPIClient | undefined;\n\n  constructor(\n    private iterator: () => AsyncIterator<Item>,\n    controller: AbortController,\n    client?: BaseGeminiNextGenAPIClient,\n  ) {\n    this.controller = controller;\n    this.client = client;\n  }\n\n  static fromSSEResponse<Item>(\n    response: Response,\n    controller: AbortController,\n    client?: BaseGeminiNextGenAPIClient,\n  ): Stream<Item> {\n    let consumed = false;\n    const logger = client ? loggerFor(client) : console;\n\n    async function* iterator(): AsyncIterator<Item, any, undefined> {\n      if (consumed) {\n        throw new GeminiNextGenAPIClientError(\n          'Cannot iterate over a consumed stream, use `.tee()` to split the stream.',\n        );\n      }\n      consumed = true;\n      let done = false;\n      try {\n        for await (const sse of _iterSSEMessages(response, controller)) {\n          if (done) continue;\n\n          if (sse.data.startsWith('[DONE]')) {\n            done = true;\n            continue;\n          } else {\n            try {\n              // @ts-ignore\n              yield JSON.parse(sse.data);\n            } catch (e) {\n              logger.error(`Could not parse message into JSON:`, sse.data);\n              logger.error(`From chunk:`, sse.raw);\n              throw e;\n            }\n          }\n        }\n        done = true;\n      } catch (e) {\n        // If the user calls `stream.controller.abort()`, we should exit without throwing.\n        if (isAbortError(e)) return;\n        throw e;\n      } finally {\n        // If the user `break`s, abort the ongoing request.\n        if (!done) controller.abort();\n      }\n    }\n\n    return new Stream(iterator, controller, client);\n  }\n\n  /**\n   * Generates a Stream from a newline-separated ReadableStream\n   * where each item is a JSON value.\n   */\n  static fromReadableStream<Item>(\n    readableStream: ReadableStream,\n    controller: AbortController,\n    client?: BaseGeminiNextGenAPIClient,\n  ): Stream<Item> {\n    let consumed = false;\n\n    async function* iterLines(): AsyncGenerator<string, void, unknown> {\n      const lineDecoder = new LineDecoder();\n\n      const iter = ReadableStreamToAsyncIterable<Bytes>(readableStream);\n      for await (const chunk of iter) {\n        for (const line of lineDecoder.decode(chunk)) {\n          yield line;\n        }\n      }\n\n      for (const line of lineDecoder.flush()) {\n        yield line;\n      }\n    }\n\n    async function* iterator(): AsyncIterator<Item, any, undefined> {\n      if (consumed) {\n        throw new GeminiNextGenAPIClientError(\n          'Cannot iterate over a consumed stream, use `.tee()` to split the stream.',\n        );\n      }\n      consumed = true;\n      let done = false;\n      try {\n        for await (const line of iterLines()) {\n          if (done) continue;\n          // @ts-ignore\n          if (line) yield JSON.parse(line);\n        }\n        done = true;\n      } catch (e) {\n        // If the user calls `stream.controller.abort()`, we should exit without throwing.\n        if (isAbortError(e)) return;\n        throw e;\n      } finally {\n        // If the user `break`s, abort the ongoing request.\n        if (!done) controller.abort();\n      }\n    }\n\n    return new Stream(iterator, controller, client);\n  }\n\n  [Symbol.asyncIterator](): AsyncIterator<Item> {\n    return this.iterator();\n  }\n\n  /**\n   * Splits the stream into two streams which can be\n   * independently read from at different speeds.\n   */\n  tee(): [Stream<Item>, Stream<Item>] {\n    const left: Array<Promise<IteratorResult<Item>>> = [];\n    const right: Array<Promise<IteratorResult<Item>>> = [];\n    const iterator = this.iterator();\n\n    const teeIterator = (queue: Array<Promise<IteratorResult<Item>>>): AsyncIterator<Item> => {\n      return {\n        next: () => {\n          if (queue.length === 0) {\n            const result = iterator.next();\n            left.push(result);\n            right.push(result);\n          }\n          return queue.shift()!;\n        },\n      };\n    };\n\n    return [\n      new Stream(() => teeIterator(left), this.controller, this.client),\n      new Stream(() => teeIterator(right), this.controller, this.client),\n    ];\n  }\n\n  /**\n   * Converts this stream to a newline-separated ReadableStream of\n   * JSON stringified values in the stream\n   * which can be turned back into a Stream with `Stream.fromReadableStream()`.\n   */\n  toReadableStream(): ReadableStream {\n    const self = this;\n    let iter: AsyncIterator<Item>;\n\n    return makeReadableStream({\n      async start() {\n        iter = self[Symbol.asyncIterator]();\n      },\n      async pull(ctrl: any) {\n        try {\n          const { value, done } = await iter.next();\n          if (done) return ctrl.close();\n\n          const bytes = encodeUTF8(JSON.stringify(value) + '\\n');\n\n          ctrl.enqueue(bytes);\n        } catch (err) {\n          ctrl.error(err);\n        }\n      },\n      async cancel() {\n        await iter.return?.();\n      },\n    });\n  }\n}\n\nexport async function* _iterSSEMessages(\n  response: Response,\n  controller: AbortController,\n): AsyncGenerator<ServerSentEvent, void, unknown> {\n  if (!response.body) {\n    controller.abort();\n    if (\n      typeof (globalThis as any).navigator !== 'undefined' &&\n      (globalThis as any).navigator.product === 'ReactNative'\n    ) {\n      throw new GeminiNextGenAPIClientError(\n        `The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`,\n      );\n    }\n    throw new GeminiNextGenAPIClientError(`Attempted to iterate over a response with no body`);\n  }\n\n  const sseDecoder = new SSEDecoder();\n  const lineDecoder = new LineDecoder();\n\n  const iter = ReadableStreamToAsyncIterable<Bytes>(response.body);\n  for await (const sseChunk of iterSSEChunks(iter)) {\n    for (const line of lineDecoder.decode(sseChunk)) {\n      const sse = sseDecoder.decode(line);\n      if (sse) yield sse;\n    }\n  }\n\n  for (const line of lineDecoder.flush()) {\n    const sse = sseDecoder.decode(line);\n    if (sse) yield sse;\n  }\n}\n\n/**\n * Given an async iterable iterator, iterates over it and yields full\n * SSE chunks, i.e. yields when a double new-line is encountered.\n */\nasync function* iterSSEChunks(iterator: AsyncIterableIterator<Bytes>): AsyncGenerator<Uint8Array> {\n  let data = new Uint8Array();\n\n  for await (const chunk of iterator) {\n    if (chunk == null) {\n      continue;\n    }\n\n    const binaryChunk =\n      chunk instanceof ArrayBuffer ? new Uint8Array(chunk)\n      : typeof chunk === 'string' ? encodeUTF8(chunk)\n      : chunk;\n\n    let newData = new Uint8Array(data.length + binaryChunk.length);\n    newData.set(data);\n    newData.set(binaryChunk, data.length);\n    data = newData;\n\n    let patternIndex;\n    while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) {\n      yield data.slice(0, patternIndex);\n      data = data.slice(patternIndex);\n    }\n  }\n\n  if (data.length > 0) {\n    yield data;\n  }\n}\n\nclass SSEDecoder {\n  private data: string[];\n  private event: string | null;\n  private chunks: string[];\n\n  constructor() {\n    this.event = null;\n    this.data = [];\n    this.chunks = [];\n  }\n\n  decode(line: string) {\n    if (line.endsWith('\\r')) {\n      line = line.substring(0, line.length - 1);\n    }\n\n    if (!line) {\n      // empty line and we didn't previously encounter any messages\n      if (!this.event && !this.data.length) return null;\n\n      const sse: ServerSentEvent = {\n        event: this.event,\n        data: this.data.join('\\n'),\n        raw: this.chunks,\n      };\n\n      this.event = null;\n      this.data = [];\n      this.chunks = [];\n\n      return sse;\n    }\n\n    this.chunks.push(line);\n\n    if (line.startsWith(':')) {\n      return null;\n    }\n\n    let [fieldname, _, value] = partition(line, ':');\n\n    if (value.startsWith(' ')) {\n      value = value.substring(1);\n    }\n\n    if (fieldname === 'event') {\n      this.event = value;\n    } else if (fieldname === 'data') {\n      this.data.push(value);\n    }\n\n    return null;\n  }\n}\n\nfunction partition(str: string, delimiter: string): [string, string, string] {\n  const index = str.indexOf(delimiter);\n  if (index !== -1) {\n    return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)];\n  }\n\n  return [str, '', ''];\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport type { FinalRequestOptions } from './request-options.js';\nimport { Stream } from '../core/streaming.js';\nimport { type BaseGeminiNextGenAPIClient } from '../client.js';\nimport { formatRequestDetails, loggerFor } from './utils/log.js';\n\nexport type APIResponseProps = {\n  response: Response;\n  options: FinalRequestOptions;\n  controller: AbortController;\n  requestLogID: string;\n  retryOfRequestLogID: string | undefined;\n  startTime: number;\n};\n\nexport async function defaultParseResponse<T>(\n  client: BaseGeminiNextGenAPIClient,\n  props: APIResponseProps,\n): Promise<T> {\n  const { response, requestLogID, retryOfRequestLogID, startTime } = props;\n  const body = await (async () => {\n    if (props.options.stream) {\n      loggerFor(client).debug('response', response.status, response.url, response.headers, response.body);\n\n      // Note: there is an invariant here that isn't represented in the type system\n      // that if you set `stream: true` the response type must also be `Stream<T>`\n\n      if (props.options.__streamClass) {\n        return props.options.__streamClass.fromSSEResponse(response, props.controller, client) as any;\n      }\n\n      return Stream.fromSSEResponse(response, props.controller, client) as any;\n    }\n\n    // fetch refuses to read the body when the status code is 204.\n    if (response.status === 204) {\n      return null as T;\n    }\n\n    if (props.options.__binaryResponse) {\n      return response as unknown as T;\n    }\n\n    const contentType = response.headers.get('content-type');\n    const mediaType = contentType?.split(';')[0]?.trim();\n    const isJSON = mediaType?.includes('application/json') || mediaType?.endsWith('+json');\n    if (isJSON) {\n      const json = await response.json();\n      return json as T;\n    }\n\n    const text = await response.text();\n    return text as unknown as T;\n  })();\n  loggerFor(client).debug(\n    `[${requestLogID}] response parsed`,\n    formatRequestDetails({\n      retryOfRequestLogID,\n      url: response.url,\n      status: response.status,\n      body,\n      durationMs: Date.now() - startTime,\n    }),\n  );\n  return body;\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { type BaseGeminiNextGenAPIClient } from '../client.js';\n\nimport { type PromiseOrValue } from '../internal/types.js';\nimport { APIResponseProps, defaultParseResponse } from '../internal/parse.js';\n\n/**\n * A subclass of `Promise` providing additional helper methods\n * for interacting with the SDK.\n */\nexport class APIPromise<T> extends Promise<T> {\n  private parsedPromise: Promise<T> | undefined;\n  private client: BaseGeminiNextGenAPIClient;\n\n  constructor(\n    client: BaseGeminiNextGenAPIClient,\n    private responsePromise: Promise<APIResponseProps>,\n    private parseResponse: (\n      client: BaseGeminiNextGenAPIClient,\n      props: APIResponseProps,\n    ) => PromiseOrValue<T> = defaultParseResponse,\n  ) {\n    super((resolve) => {\n      // this is maybe a bit weird but this has to be a no-op to not implicitly\n      // parse the response body; instead .then, .catch, .finally are overridden\n      // to parse the response\n      resolve(null as any);\n    });\n    this.client = client;\n  }\n\n  _thenUnwrap<U>(transform: (data: T, props: APIResponseProps) => U): APIPromise<U> {\n    return new APIPromise(this.client, this.responsePromise, async (client, props) =>\n      transform(await this.parseResponse(client, props), props),\n    );\n  }\n\n  /**\n   * Gets the raw `Response` instance instead of parsing the response\n   * data.\n   *\n   * If you want to parse the response body but still get the `Response`\n   * instance, you can use {@link withResponse()}.\n   *\n   * 👋 Getting the wrong TypeScript type for `Response`?\n   * Try setting `\"moduleResolution\": \"NodeNext\"` or add `\"lib\": [\"DOM\"]`\n   * to your `tsconfig.json`.\n   */\n  asResponse(): Promise<Response> {\n    return this.responsePromise.then((p) => p.response);\n  }\n\n  /**\n   * Gets the parsed response data and the raw `Response` instance.\n   *\n   * If you just want to get the raw `Response` instance without parsing it,\n   * you can use {@link asResponse()}.\n   *\n   * 👋 Getting the wrong TypeScript type for `Response`?\n   * Try setting `\"moduleResolution\": \"NodeNext\"` or add `\"lib\": [\"DOM\"]`\n   * to your `tsconfig.json`.\n   */\n  async withResponse(): Promise<{ data: T; response: Response }> {\n    const [data, response] = await Promise.all([this.parse(), this.asResponse()]);\n    return { data, response };\n  }\n\n  private parse(): Promise<T> {\n    if (!this.parsedPromise) {\n      this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(this.client, data));\n    }\n    return this.parsedPromise;\n  }\n\n  override then<TResult1 = T, TResult2 = never>(\n    onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null,\n    onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null,\n  ): Promise<TResult1 | TResult2> {\n    return this.parse().then(onfulfilled, onrejected);\n  }\n\n  override catch<TResult = never>(\n    onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null,\n  ): Promise<T | TResult> {\n    return this.parse().catch(onrejected);\n  }\n\n  override finally(onfinally?: (() => void) | undefined | null): Promise<T> {\n    return this.parse().finally(onfinally);\n  }\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport { isReadonlyArray } from './utils/values.js';\n\ntype HeaderValue = string | undefined | null;\nexport type HeadersLike =\n  | Headers\n  | readonly HeaderValue[][]\n  | Record<string, HeaderValue | readonly HeaderValue[]>\n  | undefined\n  | null\n  | NullableHeaders;\n\nconst brand_privateNullableHeaders = /* @__PURE__ */ Symbol('brand.privateNullableHeaders');\n\n/**\n * @internal\n * Users can pass explicit nulls to unset default headers. When we parse them\n * into a standard headers type we need to preserve that information.\n */\nexport type NullableHeaders = {\n  /** Brand check, prevent users from creating a NullableHeaders. */\n  [brand_privateNullableHeaders]: true;\n  /** Parsed headers. */\n  values: Headers;\n  /** Set of lowercase header names explicitly set to null. */\n  nulls: Set<string>;\n};\n\nfunction* iterateHeaders(headers: HeadersLike): IterableIterator<readonly [string, string | null]> {\n  if (!headers) return;\n\n  if (brand_privateNullableHeaders in headers) {\n    const { values, nulls } = headers;\n    yield* values.entries();\n    for (const name of nulls) {\n      yield [name, null];\n    }\n    return;\n  }\n\n  let shouldClear = false;\n  let iter: Iterable<readonly (HeaderValue | readonly HeaderValue[])[]>;\n  if (headers instanceof Headers) {\n    iter = headers.entries();\n  } else if (isReadonlyArray(headers)) {\n    iter = headers;\n  } else {\n    shouldClear = true;\n    iter = Object.entries(headers ?? {});\n  }\n  for (let row of iter) {\n    const name = row[0];\n    if (typeof name !== 'string') throw new TypeError('expected header name to be a string');\n    const values = isReadonlyArray(row[1]) ? row[1] : [row[1]];\n    let didClear = false;\n    for (const value of values) {\n      if (value === undefined) continue;\n\n      // Objects keys always overwrite older headers, they never append.\n      // Yield a null to clear the header before adding the new values.\n      if (shouldClear && !didClear) {\n        didClear = true;\n        yield [name, null];\n      }\n      yield [name, value];\n    }\n  }\n}\n\nexport const buildHeaders = (newHeaders: HeadersLike[]): NullableHeaders => {\n  const targetHeaders = new Headers();\n  const nullHeaders = new Set<string>();\n  for (const headers of newHeaders) {\n    const seenHeaders = new Set<string>();\n    for (const [name, value] of iterateHeaders(headers)) {\n      const lowerName = name.toLowerCase();\n      if (!seenHeaders.has(lowerName)) {\n        targetHeaders.delete(name);\n        seenHeaders.add(lowerName);\n      }\n      if (value === null) {\n        targetHeaders.delete(name);\n        nullHeaders.add(lowerName);\n      } else {\n        targetHeaders.append(name, value);\n        nullHeaders.delete(lowerName);\n      }\n    }\n  }\n  return { [brand_privateNullableHeaders]: true, values: targetHeaders, nulls: nullHeaders };\n};\n\nexport const isEmptyHeaders = (headers: HeadersLike) => {\n  for (const _ of iterateHeaders(headers)) return false;\n  return true;\n};\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\n/**\n * Read an environment variable.\n *\n * Trims beginning and trailing whitespace.\n *\n * Will return undefined if the environment variable doesn't exist or cannot be accessed.\n */\nexport const readEnv = (env: string): string | undefined => {\n  if (typeof (globalThis as any).process !== 'undefined') {\n    return (globalThis as any).process.env?.[env]?.trim() ?? undefined;\n  }\n  if (typeof (globalThis as any).Deno !== 'undefined') {\n    return (globalThis as any).Deno.env?.get?.(env)?.trim();\n  }\n  return undefined;\n};\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\n\nimport type { RequestInit, RequestInfo, BodyInit } from './internal/builtin-types.js';\nimport type { HTTPMethod, PromiseOrValue, MergedRequestInit, FinalizedRequestInit } from './internal/types.js';\nimport { uuid4 } from './internal/utils/uuid.js';\nimport { validatePositiveInteger, isAbsoluteURL, safeJSON } from './internal/utils/values.js';\nimport { sleep } from './internal/utils/sleep.js';\nexport type { Logger, LogLevel } from './internal/utils/log.js';\nimport { castToError, isAbortError } from './internal/errors.js';\nimport type { APIResponseProps } from './internal/parse.js';\nimport { getPlatformHeaders } from './internal/detect-platform.js';\nimport * as Shims from './internal/shims.js';\nimport * as Opts from './internal/request-options.js';\nimport { VERSION } from './version.js';\nimport * as Errors from './core/error.js';\nimport * as Uploads from './core/uploads.js';\nimport * as API from './resources/index.js';\nimport { APIPromise } from './core/api-promise.js';\nimport {\n  AllowedTools,\n  Annotation,\n  AudioContent,\n  AudioMimeType,\n  CodeExecutionCallArguments,\n  CodeExecutionCallContent,\n  CodeExecutionResultContent,\n  ContentDelta,\n  ContentStart,\n  ContentStop,\n  CreateAgentInteractionParamsNonStreaming,\n  CreateAgentInteractionParamsStreaming,\n  CreateModelInteractionParamsNonStreaming,\n  CreateModelInteractionParamsStreaming,\n  DeepResearchAgentConfig,\n  DocumentContent,\n  DynamicAgentConfig,\n  ErrorEvent,\n  FileSearchResultContent,\n  Function,\n  FunctionCallContent,\n  FunctionResultContent,\n  GenerationConfig,\n  GoogleSearchCallArguments,\n  GoogleSearchCallContent,\n  GoogleSearchResult,\n  GoogleSearchResultContent,\n  ImageContent,\n  ImageMimeType,\n  Interaction,\n  InteractionCancelParams,\n  InteractionCreateParams,\n  InteractionDeleteParams,\n  InteractionDeleteResponse,\n  InteractionEvent,\n  InteractionGetParams,\n  InteractionGetParamsNonStreaming,\n  InteractionGetParamsStreaming,\n  InteractionSSEEvent,\n  InteractionStatusUpdate,\n  Interactions,\n  MCPServerToolCallContent,\n  MCPServerToolResultContent,\n  Model,\n  SpeechConfig,\n  TextContent,\n  ThinkingLevel,\n  ThoughtContent,\n  Tool,\n  ToolChoice,\n  ToolChoiceConfig,\n  ToolChoiceType,\n  Turn,\n  URLContextCallArguments,\n  URLContextCallContent,\n  URLContextResult,\n  URLContextResultContent,\n  Usage,\n  VideoContent,\n  VideoMimeType,\n} from './resources/interactions.js';\nimport { type Fetch } from './internal/builtin-types.js';\nimport { HeadersLike, NullableHeaders, buildHeaders } from './internal/headers.js';\nimport { FinalRequestOptions, RequestOptions } from './internal/request-options.js';\nimport { readEnv } from './internal/utils/env.js';\nimport {\n  type LogLevel,\n  type Logger,\n  formatRequestDetails,\n  loggerFor,\n  parseLogLevel,\n} from './internal/utils/log.js';\nimport { isEmptyObj } from './internal/utils/values.js';\n\nexport interface ClientOptions {\n  /**\n   * Defaults to process.env['GEMINI_API_KEY'].\n   */\n  apiKey?: string | null | undefined;\n\n  apiVersion?: string | undefined;\n\n  /**\n   * Override the default base URL for the API, e.g., \"https://api.example.com/v2/\"\n   *\n   * Defaults to process.env['GEMINI_NEXT_GEN_API_BASE_URL'].\n   */\n  baseURL?: string | null | undefined;\n\n  /**\n   * The maximum amount of time (in milliseconds) that the client should wait for a response\n   * from the server before timing out a single request.\n   *\n   * Note that request timeouts are retried by default, so in a worst-case scenario you may wait\n   * much longer than this timeout before the promise succeeds or fails.\n   *\n   * @unit milliseconds\n   */\n  timeout?: number | undefined;\n  /**\n   * Additional `RequestInit` options to be passed to `fetch` calls.\n   * Properties will be overridden by per-request `fetchOptions`.\n   */\n  fetchOptions?: MergedRequestInit | undefined;\n\n  /**\n   * Specify a custom `fetch` function implementation.\n   *\n   * If not provided, we expect that `fetch` is defined globally.\n   */\n  fetch?: Fetch | undefined;\n\n  /**\n   * The maximum number of times that the client will retry a request in case of a\n   * temporary failure, like a network error or a 5XX error from the server.\n   *\n   * @default 2\n   */\n  maxRetries?: number | undefined;\n\n  /**\n   * Default headers to include with every request to the API.\n   *\n   * These can be removed in individual requests by explicitly setting the\n   * header to `null` in request options.\n   */\n  defaultHeaders?: HeadersLike | undefined;\n\n  /**\n   * Default query parameters to include with every request to the API.\n   *\n   * These can be removed in individual requests by explicitly setting the\n   * param to `undefined` in request options.\n   */\n  defaultQuery?: Record<string, string | undefined> | undefined;\n\n  /**\n   * Set the log level.\n   *\n   * Defaults to process.env['GEMINI_NEXT_GEN_API_LOG'] or 'warn' if it isn't set.\n   */\n  logLevel?: LogLevel | undefined;\n\n  /**\n   * Set the logger.\n   *\n   * Defaults to globalThis.console.\n   */\n  logger?: Logger | undefined;\n}\n\n/**\n * Base class for Gemini Next Gen API API clients.\n */\nexport class BaseGeminiNextGenAPIClient {\n  apiKey: string | null;\n  apiVersion: string;\n\n  baseURL: string;\n  maxRetries: number;\n  timeout: number;\n  logger: Logger;\n  logLevel: LogLevel | undefined;\n  fetchOptions: MergedRequestInit | undefined;\n\n  private fetch: Fetch;\n  private encoder: Opts.RequestEncoder;\n  protected idempotencyHeader?: string;\n  private _options: ClientOptions;\n\n  /**\n   * API Client for interfacing with the Gemini Next Gen API API.\n   *\n   * @param {string | null | undefined} [opts.apiKey=process.env['GEMINI_API_KEY'] ?? null]\n   * @param {string | undefined} [opts.apiVersion=v1beta]\n   * @param {string} [opts.baseURL=process.env['GEMINI_NEXT_GEN_API_BASE_URL'] ?? https://generativelanguage.googleapis.com] - Override the default base URL for the API.\n   * @param {number} [opts.timeout=1 minute] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.\n   * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.\n   * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.\n   * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.\n   * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.\n   * @param {Record<string, string | undefined>} opts.defaultQuery - Default query parameters to include with every request to the API.\n   */\n  constructor({\n    baseURL = readEnv('GEMINI_NEXT_GEN_API_BASE_URL'),\n    apiKey = readEnv('GEMINI_API_KEY') ?? null,\n    apiVersion = 'v1beta',\n    ...opts\n  }: ClientOptions = {}) {\n    const options: ClientOptions = {\n      apiKey,\n      apiVersion,\n      ...opts,\n      baseURL: baseURL || `https://generativelanguage.googleapis.com`,\n    };\n\n    this.baseURL = options.baseURL!;\n    this.timeout = options.timeout ?? BaseGeminiNextGenAPIClient.DEFAULT_TIMEOUT /* 1 minute */;\n    this.logger = options.logger ?? console;\n    const defaultLogLevel = 'warn';\n    // Set default logLevel early so that we can log a warning in parseLogLevel.\n    this.logLevel = defaultLogLevel;\n    this.logLevel =\n      parseLogLevel(options.logLevel, 'ClientOptions.logLevel', this) ??\n      parseLogLevel(readEnv('GEMINI_NEXT_GEN_API_LOG'), \"process.env['GEMINI_NEXT_GEN_API_LOG']\", this) ??\n      defaultLogLevel;\n    this.fetchOptions = options.fetchOptions;\n    this.maxRetries = options.maxRetries ?? 2;\n    this.fetch = options.fetch ?? Shims.getDefaultFetch();\n    this.encoder = Opts.FallbackEncoder;\n\n    this._options = options;\n\n    this.apiKey = apiKey;\n    this.apiVersion = apiVersion;\n  }\n\n  /**\n   * Create a new client instance re-using the same options given to the current client with optional overriding.\n   */\n  withOptions(options: Partial<ClientOptions>): this {\n    const client = new (this.constructor as any as new (props: ClientOptions) => typeof this)({\n      ...this._options,\n      baseURL: this.baseURL,\n      maxRetries: this.maxRetries,\n      timeout: this.timeout,\n      logger: this.logger,\n      logLevel: this.logLevel,\n      fetch: this.fetch,\n      fetchOptions: this.fetchOptions,\n      apiKey: this.apiKey,\n      apiVersion: this.apiVersion,\n      ...options,\n    });\n    return client;\n  }\n\n  /**\n   * Check whether the base URL is set to its default.\n   */\n  private baseURLOverridden() {\n    return this.baseURL !== 'https://generativelanguage.googleapis.com';\n  }\n\n  protected defaultQuery(): Record<string, string | undefined> | undefined {\n    return this._options.defaultQuery;\n  }\n\n  protected validateHeaders({ values, nulls }: NullableHeaders) {\n    if (this.apiKey && values.get('x-goog-api-key')) {\n      return;\n    }\n    if (nulls.has('x-goog-api-key')) {\n      return;\n    }\n\n    throw new Error(\n      'Could not resolve authentication method. Expected the apiKey to be set. Or for the \"x-goog-api-key\" headers to be explicitly omitted',\n    );\n  }\n\n  protected async authHeaders(opts: FinalRequestOptions): Promise<NullableHeaders | undefined> {\n    if (this.apiKey == null) {\n      return undefined;\n    }\n    return buildHeaders([{ 'x-goog-api-key': this.apiKey }]);\n  }\n\n  /**\n   * Basic re-implementation of `qs.stringify` for primitive types.\n   */\n  protected stringifyQuery(query: Record<string, unknown>): string {\n    return Object.entries(query)\n      .filter(([_, value]) => typeof value !== 'undefined')\n      .map(([key, value]) => {\n        if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n          return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;\n        }\n        if (value === null) {\n          return `${encodeURIComponent(key)}=`;\n        }\n        throw new Errors.GeminiNextGenAPIClientError(\n          `Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`,\n        );\n      })\n      .join('&');\n  }\n\n  private getUserAgent(): string {\n    return `${this.constructor.name}/JS ${VERSION}`;\n  }\n\n  protected defaultIdempotencyKey(): string {\n    return `stainless-node-retry-${uuid4()}`;\n  }\n\n  protected makeStatusError(\n    status: number,\n    error: Object,\n    message: string | undefined,\n    headers: Headers,\n  ): Errors.APIError {\n    return Errors.APIError.generate(status, error, message, headers);\n  }\n\n  buildURL(\n    path: string,\n    query: Record<string, unknown> | null | undefined,\n    defaultBaseURL?: string | undefined,\n  ): string {\n    const baseURL = (!this.baseURLOverridden() && defaultBaseURL) || this.baseURL;\n    const url =\n      isAbsoluteURL(path) ?\n        new URL(path)\n      : new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));\n\n    const defaultQuery = this.defaultQuery();\n    if (!isEmptyObj(defaultQuery)) {\n      query = { ...defaultQuery, ...query };\n    }\n\n    if (typeof query === 'object' && query && !Array.isArray(query)) {\n      url.search = this.stringifyQuery(query as Record<string, unknown>);\n    }\n\n    return url.toString();\n  }\n\n  /**\n   * Used as a callback for mutating the given `FinalRequestOptions` object.\n   */\n  protected async prepareOptions(options: FinalRequestOptions): Promise<void> {}\n\n  /**\n   * Used as a callback for mutating the given `RequestInit` object.\n   *\n   * This is useful for cases where you want to add certain headers based off of\n   * the request properties, e.g. `method` or `url`.\n   */\n  protected async prepareRequest(\n    request: RequestInit,\n    { url, options }: { url: string; options: FinalRequestOptions },\n  ): Promise<void> {}\n\n  get<Rsp>(path: string, opts?: PromiseOrValue<RequestOptions>): APIPromise<Rsp> {\n    return this.methodRequest('get', path, opts);\n  }\n\n  post<Rsp>(path: string, opts?: PromiseOrValue<RequestOptions>): APIPromise<Rsp> {\n    return this.methodRequest('post', path, opts);\n  }\n\n  patch<Rsp>(path: string, opts?: PromiseOrValue<RequestOptions>): APIPromise<Rsp> {\n    return this.methodRequest('patch', path, opts);\n  }\n\n  put<Rsp>(path: string, opts?: PromiseOrValue<RequestOptions>): APIPromise<Rsp> {\n    return this.methodRequest('put', path, opts);\n  }\n\n  delete<Rsp>(path: string, opts?: PromiseOrValue<RequestOptions>): APIPromise<Rsp> {\n    return this.methodRequest('delete', path, opts);\n  }\n\n  private methodRequest<Rsp>(\n    method: HTTPMethod,\n    path: string,\n    opts?: PromiseOrValue<RequestOptions>,\n  ): APIPromise<Rsp> {\n    return this.request(\n      Promise.resolve(opts).then((opts) => {\n        return { method, path, ...opts };\n      }),\n    );\n  }\n\n  request<Rsp>(\n    options: PromiseOrValue<FinalRequestOptions>,\n    remainingRetries: number | null = null,\n  ): APIPromise<Rsp> {\n    return new APIPromise(this, this.makeRequest(options, remainingRetries, undefined));\n  }\n\n  private async makeRequest(\n    optionsInput: PromiseOrValue<FinalRequestOptions>,\n    retriesRemaining: number | null,\n    retryOfRequestLogID: string | undefined,\n  ): Promise<APIResponseProps> {\n    const options = await optionsInput;\n    const maxRetries = options.maxRetries ?? this.maxRetries;\n    if (retriesRemaining == null) {\n      retriesRemaining = maxRetries;\n    }\n\n    await this.prepareOptions(options);\n\n    const { req, url, timeout } = await this.buildRequest(options, {\n      retryCount: maxRetries - retriesRemaining,\n    });\n\n    await this.prepareRequest(req, { url, options });\n\n    /** Not an API request ID, just for correlating local log entries. */\n    const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0');\n    const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`;\n    const startTime = Date.now();\n\n    loggerFor(this).debug(\n      `[${requestLogID}] sending request`,\n      formatRequestDetails({\n        retryOfRequestLogID,\n        method: options.method,\n        url,\n        options,\n        headers: req.headers,\n      }),\n    );\n\n    if (options.signal?.aborted) {\n      throw new Errors.APIUserAbortError();\n    }\n\n    const controller = new AbortController();\n    const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);\n    const headersTime = Date.now();\n\n    if (response instanceof globalThis.Error) {\n      const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;\n      if (options.signal?.aborted) {\n        throw new Errors.APIUserAbortError();\n      }\n      // detect native connection timeout errors\n      // deno throws \"TypeError: error sending request for url (https://example/): client error (Connect): tcp connect error: Operation timed out (os error 60): Operation timed out (os error 60)\"\n      // undici throws \"TypeError: fetch failed\" with cause \"ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)\"\n      // others do not provide enough information to distinguish timeouts from other connection errors\n      const isTimeout =\n        isAbortError(response) ||\n        /timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : ''));\n      if (retriesRemaining) {\n        loggerFor(this).info(\n          `[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`,\n        );\n        loggerFor(this).debug(\n          `[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`,\n          formatRequestDetails({\n            retryOfRequestLogID,\n            url,\n            durationMs: headersTime - startTime,\n            message: response.message,\n          }),\n        );\n        return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID);\n      }\n      loggerFor(this).info(\n        `[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`,\n      );\n      loggerFor(this).debug(\n        `[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`,\n        formatRequestDetails({\n          retryOfRequestLogID,\n          url,\n          durationMs: headersTime - startTime,\n          message: response.message,\n        }),\n      );\n      if (isTimeout) {\n        throw new Errors.APIConnectionTimeoutError();\n      }\n      throw new Errors.APIConnectionError({ cause: response });\n    }\n\n    const responseInfo = `[${requestLogID}${retryLogStr}] ${req.method} ${url} ${\n      response.ok ? 'succeeded' : 'failed'\n    } with status ${response.status} in ${headersTime - startTime}ms`;\n\n    if (!response.ok) {\n      const shouldRetry = await this.shouldRetry(response);\n      if (retriesRemaining && shouldRetry) {\n        const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;\n\n        // We don't need the body of this response.\n        await Shims.CancelReadableStream(response.body);\n        loggerFor(this).info(`${responseInfo} - ${retryMessage}`);\n        loggerFor(this).debug(\n          `[${requestLogID}] response error (${retryMessage})`,\n          formatRequestDetails({\n            retryOfRequestLogID,\n            url: response.url,\n            status: response.status,\n            headers: response.headers,\n            durationMs: headersTime - startTime,\n          }),\n        );\n        return this.retryRequest(\n          options,\n          retriesRemaining,\n          retryOfRequestLogID ?? requestLogID,\n          response.headers,\n        );\n      }\n\n      const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;\n\n      loggerFor(this).info(`${responseInfo} - ${retryMessage}`);\n\n      const errText = await response.text().catch((err: any) => castToError(err).message);\n      const errJSON = safeJSON(errText);\n      const errMessage = errJSON ? undefined : errText;\n\n      loggerFor(this).debug(\n        `[${requestLogID}] response error (${retryMessage})`,\n        formatRequestDetails({\n          retryOfRequestLogID,\n          url: response.url,\n          status: response.status,\n          headers: response.headers,\n          message: errMessage,\n          durationMs: Date.now() - startTime,\n        }),\n      );\n      // @ts-ignore\n      const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers);\n      throw err;\n    }\n\n    loggerFor(this).info(responseInfo);\n    loggerFor(this).debug(\n      `[${requestLogID}] response start`,\n      formatRequestDetails({\n        retryOfRequestLogID,\n        url: response.url,\n        status: response.status,\n        headers: response.headers,\n        durationMs: headersTime - startTime,\n      }),\n    );\n\n    return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };\n  }\n\n  async fetchWithTimeout(\n    url: RequestInfo,\n    init: RequestInit | undefined,\n    ms: number,\n    controller: AbortController,\n  ): Promise<Response> {\n    const { signal, method, ...options } = init || {};\n    if (signal) signal.addEventListener('abort', () => controller.abort());\n\n    const timeout = setTimeout(() => controller.abort(), ms);\n\n    const isReadableBody =\n      ((globalThis as any).ReadableStream && options.body instanceof (globalThis as any).ReadableStream) ||\n      (typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body);\n\n    const fetchOptions: RequestInit = {\n      signal: controller.signal as any,\n      ...(isReadableBody ? { duplex: 'half' } : {}),\n      method: 'GET',\n      ...options,\n    };\n    if (method) {\n      // Custom methods like 'patch' need to be uppercased\n      // See https://github.com/nodejs/undici/issues/2294\n      fetchOptions.method = method.toUpperCase();\n    }\n\n    try {\n      // use undefined this binding; fetch errors if bound to something else in browser/cloudflare\n      return await this.fetch.call(undefined, url, fetchOptions);\n    } finally {\n      clearTimeout(timeout);\n    }\n  }\n\n  private async shouldRetry(response: Response): Promise<boolean> {\n    // Note this is not a standard header.\n    const shouldRetryHeader = response.headers.get('x-should-retry');\n\n    // If the server explicitly says whether or not to retry, obey.\n    if (shouldRetryHeader === 'true') return true;\n    if (shouldRetryHeader === 'false') return false;\n\n    // Retry on request timeouts.\n    if (response.status === 408) return true;\n\n    // Retry on lock timeouts.\n    if (response.status === 409) return true;\n\n    // Retry on rate limits.\n    if (response.status === 429) return true;\n\n    // Retry internal errors.\n    if (response.status >= 500) return true;\n\n    return false;\n  }\n\n  private async retryRequest(\n    options: FinalRequestOptions,\n    retriesRemaining: number,\n    requestLogID: string,\n    responseHeaders?: Headers | undefined,\n  ): Promise<APIResponseProps> {\n    let timeoutMillis: number | undefined;\n\n    // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it.\n    const retryAfterMillisHeader = responseHeaders?.get('retry-after-ms');\n    if (retryAfterMillisHeader) {\n      const timeoutMs = parseFloat(retryAfterMillisHeader);\n      if (!Number.isNaN(timeoutMs)) {\n        timeoutMillis = timeoutMs;\n      }\n    }\n\n    // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After\n    const retryAfterHeader = responseHeaders?.get('retry-after');\n    if (retryAfterHeader && !timeoutMillis) {\n      const timeoutSeconds = parseFloat(retryAfterHeader);\n      if (!Number.isNaN(timeoutSeconds)) {\n        timeoutMillis = timeoutSeconds * 1000;\n      } else {\n        timeoutMillis = Date.parse(retryAfterHeader) - Date.now();\n      }\n    }\n\n    // If the API asks us to wait a certain amount of time (and it's a reasonable amount),\n    // just do what it says, but otherwise calculate a default\n    if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) {\n      const maxRetries = options.maxRetries ?? this.maxRetries;\n      timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);\n    }\n    await sleep(timeoutMillis);\n\n    return this.makeRequest(options, retriesRemaining - 1, requestLogID);\n  }\n\n  private calculateDefaultRetryTimeoutMillis(retriesRemaining: number, maxRetries: number): number {\n    const initialRetryDelay = 0.5;\n    const maxRetryDelay = 8.0;\n\n    const numRetries = maxRetries - retriesRemaining;\n\n    // Apply exponential backoff, but not more than the max.\n    const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);\n\n    // Apply some jitter, take up to at most 25 percent of the retry time.\n    const jitter = 1 - Math.random() * 0.25;\n\n    return sleepSeconds * jitter * 1000;\n  }\n\n  async buildRequest(\n    inputOptions: FinalRequestOptions,\n    { retryCount = 0 }: { retryCount?: number } = {},\n  ): Promise<{ req: FinalizedRequestInit; url: string; timeout: number }> {\n    const options = { ...inputOptions };\n    const { method, path, query, defaultBaseURL } = options;\n\n    const url = this.buildURL(path!, query as Record<string, unknown>, defaultBaseURL);\n    if ('timeout' in options) validatePositiveInteger('timeout', options.timeout);\n    options.timeout = options.timeout ?? this.timeout;\n    const { bodyHeaders, body } = this.buildBody({ options });\n    const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });\n\n    const req: FinalizedRequestInit = {\n      method,\n      headers: reqHeaders,\n      ...(options.signal && { signal: options.signal }),\n      ...((globalThis as any).ReadableStream &&\n        body instanceof (globalThis as any).ReadableStream && { duplex: 'half' }),\n      ...(body && { body }),\n      ...((this.fetchOptions as any) ?? {}),\n      ...((options.fetchOptions as any) ?? {}),\n    };\n\n    return { req, url, timeout: options.timeout };\n  }\n\n  private async buildHeaders({\n    options,\n    method,\n    bodyHeaders,\n    retryCount,\n  }: {\n    options: FinalRequestOptions;\n    method: HTTPMethod;\n    bodyHeaders: HeadersLike;\n    retryCount: number;\n  }): Promise<Headers> {\n    let idempotencyHeaders: HeadersLike = {};\n    if (this.idempotencyHeader && method !== 'get') {\n      if (!options.idempotencyKey) options.idempotencyKey = this.defaultIdempotencyKey();\n      idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey;\n    }\n\n    const headers = buildHeaders([\n      idempotencyHeaders,\n      {\n        Accept: 'application/json',\n        'User-Agent': this.getUserAgent(),\n        'X-Stainless-Retry-Count': String(retryCount),\n        ...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}),\n        ...getPlatformHeaders(),\n      },\n      await this.authHeaders(options),\n      this._options.defaultHeaders,\n      bodyHeaders,\n      options.headers,\n    ]);\n\n    this.validateHeaders(headers);\n\n    return headers.values;\n  }\n\n  private buildBody({ options: { body, headers: rawHeaders } }: { options: FinalRequestOptions }): {\n    bodyHeaders: HeadersLike;\n    body: BodyInit | undefined;\n  } {\n    if (!body) {\n      return { bodyHeaders: undefined, body: undefined };\n    }\n    const headers = buildHeaders([rawHeaders]);\n    if (\n      // Pass raw type verbatim\n      ArrayBuffer.isView(body) ||\n      body instanceof ArrayBuffer ||\n      body instanceof DataView ||\n      (typeof body === 'string' &&\n        // Preserve legacy string encoding behavior for now\n        headers.values.has('content-type')) ||\n      // `Blob` is superset of `File`\n      ((globalThis as any).Blob && body instanceof (globalThis as any).Blob) ||\n      // `FormData` -> `multipart/form-data`\n      body instanceof FormData ||\n      // `URLSearchParams` -> `application/x-www-form-urlencoded`\n      body instanceof URLSearchParams ||\n      // Send chunked stream (each chunk has own `length`)\n      ((globalThis as any).ReadableStream && body instanceof (globalThis as any).ReadableStream)\n    ) {\n      return { bodyHeaders: undefined, body: body as BodyInit };\n    } else if (\n      typeof body === 'object' &&\n      (Symbol.asyncIterator in body ||\n        (Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))\n    ) {\n      return { bodyHeaders: undefined, body: Shims.ReadableStreamFrom(body as AsyncIterable<Uint8Array>) };\n    } else {\n      return this.encoder({ body, headers });\n    }\n  }\n\n  static DEFAULT_TIMEOUT = 60000; // 1 minute\n}\n\n/**\n * API Client for interfacing with the Gemini Next Gen API API.\n */\nexport class GeminiNextGenAPIClient extends BaseGeminiNextGenAPIClient {\n  static GeminiNextGenAPIClient = this;\n\n  static GeminiNextGenAPIClientError = Errors.GeminiNextGenAPIClientError;\n  static APIError = Errors.APIError;\n  static APIConnectionError = Errors.APIConnectionError;\n  static APIConnectionTimeoutError = Errors.APIConnectionTimeoutError;\n  static APIUserAbortError = Errors.APIUserAbortError;\n  static NotFoundError = Errors.NotFoundError;\n  static ConflictError = Errors.ConflictError;\n  static RateLimitError = Errors.RateLimitError;\n  static BadRequestError = Errors.BadRequestError;\n  static AuthenticationError = Errors.AuthenticationError;\n  static InternalServerError = Errors.InternalServerError;\n  static PermissionDeniedError = Errors.PermissionDeniedError;\n  static UnprocessableEntityError = Errors.UnprocessableEntityError;\n\n  static toFile = Uploads.toFile;\n\n  interactions: API.Interactions = new API.Interactions(this);\n}\n\nGeminiNextGenAPIClient.Interactions = Interactions;\n\nexport declare namespace GeminiNextGenAPIClient {\n  export type RequestOptions = Opts.RequestOptions;\n\n  export {\n    Interactions as Interactions,\n    type AllowedTools as AllowedTools,\n    type Annotation as Annotation,\n    type AudioContent as AudioContent,\n    type AudioMimeType as AudioMimeType,\n    type CodeExecutionCallArguments as CodeExecutionCallArguments,\n    type CodeExecutionCallContent as CodeExecutionCallContent,\n    type CodeExecutionResultContent as CodeExecutionResultContent,\n    type ContentDelta as ContentDelta,\n    type ContentStart as ContentStart,\n    type ContentStop as ContentStop,\n    type DeepResearchAgentConfig as DeepResearchAgentConfig,\n    type DocumentContent as DocumentContent,\n    type DynamicAgentConfig as DynamicAgentConfig,\n    type ErrorEvent as ErrorEvent,\n    type FileSearchResultContent as FileSearchResultContent,\n    type Function as Function,\n    type FunctionCallContent as FunctionCallContent,\n    type FunctionResultContent as FunctionResultContent,\n    type GenerationConfig as GenerationConfig,\n    type GoogleSearchCallArguments as GoogleSearchCallArguments,\n    type GoogleSearchCallContent as GoogleSearchCallContent,\n    type GoogleSearchResult as GoogleSearchResult,\n    type GoogleSearchResultContent as GoogleSearchResultContent,\n    type ImageContent as ImageContent,\n    type ImageMimeType as ImageMimeType,\n    type Interaction as Interaction,\n    type InteractionEvent as InteractionEvent,\n    type InteractionSSEEvent as InteractionSSEEvent,\n    type InteractionStatusUpdate as InteractionStatusUpdate,\n    type MCPServerToolCallContent as MCPServerToolCallContent,\n    type MCPServerToolResultContent as MCPServerToolResultContent,\n    type Model as Model,\n    type SpeechConfig as SpeechConfig,\n    type TextContent as TextContent,\n    type ThinkingLevel as ThinkingLevel,\n    type ThoughtContent as ThoughtContent,\n    type Tool as Tool,\n    type ToolChoice as ToolChoice,\n    type ToolChoiceConfig as ToolChoiceConfig,\n    type ToolChoiceType as ToolChoiceType,\n    type Turn as Turn,\n    type URLContextCallArguments as URLContextCallArguments,\n    type URLContextCallContent as URLContextCallContent,\n    type URLContextResult as URLContextResult,\n    type URLContextResultContent as URLContextResultContent,\n    type Usage as Usage,\n    type VideoContent as VideoContent,\n    type VideoMimeType as VideoMimeType,\n    type InteractionDeleteResponse as InteractionDeleteResponse,\n    type InteractionCreateParams as InteractionCreateParams,\n    type CreateModelInteractionParamsNonStreaming as CreateModelInteractionParamsNonStreaming,\n    type CreateModelInteractionParamsStreaming as CreateModelInteractionParamsStreaming,\n    type CreateAgentInteractionParamsNonStreaming as CreateAgentInteractionParamsNonStreaming,\n    type CreateAgentInteractionParamsStreaming as CreateAgentInteractionParamsStreaming,\n    type InteractionDeleteParams as InteractionDeleteParams,\n    type InteractionCancelParams as InteractionCancelParams,\n    type InteractionGetParams as InteractionGetParams,\n    type InteractionGetParamsNonStreaming as InteractionGetParamsNonStreaming,\n    type InteractionGetParamsStreaming as InteractionGetParamsStreaming,\n  };\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport type * as types from '../types.js';\n\nexport function cancelTuningJobParametersToMldev(\n  fromObject: types.CancelTuningJobParameters,\n  _rootObject?: unknown,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromName = common.getValueByPath(fromObject, ['name']);\n  if (fromName != null) {\n    common.setValueByPath(toObject, ['_url', 'name'], fromName);\n  }\n\n  return toObject;\n}\n\nexport function cancelTuningJobParametersToVertex(\n  fromObject: types.CancelTuningJobParameters,\n  _rootObject?: unknown,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromName = common.getValueByPath(fromObject, ['name']);\n  if (fromName != null) {\n    common.setValueByPath(toObject, ['_url', 'name'], fromName);\n  }\n\n  return toObject;\n}\n\nexport function cancelTuningJobResponseFromMldev(\n  fromObject: types.CancelTuningJobResponse,\n  _rootObject?: unknown,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n    'sdkHttpResponse',\n  ]);\n  if (fromSdkHttpResponse != null) {\n    common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n  }\n\n  return toObject;\n}\n\nexport function cancelTuningJobResponseFromVertex(\n  fromObject: types.CancelTuningJobResponse,\n  _rootObject?: unknown,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n    'sdkHttpResponse',\n  ]);\n  if (fromSdkHttpResponse != null) {\n    common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n  }\n\n  return toObject;\n}\n\nexport function createTuningJobConfigToMldev(\n  fromObject: types.CreateTuningJobConfig,\n  parentObject: Record<string, unknown>,\n  _rootObject?: unknown,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  if (common.getValueByPath(fromObject, ['validationDataset']) !== undefined) {\n    throw new Error(\n      'validationDataset parameter is not supported in Gemini API.',\n    );\n  }\n\n  const fromTunedModelDisplayName = common.getValueByPath(fromObject, [\n    'tunedModelDisplayName',\n  ]);\n  if (parentObject !== undefined && fromTunedModelDisplayName != null) {\n    common.setValueByPath(\n      parentObject,\n      ['displayName'],\n      fromTunedModelDisplayName,\n    );\n  }\n\n  if (common.getValueByPath(fromObject, ['description']) !== undefined) {\n    throw new Error('description parameter is not supported in Gemini API.');\n  }\n\n  const fromEpochCount = common.getValueByPath(fromObject, ['epochCount']);\n  if (parentObject !== undefined && fromEpochCount != null) {\n    common.setValueByPath(\n      parentObject,\n      ['tuningTask', 'hyperparameters', 'epochCount'],\n      fromEpochCount,\n    );\n  }\n\n  const fromLearningRateMultiplier = common.getValueByPath(fromObject, [\n    'learningRateMultiplier',\n  ]);\n  if (fromLearningRateMultiplier != null) {\n    common.setValueByPath(\n      toObject,\n      ['tuningTask', 'hyperparameters', 'learningRateMultiplier'],\n      fromLearningRateMultiplier,\n    );\n  }\n\n  if (\n    common.getValueByPath(fromObject, ['exportLastCheckpointOnly']) !==\n    undefined\n  ) {\n    throw new Error(\n      'exportLastCheckpointOnly parameter is not supported in Gemini API.',\n    );\n  }\n\n  if (\n    common.getValueByPath(fromObject, ['preTunedModelCheckpointId']) !==\n    undefined\n  ) {\n    throw new Error(\n      'preTunedModelCheckpointId parameter is not supported in Gemini API.',\n    );\n  }\n\n  if (common.getValueByPath(fromObject, ['adapterSize']) !== undefined) {\n    throw new Error('adapterSize parameter is not supported in Gemini API.');\n  }\n\n  const fromBatchSize = common.getValueByPath(fromObject, ['batchSize']);\n  if (parentObject !== undefined && fromBatchSize != null) {\n    common.setValueByPath(\n      parentObject,\n      ['tuningTask', 'hyperparameters', 'batchSize'],\n      fromBatchSize,\n    );\n  }\n\n  const fromLearningRate = common.getValueByPath(fromObject, ['learningRate']);\n  if (parentObject !== undefined && fromLearningRate != null) {\n    common.setValueByPath(\n      parentObject,\n      ['tuningTask', 'hyperparameters', 'learningRate'],\n      fromLearningRate,\n    );\n  }\n\n  if (common.getValueByPath(fromObject, ['labels']) !== undefined) {\n    throw new Error('labels parameter is not supported in Gemini API.');\n  }\n\n  if (common.getValueByPath(fromObject, ['beta']) !== undefined) {\n    throw new Error('beta parameter is not supported in Gemini API.');\n  }\n\n  return toObject;\n}\n\nexport function createTuningJobConfigToVertex(\n  fromObject: types.CreateTuningJobConfig,\n  parentObject: Record<string, unknown>,\n  rootObject?: unknown,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  let discriminatorValidationDataset = common.getValueByPath(rootObject, [\n    'config',\n    'method',\n  ]);\n  if (discriminatorValidationDataset === undefined) {\n    discriminatorValidationDataset = 'SUPERVISED_FINE_TUNING';\n  }\n  if (discriminatorValidationDataset === 'SUPERVISED_FINE_TUNING') {\n    const fromValidationDataset = common.getValueByPath(fromObject, [\n      'validationDataset',\n    ]);\n    if (parentObject !== undefined && fromValidationDataset != null) {\n      common.setValueByPath(\n        parentObject,\n        ['supervisedTuningSpec'],\n        tuningValidationDatasetToVertex(fromValidationDataset, rootObject),\n      );\n    }\n  } else if (discriminatorValidationDataset === 'PREFERENCE_TUNING') {\n    const fromValidationDataset = common.getValueByPath(fromObject, [\n      'validationDataset',\n    ]);\n    if (parentObject !== undefined && fromValidationDataset != null) {\n      common.setValueByPath(\n        parentObject,\n        ['preferenceOptimizationSpec'],\n        tuningValidationDatasetToVertex(fromValidationDataset, rootObject),\n      );\n    }\n  }\n\n  const fromTunedModelDisplayName = common.getValueByPath(fromObject, [\n    'tunedModelDisplayName',\n  ]);\n  if (parentObject !== undefined && fromTunedModelDisplayName != null) {\n    common.setValueByPath(\n      parentObject,\n      ['tunedModelDisplayName'],\n      fromTunedModelDisplayName,\n    );\n  }\n\n  const fromDescription = common.getValueByPath(fromObject, ['description']);\n  if (parentObject !== undefined && fromDescription != null) {\n    common.setValueByPath(parentObject, ['description'], fromDescription);\n  }\n\n  let discriminatorEpochCount = common.getValueByPath(rootObject, [\n    'config',\n    'method',\n  ]);\n  if (discriminatorEpochCount === undefined) {\n    discriminatorEpochCount = 'SUPERVISED_FINE_TUNING';\n  }\n  if (discriminatorEpochCount === 'SUPERVISED_FINE_TUNING') {\n    const fromEpochCount = common.getValueByPath(fromObject, ['epochCount']);\n    if (parentObject !== undefined && fromEpochCount != null) {\n      common.setValueByPath(\n        parentObject,\n        ['supervisedTuningSpec', 'hyperParameters', 'epochCount'],\n        fromEpochCount,\n      );\n    }\n  } else if (discriminatorEpochCount === 'PREFERENCE_TUNING') {\n    const fromEpochCount = common.getValueByPath(fromObject, ['epochCount']);\n    if (parentObject !== undefined && fromEpochCount != null) {\n      common.setValueByPath(\n        parentObject,\n        ['preferenceOptimizationSpec', 'hyperParameters', 'epochCount'],\n        fromEpochCount,\n      );\n    }\n  }\n\n  let discriminatorLearningRateMultiplier = common.getValueByPath(rootObject, [\n    'config',\n    'method',\n  ]);\n  if (discriminatorLearningRateMultiplier === undefined) {\n    discriminatorLearningRateMultiplier = 'SUPERVISED_FINE_TUNING';\n  }\n  if (discriminatorLearningRateMultiplier === 'SUPERVISED_FINE_TUNING') {\n    const fromLearningRateMultiplier = common.getValueByPath(fromObject, [\n      'learningRateMultiplier',\n    ]);\n    if (parentObject !== undefined && fromLearningRateMultiplier != null) {\n      common.setValueByPath(\n        parentObject,\n        ['supervisedTuningSpec', 'hyperParameters', 'learningRateMultiplier'],\n        fromLearningRateMultiplier,\n      );\n    }\n  } else if (discriminatorLearningRateMultiplier === 'PREFERENCE_TUNING') {\n    const fromLearningRateMultiplier = common.getValueByPath(fromObject, [\n      'learningRateMultiplier',\n    ]);\n    if (parentObject !== undefined && fromLearningRateMultiplier != null) {\n      common.setValueByPath(\n        parentObject,\n        [\n          'preferenceOptimizationSpec',\n          'hyperParameters',\n          'learningRateMultiplier',\n        ],\n        fromLearningRateMultiplier,\n      );\n    }\n  }\n\n  let discriminatorExportLastCheckpointOnly = common.getValueByPath(\n    rootObject,\n    ['config', 'method'],\n  );\n  if (discriminatorExportLastCheckpointOnly === undefined) {\n    discriminatorExportLastCheckpointOnly = 'SUPERVISED_FINE_TUNING';\n  }\n  if (discriminatorExportLastCheckpointOnly === 'SUPERVISED_FINE_TUNING') {\n    const fromExportLastCheckpointOnly = common.getValueByPath(fromObject, [\n      'exportLastCheckpointOnly',\n    ]);\n    if (parentObject !== undefined && fromExportLastCheckpointOnly != null) {\n      common.setValueByPath(\n        parentObject,\n        ['supervisedTuningSpec', 'exportLastCheckpointOnly'],\n        fromExportLastCheckpointOnly,\n      );\n    }\n  } else if (discriminatorExportLastCheckpointOnly === 'PREFERENCE_TUNING') {\n    const fromExportLastCheckpointOnly = common.getValueByPath(fromObject, [\n      'exportLastCheckpointOnly',\n    ]);\n    if (parentObject !== undefined && fromExportLastCheckpointOnly != null) {\n      common.setValueByPath(\n        parentObject,\n        ['preferenceOptimizationSpec', 'exportLastCheckpointOnly'],\n        fromExportLastCheckpointOnly,\n      );\n    }\n  }\n\n  let discriminatorAdapterSize = common.getValueByPath(rootObject, [\n    'config',\n    'method',\n  ]);\n  if (discriminatorAdapterSize === undefined) {\n    discriminatorAdapterSize = 'SUPERVISED_FINE_TUNING';\n  }\n  if (discriminatorAdapterSize === 'SUPERVISED_FINE_TUNING') {\n    const fromAdapterSize = common.getValueByPath(fromObject, ['adapterSize']);\n    if (parentObject !== undefined && fromAdapterSize != null) {\n      common.setValueByPath(\n        parentObject,\n        ['supervisedTuningSpec', 'hyperParameters', 'adapterSize'],\n        fromAdapterSize,\n      );\n    }\n  } else if (discriminatorAdapterSize === 'PREFERENCE_TUNING') {\n    const fromAdapterSize = common.getValueByPath(fromObject, ['adapterSize']);\n    if (parentObject !== undefined && fromAdapterSize != null) {\n      common.setValueByPath(\n        parentObject,\n        ['preferenceOptimizationSpec', 'hyperParameters', 'adapterSize'],\n        fromAdapterSize,\n      );\n    }\n  }\n  if (common.getValueByPath(fromObject, ['batchSize']) !== undefined) {\n    throw new Error('batchSize parameter is not supported in Vertex AI.');\n  }\n\n  if (common.getValueByPath(fromObject, ['learningRate']) !== undefined) {\n    throw new Error('learningRate parameter is not supported in Vertex AI.');\n  }\n\n  const fromLabels = common.getValueByPath(fromObject, ['labels']);\n  if (parentObject !== undefined && fromLabels != null) {\n    common.setValueByPath(parentObject, ['labels'], fromLabels);\n  }\n\n  const fromBeta = common.getValueByPath(fromObject, ['beta']);\n  if (parentObject !== undefined && fromBeta != null) {\n    common.setValueByPath(\n      parentObject,\n      ['preferenceOptimizationSpec', 'hyperParameters', 'beta'],\n      fromBeta,\n    );\n  }\n\n  return toObject;\n}\n\nexport function createTuningJobParametersPrivateToMldev(\n  fromObject: types.CreateTuningJobParametersPrivate,\n  rootObject?: unknown,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n  if (fromBaseModel != null) {\n    common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n  }\n\n  const fromPreTunedModel = common.getValueByPath(fromObject, [\n    'preTunedModel',\n  ]);\n  if (fromPreTunedModel != null) {\n    common.setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel);\n  }\n\n  const fromTrainingDataset = common.getValueByPath(fromObject, [\n    'trainingDataset',\n  ]);\n  if (fromTrainingDataset != null) {\n    tuningDatasetToMldev(fromTrainingDataset, rootObject);\n  }\n\n  const fromConfig = common.getValueByPath(fromObject, ['config']);\n  if (fromConfig != null) {\n    createTuningJobConfigToMldev(fromConfig, toObject, rootObject);\n  }\n\n  return toObject;\n}\n\nexport function createTuningJobParametersPrivateToVertex(\n  fromObject: types.CreateTuningJobParametersPrivate,\n  rootObject?: unknown,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n  if (fromBaseModel != null) {\n    common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n  }\n\n  const fromPreTunedModel = common.getValueByPath(fromObject, [\n    'preTunedModel',\n  ]);\n  if (fromPreTunedModel != null) {\n    common.setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel);\n  }\n\n  const fromTrainingDataset = common.getValueByPath(fromObject, [\n    'trainingDataset',\n  ]);\n  if (fromTrainingDataset != null) {\n    tuningDatasetToVertex(fromTrainingDataset, toObject, rootObject);\n  }\n\n  const fromConfig = common.getValueByPath(fromObject, ['config']);\n  if (fromConfig != null) {\n    createTuningJobConfigToVertex(fromConfig, toObject, rootObject);\n  }\n\n  return toObject;\n}\n\nexport function getTuningJobParametersToMldev(\n  fromObject: types.GetTuningJobParameters,\n  _rootObject?: unknown,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromName = common.getValueByPath(fromObject, ['name']);\n  if (fromName != null) {\n    common.setValueByPath(toObject, ['_url', 'name'], fromName);\n  }\n\n  return toObject;\n}\n\nexport function getTuningJobParametersToVertex(\n  fromObject: types.GetTuningJobParameters,\n  _rootObject?: unknown,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromName = common.getValueByPath(fromObject, ['name']);\n  if (fromName != null) {\n    common.setValueByPath(toObject, ['_url', 'name'], fromName);\n  }\n\n  return toObject;\n}\n\nexport function listTuningJobsConfigToMldev(\n  fromObject: types.ListTuningJobsConfig,\n  parentObject: Record<string, unknown>,\n  _rootObject?: unknown,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n  if (parentObject !== undefined && fromPageSize != null) {\n    common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n  }\n\n  const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n  if (parentObject !== undefined && fromPageToken != null) {\n    common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n  }\n\n  const fromFilter = common.getValueByPath(fromObject, ['filter']);\n  if (parentObject !== undefined && fromFilter != null) {\n    common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n  }\n\n  return toObject;\n}\n\nexport function listTuningJobsConfigToVertex(\n  fromObject: types.ListTuningJobsConfig,\n  parentObject: Record<string, unknown>,\n  _rootObject?: unknown,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n  if (parentObject !== undefined && fromPageSize != null) {\n    common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n  }\n\n  const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n  if (parentObject !== undefined && fromPageToken != null) {\n    common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n  }\n\n  const fromFilter = common.getValueByPath(fromObject, ['filter']);\n  if (parentObject !== undefined && fromFilter != null) {\n    common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n  }\n\n  return toObject;\n}\n\nexport function listTuningJobsParametersToMldev(\n  fromObject: types.ListTuningJobsParameters,\n  rootObject?: unknown,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromConfig = common.getValueByPath(fromObject, ['config']);\n  if (fromConfig != null) {\n    listTuningJobsConfigToMldev(fromConfig, toObject, rootObject);\n  }\n\n  return toObject;\n}\n\nexport function listTuningJobsParametersToVertex(\n  fromObject: types.ListTuningJobsParameters,\n  rootObject?: unknown,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromConfig = common.getValueByPath(fromObject, ['config']);\n  if (fromConfig != null) {\n    listTuningJobsConfigToVertex(fromConfig, toObject, rootObject);\n  }\n\n  return toObject;\n}\n\nexport function listTuningJobsResponseFromMldev(\n  fromObject: types.ListTuningJobsResponse,\n  rootObject?: unknown,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n    'sdkHttpResponse',\n  ]);\n  if (fromSdkHttpResponse != null) {\n    common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n  }\n\n  const fromNextPageToken = common.getValueByPath(fromObject, [\n    'nextPageToken',\n  ]);\n  if (fromNextPageToken != null) {\n    common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n  }\n\n  const fromTuningJobs = common.getValueByPath(fromObject, ['tunedModels']);\n  if (fromTuningJobs != null) {\n    let transformedList = fromTuningJobs;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return tuningJobFromMldev(item, rootObject);\n      });\n    }\n    common.setValueByPath(toObject, ['tuningJobs'], transformedList);\n  }\n\n  return toObject;\n}\n\nexport function listTuningJobsResponseFromVertex(\n  fromObject: types.ListTuningJobsResponse,\n  rootObject?: unknown,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n    'sdkHttpResponse',\n  ]);\n  if (fromSdkHttpResponse != null) {\n    common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n  }\n\n  const fromNextPageToken = common.getValueByPath(fromObject, [\n    'nextPageToken',\n  ]);\n  if (fromNextPageToken != null) {\n    common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n  }\n\n  const fromTuningJobs = common.getValueByPath(fromObject, ['tuningJobs']);\n  if (fromTuningJobs != null) {\n    let transformedList = fromTuningJobs;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return tuningJobFromVertex(item, rootObject);\n      });\n    }\n    common.setValueByPath(toObject, ['tuningJobs'], transformedList);\n  }\n\n  return toObject;\n}\n\nexport function tunedModelFromMldev(\n  fromObject: types.TunedModel,\n  _rootObject?: unknown,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromModel = common.getValueByPath(fromObject, ['name']);\n  if (fromModel != null) {\n    common.setValueByPath(toObject, ['model'], fromModel);\n  }\n\n  const fromEndpoint = common.getValueByPath(fromObject, ['name']);\n  if (fromEndpoint != null) {\n    common.setValueByPath(toObject, ['endpoint'], fromEndpoint);\n  }\n\n  return toObject;\n}\n\nexport function tuningDatasetToMldev(\n  fromObject: types.TuningDataset,\n  _rootObject?: unknown,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  if (common.getValueByPath(fromObject, ['gcsUri']) !== undefined) {\n    throw new Error('gcsUri parameter is not supported in Gemini API.');\n  }\n\n  if (\n    common.getValueByPath(fromObject, ['vertexDatasetResource']) !== undefined\n  ) {\n    throw new Error(\n      'vertexDatasetResource parameter is not supported in Gemini API.',\n    );\n  }\n\n  const fromExamples = common.getValueByPath(fromObject, ['examples']);\n  if (fromExamples != null) {\n    let transformedList = fromExamples;\n    if (Array.isArray(transformedList)) {\n      transformedList = transformedList.map((item) => {\n        return item;\n      });\n    }\n    common.setValueByPath(toObject, ['examples', 'examples'], transformedList);\n  }\n\n  return toObject;\n}\n\nexport function tuningDatasetToVertex(\n  fromObject: types.TuningDataset,\n  parentObject: Record<string, unknown>,\n  rootObject?: unknown,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  let discriminatorGcsUri = common.getValueByPath(rootObject, [\n    'config',\n    'method',\n  ]);\n  if (discriminatorGcsUri === undefined) {\n    discriminatorGcsUri = 'SUPERVISED_FINE_TUNING';\n  }\n  if (discriminatorGcsUri === 'SUPERVISED_FINE_TUNING') {\n    const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n    if (parentObject !== undefined && fromGcsUri != null) {\n      common.setValueByPath(\n        parentObject,\n        ['supervisedTuningSpec', 'trainingDatasetUri'],\n        fromGcsUri,\n      );\n    }\n  } else if (discriminatorGcsUri === 'PREFERENCE_TUNING') {\n    const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n    if (parentObject !== undefined && fromGcsUri != null) {\n      common.setValueByPath(\n        parentObject,\n        ['preferenceOptimizationSpec', 'trainingDatasetUri'],\n        fromGcsUri,\n      );\n    }\n  }\n\n  let discriminatorVertexDatasetResource = common.getValueByPath(rootObject, [\n    'config',\n    'method',\n  ]);\n  if (discriminatorVertexDatasetResource === undefined) {\n    discriminatorVertexDatasetResource = 'SUPERVISED_FINE_TUNING';\n  }\n  if (discriminatorVertexDatasetResource === 'SUPERVISED_FINE_TUNING') {\n    const fromVertexDatasetResource = common.getValueByPath(fromObject, [\n      'vertexDatasetResource',\n    ]);\n    if (parentObject !== undefined && fromVertexDatasetResource != null) {\n      common.setValueByPath(\n        parentObject,\n        ['supervisedTuningSpec', 'trainingDatasetUri'],\n        fromVertexDatasetResource,\n      );\n    }\n  } else if (discriminatorVertexDatasetResource === 'PREFERENCE_TUNING') {\n    const fromVertexDatasetResource = common.getValueByPath(fromObject, [\n      'vertexDatasetResource',\n    ]);\n    if (parentObject !== undefined && fromVertexDatasetResource != null) {\n      common.setValueByPath(\n        parentObject,\n        ['preferenceOptimizationSpec', 'trainingDatasetUri'],\n        fromVertexDatasetResource,\n      );\n    }\n  }\n  if (common.getValueByPath(fromObject, ['examples']) !== undefined) {\n    throw new Error('examples parameter is not supported in Vertex AI.');\n  }\n\n  return toObject;\n}\n\nexport function tuningJobFromMldev(\n  fromObject: types.TuningJob,\n  rootObject?: unknown,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n    'sdkHttpResponse',\n  ]);\n  if (fromSdkHttpResponse != null) {\n    common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n  }\n\n  const fromName = common.getValueByPath(fromObject, ['name']);\n  if (fromName != null) {\n    common.setValueByPath(toObject, ['name'], fromName);\n  }\n\n  const fromState = common.getValueByPath(fromObject, ['state']);\n  if (fromState != null) {\n    common.setValueByPath(toObject, ['state'], t.tTuningJobStatus(fromState));\n  }\n\n  const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n  if (fromCreateTime != null) {\n    common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n  }\n\n  const fromStartTime = common.getValueByPath(fromObject, [\n    'tuningTask',\n    'startTime',\n  ]);\n  if (fromStartTime != null) {\n    common.setValueByPath(toObject, ['startTime'], fromStartTime);\n  }\n\n  const fromEndTime = common.getValueByPath(fromObject, [\n    'tuningTask',\n    'completeTime',\n  ]);\n  if (fromEndTime != null) {\n    common.setValueByPath(toObject, ['endTime'], fromEndTime);\n  }\n\n  const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n  if (fromUpdateTime != null) {\n    common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n  }\n\n  const fromDescription = common.getValueByPath(fromObject, ['description']);\n  if (fromDescription != null) {\n    common.setValueByPath(toObject, ['description'], fromDescription);\n  }\n\n  const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n  if (fromBaseModel != null) {\n    common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n  }\n\n  const fromTunedModel = common.getValueByPath(fromObject, ['_self']);\n  if (fromTunedModel != null) {\n    common.setValueByPath(\n      toObject,\n      ['tunedModel'],\n      tunedModelFromMldev(fromTunedModel, rootObject),\n    );\n  }\n\n  return toObject;\n}\n\nexport function tuningJobFromVertex(\n  fromObject: types.TuningJob,\n  _rootObject?: unknown,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n    'sdkHttpResponse',\n  ]);\n  if (fromSdkHttpResponse != null) {\n    common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n  }\n\n  const fromName = common.getValueByPath(fromObject, ['name']);\n  if (fromName != null) {\n    common.setValueByPath(toObject, ['name'], fromName);\n  }\n\n  const fromState = common.getValueByPath(fromObject, ['state']);\n  if (fromState != null) {\n    common.setValueByPath(toObject, ['state'], t.tTuningJobStatus(fromState));\n  }\n\n  const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n  if (fromCreateTime != null) {\n    common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n  }\n\n  const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n  if (fromStartTime != null) {\n    common.setValueByPath(toObject, ['startTime'], fromStartTime);\n  }\n\n  const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n  if (fromEndTime != null) {\n    common.setValueByPath(toObject, ['endTime'], fromEndTime);\n  }\n\n  const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n  if (fromUpdateTime != null) {\n    common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n  }\n\n  const fromError = common.getValueByPath(fromObject, ['error']);\n  if (fromError != null) {\n    common.setValueByPath(toObject, ['error'], fromError);\n  }\n\n  const fromDescription = common.getValueByPath(fromObject, ['description']);\n  if (fromDescription != null) {\n    common.setValueByPath(toObject, ['description'], fromDescription);\n  }\n\n  const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n  if (fromBaseModel != null) {\n    common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n  }\n\n  const fromTunedModel = common.getValueByPath(fromObject, ['tunedModel']);\n  if (fromTunedModel != null) {\n    common.setValueByPath(toObject, ['tunedModel'], fromTunedModel);\n  }\n\n  const fromPreTunedModel = common.getValueByPath(fromObject, [\n    'preTunedModel',\n  ]);\n  if (fromPreTunedModel != null) {\n    common.setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel);\n  }\n\n  const fromSupervisedTuningSpec = common.getValueByPath(fromObject, [\n    'supervisedTuningSpec',\n  ]);\n  if (fromSupervisedTuningSpec != null) {\n    common.setValueByPath(\n      toObject,\n      ['supervisedTuningSpec'],\n      fromSupervisedTuningSpec,\n    );\n  }\n\n  const fromPreferenceOptimizationSpec = common.getValueByPath(fromObject, [\n    'preferenceOptimizationSpec',\n  ]);\n  if (fromPreferenceOptimizationSpec != null) {\n    common.setValueByPath(\n      toObject,\n      ['preferenceOptimizationSpec'],\n      fromPreferenceOptimizationSpec,\n    );\n  }\n\n  const fromTuningDataStats = common.getValueByPath(fromObject, [\n    'tuningDataStats',\n  ]);\n  if (fromTuningDataStats != null) {\n    common.setValueByPath(toObject, ['tuningDataStats'], fromTuningDataStats);\n  }\n\n  const fromEncryptionSpec = common.getValueByPath(fromObject, [\n    'encryptionSpec',\n  ]);\n  if (fromEncryptionSpec != null) {\n    common.setValueByPath(toObject, ['encryptionSpec'], fromEncryptionSpec);\n  }\n\n  const fromPartnerModelTuningSpec = common.getValueByPath(fromObject, [\n    'partnerModelTuningSpec',\n  ]);\n  if (fromPartnerModelTuningSpec != null) {\n    common.setValueByPath(\n      toObject,\n      ['partnerModelTuningSpec'],\n      fromPartnerModelTuningSpec,\n    );\n  }\n\n  const fromCustomBaseModel = common.getValueByPath(fromObject, [\n    'customBaseModel',\n  ]);\n  if (fromCustomBaseModel != null) {\n    common.setValueByPath(toObject, ['customBaseModel'], fromCustomBaseModel);\n  }\n\n  const fromExperiment = common.getValueByPath(fromObject, ['experiment']);\n  if (fromExperiment != null) {\n    common.setValueByPath(toObject, ['experiment'], fromExperiment);\n  }\n\n  const fromLabels = common.getValueByPath(fromObject, ['labels']);\n  if (fromLabels != null) {\n    common.setValueByPath(toObject, ['labels'], fromLabels);\n  }\n\n  const fromOutputUri = common.getValueByPath(fromObject, ['outputUri']);\n  if (fromOutputUri != null) {\n    common.setValueByPath(toObject, ['outputUri'], fromOutputUri);\n  }\n\n  const fromPipelineJob = common.getValueByPath(fromObject, ['pipelineJob']);\n  if (fromPipelineJob != null) {\n    common.setValueByPath(toObject, ['pipelineJob'], fromPipelineJob);\n  }\n\n  const fromServiceAccount = common.getValueByPath(fromObject, [\n    'serviceAccount',\n  ]);\n  if (fromServiceAccount != null) {\n    common.setValueByPath(toObject, ['serviceAccount'], fromServiceAccount);\n  }\n\n  const fromTunedModelDisplayName = common.getValueByPath(fromObject, [\n    'tunedModelDisplayName',\n  ]);\n  if (fromTunedModelDisplayName != null) {\n    common.setValueByPath(\n      toObject,\n      ['tunedModelDisplayName'],\n      fromTunedModelDisplayName,\n    );\n  }\n\n  const fromVeoTuningSpec = common.getValueByPath(fromObject, [\n    'veoTuningSpec',\n  ]);\n  if (fromVeoTuningSpec != null) {\n    common.setValueByPath(toObject, ['veoTuningSpec'], fromVeoTuningSpec);\n  }\n\n  return toObject;\n}\n\nexport function tuningOperationFromMldev(\n  fromObject: types.TuningOperation,\n  _rootObject?: unknown,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n    'sdkHttpResponse',\n  ]);\n  if (fromSdkHttpResponse != null) {\n    common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n  }\n\n  const fromName = common.getValueByPath(fromObject, ['name']);\n  if (fromName != null) {\n    common.setValueByPath(toObject, ['name'], fromName);\n  }\n\n  const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n  if (fromMetadata != null) {\n    common.setValueByPath(toObject, ['metadata'], fromMetadata);\n  }\n\n  const fromDone = common.getValueByPath(fromObject, ['done']);\n  if (fromDone != null) {\n    common.setValueByPath(toObject, ['done'], fromDone);\n  }\n\n  const fromError = common.getValueByPath(fromObject, ['error']);\n  if (fromError != null) {\n    common.setValueByPath(toObject, ['error'], fromError);\n  }\n\n  return toObject;\n}\n\nexport function tuningValidationDatasetToVertex(\n  fromObject: types.TuningValidationDataset,\n  _rootObject?: unknown,\n): Record<string, unknown> {\n  const toObject: Record<string, unknown> = {};\n\n  const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n  if (fromGcsUri != null) {\n    common.setValueByPath(toObject, ['validationDatasetUri'], fromGcsUri);\n  }\n\n  const fromVertexDatasetResource = common.getValueByPath(fromObject, [\n    'vertexDatasetResource',\n  ]);\n  if (fromVertexDatasetResource != null) {\n    common.setValueByPath(\n      toObject,\n      ['validationDatasetUri'],\n      fromVertexDatasetResource,\n    );\n  }\n\n  return toObject;\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_tunings_converters.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Tunings extends BaseModule {\n  constructor(private readonly apiClient: ApiClient) {\n    super();\n  }\n\n  /**\n   * Lists tuning jobs.\n   *\n   * @param params - The parameters for the list request.\n   * @return - A pager of tuning jobs.\n   *\n   * @example\n   * ```ts\n   * const tuningJobs = await ai.tunings.list({config: {'pageSize': 2}});\n   * for await (const tuningJob of tuningJobs) {\n   *   console.log(tuningJob);\n   * }\n   * ```\n   */\n  list = async (\n    params: types.ListTuningJobsParameters = {},\n  ): Promise<Pager<types.TuningJob>> => {\n    return new Pager<types.TuningJob>(\n      PagedItem.PAGED_ITEM_TUNING_JOBS,\n      (x: types.ListTuningJobsParameters) => this.listInternal(x),\n      await this.listInternal(params),\n      params,\n    );\n  };\n\n  /**\n   * Gets a TuningJob.\n   *\n   * @param name - The resource name of the tuning job.\n   * @return - A TuningJob object.\n   *\n   * @experimental - The SDK's tuning implementation is experimental, and may\n   * change in future versions.\n   */\n  get = async (\n    params: types.GetTuningJobParameters,\n  ): Promise<types.TuningJob> => {\n    return await this.getInternal(params);\n  };\n\n  /**\n   * Creates a supervised fine-tuning job.\n   *\n   * @param params - The parameters for the tuning job.\n   * @return - A TuningJob operation.\n   *\n   * @experimental - The SDK's tuning implementation is experimental, and may\n   * change in future versions.\n   */\n  tune = async (\n    params: types.CreateTuningJobParameters,\n  ): Promise<types.TuningJob> => {\n    if (this.apiClient.isVertexAI()) {\n      if (params.baseModel.startsWith('projects/')) {\n        const preTunedModel: types.PreTunedModel = {\n          tunedModelName: params.baseModel,\n        };\n        if (params.config?.preTunedModelCheckpointId) {\n          preTunedModel.checkpointId = params.config.preTunedModelCheckpointId;\n        }\n        const paramsPrivate: types.CreateTuningJobParametersPrivate = {\n          ...params,\n          preTunedModel: preTunedModel,\n        };\n        paramsPrivate.baseModel = undefined;\n        return await this.tuneInternal(paramsPrivate);\n      } else {\n        const paramsPrivate: types.CreateTuningJobParametersPrivate = {\n          ...params,\n        };\n        return await this.tuneInternal(paramsPrivate);\n      }\n    } else {\n      const paramsPrivate: types.CreateTuningJobParametersPrivate = {\n        ...params,\n      };\n      const operation = await this.tuneMldevInternal(paramsPrivate);\n      let tunedModelName = '';\n      if (\n        operation['metadata'] !== undefined &&\n        operation['metadata']['tunedModel'] !== undefined\n      ) {\n        tunedModelName = operation['metadata']['tunedModel'] as string;\n      } else if (\n        operation['name'] !== undefined &&\n        operation['name'].includes('/operations/')\n      ) {\n        tunedModelName = operation['name'].split('/operations/')[0];\n      }\n      const tuningJob: types.TuningJob = {\n        name: tunedModelName,\n        state: types.JobState.JOB_STATE_QUEUED,\n      };\n\n      return tuningJob;\n    }\n  };\n\n  private async getInternal(\n    params: types.GetTuningJobParameters,\n  ): Promise<types.TuningJob> {\n    let response: Promise<types.TuningJob>;\n\n    let path: string = '';\n    let queryParams: Record<string, string> = {};\n    if (this.apiClient.isVertexAI()) {\n      const body = converters.getTuningJobParametersToVertex(params, params);\n      path = common.formatMap(\n        '{name}',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'GET',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json().then((jsonResponse) => {\n            const response = jsonResponse as types.TuningJob;\n            response.sdkHttpResponse = {\n              headers: httpResponse.headers,\n            } as types.HttpResponse;\n            return response;\n          });\n        }) as Promise<types.TuningJob>;\n\n      return response.then((apiResponse) => {\n        const resp = converters.tuningJobFromVertex(apiResponse);\n\n        return resp as types.TuningJob;\n      });\n    } else {\n      const body = converters.getTuningJobParametersToMldev(params, params);\n      path = common.formatMap(\n        '{name}',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'GET',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json().then((jsonResponse) => {\n            const response = jsonResponse as types.TuningJob;\n            response.sdkHttpResponse = {\n              headers: httpResponse.headers,\n            } as types.HttpResponse;\n            return response;\n          });\n        }) as Promise<types.TuningJob>;\n\n      return response.then((apiResponse) => {\n        const resp = converters.tuningJobFromMldev(apiResponse);\n\n        return resp as types.TuningJob;\n      });\n    }\n  }\n\n  private async listInternal(\n    params: types.ListTuningJobsParameters,\n  ): Promise<types.ListTuningJobsResponse> {\n    let response: Promise<types.ListTuningJobsResponse>;\n\n    let path: string = '';\n    let queryParams: Record<string, string> = {};\n    if (this.apiClient.isVertexAI()) {\n      const body = converters.listTuningJobsParametersToVertex(params, params);\n      path = common.formatMap(\n        'tuningJobs',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'GET',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json().then((jsonResponse) => {\n            const response = jsonResponse as types.ListTuningJobsResponse;\n            response.sdkHttpResponse = {\n              headers: httpResponse.headers,\n            } as types.HttpResponse;\n            return response;\n          });\n        }) as Promise<types.ListTuningJobsResponse>;\n\n      return response.then((apiResponse) => {\n        const resp = converters.listTuningJobsResponseFromVertex(apiResponse);\n        const typedResp = new types.ListTuningJobsResponse();\n        Object.assign(typedResp, resp);\n        return typedResp;\n      });\n    } else {\n      const body = converters.listTuningJobsParametersToMldev(params, params);\n      path = common.formatMap(\n        'tunedModels',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'GET',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json().then((jsonResponse) => {\n            const response = jsonResponse as types.ListTuningJobsResponse;\n            response.sdkHttpResponse = {\n              headers: httpResponse.headers,\n            } as types.HttpResponse;\n            return response;\n          });\n        }) as Promise<types.ListTuningJobsResponse>;\n\n      return response.then((apiResponse) => {\n        const resp = converters.listTuningJobsResponseFromMldev(apiResponse);\n        const typedResp = new types.ListTuningJobsResponse();\n        Object.assign(typedResp, resp);\n        return typedResp;\n      });\n    }\n  }\n\n  /**\n   * Cancels a tuning job.\n   *\n   * @param params - The parameters for the cancel request.\n   * @return The empty response returned by the API.\n   *\n   * @example\n   * ```ts\n   * await ai.tunings.cancel({name: '...'}); // The server-generated resource name.\n   * ```\n   */\n  async cancel(\n    params: types.CancelTuningJobParameters,\n  ): Promise<types.CancelTuningJobResponse> {\n    let response: Promise<types.CancelTuningJobResponse>;\n\n    let path: string = '';\n    let queryParams: Record<string, string> = {};\n    if (this.apiClient.isVertexAI()) {\n      const body = converters.cancelTuningJobParametersToVertex(params, params);\n      path = common.formatMap(\n        '{name}:cancel',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'POST',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json().then((jsonResponse) => {\n            const response = jsonResponse as types.CancelTuningJobResponse;\n            response.sdkHttpResponse = {\n              headers: httpResponse.headers,\n            } as types.HttpResponse;\n            return response;\n          });\n        }) as Promise<types.CancelTuningJobResponse>;\n\n      return response.then((apiResponse) => {\n        const resp = converters.cancelTuningJobResponseFromVertex(apiResponse);\n        const typedResp = new types.CancelTuningJobResponse();\n        Object.assign(typedResp, resp);\n        return typedResp;\n      });\n    } else {\n      const body = converters.cancelTuningJobParametersToMldev(params, params);\n      path = common.formatMap(\n        '{name}:cancel',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'POST',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json().then((jsonResponse) => {\n            const response = jsonResponse as types.CancelTuningJobResponse;\n            response.sdkHttpResponse = {\n              headers: httpResponse.headers,\n            } as types.HttpResponse;\n            return response;\n          });\n        }) as Promise<types.CancelTuningJobResponse>;\n\n      return response.then((apiResponse) => {\n        const resp = converters.cancelTuningJobResponseFromMldev(apiResponse);\n        const typedResp = new types.CancelTuningJobResponse();\n        Object.assign(typedResp, resp);\n        return typedResp;\n      });\n    }\n  }\n\n  private async tuneInternal(\n    params: types.CreateTuningJobParametersPrivate,\n  ): Promise<types.TuningJob> {\n    let response: Promise<types.TuningJob>;\n\n    let path: string = '';\n    let queryParams: Record<string, string> = {};\n    if (this.apiClient.isVertexAI()) {\n      const body = converters.createTuningJobParametersPrivateToVertex(\n        params,\n        params,\n      );\n      path = common.formatMap(\n        'tuningJobs',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'POST',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json().then((jsonResponse) => {\n            const response = jsonResponse as types.TuningJob;\n            response.sdkHttpResponse = {\n              headers: httpResponse.headers,\n            } as types.HttpResponse;\n            return response;\n          });\n        }) as Promise<types.TuningJob>;\n\n      return response.then((apiResponse) => {\n        const resp = converters.tuningJobFromVertex(apiResponse);\n\n        return resp as types.TuningJob;\n      });\n    } else {\n      throw new Error('This method is only supported by the Vertex AI.');\n    }\n  }\n\n  private async tuneMldevInternal(\n    params: types.CreateTuningJobParametersPrivate,\n  ): Promise<types.TuningOperation> {\n    let response: Promise<types.TuningOperation>;\n\n    let path: string = '';\n    let queryParams: Record<string, string> = {};\n    if (this.apiClient.isVertexAI()) {\n      throw new Error(\n        'This method is only supported by the Gemini Developer API.',\n      );\n    } else {\n      const body = converters.createTuningJobParametersPrivateToMldev(\n        params,\n        params,\n      );\n      path = common.formatMap(\n        'tunedModels',\n        body['_url'] as Record<string, unknown>,\n      );\n      queryParams = body['_query'] as Record<string, string>;\n      delete body['_url'];\n      delete body['_query'];\n\n      response = this.apiClient\n        .request({\n          path: path,\n          queryParams: queryParams,\n          body: JSON.stringify(body),\n          httpMethod: 'POST',\n          httpOptions: params.config?.httpOptions,\n          abortSignal: params.config?.abortSignal,\n        })\n        .then((httpResponse) => {\n          return httpResponse.json().then((jsonResponse) => {\n            const response = jsonResponse as types.TuningOperation;\n            response.sdkHttpResponse = {\n              headers: httpResponse.headers,\n            } as types.HttpResponse;\n            return response;\n          });\n        }) as Promise<types.TuningOperation>;\n\n      return response.then((apiResponse) => {\n        const resp = converters.tuningOperationFromMldev(apiResponse);\n\n        return resp as types.TuningOperation;\n      });\n    }\n  }\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {ApiClient} from '../_api_client.js';\nimport {Downloader} from '../_downloader.js';\nimport {DownloadFileParameters} from '../types.js';\n\nexport class BrowserDownloader implements Downloader {\n  async download(\n    _params: DownloadFileParameters,\n    _apiClient: ApiClient,\n  ): Promise<void> {\n    throw new Error(\n      'Download to file is not supported in the browser, please use a browser compliant download like an <a> tag.',\n    );\n  }\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {ApiClient} from '../_api_client.js';\nimport {FileStat, Uploader} from '../_uploader.js';\nimport * as _converters from '../converters/_operations_converters.js';\nimport {\n  File,\n  HttpResponse,\n  UploadToFileSearchStoreOperation,\n} from '../types.js';\nimport {crossError} from './_cross_error.js';\n\nexport const MAX_CHUNK_SIZE = 1024 * 1024 * 8; // bytes\nexport const MAX_RETRY_COUNT = 3;\nexport const INITIAL_RETRY_DELAY_MS = 1000;\nexport const DELAY_MULTIPLIER = 2;\nexport const X_GOOG_UPLOAD_STATUS_HEADER_FIELD = 'x-goog-upload-status';\n\nexport class CrossUploader implements Uploader {\n  async upload(\n    file: string | Blob,\n    uploadUrl: string,\n    apiClient: ApiClient,\n  ): Promise<File> {\n    if (typeof file === 'string') {\n      throw crossError();\n    } else {\n      return uploadBlob(file, uploadUrl, apiClient);\n    }\n  }\n\n  async uploadToFileSearchStore(\n    file: string | Blob,\n    uploadUrl: string,\n    apiClient: ApiClient,\n  ): Promise<UploadToFileSearchStoreOperation> {\n    if (typeof file === 'string') {\n      throw crossError();\n    } else {\n      return uploadBlobToFileSearchStore(file, uploadUrl, apiClient);\n    }\n  }\n\n  async stat(file: string | Blob): Promise<FileStat> {\n    if (typeof file === 'string') {\n      throw crossError();\n    } else {\n      return getBlobStat(file);\n    }\n  }\n}\n\nexport async function uploadBlob(\n  file: Blob,\n  uploadUrl: string,\n  apiClient: ApiClient,\n): Promise<File> {\n  const response = await uploadBlobInternal(file, uploadUrl, apiClient);\n  const responseJson = (await response?.json()) as Record<\n    string,\n    File | unknown\n  >;\n  if (response?.headers?.[X_GOOG_UPLOAD_STATUS_HEADER_FIELD] !== 'final') {\n    throw new Error('Failed to upload file: Upload status is not finalized.');\n  }\n  return responseJson['file'] as File;\n}\n\nexport async function uploadBlobToFileSearchStore(\n  file: Blob,\n  uploadUrl: string,\n  apiClient: ApiClient,\n): Promise<UploadToFileSearchStoreOperation> {\n  const response = await uploadBlobInternal(file, uploadUrl, apiClient);\n  const responseJson =\n    (await response?.json()) as UploadToFileSearchStoreOperation;\n  if (response?.headers?.[X_GOOG_UPLOAD_STATUS_HEADER_FIELD] !== 'final') {\n    throw new Error('Failed to upload file: Upload status is not finalized.');\n  }\n  const resp =\n    _converters.uploadToFileSearchStoreOperationFromMldev(responseJson);\n  const typedResp = new UploadToFileSearchStoreOperation();\n  Object.assign(typedResp, resp);\n  return typedResp;\n}\n\nasync function uploadBlobInternal(\n  file: Blob,\n  uploadUrl: string,\n  apiClient: ApiClient,\n): Promise<HttpResponse> {\n  let fileSize = 0;\n  let offset = 0;\n  let response: HttpResponse = new HttpResponse(new Response());\n  let uploadCommand = 'upload';\n  fileSize = file.size;\n  while (offset < fileSize) {\n    const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset);\n    const chunk = file.slice(offset, offset + chunkSize);\n    if (offset + chunkSize >= fileSize) {\n      uploadCommand += ', finalize';\n    }\n    let retryCount = 0;\n    let currentDelayMs = INITIAL_RETRY_DELAY_MS;\n    while (retryCount < MAX_RETRY_COUNT) {\n      response = await apiClient.request({\n        path: '',\n        body: chunk,\n        httpMethod: 'POST',\n        httpOptions: {\n          apiVersion: '',\n          baseUrl: uploadUrl,\n          headers: {\n            'X-Goog-Upload-Command': uploadCommand,\n            'X-Goog-Upload-Offset': String(offset),\n            'Content-Length': String(chunkSize),\n          },\n        },\n      });\n      if (response?.headers?.[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) {\n        break;\n      }\n      retryCount++;\n      await sleep(currentDelayMs);\n      currentDelayMs = currentDelayMs * DELAY_MULTIPLIER;\n    }\n    offset += chunkSize;\n    // The `x-goog-upload-status` header field can be `active`, `final` and\n    //`cancelled` in resposne.\n    if (response?.headers?.[X_GOOG_UPLOAD_STATUS_HEADER_FIELD] !== 'active') {\n      break;\n    }\n    // TODO(b/401391430) Investigate why the upload status is not finalized\n    // even though all content has been uploaded.\n    if (fileSize <= offset) {\n      throw new Error(\n        'All content has been uploaded, but the upload status is not finalized.',\n      );\n    }\n  }\n\n  return response;\n}\n\nexport async function getBlobStat(file: Blob): Promise<FileStat> {\n  const fileStat: FileStat = {size: file.size, type: file.type};\n  return fileStat;\n}\n\nexport function sleep(ms: number): Promise<void> {\n  return new Promise((resolvePromise) => setTimeout(resolvePromise, ms));\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {ApiClient} from '../_api_client.js';\nimport {FileStat, Uploader} from '../_uploader.js';\nimport {\n  getBlobStat,\n  uploadBlob,\n  uploadBlobToFileSearchStore,\n} from '../cross/_cross_uploader.js';\nimport {File, UploadToFileSearchStoreOperation} from '../types.js';\n\nexport class BrowserUploader implements Uploader {\n  async upload(\n    file: string | Blob,\n    uploadUrl: string,\n    apiClient: ApiClient,\n  ): Promise<File> {\n    if (typeof file === 'string') {\n      throw new Error('File path is not supported in browser uploader.');\n    }\n\n    return await uploadBlob(file, uploadUrl, apiClient);\n  }\n\n  async uploadToFileSearchStore(\n    file: string | Blob,\n    uploadUrl: string,\n    apiClient: ApiClient,\n  ): Promise<UploadToFileSearchStoreOperation> {\n    if (typeof file === 'string') {\n      throw new Error('File path is not supported in browser uploader.');\n    }\n\n    return await uploadBlobToFileSearchStore(file, uploadUrl, apiClient);\n  }\n\n  async stat(file: string | Blob): Promise<FileStat> {\n    if (typeof file === 'string') {\n      throw new Error('File path is not supported in browser uploader.');\n    } else {\n      return await getBlobStat(file);\n    }\n  }\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {\n  WebSocketCallbacks,\n  WebSocketFactory,\n  WebSocket as Ws,\n} from '../_websocket.js';\n\nexport class BrowserWebSocketFactory implements WebSocketFactory {\n  create(\n    url: string,\n    headers: Record<string, string>,\n    callbacks: WebSocketCallbacks,\n  ): Ws {\n    return new BrowserWebSocket(url, headers, callbacks);\n  }\n}\n\nexport class BrowserWebSocket implements Ws {\n  private ws?: WebSocket;\n\n  constructor(\n    private readonly url: string,\n    private readonly headers: Record<string, string>,\n    private readonly callbacks: WebSocketCallbacks,\n  ) {}\n\n  connect(): void {\n    this.ws = new WebSocket(this.url);\n\n    this.ws.onopen = this.callbacks.onopen;\n    this.ws.onerror = this.callbacks.onerror;\n    this.ws.onclose = this.callbacks.onclose;\n    this.ws.onmessage = this.callbacks.onmessage;\n  }\n\n  send(message: string) {\n    if (this.ws === undefined) {\n      throw new Error('WebSocket is not connected');\n    }\n\n    this.ws.send(message);\n  }\n\n  close() {\n    if (this.ws === undefined) {\n      throw new Error('WebSocket is not connected');\n    }\n\n    this.ws.close();\n  }\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {Auth} from '../_auth.js';\n\nexport const GOOGLE_API_KEY_HEADER = 'x-goog-api-key';\n// TODO(b/395122533): We need a secure client side authentication mechanism.\nexport class WebAuth implements Auth {\n  constructor(private readonly apiKey: string) {}\n\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  async addAuthHeaders(headers: Headers, url?: string): Promise<void> {\n    if (headers.get(GOOGLE_API_KEY_HEADER) !== null) {\n      return;\n    }\n\n    if (this.apiKey.startsWith('auth_tokens/')) {\n      throw new Error('Ephemeral tokens are only supported by the live API.');\n    }\n\n    // Check if API key is empty or null\n    if (!this.apiKey) {\n      throw new Error('API key is missing. Please provide a valid API key.');\n    }\n    headers.append(GOOGLE_API_KEY_HEADER, this.apiKey);\n  }\n}\n", "/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {ApiClient} from '../_api_client.js';\nimport {getBaseUrl} from '../_base_url.js';\nimport {Batches} from '../batches.js';\nimport {Caches} from '../caches.js';\nimport {Chats} from '../chats.js';\nimport {GoogleGenAIOptions} from '../client.js';\nimport {Files} from '../files.js';\nimport {FileSearchStores} from '../filesearchstores.js';\nimport GeminiNextGenAPI from '../interactions/index.js';\nimport {Interactions as GeminiNextGenInteractions} from '../interactions/resources/interactions.js';\nimport {Live} from '../live.js';\nimport {Models} from '../models.js';\nimport {Operations} from '../operations.js';\nimport {Tokens} from '../tokens.js';\nimport {Tunings} from '../tunings.js';\nimport {HttpOptions} from '../types.js';\n\nimport {BrowserDownloader} from './_browser_downloader.js';\nimport {BrowserUploader} from './_browser_uploader.js';\nimport {BrowserWebSocketFactory} from './_browser_websocket.js';\nimport {WebAuth} from './_web_auth.js';\n\nconst LANGUAGE_LABEL_PREFIX = 'gl-node/';\n\n/**\n * The Google GenAI SDK.\n *\n * @remarks\n * Provides access to the GenAI features through either the {@link\n * https://cloud.google.com/vertex-ai/docs/reference/rest | Gemini API} or\n * the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI\n * API}.\n *\n * The {@link GoogleGenAIOptions.vertexai} value determines which of the API\n * services to use.\n *\n * When using the Gemini API, a {@link GoogleGenAIOptions.apiKey} must also be\n * set. When using Vertex AI, currently only {@link GoogleGenAIOptions.apiKey}\n * is supported via Express mode. {@link GoogleGenAIOptions.project} and {@link\n * GoogleGenAIOptions.location} should not be set.\n *\n * @example\n * Initializing the SDK for using the Gemini API:\n * ```ts\n * import {GoogleGenAI} from '@google/genai';\n * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'});\n * ```\n *\n * @example\n * Initializing the SDK for using the Vertex AI API:\n * ```ts\n * import {GoogleGenAI} from '@google/genai';\n * const ai = new GoogleGenAI({\n *   vertexai: true,\n *   project: 'PROJECT_ID',\n *   location: 'PROJECT_LOCATION'\n * });\n * ```\n *\n */\nexport class GoogleGenAI {\n  protected readonly apiClient: ApiClient;\n  private readonly apiKey?: string;\n  public readonly vertexai: boolean;\n  private readonly apiVersion?: string;\n  private readonly httpOptions?: HttpOptions;\n  readonly models: Models;\n  readonly live: Live;\n  readonly batches: Batches;\n  readonly chats: Chats;\n  readonly caches: Caches;\n  readonly files: Files;\n  readonly operations: Operations;\n  readonly authTokens: Tokens;\n  readonly tunings: Tunings;\n  readonly fileSearchStores: FileSearchStores;\n  private _interactions: GeminiNextGenInteractions | undefined;\n  get interactions(): GeminiNextGenInteractions {\n    if (this._interactions !== undefined) {\n      return this._interactions;\n    }\n\n    console.warn(\n      'GoogleGenAI.interactions: Interactions usage is experimental and may change in future versions.',\n    );\n\n    if (this.vertexai) {\n      throw new Error(\n        'This version of the GenAI SDK does not support Vertex AI API for interactions.',\n      );\n    }\n\n    const httpOpts = this.httpOptions;\n\n    // Unsupported Options Warnings\n    if (httpOpts?.extraBody) {\n      console.warn(\n        'GoogleGenAI.interactions: Client level httpOptions.extraBody is not supported by the interactions client and will be ignored.',\n      );\n    }\n\n    const nextGenClient = new GeminiNextGenAPI({\n      baseURL: this.apiClient.getBaseUrl(),\n      apiKey: this.apiKey,\n      defaultHeaders: this.apiClient.getDefaultHeaders(),\n      timeout: httpOpts?.timeout,\n    });\n    this._interactions = nextGenClient.interactions;\n\n    return this._interactions;\n  }\n  constructor(options: GoogleGenAIOptions) {\n    if (options.apiKey == null) {\n      throw new Error('An API Key must be set when running in a browser');\n    }\n    // Web client only supports API key mode for Vertex AI.\n    if (options.project || options.location) {\n      throw new Error(\n        'Vertex AI project based authentication is not supported on browser runtimes. Please do not provide a project or location.',\n      );\n    }\n    this.vertexai = options.vertexai ?? false;\n\n    this.apiKey = options.apiKey;\n\n    const baseUrl = getBaseUrl(\n      options.httpOptions,\n      options.vertexai,\n      /*vertexBaseUrlFromEnv*/ undefined,\n      /*geminiBaseUrlFromEnv*/ undefined,\n    );\n    if (baseUrl) {\n      if (options.httpOptions) {\n        options.httpOptions.baseUrl = baseUrl;\n      } else {\n        options.httpOptions = {baseUrl: baseUrl};\n      }\n    }\n\n    this.apiVersion = options.apiVersion;\n    this.httpOptions = options.httpOptions;\n    const auth = new WebAuth(this.apiKey);\n    this.apiClient = new ApiClient({\n      auth: auth,\n      apiVersion: this.apiVersion,\n      apiKey: this.apiKey,\n      vertexai: this.vertexai,\n      httpOptions: this.httpOptions,\n      userAgentExtra: LANGUAGE_LABEL_PREFIX + 'web',\n      uploader: new BrowserUploader(),\n      downloader: new BrowserDownloader(),\n    });\n    this.models = new Models(this.apiClient);\n    this.live = new Live(this.apiClient, auth, new BrowserWebSocketFactory());\n    this.batches = new Batches(this.apiClient);\n    this.chats = new Chats(this.models, this.apiClient);\n    this.caches = new Caches(this.apiClient);\n    this.files = new Files(this.apiClient);\n    this.operations = new Operations(this.apiClient);\n    this.authTokens = new Tokens(this.apiClient);\n    this.tunings = new Tunings(this.apiClient);\n    this.fileSearchStores = new FileSearchStores(this.apiClient);\n  }\n}\n", "/**\n * @module gemini-helpers.mts\n *\n * ## MIGRATION to @google/genai\n *\n * See migration notes in agent-witness-gemini.mts.\n */\nimport { FunctionCallPart, FunctionResponsePart, } from \"./gemini-types.mjs\";\nimport { Content, FunctionCall, FunctionResponse, } from \"@google/genai\";\n\nimport { extractErrorMsg, pretty } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { IbGib_V1 } from \"@ibgib/ts-gib/dist/V1/types.mjs\";\nimport { isComment, } from \"@ibgib/core-gib/dist/common/comment/comment-helper.mjs\";\n\nimport { GLOBAL_LOG_A_LOT } from '../../../constants.mjs';\nimport { getAllFunctionInfos } from \"../../../api/api-index.mjs\";\nimport { APIFunctionInfo } from \"../../../api/api-types.mjs\";\nimport { PromptInfo, } from \"../agent-types.mjs\";\nimport { FUNCTION_CALL_REQUEST_COMMENT_TAG, TextSource, } from \"../agent-constants.mjs\";\nimport { FunctionResponsePart_ResponseWrapper, PromptInfoEntryGemini, PromptInfoGemini } from \"./gemini-types.mjs\";\nimport { FunctionInfoIbGib_V1 } from \"../function-info/function-info-one-file.mjs\";\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\nexport function textSourceToGeminiRole(src: TextSource): string {\n    switch (src) {\n        case TextSource.HUMAN:\n            return 'user';\n        case TextSource.AI:\n            return 'model';\n        case TextSource.FUNCTION:\n            // return 'function';\n            return 'user';\n        case TextSource.HARDCODED:\n            return 'user';\n        case TextSource.UNKNOWN:\n            return 'user';\n        default:\n            throw new Error(`(UNEXPECTED) src is not a valid TextSource? src: ${src} (E: 9d954fe0bc49cf4572a65b19b6173925)`);\n    }\n}\n// export function geminiRoleToTextSource(geminiRole: 'user' | 'model' | ''): TextSource {\n//     if (geminiRole === 'user') {\n//         return TextSource.HUMAN;\n//     } else if (geminiRole === 'model') {\n//         return TextSource.AI;\n//     } else {\n//         return TextSource.UNKNOWN;\n//     }\n// }\n\nexport function isPromptInfoGemini(info: PromptInfo): info is PromptInfoGemini {\n    return info.api === 'gemini';\n}\n\n/**\n * gemini api-specific helper that maps gemini function call returned from the\n * model to our API function info interface\n */\nexport function geminiFunctionCallToAPIFunctionInfo({\n    functionCall,\n}: {\n    functionCall: FunctionCall\n}): { info: APIFunctionInfo, args: any } {\n    const lc = `[${geminiFunctionCallToAPIFunctionInfo.name}]`;\n    if (!functionCall.name) { throw new Error(`(UNEXPECTED) functionCall.name is falsy? (E: b2c638cf22f88493d823e7e9915fd625)`); }\n    const functionInfo = getAllFunctionInfos().get(functionCall.name);\n    if (!functionInfo) {\n        throw new Error(`${lc} no APIFunctionInfo found matching name: ${functionCall.name} (E: 7c5c7c17988a666a86e72299630c7f25)`);\n    }\n    return {\n        info: functionInfo,\n        args: functionCall.args ?? undefined,\n    };\n}\n\n/**\n * Takes 0 or more entries and combines them into a single {@link Content}\n * object that Gemini API expects for `systemInstruction` when using the fn\n *\n * @param entries for system instruction, probably from {@link AgentWitnessGemini_V1.systemPromptParts}\n * @returns undefined if no entries, else single Gemini API Content object with role === \"user\" and combined parts from {@link systemPromptEntries}\n */\nexport function systemPromptEntriesToSystemInstructionContent({\n    systemPromptEntries,\n}: {\n    systemPromptEntries: PromptInfoEntryGemini[],\n}): Content | undefined {\n    const lc = `[${systemPromptEntriesToSystemInstructionContent.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 18693a97427939699285ef8c1a9cc425)`); }\n\n        if (systemPromptEntries.length === 0) { return undefined; /* <<<< returns early */ }\n        if (!systemPromptEntries.every(entry => entry.src === TextSource.HUMAN)) {\n            if (logalot) { console.warn(`${lc} not every system entry's src is human. We're still going to say that these are \"user\" origin in Gemini API. (W: 7115e2be876498ecb1e153c79a86e125)`); }\n        }\n        const sysInstructionContent: Content = {\n            role: \"user\",\n            parts:\n                systemPromptEntries\n                    .filter(entry => !!entry.content.parts)\n                    .flatMap(entry => entry.content.parts!),\n        };\n        if (logalot) { console.log(`${lc} sysInstructionContent: ${pretty(sysInstructionContent)} (I: 011e5b865c23eb0b640df3f464ac2525)`); }\n        return sysInstructionContent;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * helper function (not a guard) that determines if the given ibgib has the\n * expected shape of a Function Call Request comment (FCR).\n *\n * These objects are created when a model requests a function call.\n *\n * ATOW (01/2025) these FCRs should include both one or more infos for both\n * function calls and function responses.\n */\nexport function isFunctionCallRequestComment({ ibGib }: { ibGib: IbGib_V1 }): boolean {\n    const lc = `[${isFunctionCallRequestComment.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 986d3edcd4f3aaf1d7eb0f8b59206b25)`); }\n\n        if (!ibGib) {\n            if (logalot) { console.warn(`${lc} ibGib falsy. (W: a70390e8bc3f420a92d3a84f4c78f12a)`); }\n            return false; /* <<<< returns early */\n        }\n        if (!isComment({ ibGib })) {\n            if (logalot) { console.log(`${lc} not a comment ibgib (I: 6a62c4f6e13776616855c4f237a5206b)`); }\n            return false; /* <<<< returns early */\n        }\n        if (!ibGib.data) {\n            if (logalot) { console.log(`${lc} ibGib.data falsy (I: 69eb86975640475395bb74944141a46d)`); }\n            return false; /* <<<< returns early */\n        }\n\n        const { text } = ibGib.data;\n        if (!text) {\n            if (logalot) { console.log(`${lc} text falsy (I: e348e38c841b4443b3f09e75c0215b24)`); }\n            return false; /* <<<< returns early */\n        }\n\n        if (text.includes(FUNCTION_CALL_REQUEST_COMMENT_TAG)) {\n            if (logalot) { console.log(`${lc} has tag. returning true. (I: 6d76b27d558d44f696582f41af561f29)`); }\n            return true;\n        }\n        // let { safeIbCommentMetadataText } = parseCommentIb({ ib: ibGib.ib });\n        // if (safeIbCommentMetadataText && safeIbCommentMetadataText.includes(FUNCTION_INFO_ATOM)) {\n        //  return true;\n        // }\n\n        if (logalot) { console.log(`${lc} no indicator found. returning false. (I: 815f181a0a08058362f76b08a8964674)`); }\n\n        return false;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n\n/**\n * Helper function to create Gemini API FunctionCallPart and FunctionResponsePart\n * objects from a FunctionInfoIbGib_V1.\n *\n * @param {object} arg - Arguments object.\n * @param {FunctionInfoIbGib_V1} arg.functionInfoIbGib - The FunctionInfoIbGib_V1 instance containing function call details.\n * @returns {{ call: Part; response: Part }} - An object containing both FunctionCallPart and FunctionResponsePart objects.\n * @throws {Error} If there's an error during the process, such as missing function name or arguments.\n */\nexport function getFunctionCallAndResponseParts({\n    functionInfoIbGib,\n}: {\n    functionInfoIbGib: FunctionInfoIbGib_V1,\n}): { call: FunctionCallPart, response: FunctionResponsePart } {\n    const lc = `[${getFunctionCallAndResponseParts.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 1a2b3c4d5e6f7a8b)`); }\n\n        if (!functionInfoIbGib) {\n            throw new Error(`${lc} functionInfoIbGib parameter is required. (E: 9c8f7a3b2d1e4a5b6c7d8e9f)`);\n        }\n        if (!functionInfoIbGib.data) {\n            throw new Error(`${lc} functionInfoIbGib.data is required. (E: 2b3c4d5e6f7a8b1c2d3e4f5a)`);\n        }\n\n        const { fnName, fnArgs, fnResult } = functionInfoIbGib.data;\n\n        if (!fnName) {\n            throw new Error(`${lc} functionInfoIbGib.data.fnName is required. (E: 6f7a8b1c2d3e4f5a6b7c8d9e)`);\n        }\n\n        // 1. Create FunctionCallPart\n        const functionCallPart: FunctionCallPart = {\n            functionCall: {\n                name: fnName,\n                args: fnArgs ?? {}, // Use empty object if fnArgs is not provided\n            } as FunctionCall,\n        } satisfies FunctionCallPart;\n\n\n        // 2. Create FunctionResponsePart\n        const responseWrapper: FunctionResponsePart_ResponseWrapper = {\n            value: fnResult,\n        };\n        const functionResponsePart: FunctionResponsePart = {\n            functionResponse: {\n                name: fnName,\n                response: responseWrapper, // Use empty object if fnResult is not provided\n            } as FunctionResponse,\n        } satisfies FunctionResponsePart;\n\n        return { call: functionCallPart, response: functionResponsePart };\n\n    } catch (error) {\n        console.error(`${lc} Error: ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n", "import {\n    extractErrorMsg, getTimestamp, getTimestampInTicks,\n} from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';\nimport { UUID_REGEXP } from '@ibgib/helper-gib/dist/constants.mjs';\nimport { Ib, TransformResult } from '@ibgib/ts-gib/dist/types.mjs';\nimport { IbGibData_V1, IbGibRel8ns_V1, IbGib_V1 } from '@ibgib/ts-gib/dist/V1/types.mjs';\nimport { Factory_V1 } from '@ibgib/ts-gib/dist/V1/factory.mjs';\nimport { getIbGibAddr } from '@ibgib/ts-gib/dist/helper.mjs';\nimport { IbGibSpaceAny } from '@ibgib/core-gib/dist/witness/space/space-base-v1.mjs';\nimport { MetaspaceService } from '@ibgib/core-gib/dist/witness/space/metaspace/metaspace-types.mjs';\nimport { getTimestampInfo } from '@ibgib/core-gib/dist/common/other/ibgib-helper.mjs';\n\nimport { GLOBAL_LOG_A_LOT } from '../../../constants.mjs';\nimport { AgentAPI } from '../agent-types.mjs';\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\n/**\n * used as a rel8nName to link a Function Call Request (FCR) comment ibgib to\n * the actual function call info ibgibs that represent each FCR.\n */\nexport const FUNCTION_INFO_REL8N_NAME = 'function_info';\n\nexport const FUNCTION_INFO_ATOM = 'function_info';\n\n/**\n * @interface FunctionInfoIbInfo - Type for parsed function info ib.\n * Used by parseFunctionInfoIb\n */\nexport interface FunctionInfoIbInfo {\n    atom: string;\n    timestampInTicks: string;\n    model: string;\n    api: AgentAPI;\n    agentId: string;\n}\n\n/**\n * builds the function info ibgib's ib based on given {@link data}\n * @see {@link parseFunctionInfoIb}\n */\nexport function getFunctionInfoIb({\n    data,\n}: {\n    /** function info data, should be valid */\n    data: FunctionInfoData_V1,\n}): string {\n    const lc = `[${getFunctionInfoIb.name}]`;\n    const { model, api, agentId, timestamp, } = data;\n    if (!model) { throw new Error(`${lc} data.model falsy (E: 6f47a28c0a8a45d794149c83e8f27e25)`); }\n    if (!api) { throw new Error(`${lc} data.api falsy (E: a0a812508a952a87c619d38084b7e325)`); }\n    if (!agentId) { throw new Error(`${lc} data.agentId falsy (E: ac35c1592c458e2c0e5908f6a9a3e525)`); }\n    const timestampInTicks = getTimestampInTicks(timestamp);\n    const fields: string[] = [model, api, agentId, timestampInTicks];\n    if (fields.some(x => x.includes(' '))) { throw new Error(`invalid data. ib must not contain spaces (E: 36a56e4685163848458be06f51d4ad25)`); }\n\n    return [\n        FUNCTION_INFO_ATOM,\n        timestampInTicks,\n        model,\n        api,\n        agentId,\n    ].join(' ');\n}\n\n/**\n * @returns parsed info from an ib\n * @see {@link getFunctionInfoIb}\n */\nexport function parseFunctionInfoIb({\n    ib,\n}: {\n    ib: Ib,\n}): FunctionInfoIbInfo {\n    const lc = `[${parseFunctionInfoIb.name}]`;\n    /** getFunctionInfoIb must match parseFunctionInfoIb. If this array changes, change the other one. */\n    const [\n        atom,\n        timestampInTicks,\n        model,\n        api,\n        agentId,\n    ] = ib.split(' ');\n    if (atom !== FUNCTION_INFO_ATOM) { throw new Error(`invalid ib. first term expected to e an atom: ${FUNCTION_INFO_ATOM} (E: 3c01d42035d2e32c4bfd5c1bf363f725)`); }\n\n    return { atom, timestampInTicks, model, api: api as AgentAPI, agentId };\n}\n\n/**\n * Validates a `FunctionInfoIb` and returns a list of any errors.\n *\n * @param {object} arg - Options for validating the `ib`.\n * @param {string} arg.ib - `ib` to validate.\n * @returns {string[]} - list of validation errors or an empty array if valid.\n */\nexport function validateFunctionInfoIb({\n    ib,\n}: {\n    ib: Ib,\n}): string[] {\n    const lc = `[${validateFunctionInfoIb.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting...`); }\n\n        const errors: string[] = [];\n        let parsed: FunctionInfoIbInfo;\n\n        try {\n            parsed = parseFunctionInfoIb({ ib });\n        } catch (error: any) {\n            errors.push(`${lc} error parsing ib: ${extractErrorMsg(error)} (E: a1c09537f9f6485427c30b74d27c9a25)`);\n            return errors; /* <<<< returns early if parsing fails */\n        }\n\n        const {\n            atom,\n            timestampInTicks,\n            model,\n            api,\n            agentId,\n        } = parsed;\n\n        if (atom !== FUNCTION_INFO_ATOM) {\n            errors.push(`${lc} invalid ib. atom is expected to be FUNCTION_INFO_ATOM: ${FUNCTION_INFO_ATOM} (E: a9812bffc18f44418aa091fb0ed260bd)`)\n        }\n\n        // timestampInTicks\n        if (timestampInTicks === 'undefined') {\n            // this happens when it's a binary ibgib or just doesn't have a timestamp in the data map\n            errors.push(`invalid ib. timestampInTicks is falsy (E: 0985656eb2084046a43845a8f9d47d25)`)\n        } else {\n            const timestampInfo = getTimestampInfo({ timestamp: timestampInTicks });\n            if (!timestampInfo.valid) {\n                errors.push(`invalid ib. pieces[3] should be valid timestampInTicks. emsg: (${timestampInfo.emsg}) (E: 06dae01d66f54f54b71d9c920c730840)`);\n            }\n        }\n        if (!model) {\n            errors.push(`invalid ib. model is falsy (E: 654678f3a1e86f0c9811b8a3749d4e25)`);\n        }\n        if (!api) {\n            errors.push(`invalid ib. api is falsy (E: a20c879391850c9396e13f27e8469025)`);\n        }\n\n        if (agentId) {\n            if (!agentId.match(UUID_REGEXP)) {\n                errors.push(`invalid ib. agentId does not match expected UUID_REGEXP: ${UUID_REGEXP} (E: 3e7a70c28190777178693150563d6725)`)\n            }\n        } else {\n            errors.push(`invalid ib. agentId is falsy (E: 9b5c4d2f74698557e2c1173947e35e25)`);\n        }\n\n        return errors;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * Information required when creating an info ibgib.\n *\n * ATOW (01/2025) Note that this does NOT save the ibgib in any spaces.\n */\nexport interface CreateFunctionInfoIbGibArgs {\n    /**\n     * raw string of the function call requested by the model.\n     */\n    fnRawRequest: string;\n    /**\n     * which api (e.g. 'gemini') was used when generating the function call\n     * request.\n     * @see {@link model}\n     * @see {@link FunctionInfoData_V1.api}\n     */\n    api: AgentAPI;\n    /**\n     * model that generated the request\n     * @see {@link api}\n     * @see {@link FunctionInfoData_V1.model}\n     */\n    model: string;\n    /**\n     * id of the agent that this will be associated with\n     */\n    agentId: string;\n    /**\n     * name of the function.\n     *\n     * in gemini, this should be provided easily and we shouldn't need a regex for it.\n     */\n    fnName: string;\n    /**\n     * parsed args from the raw request string\n     */\n    fnArgs: any;\n    /**\n     * the result of a successful functionImpl, otherwise undefined.\n     * @see {@link FunctionInfoData_V1.fnResult}\n     */\n    fnResult?: any;\n    /**\n     * flag that indicates if the function completed successfully.\n     * @see {@link FunctionInfoData_V1.fnComplete}\n     */\n    fnComplete?: boolean;\n    /**\n     * This is the error msg if there was an error actually parsing the raw\n     * function info.\n     * @see {@link execErrorMsg}\n     */\n    parseErrorMsg?: string;\n    /**\n     * This is the error msg if there was an error actually executing the\n     * function.\n     * @see {@link parseErrorMsg}\n     */\n    execErrorMsg?: string;\n    /**\n     * corresponds to whether or not the model wanted to be notified upon function completion/error.\n     * @see {@link FunctionInfoData_V1.repromptWithResult}\n     */\n    repromptWithResult?: boolean;\n    /**\n     * should we save the newly created ibgib and its dependency graph?\n     * @see {@link metaspace}\n     */\n    saveInSpace?: boolean;\n    /**\n     * if {@link saveInSpace}, this is the required metaspace to handle saving.\n     * @see {@link space}\n     */\n    metaspace?: MetaspaceService;\n    /**\n     * if {@link saveInSpace}, this is the required space in which to save.\n     * @see {@link metaspace}\n     */\n    space?: IbGibSpaceAny;\n}\n\n/**\n * Creates a new FunctionInfoIbGib_V1 object.\n *\n * @param {object} arg - Arguments for creating the new ibgib\n * @returns {Promise<FunctionInfoIbGib_V1>} A promise that resolves to the new FunctionInfoIbGib_V1 object.\n * @throws {Error} If there is an error during ibgib creation.\n */\nexport async function createFunctionInfoIbGib(arg: CreateFunctionInfoIbGibArgs): Promise<TransformResult<FunctionInfoIbGib_V1>> {\n    const lc = `[${createFunctionInfoIbGib.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: f4c9f0810a4d877f676297f6e6a96825)`); }\n        let {\n            fnRawRequest, api, model, agentId,\n            fnName, fnArgs,\n            fnResult, fnComplete,\n            parseErrorMsg, execErrorMsg,\n            repromptWithResult,\n            saveInSpace, metaspace, space,\n        } = arg;\n\n        const date = new Date();\n        const data: FunctionInfoData_V1 = {\n            name: model,\n            timestamp: getTimestamp(date),\n            timestampMs: date.getMilliseconds(),\n            agentId,\n            api, model,\n            fnRawRequest,\n            fnName, fnArgs,\n            fnResult, fnComplete,\n            repromptWithResult,\n        };\n        if (parseErrorMsg) { data.parseErrorMsg = parseErrorMsg };\n        if (execErrorMsg) { data.execErrorMsg = execErrorMsg };\n        const ib = getFunctionInfoIb({ data });\n\n        const resFunctionInfo = await Factory_V1.firstGen({\n            ib,\n            parentIbGib: Factory_V1.primitive({ ib: FUNCTION_INFO_ATOM }),\n            data,\n            nCounter: true, dna: true,\n            tjp: { uuid: true, }, // no timestamp because we're doing that manually\n        }) as TransformResult<FunctionInfoIbGib_V1>;\n        if (logalot) { console.log(`${lc} created functionInfoIbGib (I: e50d2e17f43312d4f4739899306bb725)`); }\n\n        if (saveInSpace) {\n            if (!metaspace) { throw new Error(`${lc} metaspace must be provided if saveInSpace is set to true (E: e74b76b00124d5874a6c5404e794b725)`); }\n            if (!space) { throw new Error(`${lc} space must be provided if saveInSpace is set to true (E: f3d5f1695a52707114117f72d932a025)`); }\n            await metaspace.persistTransformResult({ resTransform: resFunctionInfo, space });\n            if (logalot) { console.log(`${lc} persisted resFunctionInfo (${getIbGibAddr({ ibGib: resFunctionInfo.newIbGib })}) to space ${space.data?.uuid} (I: aa98e877d3b34e0d2a3b7711f8f27e25)`); }\n            await metaspace.registerNewIbGib({ ibGib: resFunctionInfo.newIbGib, space });\n            if (logalot) { console.log(`${lc} registered new function info ibgib (${getIbGibAddr({ ibGib: resFunctionInfo.newIbGib })}) with metaspace (I: aa98e877d3b34e0d2a3b7711f8f27e25)`); }\n        }\n\n        return resFunctionInfo;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * @interface FunctionInfoData_V1\n * Data interface for a function call.\n */\nexport interface FunctionInfoData_V1 extends IbGibData_V1 {\n    /**\n     * which model generated this function request.\n     */\n    model: string;\n    /**\n     * Which api was used to generate this function request.\n     */\n    api: AgentAPI;\n    /**\n     *  This is the raw JSON string that was returned from the LLM function call\n     */\n    fnRawRequest: string;\n    /**\n     * name of the function.\n     *\n     * in gemini, this should be provided easily and we shouldn't need a regex for it.\n     */\n    fnName: string;\n    /**\n     * parsed args from the raw request string\n     */\n    fnArgs: any;\n    /**\n     * The results of the called function. If the function implementation called\n     * returns void/Promise<void> then this should remain undefined.\n     */\n    fnResult?: any;\n    /**\n     * Was the functionImpl completed without issue? If it returned void, this\n     * should be set to true, but this may be used for other workflows in the\n     * future.\n     */\n    fnComplete?: boolean;\n    /**\n     * Is the function call request intended to have its result reprompted to the model\n     * upon function completion or error?\n     */\n    repromptWithResult?: boolean;\n}\n\n/**\n * @interface FunctionInfoRel8ns_V1 - Rel8ns interface for function info ibgibs.\n * Extends {@link IbGibRel8ns_V1}\n */\nexport interface FunctionInfoRel8ns_V1 extends IbGibRel8ns_V1 {\n}\n\n/**\n * @interface FunctionInfoIbGib_V1 - Interface for ibgibs of individual function calls.\n * Extends {@link IbGib_V1} with {@link FunctionInfoData_V1} and {@link FunctionInfoRel8ns_V1}\n */\nexport interface FunctionInfoIbGib_V1 extends IbGib_V1<FunctionInfoData_V1, FunctionInfoRel8ns_V1> {\n}\n", "import { clone, getUUID, pretty } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';\nimport { getGib, IbGib_V1, IbGibRel8ns_V1, } from '@ibgib/ts-gib/dist/V1/index.mjs';\n\nimport { GLOBAL_LOG_A_LOT } from '../core-constants.mjs';\nimport { WitnessData_V1, Witness_V1, } from './witness-types.mjs';\nimport { toDto } from '../common/other/ibgib-helper.mjs';\n\nconst logalot = GLOBAL_LOG_A_LOT || false;\n\nexport abstract class LightWitnessBase_V1<\n    TData extends WitnessData_V1 = WitnessData_V1,\n    TRel8ns extends IbGibRel8ns_V1 = IbGibRel8ns_V1\n>\n    implements Witness_V1<\n        any, any, IbGib_V1, // options arg can be any ibgib\n        any, any, IbGib_V1, // result can be any ibgib\n        TData, TRel8ns                   // this witness itself\n    > {\n\n    /**\n     * Log context for convenience with logging. (Ignore if you don't want to use this.)\n     */\n    protected lc: string = `[${LightWitnessBase_V1.name}]`;\n\n    public instanceId: string = '';\n\n    // #region IbGib interface fields: ib, gib, data, rel8ns\n\n    /**\n     * Used per use case in implementing class.\n     *\n     * This property is a simple property (no getter/setter with backing\n     * fields).  This is to simplify usage with DTOs (Data Transfer Objects) for\n     * storing in spaces.\n     */\n    ib: string = '';\n\n    /**\n     * Used per use case in implementing class.\n     *\n     * This property is a simple property (no getter/setter with backing\n     * fields).  This is to simplify usage with DTOs (Data Transfer Objects) for\n     * storing in spaces.\n     */\n    gib: string | undefined;\n\n    /**\n     * Used per use case in implementing class.\n     *\n     * This property is a simple property (no getter/setter with backing\n     * fields).  This is to simplify usage with DTOs (Data Transfer Objects) for\n     * storing in spaces.\n     */\n    data: TData | undefined;\n\n    /**\n     * Used per use case in implementing class.\n     *\n     * This property is a simple property (no getter/setter with backing\n     * fields).  This is to simplify usage with DTOs (Data Transfer Objects) for\n     * storing in spaces.\n     */\n    rel8ns: TRel8ns | undefined;\n\n    // #endregion IbGib interface fields: ib, gib, data, rel8ns\n\n    /**\n     * await this to ensure the witness is ready.\n     *\n     * This is called in the base `Witness.witness` function before `witnessImpl`.\n     */\n    initialized: Promise<void> | undefined;\n    /**\n     * synchronous and faster boolean for checking faster.\n     *\n     * so normally, do a check like...\n     *    if (!this._isInitialized) { await this.initialized; }\n     */\n    protected _isInitialized: boolean = false;\n\n    constructor(initialData?: TData, initialRel8ns?: TRel8ns) {\n        if (initialData) { this.data = initialData; }\n        if (initialRel8ns) { this.rel8ns = initialRel8ns; }\n        this.initialized = this.initialize().then(() => { this._isInitialized = true });\n    }\n\n    /**\n     * by default, simply returns true atow in base class.\n     * override this to perform code before any other code is executed.\n     */\n    protected async initialize(): Promise<void> {\n        this.instanceId = await getUUID();\n        this.gib = await getGib({ ibGib: this.toIbGibDto() });\n    }\n\n    /**\n     * Creates a data transfer object (dto) snapshot out of this\n     * witness' `ib`, `gib`, `data` and `rel8ns` properties.\n     *\n     * I say \"snapshot\" because this copies each property\n     * (`ib`, `gib`, `data`, `rel8ns`).\n     *\n     * ## thoughts\n     *\n     * Witness classes need to be able to persist their ibgib\n     * just as regular data. But witnesses have the additional\n     * layer of behavior (e.g. the `witness` function) that\n     * will not persist (until we get more integrated version control\n     * types of functionality in ibgib).\n     *\n     * @returns dto ibgib object with just clones of this.ib/gib/data/rel8ns props.\n     *\n     * @see {loadIbGibDto}\n     */\n    toIbGibDto(): IbGib_V1<TData, TRel8ns> {\n        return toDto({ ibGib: this });\n    }\n\n    /**\n     * (Re)hydrates this witness class with the ibgib information from the dto.\n     *\n     * ## notes\n     *\n     * * You can extend this function for witness-specific behavior when loading.\n     *\n     * @param dto ib, gib, data & rel8ns to load for this witness ibgib instance.\n     *\n     * @see {toIbGibDto}\n     */\n    loadIbGibDto(dto: IbGib_V1<TData, TRel8ns>): Promise<void> {\n        const lc = `${this.lc}[${this.loadIbGibDto.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting...`); }\n\n            if (!dto.ib) { console.warn(`${lc} dto.ib is falsy.`); }\n            if (!dto.gib) { console.warn(`${lc} dto.gib is falsy.`); }\n\n            this.ib = clone(dto.ib);\n            this.gib = clone(dto.gib);\n            if (dto.data) {\n                this.data = clone(dto.data);\n            } else {\n                delete this.data;\n            }\n            if (dto.rel8ns) { this.rel8ns = clone(dto.rel8ns); } else { delete this.rel8ns; }\n\n            return Promise.resolve();\n        } catch (error) {\n            console.error(`${lc} ${error.message}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * The primary function of a witness is...well... to witness things.\n     *\n     * So this is the base implementation that includes validation\n     * plumbing, tracing, error checking/catching - all depending\n     * on witness configuration.\n     *\n     *\n     * ## usage\n     *\n     * Only override this function if you really want custom handling of\n     * the plumbing.  Instead override `witnessImpl`.\n     *\n     * {@see validateThis}\n     * {@see validateWitnessArg}\n     *\n     * @param arg\n     * @returns\n     */\n    abstract witness(arg: IbGib_V1): Promise<IbGib_V1 | undefined>;\n\n    /**\n     * Validate this witness object, checking its own `data` and `rel8ns`, and\n     * possibly other state.\n     *\n     * ## notes\n     *\n     * ATOW base implementation of this just checks for non-falsy\n     * `this.ib` and `this.gib`\n     */\n    protected async validateThis(): Promise<string[]> {\n        const lc = `${this.lc}[${this.validateThis.name}]`;\n        const errors: string[] = [];\n        try {\n            if (!this.ib) { errors.push(`this.ib is falsy.`); }\n            if (!this.gib) { errors.push(`this.gib is falsy.`); }\n        } catch (error) {\n            console.error(`${lc} ${error.message}`);\n            throw error;\n        }\n        return errors;\n    }\n\n}\n\n/**\n * LightWitness with `any` types in generic.\n */\nexport type LightWitnessAny = LightWitnessBase_V1<any, any>;\n", "/**\n * Used in ErrorIbGib_V1.ib\n */\nexport const DEFAULT_ERROR_MSG_IB_SUBSTRING_LENGTH = 20;\n/**\n * regexp for an error ibgib's (ErrorIbGib_V1) ib property.\n */\nexport const ERROR_IB_REGEXP = /^error (\\w+) ([a-fA-F\\d]{32}|undefined)$/;\n", "import { Ib } from '@ibgib/ts-gib/dist/types.mjs';\nimport { IbGib_V1 } from '@ibgib/ts-gib/dist/V1/index.mjs';\n\nimport { GLOBAL_LOG_A_LOT } from '../../core-constants.mjs';\nimport { ErrorData_V1, ErrorIbGib_V1, ErrorRel8ns_V1 } from './error-types.mjs';\nimport { constantIbGib } from '../other/ibgib-helper.mjs';\nimport { DEFAULT_ERROR_MSG_IB_SUBSTRING_LENGTH, ERROR_IB_REGEXP } from './error-constants.mjs';\nimport {\n    ERROR_MSG_LOCATION_ONLY_REGEXP, ERROR_MSG_WITH_ID_CAPTURE_GROUPS_REGEXP\n} from '@ibgib/helper-gib/dist/constants.mjs';\n\n\nconst logalot = GLOBAL_LOG_A_LOT || false;\n\n/**\n * Generates an ib based on a raw error msg.\n *\n * ## future\n *\n * If this is changed in the future, then without versioning of some sort, this\n * will change the error constant ibgibs that rely on this functions\n * deterministic qualities.\n *\n * @returns the error's `ib`\n */\nexport function getErrorIb({\n    rawMsg,\n}: {\n    rawMsg: string,\n}): Ib {\n    const lc = `[${getErrorIb.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting...`); }\n        const parsed = parseRawErrorMsg({ rawMsg });\n        const saferText = parsed.body.replace(/\\s/g, '_').replace(/\\W/g, '');\n        let msgSlice: string;\n        if (saferText.length > DEFAULT_ERROR_MSG_IB_SUBSTRING_LENGTH) {\n            msgSlice =\n                saferText.substring(0, DEFAULT_ERROR_MSG_IB_SUBSTRING_LENGTH);\n        } else if (saferText.length > 0) {\n            msgSlice = saferText;\n        } else {\n            // msg only has characters/nonalphanumerics ?\n            throw new Error(`(UNEXPECTED) error msg should have characters/alphanumerics... (E: a3b9cd11a44cc7892a748819c2885422)`);\n        }\n\n        return `error ${msgSlice} ${parsed.uuid ?? 'undefined'}`;\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * Parses a raw error/exception message.\n *\n * If it has sections that I personally use (usually), then it will break that\n * out. otherwise, it will just have the `rawMsg` as the msg body and raw msg.\n *\n * @see {@link ErrorData_V1}\n */\nexport function parseRawErrorMsg({\n    rawMsg,\n}: {\n    rawMsg: string,\n}): ErrorData_V1 {\n    const lc = `[${parseRawErrorMsg.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting...`); }\n        if (!rawMsg) { throw new Error(`(UNEXPECTED) rawMsg required (E: e5bd3b433a1781ebe885534cd2495622)`); }\n\n        let data: ErrorData_V1;\n        let regexResult = rawMsg.match(ERROR_MSG_WITH_ID_CAPTURE_GROUPS_REGEXP);\n        if (regexResult) {\n            // has id section\n            const [_, location, unexpectedAtStart, body, idSection, unexpectedAtEnd] = regexResult;\n            if (!body) { throw new Error(`invalid error msg body (E: a675e6855cca96519d33d44ea5400922)`); }\n            data = {\n                success: false,\n                raw: rawMsg,\n                body: body?.trim(),\n                uuid: idSection.slice(4, 36),\n            };\n            if (location) { data.location = location; }\n            if (unexpectedAtStart || unexpectedAtEnd) { data.unexpected = true; }\n        } else {\n            // no id or unexpected regex (maybe changed?)\n            data = {\n                success: false,\n                raw: rawMsg,\n                body: rawMsg,\n            };\n            let regexResultLocation = rawMsg.match(ERROR_MSG_LOCATION_ONLY_REGEXP);\n            if (regexResultLocation) {\n                const [_, location] = regexResultLocation;\n                data.location = location;\n            }\n            if (rawMsg.toLowerCase().includes(`(unexpected)`)) {\n                data.unexpected = true;\n            }\n        }\n\n        return data;\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * Builds a \"constant\" error ibgib based on the given `rawMsg`.\n *\n * @returns constant error ibgib built from given `rawMsg`\n *\n * @see {@link ErrorData_V1}\n * @see {@link ErrorIbGib_V1}\n */\nexport function getErrorIbGib({ rawMsg }: { rawMsg: string }): Promise<ErrorIbGib_V1> {\n    const lc = `[${getErrorIbGib.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting...`); }\n\n        return constantIbGib<ErrorData_V1, ErrorRel8ns_V1>({\n            parentPrimitiveIb: 'error',\n            ib: getErrorIb({ rawMsg }),\n            data: parseRawErrorMsg({ rawMsg }),\n            ibRegExpPattern: ERROR_IB_REGEXP.source,\n        });\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport function isError({\n    ibGib\n}: {\n    ibGib: IbGib_V1\n}): boolean {\n    const lc = `[${isError.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting...`); }\n        if (!ibGib) { throw new Error(`ibGib required (E: 1d756fbbd96f1734b97ba013537ed522)`); }\n        return ibGib.ib.startsWith('error ');\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n", "import { AnonymousFnWitnessData_V1 } from \"./anonymous-fn-types.mjs\";\n\nexport const ANONYMOUS_FN_ATOM = 'anon_fn';\n\nexport const DEFAULT_ANONYMOUS_FN_DATA_V1: AnonymousFnWitnessData_V1 = {\n    fnHash: '',\n};\n", "import { GLOBAL_LOG_A_LOT } from \"../../core-constants.mjs\";\nimport { WitnessFn } from \"../witness-types.mjs\";\nimport { ANONYMOUS_FN_ATOM } from \"./anonymous-fn-constants.mjs\";\nimport { AnonymousFnWitnessData_V1 } from \"./anonymous-fn-types.mjs\";\nimport { AnonymousFnWitness_V1 } from \"./anonymous-fn-v1.mjs\";\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\nexport function getAnonymousFnIb({\n    data,\n}: {\n    data: AnonymousFnWitnessData_V1,\n}): string {\n    const lc = `[${getAnonymousFnIb.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 37bb06e0390c5bcadf04501727d64923)`); }\n        if (!data?.fnHash) { throw new Error(`data.fnHash required (E: 2e560f2c59822bc5ba024d4a8e99d323)`); }\n        return `witness ${ANONYMOUS_FN_ATOM} ${data.fnHash}`;\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * wraps a fn in an anonymous witness.\n *\n * @param fn fn to execute\n * @returns anonymous witness ibgib\n */\nexport async function fnToWitness(fn: WitnessFn): Promise<AnonymousFnWitness_V1> {\n    const lc = `[${fnToWitness.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: e64fe14287de9716f2e5ff3bf9d93923)`); }\n        let witness = new AnonymousFnWitness_V1(fn);\n        return witness;\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n", "import { clone, hash } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { GIB } from \"@ibgib/ts-gib/dist/V1/constants.mjs\";\nimport { IbGib_V1 } from \"@ibgib/ts-gib/dist/V1/types.mjs\";\nimport { getGib } from \"@ibgib/ts-gib/dist/V1/transforms/transform-helper.mjs\";\n\nimport { Witness, WitnessFn, } from \"../witness-types.mjs\";\nimport { ANONYMOUS_FN_ATOM, DEFAULT_ANONYMOUS_FN_DATA_V1 } from \"./anonymous-fn-constants.mjs\";\nimport { getAnonymousFnIb } from \"./anonymous-fn-helper.mjs\";\nimport { AnonymousFnWitnessData_V1, AnonymousFnWitnessIbGib_V1, AnonymousFnWitnessRel8ns_V1, } from \"./anonymous-fn-types.mjs\";\n\n/**\n * Helper class that wraps a witness function.\n *\n * @see {@link AnonymousFnWitnessData_V1}\n * @see {@link AnonymousFnWitnessRel8ns_V1}\n * @see {@link WitnessFn}\n */\nexport class AnonymousFnWitness_V1\n    implements\n    Witness<IbGib_V1, IbGib_V1, AnonymousFnWitnessData_V1, AnonymousFnWitnessRel8ns_V1>,\n    AnonymousFnWitnessIbGib_V1 {\n\n    ib: string = ANONYMOUS_FN_ATOM.concat();\n    gib?: string | undefined = GIB;\n    data?: AnonymousFnWitnessData_V1 | undefined = clone(DEFAULT_ANONYMOUS_FN_DATA_V1);\n    rel8ns?: AnonymousFnWitnessRel8ns_V1 | undefined;\n\n    constructor(public fn: WitnessFn) {\n        if (!fn) { throw new Error(`fn required (E: b1e1478f466a2a347b75e7c336f8d323)`); }\n    }\n\n    async witness(arg: IbGib_V1): Promise<IbGib_V1 | undefined> {\n        this.data!.fnHash = await hash({ s: this.fn.toString() });\n        this.ib = getAnonymousFnIb({ data: this.data! });\n        this.gib = await getGib({ ibGib: this });\n        return this.fn(arg);\n    }\n\n}\n", "import { extractErrorMsg } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { IbGib_V1 } from \"@ibgib/ts-gib/dist/V1/types.mjs\";\nimport { ROOT } from \"@ibgib/ts-gib/dist/V1/constants.mjs\";\n\nimport { GLOBAL_LOG_A_LOT } from \"../../../core-constants.mjs\";\nimport { ErrorIbGib_V1 } from \"../../error/error-types.mjs\";\nimport { isIbGib } from \"../../other/ibgib-helper.mjs\";\nimport { getErrorIbGib, isError } from \"../../error/error-helper.mjs\";\nimport { Observer, ObserverWitness } from \"./observer-types.mjs\";\nimport { WitnessFn } from \"../../../witness/witness-types.mjs\";\nimport { AnonymousFnWitness_V1 } from \"../../../witness/anonymous-fn/anonymous-fn-v1.mjs\";\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\n/**\n * Determines type of incoming `err` and pulls out the error msg accordingly.\n *\n * ## note on not using {@link extractErrorMsg}\n *\n * {@link extractErrorMsg} is in helper-gib, which despite the name, does not\n * contain ibgib-specific types. So we can't pass in an ibGib and have it\n * extract the error msg.\n *\n * @returns error msg from incoming err\n */\nexport function extractObsErrMsg({\n    err,\n}: {\n    err: ErrorIbGib_V1 | Error | string,\n}): string {\n    const lc = `[${extractObsErrMsg.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 96f8b767c50f24768ced7beebb291723)`); }\n        if (isIbGib(err)) {\n            let ibGib = err as IbGib_V1;\n            if (!(err as IbGib_V1).data) { throw new Error(`err isIbGib but err.data is false. (E: 151a6bab647c638c454fd277ac468f23)`); }\n            if (isError({ ibGib: err as IbGib_V1 })) {\n                return (err as ErrorIbGib_V1).data!.raw;\n            } else {\n                // shouldn't get here because function signature but hey ynk\n                throw new Error(`(UNEXPECTED) err isIbGib but not ErrorIbGib_V1? (E: 81c2283fad5db3485c6e9acedbda9723)`);\n            }\n        } else {\n            return extractErrorMsg(err);\n        }\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * this is meant to be a wrapper of non-ibgib-like lambdas.\n *\n * So you take normal, mostly non-ibgib anonymous lambdas (that do indeed\n * have ibgib's as their inputs/outputs) and you wrap it here to get an\n * {@link ObserverWitness} which is an actual witness ibGib.\n * @param observer with regularish lambdas in a javascript object (not an ibgib)\n * @returns observer ibgib witness with formal ibgib witness signatures and the other ibgib properties: `ib`, `gib`, `data`, `rel8ns`\n */\nexport function fnObs<T extends IbGib_V1 = IbGib_V1>(\n    observerOrFn: Observer<T> | ((ibGib: T) => Promise<void>)\n): ObserverWitness<T> {\n    const lc = `[${fnObs.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 3d2c3658a0fda83ece1f2b095a365823)`); }\n\n        let observer: Observer<T>;\n        if (typeof observerOrFn === 'function') {\n            observer = { next: observerOrFn, };\n        } else {\n            observer = observerOrFn;\n        }\n\n        if (!observer.next) { throw new Error(`observer.next required (typeof observerOrFn !== 'function') (E: da944e93b32ab5918f11751bcd651823)`); }\n\n        const fnNext: WitnessFn<T> = async (ibGib) => {\n            await observer.next(ibGib);\n            return ROOT;\n        };\n        /**\n         * no idea what im doing here really...making an anonymous ibgib\n         * essentially, but not sure how the witness fn would actually be used.\n         * @param ibGib coming down the pipe?\n         * @returns `ROOT`\n         */\n        const fnWitness: WitnessFn<T | ErrorIbGib_V1> = async (ibGib) => {\n            if (ibGib.ib === 'complete') {\n                if (observer.complete) { await observer.complete(); }\n            } else if (isError({ ibGib })) {\n                if (observer.error) {\n                    await observer.error(ibGib as ErrorIbGib_V1)\n                }\n            } else {\n                await observer.next(ibGib as T);\n            }\n            return ROOT;\n        };\n\n        // I'm wrapping these in anonymous fn witnesses, but do I need to?\n        let nextAnonFnWitness = new AnonymousFnWitness_V1(fnNext as WitnessFn); // cast should not be necessary\n        let witnessAnonFnWitness = new AnonymousFnWitness_V1(fnWitness as WitnessFn); // cast should not be necessary\n\n        // const observerWitness: SubjectWitness<T> = {\n        const observerWitness: ObserverWitness<T> = {\n            ib: 'observer',\n            witness: async (x: T) => await witnessAnonFnWitness.witness(x),\n            next: async (x: T) => { await nextAnonFnWitness.witness(x); },\n            // isComplete: false,\n            // isErrored: false,\n            // isCompleteOrErrored: false,\n            // asObservable: () => { throw new Error(`asObservable not impl on anonymous fn witness (E: d127d1822dbd90e7134cef75e4e23c23)`); },\n            // subscribe: () => { throw new Error(`subscribe not impl on anonymous fn witness (E: 11ce7903626e8d1c3d27dc28f1e5cd23)`); },\n        };\n\n        let fnError = observer.error ?? (async (error: string | ErrorIbGib_V1 | Error) => {\n            let errorMsg: string;\n            if (typeof error === 'string') {\n                errorMsg = extractErrorMsg(error);\n            } else if (!!(error as any).ib) {\n                // error ibgib\n                if (isError({ ibGib: error as IbGib_V1 })) {\n                    errorMsg = extractErrorMsg((error as ErrorIbGib_V1).data!.raw);\n                } else {\n                    throw new Error(`${lc} (UNEXPECTED) first off, observer.error is falsy. secondly, error came down pipeline and has an \"ib\" property but is not an ErrorIbGib_V1? (E: 0a2a46b9620b4a6a84c7ba1100da537b)`);\n                }\n            } else if (error instanceof Error) {\n                errorMsg = extractErrorMsg(error as any)\n            } else if (typeof (error as any).message === 'string') {\n                errorMsg = extractErrorMsg((error as any).message)\n            } else {\n                errorMsg = '[unknown thing came down pipe that ain\\'t an error]';\n            }\n            console.error(`Error occurred but observer.error is falsy. error: ${errorMsg} (E: 822c60c7c4d542efacd5c2dea7e88062)`)\n        });\n        const errorAnonFnWitness =\n            new AnonymousFnWitness_V1(async x => { fnError(x as ErrorIbGib_V1); return ROOT; });\n        observerWitness.error = async (x: string | ErrorIbGib_V1 | Error) => {\n            // if (observerWitness.isCompleteOrErrored) {\n            //     console.warn(`${lc} observerWitness.error triggered but observerWitness already complete or errored. (W: 85f8426d70404208b721a9de2876bbc2)`)\n            //     return; /* <<<< returns early */\n            // } else {\n            //     // do these before any more handling in case there is some problem.\n            //     (observerWitness as any).isErrored = true;\n            //     (observerWitness as any).isCompleteOrErrored = true;\n            // }\n            // coerce non-ibgib errors into ErrorIbGib_V1\n            if (typeof x === 'string') {\n                x = await getErrorIbGib({ rawMsg: x });\n            } else if (x instanceof Error) {\n                x = await getErrorIbGib({ rawMsg: x.message });\n            }\n            try {\n                await errorAnonFnWitness.witness(x);\n            } catch (anotherError) {\n                if (observer.error) {\n                    console.error(`${lc} there was another error when executing errorAnonFnWitness.witness (wrapper of caller's observer.error) trapping this. (E: 8fa3c4e633df4491a82951e3b677d9a9)`)\n                } else {\n                    console.error(`${lc} there was another error when executing errorAnonFnWitness.witness (caller's observer.error was falsy). trapping this. (E: f5ff2db0d762487287139a4175eb7689)`)\n                }\n            }\n        };\n\n        if (observer.complete) {\n            let fnComplete = observer.complete;\n            let completeAnonFnWitness = new AnonymousFnWitness_V1(async (_) => {\n                await fnComplete();\n                return ROOT;\n            });\n\n            observerWitness.complete = async () => {\n                // (observerWitness as any).isComplete = true;\n                // (observerWitness as any).isCompleteOrErrored = true;\n                try {\n                    await completeAnonFnWitness.witness(ROOT);\n                } catch (error) {\n                    console.error(`${lc} there was an error when executing completeAnonFnWitness (wrapper for observer.complete fn) error: ${extractErrorMsg(error)} (E: c9e61b08429e42c1b85d2215f735ba2f)`)\n                }\n            };\n        }\n\n        return observerWitness;\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n", "import { clone, } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';\nimport { getIbGibAddr, } from '@ibgib/ts-gib/dist/helper.mjs';\nimport { IbGib_V1, IbGibRel8ns_V1, sha256v1, } from '@ibgib/ts-gib/dist/V1/index.mjs';\nimport { getGibInfo } from '@ibgib/ts-gib/dist/V1/transforms/transform-helper.mjs';\nimport { validateGib, validateIb, validateIbGibIntrinsically } from '@ibgib/ts-gib/dist/V1/validate-helper.mjs';\n\nimport { GLOBAL_LOG_A_LOT } from '../core-constants.mjs';\nimport { WitnessData_V1, Witness_V1, } from './witness-types.mjs';\nimport { ErrorIbGib_V1 } from '../common/error/error-types.mjs';\nimport { toDto } from '../common/other/ibgib-helper.mjs';\n\nconst logalot = GLOBAL_LOG_A_LOT || false;\n\nexport abstract class WitnessBase_V1<\n    TOptionsData extends any,\n    TOptionsRel8ns extends IbGibRel8ns_V1,\n    TOptionsIbGib extends IbGib_V1<TOptionsData, TOptionsRel8ns>,\n    TResultData extends any,\n    TResultRel8ns extends IbGibRel8ns_V1,\n    TResultIbGib extends IbGib_V1<TResultData, TResultRel8ns> | ErrorIbGib_V1,\n    TData extends WitnessData_V1 = any,\n    TRel8ns extends IbGibRel8ns_V1 = IbGibRel8ns_V1\n>\n    implements Witness_V1<\n        TOptionsData, TOptionsRel8ns, TOptionsIbGib, // options arg\n        TResultData, TResultRel8ns, TResultIbGib,    // result\n        TData, TRel8ns                   // this witness itself\n    > {\n\n    /**\n     * Log context for convenience with logging. (Ignore if you don't want to use this.)\n     */\n    protected lc: string = `[${WitnessBase_V1.name}]`;\n\n    /**\n     * Optional arg for verbose logging.\n     */\n    protected set trace(value: boolean) {\n        const lc = `${this.lc}[set trace]`;\n        if (value === (this.data?.trace || false)) { return; }\n        if (this.data) {\n            this.data.trace = value;\n            delete this.gib; // gib is invalid now\n        } else {\n            console.warn(`${lc} data is falsy. Can't set.`);\n        }\n    }\n    protected get trace(): boolean { return this.data?.trace ?? false; }\n\n    /**\n     * Optional configuration for `witness` call.\n     * If true, then this space will catch any error that propagates up\n     * from the `witnessImpl` function.\n     *\n     * ## notes\n     *\n     * Descendants of Witness who don't override the base `witness` function\n     * (but rather override `witnessImpl` as expected) don't need to check\n     * for this explicitly, since it is referenced in the base `witness`\n     * function implementation.\n     */\n    protected set catchAllErrors(value: boolean) {\n        const lc = `${this.lc}[set catchAllErrors]`;\n        if (value === this.data?.catchAllErrors) { return; }\n        if (this.data) {\n            this.data.catchAllErrors = value;\n            delete this.gib;\n        } else {\n            console.error(`${lc} data is falsy. Can't set value.`);\n        }\n    }\n    protected get catchAllErrors(): boolean {\n        const lc = `${this.lc}[catchAllErrors]`;\n        const result = this.data?.catchAllErrors || false;\n        if (logalot || this.trace) { console.log(`${lc} result: ${result}`) }\n        return result;\n    }\n\n    // #region IbGib interface fields: ib, gib, data, rel8ns\n\n    /**\n     * Used per use case in implementing class.\n     *\n     * This property is a simple property (no getter/setter with backing\n     * fields).  This is to simplify usage with DTOs (Data Transfer Objects) for\n     * storing in spaces.\n     */\n    ib: string = '';\n\n    /**\n     * Used per use case in implementing class.\n     *\n     * This property is a simple property (no getter/setter with backing\n     * fields).  This is to simplify usage with DTOs (Data Transfer Objects) for\n     * storing in spaces.\n     */\n    gib: string | undefined;\n\n    /**\n     * Used per use case in implementing class.\n     *\n     * This property is a simple property (no getter/setter with backing\n     * fields).  This is to simplify usage with DTOs (Data Transfer Objects) for\n     * storing in spaces.\n     */\n    data: TData | undefined;\n\n    /**\n     * Used per use case in implementing class.\n     *\n     * This property is a simple property (no getter/setter with backing\n     * fields).  This is to simplify usage with DTOs (Data Transfer Objects) for\n     * storing in spaces.\n     */\n    rel8ns: TRel8ns | undefined;\n\n    // #endregion IbGib interface fields: ib, gib, data, rel8ns\n\n    /**\n     * await this to ensure the witness is ready.\n     *\n     * This is called in the base `Witness.witness` function before `witnessImpl`.\n     */\n    initialized: Promise<void> | undefined;\n\n    constructor(initialData?: TData, initialRel8ns?: TRel8ns) {\n        if (initialData) { this.data = initialData; }\n        if (initialRel8ns) { this.rel8ns = initialRel8ns; }\n        this.initialized = this.initialize();\n    }\n\n    /**\n     * by default, simply returns true atow in base class.\n     * override this to perform code before any other code is executed.\n     */\n    protected initialize(): Promise<void> {\n        return Promise.resolve();\n    }\n\n    /**\n     * Creates a data transfer object (dto) snapshot out of this\n     * witness' `ib`, `gib`, `data` and `rel8ns` properties.\n     *\n     * I say \"snapshot\" because this copies each property\n     * (`ib`, `gib`, `data`, `rel8ns`).\n     *\n     * ## thoughts\n     *\n     * Witness classes need to be able to persist their ibgib\n     * just as regular data. But witnesses have the additional\n     * layer of behavior (e.g. the `witness` function) that\n     * will not persist (until we get more integrated version control\n     * types of functionality in ibgib).\n     *\n     * @returns dto ibgib object with just clones of this.ib/gib/data/rel8ns props.\n     *\n     * @see {loadIbGibDto}\n     */\n    toIbGibDto(): IbGib_V1<TData, TRel8ns> {\n        return toDto({ ibGib: this });\n        // const lc = `${this.lc}[${this.toIbGibDto.name}]`;\n        // if (!this.ib) { console.warn(`${lc} this.ib is falsy. (W: 60162e3ab42941e9a68cd6adc8d23387)`); }\n        // if (!this.gib) { console.warn(`${lc} this.gib is falsy. (W: 61dc535639dc410d874635013fce5b8a)`); }\n\n        // let dtoIbGib: IbGib_V1<TData, TRel8ns> = { ib: (this.ib || '').slice() };\n        // if (this.gib) { dtoIbGib.gib = this.gib.slice(); };\n        // if (this.data) { dtoIbGib.data = clone(this.data); }\n        // if (this.rel8ns) { dtoIbGib.rel8ns = clone(this.rel8ns); }\n\n        // return dtoIbGib;\n    }\n\n    /**\n     * (Re)hydrates this witness class with the ibgib information from the dto.\n     *\n     * ## notes\n     *\n     * * You can extend this function for witness-specific behavior when loading.\n     *\n     * @param dto ib, gib, data & rel8ns to load for this witness ibgib instance.\n     *\n     * @see {toIbGibDto}\n     */\n    loadIbGibDto(dto: IbGib_V1<TData, TRel8ns>): Promise<void> {\n        const lc = `${this.lc}[${this.loadIbGibDto.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting...`); }\n\n            if (!dto.ib) { console.warn(`${lc} dto.ib is falsy.`); }\n            if (!dto.gib) { console.warn(`${lc} dto.gib is falsy.`); }\n\n            this.ib = clone(dto.ib);\n            this.gib = clone(dto.gib);\n            if (dto.data) {\n                this.data = clone(dto.data);\n            } else {\n                delete this.data;\n            }\n            if (dto.rel8ns) { this.rel8ns = clone(dto.rel8ns); } else { delete this.rel8ns; }\n\n            return Promise.resolve();\n        } catch (error) {\n            console.error(`${lc} ${error.message}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * The primary function of a witness is...well... to witness things.\n     *\n     * So this is the base implementation that includes validation\n     * plumbing, tracing, error checking/catching - all depending\n     * on witness configuration.\n     *\n     *\n     * ## usage\n     *\n     * Only override this function if you really want custom handling of\n     * the plumbing.  Instead override `witnessImpl`.\n     *\n     * {@see validateThis}\n     * {@see validateWitnessArg}\n     *\n     * @param arg\n     * @returns\n     */\n    async witness(arg: TOptionsIbGib): Promise<TResultIbGib | undefined> {\n        const lc = `${this.lc}[${this.witness.name}]`;\n        try {\n            await this.initialized;\n            if (!this.gib) { this.gib = await sha256v1(this.toIbGibDto()); }\n            const validationErrors_this = await this.validateThis();\n            if (validationErrors_this?.length > 0) {\n                for (const error of validationErrors_this) { console.error(`${lc} ${error}`); }\n                throw new Error(`internal witness validation failed. See \\`WitnessBase_V1.validateThis\\` (E: 2b5f73cadbfa416ba189346f3c31cd0c)`);\n            }\n            const validationErrors_arg = await this.validateWitnessArg(arg);\n            if (validationErrors_arg?.length > 0) {\n                for (const error of validationErrors_arg) { console.error(`${lc} ${error}`); }\n                throw new Error(`arg validation failed. See \\`WitnessBase_V1.validateWitnessArg\\` (E: 51531a1d928a485e8ffc277145ec44e9)`);\n            }\n            if (logalot || this.trace) { console.log(`${lc} addr: ${getIbGibAddr(arg)}`); }\n            if (logalot) { console.log(`${lc} addr: ${getIbGibAddr(arg)} (I: f4cf13a44c4e4fc3903f14018e616c64)`); }\n            const result = await this.witnessImpl(arg);\n\n            // persist the arg and result if we're configured to do so it is up\n            // to the implementation whether or not to throw on this.\n            if (this.data?.persistOptsAndResultIbGibs) {\n                await this.persistOptsAndResultIbGibs({ arg, result });\n            }\n\n            return result;\n        } catch (error) {\n            console.error(`${lc} ${error.message || 'unknown error (E: 3e22bea4c7fb4668bf13d7146b927869)'}`);\n            if (!this.catchAllErrors) {\n                throw error;\n            } else {\n                return; // undefined\n            }\n        }\n    }\n    protected abstract witnessImpl(arg: TOptionsIbGib): Promise<TResultIbGib | undefined>;\n\n    /**\n     * Validate the incoming arg.\n     *\n     * Override this in descending classes per use case.\n     */\n    protected async validateWitnessArg(arg: TOptionsIbGib): Promise<string[]> {\n        const lc = `${this.lc}[${this.validateWitnessArg.name}]`;\n        try {\n            const errors: string[] = [];\n            if (!arg) { errors.push(`arg required (E: a222db3b668e4bb09cfd82e75c07bfa6)`); }\n\n            const ibErrors = validateIb({ ib: arg?.ib });\n            if (ibErrors?.length ?? 0 > 0) { errors.push(`invalid arg.ib (E: 2ae362ef274d4c3bb9716800f2106d28) errors: ${ibErrors!.join('\\n')}`); }\n\n            const gibErrors = validateGib({ gib: arg?.gib! });\n            if (gibErrors?.length ?? 0 > 0) { errors.push(`invalid arg.gib (E: 73be275058084d768a39299337f2ce34) errors: ${gibErrors!.join('\\n')}`); }\n\n            const intrinsicErrors = await validateIbGibIntrinsically({ ibGib: arg as IbGib_V1<any> });\n            if (intrinsicErrors?.length ?? 0 > 0) {\n                errors.push(`arg ibgib invalid intrinsically (E: 73be275058084d768a39299337f2ce34) errors: ${intrinsicErrors!.join('\\n')}`);\n            } else if (!this.data?.allowPrimitiveArgs) {\n                // further check to see if primitive\n                const gibInfo = getGibInfo({ gib: arg.gib });\n                if (gibInfo.isPrimitive) { errors.push(`arg is primitive (i.e. gib === \"gib\") and witness.data.allowPrimitiveArgs is falsy. (E: d0aa3d7ad4f54b01bd0023300d15ecd9)`) }\n            }\n\n            return errors;\n        } catch (error) {\n            console.error(`${lc} ${error.message}`);\n            throw error;\n        }\n    }\n\n    /**\n     * Validate this witness object, checking its own `data` and `rel8ns`, and\n     * possibly other state.\n     *\n     * ## notes\n     *\n     * ATOW base implementation of this just checks for non-falsy\n     * `this.ib` and `this.gib`\n     */\n    protected async validateThis(): Promise<string[]> {\n        const lc = `${this.lc}[${this.validateThis.name}]`;\n        const errors: string[] = [];\n        try {\n            if (!this.ib) { errors.push(`this.ib is falsy.`); }\n            if (!this.gib) { errors.push(`this.gib is falsy.`); }\n        } catch (error) {\n            console.error(`${lc} ${error.message}`);\n            throw error;\n        }\n        return errors;\n    }\n\n    /**\n     * Empty implementation in this base class.\n     *\n     * @see {@link WitnessData_V1.persistOptsAndResultIbGibs}\n     */\n    protected persistOptsAndResultIbGibs({\n        arg,\n        result\n    }: {\n        arg: TOptionsIbGib,\n        result: TResultIbGib | undefined\n    }): Promise<void> {\n        const lc = `${this.lc}[${this.persistOptsAndResultIbGibs.name}]`;\n        console.warn(`${lc} not implemented in this base class. Override this in descendent class. (W: 087514e851704322a4ec8069a73ce944)`);\n        return Promise.resolve();\n    }\n\n}\n\nexport type WitnessBaseAny = WitnessBase_V1<any, any, IbGib_V1, any, any, IbGib_V1, any, any>;\n", "// import { Subscription } from 'rxjs/index.js';\n// import { filter } from 'rxjs/operators';\n\nimport {\n    delay, extractErrorMsg, getSaferSubstring, pretty,\n} from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';\nimport { Ib, IbGibAddr, } from '@ibgib/ts-gib/dist/types.mjs';\nimport { getIbGibAddr } from '@ibgib/ts-gib/dist/helper.mjs';\nimport { rel8 } from '@ibgib/ts-gib/dist/V1/transforms/rel8.mjs';\nimport { getGibInfo, IbGib_V1, IbGibRel8ns_V1 } from '@ibgib/ts-gib/dist/V1/index.mjs';\nimport { validateIbGibIntrinsically } from '@ibgib/ts-gib/dist/V1/validate-helper.mjs';\n\nimport { GLOBAL_LOG_A_LOT } from '../../core-constants.mjs';\nimport { WitnessBase_V1, } from '../witness-base-v1.mjs';\nimport { CommentIbGib_V1 } from '../../common/comment/comment-types.mjs';\nimport { ErrorIbGib_V1 } from '../../common/error/error-types.mjs';\nimport { createCommentIbGib, } from '../../common/comment/comment-helper.mjs';\nimport { getLatestAddrs } from '../space/space-helper.mjs';\nimport { getTjpAddr } from '../../common/other/ibgib-helper.mjs';\nimport { IbGibTimelineUpdateInfo } from '../../common/other/other-types.mjs';\nimport { WitnessArgIbGib, } from '../witness-types.mjs';\nimport { WitnessWithContextData_V1, WitnessWithContextRel8ns_V1 } from './witness-with-context-types.mjs';\nimport { MetaspaceService } from '../space/metaspace/metaspace-types.mjs';\nimport { SubscriptionWitness } from '../../common/pubsub/subscription/subscription-types.mjs';\nimport { extractObsErrMsg, fnObs } from '../../common/pubsub/observer/observer-helper.mjs';\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\n/**\n * ## distinguishing characteristics of robbots\n *\n * With any witness ibgib, we are concerned with interpreting an incoming\n * arg ibgib and producing at least one result ibgib. Most often, there will\n * be additional ibgibs created, either creating \"new\" ibgibs via `fork`\n * transforms, or changing existing ibgibs through `mut8` and `rel8`\n * transforms. And almost always these will be persisted in at least\n * one space.\n *\n * But Robbots in particular are meant to be increasingly adaptable over time.\n *\n * This results in a couple of notes:\n *\n * 1. They should be able to handle any incoming ibgib, including primitives.\n * 2. If they are learning robbots, then they will mutate internally at some rate.\n * 3. Often robbots' output ibgib(s) will be intended for others'\n *    consumption, in service of others - be they humans or other\n *    biologically living organisms, other robbots or even later versions of\n *    themselves.\n *\n * So for example, one of the simplest robbots is one which simply echos the\n * incoming ibgib arg.\n\n * ## architecture\n *\n * At the base, any robbot should be able to handle any incoming ibgib.  This is\n * in contrast to, e.g., a Space, which is more rigid in design.\n *\n * Certainly there are robbot's who will be more rigid, but this will be an\n * abstract class on top of this one, and all robbots should be able to react to\n * all incoming ibgibs.\n *\n * Output will default to a simple ok^gib or (ROOT) ib^gib primitive...perhaps\n * we'll go with ack^gib, but whatever it is, it's just an acknowledgement of\n * input received.  (I'll put it in the constants file).\n *\n * Side effects should occur in a parallel execution thread, which ideally would\n * work in a completely parallel execution context (like a service worker). But\n * then we have to deal with race conditions and the real solution there is to\n * abstract to the robbot having its own space and the synchronization happening\n * exactly like any other sync space.\n *\n * For now, we'll spin off a promise with some intermittent `await delay`\n * calls if they end up called for, effectively the equivalent of the\n * old-fashioned \"ProcessMessages/DoEvents\" hack.\n */\nexport abstract class WitnessWithContextBase_V1<\n    TOptionsData extends any = any,\n    TOptionsRel8ns extends IbGibRel8ns_V1 = IbGibRel8ns_V1,\n    TOptionsIbGib extends IbGib_V1<TOptionsData, TOptionsRel8ns>\n    = IbGib_V1<TOptionsData, TOptionsRel8ns>,\n    TResultData extends any = any,\n    TResultRel8ns extends IbGibRel8ns_V1 = IbGibRel8ns_V1,\n    TResultIbGib extends IbGib_V1<TResultData, TResultRel8ns> | ErrorIbGib_V1\n    = IbGib_V1<TResultData, TResultRel8ns>,\n    TData extends WitnessWithContextData_V1 = WitnessWithContextData_V1,\n    TRel8ns extends WitnessWithContextRel8ns_V1 = WitnessWithContextRel8ns_V1,\n> extends WitnessBase_V1<\n    TOptionsData, TOptionsRel8ns, TOptionsIbGib,\n    TResultData, TResultRel8ns, TResultIbGib,\n    TData, TRel8ns> {\n\n    /**\n     * Log context for convenience with logging. (Ignore if you don't want to use this.)\n     *\n     * Often used in conjunction with `logalot`.\n     */\n    protected lc: string = `[${WitnessWithContextBase_V1.name}]`;\n\n    /**\n     * Reference to the local ibgibs service, which is one way at getting at the\n     * local user space.\n     *\n     * todo: refactor this to `metaspace` after we have completed majority of refactor/breakout from mvp\n     */\n    public metaspace: MetaspaceService | undefined;\n\n    protected _contextChangesSubscription: SubscriptionWitness | undefined;\n    protected _currentWorkingContextIbGib: IbGib_V1 | undefined;\n    /**\n     * when we get an update to the context, we want to know what the _new_\n     * children are in order to interpret comments from the user that may be\n     * directed at us.\n     *\n     * So we will get an initial snapshot of children that we will diff against.\n     * We could go via the dna, but ultimately a diff is what is needed.\n     */\n    protected _currentWorkingContextIbGib_PriorChildrenAddrs: IbGibAddr[] = [];\n\n    protected _updatingContext: boolean = false;\n\n    constructor(initialData?: TData, initialRel8ns?: TRel8ns) {\n        super(initialData, initialRel8ns);\n        this.initialized = this.initialize();\n    }\n\n    protected async initialize(): Promise<void> {\n        const lc = `${this.lc}[${this.initialize.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: f0e65ab0f80046a59668ddfbf9f47a4a5)`); }\n            await super.initialize();\n\n            // await this.initialize_semanticHandlers();\n            // await this.initialize_lex();\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    protected async loadNewerSelfIfAvailable(): Promise<void> {\n        const lc = `${this.lc}[${this.loadNewerSelfIfAvailable.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 94755c3131f4dfa12d20fa38e2926522)`); }\n            if (this.metaspace) {\n                // check for newer version of self locally before executing\n                const thisAddr = getIbGibAddr({ ibGib: this });\n                const latestAddr = await this.metaspace.getLatestAddr({ ibGib: this });\n                if (latestAddr && latestAddr !== thisAddr) {\n                    // this has a newer ibgib in its timeline\n                    let resGet = await this.metaspace.get({ addr: latestAddr });\n                    if (!resGet || !resGet?.success || (resGet?.ibGibs ?? []).length === 0) {\n                        throw new Error(`could not get newer ibgib in timeline (E: 15fa346c8ac17edb96e4b0870104c122)`);\n                    }\n                    await this.loadIbGibDto(resGet.ibGibs![0] as IbGib_V1<TData, TRel8ns>);\n                    const validationErrors = await this.validateThis();\n                    if (validationErrors?.length > 0) { throw new Error(`validationErrors when loading newer version: ${pretty(validationErrors)} (E: 0d9f0684a1ff6af44e20a57130e3ac22)`); }\n                }\n            } else {\n                console.warn(`${lc} this.metaspace undefined (W: 44cc5bf1b14b4695b8de4c589787be06)`);\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * By default, this...\n     *\n     * * performs the raw {@link rel8} transform to the given `ibGib`.\n     * * persists the new ibgib's transform result in the given space.\n     * * registers the newer version of this robbot ibgib with the ibgibs svc.\n     *\n     * @see {@link ibGibs}\n     * @see {@link rel8nName}\n     * @see {@link metaspace}\n     * @see {@link space}\n     *\n     * ## notes\n     *\n     * * If there is no given `space`, then we will use the `metaspace` to get\n     *   the local user space. If none, then we skip persistence.\n     * * If there is no `metaspace`, we won't register the new ibgibs locally.\n     */\n    protected async rel8To({\n        ibGibs,\n        rel8nName,\n        linked,\n        metaspace,\n        // space,\n    }: {\n        /**\n         * The ibgib to which we are relating.\n         */\n        ibGibs: IbGib_V1[],\n        /**\n         * If given, will use this as the rel8n name when performing the `rel8`\n         * transform.\n         *\n         * If not given, will use the `robbot.data`'s {@link RobbotData_V1.defaultRel8nName} value.\n         */\n        rel8nName?: string,\n        /**\n         * If true, will include the `rel8nName` as a linked rel8n in the `rel8`\n         * transform.\n         */\n        linked?: boolean,\n        /**\n         * If provided, will register the newly created ibgib.\n         */\n        metaspace?: MetaspaceService,\n        // /**\n        //  * If given (which atow is most likely the case), then the {@link TransformResult} will\n        //  * be persisted in this `space`.\n        //  */\n        // space?: IbGibSpaceAny,\n    }): Promise<void> {\n        const lc = `${this.lc}[${this.rel8To.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting...`); }\n\n            // #region initialize, validate args and this\n\n            if ((ibGibs ?? []).length === 0) { throw new Error(`ibGibs required (E: 2fd13de0f025b170885bede4d7a50922)`); }\n\n            rel8nName = rel8nName || this.data?.defaultRel8nName;\n            if (!rel8nName) { throw new Error(`rel8nName required either as an arg or in this.data.defaultRel8nName (E: 43ab8ae63694a2a82cd8a70ed6b6b522)`); }\n\n            const thisValidationErrors = await this.validateThis();\n            if (thisValidationErrors?.length > 0) { throw new Error(`this is an invalid ibGib. thisValidationErrors: ${thisValidationErrors.join('|')} (E: 8f08716866cd13bf254222ee9e6a6722)`); }\n\n            metaspace = metaspace ?? this.metaspace;\n\n            if (!metaspace) {\n                // if (this.metaspace) {\n                //     if (logalot) { console.log(`${lc} metaspace arg falsy, but we have a reference on this object, which we will use. (I: ee0d39a47ee8aee8ffd797721fea4322)`); }\n                //     metaspace = this.metaspace;\n                // }\n                throw new Error(`either metaspace or this.metaspace required (E: b5f9453ddb394a2b76dec74c7304df22)`);\n            }\n\n            // if (!space) {\n            //     if (metaspace) {\n            //         if (logalot) { console.log(`${lc} space arg falsy, but metaspace truthy, so we'll use metaspace's local user space for persistence. (I: 37a4b4c1406556cb23831671755b0d22)`); }\n            //         space = await metaspace.getLocalUserSpace({ lock: true });\n            //     }\n            // }\n\n            // if (!space) { throw new Error(`(UNEXPECTED) space required and metaspace couldn't get it? (E: a3b9f9b72f6f6f18883199a19d38c622)`); }\n\n            // #endregion initialize, validate args and this\n\n            // we want to rel8 only to the ibGibs whose timelines we're not\n            // already related to. So we look to see if we already have the tjpGib\n            // per our rel8nName.\n            // if (!this.rel8ns) { this.rel8ns = {} as any };\n            const alreadyRel8dAddrs = this.rel8ns ? this.rel8ns[rel8nName] ?? [] : [];\n            const alreadyRel8dTjpGibs = alreadyRel8dAddrs.map(x => getGibInfo({ ibGibAddr: x }).tjpGib);\n            const ibGibsNotYetRel8dByTjp = ibGibs.filter(x => {\n                const tjpGib = getGibInfo({ ibGibAddr: getIbGibAddr({ ibGib: x }) }).tjpGib;\n                return !alreadyRel8dTjpGibs.includes(tjpGib);\n            });\n\n            if (ibGibsNotYetRel8dByTjp.length === 0) {\n                if (logalot) { console.log(`${lc} already rel8d to all incoming ibGib(s) via tjp. (I: 5e9d94a98ba262f146c0c0b765157922)`); }\n                return; /* <<<< returns early */\n            }\n\n            // perform the raw ibgib rel8 transform\n            const addrs = ibGibsNotYetRel8dByTjp.map(x => getIbGibAddr({ ibGib: x }));\n            const resNewThis = await rel8({\n                src: this.toIbGibDto(),\n                rel8nsToAddByAddr: { [rel8nName]: addrs },\n                linkedRel8ns: linked ? [\"past\", \"ancestor\", rel8nName] : [\"past\", \"ancestor\"],\n                dna: true,\n                nCounter: true,\n            });\n            const newThisIbGib = resNewThis.newIbGib as any as IbGib_V1<TData, TRel8ns>;\n            const newThisValidationErrors =\n                await validateIbGibIntrinsically({ ibGib: newThisIbGib as any });\n            if (newThisValidationErrors?.length ?? 0 > 0) { throw new Error(`new this ibgib would have validation errors. aborting. newThisValidationErrors: ${newThisValidationErrors!.join('|')} (E: eb816a27156c246c121ef55e37d59322)`); }\n\n            // if space is given, perform the persistence\n            // if (space) {\n            await metaspace.persistTransformResult({ resTransform: resNewThis });\n            // } else {\n            //     if (logalot) { console.log(`${lc} space falsy, skipping persistence (I: 90aa3553e92ad1d02bce61f83648ea22)`); }\n            // }\n\n            // update this witness' primary ibGib properties (ib, gib, data, rel8ns).\n            //   override `loadIbGibDto` to update secondary/derivative properties\n            await this.loadIbGibDto(newThisIbGib);\n\n            // (in the future, need to revisit the ibgibs service to the idea of locality/ies).\n            await metaspace.registerNewIbGib({ ibGib: newThisIbGib });\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    protected async rel8ToContextIbGib({\n        ibGibToRel8,\n        ibGibAddrToRel8,\n        contextIbGib,\n        rel8nNames,\n        // space,\n    }: {\n        ibGibToRel8?: IbGib_V1,\n        ibGibAddrToRel8?: IbGibAddr,\n        contextIbGib: IbGib_V1,\n        rel8nNames: string[],\n        // space?: IbGibSpaceAny,\n    }): Promise<void> {\n        const lc = `${this.lc}[${this.rel8ToContextIbGib.name}]`;\n        try {\n            if (!ibGibToRel8 && !ibGibAddrToRel8) { throw new Error(`ibGibToRel8 or ibGibAddrToRel8 required (E: 3ee14659fd22355a5ba0e537a477be22)`); }\n            if (!contextIbGib) { throw new Error(`contextIbGib required (E: 85f27c7cbf713704c21084c141cd8822)`); }\n            if (!this.metaspace) { throw new Error(`this.metaspace required (E: 6a38c4274bdefc8d44cafd2d6faaa222)`); }\n\n            // space = space ?? await this.metaspace.getLocalUserSpace({ lock: true });\n            // if (!space) { throw new Error(`space required (E: 267ad87c148942cda641349df0bbbd22)`); }\n\n            if ((rel8nNames ?? []).length === 0) {\n                if (!this.data?.defaultRel8nName) { throw new Error(`either rel8nNames or this.data.defaultRel8nName required (E: a14ab4b3e479d9274c61bc5a30bc2222)`); }\n                rel8nNames = [this.data.defaultRel8nName];\n            }\n\n            // set up the rel8ns to add\n            const rel8nsToAddByAddr: IbGibRel8ns_V1 = {};\n            ibGibAddrToRel8 = ibGibAddrToRel8 || getIbGibAddr({ ibGib: ibGibToRel8 });\n            rel8nNames.forEach((rel8nName) => { rel8nsToAddByAddr[rel8nName] = [ibGibAddrToRel8!]; });\n\n            // perform the rel8 transform and...\n            const resRel8ToContext =\n                await rel8({\n                    src: contextIbGib,\n                    rel8nsToAddByAddr,\n                    dna: true,\n                    nCounter: true\n                });\n\n            // ...persist it...\n            await this.metaspace.persistTransformResult({ resTransform: resRel8ToContext });\n\n            // ...register the context.\n            const { newIbGib: newContext } = resRel8ToContext;\n            await this.metaspace.registerNewIbGib({ ibGib: newContext });\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        }\n    }\n\n    protected async createCommentAndRel8ToContextIbGib({\n        text,\n        contextIbGib,\n        rel8nName,\n    }: {\n        text: string,\n        contextIbGib: IbGib_V1,\n        rel8nName: string,\n        metaspace?: MetaspaceService,\n    }): Promise<void> {\n        const lc = `${this.lc}[${this.createCommentAndRel8ToContextIbGib.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: c3a005f7d323468a5b4e1b2710901d22)`); }\n\n            if (!this.metaspace) { throw new Error(`this.metaspace required (E: 5dbb1a7f0ff5469b8ce3cb1be175e521)`); }\n\n            // space = space ?? await this.metaspace.getLocalUserSpace({ lock: true });\n            // if (!space) { throw new Error(`(UNEXPECTED) space required and wasn't able to get it from metaspace? (E: 7159f9893a66c28a7e09b61384545622)`); }\n            let space = await this.metaspace.getLocalUserSpace({ lock: true });\n\n            /** tag this comment with metadata to show it came from this witness */\n            let resComment = await createCommentIbGib({ text, addlMetadataText: this.getAddlMetadata(), saveInSpace: true, space });\n\n            // get again to be sure it's the latest space.\n            space = await this.metaspace.getLocalUserSpace({ lock: true });\n\n            const commentIbGib = resComment.newIbGib as CommentIbGib_V1;\n            if (!commentIbGib) { throw new Error(`(UNEXPECTED) failed to create comment? (E: 6d668f4e55198e654324622eabaac922)`); }\n            await this.metaspace.registerNewIbGib({ ibGib: commentIbGib });\n\n            await this.rel8ToContextIbGib({ ibGibToRel8: commentIbGib, contextIbGib, rel8nNames: ['comment'] });\n            await this.rel8To({\n                ibGibs: [commentIbGib],\n                rel8nName,\n            });\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * I'm abstracting getAddlMetadata and for a robbot witness the first part\n     * is atow  \"robbot\", e.g., * `robbot_classname_id_etc`. So \"ThisAtom\" is\n     * \"robbot\" for a robbot.\n     *\n     * override this in descending classes per use case.\n     *\n     * by default, this returns a safe substring of this.data.classname or \"this\".\n     */\n    protected getThisAtom(): string {\n        return getSaferSubstring({ text: this.data?.classname ?? 'this', length: 16 });\n    }\n\n    /**\n     * used to help identify when comments are made by descending witnesses.\n     *\n     * override this with your particular use case's addl metadata.\n     *\n     * @example atow robbot is: `robbot_${this.data.classname}_${this.data.name}_${this.data.uuid.slice(0, 8)}`;\n     *\n     * @returns addlmetadata string to be used in comment ib's\n     */\n    protected getAddlMetadata(): string {\n        const lc = `${this.lc}[${this.getAddlMetadata.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 7800732facf3783943fdf1b2423b0c22)`); }\n            if (!this.data) { throw new Error(`(UNEXPECTED) this.data falsy? (E: 7cb044b39b2b8e31f363f3b82f256323)`); }\n            const atom = this.getThisAtom();\n            if (!atom) { throw new Error(`(UNEXPECTED) atom couldn't be gotten? (E: b260de391356e04abd334e0cd8b09123)`); }\n            if (atom.includes(' ')) { throw new Error(`(UNEXPECTED) atom contains space? (E: 574d088eea13d3afe5fcd2999ab6b423)`); }\n            const classnameIsh = this.data.classname?.replace(/[_]/mg, '') || undefined;\n            const nameIsh = this.data.name?.slice(0, 8).replace(/[__]/mg, '') || undefined;\n            const idIsh = this.data.uuid?.slice(0, 8) || undefined;\n            const addlMetadataText = `${atom}_${classnameIsh}_${nameIsh}_${idIsh}`;\n            if (logalot) { console.log(`${lc} addlMetadataText: ${addlMetadataText} (I: 53c0044671dc99fb75635367d2e63c22)`); }\n            return addlMetadataText;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * override this in concrete class for addlMetadata used (if used)...\n     *\n     * Also be sure to override `getAddlMetadata` (if used)\n     *\n     * ## notes\n     *\n     * I'm refactoring and this may need to come out, but it's used in RobbotBase atow.\n     */\n    protected abstract parseAddlMetadataString<TParseResult>({ ib }: { ib: Ib }): TParseResult;\n\n    /**\n     * I originally created this just to extract the context from the arg, but\n     * I'm reusing it to get the latest context from the addr alone.\n     */\n    protected async getContextIbGibFromArgOrAddr({\n        arg,\n        addr,\n        latest,\n    }: {\n        arg?: WitnessArgIbGib<IbGib_V1, TData, TRel8ns>,\n        addr?: IbGibAddr,\n        /**\n         * if true, after extracting the context from the arg, will get the\n         * latest ibgib (if there is a newer version).\n         */\n        latest?: boolean,\n    }): Promise<IbGib_V1> {\n        const lc = `${this.lc}[${this.getContextIbGibFromArgOrAddr.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: c13f7cb92133984048f606075efb8a22)`); }\n            let contextIbGib: IbGib_V1;\n            if (!arg && !addr) { throw new Error(`either arg or addr required. (E: 3f647b65742242fd9ba878521acf7c22)`); }\n            if (!this.metaspace) { throw new Error(`(UNEXPECTED) this.metaspace required (E: f0046290b0d66d28c4bbbf83d9d9f523)`); }\n            if (arg) {\n                if ((arg.ibGibs ?? []).length === 0) { throw new Error(`(UNEXPECTED) invalid arg? no context ibgib on arg (E: 89997eb4bdeb3885bee9de5d33ee0f22)`); }\n                if ((arg.ibGibs ?? []).length !== 1) { throw new Error(`(UNEXPECTED) invalid arg? only expected one ibgib on arg.ibGibs (E: 1a1498af668740fe9439f4953a74ea8a)`); }\n                contextIbGib = arg.ibGibs![0];\n            } else {\n                // addr provided\n                const resGet = await this.metaspace.get({ addr });\n                if (!resGet.success || resGet.ibGibs?.length !== 1) { throw new Error(`could not get context addr (${addr}) (E: 834492313512a45b23a7bebacdc48122)`); }\n                contextIbGib = resGet.ibGibs[0];\n            }\n\n            if (latest) {\n                const resLatestAddr = await this.metaspace.getLatestAddr({ ibGib: contextIbGib });\n                if (resLatestAddr !== getIbGibAddr({ ibGib: contextIbGib })) {\n                    const resGet = await this.metaspace.get({ addr: resLatestAddr });\n                    if (resGet.success && resGet.ibGibs?.length === 1) {\n                        contextIbGib = resGet.ibGibs[0];\n                    } else {\n                        throw new Error(`unable to get resLatestAddr (${resLatestAddr}) (E: ce1e1297743e9a16c8f082321e52a122)`);\n                    }\n                }\n            }\n            return contextIbGib;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * The context is the ibgib where we are interacting with the user(s).\n     *\n     * When we initialize, we are setting state on this witness as well as\n     * subscribing to the context ibgib's updates in `this.metaspace`.\n     *\n     * if we already have a context, then this will check the new incoming\n     * context against it.  If it's the same timeline, then this won't do\n     * anything. Otherwise, it will finalize the previous context.\n     */\n    protected async initializeContext({\n        arg,\n        contextIbGib,\n        rel8nName,\n    }: {\n        /**\n         * If the context ibgib is wrapped in an arg, just pass in the arg and\n         * this will unwrap.\n         *\n         * don't use this if you already have access to `contextIbGib` itself.\n         */\n        arg?: WitnessArgIbGib<IbGib_V1, TData, TRel8ns>,\n        /**\n         * \"Raw\" (i.e. not wrapped in a WitnessArgIbGib) context ibgib that\n         * we're initializing with.\n         *\n         * If you already have access to this context, use this. Do not use both\n         * this and the `arg`.\n         */\n        contextIbGib?: IbGib_V1,\n        /**\n         * If provided, will rel8 the context to this witness upon initialize completion.\n         *\n         * todo: refactor this to not have this in this function. I have this in here\n         * to trigger a compilation error\n         *\n         * originally this function was inside a robbot and part of the init is to rel8\n         * the context to the robbot to say it's taking part in that conversation context.\n         */\n        rel8nName: string,\n    }): Promise<void> {\n        const lc = `${this.lc}[${this.initializeContext.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: d93429c85b0a494388f66fba3eece922)`); }\n            if (!this.metaspace) { throw new Error(`this.metaspace (metaspace) required. set this before using this witness. (E: 67db388a0223bf813b40accd9941ad23)`); }\n            if (arg && contextIbGib) {\n                console.warn(`${lc} both arg and contextIbGib provided. using raw contextIbGib (W: d6d723ad7fb942079833c40647aecd22)`);\n            }\n\n            // get context from arg just to compare the tjp's so we don't need\n            // the latest at this point\n            const incomingContext_NotLatest =\n                contextIbGib ?? await this.getContextIbGibFromArgOrAddr({ arg, latest: false });\n            if (this._currentWorkingContextIbGib) {\n                let currentTjpAddr = getTjpAddr({ ibGib: this._currentWorkingContextIbGib });\n                const incomingTjpAddr = getTjpAddr({ ibGib: incomingContext_NotLatest })\n                if (currentTjpAddr === incomingTjpAddr) {\n                    if (logalot) { console.warn(`${lc} initializing context but it's the same timeline (${currentTjpAddr}). (W: 7609f8f51172443183e0c93ad52bfe56)`); }\n                    return;\n                } else {\n                    await this.finalizeContext({ arg });\n                }\n            }\n\n            /** used both now and when context ibgib is updated via observable */\n            const updatePriorChildren = () => {\n                this._currentWorkingContextIbGib_PriorChildrenAddrs = [\n                    ...this._currentWorkingContextIbGib?.rel8ns?.comment ?? [],\n                    ...this._currentWorkingContextIbGib?.rel8ns?.pic ?? [],\n                    ...this._currentWorkingContextIbGib?.rel8ns?.link ?? [],\n                ];\n            };\n\n            // set the props\n            this._currentWorkingContextIbGib = contextIbGib ?\n                await this.getContextIbGibFromArgOrAddr({\n                    addr: getIbGibAddr({ ibGib: contextIbGib }),\n                    latest: true\n                }) :\n                await this.getContextIbGibFromArgOrAddr({ arg, latest: true });\n            updatePriorChildren();\n\n            // subscribe to context ibgib updates\n            const contextTjpAddr = getTjpAddr({ ibGib: this._currentWorkingContextIbGib });\n            if (!this.metaspace) { throw new Error(`(UNEXPECTED) this.metaspace falsy...not initialized? (E: 6e38bfdc5c2eb5fef884f0183889e823)`); }\n            if (!this.metaspace.latestObs) { throw new Error(`(UNEXPECTED) this.metaspace.latestObs falsy? (E: 831936570c14ed526f9c9ab511929923)`); }\n            this._contextChangesSubscription =\n                await this.metaspace.latestObs\n                    // .pipe(\n                    //     filter(x => x.tjpAddr === contextTjpAddr)\n                    // ).subscribe(async (update: any) => {\n                    .subscribe(fnObs({\n                        next: async (update) => {\n                            const lcNext = `${lc}[latestObs.next]`;\n                            // acts like a poor man's `filter` operator on this observerable\n                            if (update.tjpAddr !== contextTjpAddr) { return; /* <<<< returns early */ }\n\n                            const currentAddr = getIbGibAddr({ ibGib: this._currentWorkingContextIbGib });\n                            if (update.latestAddr !== currentAddr) {\n                                if (logalot) { console.warn(`${lcNext} checking if new context is actually new...damn getLatestAddr maybe not working in ionic space... argh (W: 3d1a12154dfafb9c96d07e6f75f7a322)`); }\n                                if (update.latestIbGib) {\n                                    let latestN_Supposedly = update.latestIbGib.data?.n ?? -1;\n                                    let currentN = this._currentWorkingContextIbGib?.data?.n ?? -2;\n                                    if (latestN_Supposedly <= currentN) {\n                                        console.warn(`${lcNext} latestN is not really the latest. latestN_Supposedly: ${latestN_Supposedly}, currentN: ${currentN}. (tjpGib: ${update.tjpAddr}) (W: 6792c9a596c44c03b262614ae79a715e)`)\n                                        return; /* <<<< returns early */\n                                    }\n                                }\n                                if (logalot) { console.log(`${lcNext} update to context.\\ncurrentAddr: ${currentAddr}\\nlatestAddr: ${update.latestAddr} (I: d0adcc392e6e974c9917730ebad51322)`); }\n                                this._currentWorkingContextIbGib =\n                                    update.latestIbGib ??\n                                    await this.getContextIbGibFromArgOrAddr({ addr: update.latestAddr, latest: false }); // already latest\n                                if (!this._updatingContext) {\n                                    await this.handleContextUpdate({ update });\n                                    updatePriorChildren();\n                                } else {\n                                    if (logalot) { console.log(`${lcNext} already updating context (I: f856f9414627ab00418dccd285b55822)`); }\n                                }\n                            }\n                        },\n                        error: async (err) => {\n                            const lcErr = `${lc}[latestObs.error]`;\n                            console.error(`${lcErr} this.metaspace.latestObs error: ${extractObsErrMsg({ err })}. (E: 99df4c42195d46d0a9dbfb06ac45ae00)`)\n                        },\n                    }));\n\n            // rel8 to the context (conversation)\n\n            if (rel8nName) {\n                await this.rel8To({\n                    ibGibs: [this._currentWorkingContextIbGib],\n                    rel8nName,\n                });\n            }\n\n            // subscribe to receive updates to the context so we can participate\n            // in the conversation (i.e. interpret incoming ibgibs like commands\n            // if needed)\n            // let gibInfo = getGibInfo({ gib: this._currentWorkingContextIbGib.gib });\n            // if (gibInfo.tjpGib) {\n            //     this.metaspace.latestObs\n            //         .subscribe(update => {\n            //             if (!update.tjpAddr) { return; /* <<<< returns early */ }\n            //             if (getIbAndGib({ ibGibAddr: update.tjpAddr }).gib !== gibInfo.tjpGib) { return; /* <<<< returns early */ }\n            //             if (update.latestAddr === getIbGibAddr({ ibGib: this._currentWorkingContextIbGib })) {\n            //                 if (logalot) { console.log(`${lc} already have that context... (I: a6e17ec40d620f0bd5b231db39eaa522)`); }\n            //                 return; /* <<<< returns early */\n            //             }\n            //             if (this._updatingContext) {\n            //                 if (logalot) { console.log(`${lc} already updating context (I: f856f9414627ab00418dccd285b55822)`); }\n            //                 return; /* <<<< returns early */\n            //             }\n            //             this.handleContextUpdate({ update });\n            //         });\n            // }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    protected async finalizeContext({\n        arg,\n    }: {\n        arg: WitnessArgIbGib<IbGib_V1, TData, TRel8ns> | undefined,\n    }): Promise<void> {\n        const lc = `${this.lc}[${this.finalizeContext.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: dd53dfc745864dd19fde5f209ceb82c8)`); }\n\n\n            let tries = 0;\n            const maxTries = 100;\n            while (this._updatingContext && tries < maxTries) {\n                await delay(100);\n                tries++;\n                if (tries % 10 === 0) {\n                    console.log(`${lc} already updating context and taking a litle while... waiting still. tries: ${tries}/${maxTries} (I: d45ab59af9ea43518432e34ddad95c19)`)\n                }\n            }\n            if (this._updatingContext) {\n                console.error(`${lc} previous call to updatingContext took too long. Ignoring flag and finalizing context. (E: 9a2dc4e1923442fa90fbeae72f358acd)`);\n            }\n\n            this._updatingContext = true;\n            if (this._contextChangesSubscription) {\n                await this._contextChangesSubscription.unsubscribe();\n                delete this._contextChangesSubscription;\n            }\n            delete this._currentWorkingContextIbGib;\n\n            throw new Error(`not refactored yet. the proceeding code needs to be introduced in the robbot descending class. (E: 066aa414693672d868dbf953617aab23)`);\n            // if (this._currentWorkingContextIbGib) {\n            //     await this.createCommentAndRel8ToContextIbGib({\n            //         text: await this.getOutputText({ text: 'end of line' }),\n            //         contextIbGib: this._currentWorkingContextIbGib,\n            //     });\n            //     delete this._currentWorkingContextIbGib;\n            // }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            this._updatingContext = false;\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * Handles a new ibgib in the current working context.\n     *\n     * If it originated from the witness itself, then we will ignore it.\n     * Otherwise, for robbot witnesses, this is interpreted either as a\n     * \"command\" or something to remember.\n     *\n     * ## notes\n     *\n     * If the user says something and we're listening (this is triggered), then\n     * it should be either interpreted as a \"command\" or ignored. I put\n     * \"command\" in quotes because the word is a very short-sighted\n     * understanding of the conversational aspect. Or perhaps I speak to the\n     * connotations to current belief's regarding robbots and commands.\n     *\n     * This is complicated by the possibility in the future of multiple robbots\n     * being engaged in a conversation within the same context.\n     */\n    protected async handleContextUpdate({ update }: { update: IbGibTimelineUpdateInfo }): Promise<void> {\n        const lc = `${this.lc}[${this.handleContextUpdate.name}]`;\n        // I don't see this as really being very likely in the near future,\n        // but putting in a wait delay in case there are multiple updates\n        while (this._updatingContext) {\n            console.warn(`${lc} already updating context? delaying... (W: 19d2ebeaaf2340fb91a7d6c717e9cb41)`);\n            await delay(1000);\n        }\n        this._updatingContext = true;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 3eeaa40cad49094f125f9f5cd6ff6e22)`); }\n\n            // if it's caused by this robbot speaking, then we don't really need\n            // it. but if it's from the user, then we want to respond.\n            if (logalot) {\n                console.log(`${lc} update: (I: ad0abae7de472e3b4d3891ea0b937322)`);\n                console.table(update);\n            }\n            if (!update.latestIbGib) {\n                debugger; // before error\n                throw new Error(`(UNEXPECTED) update.latestIbGib falsy? (E: e18a048d7e95757238396ddd84748f22)`);\n            }\n\n            const newContext = update.latestIbGib;\n            const newChildrenIbGibs = await this.getNewChildrenIbGibs({ newContext });\n            // should normally be just one (would be very edge casey if not atow)\n            // 05/2025 - making it iterate through each new child because this is happening downstream in blank-gib app when dealing with talking with agents within an ibgib context. So the ibgib is added to the context, then the agent hears this and immediately responds within the broadcast handler. now there are two new children by the time we get to this point in code. So this could be brittle, I dunno. Probably need a better pubsub service, but hey, what are ya gonna do when only one fing person is working on something that could be worth so much fing money. but i'm not bitter... ^-^/\n            if (newChildrenIbGibs.length === 1) {\n                const newChild = newChildrenIbGibs[0];\n                // we have a single new child in the context.\n                await this.handleNewContextChild({ newChild, });\n\n            } else if (newChildrenIbGibs.length > 1) {\n                // we multiple new children. iterate\n                console.warn(`${lc} (UNEXPECTED) multiple new children in context update. iterating through each one. (W: 02d82a8f755f418d95fa30f0f52ad58e)`);\n                for (const newChild of newChildrenIbGibs) {\n                    await this.handleNewContextChild({ newChild, });\n                }\n            } else {\n                // no new children, so maybe the user deleted something or who knows.\n                if (logalot) { console.log(`${lc} no new children in context update. returning early... (I: 31397b04965351ab29bb3f78cb709122)`); }\n                return; /* <<<< returns early */\n            }\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            this._updatingContext = false;\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    async getNewChildrenIbGibs({ newContext }: { newContext: IbGib_V1 }): Promise<IbGib_V1[]> {\n        const lc = `${this.lc}[${this.getNewChildrenIbGibs.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 1b3d1cf908489087fa3b281f55b9a522)`); }\n            // get a diff of the new addrs vs. the old addrs.\n            /** all of the children addrs of the new context */\n            const newContextChildrenAddrs = [\n                ...newContext.rel8ns?.comment ?? [],\n                ...newContext.rel8ns?.pic ?? [],\n                ...newContext.rel8ns?.link ?? [],\n            ];\n            /** just the new addrs from the context  */\n            const newChildrenAddrs = newContextChildrenAddrs.filter(x =>\n                !this._currentWorkingContextIbGib_PriorChildrenAddrs.includes(x)\n            );\n            if (newChildrenAddrs.length === 0) {\n                // no new children\n                if (logalot) { console.log(`${lc} no new children addrs in newContext. returning early... (I: 8f9c3658c194c472cb1e2bc19d847b22)`); }\n                return []; /* <<<< returns early */\n            }\n\n            // get the latest addrs for those children\n            if (!this.metaspace) { throw new Error(`this.metaspace falsy. not initialized? (E: 1cc26ca7de7fadcdbaecbd6613350e23)`); }\n            const space = await this.metaspace.getLocalUserSpace({});\n            if (!space) { throw new Error(`couldn't get local user space? (E: f118f75e5852fc22bba3a6495beec723)`); }\n            const resLatestAddrs = await getLatestAddrs({ addrs: newChildrenAddrs, space, });\n            const latestAddrs = Object.values(resLatestAddrs?.data?.latestAddrsMap ?? {});\n            if (!resLatestAddrs?.data?.success || latestAddrs.length !== newChildrenAddrs.length) { throw new Error(`could not get latest addrs. (E: 2e1619e7e2e166696fe8ff78cb02cc22)`); }\n\n            // get the addrs' corresponding ibgibs\n            if (latestAddrs.some(x => x === null)) {\n                // some of the addrs were not found in the space\n                throw new Error(`some addrs were not found in the space. (E: 2216d8e5ad7fb600ceb025ed7c90f323)`);\n            }\n            const resGet = await this.metaspace.get({ addrs: latestAddrs as IbGibAddr[] });\n            if (!resGet.success || resGet.ibGibs?.length !== newChildrenAddrs.length) {\n                throw new Error(`failed to get newChildren with addrs: ${newChildrenAddrs.join('|')}. Error: ${resGet.errorMsg ?? 'unknown error 5737bd0996d5445b8bd80975bedc0d57'} (E: 05722e11350ec6ffffdb5c7d0caa2922)`);\n            }\n\n            return resGet.ibGibs;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    protected async handleNewContextChild({\n        newChild,\n    }: {\n        newChild: IbGib_V1,\n    }): Promise<void> {\n        const lc = `${this.lc}[${this.handleNewContextChild.name}]`;\n        try {\n            throw new Error(`not implemented in base class (E: ea6b2b13d9504d93b33b70191d106084)`);\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        }\n    }\n\n}\n\n// export interface IbGibRobbotAny\n//     extends RobbotBase_V1<any, any, any, any, any, any, any, any> {\n// }\n", "/**\n * @module subject constants\n *\n * witness constants are in this file!\n */\n\n// /**\n//  * example enum-like type+const that I use in ibgib. sometimes i put\n//  * these in the types.mts and sometimes in the const.mts, depending\n//  * on context.\n//  */\n// export type SomeEnum =\n//     'ib' | 'gib';\n// export const SomeEnum = {\n//     ib: 'ib' as SomeEnum,\n//     gib: 'gib' as SomeEnum,\n// } satisfies { [key: string]: SomeEnum };\n// export const SOME_TYPE_VALUES: SomeEnum[] = Object.values(SomeEnum);\n\n/**\n * atom used in ibs\n */\nexport const SUBJECT_ATOM = 'subject';\n\n/**\n * default regexp for a simple name string.\n */\nexport const SUBJECT_NAME_REGEXP = /^[a-zA-Z0-9_\\-.]{1,255}$/;\n\nexport const DEFAULT_NAME_SUBJECT = 'subject';\nexport const DEFAULT_UUID_SUBJECT = '';\nexport const DEFAULT_DESCRIPTION_SUBJECT = 'subject is a cool ibgib witness that has seriously fascinating behavior.';\n", "/**\n * @module observable constants\n *\n * witness constants are in this file!\n */\n\n// /**\n//  * example enum-like type+const that I use in ibgib. sometimes i put\n//  * these in the types.mts and sometimes in the const.mts, depending\n//  * on context.\n//  */\n// export type SomeEnum =\n//     'ib' | 'gib';\n// export const SomeEnum = {\n//     ib: 'ib' as SomeEnum,\n//     gib: 'gib' as SomeEnum,\n// } satisfies { [key: string]: SomeEnum };\n// export const SOME_TYPE_VALUES: SomeEnum[] = Object.values(SomeEnum);\n\n/**\n * atom used in ibs\n */\nexport const OBSERVABLE_ATOM = 'observable';\n\n/**\n * default regexp for a simple name string.\n */\nexport const OBSERVABLE_NAME_REGEXP = /^[a-zA-Z0-9_\\-.]{1,255}$/;\n\nexport const DEFAULT_UUID_OBSERVABLE = '';\nexport const DEFAULT_NAME_OBSERVABLE = 'observable';\nexport const DEFAULT_DESCRIPTION_OBSERVABLE = 'observable is a cool ibgib witness that has seriously fascinating behavior. this is an ibgibiffied pubsub implementation.';\n", "/**\n * @module observable types (and some enums/constants)\n */\n\nimport { IbGibAddr } from '@ibgib/ts-gib/dist/types.mjs';\nimport { IbGibData_V1, IbGibRel8ns_V1, IbGib_V1 } from '@ibgib/ts-gib/dist/V1/types.mjs';\nimport { WitnessWithContextData_V1, WitnessWithContextRel8ns_V1 } from '../../../witness/witness-with-context/witness-with-context-types.mjs';\nimport { WitnessCmdData, WitnessCmdIbGib, WitnessCmdRel8ns } from '../../../witness/witness-cmd/witness-cmd-types.mjs';\nimport { Witness, WitnessAny, WitnessFn, WitnessResultData, WitnessResultIbGib, WitnessResultRel8ns } from '../../../witness/witness-types.mjs';\nimport { DEFAULT_DESCRIPTION_OBSERVABLE, DEFAULT_NAME_OBSERVABLE, DEFAULT_UUID_OBSERVABLE } from './observable-constants.mjs';\nimport { SubscriptionIbGib_V1, SubscriptionWitness } from '../subscription/subscription-types.mjs';\nimport { Subscription_V1 } from '../subscription/subscription-v1.mjs';\nimport { ErrorIbGib_V1 } from '../../error/error-types.mjs';\nimport { ROOT } from '@ibgib/ts-gib/dist/V1/constants.mjs';\nimport { ObserverWitness } from '../observer/observer-types.mjs';\n// and just to show where these things are\n// import { CommentIbGib_V1 } from \"@ibgib/core-gib/dist/common/comment/comment-types.mjs\";\n// import { MetaspaceService } from \"@ibgib/core-gib/dist/witness/space/metaspace/metaspace-types.mjs\";\n\n// /**\n//  * example enum-like type+const that I use in ibgib. sometimes i put\n//  * these in the types.mts and sometimes in the const.mts, depending\n//  * on context.\n//  */\n// export type SomeEnum =\n//     'ib' | 'gib';\n// /**\n//  * @see {@link SomeEnum}\n//  */\n// export const SomeEnum = {\n//     ib: 'ib' as SomeEnum,\n//     gib: 'gib' as SomeEnum,\n// } satisfies { [key: string]: SomeEnum };\n// /**\n//  * values of {@link SomeEnum}\n//  */\n// export const SOME_ENUM_VALUES: SomeEnum[] = Object.values(SomeEnum);\n\n/**\n * ibgib's intrinsic data goes here.\n *\n * @see {@link IbGib_V1.data}\n */\nexport interface ObservableData_V1 extends WitnessWithContextData_V1 {\n    // ibgib data (settings/values/etc) goes here\n    // /**\n    //  * docs yo\n    //  */\n    // setting: string;\n    /**\n     * if true, will replay previous events when subscribed.\n     */\n    replay?: boolean;\n}\n\n/**\n * rel8ns (named edges/links in DAG) go here.\n *\n * @see {@link IbGib_V1.rel8ns}\n */\nexport interface ObservableRel8ns_V1 extends WitnessWithContextRel8ns_V1 {\n    // /**\n    //  * required rel8n. for most, put in observable-constants.mts file\n    //  *\n    //  * @see {@link REQUIRED_REL8N_NAME}\n    //  */\n    // [REQUIRED_REL8N_NAME]: IbGibAddr[];\n    // /**\n    //  * optional rel8n. for most, put in observable-constants.mts file\n    //  *\n    //  * @see {@link OPTIONAL_REL8N_NAME}\n    //  */\n    // [OPTIONAL_REL8N_NAME]?: IbGibAddr[];\n}\n\n/**\n * this is the ibgib object itself.\n *\n * If this is a plain ibgib data only object, this acts as a dto. You may also\n * want to generate a witness ibgib, which is slightly different, for ibgibs\n * that will have behavior (i.e. methods).\n *\n * @see {@link ObservableData_V1}\n * @see {@link ObservableRel8ns_V1}\n */\nexport interface ObservableIbGib_V1 extends IbGib_V1<ObservableData_V1, ObservableRel8ns_V1> {\n\n}\n\n/**\n * Cmds for interacting with ibgib witnesses.\n\n * @see const {@link ObservableCmd} for individual jsdocs\n */\nexport type ObservableCmd =\n    'subscribe';\n/** Cmds for interacting with ibgib spaces. */\nexport const ObservableCmd = {\n    /**\n     * subscribe to the observable\n     */\n    subscribe: 'subscribe' as ObservableCmd,\n}\nexport const OBSERVABLE_CMD_VALUES: ObservableCmd[] = Object.values(ObservableCmd);\n\n/**\n * Flags to affect the command's interpretation.\n *\n * atow 11/2023 not used\n */\nexport type ObservableCmdModifier =\n    'ib' | 'gib' | 'ibgib';\n/**\n * Flags to affect the command's interpretation.\n *\n * atow 11/2023 not used\n */\nexport const ObservableCmdModifier = {\n    /**\n     * hmm...\n     */\n    ib: 'ib' as ObservableCmdModifier,\n    /**\n     * hmm...\n     */\n    gib: 'gib' as ObservableCmdModifier,\n    /**\n     * hmm...\n     */\n    ibgib: 'ibgib' as ObservableCmdModifier,\n}\n\n/** Information for interacting with spaces. */\nexport interface ObservableCmdData\n    extends WitnessCmdData<ObservableCmd, ObservableCmdModifier> {\n}\n\nexport interface ObservableCmdRel8ns extends WitnessCmdRel8ns {\n}\n\n/**\n * Shape of options ibgib if used for a command-based witness.\n */\nexport interface ObservableCmdIbGib\n    extends WitnessCmdIbGib<\n        IbGib_V1,\n        ObservableCmd, ObservableCmdModifier,\n        ObservableCmdData, ObservableCmdRel8ns\n    > {\n}\n\n/**\n * Optional shape of result data to witness interactions.\n *\n * This is in addition of course to {@link ObservableResultData}.\n *\n * so if you're sending a cmd to this witness, this should probably be the shape\n * of the result.\n *\n * ## notes\n *\n * * I'm not sure what to do with this atm, so I'm just stubbing out...\n */\nexport interface ObservableResultData extends WitnessResultData {\n}\n\n/**\n * Marker interface rel8ns atm...\n *\n * so if you're sending a cmd to this witness, this should probably be the shape\n * of the result.\n *\n * I'm not sure what to do with this atm, so I'm just stubbing out...\n */\nexport interface ObservableResultRel8ns extends WitnessResultRel8ns { }\n\n/**\n * Shape of result ibgib if used for a witness.\n *\n * so if you're sending a cmd to this witness, this should probably be the shape\n * of the result.\n *\n * I'm not sure what to do with this atm, so I'm just stubbing out...\n */\nexport interface ObservableResultIbGib\n    extends WitnessResultIbGib<IbGib_V1, ObservableResultData, ObservableResultRel8ns> {\n}\n\n/**\n * shape of underscore-delimited addl metadata string that may be present in the\n * ib (i.e. available when parsing the ib)\n *\n * This is not hard and fast and can (and should?) vary greatly per use case.\n */\nexport interface ObservableAddlMetadata {\n    /**\n     * should be observable\n     */\n    atom?: 'observable'\n    /**\n     * classname of observable **with any underscores removed**.\n     */\n    classnameIsh?: string;\n    /**\n     * name of observable witness (data.name) **with any underscores removed**.\n     */\n    nameIsh?: string;\n    /**\n     * id of witness (data.uuid) **with any underscores removed**.\n     *\n     * may be a substring per use case...?\n     */\n    idIsh?: string;\n}\n\n/**\n * Default data values for a Observable.\n *\n * If you change this, please bump the version\n *\n * (but of course won't be the end of the world when this doesn't happen).\n */\nexport const DEFAULT_OBSERVABLE_DATA_V1: ObservableData_V1 = {\n    version: '1',\n    uuid: DEFAULT_UUID_OBSERVABLE,\n    name: DEFAULT_NAME_OBSERVABLE,\n    description: DEFAULT_DESCRIPTION_OBSERVABLE,\n    classname: `Observable_V1`,\n\n    /**\n     * if true, then the witness will attempt to persist ALL calls to\n     * `witness.witness(...)`.\n     */\n    persistOptsAndResultIbGibs: false,\n    /**\n     * allow ibgibs like 42^gib ({ib: 42, gib: 'gib'} with `data` and `rel8ns` undefined)\n     */\n    allowPrimitiveArgs: true,\n    /**\n     * witnesses should be guaranteed not to throw uncaught exceptions.\n     */\n    catchAllErrors: false,\n    /**\n     * if true, would enable logging of all calls to `witness.witness(...)`\n     */\n    trace: false,\n\n    // put in your custom defaults here\n}\nexport const DEFAULT_OBSERVABLE_REL8NS_V1: ObservableRel8ns_V1 | undefined = undefined;\n\n/**\n * v1 observABLE witness shape\n *\n * this is the \"future array\" that is being observed. it outputs a stream of\n * ibgibs, and can error and complete.\n *\n * @see {@link ObserverWitness}\n */\nexport interface ObservableWitness<\n    TIbGibIn_ie_Payload extends IbGib_V1 = IbGib_V1,\n    TIbGibOut_ie_ProbablyDontCare extends IbGib_V1 = IbGib_V1\n> extends WitnessAny {\n    get isCompleteOrErrored(): boolean;\n    get isComplete(): boolean;\n    get isErrored(): boolean;\n    /**\n     * primary function to subscribe to new\n     * @param witness ibgib to fire off when a new ibgib come downs the obsesrvable's pipe\n     */\n    subscribe(\n        observer: WitnessAny | ObserverWitness<TIbGibIn_ie_Payload>\n    ): Promise<SubscriptionWitness>;\n}\n\nexport interface ObservableWitnessAny extends ObservableWitness<any, any> { }\n", "/**\n * @module observer types (and some enums/constants)\n *\n * i don't have observers fleshed out like observables/subjects.\n *\n * i think this is more of list of shapes to be used by other concrete\n * observers, like subjects.\n */\n\nimport { IbGib_V1 } from '@ibgib/ts-gib/dist/V1/types.mjs';\nimport { Witness, WitnessAny, } from '../../../witness/witness-types.mjs';\nimport { ErrorIbGib_V1 } from '../../error/error-types.mjs';\n\n\n\n/**\n * Plain-jane, non-witness version of observer shape.\n *\n * note that even though this isn't witness-based, it still is mostly\n * concerned with ibgibs as args. Where there are non-ibgib args,\n * this should be converted in the concrete implementor to an ibgib-wrapped\n * arg and passed to the `witness` function.\n *\n * @see {@link ObserverWitness}\n */\nexport interface Observer<T extends IbGib_V1 = IbGib_V1> {\n    next(ibGib: T): Promise<void>;\n    /**\n     * @optional handler for an observable stream that produces an error.\n     * @param error error or error ibgib produced when observable errors out\n     */\n    error?(error: string | Error | ErrorIbGib_V1): Promise<void>;\n    complete?(): Promise<void>;\n}\n\n/**\n * v1 observER witness shape (as opposed to observABLE)\n *\n * this is the shape of the consumer's handler, usually an anonymous function.\n *\n * so when you subscribe to an observABLE witness, you pass in this shape which\n * will contain anonymous function ibgib witnesses.\n */\nexport interface ObserverWitness<TIbGibIn_ie_Payload extends IbGib_V1, TIbGibOut_ie_ProbablyDontCare extends IbGib_V1 = IbGib_V1>\n    extends WitnessAny, Observer<TIbGibIn_ie_Payload> {\n}\n\n/** Cmds for interacting with ibgib observer witnesses. */\nexport type ObserverCmd =\n    'next' | 'error' | 'complete';\n/** Cmds for interacting with ibgib observer witnesses. */\nexport const ObserverCmd = {\n    /**\n     * it's more like a grunt that is intepreted by context.\n     */\n    next: 'next' as ObserverCmd,\n    /**\n     * it's more like a grunt that is intepreted by context.\n     */\n    error: 'error' as ObserverCmd,\n    /**\n     * indicate to complete the observable\n     */\n    complete: 'complete' as ObserverCmd,\n}\n", "/**\n * @module subject types (and some enums/constants)\n */\n\nimport { IbGib_V1 } from '@ibgib/ts-gib/dist/V1/types.mjs';\n\nimport { WitnessCmdData, WitnessCmdIbGib, WitnessCmdRel8ns } from '../../../witness/witness-cmd/witness-cmd-types.mjs';\nimport { WitnessResultData, WitnessResultIbGib, WitnessResultRel8ns } from '../../../witness/witness-types.mjs';\nimport { DEFAULT_DESCRIPTION_SUBJECT, DEFAULT_NAME_SUBJECT, DEFAULT_UUID_SUBJECT } from './subject-constants.mjs';\nimport {\n    ObservableCmd,\n    ObservableData_V1, ObservableRel8ns_V1,\n    ObservableWitness,\n} from '../observable/observable-types.mjs';\nimport { ObserverCmd, ObserverWitness } from '../observer/observer-types.mjs';\n\n/**\n * ibgib's intrinsic data goes here.\n *\n * @see {@link IbGib_V1.data}\n */\nexport interface SubjectData_V1 extends ObservableData_V1 {\n    // ibgib data (settings/values/etc) goes here\n    // /**\n    //  * docs yo\n    //  */\n    // setting: string;\n}\n\n/**\n * rel8ns (named edges/links in DAG) go here.\n *\n * @see {@link IbGib_V1.rel8ns}\n */\nexport interface SubjectRel8ns_V1 extends ObservableRel8ns_V1 {\n    // /**\n    //  * required rel8n. for most, put in subject-constants.mts file\n    //  *\n    //  * @see {@link REQUIRED_REL8N_NAME}\n    //  */\n    // [REQUIRED_REL8N_NAME]: IbGibAddr[];\n    // /**\n    //  * optional rel8n. for most, put in subject-constants.mts file\n    //  *\n    //  * @see {@link OPTIONAL_REL8N_NAME}\n    //  */\n    // [OPTIONAL_REL8N_NAME]?: IbGibAddr[];\n}\n\n/**\n * this is the ibgib object itself.\n *\n * If this is a plain ibgib data only object, this acts as a dto. You may also\n * want to generate a witness ibgib, which is slightly different, for ibgibs\n * that will have behavior (i.e. methods).\n *\n * @see {@link SubjectData_V1}\n * @see {@link SubjectRel8ns_V1}\n */\nexport interface SubjectIbGib_V1 extends IbGib_V1<SubjectData_V1, SubjectRel8ns_V1> {\n\n}\n\n/**\n * Cmds for interacting with ibgib subject witnesses.\n *\n * this is atow (11/2023) the union of `ObservableCmd` and `ObserverCmd`.\n *\n * @see {ObservableCmd}\n * @see {ObserverCmd}\n * */\nexport type SubjectCmd =\n    ObservableCmd | ObserverCmd;\n/**\n * Cmds for interacting with ibgib subject witnesses.\n *\n * this is atow (11/2023) the union of `ObservableCmd` and `ObserverCmd`.\n *\n * @see {ObservableCmd}\n * @see {ObserverCmd}\n * */\nexport const SubjectCmd = {\n    ...ObservableCmd,\n    ...ObserverCmd,\n}\n\n/**\n * Flags to affect the command's interpretation.\n */\nexport type SubjectCmdModifier =\n    'ib' | 'gib' | 'ibgib';\n/**\n * Flags to affect the command's interpretation.\n */\nexport const SubjectCmdModifier = {\n    /**\n     * hmm...\n     */\n    ib: 'ib' as SubjectCmdModifier,\n    /**\n     * hmm...\n     */\n    gib: 'gib' as SubjectCmdModifier,\n    /**\n     * hmm...\n     */\n    ibgib: 'ibgib' as SubjectCmdModifier,\n}\n\n/** Information for interacting with spaces. */\nexport interface SubjectCmdData\n    extends WitnessCmdData<SubjectCmd, SubjectCmdModifier> {\n}\n\nexport interface SubjectCmdRel8ns extends WitnessCmdRel8ns {\n}\n\n/**\n * Shape of options ibgib if used for a command-based witness.\n */\nexport interface SubjectCmdIbGib\n    extends WitnessCmdIbGib<\n        IbGib_V1,\n        SubjectCmd, SubjectCmdModifier,\n        SubjectCmdData, SubjectCmdRel8ns\n    > {\n}\n\n/**\n * Optional shape of result data to witness interactions.\n *\n * This is in addition of course to {@link SubjectResultData}.\n *\n * so if you're sending a cmd to this witness, this should probably be the shape\n * of the result.\n *\n * ## notes\n *\n * * I'm not sure what to do with this atm, so I'm just stubbing out...\n */\nexport interface SubjectResultData extends WitnessResultData {\n}\n\n/**\n * Marker interface rel8ns atm...\n *\n * so if you're sending a cmd to this witness, this should probably be the shape\n * of the result.\n *\n * I'm not sure what to do with this atm, so I'm just stubbing out...\n */\nexport interface SubjectResultRel8ns extends WitnessResultRel8ns { }\n\n/**\n * Shape of result ibgib if used for a witness.\n *\n * so if you're sending a cmd to this witness, this should probably be the shape\n * of the result.\n *\n * I'm not sure what to do with this atm, so I'm just stubbing out...\n */\nexport interface SubjectResultIbGib\n    extends WitnessResultIbGib<IbGib_V1, SubjectResultData, SubjectResultRel8ns> {\n}\n\n/**\n * shape of underscore-delimited addl metadata string that may be present in the\n * ib (i.e. available when parsing the ib)\n *\n * This is not hard and fast and can (and should?) vary greatly per use case.\n */\nexport interface SubjectAddlMetadata {\n    /**\n     * should be subject\n     */\n    atom?: 'subject'\n    /**\n     * classname of subject **with any underscores removed**.\n     */\n    classnameIsh?: string;\n    /**\n     * name of subject witness (data.name) **with any underscores removed**.\n     */\n    nameIsh?: string;\n    /**\n     * id of witness (data.uuid) **with any underscores removed**.\n     *\n     * may be a substring per use case...?\n     */\n    idIsh?: string;\n}\n\n/**\n * Default data values for a Subject.\n *\n * If you change this, please bump the version\n *\n * (but of course won't be the end of the world when this doesn't happen).\n */\nexport const DEFAULT_SUBJECT_DATA_V1: SubjectData_V1 = {\n    version: '1',\n    uuid: DEFAULT_UUID_SUBJECT,\n    name: DEFAULT_NAME_SUBJECT,\n    description: DEFAULT_DESCRIPTION_SUBJECT,\n    classname: `Subject_V1`,\n\n    /**\n     * if true, then the witness will attempt to persist ALL calls to\n     * `witness.witness(...)`.\n     */\n    persistOptsAndResultIbGibs: false,\n    /**\n     * allow ibgibs like 42^gib ({ib: 42, gib: 'gib'} with `data` and `rel8ns` undefined)\n     */\n    allowPrimitiveArgs: true,\n    /**\n     * witnesses should be guaranteed not to throw uncaught exceptions.\n     */\n    catchAllErrors: true,\n    /**\n     * if true, would enable logging of all calls to `witness.witness(...)`\n     */\n    trace: false,\n\n    // put in your custom defaults here\n}\nexport const DEFAULT_SUBJECT_REL8NS_V1: SubjectRel8ns_V1 | undefined = undefined;\n\n\n/**\n * Subject is both an observable stream and event producer\n */\nexport interface SubjectWitness<\n    TIbGibIn_ie_Payload extends IbGib_V1 = IbGib_V1,\n    TIbGibOut_ie_ProbablyDontCare extends IbGib_V1 = IbGib_V1\n> extends ObserverWitness<TIbGibIn_ie_Payload>,\n    ObservableWitness<TIbGibIn_ie_Payload, TIbGibOut_ie_ProbablyDontCare> {\n    asObservable(): ObservableWitness<TIbGibIn_ie_Payload, TIbGibOut_ie_ProbablyDontCare>;\n}\n", "import { CLASSNAME_REGEXP } from '@ibgib/helper-gib/dist/constants.mjs';\nimport { Ib } from '@ibgib/ts-gib/dist/types.mjs';\nimport {\n    IbGib_V1, IbGibRel8ns_V1, Factory_V1 as factory, sha256v1,\n} from '@ibgib/ts-gib/dist/V1/index.mjs';\n\nimport { GLOBAL_LOG_A_LOT } from '../core-constants.mjs';\nimport { WITNESS_ARG_METADATA_STRING, WITNESS_RESULT_METADATA_STRING } from './witness-constants.mjs';\n\nimport { WitnessCmdData } from './witness-cmd/witness-cmd-types.mjs';\nimport { Witness, WitnessAny } from './witness-types.mjs';\n\nconst logalot = GLOBAL_LOG_A_LOT || false;\n\n/**\n * Builds the ib for the witness arg ibgib.\n *\n * @returns ib that we'll use when creating a witness arg.\n */\nexport function getArgIb(ibMetadata: string | undefined): string {\n    const lc = `[${getArgIb.name}]`;\n    try {\n        const ib = ibMetadata ?\n            `${WITNESS_ARG_METADATA_STRING} ${ibMetadata}` :\n            WITNESS_ARG_METADATA_STRING;\n        if (logalot) { console.log(`${lc} ${ib}`); }\n        return ib;\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    }\n}\n\n/**\n * helper function that checks if an incoming `ib` or `ibGib.ib` indicates that\n * it is an arg ibGib used with witnesses.\n *\n * ## notes\n * * atow, this basically just checks to see if it starts with\n *   `WITNESS_ARG_METADATA_STRING` (`witness_arg`).\n *\n * @throws if neither `ib` nor `ibGib` are provided.\n *\n * @returns true if the ib/ibGib.ib indicates an arg ibgib, else false\n *\n * @see {@link argy_}\n */\nexport function isArg({\n    ib,\n    ibGib,\n}: {\n    ib?: Ib,\n    ibGib?: IbGib_V1,\n}): boolean {\n    const lc = `[${isArg.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting...`); }\n\n        if (!ib) {\n            if (ibGib) {\n                ib = ibGib.ib;\n            } else {\n                throw new Error(`either ib or ibGib required (E: c052a9d76df867626f9ba17141cdce22)`);\n            }\n        }\n\n        return ib.startsWith(WITNESS_ARG_METADATA_STRING);\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * Builds the ib for the witness result ibgib.\n *\n * @returns ib that we'll use when creating a witness result.\n */\nexport function getResultIb(ibMetadata: string | undefined): string {\n    const lc = `[${getResultIb.name}]`;\n    try {\n        const ib = ibMetadata ?\n            `${WITNESS_RESULT_METADATA_STRING} ${ibMetadata}` :\n            WITNESS_RESULT_METADATA_STRING;\n        if (logalot) { console.log(`${lc} ${ib}`); }\n        return ib;\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    }\n}\n\n/**\n * helper function that checks if an incoming `ib` or `ibGib.ib` indicates that\n * it is a result ibGib used with witnesses.\n *\n * ## notes\n * * atow, this basically just checks to see if it starts with\n *   `WITNESS_ARG_METADATA_STRING` (`witness_arg`).\n *\n * @throws if neither `ib` nor `ibGib` are provided.\n *\n * @returns true if the ib/ibGib.ib indicates a result ibgib, else false\n *\n * @see {@link resulty_}\n */\nexport function isResult({\n    ib,\n    ibGib,\n}: {\n    ib?: Ib,\n    ibGib?: IbGib_V1,\n}): boolean {\n    const lc = `[${isResult.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting...`); }\n\n        if (!ib) {\n            if (ibGib) {\n                ib = ibGib.ib;\n            } else {\n                throw new Error(`either ib or ibGib required (E: 7d32a54825764d8ea72a8a38cac14224)`);\n            }\n        }\n\n        return ib.startsWith(WITNESS_RESULT_METADATA_STRING);\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n/**\n * This builds the arg ibGib for a witness function.\n *\n * By default, this is considered a one-off ibGib. As such,\n * there is no dna and no uuid. The timestamp will be included, which\n * adds some metadata (and makes for a most-often unique tjp). If there\n * is something that needs to reference this result, it can use the\n * the ibgib's address.\n *\n * @returns Result (wrapper) ibGib for a `witness` function.\n */\nexport async function argy_<\n    TArgData,\n    TArgRel8ns extends IbGibRel8ns_V1,\n    TArgIbGib extends IbGib_V1<TArgData, TArgRel8ns\n    > = IbGib_V1<TArgData, TArgRel8ns>>({\n        argData,\n        ibMetadata,\n        noTimestamp,\n    }: {\n        argData: TArgData,\n        ibMetadata?: string,\n        noTimestamp?: boolean,\n    }): Promise<TArgIbGib> {\n    const lc = `[${argy_.name}]`;\n    try {\n        const resArgIbGib = await factory.firstGen<TArgData>({\n            ib: getArgIb(ibMetadata),\n            parentIbGib: factory.primitive({ ib: WITNESS_ARG_METADATA_STRING }),\n            data: argData,\n            dna: false,\n            noTimestamp,\n        });\n        if (resArgIbGib.newIbGib) {\n            const { newIbGib: resultIbGib } = resArgIbGib;\n\n            // clear out past, disregard any intermediate ibgibs.\n            resultIbGib.rel8ns!.past = [];\n\n            resultIbGib.gib = await sha256v1(resultIbGib);\n\n            return (resultIbGib as TArgIbGib);\n        } else {\n            throw new Error(`create ibGib failed`);\n        }\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    }\n}\n\n/**\n * This builds the result ibGib for a witness function.\n *\n * By default, the result is considered a one-off ibGib. As such,\n * there is no dna and no uuid. The timestamp will be included, which\n * adds some metadata (and makes for a most-often unique tjp). If there\n * is something that needs to reference this result, it can use the\n * the ibgib's address.\n *\n * @returns Result (wrapper) ibGib for a `witness` function.\n */\nexport async function resulty_<TResultData, TResultIbGib extends IbGib_V1<TResultData> = IbGib_V1<TResultData>>({\n    resultData,\n    ibMetadata,\n    noTimestamp,\n}: {\n    resultData: TResultData,\n    ibMetadata?: string,\n    noTimestamp?: boolean,\n}): Promise<TResultIbGib> {\n    const lc = `[${resulty_.name}]`;\n    try {\n        const resResultIbGib = await factory.firstGen<TResultData>({\n            ib: getResultIb(ibMetadata),\n            parentIbGib: factory.primitive({ ib: WITNESS_RESULT_METADATA_STRING }),\n            data: resultData,\n            dna: false,\n            noTimestamp,\n        });\n        if (resResultIbGib?.newIbGib) {\n            const { newIbGib: resultIbGib } = resResultIbGib;\n\n            // clear out past, disregard any intermediate ibgibs.\n            resultIbGib.rel8ns!.past = [];\n\n            resultIbGib.gib = await sha256v1(resultIbGib);\n\n            return resultIbGib as TResultIbGib;\n        } else {\n            throw new Error(`create ibGib failed`);\n        }\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    }\n}\n\n/**\n * If valid, returns null.\n */\nexport function validateWitnessClassname({\n    classname,\n}: {\n    classname: string,\n}): string | null {\n    const lc = `[${validateWitnessClassname.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting...`); }\n        if (!classname) { throw new Error(`classname required (E: b1c7b455d58fdd8d77acd15bdf017722)`); }\n\n        if (!classname.match(CLASSNAME_REGEXP)) {\n            return `classname (${classname}) must match regex ${CLASSNAME_REGEXP}`;\n        }\n\n        return null;\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * @throws if `ibGib` falsy.\n *\n * @returns true ibGib indicates a cmd arg ibgib, else false\n */\nexport function isCommand({\n    ibGib,\n}: {\n    ibGib: IbGib_V1,\n}): boolean {\n    const lc = `[${isCommand.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting...`); }\n\n        if (!ibGib) { throw new Error(`ibGib required (E: e11cee2a6c59a5e7a4d39ea55751c423)`); }\n\n        if (!ibGib.data) {\n            return false; /* <<<< returns early */\n        }\n\n        const cmdData = (ibGib.data as WitnessCmdData<any, any>);\n        return (cmdData.cmd && typeof (cmdData.cmd) === 'string');\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport async function fnToWitness({\n    fn,\n}: {\n    fn: (arg: IbGib_V1) => Promise<IbGib_V1>,\n}): Promise<Witness<any, any, any, any>> {\n    const lc = `[${fnToWitness.name}]`;\n    try {\n\n        throw new Error(`not impl (E: 44d548c2656dc6bf27715a0ff606f223)`);\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n\n    }\n}\n\nexport function isWitness({ ibGib }: { ibGib: IbGib_V1 }): boolean {\n    const lc = `[${isWitness.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: aad0a14f4d62061424fc92da4d53d823)`); }\n        return typeof (ibGib as WitnessAny).witness === 'function';\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n", "/**\n * @module witness-factory-base\n *\n * this was a probably-klugy plumbing attempt for ionic-gib to instantiate ibgib\n * witness objects.\n *\n * Specifically this was to go from angular forms to witness ibgibs. The trick\n * was that ibgib's are data objects and you had to load the witness ibgibs\n * which actually had functions/methods on them.\n *\n * So the workflow was you get a form component with some fields, and you\n * generate the witness via this factory.\n *\n * it worked, but it's not strong I don't think.\n *\n * the main weak point is that i didn't fill out the form-items enough and i\n * never got it so that you could create nested forms.\n *\n * in its favor, i do use this (although klugily) in the ibgib rcli app, where\n * instead of a visual form it prompts the user. terrible ux but it did \"work\"\n * as a quick and dirty implementation. it could be polished going forward (i\n * dont think the design is inherently flawed).\n */\n\nimport { IbGibRel8ns_V1, IbGib_V1 } from \"@ibgib/ts-gib/dist/V1/types.mjs\";\nimport { TransformResult } from \"@ibgib/ts-gib/dist/types.mjs\";\n\nimport { Witness, WitnessData_V1, WitnessRel8ns_V1 } from \"../witness-types.mjs\";\n\n// import * as c from '../constants';\n\n// const logalot = c.GLOBAL_LOG_A_LOT || false;\n\n/**\n * The idea is that any model can be injected via this factory provider.\n */\nexport abstract class WitnessFactoryBase<\n    TWitnessData extends WitnessData_V1,\n    TWitnessRel8ns extends WitnessRel8ns_V1,\n    TWitness extends Witness<IbGib_V1, IbGib_V1, TWitnessData, TWitnessRel8ns>\n> {\n    protected lc: string = `[${WitnessFactoryBase.name}]`;\n\n    /**\n     * override this to provide the name of the class for the factory.\n     *\n     * ## usage\n     *\n     * atm I'm using this to return the classname for the witness.\n     *\n     * @example MyWitnessClass.classname\n     */\n    abstract getName(): string;\n\n    /**\n     * creates a new witness. This should return the transform result with the\n     * new ibgib being the witness class itself, not just the ibgib dto.\n     *\n     * So said in another way, the `result.newIbGib` should include the class\n     * instantiation which has the `witness` function on it.\n     *\n     * @see {@link WitnessB}\n     */\n    abstract newUp({ data, rel8ns }: { data?: TWitnessData, rel8ns?: TWitnessRel8ns }):\n        Promise<TransformResult<TWitness>>;\n\n}\n\nexport type WitnessFactoryAny = WitnessFactoryBase<any, any, any>;\n", "/**\n * @module dynamic-form-factory-base\n *\n *\n * @see {@link WitnessFactoryBase}\n */\n\nimport { patchObject } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { TransformResult } from \"@ibgib/ts-gib/dist/types.mjs\";\nimport { IbGibRel8ns_V1, IbGib_V1 } from \"@ibgib/ts-gib/dist/V1/types.mjs\";\n\nimport { DynamicForm, FormItemInfo } from \"../../common/form/form-items.mjs\";\nimport { WitnessFactoryBase } from \"./witness-factory-base.mjs\";\nimport { Witness, WitnessData_V1, WitnessRel8ns_V1 } from \"../witness-types.mjs\";\n\nimport { GLOBAL_LOG_A_LOT } from \"../../core-constants.mjs\";\nconst logalot = GLOBAL_LOG_A_LOT || false;\n\n/**\n * The idea is that any model can be injected via this factory provider.\n *\n * So when you create a witness that you want to be able to instantiate via\n * just metadata, you also provide an accompanying factory that knows\n * how to map from a\n *   * witness(model) -> form data (to generate dynamic forms)\n *   * form data -> witness (to instantiate witness from data)\n */\nexport abstract class DynamicFormFactoryBase<\n    TWitnessData extends WitnessData_V1,\n    TWitnessRel8ns extends WitnessRel8ns_V1,\n    TWitness extends Witness<IbGib_V1, IbGib_V1, TWitnessData, TWitnessRel8ns>\n>\n    extends WitnessFactoryBase<TWitnessData, TWitnessRel8ns, TWitness>{\n    protected lc: string = `[${DynamicFormFactoryBase.name}]`;\n    /**\n     * override this with something that maps from the ibgib/model to the form infos.\n     */\n    abstract witnessToForm({ witness }: { witness: TWitness }): Promise<DynamicForm>;\n    /**\n     * override this with specific behavior that will reify an instance based on\n     * the given {@link form}.\n     */\n    abstract formToWitness({ form }: { form: DynamicForm }): Promise<TransformResult<TWitness>>;\n\n    /**\n     * iterates through the given {@link items}.\n     *\n     * If the item has child items, it is considered a grouping (i.e. FormGroup\n     * or FormArray) and this function is called recursively with the\n     * {@link contextPath} adjusted per the {@link pathDelimiter} and\n     * `item.name`.\n     *\n     * If the item does not have child items, it's considered to be a setting at\n     * the current path level and it's value is assigned per its `item.name` as\n     * the key.\n     */\n    protected patchDataFromItems({\n        data,\n        contextPath,\n        items,\n        pathDelimiter,\n    }: {\n        /**\n         * ibgib.data object that we are patching/setting from the form items.\n         */\n        data: any,\n        /**\n         * source items whose values we are patching the {@link data} with.\n         */\n        items: FormItemInfo[],\n        /**\n         * Separates sections of pathing into the data object.\n         *\n         * @default @see {@link DEFAULT_DATA_PATH_DELIMITER}\n         */\n        pathDelimiter: string,\n        /**\n         * we're patching the data object as follows:\n         *\n         * data[contextPath/item.name] = value\n         *\n         * where the '/' is the data path delimiter.\n         *\n         * So if the incoming items are nested deeper, this will look like\n         *\n         * data['mysetting/subsetting/color'] = \"red\"\n         *\n         * @see {@link pathDelimiter}\n         * @see {@link DEFAULT_DATA_PATH_DELIMITER}\n         */\n        contextPath?: string,\n    }): void {\n        const lc = `${this.lc}[${this.patchDataFromItems.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting...`); }\n            if (!pathDelimiter) { throw new Error(`pathDelimiter required (E: 958d472a15fb71e45cd2925883f2ec22)`); }\n\n            for (let i = 0; i < items.length; i++) {\n                const item = items[i];\n                const path = contextPath ?\n                    contextPath + pathDelimiter + item.name :\n                    item.name;\n                if (!item.items) {\n                    // it's a property (FormControl, not FormGroup/Array)\n                    patchObject({\n                        obj: data,\n                        value: item.value,\n                        path,\n                        logalot,\n                        pathDelimiter,\n                    });\n                } else if (item.items.length > 0) {\n                    // it's a group, so call this function recursively\n                    this.patchDataFromItems({\n                        data,\n                        contextPath: path,\n                        items: item.items,\n                        pathDelimiter,\n                    });\n                } else {\n                    throw new Error(`invalid item. items is truthy but with a length of 0. items should either be falsy or have at least one child. (E: ee2765e0b920477f919fcb09e9d951b4)`);\n                }\n            }\n        } catch (error) {\n            console.error(`${lc} ${error.message}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n}\n", "/**\n * @module subscription constants\n *\n * witness constants are in this file!\n */\n\n// /**\n//  * example enum-like type+const that I use in ibgib. sometimes i put\n//  * these in the types.mts and sometimes in the const.mts, depending\n//  * on context.\n//  */\n// export type SomeEnum =\n//     'ib' | 'gib';\n// export const SomeEnum = {\n//     ib: 'ib' as SomeEnum,\n//     gib: 'gib' as SomeEnum,\n// } satisfies { [key: string]: SomeEnum };\n// export const SOME_TYPE_VALUES: SomeEnum[] = Object.values(SomeEnum);\n\n/**\n * atom used in ibs\n */\nexport const SUBSCRIPTION_ATOM = 'subscription';\n\n/**\n * default regexp for a simple name string.\n */\nexport const SUBSCRIPTION_NAME_REGEXP = /^[a-zA-Z0-9_\\-.]{1,255}$/;\n\nexport const DEFAULT_UUID_SUBSCRIPTION = '';\nexport const DEFAULT_NAME_SUBSCRIPTION = 'subscription';\nexport const DEFAULT_DESCRIPTION_SUBSCRIPTION = 'subscription is a cool ibgib witness that has seriously fascinating behavior.';\n", "/**\n * @module subscription types (and some enums/constants)\n */\n\nimport { IbGibAddr } from '@ibgib/ts-gib/dist/types.mjs';\nimport { IbGib_V1 } from '@ibgib/ts-gib/dist/V1/types.mjs';\nimport { WitnessWithContextData_V1, WitnessWithContextRel8ns_V1 } from '../../../witness/witness-with-context/witness-with-context-types.mjs';\nimport { WitnessCmdData, WitnessCmdIbGib, WitnessCmdRel8ns } from '../../../witness/witness-cmd/witness-cmd-types.mjs';\nimport { Witness, WitnessAny, WitnessResultData, WitnessResultIbGib, WitnessResultRel8ns } from '../../../witness/witness-types.mjs';\nimport { DEFAULT_DESCRIPTION_SUBSCRIPTION, DEFAULT_NAME_SUBSCRIPTION, DEFAULT_UUID_SUBSCRIPTION } from './subscription-constants.mjs';\n// and just to show where these things are\n// import { CommentIbGib_V1 } from \"@ibgib/core-gib/dist/common/comment/comment-types.mjs\";\n// import { MetaspaceService } from \"@ibgib/core-gib/dist/witness/space/metaspace/metaspace-types.mjs\";\n\n// /**\n//  * example enum-like type+const that I use in ibgib. sometimes i put\n//  * these in the types.mts and sometimes in the const.mts, depending\n//  * on context.\n//  */\n// export type SomeEnum =\n//     'ib' | 'gib';\n// /**\n//  * @see {@link SomeEnum}\n//  */\n// export const SomeEnum = {\n//     ib: 'ib' as SomeEnum,\n//     gib: 'gib' as SomeEnum,\n// } satisfies { [key: string]: SomeEnum };\n// /**\n//  * values of {@link SomeEnum}\n//  */\n// export const SOME_ENUM_VALUES: SomeEnum[] = Object.values(SomeEnum);\n\n/**\n * ibgib's intrinsic data goes here.\n *\n * @see {@link IbGib_V1.data}\n */\nexport interface SubscriptionData_V1 extends WitnessWithContextData_V1 {\n    // ibgib data (settings/values/etc) goes here\n    // /**\n    //  * docs yo\n    //  */\n    // setting: string;\n    // createdTimestamp: string;\n    // unsubscribedTimestamp: string;\n}\n\n/**\n * rel8ns (named edges/links in DAG) go here.\n *\n * @see {@link IbGib_V1.rel8ns}\n */\nexport interface SubscriptionRel8ns_V1 extends WitnessWithContextRel8ns_V1 {\n    // /**\n    //  * required rel8n. for most, put in subscription-constants.mts file\n    //  *\n    //  * @see {@link REQUIRED_REL8N_NAME}\n    //  */\n    // [REQUIRED_REL8N_NAME]: IbGibAddr[];\n    // /**\n    //  * optional rel8n. for most, put in subscription-constants.mts file\n    //  *\n    //  * @see {@link OPTIONAL_REL8N_NAME}\n    //  */\n    // [OPTIONAL_REL8N_NAME]?: IbGibAddr[];\n}\n\n/**\n * this is the ibgib object itself.\n *\n * If this is a plain ibgib data only object, this acts as a dto. You may also\n * want to generate a witness ibgib, which is slightly different, for ibgibs\n * that will have behavior (i.e. methods).\n *\n * @see {@link SubscriptionData_V1}\n * @see {@link SubscriptionRel8ns_V1}\n */\nexport interface SubscriptionIbGib_V1 extends IbGib_V1<SubscriptionData_V1, SubscriptionRel8ns_V1> {\n\n}\n\nexport type SubscriptionCmd =\n    'unsubscribe' | 'unsubscribed';\n/** Cmds for interacting with ibgib spaces. */\nexport const SubscriptionCmd = {\n    /**\n     * unsubscribe from the subscription's associated observable (that generated\n     * this subscription).\n     */\n    unsubscribe: 'unsubscribe' as SubscriptionCmd,\n    /**\n     * returns boolean if this subscription is still actively subscribed to the\n     * associated observable (that generated this subscription).\n     */\n    unsubscribed: 'unsubscribed' as SubscriptionCmd,\n}\n\n/**\n * Flags to affect the command's interpretation.\n */\nexport type SubscriptionCmdModifier =\n    'ib' | 'gib' | 'ibgib';\n/**\n * Flags to affect the command's interpretation.\n */\nexport const SubscriptionCmdModifier = {\n    /**\n     * hmm...\n     */\n    ib: 'ib' as SubscriptionCmdModifier,\n    /**\n     * hmm...\n     */\n    gib: 'gib' as SubscriptionCmdModifier,\n    /**\n     * hmm...\n     */\n    ibgib: 'ibgib' as SubscriptionCmdModifier,\n}\n\n/** Information for interacting with spaces. */\nexport interface SubscriptionCmdData\n    extends WitnessCmdData<SubscriptionCmd, SubscriptionCmdModifier> {\n}\n\nexport interface SubscriptionCmdRel8ns extends WitnessCmdRel8ns {\n}\n\n/**\n * Shape of options ibgib if used for a command-based witness.\n */\nexport interface SubscriptionCmdIbGib\n    extends WitnessCmdIbGib<\n        IbGib_V1,\n        SubscriptionCmd, SubscriptionCmdModifier,\n        SubscriptionCmdData, SubscriptionCmdRel8ns\n    > {\n}\n\n/**\n * Optional shape of result data to witness interactions.\n *\n * This is in addition of course to {@link SubscriptionResultData}.\n *\n * so if you're sending a cmd to this witness, this should probably be the shape\n * of the result.\n *\n * ## notes\n *\n * * I'm not sure what to do with this atm, so I'm just stubbing out...\n */\nexport interface SubscriptionResultData extends WitnessResultData {\n}\n\n/**\n * Marker interface rel8ns atm...\n *\n * so if you're sending a cmd to this witness, this should probably be the shape\n * of the result.\n *\n * I'm not sure what to do with this atm, so I'm just stubbing out...\n */\nexport interface SubscriptionResultRel8ns extends WitnessResultRel8ns { }\n\n/**\n * Shape of result ibgib if used for a witness.\n *\n * so if you're sending a cmd to this witness, this should probably be the shape\n * of the result.\n *\n * I'm not sure what to do with this atm, so I'm just stubbing out...\n */\nexport interface SubscriptionResultIbGib\n    extends WitnessResultIbGib<IbGib_V1, SubscriptionResultData, SubscriptionResultRel8ns> {\n}\n\n/**\n * shape of underscore-delimited addl metadata string that may be present in the\n * ib (i.e. available when parsing the ib)\n *\n * This is not hard and fast and can (and should?) vary greatly per use case.\n */\nexport interface SubscriptionAddlMetadata {\n    /**\n     * should be subscription\n     */\n    atom?: 'subscription'\n    /**\n     * classname of subscription **with any underscores removed**.\n     */\n    classnameIsh?: string;\n    /**\n     * name of subscription witness (data.name) **with any underscores removed**.\n     */\n    nameIsh?: string;\n    /**\n     * id of witness (data.uuid) **with any underscores removed**.\n     *\n     * may be a substring per use case...?\n     */\n    idIsh?: string;\n}\n\n/**\n * Default data values for a Subscription.\n *\n * If you change this, please bump the version\n *\n * (but of course won't be the end of the world when this doesn't happen).\n */\nexport const DEFAULT_SUBSCRIPTION_DATA_V1: SubscriptionData_V1 = {\n    version: '1',\n    uuid: DEFAULT_UUID_SUBSCRIPTION,\n    name: DEFAULT_NAME_SUBSCRIPTION,\n    description: DEFAULT_DESCRIPTION_SUBSCRIPTION,\n    classname: `Subscription_V1`,\n\n    /**\n     * if true, then the witness will attempt to persist ALL calls to\n     * `witness.witness(...)`.\n     */\n    persistOptsAndResultIbGibs: false,\n    /**\n     * allow ibgibs like 42^gib ({ib: 42, gib: 'gib'} with `data` and `rel8ns` undefined)\n     */\n    allowPrimitiveArgs: true,\n    /**\n     * witnesses should be guaranteed not to throw uncaught exceptions.\n     */\n    catchAllErrors: false,\n    /**\n     * if true, would enable logging of all calls to `witness.witness(...)`\n     */\n    trace: false,\n\n    // put in your custom defaults here\n}\nexport const DEFAULT_SUBSCRIPTION_REL8NS_V1: SubscriptionRel8ns_V1 | undefined = undefined;\n\n/**\n * v1 subscription witness shape\n */\nexport interface SubscriptionWitness extends WitnessAny {\n    /**\n     * unsubscribe a subscriber of an observable via this subscription.\n     * see `Subscription_V1`\n     */\n    unsubscribe(): Promise<void>;\n    /**\n     * flag to indicate if a subscription is still active or not.\n     * see `Subscription_V1`\n     */\n    unsubscribed(): Promise<boolean>;\n}\n", "/*\n * @module observable helper/util/etc. functions\n *\n * this is where you will find helper functions like those that generate\n * and parse ibs for observable.\n */\n\n// import * as pathUtils from 'path';\n// import { statSync } from 'node:fs';\n// import { readFile, } from 'node:fs/promises';\n// import * as readline from 'node:readline/promises';\n// import { stdin, stdout } from 'node:process'; // decide if use this or not\n\nimport {\n    extractErrorMsg, delay, getSaferSubstring,\n    getTimestampInTicks, getUUID, pretty,\n} from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';\nimport { UUID_REGEXP, CLASSNAME_REGEXP, } from '@ibgib/helper-gib/dist/constants.mjs';\nimport { Ib, } from '@ibgib/ts-gib/dist/types.mjs';\nimport { IbGib_V1 } from '@ibgib/ts-gib/dist/V1/types.mjs';\nimport { validateIbGibIntrinsically, } from '@ibgib/ts-gib/dist/V1/validate-helper.mjs';\n\nimport { GLOBAL_LOG_A_LOT } from '../../../core-constants.mjs';\nimport { WitnessFormBuilder } from '../../../witness/witness-form-builder.mjs';\n// import { IbGibObservableAny } from './observable-v1.mjs';\nimport {\n    ObservableData_V1, ObservableRel8ns_V1, ObservableIbGib_V1,\n} from './observable-types.mjs';\nimport { OBSERVABLE_NAME_REGEXP, } from './observable-constants.mjs';\nimport { OBSERVABLE_ATOM } from './observable-constants.mjs';\nimport { SUBJECT_ATOM } from '../subject/subject-constants.mjs';\n\n\n/**\n * for logging. import this constant from your project.\n */\nconst logalot = GLOBAL_LOG_A_LOT;\n\nexport function validateCommonObservableData({\n    data,\n}: {\n    data?: ObservableData_V1,\n}): string[] {\n    const lc = `[${validateCommonObservableData.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting...`); }\n        if (!data) { throw new Error(`Observable Data required (E: 6d1c97931dcab8ea9f3e9b32c794b90c)`); }\n        const errors: string[] = [];\n        const {\n            name, uuid, classname,\n        } =\n            data;\n\n        if (name) {\n            if (!name.match(OBSERVABLE_NAME_REGEXP)) {\n                errors.push(`name must match regexp: ${OBSERVABLE_NAME_REGEXP} (E: 21bf77e398d47e9d035376510505eda2)`);\n            }\n        } else {\n            errors.push(`name required.`);\n        }\n\n        if (uuid) {\n            if (!uuid.match(UUID_REGEXP)) {\n                errors.push(`uuid must match regexp: ${UUID_REGEXP} (E: e53fd08ae69e945b37ed895b864b6bd7)`);\n            }\n        } else {\n            errors.push(`uuid required.`);\n        }\n\n        if (classname) {\n            if (!classname.match(CLASSNAME_REGEXP)) {\n                errors.push(`classname must match regexp: ${CLASSNAME_REGEXP}`);\n            }\n        }\n\n        return errors;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport async function validateCommonObservableIbGib({\n    ibGib,\n}: {\n    ibGib: ObservableIbGib_V1,\n}): Promise<string[] | undefined> {\n    const lc = `[${validateCommonObservableIbGib.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 53696a50efff60fd86a2f431dae6ac67)`); }\n        const intrinsicErrors: string[] = await validateIbGibIntrinsically({ ibGib }) ?? [];\n\n        if (!ibGib.data) { throw new Error(`ibGib.data required (E: 5bae607c41ed4de40ec333a40673bdb8)`); }\n        const ibErrors: string[] = [];\n        let { ObservableClassname, ObservableName, ObservableId } =\n            parseObservableIb({ ib: ibGib.ib });\n        if (!ObservableClassname) { ibErrors.push(`ObservableClassname required (E: 029f7a2405c4b7aa1f52711586f8ebfd)`); }\n        if (!ObservableName) { ibErrors.push(`ObservableName required (E: e68cbc6f3183169c35117184f610573e)`); }\n        if (!ObservableId) { ibErrors.push(`ObservableId required (E: 0516442854be7ec32f5928b4cf2697f7)`); }\n\n        const dataErrors = validateCommonObservableData({ data: ibGib.data });\n\n        let result = [...(intrinsicErrors ?? []), ...(ibErrors ?? []), ...(dataErrors ?? [])];\n        if (result.length > 0) {\n            return result;\n        } else {\n            return undefined;\n        }\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport function getObservableIb({\n    data,\n    classname,\n}: {\n    data: ObservableData_V1,\n    classname?: string,\n}): Ib {\n    const lc = `[${getObservableIb.name}]`;\n    try {\n        const validationErrors = validateCommonObservableData({ data });\n        if (validationErrors.length > 0) { throw new Error(`invalid Observable data: ${validationErrors} (E: fd6b0b32d8f6c4b97eebd489cdb07a4a)`); }\n        if (classname) {\n            if (data.classname && data.classname !== classname) { throw new Error(`classname does not match data.classname (E: 354285a56a20b9b65b06abfcd9f2e621)`); }\n        } else {\n            classname = data.classname;\n            if (!classname) { throw new Error(`classname required (E: 040c1fd71853fa7874146999afb355c3)`); }\n        }\n\n        // ad hoc validation here. should centralize witness classname validation\n\n        const { name, uuid } = data;\n        return `witness ${OBSERVABLE_ATOM} ${classname} ${name} ${uuid}`;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    }\n}\n\n/**\n * Current schema is 'witness [OBSERVABLE_ATOM] [classname] [ObservableName] [ObservableId]'\n *\n * NOTE this is space-delimited\n */\nexport function parseObservableIb({\n    ib,\n}: {\n    ib: Ib,\n}): {\n    ObservableClassname: string,\n    ObservableName: string,\n    ObservableId: string,\n} {\n    const lc = `[${parseObservableIb.name}]`;\n    try {\n        if (!ib) { throw new Error(`Observable ib required (E: 84156af64e73d479220a36f247466659)`); }\n\n        const pieces = ib.split(' ');\n\n        return {\n            ObservableClassname: pieces[2],\n            ObservableName: pieces[3],\n            ObservableId: pieces[4],\n        };\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    }\n}\n\nexport class ObservableFormBuilder extends WitnessFormBuilder {\n    protected lc: string = `[${ObservableFormBuilder.name}]`;\n\n    constructor() {\n        super();\n        this.what = 'observable';\n    }\n\n    // exampleSetting({\n    //     of,\n    //     required,\n    // }: {\n    //     of: string,\n    //     required?: boolean,\n    // }): ObservableFormBuilder {\n    //     this.addItem({\n    //         // Observable.data.exampleSetting\n    //         name: \"exampleSetting\",\n    //         description: `example description`,\n    //         label: \"Example Label\",\n    //         regexp: EXAMPLE_REGEXP,\n    //         regexpErrorMsg: EXAMPLE_REGEXP_DESC,\n    //         dataType: 'textarea',\n    //         value: of,\n    //         required,\n    //     });\n    //     return this;\n    // }\n\n}\n\n/**\n * helper to determine if an ibGib is observable.\n *\n * atow 11/2023 just checks ib for presence of either SUBJECT_ATOM or OBSERVABLE_ATOM\n *\n * @returns true if observable witness, else false.\n */\nexport function isObservable({\n    ibGib,\n}: {\n    ibGib: IbGib_V1,\n}): boolean {\n    const lc = `[${isObservable.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 3aadb634377acbe42984b61c91975323)`); }\n        const { ib } = ibGib;\n        const observableAtoms = [OBSERVABLE_ATOM, SUBJECT_ATOM];\n        return observableAtoms.some(atom => ib.includes(atom));\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n", "/**\n * @module Subscription_V1 witness class\n *\n * this is where you will find the witness class that contains behavior\n * for the Subscription ibgib.\n *\n * A subscription can do two things from the caller's side:\n *\n * 1. unsubscribe\n * 2. give a boolean on whether it has been unsubscribed or not\n *\n * A subscription is created from a call to subscribe on an observable. Since\n * the observable is also a witness, we can have this subscription visit the\n * observable via `observable.witness(subscription)`. IOW, the subscription\n * witness ibgib is the argument to `witness` function.\n *\n * The observable will know that if a subscription visits it, then the\n * observable needs to release/unsubscribe that subscription.\n *\n * So since this is a light witness, we can just have two primitives be the\n * incoming argument ibgibs: unsubscribe^gib and unsubscribed^gib.\n */\n\nimport {\n    extractErrorMsg, delay, getSaferSubstring,\n    getTimestampInTicks, getUUID, pretty, clone, getIdPool,\n} from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';\nimport { DEFAULT_DATA_PATH_DELIMITER } from '@ibgib/helper-gib/dist/constants.mjs';\nimport { IbGib_V1, Rel8n, } from '@ibgib/ts-gib/dist/V1/types.mjs';\nimport { Factory_V1, } from '@ibgib/ts-gib/dist/V1/factory.mjs';\nimport { TransformResult } from '@ibgib/ts-gib/dist/types.mjs';\nimport { ROOT } from '@ibgib/ts-gib/dist/V1/constants.mjs';\n\n\nimport { GLOBAL_LOG_A_LOT } from '../../../core-constants.mjs';\nimport { MetaspaceService } from '../../../witness/space/metaspace/metaspace-types.mjs';\nimport { argy_, isArg, isCommand, resulty_ } from '../../../witness/witness-helper.mjs';\nimport { isError } from '../../error/error-helper.mjs';\nimport { DynamicFormBuilder } from '../../form/form-helper.mjs';\nimport { WitnessFormBuilder } from '../../../witness/witness-form-builder.mjs';\nimport { DynamicFormFactoryBase } from '../../../witness/factory/dynamic-form-factory-base.mjs';\nimport { DynamicForm } from '../../form/form-items.mjs';\nimport {\n    SubscriptionData_V1, SubscriptionRel8ns_V1, SubscriptionIbGib_V1,\n    SubscriptionCmd, SubscriptionCmdData, SubscriptionCmdRel8ns, SubscriptionCmdIbGib,\n    SubscriptionResultData, SubscriptionResultRel8ns, SubscriptionResultIbGib,\n    SubscriptionAddlMetadata,\n    DEFAULT_SUBSCRIPTION_DATA_V1,\n    DEFAULT_SUBSCRIPTION_REL8NS_V1,\n    SubscriptionWitness,\n} from './subscription-types.mjs';\nimport { SubscriptionFormBuilder, getSubscriptionIb } from './subscription-helper.mjs';\nimport { DEFAULT_DESCRIPTION_SUBSCRIPTION, DEFAULT_NAME_SUBSCRIPTION, SUBSCRIPTION_ATOM } from './subscription-constants.mjs';\nimport { LightWitnessBase_V1 } from '../../../witness/light-witness-base-v1.mjs';\nimport { FALSE_GIB, TRUE_GIB } from '../../other/ibgib-constants.mjs';\nimport { ErrorIbGib_V1 } from '../../error/error-types.mjs';\nimport { getGib } from '@ibgib/ts-gib/dist/V1/transforms/transform-helper.mjs';\nimport { constantIbGib } from '../../other/ibgib-helper.mjs';\nimport { isObservable } from '../observable/observable-helper.mjs';\nimport { ObservableWitnessAny } from '../observable/observable-types.mjs';\n\n\n/**\n * for logging. import this constant from your project.\n */\nconst logalot = GLOBAL_LOG_A_LOT; // change this when you want to turn off verbose logging\n\n/**\n * sketching...\n * under construction...\n */\nexport class Subscription_V1\n    extends LightWitnessBase_V1<SubscriptionData_V1, SubscriptionRel8ns_V1>\n    implements SubscriptionIbGib_V1, SubscriptionWitness {\n\n    /**\n     * Log context for convenience with logging. (Ignore if you don't want to use this.)\n     */\n    protected lc: string = `[${Subscription_V1.name}]`;\n\n    /**\n     * Reference to the local ibgibs service, which is one way at getting at the\n     * local user space.\n     */\n    public metaspace: MetaspaceService | undefined;\n\n    /**\n     * this is UNDEFINED if we have not yet subscribed.\n     *\n     * this is only true AFTER we have subscribed.\n     *\n     * this is FALSE after we have subscribed AND THEN UNSUBSCRIBED.\n     */\n    private _subscribed: boolean | undefined;\n\n    /**\n     * this is not !this._subscribed!!!\n     *\n     * this is only true AFTER we have subscribed and then unsubscribed.\n     */\n    private _unsubscribed: boolean | undefined;\n\n    /**\n     * this is the observable\n     */\n    private _srcObservable: ObservableWitnessAny | undefined;\n\n\n    constructor(initialData?: SubscriptionData_V1, initialRel8ns?: SubscriptionRel8ns_V1) {\n        super(initialData, initialRel8ns);\n    }\n\n    protected async initialize(): Promise<void> {\n        const lc = `${this.lc}[${this.initialize.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 8097612cda5f43e5b38249d057b65b1e)`); }\n            await super.initialize();\n\n            if (!this.data) { throw new Error(`this.data required (E: 1af73af2d17a48ada42596ad395fd99c)`); }\n            this.data.uuid = this.instanceId;\n            this.ib = getSubscriptionIb({ data: this.data, classname: 'Subscription_V1' });\n            this.gib = await getGib({ ibGib: this });\n        } catch (error) {\n            console.error(`${lc} ${error.message}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     *\n     * @param arg\n     * @returns\n     */\n    async witness(arg: IbGib_V1): Promise<IbGib_V1 | undefined> {\n        const lc = `${this.lc}[${this.witness.name}]`;\n        try {\n            if (!this._isInitialized) { await this.initialized; }\n            const { ib } = arg;\n            if (!ib) { throw new Error(`arg.ib required (E: 1fd9aebef07b4bdaacc0cd323c8ddf76)`); }\n            if (logalot) { console.log(`${lc} ib: ${ib} (I: 4de7771f477dc5b36933343b694ce223)`); }\n            if (ib === SubscriptionCmd.unsubscribe) {\n                if (logalot) { console.log(`${lc} routing unsubscribe cmd (I: 5633b86d467af2aa67388abf559a3c23)`); }\n                return this.witness_unsubscribe();\n            } else if (ib === SubscriptionCmd.unsubscribed) {\n                if (logalot) { console.log(`${lc} routing unsubscribed query (I: 6e0ae61d90f1974d76bcdbb47970e723)`); }\n                return this.witness_unsubscribed();\n            } else if (isObservable({ ibGib: arg })) {\n                if (logalot) { console.log(`${lc} routing observerable (I: 165b422cda9ec3052312243dc965cf23)`); }\n                return this.witness_observable({ ibGib: arg as ObservableWitnessAny });\n            } else {\n                throw new Error(`unknown arg. expect unsubscribe/unsubscribed primitive ibgib or Observable ibgib. (E: 132dc7cd8f7c4afc9ec4651e2c559c74)`);\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error) ?? 'unknown error (E: b0bbaab21833404a9420c3d273df7f21)'}`);\n            throw error;\n        }\n    }\n\n    private async witness_unsubscribe(): Promise<IbGib_V1> {\n        const lc = `${this.lc}[${this.witness_unsubscribe.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: a3d549220ef24604956aaa2c66fff09b)`); }\n            if (!this._subscribed) {\n                console.warn(`${lc} tried to unsubscribe but this._subscribed is ${this._subscribed} (W: cdc94f59447d4011b4b4cc12ef9ec074)`);\n                return ROOT; /* <<<< returns early */\n            }\n            if (this._unsubscribed) {\n                console.warn(`{lc} this._unsubscribed already true. (W: fa287d76cec040e0978a8add5c758093)`)\n                return ROOT;\n            }\n\n            if (!this._srcObservable) { throw new Error(`(UNEXPECTED) this._subscribed but this._srcObservable falsy? (E: 83687993b7bea299b4ba2438b530a123)`); }\n\n            if (logalot) {\n                console.log(`${lc} inspecting srcObservable before src.witness... (I: f15a33d10f1cae3cec6fdbdb32596823)`);\n                console.dir(this._srcObservable);\n            }\n\n            await this._srcObservable.witness(this);\n\n            if (logalot) {\n                console.log(`${lc} inspecting srcObservable after src.witness... (I: f15a33d10f1cae3cec6fdbdb32596823)`);\n                console.dir(this._srcObservable);\n            }\n\n            // hmm maybe being too picky here with two different 3-state flags.\n            this._subscribed = false;\n            this._unsubscribed = true;\n            delete this._srcObservable;\n\n            if (logalot) { console.log(`${lc} this._ (I: 7b1bc418a3d32757772391cad7a49523)`); }\n\n            return ROOT;\n        } catch (error) {\n            console.error(`${lc} ${error.message}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private async witness_observable({ ibGib }: { ibGib: ObservableWitnessAny }): Promise<IbGib_V1> {\n        const lc = `${this.lc}[${this.witness_observable.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: faf248f372fc44a7bb0e70492e8284f9)`); }\n            if (this._subscribed !== undefined) { throw new Error(`(UNEXPECTED) this._subscribed (${this._subscribed} is not undefined? (E: 09a0e926357676c2c93a173ccbe93923)`); }\n            if (this._srcObservable) { throw new Error(`(UNEXPECTED) this subscription isn't subscribed but this._observable is truthy? (E: acdf5198fb2ff3c8b2db95450bd55b23)`); }\n\n            // store the observable reference as this subscription's observable\n            this._srcObservable = ibGib;\n            if (logalot) { console.log(`${lc} this._srcObservable set to ibgib with ib: ${ibGib.ib} (I: 4b81d17243f60dfdcc2163fbb55e9223)`); }\n\n            // we are now subscribed\n            this._subscribed = true;\n\n            // like an ack/ok/void/whatever\n            return ROOT;\n        } catch (error) {\n            console.error(`${lc} ${error.message}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private async witness_unsubscribed(): Promise<IbGib_V1> {\n        const lc = `${this.lc}[${this.witness_unsubscribed.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 1beac551253e4c5694b63e0d36d5d5c0)`); }\n            if (this._subscribed == undefined) { throw new Error(`subscription never subscribed in the first place (this._subscribed === undefined) (E: b2c1b21a0e876a4908339a976924b923)`); }\n            if (this._subscribed && this._unsubscribed) { throw new Error(`(UNEXPECTED) both this._subscribed and this._unsubscribed true (E: a967e49de657a43929a74703c656ad23)`); }\n            const result =\n                this._unsubscribed === true ?\n                    TRUE_GIB : // still subscribed, so UNsubscribed is false\n                    FALSE_GIB; // subscribed is false, so UNsubscribed is true\n            if (logalot) { console.log(`${lc} result: ${pretty(result)} (I: b488cf36ce39e006a81d3ad3db5b4a23)`); }\n            return result;\n        } catch (error) {\n            console.error(`${lc} ${error.message}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    // #region public api\n\n    /**\n     * unsubscribe a subscriber of an observable via this subscription.\n     */\n    async unsubscribe(): Promise<void> {\n        const lc = `${this.lc}[${this.unsubscribe.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: ef7f3f4787a74fcca65d761880f44594)`); }\n            const result = await this.witness(Factory_V1.primitive({ ib: SubscriptionCmd.unsubscribe }));\n\n            // do we really care about the result other than checking for error?\n            if (!result) { throw new Error(`(UNEXPECTED) unsubscribe returned undefined? (E: 7013193490b94b6880f1049c36577d6f)`); }\n\n            if (isError({ ibGib: result })) {\n                const errorIbGib = result as ErrorIbGib_V1;\n                // should we just return the error?\n                throw new Error(`${errorIbGib.data!.raw} (E: fca1200dccb14f84968b2462f1b4c29e)`);\n            }\n        } catch (error) {\n            console.error(`${lc} ${error.message}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * (async) flag to indicate if a subscription is still active or not.\n     *\n     * @returns `true` if we have unsubscribed/deactivated this subscription, `false` if this subscription is still active\n     */\n    async unsubscribed(): Promise<boolean> {\n        const lc = `${this.lc}[${this.unsubscribed.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 8ee9a93be61647d6aef6a4fa03e96dad)`); }\n            const resRaw = await this.witness(Factory_V1.primitive({ ib: SubscriptionCmd.unsubscribed }));\n            if (!resRaw) { throw new Error(`(UNEXPECTED) unsubscribe returned undefined? (E: 5051d7ff4a4d4bf7864c520b53f028d5)`); }\n            const resUnsubscribed = resRaw.ib === TRUE_GIB.ib;\n            if (logalot) { console.log(`${lc} resUnsubscribed: ${resUnsubscribed} (I: b4800166c58d5ba2ca1dccaa53de2323)`); }\n            return resUnsubscribed;\n        } catch (error) {\n            console.error(`${lc} ${error.message}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    // #endregion public api\n\n    /**\n     * validates against common witness qualities.\n     *\n     * Override this with a call to `super.validateThis` for custom validation\n     * for descending witness classes.\n     *\n     * @returns validation errors common to all subscription witnesses, if any errors exist.\n     */\n    protected async validateThis(): Promise<string[]> {\n        const lc = `${this.lc}[${this.validateThis.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting...`); }\n            if (!this.data) {\n\n            }\n            const errors: string[] = [\n                // ...await super.validateThis(),\n                // ...validateCommonSubscriptionData({ data: this.data }),\n            ];\n            return errors;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * builds an arg ibGib.\n     *\n     * wrapper convenience to avoid long generic calls.\n     */\n    async argy({\n        argData,\n        ibMetadata,\n        noTimestamp,\n        ibGibs,\n    }: {\n        argData: SubscriptionCmdData,\n        ibMetadata?: string,\n        noTimestamp?: boolean,\n        ibGibs?: IbGib_V1[],\n    }): Promise<SubscriptionCmdIbGib> {\n        const arg = await argy_<SubscriptionCmdData, SubscriptionCmdRel8ns, SubscriptionCmdIbGib>({\n            argData,\n            ibMetadata,\n            noTimestamp\n        });\n\n        if (ibGibs) { arg.ibGibs = ibGibs; }\n\n        return arg;\n    }\n\n    /**\n     * builds a result ibGib, if indeed a result ibgib is required.\n     *\n     * This is only useful in witnesses that have more structured\n     * inputs/outputs. For those that simply accept any ibgib incoming and\n     * return a primitive like ib^gib or whatever, then this is unnecessary.\n     *\n     * wrapper convenience to avoid long generic calls.\n     */\n    async resulty({\n        resultData,\n        ibGibs,\n    }: {\n        resultData: SubscriptionResultData,\n        ibGibs?: IbGib_V1[],\n    }): Promise<SubscriptionResultIbGib> {\n        const result = await resulty_<SubscriptionResultData, SubscriptionResultIbGib>({\n            // ibMetadata: getSubscriptionResultMetadata({space: this}),\n            resultData,\n        });\n        if (ibGibs) { result.ibGibs = ibGibs; }\n        return result;\n    }\n\n}\n\n/**\n * factory for random Subscription witness.\n *\n * @see {@link DynamicFormFactoryBase}\n */\nexport class Subscription_V1_Factory\n    extends DynamicFormFactoryBase<SubscriptionData_V1, SubscriptionRel8ns_V1, Subscription_V1> {\n\n    protected lc: string = `[${Subscription_V1_Factory.name}]`;\n\n    getName(): string { return Subscription_V1.name; }\n\n    async newUp({\n        data,\n        rel8ns,\n    }: {\n        data?: SubscriptionData_V1,\n        rel8ns?: SubscriptionRel8ns_V1,\n    }): Promise<TransformResult<Subscription_V1>> {\n        const lc = `${this.lc}[${this.newUp.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting...`); }\n            data ??= clone(DEFAULT_SUBSCRIPTION_DATA_V1);\n            data = data!;\n            rel8ns = rel8ns ?? DEFAULT_SUBSCRIPTION_REL8NS_V1 ? clone(DEFAULT_SUBSCRIPTION_REL8NS_V1) : undefined;\n            data.uuid ||= await getUUID();\n            let { classname } = data;\n\n            const ib = getSubscriptionIb({ data });\n\n            // subscription is a constant, so we dont need to create a\n            // dependency graph or timeline or anything like that. it's just a\n            // stone.\n            const subscriptionIbGibDto =\n                await constantIbGib<SubscriptionData_V1, SubscriptionRel8ns_V1>({\n                    parentPrimitiveIb: `witness ${classname}`,\n                    ib, data, rel8ns,\n                }) as SubscriptionIbGib_V1;\n\n            // replace the newIbGib which is just ib,gib,data,rel8ns with loaded\n            // witness class (that has the witness function on it)\n            const witnessIbGib = new Subscription_V1(undefined, undefined);\n            await witnessIbGib.loadIbGibDto(subscriptionIbGibDto);\n            if (logalot) { console.log(`${lc} witnessDto: ${pretty(subscriptionIbGibDto)} (I: 5e41337176d1441f9a5c7b43664d43ef)`); }\n\n            return { newIbGib: witnessIbGib };\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg({ error })}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    async witnessToForm({ witness }: { witness: Subscription_V1; }): Promise<DynamicForm> {\n        const lc = `${this.lc}[${this.witnessToForm.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting...`); }\n            let { data } = witness;\n            if (!data) { throw new Error(`(UNEXPECTED) witness.data falsy? (E: ef44497ff97a4e5bac004d52c4ff40eb)`); }\n            if (logalot) { console.log(`${lc} data: ${pretty(data)} (I: c3f4c3d85386461aaefbe33524ff9cbd)`); }\n            // be careful of order here because of TS type inference\n            const idPool = await getIdPool({ n: 100 });\n            const form = new SubscriptionFormBuilder()\n                .with({ idPool })\n                .name({ of: data.name!, required: false, })\n                .description({ of: data.description ?? DEFAULT_DESCRIPTION_SUBSCRIPTION })\n                .and<SubscriptionFormBuilder>()\n                .and<DynamicFormBuilder>()\n                .uuid({ of: data.uuid!, required: true })\n                .classname({ of: data.classname! })\n                .and<WitnessFormBuilder>()\n                .commonWitnessFields({ data })\n                .outputForm({\n                    formName: 'form',\n                    label: 'subscription',\n                });\n            return Promise.resolve(form);\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg({ error })}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    async formToWitness({ form }: { form: DynamicForm; }): Promise<TransformResult<Subscription_V1>> {\n        let data: SubscriptionData_V1 = clone(DEFAULT_SUBSCRIPTION_DATA_V1);\n        this.patchDataFromItems({ data, items: form.items, pathDelimiter: DEFAULT_DATA_PATH_DELIMITER });\n        let resWitnessIbGib = await this.newUp({ data });\n        return resWitnessIbGib;\n    }\n\n}\n", "/*\n * @module subscription helper/util/etc. functions\n *\n * this is where you will find helper functions like those that generate\n * and parse ibs for subscription.\n */\n\n// import * as pathUtils from 'path';\n// import { statSync } from 'node:fs';\n// import { readFile, } from 'node:fs/promises';\n// import * as readline from 'node:readline/promises';\n// import { stdin, stdout } from 'node:process'; // decide if use this or not\n\nimport {\n    extractErrorMsg, delay, getSaferSubstring,\n    getTimestampInTicks, getUUID, pretty,\n} from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';\nimport { UUID_REGEXP, CLASSNAME_REGEXP, } from '@ibgib/helper-gib/dist/constants.mjs';\nimport { Ib, } from '@ibgib/ts-gib/dist/types.mjs';\nimport { validateIbGibIntrinsically, } from '@ibgib/ts-gib/dist/V1/validate-helper.mjs';\n\nimport { GLOBAL_LOG_A_LOT } from '../../../core-constants.mjs';\nimport { WitnessFormBuilder } from '../../../witness/witness-form-builder.mjs';\n// import { IbGibSubscriptionAny } from './subscription-v1.mjs';\nimport {\n    SubscriptionData_V1, SubscriptionRel8ns_V1, SubscriptionIbGib_V1, SubscriptionWitness,\n} from './subscription-types.mjs';\nimport { SUBSCRIPTION_ATOM, SUBSCRIPTION_NAME_REGEXP, } from './subscription-constants.mjs';\nimport { IbGib_V1 } from '@ibgib/ts-gib/dist/V1/types.mjs';\nimport { Subscription_V1, Subscription_V1_Factory } from './subscription-v1.mjs';\n\n/**\n * for logging. import this constant from your project.\n */\nconst logalot = GLOBAL_LOG_A_LOT;\n\nexport function validateCommonSubscriptionData({\n    data,\n}: {\n    data?: SubscriptionData_V1,\n}): string[] {\n    const lc = `[${validateCommonSubscriptionData.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting...`); }\n        if (!data) { throw new Error(`Subscription Data required (E: 6d1c97931dcab8ea9f3e9b32c794b90c)`); }\n        const errors: string[] = [];\n        const {\n            name, uuid, classname,\n        } =\n            data;\n\n        if (name) {\n            if (!name.match(SUBSCRIPTION_NAME_REGEXP)) {\n                errors.push(`name must match regexp: ${SUBSCRIPTION_NAME_REGEXP} (E: 21bf77e398d47e9d035376510505eda2)`);\n            }\n        } else {\n            errors.push(`name required.`);\n        }\n\n        if (uuid) {\n            if (!uuid.match(UUID_REGEXP)) {\n                errors.push(`uuid must match regexp: ${UUID_REGEXP} (E: e53fd08ae69e945b37ed895b864b6bd7)`);\n            }\n        } else {\n            errors.push(`uuid required.`);\n        }\n\n        if (classname) {\n            if (!classname.match(CLASSNAME_REGEXP)) {\n                errors.push(`classname must match regexp: ${CLASSNAME_REGEXP}`);\n            }\n        }\n\n        return errors;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport async function validateCommonSubscriptionIbGib({\n    ibGib,\n}: {\n    ibGib: SubscriptionIbGib_V1,\n}): Promise<string[] | undefined> {\n    const lc = `[${validateCommonSubscriptionIbGib.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 53696a50efff60fd86a2f431dae6ac67)`); }\n        const intrinsicErrors: string[] = await validateIbGibIntrinsically({ ibGib }) ?? [];\n\n        if (!ibGib.data) { throw new Error(`ibGib.data required (E: 5bae607c41ed4de40ec333a40673bdb8)`); }\n        const ibErrors: string[] = [];\n        let { SubscriptionClassname, SubscriptionName, SubscriptionId } =\n            parseSubscriptionIb({ ib: ibGib.ib });\n        if (!SubscriptionClassname) { ibErrors.push(`SubscriptionClassname required (E: 029f7a2405c4b7aa1f52711586f8ebfd)`); }\n        if (!SubscriptionName) { ibErrors.push(`SubscriptionName required (E: e68cbc6f3183169c35117184f610573e)`); }\n        if (!SubscriptionId) { ibErrors.push(`SubscriptionId required (E: 0516442854be7ec32f5928b4cf2697f7)`); }\n\n        const dataErrors = validateCommonSubscriptionData({ data: ibGib.data });\n\n        let result = [...(intrinsicErrors ?? []), ...(ibErrors ?? []), ...(dataErrors ?? [])];\n        if (result.length > 0) {\n            return result;\n        } else {\n            return undefined;\n        }\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport function getSubscriptionIb({\n    data,\n    classname,\n}: {\n    data: SubscriptionData_V1,\n    classname?: string,\n}): Ib {\n    const lc = `[${getSubscriptionIb.name}]`;\n    try {\n        const validationErrors = validateCommonSubscriptionData({ data });\n        if (validationErrors.length > 0) { throw new Error(`invalid Subscription data: ${validationErrors} (E: fd6b0b32d8f6c4b97eebd489cdb07a4a)`); }\n        if (classname) {\n            if (data.classname && data.classname !== classname) { throw new Error(`classname does not match data.classname (E: 354285a56a20b9b65b06abfcd9f2e621)`); }\n        } else {\n            classname = data.classname;\n            if (!classname) { throw new Error(`classname required (E: 040c1fd71853fa7874146999afb355c3)`); }\n        }\n\n        // ad hoc validation here. should centralize witness classname validation\n\n        const { uuid } = data;\n        // uuid is instanceId (atow 11/2023)\n        return `witness ${SUBSCRIPTION_ATOM} ${classname} ${uuid}`;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    }\n}\n\n/**\n * Current schema is 'witness [SUBSCRIPTION_ATOM] [classname] [SubscriptionName] [SubscriptionId]'\n *\n * NOTE this is space-delimited\n */\nexport function parseSubscriptionIb({\n    ib,\n}: {\n    ib: Ib,\n}): {\n    SubscriptionClassname: string,\n    SubscriptionName: string,\n    SubscriptionId: string,\n} {\n    const lc = `[${parseSubscriptionIb.name}]`;\n    try {\n        if (!ib) { throw new Error(`Subscription ib required (E: 84156af64e73d479220a36f247466659)`); }\n\n        const pieces = ib.split(' ');\n\n        return {\n            SubscriptionClassname: pieces[2],\n            SubscriptionName: pieces[3],\n            SubscriptionId: pieces[4],\n        };\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    }\n}\n\nexport class SubscriptionFormBuilder extends WitnessFormBuilder {\n    protected lc: string = `[${SubscriptionFormBuilder.name}]`;\n\n    constructor() {\n        super();\n        this.what = 'subscription';\n    }\n\n    // exampleSetting({\n    //     of,\n    //     required,\n    // }: {\n    //     of: string,\n    //     required?: boolean,\n    // }): SubscriptionFormBuilder {\n    //     this.addItem({\n    //         // Subscription.data.exampleSetting\n    //         name: \"exampleSetting\",\n    //         description: `example description`,\n    //         label: \"Example Label\",\n    //         regexp: EXAMPLE_REGEXP,\n    //         regexpErrorMsg: EXAMPLE_REGEXP_DESC,\n    //         dataType: 'textarea',\n    //         value: of,\n    //         required,\n    //     });\n    //     return this;\n    // }\n\n}\n\nexport function isSubscription({\n    ibGib,\n}: {\n    ibGib: IbGib_V1 | undefined,\n}): boolean {\n    const lc = `[${isSubscription.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 43df7e7f61f25e65662ce8aa5a105a23)`); }\n        if (!ibGib) { return false; }\n        let sub = ibGib as SubscriptionWitness;\n        return typeof sub.witness === 'function' &&\n            typeof sub.unsubscribe === 'function' &&\n            typeof sub.unsubscribed === 'function';\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n// #region sugar\n\n/**\n * Uses {@link Subscription_V1_Factory} to new up a blank subscription.\n * @returns subscription\n */\nexport async function newupSubscription(): Promise<Subscription_V1> {\n    const subscriptionFactory = new Subscription_V1_Factory();\n    return (await subscriptionFactory.newUp({})).newIbGib;\n}\n\n// #endregion sugar\n", "\nexport const OBSERVABLE_EVENT_ATOM = 'observable_event';\n", "/**\n * @module observable-event-helper helper functions, utils, etc.\n */\n\nimport { IbGib_V1 } from \"@ibgib/ts-gib/dist/V1/types.mjs\";\n\nimport { GLOBAL_LOG_A_LOT } from \"../../../../core-constants.mjs\";\nimport { ObservableEventData_V1, ObservableEventIbGib_V1, ObservableEventType } from \"./observable-event-types.mjs\";\nimport { constantIbGib } from \"../../../other/ibgib-helper.mjs\";\nimport { OBSERVABLE_EVENT_ATOM } from \"./observable-event-constants.mjs\";\nimport { extractErrorMsg, getUUID } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { getIbGibAddr } from \"@ibgib/ts-gib/dist/helper.mjs\";\nimport { ObservableData_V1, ObservableWitness } from \"../observable-types.mjs\";\nimport { Ib } from \"@ibgib/ts-gib/dist/types.mjs\";\nimport { UUID_REGEXP } from \"@ibgib/helper-gib/dist/constants.mjs\";\n\n/**\n * for logging. import this constant from your project.\n */\nconst logalot = GLOBAL_LOG_A_LOT; // change this when you want to turn off verbose logging\n\nexport async function getObservableEventIbGib<TIbGibIn_ie_Payload extends IbGib_V1>({\n    eventType,\n    srcObservable,\n    payload,\n}: {\n    eventType: ObservableEventType,\n    srcObservable: ObservableWitness<TIbGibIn_ie_Payload>,\n    payload: TIbGibIn_ie_Payload | undefined,\n}): Promise<ObservableEventIbGib_V1<TIbGibIn_ie_Payload>> {\n    const lc = `[${getObservableEventIbGib.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: e2290f2f46d1993d6893a24c19100823)`); }\n\n        // validate\n        if (!srcObservable) { throw new Error(`srcObservable required (E: 3470a97bbf3802cbc8dd64339f5ef623)`); }\n        if (!srcObservable.data) { throw new Error(`srcObservable.data required (E: df1786585ba849c08e7f4f1fddd30a31)`); }\n        if (!srcObservable.data.uuid) { throw new Error(`srcObservable.data.uuid required (E: 173a1a53f274bc1cef879bad2288ca23)`); }\n        if (!(srcObservable.data.uuid as string).match(UUID_REGEXP)) { throw new Error(`valid srcObservable.data.uuid required. must pass UUID_REGEXP: ${UUID_REGEXP.source} (E: 10f4bd1863f18250cc79cd65221da223)`); }\n\n        const data: ObservableEventData_V1 = {\n            uuid: await getUUID(),\n            eventType,\n            srcObservableId: srcObservable.data.uuid,\n            \"@srcObservableAddr\": getIbGibAddr({ ibGib: srcObservable }),\n            \"@payloadAddr\": getIbGibAddr({ ibGib: payload }),\n        };\n\n        const ibGib = await constantIbGib({\n            parentPrimitiveIb: OBSERVABLE_EVENT_ATOM,\n            ib: getObservableEventIb({ data }),\n            data,\n        }) as ObservableEventIbGib_V1<TIbGibIn_ie_Payload>;\n\n        return ibGib;\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport function getObservableEventIb({\n    data,\n    classname,\n}: {\n    data: ObservableData_V1,\n    classname?: string,\n}): Ib {\n    const lc = `[${getObservableEventIb.name}]`;\n    try {\n        if (classname) {\n            if (data.classname && data.classname !== classname) { throw new Error(`classname does not match data.classname (E: 523aabc53fb944789202a5f468abd338)`); }\n        } else {\n            classname = data.classname;\n            if (!classname) { throw new Error(`classname required (E: d4401ea682894c5fa824b38d4989aa76)`); }\n        }\n\n        if (!data.uuid) { throw new Error(`data.uuid required (E: 204cc7c20efd8a55263cdea8b1223e23)`); }\n\n        return `${OBSERVABLE_EVENT_ATOM} ${classname} ${data.uuid}`;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    }\n}\n\n/**\n * Current schema is '[OBSERVABLE_EVENT_ATOM] [classname] [ObservableEventId]'\n *\n * NOTE this is space-delimited\n */\nexport function parseObservableEventIb({\n    ib,\n}: {\n    ib: Ib,\n}): {\n    ObservableEventClassname: string,\n    ObservableEventId: string,\n} {\n    const lc = `[${parseObservableEventIb.name}]`;\n    try {\n        if (!ib) { throw new Error(`ObservableEvent ib required (E: 6cd1184d52284912916d6f972d375113)`); }\n\n        const pieces = ib.split(' ');\n\n        return {\n            ObservableEventClassname: pieces[1],\n            ObservableEventId: pieces[2],\n        };\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    }\n}\n", "/**\n * @module ObservableBase_V1 witness class\n *\n */\n\nimport {\n    delay,\n    extractErrorMsg,\n} from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';\nimport { IbGib_V1, } from '@ibgib/ts-gib/dist/V1/types.mjs';\nimport { ROOT } from '@ibgib/ts-gib/dist/V1/constants.mjs';\nimport { getIbGibAddr } from '@ibgib/ts-gib/dist/helper.mjs';\n\nimport { GLOBAL_LOG_A_LOT } from '../../../core-constants.mjs';\nimport { MetaspaceService } from '../../../witness/space/metaspace/metaspace-types.mjs';\nimport { argy_, isArg, isCommand, isWitness, resulty_ } from '../../../witness/witness-helper.mjs';\nimport {\n    ObservableData_V1, ObservableRel8ns_V1, ObservableIbGib_V1,\n    ObservableCmd,\n    ObservableResultData, ObservableResultIbGib,\n    OBSERVABLE_CMD_VALUES,\n    ObservableWitness,\n} from './observable-types.mjs';\nimport { LightWitnessBase_V1 } from '../../../witness/light-witness-base-v1.mjs';\nimport { WitnessAny } from '../../../witness/witness-types.mjs';\nimport { SubscriptionIbGib_V1, SubscriptionWitness } from '../subscription/subscription-types.mjs';\nimport { isObserver } from '../subject/subject-helper.mjs';\nimport { ObserverWitness, } from '../observer/observer-types.mjs';\nimport { isSubscription, newupSubscription } from '../subscription/subscription-helper.mjs';\nimport { WitnessCmdData, WitnessCmdIbGib, WitnessCmdRel8ns } from '../../../witness/witness-cmd/witness-cmd-types.mjs';\nimport { getObservableEventIbGib } from './observable-event/observable-event-helper.mjs';\nimport { ObservableEventType } from './observable-event/observable-event-types.mjs';\nimport { ErrorIbGib_V1 } from '../../error/error-types.mjs';\n\n\n/**\n * for logging. import this constant from your project.\n */\nconst logalot = GLOBAL_LOG_A_LOT; // change this when you want to turn off verbose logging\n\n/**\n * sketching...\n * under construction...\n */\nexport abstract class ObservableBase_V1<\n    TIbGibIn_ie_Payload extends IbGib_V1 = IbGib_V1,\n    TIbGibOut_ie_ProbablyDontCare extends IbGib_V1 = IbGib_V1,\n    TCmd = any, TCmdModifiers = any,\n    TCmdData extends WitnessCmdData<TCmd, TCmdModifiers> = WitnessCmdData<TCmd, TCmdModifiers>,\n    TCmdRel8ns extends WitnessCmdRel8ns = WitnessCmdRel8ns,\n    TCmdIbGib extends WitnessCmdIbGib<IbGib_V1, TCmd, TCmdModifiers, TCmdData, TCmdRel8ns> = WitnessCmdIbGib<IbGib_V1, TCmd, TCmdModifiers, TCmdData, TCmdRel8ns>,\n    TData extends ObservableData_V1 = ObservableData_V1,\n    TRel8ns extends ObservableRel8ns_V1 = ObservableRel8ns_V1\n>\n    extends LightWitnessBase_V1<TData, TRel8ns>\n    implements ObservableIbGib_V1, ObservableWitness<TIbGibIn_ie_Payload> {\n\n    /**\n     * Log context for convenience with logging. (Ignore if you don't want to use this.)\n     */\n    protected lc: string = `[${ObservableBase_V1.name}]`;\n\n    /**\n     * Reference to the local ibgibs service, which is one way at getting at the\n     * local user space.\n     */\n    public metaspace: MetaspaceService | undefined;\n\n    protected _subscribers: { [subscriptionId: string]: [SubscriptionWitness, ObserverWitness<TIbGibIn_ie_Payload> | WitnessAny] } = {};\n\n    protected _isComplete: boolean = false;\n\n    /**\n     * this is used for {@link SubjectData_V1.replay}\n     */\n    protected _pastPayloads: TIbGibIn_ie_Payload[] = [];\n    /**\n     * if observable errors out, this should be the stored error.\n     */\n    protected _pastError: ErrorIbGib_V1 | Error | string | undefined;\n\n    // #region public api properties\n\n    get isCompleteOrErrored(): boolean {\n        return this._isComplete || !!this._pastError;\n    }\n    get isComplete(): boolean { return this._isComplete; }\n    get isErrored(): boolean { return !!this._pastError; }\n\n    // #endregion public api properties\n\n    constructor(initialData?: TData, initialRel8ns?: TRel8ns) {\n        super(initialData, initialRel8ns);\n    }\n\n    /**\n     * The observable's primary function is to accept subscribers\n     * who wish to observe the stream of ibgibs this observable creates.\n     *\n     * So there are two ways to subscribe:\n     *\n     * ## 1. Use an ObservableCmd (via this.argy(...) for convenience)\n     *\n     * @see {@link subscribe}\n     *\n     * ## 2. Use any ol' Witness IbGib\n\n     * @see {@link witness_otherWitness}\n     *\n     * @param arg\n     * @returns\n     *\n     * @see {@link argy}\n     */\n    async witness(arg: IbGib_V1): Promise<IbGib_V1 | undefined> {\n        const lc = `${this.lc}[${this.witness.name}]`;\n        try {\n            if (!this._isInitialized) { await this.initialized; }\n            const { ib } = arg;\n            if (!ib) { throw new Error(`arg.ib required (E: 87659d093b82436ce2f7a87e402a5423)`); }\n            if (isCommand({ ibGib: arg })) {\n                return this.witness_cmd({ arg: arg as TCmdIbGib });\n            } else if (isWitness({ ibGib: arg })) {\n                return this.witness_otherWitness({ arg: arg as WitnessAny });\n            } else {\n                throw new Error(`unknown arg. expect observable cmd or ibgib witness (E: dc2667cffac5b8d7b1bf2ea737c81a23)`);\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error) ?? 'unknown error (E: 3e22bea4c7fb4668bf13d7146b927869)'}`);\n            throw error;\n        }\n    }\n\n    // #region witness sub-functions\n\n    /**\n     * default implementation here subscribes the witness.\n     *\n     * override this for custom handling cmds.\n     *\n     * @returns idk, an ibgib\n     */\n    protected async witness_cmd({\n        arg,\n    }: {\n        arg: TCmdIbGib,\n    }): Promise<IbGib_V1> {\n        const lc = `${this.lc}[${this.witness_cmd.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 69257fac8328b9de9755fdd237b92723)`); }\n            if (arg.data!.cmd === ObservableCmd.subscribe) {\n                return this.witness_subscribe_cmd({ ibGib: arg as TCmdIbGib });\n            } else {\n                throw new Error(`unknown command. must be of type ObservableCmd (${OBSERVABLE_CMD_VALUES}) (E: 5910e5cbafead25ea2917a65a3fc4123)`);\n            }\n        } catch (error) {\n            console.error(`${lc} ${error.message}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    protected async witness_otherWitness({\n        arg,\n    }: {\n        arg: WitnessAny,\n    }): Promise<IbGib_V1> {\n        const lc = `${this.lc}[${this.witness_otherWitness.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 871d0b7a2bef4596bad430f1cbacde02)`); }\n            if (isSubscription({ ibGib: arg })) {\n                return this.witness_subscriptionIbGib({ arg: arg as SubscriptionIbGib_V1 });\n            } else {\n                return this.witness_subscribe_nonCmdWitness({ arg });\n            }\n        } catch (error) {\n            console.error(`${lc} ${error.message}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    protected async witness_subscriptionIbGib({\n        arg,\n    }: {\n        arg: SubscriptionIbGib_V1,\n    }): Promise<IbGib_V1> {\n        const lc = `${this.lc}[${this.witness_subscriptionIbGib.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 4ac764776ef7e3f9074eb95a999ba423)`); }\n            if (!arg.data) { throw new Error(`arg.data required (E: 764ae772727ceba95a18140fdd938323)`); }\n            const key = this.getSubscriberKey({ subscription: arg });\n            const [subscription, _observer] = this._subscribers[key];\n            // will the stored subscription always be the same instance as the arg?\n            if (arg === subscription) {\n                delete this._subscribers[key];\n            } else {\n                throw new Error(`(UNEXPECTED) arg and subscription are two different instances? (E: aab5ef9bdc92abb9e816e2c443ab5723)`);\n            }\n            return ROOT;\n        } catch (error) {\n            console.error(`${lc} ${error.message}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    protected async replayPastPayloads({\n        observer,\n        subscription,\n    }: {\n        observer: ObserverWitness<TIbGibIn_ie_Payload>,\n        subscription: SubscriptionWitness,\n    }): Promise<void> {\n        const lc = `${this.lc}[${this.replayPastPayloads.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: b3c8f9c76a4af030cf52fdcf01c3fd23)`); }\n\n            // we want to be able to abort replay if the subscription is\n            // unsubscribed during this execution. (imagine a long list to\n            // replay and the subscriber cancels subscription after they found\n            // out what they needed).\n\n            const subscriberKey = this.getSubscriberKey({ subscription });\n            const fnStillSubscribed = () => {\n                return !!this._subscribers[subscriberKey];\n            };\n\n            // we cannot do a for loop because the pastPayloads may change\n            // during execution. so we will do manual \"jit\" checking for the\n            // index.\n            let i = -1;\n            let keepGoing = true;\n            do {\n                i++;\n                if (i < this._pastPayloads.length) {\n                    // stillSubscribed = await subscription.unsubscribed();\n                    if (!fnStillSubscribed()) {\n                        if (logalot) { console.log(`${lc} subscription canceled before past payloads dispatch completed. (I: f1778f868446a518030d1cf7800c8a23)`); }\n                        return; /* <<<< returns early */\n                    }\n                    try {\n                        const payload = this._pastPayloads[i];\n                        await observer.next(payload);\n                    } catch (error) {\n                        console.error(`${lc} observer errored on payload (i: ${i}). aborting replay (E: 1d7efc7c48e1491da4317ef333031077)`)\n                        return; /* <<<< returns early */\n                    }\n                } else {\n                    keepGoing = false;\n                }\n            } while (keepGoing);\n\n            if (this.isErrored && observer.error && fnStillSubscribed()) {\n                try {\n                    await observer.error(this._pastError!);\n                } catch (error) {\n                    console.error(`${lc} observer.error(this._pastError) errored itself (E: 18310e5e032345e7bdc3f2479807866c)`);\n                }\n            } else if (this.isComplete && observer.complete && fnStillSubscribed()) {\n                try {\n                    await observer.complete();\n                } catch (error) {\n                    console.error(`${lc} observer.complete errored (E: d9d027f5520f4d7eadfc669d66b5b550)`);\n                }\n            }\n        } catch (error) {\n            console.error(`${lc} ${error.message}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    protected async witness_subscribe_cmd({\n        ibGib,\n    }: {\n        ibGib: TCmdIbGib,\n    }): Promise<SubscriptionWitness> {\n        const lc = `${this.lc}[${this.witness_subscribe_cmd.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 0c4c75c3fae297af6449c1048ce55423)`); }\n\n            // validate arg and extract observer from it\n            if ((ibGib.ibGibs ?? []).length !== 1) { throw new Error(`ibGib.ibGibs required. should contain one ObserverWitness (E: 3ed99b32e22284573c497df788a9f923)`); }\n            const observer = ibGib.ibGibs![0] as ObserverWitness<TIbGibIn_ie_Payload>;\n\n            // create the subscription\n            const subscription = await newupSubscription();\n            if (logalot) { console.log(`${lc} subscription created (I: 89ccd97803c66292f9d7334e1e2de523)`); }\n            await subscription.witness(this);\n            await subscription.initialized;\n            if (logalot) { console.log(`${lc} subscription initialized (after witnessing this observable as its src). (I: 3021483402b21c4df64a9173bd223a23)`); }\n\n            // store subscription with observer for unsubscribe purposes BEFORE spinning off\n            // replayPastPayloads, because that relies on cancellation detection of looking\n            // at this key\n            this._subscribers[this.getSubscriberKey({ subscription })] = [subscription, observer];\n            if (logalot) { console.log(`${lc} stored subscriber (subscription, observer) (I: fb09660d885e33b80188dd0386ffc723)`); }\n\n            // spin off dispatch of previous payloads if applicable AFTER adding\n            // subscriber to this._subscribers.\n            if (this.data!.replay && this._pastPayloads.length > 0) {\n                // SPINS OFF!!\n                this.replayPastPayloads({ observer, subscription });\n            }\n\n            // return it!\n            return subscription;\n        } catch (error) {\n            console.error(`${lc} ${error.message}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * we have been given a witness ibGib that is not a command.  by default, an\n     * observable will subscribe a witness, and when a value comes down the pipe\n     * the witness will have its `witness` fn called a la a visitor pattern. If\n     * an error occurs, it will be propagated. I'm not sure how to do the\n     * `observer.complete` analog.\n     * @param arg ibgib object with `witness` function\n     */\n    protected async witness_subscribe_nonCmdWitness({ arg }: { arg: WitnessAny }): Promise<IbGib_V1> {\n        const lc = `${this.lc}[${this.witness_subscribe_nonCmdWitness.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: d9571dfcab4247d594c838233971886a)`); }\n            throw new Error(`not impl (E: 76219cf238ba4f849480bd7c82eefab9)`);\n        } catch (error) {\n            console.error(`${lc} ${error.message}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    // #endregion witness sub-functions\n\n    // #region public api\n\n    /**\n     * subscribes the given `observer` to this observable's stream.\n     *\n     * ## notes\n     *\n     * * The `observer` can be any ibgib witness (not specifically expose the\n     *   {@link ObserverWitness} contract), but that witness will have to be\n     *   able to deal with this observable's outputs via that witness ibGib's\n     *   `witness` function (visitor pattern).\n     * * this is a wrapper that internally produces an ObservableCmd\n     *\n     * @param observer\n     *\n     * @returns subscription used for unsubscribing\n     */\n    async subscribe(observer: WitnessAny | ObserverWitness<TIbGibIn_ie_Payload>): Promise<SubscriptionWitness> {\n        const lc = `${this.lc}[${this.subscribe.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 0dec9a06c562711e19482d45a7075e23)`); }\n            let resSubscription: SubscriptionWitness;\n            if (isObserver({ ibGib: observer })) {\n                // witness with Observer shape\n                const arg = await this.argy({\n                    argData: {\n                        cmd: ObservableCmd.subscribe,\n                        ibGibAddrs: [getIbGibAddr({ ibGib: observer })],\n                    } as TCmdData, // I'm struggling to think of a descending TCmdData 'subscribe' that has other properties\n                    ibGibs: [observer]\n                });\n                resSubscription = await this.witness(arg) as SubscriptionWitness;\n            } else {\n                // plain ol' witness (without a `next` fn atow 11/2023)\n                resSubscription = await this.witness(observer) as SubscriptionWitness;\n            }\n            if (!isSubscription({ ibGib: resSubscription })) { throw new Error(`(UNEXPECTED) resSubscription is not a SubscriptionWitness? (E: c29bec4e3a48d6f1299143399ac55a23)`); }\n            return resSubscription;\n        } catch (error) {\n            console.error(`${lc} ${error.message}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    // #endregion public api\n\n    // #region helpers\n\n    private getSubscriberKey({\n        subscription,\n    }: {\n        subscription: SubscriptionIbGib_V1\n    }): string {\n        if (subscription.data?.uuid) {\n            return subscription.data.uuid;\n        } else {\n            throw new Error(`(UNEXPECTED) subscription.data.uuid falsy? (E: 8d078e6f8155f7567fd9378557e91823)`);\n        }\n\n    }\n\n    protected async dispatchToEachSubscriber({\n        payload,\n        fnForObserver,\n        observableEventType,\n    }: {\n        /**\n         * payload to dispatch\n         */\n        payload: TIbGibIn_ie_Payload | undefined,\n        /**\n         * fn to execute dispatch for each observer subscriber.\n         *\n         * each subscriber is either an observer or a plain jane witness. if\n         * it's a plain witness, then it's easy - we just dispatch the payload\n         * to the `subscriber.witness` function. If it's an observer though,\n         * we need to decide which function to do: `next`, `error`, `complete`.\n         */\n        fnForObserver: (observer: ObserverWitness<TIbGibIn_ie_Payload>, payload: TIbGibIn_ie_Payload | undefined) => Promise<void>,\n        /**\n         * this type is used for dispatching to bare witness subscribers (i.e.\n         * non-observer interface witnesses).\n         */\n        observableEventType: ObservableEventType,\n    }): Promise<void> {\n        const lc = `${this.lc}[${this.dispatchToEachSubscriber.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 0b990ce892f689d14458565717e66a23)`); }\n\n            // dispatch to subscribers (serially)\n            const subscriberTuples = Object.values(this._subscribers);\n            for (let i = 0; i < subscriberTuples.length; i++) {\n                const [subscription, observerOrWitness] = subscriberTuples[i];\n\n                // depends on if subscriber is observer or plain witness...\n                if (isObserver({ ibGib: observerOrWitness })) {\n                    // subscriber uses observer interface\n                    const observer = observerOrWitness as ObserverWitness<TIbGibIn_ie_Payload>;\n                    await fnForObserver(observer, payload);\n                    if (observer.complete) {\n                        // we remove subscribers on unsubscribe, but just in case we\n                        // will double-check here if we are still subscribed\n                        const unsubscribed = await subscription.unsubscribed();\n                        if (!unsubscribed) {\n                            // dispatch to observer's via its `next` fn\n                            await observer.complete();\n                        } else {\n                            console.warn(`${lc} (UNEXPECTED) subscriber reference still held but is unsubscribed? skipping for now (i.e. won't remove subscriber) in case that code is in yielded execution and just hasn't gotten around to it with event loop (but that would be weird). (W: 1d98f35d2fdd4345954c947265d9fb85)`)\n                        }\n                    } else {\n                        // no error handler for this observer\n                        if (logalot) { console.log(`${lc} no error handler for observer. skipping. (I: 6a8a52c2012c464790eb406d2ae0383f)`); }\n                    }\n                } else {\n                    // subscriber is an ibGib witness (not an observer interface)\n                    // so wrap the payload into an event and pass to\n                    // `subscriber.witness` fn\n                    const observableEventWrapper = await getObservableEventIbGib({\n                        eventType: observableEventType,\n                        srcObservable: this,\n                        payload,\n                    });\n                    await observerOrWitness.witness(observableEventWrapper);\n                }\n            }\n\n        } catch (error) {\n            console.error(`${lc} ${error.message}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * validates against common witness qualities.\n     *\n     * Override this with a call to `super.validateThis` for custom validation\n     * for descending witness classes.\n     *\n     * @returns validation errors common to all observable witnesses, if any errors exist.\n     */\n    protected async validateThis(): Promise<string[]> {\n        const lc = `${this.lc}[${this.validateThis.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting...`); }\n            if (!this.data) {\n\n            }\n            const errors: string[] = [\n                // ...await super.validateThis(),\n                // ...validateCommonObservableData({ data: this.data }),\n            ];\n            return errors;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * builds an arg ibGib.\n     *\n     * wrapper convenience to avoid long generic calls.\n     */\n    async argy({\n        argData,\n        ibMetadata,\n        noTimestamp,\n        ibGibs,\n    }: {\n        argData: TCmdData,\n        ibMetadata?: string,\n        noTimestamp?: boolean,\n        ibGibs?: IbGib_V1[],\n    }): Promise<TCmdIbGib> {\n        const arg = await argy_<TCmdData, TCmdRel8ns, TCmdIbGib>({\n            argData,\n            ibMetadata,\n            noTimestamp\n        });\n\n        if (ibGibs) { arg.ibGibs = ibGibs; }\n\n        return arg;\n    }\n\n    /**\n     * builds a result ibGib, if indeed a result ibgib is required.\n     *\n     * This is only useful in witnesses that have more structured\n     * inputs/outputs. For those that simply accept any ibgib incoming and\n     * return a primitive like ib^gib or whatever, then this is unnecessary.\n     *\n     * wrapper convenience to avoid long generic calls.\n     */\n    async resulty({\n        resultData,\n        ibGibs,\n    }: {\n        resultData: ObservableResultData,\n        ibGibs?: IbGib_V1[],\n    }): Promise<ObservableResultIbGib> {\n        const result = await resulty_<ObservableResultData, ObservableResultIbGib>({\n            // ibMetadata: getObservableResultMetadata({space: this}),\n            resultData,\n        });\n        if (ibGibs) { result.ibGibs = ibGibs; }\n        return result;\n    }\n\n    // #endregion helpers\n\n}\n", "/*\n * @module Subject_V1 witness class\n *\n * this is where you will find the witness class that contains behavior\n * for the Subject ibgib.\n *\n * A observable can do two things from the caller's side:\n *\n * 1. unsubscribe\n * 2. give a boolean on whether it has been unsubscribed or not\n *\n * A observable is created from a call to subscribe on an observable.  Since\n * the observable is also a witness, we can have this observable visit the\n * observable via `observable.witness(observable)`. IOW, the observable\n * witness ibgib is the argument to `witness` function.\n *\n * The observable will know that if a observable visits it, then the\n * observable needs to release/unsubscribe that observable.\n *\n * So since this is a light witness, we can just have two primitives be the\n * incoming argument ibgibs: unsubscribe^gib and unsubscribed^gib.\n */\n\nimport {\n    extractErrorMsg, delay, getSaferSubstring,\n    getTimestampInTicks, getUUID, pretty, clone, getIdPool,\n} from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';\nimport { DEFAULT_DATA_PATH_DELIMITER } from '@ibgib/helper-gib/dist/constants.mjs';\nimport { IbGibData_V1, IbGibRel8ns_V1, IbGib_V1, } from '@ibgib/ts-gib/dist/V1/types.mjs';\nimport { TransformResult } from '@ibgib/ts-gib/dist/types.mjs';\nimport { getIbGibAddr } from '@ibgib/ts-gib/dist/helper.mjs';\nimport { ROOT } from '@ibgib/ts-gib/dist/V1/constants.mjs';\n\nimport { MetaspaceService } from '../../../witness/space/metaspace/metaspace-types.mjs';\nimport { argy_, isArg, isCommand, resulty_ } from '../../../witness/witness-helper.mjs';\nimport { getErrorIbGib, isError } from '../../error/error-helper.mjs';\nimport { DynamicFormBuilder } from '../../form/form-helper.mjs';\nimport { WitnessFormBuilder } from '../../../witness/witness-form-builder.mjs';\nimport { DynamicFormFactoryBase } from '../../../witness/factory/dynamic-form-factory-base.mjs';\nimport { DynamicForm } from '../../form/form-items.mjs';\n\nimport { GLOBAL_LOG_A_LOT } from '../../../core-constants.mjs';\nimport {\n    SubjectData_V1, SubjectRel8ns_V1, SubjectIbGib_V1,\n    SubjectCmd, SubjectCmdData, SubjectCmdRel8ns, SubjectCmdIbGib,\n    SubjectResultData, SubjectResultRel8ns, SubjectResultIbGib,\n    SubjectAddlMetadata,\n    DEFAULT_SUBJECT_DATA_V1,\n    DEFAULT_SUBJECT_REL8NS_V1,\n    SubjectWitness,\n    SubjectCmdModifier,\n} from './subject-types.mjs';\nimport { SubjectFormBuilder, getSubjectIb, isObserver } from './subject-helper.mjs';\nimport { DEFAULT_DESCRIPTION_SUBJECT, } from './subject-constants.mjs';\nimport { WitnessAny, } from '../../../witness/witness-types.mjs';\nimport { ErrorIbGib_V1 } from '../../error/error-types.mjs';\nimport { ObservableCmd, ObservableWitness, } from '../observable/observable-types.mjs';\nimport { ObserverWitness, Observer } from '../observer/observer-types.mjs';\nimport { constantIbGib } from '../../other/ibgib-helper.mjs';\nimport { SubscriptionWitness } from '../subscription/subscription-types.mjs';\nimport { ObservableBase_V1 } from '../observable/observable-base-v1.mjs';\n\n\n/**\n * for logging. import this constant from your project.\n */\nconst logalot = GLOBAL_LOG_A_LOT; // change this when you want to turn off verbose logging\n\n/**\n * sketching...\n * under construction...\n */\nexport class Subject_V1<\n    TIbGibIn_ie_Payload extends IbGib_V1 = IbGib_V1,\n    TIbGibOut_ie_ProbablyDontCare extends IbGib_V1 = IbGib_V1\n> extends ObservableBase_V1<\n    TIbGibIn_ie_Payload,\n    TIbGibOut_ie_ProbablyDontCare,\n    SubjectCmd, SubjectCmdModifier,\n    SubjectCmdData, SubjectCmdRel8ns, SubjectCmdIbGib,\n    SubjectData_V1, SubjectRel8ns_V1\n> implements SubjectIbGib_V1, SubjectWitness<TIbGibIn_ie_Payload, TIbGibOut_ie_ProbablyDontCare> {\n    /**\n     * Log context for convenience with logging. (Ignore if you don't want to use this.)\n     */\n    protected lc: string = `[${Subject_V1.name}]`;\n\n    // /**\n    //  * Reference to the local ibgibs service, which is one way at getting at the\n    //  * local user space.\n    //  */\n    // public metaspace: MetaspaceService | undefined;\n\n    constructor(initialData?: SubjectData_V1, initialRel8ns?: SubjectRel8ns_V1) {\n        super(initialData, initialRel8ns);\n    }\n\n    // #region public api methods\n\n    asObservable(): ObservableWitness<TIbGibIn_ie_Payload, TIbGibOut_ie_ProbablyDontCare> {\n        return this as ObservableWitness<TIbGibIn_ie_Payload, TIbGibOut_ie_ProbablyDontCare>;\n    }\n    async subscribe(observer: WitnessAny | ObserverWitness<TIbGibIn_ie_Payload>): Promise<SubscriptionWitness> {\n        const lc = `${this.lc}[${this.subscribe.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 8e47b752314870ec78eb14342621f723)`); }\n            const arg = await this.argy({\n                argData: {\n                    cmd: SubjectCmd.subscribe,\n                    ibGibAddrs: [getIbGibAddr({ ibGib: observer })],\n                },\n                ibGibs: [observer],\n            });\n            const subscription = await this.witness(arg) as SubscriptionWitness;\n            return subscription;\n        } catch (error) {\n            console.error(`${lc} ${error.message}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    async next(ibGib: TIbGibIn_ie_Payload): Promise<void> {\n        const lc = `${this.lc}[${this.next.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: b30363827c56450ca918c69aa15b0046)`); }\n            const arg = await this.argy({\n                argData: {\n                    cmd: SubjectCmd.next,\n                    ibGibAddrs: [getIbGibAddr({ ibGib })],\n                },\n                ibGibs: [ibGib],\n            });\n\n            await this.witness(arg); // ignores return value\n        } catch (error) {\n            console.error(`${lc} ${error.message}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    async error(error: string | Error | ErrorIbGib_V1): Promise<void> {\n        const lc = `${this.lc}[${this.error.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 7fcc30e3763c429ea8b212491ad9455a)`); }\n\n            // wrap raw Error if necessary into an ErrorIbGib_V1\n            let errorIbGib: ErrorIbGib_V1;\n            if (typeof error === 'string') {\n                errorIbGib = await getErrorIbGib({ rawMsg: error });\n            } else if (error instanceof Error || typeof (error as any).message === 'string') {\n                errorIbGib = await getErrorIbGib({ rawMsg: extractErrorMsg(error) });\n            } else if (!!(error as IbGib_V1).ib && isError({ ibGib: (error as IbGib_V1) })) {\n                errorIbGib = error as ErrorIbGib_V1;\n            } else {\n                throw new Error(`unknown error type. shold either be ErrorIbGib_V1 or an Error instance or have error.message string property. (E: 2cfcab85439c3c845bfe18e8ecde3523)`);\n            }\n\n            // build the arg\n            const arg = await this.argy({\n                argData: {\n                    cmd: SubjectCmd.error,\n                    ibGibAddrs: [getIbGibAddr({ ibGib: errorIbGib })],\n                },\n                ibGibs: [errorIbGib],\n            });\n\n            // do it\n            await this.witness(arg); // ignores return value\n        } catch (error) {\n            console.error(`${lc} ${error.message}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    async complete(): Promise<void> {\n        const lc = `${this.lc}[${this.complete.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 5faaf13c6b0543d399815c03b9cdf80c)`); }\n\n            // build the arg\n            const arg = await this.argy({\n                argData: {\n                    cmd: SubjectCmd.complete,\n                },\n            });\n\n            // do it\n            await this.witness(arg); // ignores return value\n        } catch (error) {\n            console.error(`${lc} ${error.message}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    // #endregion public api methods\n\n    // #region witness sub-methods\n\n    protected async witness_cmd({\n        arg,\n    }: {\n        arg: SubjectCmdIbGib,\n    }): Promise<IbGib_V1> {\n        const lc = `${this.lc}[${this.witness_cmd.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 2bf7cbcadba446fa92cb649906b2b260)`); }\n            let { cmd } = arg.data!;\n            switch (cmd) {\n                case SubjectCmd.next:\n                    return this.witness_next({ ibGib: arg });\n                case SubjectCmd.error:\n                    return this.witness_error({ ibGib: arg });\n                case SubjectCmd.complete:\n                    return this.witness_complete({ ibGib: arg });\n                default:\n                    // note: this is a call to the *super*.witness_cmd\n                    return super.witness_cmd({ arg });\n            }\n        } catch (error) {\n            console.error(`${lc} ${error.message}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private async witness_next({\n        ibGib,\n    }: {\n        ibGib: SubjectCmdIbGib,\n    }): Promise<IbGib_V1> {\n        const lc = `${this.lc}[${this.witness_next.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 600da780f13f5137a2f76aad344b2923)`); }\n\n            if (this.isCompleteOrErrored) {\n                if (logalot) { console.log(`${lc} this.isCompleteOrErrored is true. returning early without producing. (I: aa823831853b134b19657c8673838c23)`); }\n                return ROOT;\n            }\n\n            // validate\n            if ((ibGib.ibGibs ?? []).length !== 1) { throw new Error(`ibGib.ibGibs required. should contain one payload ibgib (E: 4046802ff96d4adfafcee7a74d96af5e)`); }\n\n            // extract the payload\n            const payloadIbGib = ibGib.ibGibs![0] as TIbGibIn_ie_Payload;\n\n            // go ahead and persist this in our history\n            if (this.data!.replay) { this._pastPayloads.push(payloadIbGib); }\n\n            // dispatch to subscribers (serially)\n            const subscriberTuples = Object.values(this._subscribers);\n            for (let i = 0; i < subscriberTuples.length; i++) {\n                const [subscription, observer] = subscriberTuples[i];\n\n                // we remove subscribers on unsubscribe, but just in case we\n                // will double-check here if we are still subscribed\n                if (logalot) { console.log(`${lc} ensuring subscription not unsubscribed (I: ade3fd6d6ff2b5ec69eb8143e32ce223)`); }\n                const unsubscribed = await subscription.unsubscribed();\n                if (!unsubscribed) {\n                    if (logalot) { console.log(`${lc} subscription still active (I: b9ab83b28acecf0d823fdba46a81dc23)`); }\n                    // dispatch to observer's via its `next` fn\n                    await (observer as ObserverWitness<TIbGibIn_ie_Payload>).next(payloadIbGib);\n                } else {\n                    debugger; // unexpected error state\n                    console.warn(`${lc} (UNEXPECTED) subscriber reference still held but is unsubscribed? skipping for now (i.e. won't remove subscriber) in case that code is in yielded execution and just hasn't gotten around to it with event loop (but that would be weird). (W: c116e799f6b9483c97fd030eb0dd09ea)`)\n                }\n            }\n            return ROOT;\n        } catch (error) {\n            console.error(`${lc} ${error.message}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private async witness_error({\n        ibGib,\n    }: {\n        ibGib: SubjectCmdIbGib,\n    }): Promise<IbGib_V1> {\n        const lc = `${this.lc}[${this.witness_error.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 3367a73bc83c47f98d9ecfe426dc300e)`); }\n\n            // validate\n            if ((ibGib.ibGibs ?? []).length !== 1) { throw new Error(`ibGib.ibGibs required. should contain one error ibgib (E: 905474b45bcb4f0abe7bd4618f08f32c)`); }\n\n            // extract the payload\n            const errIbGib = ibGib.ibGibs![0] as ErrorIbGib_V1;\n\n            // store the error in this observable\n            this._pastError = errIbGib;\n\n            // dispatch to subscribers (serially)\n            const subscriberTuples = Object.values(this._subscribers);\n            for (let i = 0; i < subscriberTuples.length; i++) {\n                const [subscription, observerOrWitness] = subscriberTuples[i];\n\n                // depends on if observer or witness...\n                if (isObserver({ ibGib: observerOrWitness })) {\n                    // observer uses observer interface\n                    const observer = observerOrWitness as ObserverWitness<TIbGibIn_ie_Payload>;\n                    if (observer.error) {\n                        // we remove subscribers on unsubscribe, but just in case we\n                        // will double-check here if we are still subscribed\n                        const unsubscribed = await subscription.unsubscribed();\n                        if (!unsubscribed) {\n                            // dispatch to observer's via its `next` fn\n                            await observer.error(errIbGib);\n                        } else {\n                            console.warn(`${lc} (UNEXPECTED) subscriber reference still held but is unsubscribed? skipping for now (i.e. won't remove subscriber) in case that code is in yielded execution and just hasn't gotten around to it with event loop (but that would be weird). (W: 8946e97f00fd4146a470064b490a4c29)`)\n                        }\n                    } else {\n                        // no error handler for this observer\n                        if (logalot) { console.log(`${lc} no error handler for observer. skipping. (I: 59f4a1ee59a3a27d523d60cd761be923)`); }\n                    }\n                } else {\n                    // observer is an ibGib witness (not an observer interface)\n                    await observerOrWitness.witness(errIbGib);\n                }\n            }\n            return ROOT;\n        } catch (error) {\n            console.error(`${lc} ${error.message}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private async witness_complete({\n        ibGib,\n    }: {\n        ibGib: SubjectCmdIbGib,\n    }): Promise<IbGib_V1> {\n        const lc = `${this.lc}[${this.witness_complete.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 4db180f465e24df9a4ded37fbd235558)`); }\n\n            // set the flag on this observable\n            this._isComplete = true;\n\n            // dispatch to subscribers (serially)\n            const subscriberTuples = Object.values(this._subscribers);\n            for (let i = 0; i < subscriberTuples.length; i++) {\n                const [subscription, observerOrWitness] = subscriberTuples[i];\n\n                // depends on if observer or witness...\n                if (isObserver({ ibGib: observerOrWitness })) {\n                    // observer uses observer interface\n                    const observer = observerOrWitness as ObserverWitness<TIbGibIn_ie_Payload>;\n                    if (observer.complete) {\n                        // we remove subscribers on unsubscribe, but just in case we\n                        // will double-check here if we are still subscribed\n                        const unsubscribed = await subscription.unsubscribed();\n                        if (!unsubscribed) {\n                            // dispatch to observer's via its `next` fn\n                            await observer.complete();\n                        } else {\n                            console.warn(`${lc} (UNEXPECTED) subscriber reference still held but is unsubscribed? skipping for now (i.e. won't remove subscriber) in case that code is in yielded execution and just hasn't gotten around to it with event loop (but that would be weird). (W: 1d98f35d2fdd4345954c947265d9fb85)`)\n                        }\n                    } else {\n                        // no error handler for this observer\n                        if (logalot) { console.log(`${lc} no error handler for observer. skipping. (I: 6a8a52c2012c464790eb406d2ae0383f)`); }\n                    }\n                } else {\n                    // observer is an ibGib witness (not an observer interface)\n                    await observerOrWitness.witness(ibGib);\n                }\n            }\n            return ROOT;\n        } catch (error) {\n            console.error(`${lc} ${error.message}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * validates against common witness qualities.\n     *\n     * Override this with a call to `super.validateThis` for custom validation\n     * for descending witness classes.\n     *\n     * @returns validation errors common to all observable witnesses, if any errors exist.\n     */\n    protected async validateThis(): Promise<string[]> {\n        const lc = `${this.lc}[${this.validateThis.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting...`); }\n            if (!this.data) {\n\n            }\n            const errors: string[] = [\n                // ...await super.validateThis(),\n                // ...validateCommonSubjectData({ data: this.data }),\n            ];\n            return errors;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    // #endregion witness sub-methods\n\n    // #region helpers\n\n    /**\n     * builds an arg ibGib.\n     *\n     * wrapper convenience to avoid long generic calls.\n     */\n    async argy({\n        argData,\n        ibMetadata,\n        noTimestamp,\n        ibGibs,\n    }: {\n        argData: SubjectCmdData,\n        ibMetadata?: string,\n        noTimestamp?: boolean,\n        ibGibs?: IbGib_V1[],\n    }): Promise<SubjectCmdIbGib> {\n        if (argData.cmd === ObservableCmd.subscribe) {\n            return super.argy({ argData, ibMetadata, noTimestamp, ibGibs });\n        } else {\n            const arg = await argy_<SubjectCmdData, SubjectCmdRel8ns, SubjectCmdIbGib>({\n                argData,\n                ibMetadata,\n                noTimestamp\n            });\n            if (ibGibs) { arg.ibGibs = ibGibs; }\n            return arg;\n        }\n    }\n\n    /**\n     * builds a result ibGib, if indeed a result ibgib is required.\n     *\n     * This is only useful in witnesses that have more structured\n     * inputs/outputs. For those that simply accept any ibgib incoming and\n     * return a primitive like ib^gib or whatever, then this is unnecessary.\n     *\n     * wrapper convenience to avoid long generic calls.\n     */\n    async resulty({\n        resultData,\n        ibGibs,\n    }: {\n        resultData: SubjectResultData,\n        ibGibs?: IbGib_V1[],\n    }): Promise<SubjectResultIbGib> {\n        const result = await resulty_<SubjectResultData, SubjectResultIbGib>({\n            // ibMetadata: getSubjectResultMetadata({space: this}),\n            resultData,\n        });\n        if (ibGibs) { result.ibGibs = ibGibs; }\n        return result;\n    }\n\n    // #endregion helpers\n}\n\n/*\n * factory for random Subject witness.\n *\n * @see {@link DynamicFormFactoryBase}\n */\nexport class Subject_V1_Factory\n    extends DynamicFormFactoryBase<SubjectData_V1, SubjectRel8ns_V1, Subject_V1> {\n\n    protected lc: string = `[${Subject_V1_Factory.name}]`;\n\n    getName(): string { return Subject_V1.name; }\n\n    async newUp({\n        data,\n        rel8ns,\n    }: {\n        data?: SubjectData_V1,\n        rel8ns?: SubjectRel8ns_V1,\n    }): Promise<TransformResult<Subject_V1>> {\n        const lc = `${this.lc}[${this.newUp.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting...`); }\n            data ??= clone(DEFAULT_SUBJECT_DATA_V1);\n            data = data!;\n            rel8ns = rel8ns ?? DEFAULT_SUBJECT_REL8NS_V1 ? clone(DEFAULT_SUBJECT_REL8NS_V1) : undefined;\n            data.uuid ||= await getUUID();\n            let { classname } = data;\n\n            const ib = getSubjectIb({ data });\n\n            // subscription is a constant, so we dont need to create a\n            // dependency graph or timeline or anything like that. it's just a\n            // stone.\n            const subscriptionIbGibDto =\n                await constantIbGib<SubjectData_V1, SubjectRel8ns_V1>({\n                    parentPrimitiveIb: `witness ${classname}`,\n                    ib, data, rel8ns,\n                }) as SubjectIbGib_V1;\n\n            // replace the newIbGib which is just ib,gib,data,rel8ns with loaded\n            // witness class (that has the witness function on it)\n            const witnessIbGib = new Subject_V1(undefined, undefined);\n            await witnessIbGib.loadIbGibDto(subscriptionIbGibDto);\n            if (logalot) { console.log(`${lc} witnessDto: ${pretty(subscriptionIbGibDto)} (I: 6736d2b2ddf44fef9a1eb27078dfbf23)`); }\n\n            return { newIbGib: witnessIbGib };\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg({ error })}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    async witnessToForm({ witness }: { witness: Subject_V1; }): Promise<DynamicForm> {\n        const lc = `${this.lc}[${this.witnessToForm.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting...`); }\n            let { data } = witness;\n            if (!data) { throw new Error(`(UNEXPECTED) witness.data falsy? (E: 7b70c96e982d4f81b6ffda54da16b3b8)`); }\n            if (logalot) { console.log(`${lc} data: ${pretty(data)} (I: 75abef56f5004a94b2113e3b1461ac25)`); }\n            // be careful of order here because of TS type inference\n            const idPool = await getIdPool({ n: 100 });\n            const form = new SubjectFormBuilder()\n                .with({ idPool })\n                .name({ of: data.name!, required: false, })\n                .description({ of: data.description ?? DEFAULT_DESCRIPTION_SUBJECT })\n                .and<SubjectFormBuilder>()\n                .and<DynamicFormBuilder>()\n                .uuid({ of: data.uuid!, required: true })\n                .classname({ of: data.classname! })\n                .and<WitnessFormBuilder>()\n                .commonWitnessFields({ data })\n                .outputForm({\n                    formName: 'form',\n                    label: 'observable',\n                });\n            return Promise.resolve(form);\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg({ error })}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    async formToWitness({ form }: { form: DynamicForm; }): Promise<TransformResult<Subject_V1>> {\n        let data: SubjectData_V1 = clone(DEFAULT_SUBJECT_DATA_V1);\n        this.patchDataFromItems({ data, items: form.items, pathDelimiter: DEFAULT_DATA_PATH_DELIMITER });\n        let resWitnessIbGib = await this.newUp({ data });\n        return resWitnessIbGib;\n    }\n\n}\n", "/*\n * @module subject helper/util/etc. functions\n *\n * this is where you will find helper functions like those that generate\n * and parse ibs for subject.\n */\n\n// import * as pathUtils from 'path';\n// import { statSync } from 'node:fs';\n// import { readFile, } from 'node:fs/promises';\n// import * as readline from 'node:readline/promises';\n// import { stdin, stdout } from 'node:process'; // decide if use this or not\n\nimport {\n    extractErrorMsg, delay, getSaferSubstring,\n    getTimestampInTicks, getUUID, pretty, clone,\n} from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';\nimport { UUID_REGEXP, CLASSNAME_REGEXP, } from '@ibgib/helper-gib/dist/constants.mjs';\nimport { Gib, Ib, } from '@ibgib/ts-gib/dist/types.mjs';\nimport { IbGib_V1, } from '@ibgib/ts-gib/dist/V1/types.mjs';\nimport { GIB, } from '@ibgib/ts-gib/dist/V1/constants.mjs';\nimport { validateGib, validateIb, validateIbGibIntrinsically, } from '@ibgib/ts-gib/dist/V1/validate-helper.mjs';\n\nimport { GLOBAL_LOG_A_LOT } from '../../../core-constants.mjs';\n// import { IbGibSpaceAny } from '../../../witness/space/space-base-v1.mjs';\n// import { MetaspaceService } from '../../../witness/space/metaspace/metaspace-types.mjs';\nimport { WitnessFormBuilder } from '../../../witness/witness-form-builder.mjs';\n// import { IbGibSubjectAny } from './subject-v1.mjs';\nimport {\n    SubjectData_V1, SubjectRel8ns_V1, SubjectIbGib_V1, SubjectWitness, DEFAULT_SUBJECT_DATA_V1,\n} from './subject-types.mjs';\nimport { SUBJECT_ATOM, SUBJECT_NAME_REGEXP, } from './subject-constants.mjs';\nimport { Observer } from '../observer/observer-types.mjs';\nimport { Subject_V1_Factory } from './subject-v1.mjs';\n\n/**\n * for logging. import this constant from your project.\n */\nconst logalot = GLOBAL_LOG_A_LOT;\n\nexport function validateCommonSubjectData({\n    data,\n}: {\n    data?: SubjectData_V1,\n}): string[] {\n    const lc = `[${validateCommonSubjectData.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting...`); }\n        if (!data) { throw new Error(`Subject Data required (E: 207a82725648e2ef234c8bd3fa1a5312)`); }\n        const errors: string[] = [];\n        const {\n            name, uuid, classname,\n        } =\n            data;\n\n        if (name) {\n            if (!name.match(SUBJECT_NAME_REGEXP)) {\n                errors.push(`name must match regexp: ${SUBJECT_NAME_REGEXP} (E: de987eb8fea0b6232f60abf31815095c)`);\n            }\n        } else {\n            errors.push(`name required.`);\n        }\n\n        if (uuid) {\n            if (!uuid.match(UUID_REGEXP)) {\n                errors.push(`uuid must match regexp: ${UUID_REGEXP} (E: 1a6dfda91ad51696f7456bc84dfea60e)`);\n            }\n        } else {\n            errors.push(`uuid required.`);\n        }\n\n        if (classname) {\n            if (!classname.match(CLASSNAME_REGEXP)) {\n                errors.push(`classname must match regexp: ${CLASSNAME_REGEXP}`);\n            }\n        }\n\n        return errors;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport async function validateCommonSubjectIbGib({\n    ibGib,\n}: {\n    ibGib: SubjectIbGib_V1,\n}): Promise<string[] | undefined> {\n    const lc = `[${validateCommonSubjectIbGib.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: cec6bd96c70e61680fd0e6137d846a94)`); }\n        const intrinsicErrors: string[] = await validateIbGibIntrinsically({ ibGib }) ?? [];\n\n        if (!ibGib.data) { throw new Error(`ibGib.data required (E: 50b1815be5abb247f6774048bbaee538)`); }\n        const ibErrors: string[] = [];\n        let { SubjectClassname, SubjectName, SubjectId } =\n            parseSubjectIb({ ib: ibGib.ib });\n        if (!SubjectClassname) { ibErrors.push(`SubjectClassname required (E: bafa26247959d4fd9e41dbed8b839cf5)`); }\n        if (!SubjectName) { ibErrors.push(`SubjectName required (E: d95f7740415c727797c1e26f4888cbe0)`); }\n        if (!SubjectId) { ibErrors.push(`SubjectId required (E: f415b151b37fe80b99b403a1590f2e14)`); }\n\n        const dataErrors = validateCommonSubjectData({ data: ibGib.data });\n\n        let result = [...(intrinsicErrors ?? []), ...(ibErrors ?? []), ...(dataErrors ?? [])];\n        if (result.length > 0) {\n            return result;\n        } else {\n            return undefined;\n        }\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * builds/rebuilds the ib for Subject based on incoming `data` and `classname`.\n *\n * note that if `data.classname` is truthy, it must match `classname` if also\n * truthy. (`data` is required, but may not necessarily have `classname` in it.)\n *\n * @returns ib based on params\n */\nexport function getSubjectIb({\n    data,\n    classname,\n}: {\n    data: SubjectData_V1,\n    classname?: string,\n}): Ib {\n    const lc = `[${getSubjectIb.name}]`;\n    try {\n        const validationErrors = validateCommonSubjectData({ data });\n        if (validationErrors.length > 0) { throw new Error(`invalid Subject data: ${validationErrors} (E: 55620ac1f17e30a30a92850219f894ac)`); }\n        if (classname) {\n            if (data.classname && data.classname !== classname) { throw new Error(`classname does not match data.classname (E: 20e86cca70130839a49ad011c9a7aafa)`); }\n        } else {\n            classname = data.classname;\n            if (!classname) { throw new Error(`classname required (E: 74e29ae0f618fee7e7ef72a30c654a6c)`); }\n        }\n\n        // ad hoc validation here. should centralize witness classname validation\n\n        const { name, uuid } = data;\n        return `witness ${SUBJECT_ATOM} ${classname} ${name} ${uuid}`;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    }\n}\n\n/**\n * Current schema is 'witness [SUBJECT_ATOM] [classname] [SubjectName] [SubjectId]'\n *\n * NOTE this is space-delimited\n */\nexport function parseSubjectIb({\n    ib,\n}: {\n    ib: Ib,\n}): {\n    SubjectClassname: string,\n    SubjectName: string,\n    SubjectId: string,\n} {\n    const lc = `[${parseSubjectIb.name}]`;\n    try {\n        if (!ib) { throw new Error(`Subject ib required (E: b29b305c5bc5ba7adf735a037ee4c012)`); }\n\n        const pieces = ib.split(' ');\n\n        return {\n            SubjectClassname: pieces[2],\n            SubjectName: pieces[3],\n            SubjectId: pieces[4],\n        };\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    }\n}\n\nexport class SubjectFormBuilder extends WitnessFormBuilder {\n    protected lc: string = `[${SubjectFormBuilder.name}]`;\n\n    constructor() {\n        super();\n        this.what = 'subject';\n    }\n\n    // exampleSetting({\n    //     of,\n    //     required,\n    // }: {\n    //     of: string,\n    //     required?: boolean,\n    // }): SubjectFormBuilder {\n    //     this.addItem({\n    //         // Subject.data.exampleSetting\n    //         name: \"exampleSetting\",\n    //         description: `example description`,\n    //         label: \"Example Label\",\n    //         regexp: EXAMPLE_REGEXP,\n    //         regexpErrorMsg: EXAMPLE_REGEXP_DESC,\n    //         dataType: 'textarea',\n    //         value: of,\n    //         required,\n    //     });\n    //     return this;\n    // }\n\n}\n\n/**\n * helper function to determine if the given `ibGib` is an observer, i.e.,\n * fulfills the {@link Observer} contract.\n *\n * atow (11/2023) the minimal requirement is `ibGib.next` to be a function.\n *\n * @returns true if fulfills the {@link Observer} contract.\n */\nexport function isObserver({\n    ibGib,\n}: {\n    ibGib: IbGib_V1,\n}): boolean {\n    const lc = `[${isObserver.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: b54c252104f710c12951aa43b6ead323)`); }\n        return typeof (ibGib as unknown as Observer).next === 'function';\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n// #region sugar\n\n/**\n * Uses {@link Subject_V1_Factory} to new up a blank subject.\n *\n * ## future\n *\n * in the future, will see about adding a space for persisting this subject (and\n * possibly published events).\n *\n * @returns subject\n */\nexport async function newupSubject<\n    TPayloadIbGib extends IbGib_V1 = IbGib_V1\n>({\n    data,\n    replay,\n}: {\n    data?: SubjectData_V1,\n    replay?: boolean,\n} = {}): Promise<SubjectWitness<TPayloadIbGib>> {\n    const subjectFactory = new Subject_V1_Factory();\n\n    // starting data\n    data ??= clone(DEFAULT_SUBJECT_DATA_V1) as SubjectData_V1;\n\n    // additional options\n    if (replay) { data.replay = true; }\n\n    // create it\n    const resTransform = await subjectFactory.newUp({ data });\n\n    // return it\n    return resTransform.newIbGib as SubjectWitness<TPayloadIbGib>;\n}\n\n// #endregion sugar\n", "import { extractErrorMsg, pretty } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { Ib, IbGibAddr } from \"@ibgib/ts-gib/dist/types.mjs\";\nimport { IbGib_V1, IbGibRel8ns_V1 } from \"@ibgib/ts-gib/dist/V1/types.mjs\";\nimport { GIB, IB, ROOT } from \"@ibgib/ts-gib/dist/V1/constants.mjs\";\nimport { Factory_V1 } from \"@ibgib/ts-gib/dist/V1/factory.mjs\";\nimport { WitnessWithContextBase_V1 } from \"@ibgib/core-gib/dist/witness/witness-with-context/witness-with-context-base-v1.mjs\";\nimport { IbGibTimelineUpdateInfo } from \"@ibgib/core-gib/dist/common/other/other-types.mjs\";\nimport { ObservableWitness, } from \"@ibgib/core-gib/dist/common/pubsub/observable/observable-types.mjs\";\nimport { newupSubject } from \"@ibgib/core-gib/dist/common/pubsub/subject/subject-helper.mjs\";\nimport { SubjectWitness } from \"@ibgib/core-gib/dist/common/pubsub/subject/subject-types.mjs\";\nimport { WitnessWithContextData_V1, WitnessWithContextRel8ns_V1 } from \"@ibgib/core-gib/dist/witness/witness-with-context/witness-with-context-types.mjs\";\nimport { IbGibSpaceAny } from \"@ibgib/core-gib/dist/witness/space/space-base-v1.mjs\";\nimport { isSpaceIb } from \"@ibgib/core-gib/dist/witness/space/space-helper.mjs\";\nimport { SpaceId } from \"@ibgib/core-gib/dist/witness/space/space-types.mjs\";\n\nimport { GLOBAL_LOG_A_LOT } from \"../../constants.mjs\";\nimport { getGlobalMetaspace_waitIfNeeded } from \"../../helpers.mjs\";\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\n/**\n * Helper ibgib witness for backing ibgib component instances.\n *\n * This witness's job is not intrinsically do much of anything, rather, its\n * focus is to keep up-to-date with changes to a context.\n *\n * So this particular witness does not need to care about its own state (its gib\n * is actually just primitive \"gib\"). So no calls to loadNewerSelfIfAvailable\n * should be necessary.\n *\n * ## how to use\n *\n * ATOW (04/2025) the idea is to have an ibgib component that you want to keep\n * up-to-date. So you include a backing model proxy ibgib and subscribe to its\n * events, e.g., {@link LiveProxyIbGib.contextUpdated$}, and then the component\n * will update its visual elements.\n *\n * ## notes on driving intent of this class\n *\n * There is quite a bit of plumbing involved with updating ibgibs\n * when updates are published to the metaspace. This involves subscribing\n * to the ibgib timeline's latestObs observable on the metaspace, checking if\n * there are actual new updates, as well as other things.\n *\n * Our components, however, since they are web components must descend from\n * HTMLElement, so we can't descend from WitnessWithContextBase_V1 directly.\n *\n * So my hope is that this will be performant enough, and maintainable enough,\n * to have this backing model for ibgib components.\n *\n */\nexport class LiveProxyIbGib<TIbGib extends IbGib_V1 = IbGib_V1> extends WitnessWithContextBase_V1 {\n    protected lc: string = ``;\n\n    ib = this._currentWorkingContextIbGib ? this._currentWorkingContextIbGib.ib : IB;\n    gib = this._currentWorkingContextIbGib ? this._currentWorkingContextIbGib.gib : GIB;\n    data = this._currentWorkingContextIbGib ? this._currentWorkingContextIbGib.data : undefined;\n    rel8ns = this._currentWorkingContextIbGib ? this._currentWorkingContextIbGib.rel8ns : undefined;\n\n    protected override async loadNewerSelfIfAvailable(): Promise<void> {\n        const lc = `${this.lc}[${this.loadNewerSelfIfAvailable.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n            // doesn't look like this gets hit right now\n            console.warn(`${lc} does nothing in this class. I just have this warning here because I want to see if this gets executed. (W: genuuid)`)\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    override async loadIbGibDto(dto: IbGib_V1<WitnessWithContextData_V1, WitnessWithContextRel8ns_V1>): Promise<void> {\n        const lc = `${this.lc}[${this.loadIbGibDto.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n            debugger; // does live proxy ibgib hit here?\n            console.warn(`${lc} does nothing in this class. I just have this warning here because I want to see if this gets executed. (W: genuuid)`)\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * not a \"true\" witness as I'm thinking right now so I'm not validating this\n     * proxy class. I am keeping the validateArg function though, as that seems\n     * good to me.\n     */\n    protected override async validateThis(): Promise<string[]> {\n        const lc = `${this.lc}[${this.validateThis.name}]`;\n        if (logalot) { console.log(`${lc} elided in this proxy class because this isn't a true witness atow (04/2025) (I: fd223814f169798d9f499d6e9cdc0325)`); }\n        return [];\n    }\n\n    get ibGib(): TIbGib | undefined {\n        return this._currentWorkingContextIbGib as TIbGib | undefined;\n    }\n\n    /**\n     * determines the local space in which this proxy ibgib resides.\n     *\n     * set this via passing in a space ibgib for the proxy to witness.\n     */\n    spaceId: SpaceId | undefined;\n\n    constructor(initialData?: any, initialRel8ns?: IbGibRel8ns_V1) {\n        super(initialData, initialRel8ns);\n    }\n\n    protected override async initialize(): Promise<void> {\n        const lc = `${this.lc}[${this.initialize.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 1bd72217a5f334effc63f8d51e7b2225)`); }\n            await super.initialize();\n\n            // init observables event streams\n            this._contextUpdated$ = await newupSubject();\n            this.contextUpdated$ = this._contextUpdated$.asObservable();\n\n            this._newContextChild$ = await newupSubject();\n            this.newContextChild$ = this._newContextChild$.asObservable();\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n\n    protected parseAddlMetadataString({ ib }: { ib: Ib; }): any {\n        const lc = `${this.lc}[${this.parseAddlMetadataString.name}]`;\n        console.warn(`${lc} not really implemented in this class atow (04/2025). (W: genuuid)`);\n        return {};\n    }\n\n    /**\n     * @internal\n     *\n     * The first context ibgib frame that this proxy is initialized with,\n     * namely, before any updates happen that produce newer ibgibs in the\n     * timelines. Those will update the {@link _currentWorkingContextIbGib}.\n     */\n    protected _initialContext: TIbGib | undefined;\n\n    /**\n     * implementation for witnessing. Basically, the first ibgib this proxy\n     * witnesses is its context, i.e., its ibgib.\n     *\n     * ## notes\n     *\n     * ### on \"Context\" with this Proxy\n     *\n     * \"Context\" is kinda funny in this way, but it's how I'm reusing existing\n     * plumbing for updating contexts.\n     *\n     * Said another way, usually a \"context\" is peripheral/ambient compared to\n     * the primary behavior of a witness with context. But in this use case as a\n     * proxy ibgib, \"context\" is just the actual ibgib.\n     */\n    protected async witnessImpl(arg: IbGib_V1<any, IbGibRel8ns_V1>): Promise<IbGib_V1<any, IbGibRel8ns_V1> | undefined> {\n        const lc = `${this.lc}[${this.witnessImpl.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting...`); }\n\n            if (isSpaceIb({ ib: arg.ib })) {\n                // we're setting the local space\n                if (!arg.data) { throw new Error(`arg has space ib but arg.data is falsy (E: b2af9226c067d5e72f117fa36e239525)`); }\n                const spaceId: SpaceId = arg.data.uuid as string;\n                this.spaceId = spaceId;\n                if (logalot) { console.log(`${lc} spaceId set to the ${spaceId} (I: 018724a5431ba421b71fad36924c5a25)`); }\n                // return a primitive string\n                return Factory_V1.primitive({ ib: `spaceId set to ${spaceId}` });\n            } else {\n                // we're wrapping an ibgib\n                if (!this._initialContext) {\n                    const space = await this.metaspace?.getLocalUserSpace({ localSpaceId: this.spaceId });\n                    await this.setWrappedIbGib({\n                        ibGib: arg,\n                        space,\n                    });\n                    // return ROOT => default action taken\n                    return ROOT;\n                } else {\n                    debugger; // error\n                    console.error(`${lc} (UNEXPECTED) context already initialized. returning early without doing anything. NOTE: This error was not thrown, only logged. (E: genuuid)`);\n                }\n            }\n        } catch (error) {\n            console.error(`${lc} ${error.message}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    _contextUpdated$: SubjectWitness<TIbGib> | undefined;\n    /**\n     * similar to {@link newContextChild$}, but this is triggered when a NEW\n     * context ibgib is published via the metaspace (not its children).\n     *\n     * I believe this happens before the {@link newContextChild$} but don't\n     * quote me.\n     *\n     * ## notes\n     *\n     * * sometimes an ibgib is published on the timeline by the metaspace but it\n     *   is not actually new. So this swallows those old updates to essentially\n     *   be idempotent\n     *\n     * @see {@link _contextUpdated$}\n     * @see {@link newContextChild$}\n     */\n    contextUpdated$: ObservableWitness<TIbGib> | undefined;\n    /**\n     *\n     */\n    _newContextChild$: SubjectWitness<IbGib_V1> | undefined;\n    /**\n     * similar to {@link contextUpdated$}, but this happens when new _children_\n     * are added to the context ibgib, not just when the context ibgib itself is\n     * changed.\n     *\n     * This wraps {@link WitnessWithContextBase_V1.handleNewContextChild}\n     *\n     * @see {@link _newContextChild$}\n     * @see {@link contextUpdated$}\n     */\n    newContextChild$: ObservableWitness<IbGib_V1> | undefined;\n\n    protected async handleContextUpdate({ update }: { update: IbGibTimelineUpdateInfo; }): Promise<void> {\n        const lc = `${this.lc}[${this.handleContextUpdate.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: c262bcda065c086ffe9e3ac5899abe25)`); }\n\n            await super.handleContextUpdate({ update });\n            if (!this._contextUpdated$) { throw new Error(`(UNEXPECTED) this._contextUpdated$ falsy? (E: a184df090502bed9649f8df88bd4c125)`); }\n            await this._contextUpdated$.next(this._currentWorkingContextIbGib as TIbGib);\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    async setWrappedIbGib({\n        ibGib,\n        ibGibAddr,\n        space,\n    }: {\n        ibGib?: IbGib_V1,\n        ibGibAddr?: IbGibAddr,\n        space?: IbGibSpaceAny,\n    }): Promise<void> {\n        const lc = `${this.lc}[${this.setWrappedIbGib.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: a4b0acda259c121801aa701534320125)`); }\n            if (!this.metaspace) {\n                this.metaspace = await getGlobalMetaspace_waitIfNeeded();\n                // throw new Error(`(UNEXPECTED) this.metaspace falsy? (E: 60dc3b1eb082dfc266a33cd4cc96a525)`);\n            }\n\n            // get the ibgib by addr if necessary\n            // initialize the context with the ibgib\n            // NOTE: this.initializeContext says it has the ability to load from\n            // addr, but it doesn't and I'm too \"lazy\" right now to change that\n            // lib.\n\n            if (!ibGib) {\n                if (!ibGibAddr) { throw new Error(`(UNEXPECTED) both ibGib AND ibGibAddr falsy? (E: 6fac98ba2d4cfdec2b7ee974dec74625)`); }\n\n                space ??= await this.metaspace.getLocalUserSpace({ lock: false });\n                if (!space) { throw new Error(`(UNEXPECTED) space falsy? no space provided and couldn't get default local user space? (E: e14d1b7a6586f99453fc571396d4df25)`); }\n                const resGet = await this.metaspace.get({\n                    addrs: [ibGibAddr],\n                    space,\n                });\n\n                if (!resGet.success || resGet.ibGibs?.length !== 1) {\n                    throw new Error(`${lc} failed to get ibGib(?) (${ibGibAddr}). space.ib: ${space.ib} (E: b38f0a25d92e44c0aa5cc3b038a43c6c)`);\n                }\n                ibGib = resGet.ibGibs.at(0)!;\n            }\n\n            await this.initializeContext({\n                // arg: ibGib as TIbGib,\n                contextIbGib: ibGib as TIbGib,\n                // empty string for rel8nName avoids attempting to rel8 this\n                // witness to the context...sniff sniff\n                rel8nName: '',\n            });\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    protected override async handleNewContextChild({ newChild }: { newChild: IbGib_V1; }): Promise<void> {\n        const lc = `[${this.handleNewContextChild.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 7e9b6b7a4bb2726e9c717f230dfe1925)`); }\n            // console.error(`${lc} not really an error. newChild: ${pretty(newChild)}`);\n\n            if (!this._newContextChild$) { throw new Error(`(UNEXPECTED) this._contextUpdated$ falsy? (E: a184df090502bed9649f8df88bd4c125)`); }\n            await this._newContextChild$.next(newChild);\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n}\n", "import { delay, extractErrorMsg, pickRandom_Letters, pretty } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';\nimport { UUID_REGEXP } from '@ibgib/helper-gib/dist/constants.mjs';\nimport { IbGibAddr, TransformResult } from '@ibgib/ts-gib/dist/types.mjs';\nimport { IbGib_V1, } from '@ibgib/ts-gib/dist/V1/types.mjs';\nimport { rel8 } from '@ibgib/ts-gib/dist/V1/transforms/rel8.mjs';\nimport { getIbGibAddr } from '@ibgib/ts-gib/dist/helper.mjs';\nimport { GIB, IB, ROOT, ROOT_ADDR } from '@ibgib/ts-gib/dist/V1/constants.mjs';\nimport { mut8 } from '@ibgib/ts-gib/dist/V1/transforms/mut8.mjs';\nimport { getGibInfo } from '@ibgib/ts-gib/dist/V1/transforms/transform-helper.mjs';\nimport { WitnessData_V1, WitnessRel8ns_V1, } from '@ibgib/core-gib/dist/witness/witness-types.mjs';\nimport { CommentIbGib_V1 } from '@ibgib/core-gib/dist/common/comment/comment-types.mjs';\nimport { createCommentIbGib, isComment, parseCommentIb } from '@ibgib/core-gib/dist/common/comment/comment-helper.mjs';\nimport { LightWitnessBase_V1 } from '@ibgib/core-gib/dist/witness/light-witness-base-v1.mjs';\nimport { SpaceId } from '@ibgib/core-gib/dist/witness/space/space-types.mjs';\nimport { IbGibSpaceAny } from '@ibgib/core-gib/dist/witness/space/space-base-v1.mjs';\nimport { MetaspaceService } from '@ibgib/core-gib/dist/witness/space/metaspace/metaspace-types.mjs';\nimport { getTjpAddr } from '@ibgib/core-gib/dist/common/other/ibgib-helper.mjs';\nimport { fnObs } from '@ibgib/core-gib/dist/common/pubsub/observer/observer-helper.mjs';\nimport { execInSpaceWithLocking, } from '@ibgib/core-gib/dist/witness/space/space-helper.mjs';\n\nimport { GLOBAL_LOG_A_LOT } from '../../constants.mjs';\nimport {\n    AGENT_ATOM, AGENT_DESC_REGEXP, AGENT_NAME_REGEXP,\n    DEFAULT_DESCRIPTION_AGENT, DEFAULT_NAME_AGENT, DEFAULT_UUID_AGENT,\n    FUNCTION_CALL_REQUEST_COMMENT_TAG, TextSource,\n} from './agent-constants.mjs';\nimport { APIFunctionInfo } from '../../api/api-types.mjs';\nimport { getAllFunctionInfos, } from '../../api/api-index.mjs';\nimport { FUNCTION_INFO_REL8N_NAME, FunctionInfoIbGib_V1, createFunctionInfoIbGib } from './function-info/function-info-one-file.mjs';\nimport { GeminiModel } from './gemini/gemini-constants.mjs';\nimport { PromptAPIResult_Gemini } from './gemini/gemini-types.mjs';\nimport { getGlobalMetaspace_waitIfNeeded } from '../../helpers.mjs';\nimport { getAddlMetadataTextForAgentText, parseAddlMetadataTextForAgentText, taggifyForPrompt, updateAgentIndex } from './agent-helpers.mjs';\nimport { getAgentsSvc } from './agents-service-v1.mjs';\nimport { LiveProxyIbGib } from '../live-proxy-ibgib/live-proxy-ibgib-one-file.mjs';\nimport { AddTextsOpts, AgentAPI, AgentModel, AgentWitnessData_V1, AgentWitnessIbGib_V1, AgentWitnessRel8ns_V1, PromptAPIResult, PromptInfo, PromptOneOffOpts, SetActiveContextOpts } from './agent-types.mjs';\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\n/**\n * @extends LightWitnessBase_V1<AgentWitnessData_V1, AgentWitnessRel8ns_V1>\n *\n * ## notes\n *\n * This is far from complete. I don't know about performance, but it feels like\n * what we need to add:\n *\n * * initialization\n *   * an agent should have a reference to the ibgib metaspace, as well as the agent's working local space.\n *     * if no local space exists yet, one should be created.\n *     * we will have to create an index (\"special ibgib\") that tracks our agents\n */\nexport abstract class AgentWitness_V1<TAPIModel, TPromptInfo extends PromptInfo, TPromptResult extends PromptAPIResult>\n    extends LightWitnessBase_V1<AgentWitnessData_V1, AgentWitnessRel8ns_V1>\n    // extends WitnessWithContextBase_V1<\n    //     IbGibData_V1, IbGibRel8ns_V1, IbGib_V1, // options\n    //     IbGibData_V1, IbGibRel8ns_V1, IbGib_V1, // results\n    //     AgentWitnessData_V1,\n    //     AgentWitnessRel8ns_V1\n    // >\n    implements AgentWitnessIbGib_V1 {\n    protected lc: string = `[${AgentWitness_V1.name}]`;\n\n    protected availableFunctions: Map<string, APIFunctionInfo> = new Map();\n    protected commentIbGibs_system: CommentIbGib_V1[] = [];\n    protected commentIbGibs_chat: CommentIbGib_V1[] = [];\n\n    protected _metaspace: MetaspaceService | undefined;\n    // /**\n    //  * public helper to set the metaspace\n    //  * @param metaspace\n    //  */\n    // setMetaspace(metaspace: MetaspaceService): void {\n    //     if (this._metaspace) { throw new Error(`(UNEXPECTED) this.metaspace already set? (E: 60062ee8c69e773b96f8ddc38f227b25)`); }\n    //     this._metaspace = metaspace;\n    // }\n\n    /**\n     * provider function for api key.\n     */\n    fnGetAPIKey: () => Promise<string> = () => { return Promise.reject(`not implemented. you need to set this after initializing the agent. (E: a14cbe903d08821126bbbb1d063d9825)`); }\n\n    /**\n     * convenience getter for this.data.name\n     */\n    get name(): string { return this.data?.name ?? ''; }\n\n    /**\n     * convenience getter for this.data.name\n     */\n    get uuid(): string { return this.data?.uuid ?? ''; }\n\n    protected _genAI: TAPIModel | undefined;\n\n    /**\n     * @protected\n     * @property transientDecompressionPromptText - A temporary string that is\n     * added to the prompt on the next LLM call ONLY, i.e. for a single prompt.\n     *\n     * This should NOT be part of any text history, but is rather a temporary\n     * way of including text in a chat in a one-off manner.\n     *\n     * ## driving use case\n     *\n     * We're using this right now in relation with Function Call Requests from\n     * this agent's model. We don't want to spam the context window with the\n     * details of these function calls, but sometimes the model needs the\n     * results of these functions.\n     */\n    protected transientDecompressionPromptText: string | undefined;\n\n    /**\n     * @property fnOutputText - A property on the AgentWitness_V1 that provides a way to output text.\n     *\n     * Default implementation to do nothing. This is to avoid a null pointer.\n     * ATOW (01/2025) This is a hack right now to get feedback from the agent that is not a function call.\n     */\n    fnOutputText: (textResponse: string) => void = (tr) => { console.log(`${this.lc}[fnOutputText] this hack does nothing by default. set this to do something when text is returned by the model LLM. textResponse: ${tr} (W: 3007e5d69dafdd7e42157fa7370d7f25)`) }\n\n    // protected instanceId: string;\n\n    /**\n     * we need this agent witness to basically update as a singleton. enforcing\n     * singleton instances of agents is difficult even just locally, but\n     * impossible when we consider that we may have multiple tabs/apps sharing\n     * some space.\n     *\n     * So instead, we'll try having multiple witness instances wrapping the\n     * proxy.\n     */\n    protected ibGibProxy: LiveProxyIbGib<AgentWitnessIbGib_V1> | undefined;\n\n    constructor(initialData?: AgentWitnessData_V1, initialRel8ns?: AgentWitnessRel8ns_V1) {\n        super(initialData, initialRel8ns);\n        this.instanceId = pickRandom_Letters({ count: 32 });\n    }\n\n    protected override async validateThis(): Promise<string[]> {\n        const lc = `${this.lc}[${this.validateThis.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 641e211473fc54d5a9ebb4ea44944d25)`); }\n            const errors = await super.validateThis();\n\n            // todo: refactor this into a non-class-method validation helper function for data\n            if (this.data) {\n                if (!this.data?.subSpaceId) { errors.push(`agent.data.subSpaceId falsy (E: d4ea57fd6b1c5cbc1e18a084de2f7725)`) }\n                if (!this.data?.subSpaceId.match(UUID_REGEXP)) {\n                    errors.push(`agent.data.subSpaceId must match regexp: ${UUID_REGEXP}. (E: f381eff533aa3f4713316f93f7f1dc25)`);\n                }\n\n                if (this.data.name) {\n                    if (!this.data.name.match(AGENT_NAME_REGEXP)) {\n                        errors.push(`agent name must match regexp: ${AGENT_NAME_REGEXP}`);\n                    }\n                } else {\n                    errors.push(`agent name falsy (E: 1351325107e5ac5ea6b7b789b73de125)`);\n                }\n\n                if (this.data.description) {\n                    if (!this.data.description.match(AGENT_DESC_REGEXP)) {\n                        errors.push(`agent description must match regexp: ${AGENT_DESC_REGEXP}`);\n                    }\n                }\n\n                // todo: add validation for available functions\n                // todo: add other validation\n                // todo: break out data validation and rel8ns validation into separate functions\n            } else {\n                errors.push(`this.data falsy (E: f5f151e11b12cad814b37ecad7c74a25)`)\n            }\n\n            return errors;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    protected override async initialize(): Promise<void> {\n        const lc = `${this.lc}[${this.initialize.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: ce38519ac4bef52844a558fe31cda825)`); }\n            await super.initialize();\n\n            // I'm not sure how to handle metaspace init...for now, it is up to\n            // a factory function\n            this._metaspace = await getGlobalMetaspace_waitIfNeeded();\n\n\n            const ibGibProxy = new LiveProxyIbGib<AgentWitnessIbGib_V1>();\n            await ibGibProxy.initialized;\n            if (!ibGibProxy.contextUpdated$) {\n                throw new Error(`(UNEXPECTED) ibGibProxy.contextUpdated$ falsy? (E: e8840870af18091e6e4d52490ddca825)`);\n            }\n            ibGibProxy.contextUpdated$.subscribe(fnObs({\n                next: async (nextIbGib) => {\n                    // new agent dto\n                    const lcNext = `${lc}[ibGibProxy.contextUpdated$][next]`;\n                    if (logalot) { console.log(`${lcNext} nextIbGib: ${pretty(nextIbGib)} (I: 96c846357b94fda2cefa615aed88c325)`); }\n                    await this.handleContextUpdated();\n                },\n                error: async (e) => {\n                    debugger; // error in component.ibGibProxy.contextUpdated$ observable?\n                    console.error(`${lc}[ibGibProxy.contextUpdated$][error] what up? ${extractErrorMsg(e)}`);\n                },\n            }));\n\n            // while (!this._metaspace) {\n            //     console.log(`${lc} this.metaspace falsy for instance ${this.instanceId} (W: 3a89c85b6bb34c1c53a92ded9f66a925)`);\n            //     await delay(30);\n            // }\n\n            // this will populate the properties that are driven by data/rel8ns,\n            // e.g., availableFunctions, commentIbGibs_system/chat, etc.\n            if (this.ib && this.gib && this.data) {\n                const dto = this.toIbGibDto();\n                await this.loadIbGibDto(dto);\n                const space = await this._metaspace.getLocalUserSpace({\n                    localSpaceId: dto.data?.superSpaceId,\n                });\n                if (!space) { throw new Error(`couldn't get local space with agent.data.superSpaceId (${dto.data?.superSpaceId})? (E: 0fc1b8a8ffa26f39d8a15218ec818725)`); }\n                await this.ibGibProxy?.setWrappedIbGib({ ibGib: dto, space });\n            } else {\n                // this happens when you just new up empty ctor, e.g. new\n                // AgentWitnessGemini_V1(), so the caller will be responsible\n                // for calling loadIbGibDto\n                if (logalot) { console.log(`${lc} agent is \"empty\". not loading dto at this time, caller is responsible for calling loadIbGibDto (I: 06dba19d74d5695fe7d1957889283725)`); }\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * loads the new context (agent witness ibgib) if it's different than what\n     * is already loaded in this agent instance.\n     */\n    protected async handleContextUpdated(): Promise<void> {\n        const lc = `${this.lc}[${this.handleContextUpdated.name}]`;\n        try {\n            if (!this.ibGibProxy) { throw new Error(`(UNEXPECTED) this.ibGibProxy falsy but we're within handleContextUpdated handler? (E: a88fa85e8f27bd7f72c207389ebfbc25)`); }\n            if (!this.ibGibProxy.ibGib) {\n                throw new Error(`(UNEXPECTED) this.ibGibProxy.ibGib falsy but we're within the handleContextUpdated handler? (E: ca60b8f0a60a3e3d652c3018102d1825)`);\n            }\n            debugger; // want to see this early runs\n            if (!this.gib) {\n                debugger; // error state? this.gib falsy? want to see this\n                console.error(`${lc} not sure if error, but this.gib is falsy when we get a new context down the pipeline? (E: 8501d8aee4db7b8461587f38f0bbb125)`);\n            }\n            if (getIbGibAddr({ ibGib: this }) !== getIbGibAddr({ ibGib: this.ibGibProxy.ibGib })) {\n                const nProxy = this.ibGibProxy!.ibGib!.data!.n ?? 0;\n                const nThis = this.data?.n ?? 0;\n                if (nProxy <= nThis) {\n                    debugger; // no change but different address?\n                    console.error(`${lc} issue with \"new\" proxy context and the current this.data.n with different addresses. divergent timelines? (E: 15c698eb4488cbae2db0e778fec15825)`)\n                }\n                // we have not loaded the proxy's new ibGib\n                await this.loadIbGibDto(this.ibGibProxy.ibGib);\n                await delay(200); // hack to reduce the possibility of the proxy not updating elsewhere\n            } else {\n                // already loaded this ibGib, i.e., context updated is not new\n                console.error(`${lc} ibgibProxy new context is no different than current. this is NOT necessarily an error, I just want to see this when it happens. nothing is being done here, we're just not loading the \"new\" ibgib dto. (E: eff668b2e858ded448366d58e4dd6825)`)\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        }\n    }\n\n    // protected override async handleContextUpdate({ update }: { update: IbGibTimelineUpdateInfo; }): Promise<void> {\n    //     const lc = `${this.lc}[${this.handleContextUpdate.name}]`;\n    //     try {\n    //         if (logalot) { console.log(`${lc} starting... (I: 86abc8464278b3dcb8d078b830853825)`); }\n    //         // super.handleContextUpdate // to nav into the super function\n    //         super.handleContextUpdate\n    //         debugger; // just want to see if this is hit on updates?\n    //     } catch (error) {\n    //         console.error(`${lc} ${extractErrorMsg(error)}`);\n    //         throw error;\n    //     } finally {\n    //         if (logalot) { console.log(`${lc} complete.`); }\n    //     }\n    // }\n\n    /**\n     * each agent has access to its own local ibgib space for its internal contents. this gets the local\n     * space that corresponds to the agent's spaceId, or if it does not already\n     * exist, it creates the space (and updates the bootstrap).\n     * @returns space object that the agent will use as its local space.\n     *\n     * todo: refactor this with options to possibly return other spaces as well (metaspace, subSpace, superSpace). if options is undefined, do existing behavior of getting only the subspace\n     */\n    protected async getSubSpace(): Promise<IbGibSpaceAny> {\n        const lc = `[${this.getSubSpace.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: a2ec2c5e8f5fdf95c8c571b2b1b9e925)`); }\n            // await this.initialized; // what if this fn is called within initialize?\n            const { _metaspace: metaspace } = this;\n            if (!metaspace) { throw new Error(`(UNEXPECTED) this.metaspace falsy? after init this.metaspace is expected to be set. (E: 4519a8feaf4489389be679598f274425)`); }\n            let space = await metaspace.getLocalUserSpace({\n                localSpaceId: this.data!.subSpaceId,\n            });\n            if (!space) {\n                const validationErrors = await this.validateThis();\n                if (validationErrors.length > 0) { throw new Error(`this agent has validation errors: ${validationErrors} (E: 9a0c6125cf89789ddb1610cf5a752225)`); }\n                if (!this.data) { throw new Error(`(UNEXPECTED) this.data falsy? (E: 06e30e1d53fd4935333c7cf7e10db425)`); }\n                space = await metaspace.createLocalSpaceAndUpdateBootstrap({\n                    allowCancel: false,\n                    zeroSpace: metaspace.zeroSpace,\n                    spaceName: this.name + this.uuid.substring(0, 5), // arbitrary\n                    createBootstrap: false,\n                });\n            }\n            if (!space) { throw new Error(`(UNEXPECTED) space still falsy after creating locally? (E: 037ef1e6f54a675d0367227fdae16525)`); }\n            return space;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * helper that retrieves this agent's local space given by\n     * this.data.superSpaceId\n     */\n    protected async getSuperSpace(): Promise<IbGibSpaceAny> {\n        const lc = `[${this.getSuperSpace.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 55fba9bcaf9539cc2219e03cda200525)`); }\n            // await this.initialized; // what if this fn is called within initialize?\n            const { _metaspace: metaspace } = this;\n            if (!metaspace) { throw new Error(`(UNEXPECTED) this.metaspace falsy? after init this.metaspace is expected to be set. (E: 107f670c99832c573a7e5de18d58c325)`); }\n            if (!this.data) { throw new Error(`(UNEXPECTED) this.data falsy? (E: a4341b8753678fcba7877b6319769b25)`); }\n            if (!this.data.superSpaceId) { throw new Error(`(UNEXPECTED) this.data.superSpaceId falsy? (E: 0429fe44df5b56bf2ac67d38cde56325)`); }\n\n            const space = await metaspace.getLocalUserSpace({\n                localSpaceId: this.data!.superSpaceId,\n            });\n            if (!space) { throw new Error(`(UNEXPECTED) superSpace falsy? this.data.superSpaceId: ${this.data.superSpaceId} (E: fd9435212e8b87e4b60034bf9e797f25)`); }\n\n            return space;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    abstract addTexts(opts: AddTextsOpts): Promise<CommentIbGib_V1[]>;\n    /**\n     * quick and dirty, does not\n     */\n    abstract promptOneOff(opts: PromptOneOffOpts): Promise<string | undefined>;\n\n    protected _activeContext: LiveProxyIbGib | undefined = undefined;\n\n    /**\n     * Updates the agent.data to have a soft link to an ibgib's timeline (via\n     * its tjp addr) that defines the agent's current context.\n     *\n     * This is kinda like describing what \"directory\" the agent is \"in\", though\n     * remember, ibgib's contain both intrinsic meaning (like a file) and\n     * extrinsic meaning (like a folder/dir).\n     *\n     * @see {@link SetActiveContextOpts}\n     */\n    async setActiveContext(opts: SetActiveContextOpts): Promise<void> {\n        const lc = `${this.lc}[${this.setActiveContext.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n            const { contextIbGib, loggingInfo } = opts;\n\n            // #region init/validation\n\n            if (!this.data) { throw new Error(`(UNEXPECTED) this.data falsy? (E: ab5377fda6bc324638722d9832bab925)`); }\n            if (!contextIbGib) { throw new Error(`(UNEXPECTED) contextIbGib falsy? (E: 694525e512cfdd12c14e1213dbaab925)`); }\n            if (!contextIbGib.data) { throw new Error(`(UNEXPECTED) contextIbGib.data falsy? (E: f337252a23c822bcbd76144540050825)`); }\n            const contextIbGibAddr = getIbGibAddr({ ibGib: contextIbGib });\n            const contextTjpAddr = getTjpAddr({ ibGib: contextIbGib });\n            if (!contextTjpAddr) { throw new Error(`(UNEXPECTED) contextTjpAddr falsy? contextIbGib (${contextIbGibAddr}) is expected to be a living ibgib with a tjp address (i.e. a timeline). This means it should have a rel8ns.tjp or data.isTjp should be truthy. (E: d756d1e862d2cccfed4a5807737e9a25)`); }\n\n            // #endregion init/validation\n\n            // update this agent's internals if applicable\n\n            if (this.data?.['@currentContextTjpAddr'] === contextTjpAddr) {\n                if (logalot) { console.log(`${lc} this.data.@currentContextTjpAddr already set to the same addr. (I: 9f0d58ec65eee3ca2aec528f1328c325)`); }\n                // return; /* <<<< returns early */\n            } else {\n                // we're guaranteed to have a different context\n                await this.mut8Self({\n                    dataToAddOrPatch: {\n                        \"@currentContextTjpAddr\": contextTjpAddr,\n                    }\n                });\n            }\n\n            // subscribe to updates to context\n            if (!this._activeContext) {\n                // create the proxy itself\n                const proxy = new LiveProxyIbGib();\n                await proxy.initialized;\n\n                // subscribe to context updates - these are just when newer\n                // versions come down the pipe, which i don't think we're too\n                // interested in at the moment. we're more interested in the new\n                // children\n                const lcContextUpdated = `${lc}[contextUpdated]`;\n                if (!proxy.contextUpdated$) { throw new Error(`(UNEXPECTED) proxy.contextUpdated$ falsy? (E: 868c5e3bf025baa6d1ae727ab1160c25)`); }\n                proxy.contextUpdated$.subscribe(fnObs({\n                    next: async (nextIbGib) => {\n                        console.log(`${lcContextUpdated}[next] nextIbGib: ${pretty(nextIbGib)}`);\n                    },\n                    complete: async () => {\n                        debugger; // complete? in agent subscribe context update\n                        throw new Error(`${lcContextUpdated}[complete] (UNEXPECTED) agent active context subscription complete? i honestly don't know if this hits. (E: 786d26ab23e4313db7ae2e08c70a7425)`);\n                    },\n                    error: async (e) => {\n                        debugger; // error in agent subscribe context update\n                        console.error(`${lcContextUpdated}[error] ${extractErrorMsg(e)}`);\n                    },\n                }));\n\n                // subscribe to new children to add text/pics to the agent's\n                // awareness (context window/dynamic prompt when next prompt\n                // occurs) and act accordingly\n                const lcNewContextChild = `${lc}[newContextChild]`;\n                if (!proxy.newContextChild$) { throw new Error(`(UNEXPECTED) proxy.newContextChild$ falsy? (E: 123cf5624c3d2a6308aafc0c41f8a925)`); }\n                proxy.newContextChild$.subscribe(fnObs({\n                    next: async (newChild) => {\n                        // await delay(500); // magic delay temporary hack due to answering before the new child propagates to other event listeners on the timeline. namely, when user inputs text, it adds to the context ibgib. then this agent hears that and then imediately adds to the context ibgib before the chronologys has a chance to answer. shouldn't matter, but what can ya do on no fing funding. looks like this delay still happens\n                        console.log(`${lcNewContextChild}[next] newChild: ${pretty(newChild)}`);\n                        if (!newChild.data) { throw new Error(`newChild.data falsy? (E: a654134a2695c176971b0cd1426ced25)`); }\n                        if (isComment({ ibGib: newChild })) {\n                            /**\n                             * idempotent, otherwise we get repeats\n                             */\n                            const alreadyDoneCommentTjpAddrs = this.commentIbGibs_chat.map(x => {\n                                return getTjpAddr({ ibGib: x }) ?? getIbGibAddr({ ibGib: x });\n                            });\n                            const newChildTjpAddr = getTjpAddr({ ibGib: newChild }) ?? getIbGibAddr({ ibGib: newChild });\n                            if (alreadyDoneCommentTjpAddrs.includes(newChildTjpAddr)) {\n                                console.log(`${lc} already did this comment (${newChildTjpAddr}) (I: bce18642bb9babeb553e6188d7ae2825)`);\n                                return; /* <<<< returns early */\n                            }\n                            const { safeIbCommentMetadataText } = parseCommentIb({ ib: newChild.ib });\n\n                            const { textSrc, } = parseAddlMetadataTextForAgentText({\n                                addlMetadataText: safeIbCommentMetadataText ?? '',\n                                ifError: 'warn',\n                            });\n                            const isSystem = newChild.data.text.startsWith('system: ');\n                            await this.addTexts({\n                                infos: [\n                                    {\n                                        textSrc: textSrc ?? TextSource.UNKNOWN,\n                                        commentIbGib: newChild as CommentIbGib_V1,\n                                        isSystem,\n                                    }\n                                ]\n                            });\n                            // trigger doPrompt? for now we'll just do it when\n                            // the text comes directly from a human, but in the\n                            // future we either should pass this through a\n                            // smaller model or have some defined triggers like\n                            // if the text contains \"@[agent.data.name]\"\n                            if (textSrc === TextSource.HUMAN) {\n                                if (!isSystem) {\n                                    await this.doPrompt();\n                                } else {\n                                    console.log(`${lc} system prompt has been modified. (I: d21c26f0a3fa12e2a874925882f39825)`);\n                                }\n                            }\n                        } else {\n                            console.warn(`${lcNewContextChild} non-comment newChild. probably not a warning proper, but at this stage I'm only expecting comments ignoring... (W: e664834af4791ddcde19bfd4f7063e25)`);\n                        }\n                    },\n                    complete: async () => {\n                        debugger; // complete? in agent newContextChild\n                        throw new Error(`${lcNewContextChild}[complete] (UNEXPECTED) agent active context subscription complete? i honestly don't know if this hits. (E: 88202d1f7554330d3dfca0237c2d6525)`);\n                    },\n                    error: async (e) => {\n                        debugger; // error in agent newContextChild\n                        console.error(`${lcNewContextChild}[error] ${extractErrorMsg(e)}`);\n                    },\n                }));\n\n                // set the backing property\n                this._activeContext = proxy;\n\n                // is this enough if the proxy changes its internal wrapped ibgib?\n            }\n            if (!this._activeContext) {\n                throw new Error(`(UNEXPECTED) this._activeContext still falsy after we just initialized it? (E: 584f2f672b9ae7c979dde693eafb7a25)`);\n            }\n            await this._activeContext.setWrappedIbGib({ ibGib: contextIbGib });\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    // protected async subscribeToContextUpdates(): Promise<void> {\n    //     const lc = `[${this.subscribeToContextUpdates.name}]`;\n    //     try {\n    //         if (logalot) { console.log(`${lc} starting... (I: 871a18a5a0abd7e1177fde3270c12425)`); }\n\n    //     } catch (error) {\n    //         console.error(`${lc} ${extractErrorMsg(error)}`);\n    //         throw error;\n    //     } finally {\n    //         if (logalot) { console.log(`${lc} complete.`); }\n    //     }\n    // }\n\n    async updateName({ name }: { name: string }): Promise<void> {\n        const lc = `${this.lc}[${this.updateName.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n\n            if (name === this.name) {\n                console.warn(`${lc} agent (${this.uuid}) already is named ${name}. returning early...  (W: genuuid)`);\n                return; /* <<<< returns early */\n            } else {\n                if (AGENT_NAME_REGEXP.test(name)) {\n                    // we're guaranteed to have a different name\n                    await this.mut8Self({\n                        dataToAddOrPatch: {\n                            name: name,\n                        }\n                    });\n                } else {\n                    throw new Error(`invalid name ${name}. must match regexp: ${AGENT_NAME_REGEXP.source} (E: 507a2bfc0aaa60bd7bb608d253239e25)`);\n                }\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    async updateAvailableFunctions({\n        availableFunctions,\n    }: {\n        availableFunctions: APIFunctionInfo[],\n    }): Promise<void> {\n        const lc = `${this.lc}[${this.updateAvailableFunctions.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 68f1bfa343925a657f8c0545b191c725)`); }\n\n            // // first prune existing available functions...\n            // await this.pruneDeprecatedAvailableFunctions_ifApplicable({\n            //     dto: this.toIbGibDto() as AgentWitnessIbGib_V1,\n            //     metaspace: this._metaspace!,\n            //     superSpace: await this.getSuperSpace(),\n            // });\n\n            const functionsToAdd: APIFunctionInfo[] = [];\n            // const removedFunctions: string[] = []; // implement later as needed\n\n            for (const incomingFn of availableFunctions) {\n                if (!this.availableFunctions.has(incomingFn.nameOrId)) {\n                    const functionInfo = getAllFunctionInfos().get(incomingFn.nameOrId);\n                    if (functionInfo) {\n                        functionsToAdd.push(functionInfo);\n                    } else {\n                        console.error(`(UNEXPECTED) ${incomingFn} function not registered with getAllFunctionInfos()? skipping adding this function to the agent... (E: e860fe13c02677b274ac0e7df2587a25)`);\n                        continue;\n                    }\n                }\n            }\n\n            if (functionsToAdd.length > 0) {\n                console.log(`${lc} adding newly found functions to agent: ${functionsToAdd.map(x => x.nameOrId)}. (I: ab2b0ae6a62b3ced6a5f1e2e8cec4f25)`)\n                await this.addAvailableFunctions(functionsToAdd);\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * I'm taking this out temporarily because it's non-trivial to figure out\n     * where/when this should happen. We can just do the deprecated list and when\n     * we go to populate the actual availble function infos, we check the\n     * deprecated list and skip the ones that are deprecated. So in the agent's\n     * dto ibgib (data.availableFunctions) the function name will still be\n     * listed, but at runtime it will not be populated.\n     */\n    // protected async pruneDeprecatedAvailableFunctions_ifApplicable({\n    //     dto,\n    //     metaspace,\n    //     superSpace,\n    // }: {\n    //     dto: AgentWitnessIbGib_V1,\n    //     metaspace: MetaspaceService,\n    //     superSpace: IbGibSpaceAny,\n    // }): Promise<void> {\n    //     const lc = `${this.lc}[${this.pruneDeprecatedAvailableFunctions_ifApplicable.name}]`;\n    //     try {\n    //         if (logalot) { console.log(`${lc} starting... (I: e6d5f13a3c4892f5c878239744a00825)`); }\n\n    //         if (!dto.data) { throw new Error(`(UNEXPECTED) this.data falsy? (E: 83c531982725611401ebe3ecc7d1c825)`); }\n    //         if (!dto.data.availableFunctionNameOrIds || dto.data.availableFunctionNameOrIds.length === 0) {\n    //             console.warn(`${lc} dto agent (${getIbGibAddr({ ibGib: dto })} has falsy/empty availableFunctionNameOrIds? maybe this is normal, but here writing this code, i think this seems unexpected. (W: 6a15d8e2fdc8e5d38a9045d39bb06825))`);\n    //             return; /* <<<< returns early */\n    //         }\n\n    //         // deprecated, so modify the data and reload the dto\n    //         const deprecatedNameOrIds = dto.data.availableFunctionNameOrIds.filter(x => DeprecatedFunctionInfoNames.includes(x));\n    //         if (deprecatedNameOrIds.length > 0) {\n    //             console.log(`${lc} deprecatedNameOrIds.length > 0, so we're going to mut8 this agent to exclude these.`);\n    //             const newAgentIbGibDto = await mut8Timeline({\n    //                 timeline: dto,\n    //                 mut8Opts: {\n    //                     dataToAddOrPatch: {\n    //                         availableFunctionNameOrIds:\n    //                             dto.data.availableFunctionNameOrIds.filter(x => !deprecatedNameOrIds.includes(x)),\n    //                     }\n    //                 },\n    //                 metaspace,\n    //                 space: superSpace,\n    //                 timelineIndexInfo: {\n    //                     rel8nName: AGENT_REL8N_NAME,\n    //                     type: dto.data.type,\n    //                 },\n    //             });\n    //             await super.loadIbGibDto(newAgentIbGibDto);\n    //         }\n    //     } catch (error) {\n    //         console.error(`${lc} ${extractErrorMsg(error)}`);\n    //         throw error;\n    //     } finally {\n    //         if (logalot) { console.log(`${lc} complete.`); }\n    //     }\n    // }\n\n    /**\n     * Performs the {@link mut8} transform on this agent and does extra\n     * plumbing.\n     */\n    protected async mut8Self<TData extends AgentWitnessData_V1 = AgentWitnessData_V1>({\n        dataToAddOrPatch,\n    }: {\n        dataToAddOrPatch: Partial<TData>,\n    }): Promise<void> {\n        const lc = `${this.lc}[${this.mut8Self.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: f4618832a0fe07ff8c89cea889d20725)`); }\n\n\n            // get lock on self\n            const metaspace = this._metaspace;\n            if (!metaspace) { throw new Error(`(UNEXPECTED) metaspace falsy? (E: genuuid)`); }\n            const superSpace = await metaspace.getLocalUserSpace({\n                lock: false,\n                localSpaceId: this.data!.superSpaceId,\n            });\n            if (!superSpace) { throw new Error(`couldn't get local superSpace given by this.data.superSpaceId (${this.data!.superSpaceId}) (E: genuuid)`); }\n\n            const { tjpGib } = getGibInfo({ gib: this.gib });\n            if (!tjpGib) { throw new Error(`(UNEXPECTED) this.gib (${this.gib}) has no tjpGib? (E: 75b8dcb82b58d3b0db40b39149023e25)`); }\n            await execInSpaceWithLocking({\n                fn: async () => {\n                    const agentsSvc = getAgentsSvc();\n                    /**\n                     * always update at least in memory latest\n                     */\n                    await agentsSvc.updateOrSetLatestAgent({\n                        agent: this,\n                        throwIfNewerFound: false,\n                    });\n\n                    const resMut8 = await mut8({\n                        type: 'mut8',\n                        src: this.toIbGibDto(),\n                        dataToAddOrPatch,\n                        dna: true,\n                        nCounter: true,\n                    }) as TransformResult<AgentWitnessIbGib_V1>;\n\n                    await metaspace.persistTransformResult({\n                        resTransform: resMut8,\n                        space: superSpace,\n                    });\n\n                    const newAgentIbGib = resMut8.newIbGib;\n                    await this.loadIbGibDto(newAgentIbGib);\n                    await agentsSvc.updateOrSetLatestAgent({\n                        agent: this,\n                        throwIfNewerFound: true, // we **just** created what should be the latest, so throw if this isn't the case\n                    });\n\n                    await metaspace.registerNewIbGib({\n                        ibGib: newAgentIbGib,\n                        space: superSpace,\n                    });\n\n                    // update special index\n                    // this will do its own locking on the agent's type\n                    await updateAgentIndex({\n                        newAgentIbGib,\n                        metaspace,\n                        space: superSpace,\n                        type: this.data!.type,\n                    });\n                },\n                scope: tjpGib,\n                secondsValid: 60,\n                maxDelayMs: 100,\n                maxLockAttempts: Number.MAX_SAFE_INTEGER, // drive by seconds valid\n                space: superSpace,\n                callerInstanceId: this.instanceId,\n            });\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n\n    }\n\n    /**\n     * gets a list of api function infos available as tools to this agent, i.e., atow this are available for function calling in Gemini API. implementation is a WIP.\n     *\n     * @returns array of api function infos available as tools to this agent\n     */\n    protected getAvailableFunctions(): readonly APIFunctionInfo[] {\n        return Array.from(this.availableFunctions.values());\n    }\n    protected getComments_System(): readonly CommentIbGib_V1[] {\n        return [...this.commentIbGibs_system];\n    }\n    protected getComments_Chat(): readonly CommentIbGib_V1[] {\n        return [...this.commentIbGibs_chat];\n    }\n\n    // abstract addAvailableFunctions(functionInfos: APIFunctionInfo[]): Promise<void>;\n    // override async addAvailableFunctions(functionInfos: APIFunctionInfo[]): Promise<void> {\n    async addAvailableFunctions(functionInfos: APIFunctionInfo[]): Promise<void> {\n        const lc = `[${this.addAvailableFunctions.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 273525464ec540fc9cba565e608db925)`); }\n            if (!functionInfos) { throw new Error(`(UNEXPECTED) functionInfos falsy? (E: 19cf2b7c9ee1115f0a3f7f62fbf77825)`); }\n            if (functionInfos.length === 0) {\n                console.warn(`${lc} functionInfos.length === 0? why is this being called with no functions? returning early without doing anything. (W: 86c6dc4fad3c1ddcac697d5636b1eb25)`);\n                return; /* <<<< returns early */\n            }\n            const agentsSvc = getAgentsSvc();\n            /**\n             * always update at least in memory latest\n             */\n            await agentsSvc.updateOrSetLatestAgent({\n                agent: this,\n                throwIfNewerFound: false,\n            });\n            functionInfos.forEach(x => {\n                if (this.availableFunctions.has(x.nameOrId)) {\n                    console.warn(`${lc} this.availableFunctions already has an entry for ${x.nameOrId}. replacing anyway. (W: ef2372a27be67174cb3605eac2c85c25)`)\n                }\n                this.availableFunctions.set(x.nameOrId, x);\n            });\n\n            await this.mut8Self({\n                dataToAddOrPatch: {\n                    availableFunctionNameOrIds: Array.from(this.availableFunctions.keys()),\n                }\n            })\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n\n    /**\n     * Generates the prompt text for the LLM by concatenating system and chat\n     * comments. This method is meant to be overridden by descendant classes if\n     * needed.\n     *\n     * @returns A {@link TPromptInfo} object that will be used to prompt {@link _genAI}\n     * @throws {Error} If there is an error parsing the addlMetadataText, or if no metaspace is set, or if there are no chat comment ibgibs. (why are we prompting?)\n     */\n    abstract composePromptInfo(): Promise<TPromptInfo>;\n\n    /**\n     * Calls the text-based API to get a response based on the given prompt.\n     * This method is meant to be overridden by descendant classes if needed.\n     *\n     * @param {string} prompt - The text prompt to send to the API.\n     * @returns {Promise<PromptAPIResult>} - The response from the API.\n     * @throws {Error} If the api is not supported or if there is an error with the Gemini API call.\n     */\n    protected abstract callTextAPI(info: PromptInfo): Promise<TPromptResult>;\n\n    // #region doPrompt\n\n    /**\n     * Orchestrates the prompting of the agent, combining system and chat history,\n     * and processing any function calling that is returned from the API.\n     * This method is called via the witness function when it receives a ROOT input.\n     * @returns {Promise<void>}\n     * @throws {Error} If there is an error getting the prompt text, calling the text API, or processing the response.\n     */\n    async doPrompt(): Promise<void> {\n        const lc = `[${this.doPrompt.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: e7f1a7845cdf1bdce1f12d74c71a6425)`); }\n\n            if (!this.data) { throw new Error(`(UNEXPECTED) this.data falsy? (E: 3c528e2376a2f2600b347b2c183a5225)`); }\n\n            const promptTextInfo = await this.composePromptInfo();\n            if (logalot) { console.log(`${lc} promptTextInfo: ${pretty(promptTextInfo)} (I: b769b5f2a47623a99f78210994d90525)`); }\n\n            const apiResult = await this.callTextAPI(promptTextInfo);\n\n            if (logalot) { console.log(`${lc} api result:`, apiResult, `(I: e4d2c767eb3d6e38d83123d684a07425)`); }\n\n            if (\"text\" in apiResult) {\n                await this.doPrompt_text(apiResult.text);\n            } else {\n                const { functionCalls } = apiResult; // assert here that functionCalls is present\n                await this.doPrompt_functionCalls({ functionCalls }); // will call recursively if applicable\n            }\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n    * handles text when there are no function calls\n    * @param text string\n    */\n    protected async doPrompt_text(text: string): Promise<void> {\n        const lc = `${this.lc}[${this.doPrompt_text.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: a2b9c21f3b2b058d355d16421e2b4425)`); }\n            text ||= '[no text returned from the model]';\n            if (this.fnOutputText) {\n                // this indeed is occasionally hit, including when an agent\n                // hasn't actually been initialized and just text is returned.\n                this.fnOutputText(text);\n            } else {\n                console.log(`${lc} no fnOutputText set. Text Response: ${text} (I: 5936517474b10b214257781a24b10425)`);\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    /**\n     * @protected\n     * Handles the prompt function calls when there are one or more calls\n     * requested by the LLM.\n     *\n     * * parses, validates, executes those function calls\n     * * creates associated function info ibgibs\n     * * creates Function Call Request comment ibgib and relates this to this agent\n     * * recursively calls doPrompt if indicated by the LLM (if they want to be\n     *   reprompted after the function calls)\n     *\n     * @param {string[]} functionCalls are raw stringified JSON fn calls requested by the LLM\n     */\n    protected async doPrompt_functionCalls({ functionCalls }: { functionCalls: string[] }): Promise<void> {\n        const lc = `${this.lc}[${this.doPrompt_functionCalls.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: a4f1b581517a9c2a9187e9f8f3519925)`); }\n            if (functionCalls.length === 0) {\n                throw new Error(`(UNEXPECTED) functionCalls.length is zero? (E: 6434b8515a435a59b331452b563f4425)`);\n            }\n\n            // we must first create the function info ibgibs, because the FCR\n            // comment ibgib requires the ibgibs' addresses in both the\n            // data.text and rel8ns\n            const functionInfoIbGibs =\n                await this.doPrompt_functionCalls_createFunctionInfoIbGibsAndExecFunctionCalls({ functionCalls });\n            await this.doPrompt_functionCalls_addFunctionCallRequestComment({ functionInfoIbGibs });\n\n            // if the model wants a reprompt on **ANY** of the functions, we set the \"decompression\" text here\n            const repromptRequested =\n                functionInfoIbGibs.some(x => {\n                    return !!x.data?.repromptWithResult &&\n                        x.data.fnName !== 'tellUser';\n                },\n                );\n            if (repromptRequested) {\n                const transientDecompressionPromptText = await this.doPrompt_functionCalls_getTransientDecompressionPromptForNextPrompt({ functionInfoIbGibs });\n                if (transientDecompressionPromptText.length > 0) {\n                    console.log(`${lc} transientDecompressionPromptText: ${transientDecompressionPromptText} (I: 11c11d544b7c8f8f8e7e5f7c1a9e3625)`);\n                    this.transientDecompressionPromptText = transientDecompressionPromptText;\n                    await this.rePrompt();\n                } else {\n                    console.warn(`${lc} (UNEXPECTED) there is no decompression text? (W: 6ce5da95c1c89a7ec48a00fbc1d11825)`)\n                }\n            } else {\n                if (logalot) { console.log(`${lc} no repromptWithResult. returning early. (I: 9c0113c958c7404534291f6700325925)`); }\n            }\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    protected async doPrompt_functionCalls_createFunctionInfoIbGibsAndExecFunctionCalls({\n        functionCalls,\n    }: {\n        functionCalls: string[],\n    }): Promise<FunctionInfoIbGib_V1[]> {\n        const lc = `${this.lc}[${this.doPrompt_functionCalls_createFunctionInfoIbGibsAndExecFunctionCalls.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: adc094bc98cb076a4aaf729f70adce25)`); }\n            if (!this.data) { throw new Error(`(UNEXPECTED) this.data falsy? (E: d071328283b2cf880ff0ccd499c22b25)`); }\n            if (!this.data.uuid) { throw new Error(`(UNEXPECTED) this.data.uuid falsy? (E: 8acd2f793e4b5a368dbcf1d8d1e6e825)`); }\n            const metaspace = this._metaspace;\n            if (!metaspace) { throw new Error(`(UNEXPECTED) metaspace falsy? (E: acf8a69e853eb8663f1dd0f79a823e25)`); }\n\n            const functionInfoIbGibs: FunctionInfoIbGib_V1[] = [];\n            for (const functionCallStr of functionCalls) {\n                try {\n                    if (logalot) { console.log(`${lc} processing functionCall: ${functionCallStr} (I: a0c0b22b3c6b6c4b674a5a9c8c8b9e25)`); }\n\n                    let functionInfoIbGib: FunctionInfoIbGib_V1 | undefined = undefined;\n                    let functionCallParsedObj: any | undefined = undefined;\n                    let parseErrorMsg: string | undefined = undefined;\n                    let functionInfo: APIFunctionInfo | undefined = undefined;\n                    let functionArgs: any = undefined;\n                    let functionName: string = '';\n\n                    // #region get functionCallParsedObj\n                    // can we turn this into a helper? This doesn't require this agent state, right?\n                    try {\n                        functionCallParsedObj = JSON.parse(functionCallStr);\n                        functionName = functionCallParsedObj?.name ?? '';\n                        if (!functionName) { throw new Error(`functionName (functionCallParsedObj.name) falsy (E: e2397d675863a12b7609495b0007a025)`); }\n                        if (logalot) { console.log(`${lc} functionCallParsedObj:`, pretty(functionCallParsedObj), `(I: 750f097243b85644d111971e0f929c25)`); }\n\n                        functionInfo = getAllFunctionInfos().get(functionCallParsedObj.name);\n                        if (!functionInfo) {\n                            throw new Error(`no APIFunctionInfo found that matches functionName (${functionName}) (E: 9d36b6472ec5cdf95e4f498292449925)`);\n                        }\n                        // todo: validate function call json against the OpenAPI parameters defined in the api function\n\n                        functionArgs = functionCallParsedObj.args;\n                        // todo: validate args of function call\n                        if (logalot) { console.log(`${lc} valid params (I: a4d5c13c79a2405c8d20464b42083325)`) };\n                    } catch (error: any) {\n                        parseErrorMsg = `${lc} invalid functionCallParsedObj. error: ${extractErrorMsg(error)}. functionCallStr: ${functionCallStr}.  (E: 1687a24c5a3667d34689a09f8f753125)`;\n                        console.error(parseErrorMsg);\n                        functionCallParsedObj = undefined;\n                    }\n                    // #endregion get functionCallParsedObj\n\n                    if (functionInfo) {\n                        if (logalot) { console.log(`${lc} found functionInfo: ${functionInfo.nameOrId} (I: 837c7a8200689a0b2314b73057812b25)`); }\n                        let fnResult: any | undefined = undefined;\n                        let fnComplete = false;\n                        let execErrorMsg: string | undefined = undefined;\n\n                        // #region execute the functionInfo.functionImpl\n                        try {\n                            if (logalot) { console.log(`${lc} calling function impl for ${functionInfo.nameOrId} (I: b145d08186782089c18564305f0f1125)`); }\n\n                            fnResult = await functionInfo.fnViaCmd(functionArgs);\n                            fnComplete = true;\n                            if (logalot) { console.log(`${lc} functionImpl complete for ${functionInfo.nameOrId}. result:`, pretty(fnResult), `(I: e19d476f489261263165914750472d25)`); }\n                        } catch (error) {\n                            execErrorMsg = `${lc} could not call functionImpl for ${functionInfo.nameOrId}: ${extractErrorMsg(error)} (E: 9c0e97f29a9290f9d57637b7053f0c25)`;\n                            console.error(execErrorMsg);\n                        }\n                        // #endregion execute the functionInfo.functionImpl\n\n                        const resCreate = await createFunctionInfoIbGib({\n                            api: this.data.api,\n                            model: this.data.model,\n                            agentId: this.data.uuid!,\n                            fnRawRequest: functionCallStr,\n                            fnName: functionName,\n                            fnArgs: functionCallParsedObj.args,\n                            repromptWithResult: functionCallParsedObj.args?.repromptWithResult ?? false,\n                            fnResult,\n                            fnComplete,\n                            execErrorMsg,\n                            parseErrorMsg: undefined,\n                            saveInSpace: true,\n                            metaspace,\n                            space: await this.getSuperSpace(),\n                        });\n                        functionInfoIbGib = resCreate.newIbGib;\n                    } else {\n                        const resCreateErrored = await createFunctionInfoIbGib({\n                            api: this.data.api,\n                            model: this.data.model,\n                            agentId: this.data.uuid,\n                            fnRawRequest: functionCallStr,\n                            fnName: functionName,\n                            fnArgs: functionCallParsedObj.args,\n                            repromptWithResult: functionCallParsedObj.args?.repromptWithResult ?? false,\n                            fnResult: undefined,\n                            fnComplete: undefined,\n                            execErrorMsg: undefined,\n                            parseErrorMsg,\n                            saveInSpace: true,\n                            metaspace,\n                            space: await this.getSuperSpace(),\n                        });\n                        functionInfoIbGib = resCreateErrored.newIbGib;\n                    }\n\n                    if (!functionInfoIbGib) { throw new Error(`(UNEXPECTED) functionInfoIbGib falsy? we should have guaranteed to create one at this point. (E: 97c4ce12c7372adfeebfd45181b73f25)`); }\n                    functionInfoIbGibs.push(functionInfoIbGib);\n                } catch (error) {\n                    console.error(`${lc} ${extractErrorMsg(error)}`);\n                    throw error;\n                } finally {\n                    if (logalot) { console.log(`${lc} complete.`); }\n                }\n            } // end iterate functionCalls (raw JSON strings)\n\n            if (functionInfoIbGibs.length === 0) {\n                throw new Error(`(UNEXPECTED) functionInfoIbGibs.length === 0? We expect at least one to be created (E: a8f81c56377cdbdeb468af6b21879825)`);\n            }\n\n            return functionInfoIbGibs;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    protected async doPrompt_functionCalls_addFunctionCallRequestComment({\n        functionInfoIbGibs\n    }: {\n        functionInfoIbGibs: FunctionInfoIbGib_V1[]\n    }): Promise<void> {\n        const lc = `${this.lc}[${this.doPrompt_functionCalls_addFunctionCallRequestComment.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 5000adac5e8c4a7158a720c38f56b325)`); }\n            const metaspace = this._metaspace;\n            if (!metaspace) { throw new Error(`(UNEXPECTED) metaspace falsy? (E: d7275731461d8d0526af3088553ae525)`); }\n            const superSpace = await this.getSuperSpace();\n\n            // this is the actual data.text string\n            const fcrText = taggifyForPrompt({\n                tagText: FUNCTION_CALL_REQUEST_COMMENT_TAG,\n                contentText: functionInfoIbGibs.map(x => getIbGibAddr({ ibGib: x })).join('\\n'),\n                randomIdLength: 4,\n            });\n\n            const addlMetadataText = getAddlMetadataTextForAgentText({ textSrc: 'ai', other: 'functionCallRequest' });\n            const resComment: TransformResult<CommentIbGib_V1> =\n                await createCommentIbGib({\n                    text: fcrText,\n                    addlMetadataText,\n                    saveInSpace: true,\n                    space: superSpace,\n                });\n            // now we have the starting comment ibgib, but we want to relate the\n            // actual function info ibgibs via the function info rel8nName.\n            const resRel8FunctionInfosToFCR = await rel8({\n                type: 'rel8',\n                src: resComment.newIbGib,\n                rel8nsToAddByAddr: {\n                    [FUNCTION_INFO_REL8N_NAME]: functionInfoIbGibs.map(x => getIbGibAddr({ ibGib: x })),\n                },\n                dna: true,\n                nCounter: true,\n            }) as TransformResult<CommentIbGib_V1>;\n            const functionCallRequestComment = resRel8FunctionInfosToFCR.newIbGib;\n            await metaspace.persistTransformResult({\n                resTransform: resRel8FunctionInfosToFCR,\n                space: superSpace,\n            });\n            await metaspace.registerNewIbGib({\n                ibGib: functionCallRequestComment,\n                space: superSpace,\n            });\n\n            await this.addTexts({ infos: [{ textSrc: 'ai', commentIbGib: functionCallRequestComment }], });\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    protected async doPrompt_functionCalls_getTransientDecompressionPromptForNextPrompt({\n        functionInfoIbGibs\n    }: {\n        functionInfoIbGibs: FunctionInfoIbGib_V1[]\n    }): Promise<string> {\n        const lc = `${this.lc}[${this.doPrompt_functionCalls_getTransientDecompressionPromptForNextPrompt.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: c245f78f6c78a98d62375a9f14b3d625)`); }\n\n            let contentTexts: string[] = [];\n            for (const functionInfoIbGib of functionInfoIbGibs) {\n                try {\n                    const functionInfoAddr = getIbGibAddr({ ibGib: functionInfoIbGib });\n                    if (!functionInfoIbGib.data) { throw new Error(`(UNEXPECTED) !functionInfoIbGib.data? functionInfoAddr: ${functionInfoAddr} (E: 7815e4854513c26b889517a9bd7e0d25)`); }\n                    const { fnRawRequest, fnComplete, fnResult } = functionInfoIbGib.data;\n                    const dataSlice = { fnRawRequest, fnComplete, fnResult };\n                    const contentText = taggifyForPrompt({\n                        tagText: functionInfoAddr,\n                        contentText: pretty(dataSlice),\n                        randomIdLength: undefined, // don't need an id since we have a unique ibgib addr as the tag\n                    });\n                    contentTexts.push(contentText);\n                } catch (error) {\n                    console.error(`${lc} could not call functionImpl: ${extractErrorMsg(error)} (E: 2a3b8b37e146c524b67119e3a74e3d25)`)\n                }\n            }\n            return contentTexts.join('\\n');\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    // #endregion doPrompt\n\n    /**\n     * naive counter for reprompt asked for by the model\n     */\n    repromptCount: number = 0;\n    /**\n     * naive cap for reprompt asked for by the model\n     */\n    repromptMax: number = 12;\n    /**\n     * recursively calls doPrompt depending on {@link repromptCount} and {@link repromptMax}\n     */\n    async rePrompt(): Promise<void> {\n        const lc = `${this.lc}[${this.rePrompt.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: b6af34214acf07f9ca8c1d03c0011525)`); }\n            if (this.repromptCount < this.repromptMax) {\n                this.repromptCount++;\n                await this.doPrompt();\n            } else {\n                console.log(`${lc} already reached repromptMax (${this.repromptMax}). reprompt aborting. $(I: dacefb501dab2a1ee173ce8558657725)`);\n                this.repromptCount = 0;\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    async witness(arg: IbGib_V1): Promise<IbGib_V1> {\n        if (arg.ib === IB && arg.gib === GIB) {\n            // root called, which in this class is a request to doPrompt.\n            if (this.getComments_Chat().length > 0) {\n                await this.doPrompt();\n            }\n            return ROOT;\n        } else {\n            // TODO: Implement other witness logic for the agent. for now we're just ignoring this, but in the future, we need to redesign this class more towards ibgib style: functions create args that are funneled to this, or at the very least, the functions, if successful, are memoized via this witness function after-the-fact and this witness gets updated. its internal state (`this.data` and `this.rel8ns`) is changed, so therefore `this.gib` needs to be updated and most likely this witness needs to be updated/persisted in its local space. but since we're still feeling out the overall architecture, this would be too much overhead for something that might change in the near future.\n            throw new Error(`arg (${pretty(arg)}) not implemented. only expect ${ROOT} right now to trigger doPrompt. (E: 24da0ad7333b6bbb359d1be425db3c25)`);\n        }\n    }\n}\n\nexport type AgentWitnessAny = AgentWitness_V1<any, any, any>;\n", "/**\n * @module agent-witness-gemini-v1.mts\n *\n * ## MIGRATING TO @google/genai NOTES\n *\n * * Different Part types (TextPart, FunctionCallPart) are apparently \"unified\" in the new structure as just Part\n */\nimport { FunctionCallPart, FunctionResponsePart, } from './gemini-types.mjs';\nimport {\n    Part, GenerateContentResponse, Content, GoogleGenAI, SendMessageParameters,\n    CreateChatParameters, FunctionCallingConfigMode, FunctionCall,\n} from '@google/genai';\n\nimport { clone, delay, extractErrorMsg, getTimestampInTicks, pretty } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';\nimport { Ib, IbGibAddr, TransformResult } from '@ibgib/ts-gib/dist/types.mjs';\nimport { IbGib_V1, IbGibData_V1, IbGibRel8ns_V1 } from '@ibgib/ts-gib/dist/V1/types.mjs';\nimport { getIbGibAddr } from '@ibgib/ts-gib/dist/helper.mjs';\nimport { ROOT_ADDR } from '@ibgib/ts-gib/dist/V1/constants.mjs';\nimport { getGibInfo } from '@ibgib/ts-gib/dist/V1/transforms/transform-helper.mjs';\nimport { CommentIbGib_V1 } from '@ibgib/core-gib/dist/common/comment/comment-types.mjs';\nimport { createCommentIbGib, parseCommentIb } from '@ibgib/core-gib/dist/common/comment/comment-helper.mjs';\nimport { execInSpaceWithLocking } from '@ibgib/core-gib/dist/witness/space/space-helper.mjs';\nimport { appendToTimeline, Rel8nInfo } from '@ibgib/core-gib/dist/timeline/timeline-api.mjs';\n\nimport { GLOBAL_LOG_A_LOT } from '../../../constants.mjs';\nimport { getAllFunctionInfos, getDeprecatedFunctionInfoNames } from '../../../api/api-index.mjs';\nimport {\n    AddTextsOpts, AgentWitnessData_V1, AgentWitnessIbGib_V1, AgentWitnessRel8ns_V1,\n    PromptOneOffOpts,\n} from '../agent-types.mjs';\nimport {\n    getAddlMetadataTextForAgentText,\n    parseAddlMetadataTextForAgentText, validateAgentWitnessCommentIbGib\n} from '../agent-helpers.mjs';\nimport {\n    getFunctionCallAndResponseParts, isFunctionCallRequestComment,\n    isPromptInfoGemini, systemPromptEntriesToSystemInstructionContent,\n    textSourceToGeminiRole,\n} from './gemini-helpers.mjs';\nimport { PromptAPIResult_Gemini, PromptInfoEntryGemini, PromptInfoGemini } from './gemini-types.mjs';\nimport { FUNCTION_INFO_REL8N_NAME, FunctionInfoIbGib_V1 } from '../function-info/function-info-one-file.mjs';\nimport { agentIbGibDtoToWitness } from './gemini-agent-factory.mjs';\nimport { getAgentsSvc } from '../agents-service-v1.mjs';\nimport { GEMINI_BACKUP_MODEL_STR, GEMINI_ERROR_DETAILS_TYPE_RETRY_INFO, GEMINI_ERROR_DETAILS_TYPE_RETRY_INFO_RETRY_DELAY_KEY, GEMINI_ERROR_STATUS_MODEL_OVERLOADED, GEMINI_ERROR_STATUS_RATE_QUOTA_EXCEEDED, GEMINI_MAX_TRY_COUNT } from './gemini-constants.mjs';\nimport { AGENT_REL8N_NAME, TextSource } from '../agent-constants.mjs';\nimport { AgentWitness_V1 } from '../agent-one-file.mjs';\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\nexport class AgentWitnessGemini_V1\n    extends AgentWitness_V1<GoogleGenAI, PromptInfoGemini, PromptAPIResult_Gemini> {\n    // extends AgentWitness_V1<GoogleGenerativeAI, PromptInfoGemini, PromptAPIResult_Gemini> {\n    // witness(arg: IbGib_V1): Promise<IbGib_V1 | undefined> {\n    //     throw new Error('Method not implemented.');\n    // }\n    protected lc: string = `[${AgentWitnessGemini_V1.name}]`;\n\n    protected override async validateThis(): Promise<string[]> {\n        const lc = `${this.lc}[${this.validateThis.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 641e211473fc54d5a9ebb4ea44944d25)`); }\n            const errors = await super.validateThis();\n\n            // todo: refactor this into a non-class-method validation helper function for data\n            if (this.data) {\n                console.warn(`${lc} do more validation on this concrete class. (W: fb778a84ccca2ebcefd2ca7845543825)`)\n                // todo: add validation for available functions\n                // todo: add other validation\n                // todo: break out data validation and rel8ns validation into separate functions\n            } else {\n                // this is already done in the super call\n                // errors.push(`this.data falsy (E: f5f151e11b12cad814b37ecad7c74a25)`)\n            }\n\n            return errors;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n\n    /**\n     * not implemented at the moment\n     */\n    protected parseAddlMetadataString<TParseResult>({ ib }: { ib: Ib; }): TParseResult {\n        const lc = `${this.lc}[${this.parseAddlMetadataString.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 080daf4b73f8bb52c70bf0a8f329be25)`); }\n            throw new Error(`not implemented...i've just converted agent witness to a full witness with context and this was the only abstract method required. wasn't being used previously? so i'm not sure why this is here. (E: 129e816d3698f3867ec54c34fcc9a225)`);\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    override async addTexts(opts: AddTextsOpts): Promise<CommentIbGib_V1[]> {\n        const lc = `${this.lc}[${this.addTexts.name}]`;\n        try {\n            const agentsSvc = getAgentsSvc();\n            /**\n             * always update at least in memory latest\n             */\n            await agentsSvc.updateOrSetLatestAgent({\n                agent: this,\n                throwIfNewerFound: false,\n            });\n            const metaspace = this._metaspace;\n            if (!metaspace) { throw new Error(`(UNEXPECTED) metaspace falsy? (E: fd92a81901a83e2698ab2c3d4e702f25)`); }\n            if (opts.infos.length === 0) {\n                console.warn(`${lc} opts.infos.length === 0. So we've called addTexts but with an empty array? returning early. (W: 0d42cd3b26aec45874d0e65450b37d25)`)\n                return []; /* <<<< returns early */\n            }\n\n            const orderedCommentIbGibs_all: CommentIbGib_V1[] = [];\n            const orderedCommentIbGibs_system: CommentIbGib_V1[] = [];\n            const orderedCommentIbGibs_chat: CommentIbGib_V1[] = [];\n            const superSpace = await this.getSuperSpace();\n            // const superSpace = await metaspace.getLocalUserSpace({\n            //     lock: false,\n            //     localSpaceId: this.data!.superSpaceId\n            // });\n\n            // just get the slow damn version in place dude.\n            for (const info of opts.infos) {\n                const { textSrc, isSystem } = info;\n                let { text, commentIbGib, } = info;\n                if (text && commentIbGib) { throw new Error(`(UNEXPECTED) both text and commentIbGib provided? (E: a3fd590db1a5efc301f3c7e66b322f25)`); }\n                if (!text && !commentIbGib) { throw new Error(`(UNEXPECTED) both text and commentIbGib falsy? one or the other is required (E: e08c7c694a17319085adfb75914b2725)`); }\n                const addlMetadataText = getAddlMetadataTextForAgentText({ textSrc });\n                if (commentIbGib) {\n                    if (logalot) { console.log(`${lc} adding existing commentIbGib (I: 72a3f7aafde92f65b168d27605f94625)`); }\n                    // we have an existing commentIbGib, but there are a couple\n                    // of points to consider:\n\n                    // 1. is the comment valid for use in agent witnesses? does\n                    // it have the right metadata? ANSWER: we will validate\n                    // after this if..else block\n\n                    // 2. Does the comment (and its dependency graph) exist in\n                    // the agent's space? A complication for this is what if the\n                    // comment rel8s to some other (especially large) ibgib graph?\n                    // or IOW, what if the comment has some potentially huge\n                    // dependency graph? ANSWER: todo: check superSpace and/or\n                    // add a flag vouching for the dependency graph to exist in\n                    // it.\n\n                    // 3. also persist dependency graph in agent's subSpace?\n                } else {\n                    // just passed in raw text, need to create a new comment ibgib\n                    if (logalot) { console.log(`${lc} creating new commentIbGib for text (I: 72a3f7aafde92f65b168d27605f94625)`); }\n                    if (!text) { throw new Error(`(UNEXPECTED) text falsy still? at this point it should be guaranteed (E: b2deec458f35f22298ccb664d0685125)`); }\n                    const resCreateComment: TransformResult<CommentIbGib_V1> =\n                        await createCommentIbGib({\n                            text,\n                            addlMetadataText,\n                            saveInSpace: true,\n                            space: superSpace,\n                        });\n                    commentIbGib = resCreateComment.newIbGib;\n                    await metaspace.registerNewIbGib({\n                        ibGib: commentIbGib,\n                        space: superSpace,\n                    });\n                    // also persist in agent's subSpace?\n                    // const subSpace = await this.getAgentSpace();\n                    // await metaspace.persistTransformResult({ resTransform: resCreateComment, space: subSpace });\n                    // await metaspace.registerNewIbGib({ ibGib: resCreateComment.newIbGib, space: subSpace });\n                }\n                if (!commentIbGib) { throw new Error(`(UNEXPECTED) commentIbGib still falsy? we should have just created one if it didn't exist (E: 9370b19aa207234db185cd74b57be525)`); }\n                const validationErrors = await validateAgentWitnessCommentIbGib({ ibGib: commentIbGib });\n                if (validationErrors.length > 0) { throw new Error(`validation errors with trying to add a commentIbGib. errors: ${validationErrors} (E: beee1893050f9bcf9842c66831595225)`); }\n                orderedCommentIbGibs_all.push(commentIbGib);\n                if (isSystem) {\n                    orderedCommentIbGibs_system.push(commentIbGib);\n                } else {\n                    orderedCommentIbGibs_chat.push(commentIbGib);\n                }\n\n            }\n\n            // we now have all of the comment ibgibs prepared. we need to add these\n            // to this agent's rel8ns\n\n            const rel8nInfosToAppend: Rel8nInfo[] = [];\n            if (orderedCommentIbGibs_system.length > 0) {\n                rel8nInfosToAppend.push({ rel8nName: 'system', ibGibs: orderedCommentIbGibs_system, });\n            }\n            if (orderedCommentIbGibs_chat.length > 0) {\n                rel8nInfosToAppend.push({ rel8nName: 'chat', ibGibs: orderedCommentIbGibs_chat, });\n            }\n\n            const newAgentIbGib = await appendToTimeline({\n                timeline: this.toIbGibDto(),\n                rel8nInfos: rel8nInfosToAppend,\n                timelineIndexInfo: {\n                    rel8nName: AGENT_REL8N_NAME,\n                    type: this.data!.type,\n                },\n                metaspace,\n                space: superSpace,\n            }) as AgentWitnessGemini_V1;\n\n            // const resRel8 = await rel8({\n            //     type: 'rel8',\n            //     src: this.toIbGibDto(),\n            //     rel8nsToAddByAddr: {\n            //         ['system']: orderedCommentIbGibs_system.map(x => getIbGibAddr({ ibGib: x })),\n            //         ['chat']: orderedCommentIbGibs_chat.map(x => getIbGibAddr({ ibGib: x })),\n            //     },\n            //     dna: true,\n            //     nCounter: true,\n            // }) as TransformResult<AgentWitnessGemini_V1>;\n\n            // await this._metaspace!.persistTransformResult({\n            //     resTransform: resRel8,\n            //     space: superSpace,\n            // });\n\n            // const newAgentIbGib = resRel8.newIbGib;\n\n            await this.loadIbGibDto(newAgentIbGib);\n            await agentsSvc.updateOrSetLatestAgent({\n                agent: this,\n                throwIfNewerFound: true, // we **just** created what should be the latest, so throw if this isn't the case\n            });\n\n            // await metaspace.registerNewIbGib({\n            //     ibGib: newAgentIbGib,\n            //     space: superSpace,\n            // });\n\n            // update special index\n            // await updateAgentIndex({\n            //     newAgentIbGib,\n            //     metaspace,\n            //     space: superSpace,\n            //     type: this.data!.type,\n            // });\n\n            return orderedCommentIbGibs_all;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        }\n    }\n\n    override async composePromptInfo(): Promise<PromptInfoGemini> {\n        const lc = `${this.lc}[${this.composePromptInfo.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 155774d4811b038034342d5750174325)`); }\n            if (!this._metaspace) {\n                throw new Error(`this.metaspace falsy (E: 7232a3a1b4348d460ed1375b32677125)`);\n            }\n            const systemPromptEntries: PromptInfoEntryGemini[] = [];\n            for (const commentIbGib of this.commentIbGibs_system) {\n                const entry = await this.createPromptInfoEntriesFromGeminiComment({ commentIbGib });\n                systemPromptEntries.push(...entry);\n            }\n            const currentContextTjpAddr =\n                this.data?.['@currentContextTjpAddr'] ?? ROOT_ADDR;\n            if (currentContextTjpAddr !== ROOT_ADDR) {\n                systemPromptEntries.push({\n                    src: TextSource.HARDCODED,\n                    // text: commentIbGib.data.text,\n                    content: {\n                        role: textSourceToGeminiRole(TextSource.HARDCODED),\n                        parts: [\n                            {\n                                text: getTextPartForCurrentContextTjpAddr({\n                                    currentContextTjpAddr\n                                })\n                            } satisfies Part // see genai migration note at top of this file\n                            // } satisfies TextPart\n                        ],\n                    }\n                })\n            }\n\n            if (this.commentIbGibs_chat.length === 0) { throw new Error(`(UNEXPECTED) this.commentIbGibs_chat.length === 0? why are we composing prompt info? We are assumed at this point to have added at least one comment ibgib to this agent. (E: a4e3d840946ab8e6dc3fde3e25d6b225)`); }\n            const chatPromptHistoryParts: PromptInfoEntryGemini[] = [];\n            const chatCommentIbGibs_history =\n                this.commentIbGibs_chat.length > 1 ? this.commentIbGibs_chat.slice(0, -1) : [];\n            for (const commentIbGib of chatCommentIbGibs_history) {\n                const entry = await this.createPromptInfoEntriesFromGeminiComment({ commentIbGib });\n                chatPromptHistoryParts.push(...entry);\n            }\n\n            /**\n             * the most recent may be a regular comment or an FCR. if FCR, then\n             * there will be two gemini entries and we need to add the first one\n             * (functionCall part) to our history.\n             */\n            let chatPromptCurrent: PromptInfoEntryGemini;\n            const chatCommentIbGib_current = this.commentIbGibs_chat.at(-1)!; // guaranteed to have at least one element due to previous commentIbGibs_Chat.length check\n            const chatPromptCurrent_rawarray =\n                await this.createPromptInfoEntriesFromGeminiComment({ commentIbGib: chatCommentIbGib_current });\n            if (chatPromptCurrent_rawarray.length === 1) {\n                // regular\n                chatPromptCurrent = chatPromptCurrent_rawarray.at(0)!;\n            } else if (chatPromptCurrent_rawarray.length === 2) {\n                // fcr\n                chatPromptHistoryParts.push(chatPromptCurrent_rawarray.at(0)!); // functionCall entry\n                chatPromptCurrent = chatPromptCurrent_rawarray.at(1)!; // functionResponse entry;\n            } else {\n                throw new Error(`(UNEXPECTED) chatPromptCurrent_rawarray.length !== 1 or 2? We expect at this point either a regular text part or a FCR comment which creates two entries. (E: cd59f978479c20e496da4b0eb86c7d25)`);\n            }\n\n            const resPromptInfo: PromptInfoGemini = {\n                api: 'gemini', // see AgentAPI\n                systemPromptEntries,\n                chatPromptHistoryParts,\n                chatPromptCurrent,\n            };\n\n            if (logalot) { console.log(`${lc} resPromptInfo:`, pretty(resPromptInfo), `(I: 8f17a8c45b9a91e20a5c5064d9114a25)`); }\n\n            return resPromptInfo;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    protected override async callTextAPI(info: PromptInfoGemini): Promise<PromptAPIResult_Gemini> {\n        const lc = `${this.lc}[${this.callTextAPI.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 27885f5b14682646542e9658417b2f25)`); }\n\n            if (!isPromptInfoGemini(info)) { throw new Error(`(UNEXPECTED) info.api !== gemini? we are in the gemini concrete class where this is assumed. (E: 9223647ec96fb3f4eaee32c3fc15d925)`); }\n\n            // #region prepare\n\n            if (!this.data) { throw new Error(`(UNEXPECTED) this.data falsy? (E: 09224b6688fdac884ce88f196b68a425)`); }\n            const { api, model } = this.data;\n            if (api !== 'gemini') { throw new Error(`api not supported: ${api} (E: 7e5c7c17988a666a86e72299630c7f25)`); }\n\n            // todo: refactor gemini-specific code into its own descendant class\n            if (logalot) { console.log(`${lc} calling gemini api with model: ${model} (I: 6208942a419e9041bb037384135a0c25)`); }\n\n            const apiKey = await this.fnGetAPIKey();\n            if (!apiKey) {\n                console.error(`${lc} apiKey falsy. did you set this.fnGetAPIKey (E: d964596b1538c0327209a92e97a54d25)`);\n                return {\n                    text: 'no api key entered so no LLM chat happening. enter a gemini api key and donate/invest!',\n                }; /* <<<< returns early */\n            }\n            this._genAI ??= new GoogleGenAI({ apiKey });\n            // this._genAI ??= new GoogleGenerativeAI(apiKey);\n\n            const functionDeclarations = Array.from(this.availableFunctions.values()).map(\n                (x) => ({\n                    name: x.nameOrId,\n                    description: x.schema?.description,\n                    parameters: x.schema?.parameters,\n                })\n            );\n\n            if (functionDeclarations.some(x => x.parameters === 'undefined')) {\n                console.error(`${lc} (UNEXPECTED) function schema parameters not defined for all APIFunctionInfo values. (E: ae7227cdd65c0ab4513c7b282a1e4825)`);\n            }\n\n            if (logalot) {\n                console.log(`${lc} Gemini functionDeclarations:`);\n                console.dir(functionDeclarations);\n            }\n\n            // #endregion prepare\n\n            const { systemPromptEntries, chatPromptHistoryParts, chatPromptCurrent } = info;\n\n\n            /**\n             * we may add decompression text parts to the most recent entry\n             */\n            const chatPromptCurrent_final = clone(chatPromptCurrent) as PromptInfoEntryGemini;\n            if (logalot) { console.log(`chatPromptCurrent_final (before decompression): ${pretty(chatPromptCurrent_final)} (I: bbd4c7b9f3225afe9da1761918d0ac25)`) }\n\n            if (logalot) { console.warn(`${lc} skipping decompression for the moment. if we add decompression text when the last comment is a function response part, then we'll error out. Need to rethink compression/decompression with the new function call/response workflow. (W: 7478439f9bbbde30a1eab3c5189ea625)`); }\n            // if (this.transientDecompressionPromptText) {\n            //     const taggedDecompressionText = taggifyForPrompt({\n            //         tagText: CONTEXT_DECOMPRESSION_TAG,\n            //         contentText: this.transientDecompressionPromptText,\n            //         randomIdLength: 4,\n            //     });\n            //     const decompressionTextPart: TextPart = {\n            //         text: taggedDecompressionText,\n            //     };\n            //     // we insert the decompression BEFORE the current part, but only\n            //     chatPromptCurrent_final.content.parts = [decompressionTextPart, ...chatPromptCurrent_final.content.parts];\n\n            //     // `${taggedDecompressionText}\\n${chatPromptCurrent}`;\n            //     this.transientDecompressionPromptText = undefined;\n            // }\n\n            let result: GenerateContentResponse | undefined = undefined;\n            // let result: GenerateContentResult | undefined = undefined;\n\n            /**\n             * need to be able to call this function with retries with different\n             * models, depending on error code received when generating text.\n             *\n             * ## driving intent\n             *\n             * I am getting a 503 error saying the model is overloaded. We need\n             * to have a backup model that is hardcoded and updated via source\n             * code until we get a more robust model system.\n             *\n             * @param modelStr to use\n             * @param isRetry if true, this indicates this is aleady a retry and should throw if fails\n             */\n            // const fnGoModel = async (modelStr: string) => {\n            //     if (!this._genAI) { throw new Error(`(UNEXPECTED) this._genAI falsy? (E: 503a0d9e3f729de7653ee3565b017b25)`); }\n            //     const genModel = this._genAI.getGenerativeModel({\n            //         model: modelStr,\n            //         systemInstruction: systemPromptEntriesToSystemInstructionContent({ systemPromptEntries }),\n            //         tools: [{ functionDeclarations }],\n            //         toolConfig: {\n            //             functionCallingConfig: {\n            //                 // mode: FunctionCallingMode.AUTO, // can be either text or function call, this is the default\n            //                 mode:\n            //                     info.overrideFunctionCallingMode ??\n            //                     FunctionCallingMode.ANY, // MANDATES a function call. If this is not used, the model gets confused, but maybe this will be fixed after we get better function response feedback in place.\n            //             },\n            //         },\n            //     });\n            //     /**\n            //      * We start a \"chat\", _BUT ONLY TO USE THE HISTORY MECHANISM_.\n            //      * Really we use this as a one-off, but we do not know how to mimic\n            //      * the \"history\" so that the model understands to only respond to\n            //      * the most recent prompt.\n            //      */\n            //     const chat = genModel.startChat({\n            //         history: chatPromptHistoryParts.map(x => x.content),\n            //     });\n            //     result = await chat.sendMessage(chatPromptCurrent.content.parts);\n            //     return result;\n            // }\n            // interface ChatConfigParams {\n            //     model: string;\n            //     history: Content[];\n            //     config: GenerateContentConfig;\n            // }\n\n            const fnGoModel = async (modelStr: string) => {\n                if (!this._genAI) {\n                    throw new Error(`(UNEXPECTED) this._genAI falsy? (E: 503a0d9e3f729de7653ee3565b017b25)`);\n                }\n\n                const historyContents: Content[] = chatPromptHistoryParts.map(x => x.content);\n\n                const chatConfig: CreateChatParameters = {\n                    model: modelStr,\n                    history: historyContents,\n                    config: {\n                        systemInstruction: systemPromptEntriesToSystemInstructionContent({ systemPromptEntries }),\n                        tools: [{ functionDeclarations }],\n                        toolConfig: {\n                            functionCallingConfig: {\n                                mode: info.overrideFunctionCallingMode ?? FunctionCallingConfigMode.ANY,\n                            },\n                        },\n                    }\n                };\n\n                const chat = this._genAI.chats.create(chatConfig);\n\n                // The 'sendMessage' method requires a `message` property in its parameters object.\n                // The message content itself can be a string or Part[] (PartListUnion).\n\n                // Prepare the message parameters:\n                const messageParams: SendMessageParameters = {\n                    message: chatPromptCurrent.content.parts as Part[], // Cast to Part[] to satisfy the type\n                };\n\n                // The result is typed as GenerateContentResponse\n                const result: GenerateContentResponse = await chat.sendMessage(messageParams);\n\n                return result;\n            };\n\n            let tryCount = 0;\n            let modelStr = model;\n            do {\n                tryCount++;\n                try {\n                    result = await fnGoModel(modelStr);\n                    break;\n                } catch (error) {\n                    const errorMessage = error.message;\n                    const status = (error as any).status ?? '[STATUS?]';\n\n                    // if (error.status && error.status === GEMINI_ERROR_STATUS_MODEL_OVERLOADED) {\n                    if (errorMessage.includes(`${GEMINI_ERROR_STATUS_MODEL_OVERLOADED}`)) {\n                        // model is overloaded, try using the backup\n                        console.error(`${lc}[fnGoModel][${modelStr}] error trying to get result from model. will try using backup model (${GEMINI_BACKUP_MODEL_STR}) for this next call. error (${error.status}): ${extractErrorMsg(error)} (E: a5cd7d174183518058da57cc6d0d8a25)`);\n                        modelStr = GEMINI_BACKUP_MODEL_STR;\n                    } else if (errorMessage.includes(`${GEMINI_ERROR_STATUS_RATE_QUOTA_EXCEEDED}`)) {\n                        // model is overloaded, try using the backup\n                        console.error(`${lc}[fnGoModel][${modelStr}] error trying to get result from model. will try using backup model (${GEMINI_BACKUP_MODEL_STR}) for this next call. error (${error.status}): ${extractErrorMsg(error)} (E: a5cd7d174183518058da57cc6d0d8a25)`);\n                        modelStr = GEMINI_BACKUP_MODEL_STR;\n                    } else {\n                        console.error(`${lc}[fnGoModel][${modelStr}] error trying to get result from model. error (${error.status}): ${extractErrorMsg(error)} (E: a67d595c8ed313d458369d4d0b3e7f25)`);\n                    }\n                }\n                await delay(2_000); // nothing fancy right now\n            } while (!result && tryCount < GEMINI_MAX_TRY_COUNT);\n            if (!result) { throw new Error(`couldn't get result from model (E: ede013a53f875d99a96a2e257c7e7125)`); }\n\n            // const result = await genModel.generateContent(finalChatPrompt);\n            // const enhancedResult = result.response as EnhancedGenerateContentResponse;\n            // const functionCalls = enhancedResult.functionCalls();\n\n            // The 'result' IS the GenerateContentResponse object directly.\n            const response: GenerateContentResponse = result;\n\n            // Function calls are no longer accessed via a method, but by manually scanning the 'candidates' structure.\n\n            // We need a way to extract the function calls from the parts array manually.\n            const functionCalls: FunctionCall[] = [];\n            const parts = response.candidates?.[0]?.content?.parts || [];\n\n            for (const part of parts) {\n                if (part.functionCall) {\n                    functionCalls.push(part.functionCall);\n                }\n            }\n\n            if (!functionCalls || functionCalls.length === 0) {\n                if (logalot) { console.warn(`${lc} no function calls in response, returning text. (W: 3a4b8c940983b9e28e3f04c01a09bb25)`); }\n                if (!response.text) { throw new Error(`response generated no function calls and no response.text (E: 6123b8cacfb834105ad3160cfc4ef825)`); }\n                return { text: response.text };\n            }\n\n            if (logalot) {\n                console.log(`${lc} Gemini function calls:`);\n                console.dir(functionCalls);\n            }\n\n            return {\n                functionCalls: functionCalls.map(x => JSON.stringify(x, null, 2))\n            };\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    protected async createPromptInfoEntriesFromGeminiComment({\n        commentIbGib,\n    }: {\n        commentIbGib: CommentIbGib_V1,\n    }): Promise<PromptInfoEntryGemini[]> {\n        const lc = `[${this.createPromptInfoEntriesFromGeminiComment.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 826a9d6b120d96532afbe1f7a22e8d25)`); }\n\n            const validationErrors = await validateAgentWitnessCommentIbGib({ ibGib: commentIbGib });\n            if (validationErrors.length > 0) {\n                throw new Error(`validation errors with commentIbGib. Cannot create a prompt info entry. errors: ${validationErrors} (E: beee1893050f9bcf9842c66831595225)`);\n            }\n\n            // we know we have a valid agent witness comment at this point. So we\n            // can pull extract the textSrc, etc., from it.\n            let { safeIbCommentMetadataText: addlMetadataText } = parseCommentIb({ ib: commentIbGib.ib });\n            if (!addlMetadataText) { throw new Error(`(UNEXPECTED) addlMetaDataText falsy? we just validated the comment ibgib, so there should be the expected shape of the comment.ib. (E: facf5801f9ba158b1526dd09d0e1b325)`); }\n            let { textSrc, timestampInTicks, errorMsg, other } = parseAddlMetadataTextForAgentText({ addlMetadataText, ifError: 'warn' });\n            if (errorMsg) { throw new Error(`(UNEXPECTED) errorMsg is truthy after parse addl metadata from comment.ib? we just validated the comment ibgib, so there should be the expected shape of the comment.ib. (? (E: 7fd7fac50851916f39ceccbe93446425)`); }\n            if (!commentIbGib.data) { throw new Error(`(UNEXPECTED) commentIbGib.data falsy? (E: 8ce54d28219237feddf8f25b5846cc25)`); }\n            if (!commentIbGib.data.text) { throw new Error(`(UNEXPECTED) commentIbGib.data.text falsy? (E: 8556fc95c401d1b5441454fceb8f2f25)`); }\n\n            const isFCR = isFunctionCallRequestComment({ ibGib: commentIbGib });\n            if (isFCR) {\n                // 1. FCR should generate two entries: the function call entry and\n                // the function response entry\n                // 2. the role of the function call should be \"model\" and the role for\n                // the function response should be \"function\"\n                // 3. The FCR's info ibgibs must be loaded and iterated, with each\n                // one containing info for a part of the function call entry and a\n                // part for the function response entry.\n                const functionInfoIbGibs: FunctionInfoIbGib_V1[] =\n                    await this.getFunctionInfoIbGibs({ fcrCommentIbGib: commentIbGib });\n                // const functionCallParts: Part[] = [];\n                const functionCallParts: FunctionCallPart[] = [];\n                const functionResponseParts: FunctionResponsePart[] = [];\n                for (let functionInfoIbGib of functionInfoIbGibs) {\n                    let { call, response } = getFunctionCallAndResponseParts({ functionInfoIbGib });\n                    if (!call) { throw new Error(`(UNEXPECTED) call falsy? (E: 5c8f3bd6de3b300e1c105b9603bb7b25)`); }\n                    if (!response) { throw new Error(`(UNEXPECTED) response falsy? (E: d0388c838975c93126c1a6d64f781d25)`); }\n                    if (call.functionCall!.name !== response.functionResponse.name) {\n                        throw new Error(`(UNEXPECTED) functionCall.name !== functionResponse.name? (E: e49f0d60093354db2b6ad17fdf86d425)`);\n                    }\n                    functionCallParts.push(call);\n                    functionResponseParts.push(response);\n                }\n\n                // at this point we have a collection of one or more function\n                // call parts that correspond to a single chat message that the\n                // model generated, so these will be role: \"model\".  we also\n                // have function response parts that directly correspond to\n                // those function call parts one-to-one, in order. So we add two entries to the chat:\n                // 1. msg with function call entry/entries from role: \"model\"\n                // 2. msg with function response entry/entries from role: \"function\"\n\n                const functionCallEntry: PromptInfoEntryGemini = {\n                    src: TextSource.AI,\n                    content: {\n                        role: textSourceToGeminiRole('ai'),\n                        parts: functionCallParts,\n                    },\n                };\n                const functionResponseEntry: PromptInfoEntryGemini = {\n                    src: TextSource.FUNCTION, // throws error: Content with role 'user' can't contain 'functionResponse' part\n                    // src: TextSource.AI,\n                    content: {\n                        // role: textSourceToGeminiRole('function'), // user\n                        role: textSourceToGeminiRole(TextSource.FUNCTION), // model?\n                        parts: functionResponseParts,\n                    },\n                };\n\n                return [functionCallEntry, functionResponseEntry];\n            } else {\n                // non-FCR should just generate a single text part entry\n                return [{\n                    src: textSrc,\n                    // text: commentIbGib.data.text,\n                    content: {\n                        role: textSourceToGeminiRole(textSrc),\n                        parts: [\n                            {\n                                text: commentIbGib.data.text\n                            } satisfies Part // see genai migration note at top of this file\n                            // } satisfies TextPart\n                        ],\n                    }\n                }];\n            }\n\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    override async promptOneOff(opts: PromptOneOffOpts): Promise<string | undefined> {\n        const lc = `${this.lc}[${this.promptOneOff.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n            const { text, systemInstructions, } = opts;\n            if (!text) { throw new Error(`(UNEXPECTED) opts.text falsy? (E: genuuid)`); }\n\n            if (!this.data) { throw new Error(`(UNEXPECTED) this.data falsy? (E: genuuid)`); }\n            const { api, model } = this.data;\n            if (api !== 'gemini') { throw new Error(`api not supported: ${api} (E: genuuid)`); }\n\n            // todo: refactor gemini-specific code into its own descendant class\n            if (logalot) { console.log(`${lc} calling gemini api with model: ${model} (I: genuuid)`); }\n\n            const apiKey = await this.fnGetAPIKey();\n            if (!apiKey) {\n                console.error(`${lc} apiKey falsy. did you set this.fnGetAPIKey (E: genuuid)`);\n                return undefined; /* <<<< returns early */\n            }\n            this._genAI ??= new GoogleGenAI({ apiKey });\n\n            /**\n             * need to be able to call this function with retries with different\n             * models, depending on error code received when generating text.\n             *\n             * ## driving intent\n             *\n             * I am getting a 503 error saying the model is overloaded. We need\n             * to have a backup model that is hardcoded and updated via source\n             * code until we get a more robust model system.\n             *\n             * @param modelStr to use\n             * @param isRetry if true, this indicates this is aleady a retry and should throw if fails\n             */\n            const fnGoModel = async (modelStr: string) => {\n                if (!this._genAI) { throw new Error(`(UNEXPECTED) this._genAI falsy? (E: fbe235713d48f0d8e87cd0b88ec54825)`); }\n                const chatConfig: CreateChatParameters = {\n                    model: modelStr,\n                    config: {\n                        systemInstruction: systemInstructions,\n                    }\n                };\n                const chat = this._genAI.chats.create(chatConfig);\n                const response = await chat.sendMessage({ message: text });\n                if (response.text) {\n                    return response.text;\n                } else {\n                    throw new Error(`response.text empty/falsy, potentially blocked by safety settings (E: a21a78c9471f27a42c07d1c859187825)`);\n\n                }\n                // const genModel = this._genAI.getGenerativeModel({\n                //     model: modelStr,\n                //     systemInstruction: systemInstructions,\n                // });\n                // const result = await genModel.generateContent(text);\n                // if (result.response) {\n                //     return result.response.text();\n                // } else {\n                //     throw new Error(`not implemented (E: bbf05fe00da23d5b16c223bd200eaa25)`);\n                // }\n            }\n\n            let result: string | undefined = undefined;\n            let tryCount = 0;\n            const modelsToTry: string[] = [];\n            if (opts.modelOverrides && opts.modelOverrides.length > 0) {\n                modelsToTry.push(...opts.modelOverrides);\n            } else {\n                modelsToTry.push(model);\n            }\n            if (opts.modelBackupOverrides && opts.modelBackupOverrides.length > 0) {\n                modelsToTry.push(...opts.modelBackupOverrides);\n            } else {\n                modelsToTry.push(GEMINI_BACKUP_MODEL_STR);\n            }\n            let modelIndex = 0;\n            let retryDelayInSeconds = 1;\n            do {\n                tryCount++;\n                retryDelayInSeconds++;\n                const modelStr = modelsToTry[modelIndex];\n                try {\n                    // debugger; // step through the new error mechanism and look for how to determine if the model is overloaded vs quota exceeded\n                    // let x: ErrorDetails\n                    result = await fnGoModel(modelStr);\n                    break;\n                } catch (error) {\n                    if (error instanceof Error) {\n                        const errorMessage = error.message;\n                        const status = (error as any).status ?? '[STATUS?]';\n\n                        // if (error.status && error.status === GEMINI_ERROR_STATUS_MODEL_OVERLOADED) // see migration notes at top of file\n                        if (errorMessage.includes(`${GEMINI_ERROR_STATUS_MODEL_OVERLOADED}`)) {\n                            if (modelIndex === modelsToTry.length - 1) {\n                                // already is the final backup model, so we just fail/wait\n                                console.error(`${lc}[fnGoModel][${modelStr}] error trying to get result from model: GEMINI_ERROR_STATUS_MODEL_OVERLOADED ${GEMINI_ERROR_STATUS_MODEL_OVERLOADED}. we are already using the final backup model in our modelsToTry, so SOL here. will try again... error (${status}): ${extractErrorMsg(error)} (E: 9bb63cb520b8bd3bb85d2ca20715c825)`);\n                            } else {\n                                // model is overloaded, try using the next one\n                                modelIndex++;\n                                const nextModelStr = modelsToTry[modelIndex];\n                                console.error(`${lc}[fnGoModel][${modelStr}] error trying to get result from model: GEMINI_ERROR_STATUS_MODEL_OVERLOADED ${GEMINI_ERROR_STATUS_MODEL_OVERLOADED}. will try using the next model (${nextModelStr}) for this next call. error (${status}): ${extractErrorMsg(error)} (E: b07a041bb97ea95b03cd6f9856f01525)`);\n                            }\n                            //  else if (error.status && error.status === GEMINI_ERROR_STATUS_RATE_QUOTA_EXCEEDED)\n                        } else if (errorMessage.includes(`${GEMINI_ERROR_STATUS_RATE_QUOTA_EXCEEDED}`)) {\n                            // quota exceeded, try next model or wait for retry\n                            if (modelIndex === modelsToTry.length - 1) {\n                                // already is the final backup model, so we just fail/wait\n                                console.error(`${lc}[fnGoModel][${modelStr}] error trying to get result from model: GEMINI_ERROR_STATUS_RATE_QUOTA_EXCEEDED ${GEMINI_ERROR_STATUS_RATE_QUOTA_EXCEEDED}. we are already using the final backup model, so SOL here. will try again... error (${status}): ${extractErrorMsg(error)} (E: d280c441aa37579bb2cfd29038202525)`);\n                            } else {\n                                // quota exceeded, try using the backup\n                                modelIndex++;\n                                const nextModelStr = modelsToTry[modelIndex];\n                                console.error(`${lc}[fnGoModel][${modelStr}] error trying to get result from model: GEMINI_ERROR_STATUS_RATE_QUOTA_EXCEEDED ${GEMINI_ERROR_STATUS_RATE_QUOTA_EXCEEDED}. will try using the next model (${nextModelStr}) for this next call. error (${status}): ${extractErrorMsg(error)} (E: a9869883fc72bf156f1691183e27ee25)`);\n                            }\n                        } else {\n                            console.error(`${lc}[fnGoModel][${modelStr}] error trying to get result from model. error (${status}): ${extractErrorMsg(error)} (E: a67d595c8ed313d458369d4d0b3e7f25)`);\n                        }\n                    } else {\n                        console.error(`${lc}[fnGoModel][${modelStr}] (UNEXPECTED) error is not instanceof Error? The expected error from the @google/genai lib is supposed to be an instance of Error according to Gemini migration AI. (E: 15df95701e78b35f783d250801092825)`);\n                    }\n                }\n                if (tryCount > 1) {\n                    await delay(retryDelayInSeconds * 1000); // nothing fancy right now\n                }\n            } while (!result && tryCount < GEMINI_MAX_TRY_COUNT);\n\n            return result;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * Gets the function info ibgibs associated with an {@link fcrCommentIbGib}\n     * (Function Call Request IbGib) from this agent's superSpace.\n     *\n     * Note that these are fully loaded ibgibs based on just the addresses of\n     * the FCR.\n     *\n     * @see {@link getSuperSpace}\n     *\n     * @returns the array of function info ibgibs that correspond to the FCR\n     */\n    async getFunctionInfoIbGibs({\n        fcrCommentIbGib\n    }: {\n        /**\n         * Function Call Request ibgib that should contain rel8ns to one or more\n         * {@link FunctionInfoIbGib_V1}.\n         */\n        fcrCommentIbGib: CommentIbGib_V1\n    }): Promise<FunctionInfoIbGib_V1[]> {\n        const lc = `[${this.getFunctionInfoIbGibs.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 976a684b7ae58cda523b17fc0c62e325)`); }\n\n            let resFunctionInfoIbGibs: FunctionInfoIbGib_V1[] = [];\n\n            // #region prepare\n            if (!fcrCommentIbGib) {\n                throw new Error(`${lc} fcrCommentIbGib is falsy. (E: a01c80f415ab8737a81b7b2a2f479f25)`);\n            }\n            if (!fcrCommentIbGib.data) {\n                throw new Error(`${lc} fcrCommentIbGib.data is falsy. (E: a03bc3662a8d6f69c1c077605727a025)`);\n            }\n\n            const metaspace = this._metaspace;\n            if (!metaspace) { throw new Error(`(UNEXPECTED) this.metaspace falsy. (E: 997d071847c5d7e80692f48191244e25)`); }\n\n            const superSpace = await this.getSuperSpace(); // Use getSuperSpace to get the agent's super space.\n            if (!superSpace) { throw new Error(`(UNEXPECTED) superSpace falsy? (E: dd1600f15e1e659c01f73991656a3325)`); }\n            // #endregion prepare\n\n            const functionInfoAddrs = (fcrCommentIbGib.rel8ns?.[FUNCTION_INFO_REL8N_NAME] ?? []) as IbGibAddr[];\n            if (functionInfoAddrs.length === 0) {\n                if (logalot) { console.warn(`${lc} no functionInfoAddrs (I: 5f8965e92c305689c11677a1148b7425)`); }\n                return []; /* <<<< returns early */\n            }\n\n            if (logalot) { console.log(`${lc} functionInfoAddrs: ${functionInfoAddrs} (I: e7b1f5a4576c493326b913e48a505e25)`); }\n\n            // get those ibgibs that correspond to the addrs in a single call\n            // using this agent's metaspace.get and the superSpace\n            const resGetFunctionInfos = await metaspace.get({\n                addrs: functionInfoAddrs,\n                space: superSpace,\n            });\n            if (!resGetFunctionInfos.success || !resGetFunctionInfos.ibGibs || resGetFunctionInfos.ibGibs.length !== functionInfoAddrs.length) {\n                throw new Error(`${lc} could not retrieve function info ibgibs. errorMsg: ${resGetFunctionInfos.errorMsg ?? 'unknown error (E: 164246a6661d49f2b21d1b6769139625)'} (E: 0736d824876e420f91c089925191d425)`);\n            }\n            resFunctionInfoIbGibs = resGetFunctionInfos.ibGibs as FunctionInfoIbGib_V1[];\n            if (logalot) { console.log(`${lc} resFunctionInfoIbGibs: ${pretty(resFunctionInfoIbGibs.map(x => getIbGibAddr({ ibGib: x })))} (I: a5661b5c449608f0e8d773135a599a25)`); }\n\n            return resFunctionInfoIbGibs;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * loads the dto as expected, then sets the class's properties.\n     * @param dto with ibgib props (ib,gib,data,rel8ns)\n     */\n    override async loadIbGibDto(dto: IbGib_V1<AgentWitnessData_V1, AgentWitnessRel8ns_V1>): Promise<void> {\n        const lc = `[${this.loadIbGibDto.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: cb0b1e9e22fce321ca9a26e7a5d4c825)`); }\n            await super.loadIbGibDto(dto);\n            if (!this.data) { throw new Error(`(UNEXPECTED) this.data falsy after load dto? (E: 77aecd066b0bbbd0c66e2658519bdb25)`); }\n\n            const metaspace = this._metaspace;\n            if (!metaspace) { throw new Error(`(UNEXPECTED) metaspace falsy? (E: e5762b1e3f77f84ca338641edc011225)`); }\n            const superSpace = await this.getSuperSpace();\n            // const subSpace = await this.getSubSpace(); // unused now, but will be used once we get subspace mechanism going\n\n            // available functions\n            // first prune existing available functions...\n            // await this.pruneDeprecatedAvailableFunctions_ifApplicable({\n            //     dto, metaspace, superSpace,\n            // });\n\n            // ...now populate this.availableFunctions\n            // we must do this in the timeline lock scope, because if the\n            // timeline is updated mid-execution\n            const fn = async () => {\n                this.availableFunctions = new Map();\n                for (const nameOrId of this.data!.availableFunctionNameOrIds) {\n                    if (!nameOrId) {\n                        throw new Error(`(UNEXPECTED) nameOrId falsy, driven by this.data.availableFunctionNameOrIds? somehow a falsy nameOrId saved? (E: 7b63f177624de2415e1569e96ef8d125)`);\n                    }\n                    const info = getAllFunctionInfos().get(nameOrId);\n                    if (info) {\n                        this.availableFunctions.set(nameOrId, info);\n                    } else {\n                        if (getDeprecatedFunctionInfoNames().includes(nameOrId)) {\n                            if (logalot) { console.log(`${lc} function nameOrId (${nameOrId}) found as deprecated. not adding to available functions on agent. (I: 983864ad5cd8af915fb135580e455425)`); }\n                        } else {\n                            console.error(`no function info in getAllFunctionInfos() found corresponding to nameOrId (${nameOrId}) and this was not found in getDeprecatedFunctionInfoNames(). this is logged here but we're not throwing. (E: db0da9880cf1e414c3f1078d3e9f0b25)`);\n                        }\n                    }\n                }\n\n                // comment ibgibs\n\n                // todo: refactor the following two code blocks with a helper function for DRY (would require a lambda for setting the prop I think but this is a lower priority ATOW 01/2024...do this if I revisit this section of code by necessity)\n                // todo: implement caching for comment ibgibs\n                const rel8dAddrs_system = this.rel8ns?.system ?? [];\n                if (rel8dAddrs_system.length > 0) {\n                    const resGet_systemComments = await metaspace.get({\n                        addrs: rel8dAddrs_system, space: superSpace,\n                    });\n                    if (!resGet_systemComments.success || resGet_systemComments.errorMsg) {\n                        throw new Error(`couldn't get system comments. error: ${extractErrorMsg(resGet_systemComments.errorMsg ?? 'unknown error (E: c0b4d7aab724bcf58e88ffd496de8825)')} (E: 7925d4b5ec3a8f7a648c109941c38a25)`);\n                    } else if ((resGet_systemComments.ibGibs ?? []).length !== rel8dAddrs_system.length) {\n                        throw new Error(`(UNEXPECTED) (resGet_systemComments.ibGibs ?? []).length !== rel8dAddrs_system.length, but resGet.success truthy and resGet.errorMsg falsy? (E: 2055553b602e6c2fe49e956a1e423f25)`);\n                    } else {\n                        this.commentIbGibs_system = resGet_systemComments.ibGibs! as CommentIbGib_V1[];\n                    }\n                }\n                const rel8dAddrs_chat = this.rel8ns?.chat ?? [];\n                if (rel8dAddrs_chat.length > 0) {\n                    const resGet_chatComments = await metaspace.get({\n                        addrs: rel8dAddrs_chat, space: superSpace,\n                    });\n                    if (!resGet_chatComments.success || resGet_chatComments.errorMsg) {\n                        throw new Error(`couldn't get chat comments. error: ${extractErrorMsg(resGet_chatComments.errorMsg ?? 'unknown error (E: c0b4d7aab724bcf58e88ffd496de8825)')} (E: 7925d4b5ec3a8f7a648c109941c38a25)`);\n                    } else if ((resGet_chatComments.ibGibs ?? []).length !== rel8dAddrs_chat.length) {\n                        throw new Error(`(UNEXPECTED) (resGet_chatComments.ibGibs ?? []).length !== rel8dAddrs_chat.length, but resGet.success truthy and resGet.errorMsg falsy? (E: 2055553b602e6c2fe49e956a1e423f25)`);\n                    } else {\n                        this.commentIbGibs_chat = resGet_chatComments.ibGibs! as CommentIbGib_V1[];\n                    }\n                }\n            };\n\n            // const lockScope = await getLockScope({ timeline: this });\n\n            await execInSpaceWithLocking({\n                scope: 'prune',\n                secondsValid: 60,     // Example timeout\n                maxDelayMs: 100,       // Example delay\n                maxLockAttempts: 1800, // Example attempts\n                space: superSpace,\n                callerInstanceId: getTimestampInTicks(),\n                fn,\n            });\n\n            // todo: load subspace artifacts once we get that mechanism going\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n\n    }\n\n}\n\n// register the factory function with the agents svc\nsetTimeout(() => {\n    let agentsSvc = getAgentsSvc();\n    agentsSvc.registerFactory({\n        classname: AgentWitnessGemini_V1.name,\n        fnDtoToAgentWitness: async (dto: IbGib_V1) => {\n            if (!dto.data) {\n                return { applies: false, }\n            } else if (!dto.data.classname) {\n                return { applies: false, }\n            } else if (dto.data.classname === AgentWitnessGemini_V1.name) {\n                const agent = await agentIbGibDtoToWitness({\n                    agentIbGib: dto as AgentWitnessIbGib_V1,\n                });\n                return { applies: true, agent };\n            } else {\n                return { applies: false, }\n            }\n        },\n    })\n});\n\n\nexport function getTextPartForCurrentContextTjpAddr({\n    currentContextTjpAddr\n}: {\n    currentContextTjpAddr: string;\n}): string {\n    const lc = `[${getTextPartForCurrentContextTjpAddr.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 7edafbba277d57eae51af325cf7eb225)`); }\n        const info = getGibInfo({ ibGibAddr: currentContextTjpAddr });\n        // if (info.isPrimitive) {\n        // do I even care at this point? maybe I'll use primitives as some\n        // kind of global variable reference or something...commenting out\n        // because maybe YAGNI\n        // }\n        return `Your current context ibGibAddr is ${currentContextTjpAddr}\\nIt is very important that you use THIS context address. THIS context address takes precedence over previous contexts in your system chat history, because those chats may be from previous sessions per the user's POV. If there are any doubts, like if you're saying something and the user is not responding, then this may be the reason. You should call the function to get your context to be sure you are talking in the right one.`;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n", "import {\n    clone, extractErrorMsg, getUUID,\n} from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';\nimport { IbGibSpaceAny } from '@ibgib/core-gib/dist/witness/space/space-base-v1.mjs';\n\nimport { GLOBAL_LOG_A_LOT } from '../../../constants.mjs';\nimport { AgentWitnessData_V1, AgentWitnessIbGib_V1, AgentWitnessRel8ns_V1, DEFAULT_AGENT_DATA_V1, DEFAULT_AGENT_REL8NS_V1, } from '../agent-types.mjs';\nimport { AgentWitnessGemini_V1 } from './agent-witness-gemini-v1.mjs';\nimport { storageGet } from '../../../storage/storage-helpers.web.mjs';\nimport { CreateConcreteAgentWitnessFactory, CreateNewAgentArg } from '../agent-types.mjs';\nimport type { AgentsService_V1 } from '../agents-service-v1.mjs';\nimport { getGlobalDbName, getGlobalIndexedDbKey_APIKey, getGlobalStoreName } from '../../../helpers.web.mjs';\nimport { AgentWitnessAny } from '../agent-one-file.mjs';\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\n/**\n * factory class to create gemini api agents.\n *\n * This doesn't need to be instantiated necessarily, as this is used via the\n * more general factory function {@link AgentsService_V1.createNewAgent}\n */\nexport class CreateConcreteAgentWitnessFactory_Gemini\n    implements CreateConcreteAgentWitnessFactory {\n    private lc: string = `[${CreateConcreteAgentWitnessFactory_Gemini.name}]`;\n\n    private arg: CreateNewAgentArg;\n\n    constructor(arg: CreateNewAgentArg) {\n        this.arg = arg;\n    }\n\n    async createInitialData(superSpace: IbGibSpaceAny): Promise<AgentWitnessData_V1> {\n        const lc = `${this.lc}[${this.createInitialData.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: f4c8ac488804666077cfc2237972d625)`); }\n\n            const { name, api, model, type, availableFunctions, } = this.arg;\n            if (!model) { throw new Error(`(UNEXPECTED) model falsy? (E: ee7286c772a37fa86236c85f96233625)`); }\n            if (!superSpace.data) { throw new Error(`(UNEXPECTED) superSpace.data falsy? (E: 858d5950b9ef7a0175482a51caaf9c25)`); }\n            if (!superSpace.data.uuid) { throw new Error(`(UNEXPECTED) superSpace.data.uuid falsy? (E: 08867535db1b254d73c050bd5086e525)`); }\n\n            const data = clone(DEFAULT_AGENT_DATA_V1) as AgentWitnessData_V1;\n            if (name) { data.name = name; }\n            data.uuid = await getUUID();\n            data.superSpaceId = superSpace.data.uuid;\n            data.api = api;\n            data.model = model;\n            data.type = type;\n            data.availableFunctionNameOrIds = availableFunctions.map(x => x.nameOrId);\n            data.classname = AgentWitnessGemini_V1.name;\n\n            // if (model) { data.model = model; }\n\n            return data;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    async createInitialRel8ns(): Promise<AgentWitnessRel8ns_V1 | undefined> {\n        const lc = `${this.lc}[${this.createInitialRel8ns.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 2d4933ea3761bd7df701d8d306fb2825)`); }\n\n            const rel8ns = !!DEFAULT_AGENT_REL8NS_V1 ?\n                clone(DEFAULT_AGENT_REL8NS_V1) as AgentWitnessRel8ns_V1 :\n                undefined;\n\n            return rel8ns;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    async createWitness(): Promise<AgentWitnessAny> {\n        const lc = `[${this.createWitness.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 36709dfa0c398d63d64c4f6ba9055625)`); }\n            const { api, model } = this.arg;\n            if (api === 'gemini') {\n                // model is ignored atow 1/2025\n                const witness = new AgentWitnessGemini_V1();\n                await witness.initialized;\n                return witness;\n            } else {\n                throw new Error(`(UNEXPECTED) unknown api: ${api}? only 'gemini' currently implemented (E: 2d1cb22ce787c6c42d4532c260320125)`);\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n\n    }\n\n}\n\n/**\n * Takes an incoming {@link agentIbGib} (dto), creates a new agent witness,\n * initializes it and loads that {@link agentIbGib} dto into it.\n *\n * @returns the full agent witness\n */\nexport async function agentIbGibDtoToWitness({\n    agentIbGib,\n}: {\n    agentIbGib: AgentWitnessIbGib_V1,\n}): Promise<AgentWitnessAny> {\n    const lc = `[${agentIbGibDtoToWitness.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 5a4efefba9e4bdfb942afbe7919fff25)`); }\n        const agentWitness = new AgentWitnessGemini_V1();\n        await agentWitness.initialized;\n        await agentWitness.loadIbGibDto(agentIbGib);\n        agentWitness.fnGetAPIKey = async () => {\n            let apiKey = await storageGet({\n                dbName: getGlobalDbName(),\n                storeName: await getGlobalStoreName(),\n                key: await getGlobalIndexedDbKey_APIKey(),\n            });\n            return apiKey ?? '';\n        }\n        return agentWitness;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n", "import { extractErrorMsg, getTimestampInTicks, pickRandom_Letters, } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { getIbAndGib, getIbGibAddr } from \"@ibgib/ts-gib/dist/helper.mjs\";\nimport { Ib, IbGibAddr } from \"@ibgib/ts-gib/dist/types.mjs\";\nimport { IbGib_V1, } from \"@ibgib/ts-gib/dist/V1/types.mjs\";\nimport { MetaspaceService } from \"@ibgib/core-gib/dist/witness/space/metaspace/metaspace-types.mjs\";\nimport { SpaceId } from \"@ibgib/core-gib/dist/witness/space/space-types.mjs\";\nimport { SpecialIbGibType } from \"@ibgib/core-gib/dist/common/other/other-types.mjs\";\nimport { IbGibSpaceAny } from \"@ibgib/core-gib/dist/witness/space/space-base-v1.mjs\";\nimport { TAG_REL8N_NAME } from \"@ibgib/core-gib/dist/common/tag/tag-constants.mjs\";\nimport { getTjpAddr, toDto } from \"@ibgib/core-gib/dist/common/other/ibgib-helper.mjs\";\nimport { TagIbGib_V1 } from \"@ibgib/core-gib/dist/common/tag/tag-types.mjs\";\nimport { updateSpecialIndex } from \"@ibgib/core-gib/dist/timeline/timeline-api.mjs\";\n\nimport {\n    GLOBAL_LOG_A_LOT, TAG_AGENT_DESCRIPTION, TAG_AGENT_IB, TAG_AGENT_ICON,\n    TAG_AGENT_TEXT,\n} from \"../../constants.mjs\";\nimport { AgentWitnessAny, } from \"./agent-one-file.mjs\";\nimport { AGENT_ATOM, AGENT_REL8N_NAME, isTextSource, TEXT_SOURCE_VALUES, TextSource } from \"./agent-constants.mjs\";\nimport {\n    coupleDomainIbGibWithLocalIbGibViaIndex, getIndexNameFromIbGib,\n    getLocalCoupledIbGibForDomainIbGib, getTagsIbGib\n} from \"../../helpers.mjs\";\nimport { getAgentsSvc } from \"./agents-service-v1.mjs\";\nimport { AddlMetadataTextForAgentTextInfo, AgentIbInfo, AgentWitnessData_V1, AgentWitnessIbGib_V1, CreateConcreteAgentWitnessFactory, CreateNewAgentArg } from \"./agent-types.mjs\";\nimport { CreateConcreteAgentWitnessFactory_Gemini } from \"./gemini/gemini-agent-factory.mjs\";\nimport { CommentIbGib_V1 } from \"@ibgib/core-gib/dist/common/comment/comment-types.mjs\";\nimport { validateIbGibIntrinsically } from \"@ibgib/ts-gib/dist/V1/validate-helper.mjs\";\nimport { isComment, parseCommentIb } from \"@ibgib/core-gib/dist/common/comment/comment-helper.mjs\";\n// import { updateSpecialIndex } from \"../../api/timeline/timeline-api.mjs\";\n\nconst logalot = GLOBAL_LOG_A_LOT; // change this when you want to turn off verbose logging\n\n// #region snapshot of the component src file\n\n// #endregion snapshot of the component src file\n\n/**\n * helper that gets/creates the agents tag in the given {@link space}, or in the\n * default local user space if {@link space} is falsy.\n * @returns agents tag ibgib\n */\nexport async function getTag_Agents({\n    metaspace,\n    space,\n    createIfNone,\n}: {\n    metaspace: MetaspaceService,\n    space: IbGibSpaceAny | undefined,\n    createIfNone?: boolean,\n}): Promise<TagIbGib_V1> {\n    const lc = `[${getTag_Agents.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: ad1594767abce66ca80fea8c8d89f325)`); }\n        space ??= await metaspace.getLocalUserSpace({ lock: false });\n        if (!space) { throw new Error(`(UNEXPECTED) space falsy after getting local user space? (E: bc68d97d46dcf1d15dd74edba200b725)`); }\n\n        const tagsIbGib: IbGib_V1 = await getTagsIbGib({ metaspace, space });\n        if (!tagsIbGib.rel8ns) { throw new Error(`(UNEXPECTED) tagsIbGib.rel8ns falsy? (E: dc50e8d218fe5e30bbaec7f37d484525)`); }\n        const tagAddrs = tagsIbGib.rel8ns[TAG_REL8N_NAME] ?? [];\n        const agentTagAddrs = tagAddrs.filter(x => {\n            const { ib } = getIbAndGib({ ibGibAddr: x });\n            return ib === TAG_AGENT_IB;\n        });\n        let agentTagAddr: IbGibAddr | undefined = undefined;\n        let agentTagIbGib: TagIbGib_V1 | undefined = undefined;\n        if (agentTagAddrs.length === 0) {\n            if (createIfNone) {\n                if (logalot) { console.log(`${lc} creating new agents tag... (I: 47f4f4fa89f1a1bba960e0a6ff5f5225)`); }\n\n                const { newTagIbGib, } = await metaspace.createTagIbGib({\n                    text: TAG_AGENT_TEXT,\n                    icon: TAG_AGENT_ICON,\n                    description: TAG_AGENT_DESCRIPTION,\n                    space,\n                });\n                agentTagIbGib = newTagIbGib;\n                if (logalot) { console.log(`${lc} creating new agents tag complete. (I: 5f41d644f2b692348377f918057cf225)`); }\n                return newTagIbGib; /* <<<< returns early */\n            }\n        } else if (agentTagAddrs.length === 1) {\n            agentTagAddr = agentTagAddrs.at(0)!;\n            if (logalot) { console.log(`${lc} exactly one agent tag addr found (${agentTagAddr}) in space (${space.ib}) (I: 7ef995963313c966216097760d0cdb25)`); }\n        } else {\n            // more than one agent tag?\n            agentTagAddr = agentTagAddrs.at(0)!;\n            console.error(`${lc} more than one agent tag found in space (${space.ib})? Well, we're returning just the first one (${agentTagAddr}), but really we've not coded for this edge/future case. (E: 52a4e2e49d3c0d644df483119b46f125)`);\n        }\n\n        if (agentTagAddr) {\n            const resGet = await metaspace.get({ addrs: [agentTagAddr], space });\n            if (resGet.success && resGet.ibGibs?.length === 1) {\n                agentTagIbGib = resGet.ibGibs.at(0)! as TagIbGib_V1;\n                return agentTagIbGib;\n            } else {\n                throw new Error(`couldn't get agentTagAddr (${agentTagAddr}) in space (${space.ib}) (E: 53d9cdb7b769014a2de15871484cc325)`);\n            }\n        } else {\n            throw new Error(`agentTagAddr not found, so there ain't no agents tag, and createIfNone was ${createIfNone}. (E: 54cb3164a118105f187e936613ff4625)`);\n        }\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * gets agents of a certain {@link type} in the local space corresponding to\n * {@link spaceId} (or default local user space if falsy) via the agents tag.\n */\nexport async function getAgents({\n    metaspace,\n    type,\n    spaceId,\n    space,\n}: {\n    metaspace: MetaspaceService,\n    type: SpecialIbGibType,\n    spaceId?: SpaceId,\n    space?: IbGibSpaceAny,\n}): Promise<AgentWitnessAny[]> {\n    const lc = `[${getAgents.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 41037d1926051c4b051769069f518f25)`); }\n\n        space ??= await metaspace.getLocalUserSpace({ localSpaceId: spaceId, lock: false });\n        if (!space) { throw new Error(`couldn't get local user space by id (${spaceId}) (E: fe96076e79fb227c0ae2de077eb5e225)`); }\n\n        // initialize the agent index if it hasn't already been created we\n        // don't actually use this (and thus it's slightly inefficient)\n        // because we use the next getSpecialRel8dIbGibs call\n        const agentsIndexIbGib = await metaspace.getSpecialIbGib({\n            type,\n            initialize: true,\n            dontWarnIfNotExist: true,\n            lock: false, // not worried about this atow 01/2024\n            space,\n        });\n        if (!agentsIndexIbGib) { throw new Error(`(UNEXPECTED) couldn't initialize/get agents special ibgib? (E: 1abe0e2543711744adbdb7026b242e25)`); }\n        const agentIbGibs = (await metaspace.getSpecialRel8dIbGibs({\n            rel8nName: AGENT_REL8N_NAME,\n            type,\n            // type: AGENT_SPECIAL_IBGIB_TYPE_PRIMARYAGENT,\n            space,\n        }) ?? []) as AgentWitnessAny[]; // NOT actually witnesses yet!!!!!\n\n        /**\n         * convert to witnesses...right now, I'm realizing I screwed up the\n         * factory pattern to not be generalized enough and I' msoooooooo fing\n         * tired. I mean, wtf am I doing with my life right.  Project IDX is\n         * SLOOOOOW as hell and as usual, I'm fing too poor to do anything about\n         * fing anything. Anyway, we have ibgib (dtos) not witnesses which have\n         * actual OOP properties/methods. atow (04/2025) we only have gemini\n         * witnesses, so going to hardcode that in. But this needs to be changed\n         * to use a proper factory\n         */\n        const resAgentWitnessesProper: AgentWitnessAny[] = [];\n        for (const agentIbGib of agentIbGibs) {\n            if (agentIbGib.data?.api !== 'gemini') {\n                throw new Error(`(UNEXPECTED) agentIbGib.data.api !== gemini? only gemini is implemented right now. (E: 7348fe8c68565bcf88a4052458f42d25)`);\n            }\n\n            const agentsSvc = getAgentsSvc();\n\n            let actualWitness = await agentsSvc.getLatestAgent({ id: agentIbGib.data.uuid! });\n            if (!actualWitness) {\n                actualWitness = await agentsSvc.getAgentWitnessFromDto({ dto: agentIbGib });\n                if (!actualWitness) {\n                    debugger; // error couldn't get agent from dto?\n                    throw new Error(`(UNEXPECTED) couldn't get actual agent witness from agent dto? have we registered classname (${agentIbGib.data?.classname}) and factory fn with agents service? (E: bcbfdf6446793ac34d6f6118e050d325)`);\n                }\n                // actualWitness = await agentIbGibDtoToWitness({ agentIbGib });\n                await agentsSvc.updateOrSetLatestAgent({\n                    agent: actualWitness,\n                    throwIfNewerFound: false, // we just got this from the special index\n                });\n            }\n            resAgentWitnessesProper.push(actualWitness);\n        }\n        return resAgentWitnessesProper;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * i'm updating the index proactively so we don't need to rely on jit getLatest\n * any time we want to get the agent.\n */\nexport async function updateAgentIndex({\n    metaspace,\n    type,\n    space,\n    newAgentIbGib,\n}: {\n    metaspace: MetaspaceService,\n    type: SpecialIbGibType, // has | string in it\n    space: IbGibSpaceAny,\n    newAgentIbGib: AgentWitnessIbGib_V1,\n}): Promise<void> {\n    // await commandifyAnonFn({\n\n    const fn: () => Promise<void> = async () => {\n        const lc = `[${updateAgentIndex.name}]`;\n        try {\n            // d ebugger; // is this hit as expected? yes\n            if (logalot) { console.log(`${lc} starting... (I: bf6ff6bf4132eaa943eaa3af1ee17225)`); }\n            if (!newAgentIbGib.data) { throw new Error(`(UNEXPECTED) newAgentIbGib.data falsy? (E: 26e03d0a8e286ac3a13b678a50c87a25)`); }\n            if (!newAgentIbGib.data.uuid) { throw new Error(`(UNEXPECTED) newAgentIbGib.data.uuid falsy? (E: 31b753e01275272484ea93e3dfe53225)`); }\n\n\n\n            const agentsSvc = getAgentsSvc();\n\n            const latestAgentInMemory = await agentsSvc.getLatestAgent({\n                id: newAgentIbGib.data.uuid,\n            });\n            if (latestAgentInMemory) {\n                // make sure that we have a higher n than the existing latest\n                if (latestAgentInMemory.data!.n! > newAgentIbGib.data.n!) {\n                    debugger; // error: latest in memory is newer than the new agent trying to update index\n                    throw new Error(`latestInMemory.data!.n! > newAgentIbGib.data.n! ... in plain english, this means that there is a more recent (higher n) agent with the given agent's id (${newAgentIbGib.data.uuid}) already in existence, but the caller is trying to update the special ibgib index with the older agent. (E: 5c0c028075736f22072c55e20a0c7e25)`);\n                }\n            }\n\n            const newAgentAddr = getIbGibAddr({ ibGib: newAgentIbGib });\n\n            await updateSpecialIndex({\n                type: newAgentIbGib.data.type,\n                rel8nInfos: [\n                    {\n                        rel8nName: AGENT_REL8N_NAME,\n                        ibGibs: [toDto({ ibGib: newAgentIbGib })],\n                    },\n                ],\n                metaspace,\n                space,\n            });\n\n            // const agentsIndexIbGib = await metaspace.getSpecialIbGib({\n            //     type,\n            //     space,\n            //     initialize: true,\n            // });\n            // if (!agentsIndexIbGib) { throw new Error(`(UNEXPECTED) couldn't initialize/get agents special ibgib (index)? (E: 3c1c21305b256d468b2be9d12243c825)`); }\n\n            // /**\n            //  * find ibgib(s) to unrel8. should only be one at most but will cover if multiple\n            //  */\n            // let ibGibsToUnRel8: IbGib_V1[] | undefined = undefined;\n            // const agentAddrs = (agentsIndexIbGib?.rel8ns ?? {})[AGENT_REL8N_NAME] ?? [];\n            // if (agentAddrs.some(x => x === newAgentAddr)) {\n            //     if (logalot) { console.log(`${lc} agent addr (${newAgentAddr}) already registered with special ibgib index. (I: 2d0f370b0f9f3ec263489228f801ee25)`); }\n            // }\n            // const toRemoveAddrs: IbGibAddr[] | undefined = newAgentIbGib.rel8ns?.past?.filter(x => agentAddrs.includes(x)) ?? [];\n            // if (toRemoveAddrs.length > 0) {\n            //     const resGetToRemove = await metaspace.get({\n            //         addrs: toRemoveAddrs,\n            //         space,\n            //     });\n            //     if (resGetToRemove.success &&\n            //         (resGetToRemove.ibGibs ?? []).length === toRemoveAddrs.length) {\n            //         ibGibsToUnRel8 = resGetToRemove.ibGibs;\n            //     } else {\n            //         debugger; // error in getting previous agents when attempting to unrel8 past agents after an update to the agent index\n            //         throw new Error(`failed to get previous agents? wrong space maybe? space.ib: ${space.ib} (E: 97d77376bccdb44dec65a5b725108e25)`);\n            //     }\n            // }\n\n            // // update the index by relating the new ibgib and removing any\n            // // old ones if applicable\n            // await metaspace.rel8ToSpecialIbGib({\n            //     type,\n            //     rel8nName: AGENT_REL8N_NAME,\n            //     ibGibsToRel8: [toDto({ ibGib: newAgentIbGib })],\n            //     ibGibsToUnRel8,\n            //     space,\n            // });\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    await fn();\n\n    // await execInSpaceWithLocking({\n    //     fn,\n    //     scope: type,\n    //     secondsValid: 60,\n    //     maxDelayMs: 100,\n    //     maxLockAttempts: 600, // 60 seconds worth\n    //     space,\n    //     callerInstanceId: getTimestampInTicks() + '_' + newAgentIbGib.gib,\n    // });\n}\n\n/**\n * Generates a consistent special name for the agent index ibGib based on the\n * domain ibGib's primitive ancestor's ib or the ibGibAddr's ib atom.\n *\n * RIGHT NOW I\"M PRIORITIZING THE ATOM. I THINK IT ALWAYS RETURNS THE ATOM, I.E., THE FIRST SPACE-DELIMITED PIECE OF THE `ib`.\n *\n * I am doing this because the project ibgib actually forks from a comment\n * ibgib, so its primitive ancestor is \"comment^gib\".\n *\n * ## notes\n *\n * We are trying to get a special ibgib index that maps from ibgibs (the domain)\n * to what local agent is registered to handle that ibgib's timeline.\n *\n * Concretely, we're working on the project ibgibs and we need a way to get at\n * the agent that is assigned to that project. But we can't just mut8 the\n * project itself because this would cause issues once the project is spread out\n * among multiple execution contexts (similar to \"remotes\" in git).\n *\n * So we will have a special ibgib registered with the local space which will\n * act as this index that maps ibgib -> handling agent. This function helps get\n * the *name* of that special indexing ibgib.\n *\n * This can be driven either by the ibgib itself, via the last primitive ancestor\n * ibgib's address, or via the ib's atom (the first space-delimited term in the\n * `ib` metadata).\n *\n * So if an ancestor is [comment^gib, specialComment^gib, specialComment\n * abc123^ABC123.DEF456] (where the abc123 things are representative of the full\n * hashes 64 characters long atow since we're using sha256), then the *last*\n * primitive address is specialComment^gib.\n */\nexport function getAgentIndexNameFromIbGib({\n    ibGib,\n    ibGibAddr,\n    defaultNameIfError,\n}: {\n    ibGib?: IbGib_V1,\n    ibGibAddr?: IbGibAddr,\n    /**\n     * if truthy and an error is produced, then this will be returned.\n     */\n    defaultNameIfError?: string,\n}): string {\n    const lc = `[${getAgentIndexNameFromIbGib.name}]`;\n    try {\n        if (!ibGib && !ibGibAddr) { throw new Error(`${lc} Must provide either ibGib or ibGibAddr. (E: 712592bd51cabec9d23aee3a8ec2d625)`); }\n\n        let res = getIndexNameFromIbGib({\n            scope: 'agent',\n            ibGib,\n            ibGibAddr,\n            defaultNameIfError,\n        });\n        return res;\n\n        // /**\n        //  * note: non-alphanumerics are replaced with underscores\n        //  */\n        // let primitiveAncestorIb: IbGibAddr | undefined = undefined;\n        // let atom: string | undefined = undefined;\n        // /**\n        //  * This is what we're trying to extract. once we have this, then we can\n        //  * simply append our index name, e.g. `${ancestorIbOrAtom}-agent-index`\n        //  */\n        // let ancestorIbOrAtom: string | undefined = undefined;\n        // if (ibGib) {\n        //     // go by the ibgib's full data\n        //     if (!ibGib.data) { throw new Error(`(UNEXPECTED) ibGib.data falsy? (E: 31514bbd270384cc9a300fdab7603525)`); }\n        //     if (!ibGib.rel8ns) { throw new Error(`(UNEXPECTED) ibGib.rel8ns falsy? (E: e011d3ac53fb33bd82b4075e57f46825)`); }\n        //     if (!ibGib.rel8ns.ancestor) { throw new Error(`(UNEXPECTED) ibGib.rel8ns.ancestor falsy? (E: a2dcd5c706cfca2781cb13a76f1ff625)`); }\n        //     if (ibGib.rel8ns.ancestor.length === 0) {\n        //         throw new Error(`(UNEXPECTED) ibGib.rel8ns.ancestor.length === 0? there should be at least one ancestor (E: 1c7645024de35a4ca114631b2ab38c25)`);\n        //         // this may turn into a warning later on down the road and return based on the ibGib's addr\n        //     }\n        //     if (ibGib && ibGibAddr) {\n        //         if (getIbGibAddr({ ibGib }) !== ibGibAddr) {\n        //             throw new Error(`(UNEXPECTED) both ibGib and ibGibAddr provided, but addr of ibGib doesn't equal ibGibAddr? (E: ef241d9cece84e0a5aa93a35fae5bc25)`);\n        //         }\n        //     }\n\n        //     // const primitiveAncestor = getPrimitiveAncestor({ ibGib });\n        //     const primitiveAncestorAddrs =\n        //         ibGib.rel8ns.ancestor!.filter(x => isPrimitive({ gib: getIbAndGib({ ibGibAddr: x }).gib }));\n        //     if (primitiveAncestorAddrs.length === 0) {\n        //         debugger; // error no primitive ancestor addrs?\n        //         console.error(`${lc} ibGib has no primitive ancestor addrs? Still going to work off of the ib then, which should have the atom as the first space-delimited term. (E: e5ad2e057daa539d3de2c0f78eb5de25)`)\n        //     }\n        //     const primitiveAncestorAddr = primitiveAncestorAddrs.at(-1)!;\n        //     primitiveAncestorIb =\n        //         getIbAndGib({ ibGibAddr: primitiveAncestorAddr }).ib;\n        //     // replace ALL spaces with underscores\n        //     ancestorIbOrAtom = primitiveAncestorIb;\n        // }\n\n        // // get the atom from the address\n        // ibGibAddr ??= getIbGibAddr({ ibGib });\n\n        // // try to get at it from the ibGibAddr\n        // const { ib } = getIbAndGib({ ibGibAddr });\n        // atom = (ib.split(' ').at(0) ?? '');\n\n        // // at this point we have a raw atom and possibly a raw primitive\n        // // ancestor ib.  we want to compare the two, which usually should be the\n        // // same (i think?). if different, warn and return\n        // atom = atom.replace(/\\W/g, '_');\n\n        // primitiveAncestorIb ??= atom;\n        // primitiveAncestorIb = primitiveAncestorIb.replace(/\\W/g, '_');\n\n        // if (!primitiveAncestorIb && !atom) {\n        //     throw new Error(`(UNEXPECTED) both primitiveAncestorIb and atom falsy? one should be truthy at this point. (E: 5c7af3e1cc042aff674640ee4c7f2c25)`);\n        // }\n\n        // if (primitiveAncestorIb !== atom) {\n        //     // warn and do per arg\n        //     console.warn(`${lc} ibGib primitive ancestor ib (${primitiveAncestorIb}) doesn't match atom (${atom}). going with ancestorIbOrAtom: ${ancestorIbOrAtom} (W: fc2301a4a4b4ee20d90265c7bf650425)`);\n        // }\n        // ancestorIbOrAtom = atom.toLowerCase();\n        // if (logalot) { console.log(`${lc} ancestorIbOrAtom: ${ancestorIbOrAtom} (I: d1ebc76770f110d2631e369f5b094925)`); }\n\n        // /**\n        //  * I forgot, this cannot be kebab-cased because we only allow \\w regexp\n        //  * on the special ibgib name. I don't remember the reasoning for this,\n        //  * may be arbitrary. But for now, going to change this to underscore,\n        //  * even though the atom or ancestor ib may have underscores in it. Ah\n        //  * well.\n        //  */\n        // const indexName = `${ancestorIbOrAtom}_agentindex`;\n        // if (logalot) { console.log(`${lc} indexName: ${indexName} (I: ffef5d9037d62758032aa73f252f3625)`); }\n        // return indexName;\n    } catch (error) {\n        if (!!defaultNameIfError) {\n            console.warn(`${lc} error happened but defaultNameIfError (${defaultNameIfError}) provided. So will return this value. error that was thrown: ${extractErrorMsg(error)}`);\n            return defaultNameIfError;\n        } else {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        }\n    }\n}\n\n/**\n * Registers a domain ibGib with its associated agent ibGib in the special agent index ibGib.\n * This creates or updates a mapping from the domain ibGib's TJP address to the agent's address.\n */\nexport async function registerDomainIbGibWithAgentIndex({\n    domainIbGib,\n    agentIbGib,\n    metaspace,\n    space,\n}: {\n    domainIbGib: IbGib_V1,\n    agentIbGib: AgentWitnessIbGib_V1,\n    metaspace: MetaspaceService,\n    space: IbGibSpaceAny,\n}): Promise<void> {\n    const lc = `[${registerDomainIbGibWithAgentIndex.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 217ae68e0c820e48f4c00409f7f14325)`); }\n\n        await coupleDomainIbGibWithLocalIbGibViaIndex({\n            scope: 'agent',\n            domainIbGib,\n            localIbGib: agentIbGib,\n            metaspace,\n            space,\n        });\n\n        // Delete the following commented out code (and related code) after\n        // awhile (atow 05/2025). I have confirmed it looks like it's working\n        // with the above refactored, more generalized code, but meh...\n\n        // const agentIndexSpecialIbGibType: SpecialIbGibType =\n        //     // getAgentIndexNameFromIbGib({ ibGib: domainIbGib }) as SpecialIbGibType;\n        //     getIndexNameFromIbGib({ scope: 'agent', ibGib: domainIbGib, });\n\n        // const domainTjpAddr = getTjpAddr({ ibGib: domainIbGib });\n        // const agentAddr = getIbGibAddr({ ibGib: agentIbGib });\n\n        // if (!domainTjpAddr) { throw new Error(`${lc} Could not get TJP address for domain ibGib. (E: 35a4e8ac291b0b85cb958e28dd812f25)`); }\n        // if (!agentAddr) { throw new Error(`${lc} Could not get address for agent ibGib. (E: 2fce1187630b45934c4155a23204d125)`); }\n\n        // const fn = async () => {\n\n        //     // Get or create the agent index ibGib\n        //     const agentSpecialIndex = await metaspace.getSpecialIbGib({\n        //         type: agentIndexSpecialIbGibType,\n        //         space,\n        //         initialize: true, // Create if it doesn't exist\n        //         dontWarnIfNotExist: true,\n        //         lock: false,\n        //     });\n\n        //     if (!agentSpecialIndex) { throw new Error(`${lc} Could not get or create agent index ibGib.`); }\n\n        //     // Initialize data if it doesn't exist\n        //     if (!agentSpecialIndex.data) {\n        //         throw new Error(`(UNEXPECTED) agentSpecialIndex.data falsy? (E: 74299eed147debf6398ca37e7b8d5c25)`);\n        //     }\n\n        //     // Get the current mapping or initialize an empty one\n        //     const agentMap: { [tjpAddr: string]: IbGibAddr } =\n        //         !!agentSpecialIndex.data.agentMap ?\n        //             clone(agentSpecialIndex.data.agentMap) :\n        //             {};\n\n        //     // Update the mapping\n        //     const existingMappedAgentAddr = agentMap[domainTjpAddr];\n        //     if (existingMappedAgentAddr) {\n        //         if (existingMappedAgentAddr === agentAddr) {\n        //             if (logalot) { console.log(`${lc} domain ibGib (${domainTjpAddr}) already mapped to agent (${agentAddr}). returning early (I: cb5d4dcef8cf14de7336120fb8ffef25)`); }\n        //             return; /* <<<< returns early */\n        //         } else {\n        //             console.warn(`${lc} domainTjpAddr (${domainTjpAddr}) already assigned to existingMappedAgentAddr (${existingMappedAgentAddr}). We will be changing to new agentAddr (${agentAddr}). (W: eb993e33f7731e570fa76f24a2d80625)`)\n        //         }\n        //     }\n        //     agentMap[domainTjpAddr] = agentAddr;\n\n        //     // Assign the updated map back to data Save the updated index ibGib.\n        //     // there is extra plumbing involved with special index ibgibs. see\n        //     // `rel8ToSpecialIbGib` for an example in\n        //     // libs/core-gib/src/witness/space/space-helper.mts\n        //     // await updateSpecialIndex({\n        //     //     metaspace,\n        //     //     type: agentIndexSpecialIbGibType,\n        //     //     dataToAddOrPatch: { agentMap },\n        //     //     space,\n        //     // });\n        //     const resNewSpecial = await mut8({\n        //         src: agentSpecialIndex,\n        //         dataToAddOrPatch: { agentMap },\n        //         dna: false,\n        //         linkedRel8ns: [Rel8n.past],\n        //         nCounter: true,\n        //     });\n\n        //     const newSpecialIbGib = resNewSpecial.newIbGib;\n\n        //     // persist\n        //     await persistTransformResult({ resTransform: resNewSpecial, space });\n\n        //     // update the space ibgib which contains the special/config information\n        //     const configKey = getSpecialConfigKey({ type: agentIndexSpecialIbGibType });\n        //     await metaspace.setConfigAddr({\n        //         key: configKey,\n        //         addr: getIbGibAddr({ ibGib: newSpecialIbGib }),\n        //         space,\n        //     });\n\n        //     await metaspace.registerNewIbGib({ ibGib: newSpecialIbGib, space, });\n        // }\n\n        // await execInSpaceWithLocking({\n        //     scope: agentIndexSpecialIbGibType, // Use the special index type as the lock scope.\n        //     secondsValid: 60, // Example timeout\n        //     maxDelayMs: 100, // Example delay\n        //     maxLockAttempts: 600, // Example attempts\n        //     space,\n        //     // callerInstanceId: // You might need a way to generate a unique ID for the caller\n        //     fn,\n        // });\n\n        // if (logalot) { console.log(`${lc} Registered domain ${domainTjpAddr} with agent ${agentAddr}`); }\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * Retrieves the agent ibGib associated with a domain ibGib from the special agent index ibGib.\n *\n * may have to change this to require the ibgib, not give an optional\n * domainIbGibAddr\n */\nexport async function getAgentForDomainIbGib({\n    ibGib,\n    metaspace,\n    space,\n}: {\n    ibGib: IbGib_V1,\n    metaspace: MetaspaceService,\n    space: IbGibSpaceAny,\n}): Promise<AgentWitnessAny | undefined> {\n    const lc = `[${getAgentForDomainIbGib.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting...`); }\n\n        if (!ibGib) { throw new Error(`ibGib required (E: 753a0aa13e4e5ea20d7f6bb92d963625)`); }\n\n        // // Get the index name and domain TJP address\n        // const agentIndexSpecialIbGibType: SpecialIbGibType =\n        //     // getAgentIndexNameFromIbGib({ ibGib: ibGib, }) as SpecialIbGibType;\n        //     getIndexNameFromIbGib({ scope: 'agent', ibGib, });\n\n        // const domainTjpAddr = getTjpAddr({ ibGib, defaultIfNone: 'incomingAddr' })!;\n\n        // // Get the agent index ibGib\n        // const agentSpecialIndex = await metaspace.getSpecialIbGib({\n        //     type: agentIndexSpecialIbGibType,\n        //     space,\n        //     initialize: false, // Do not create if it doesn't exist when retrieving\n        //     dontWarnIfNotExist: true, // Don't warn if the index doesn't exist\n        //     lock: false,\n        // });\n\n        // // If the index ibGib doesn't exist, no agent is registered for this domain\n        // if (!agentSpecialIndex || !agentSpecialIndex.data) {\n        //     if (logalot) { console.log(`${lc} Agent index ibGib not found for agentIndexSpecialIbGibType (${agentIndexSpecialIbGibType}). No agent registered, returning undefined. (I: a10a4621aa629384f838ec74456ed925)`); }\n        //     return undefined; /* <<<< returns early */\n        // }\n\n        // // Get the agent address from the map\n        // const agentMap: { [tjpAddr: string]: IbGibAddr } = agentSpecialIndex.data.agentMap ?? {};\n        // const agentAddr = agentMap[domainTjpAddr];\n\n        // if (!agentAddr) {\n        //     if (logalot) { console.log(`${lc} No agent address found for domain ${domainTjpAddr} in the agent index map. agentIndexSpecialIbGibType: ${agentIndexSpecialIbGibType}. returning undefined. (I: a1666e226ca916918c051cdbb08ff425)`); }\n        //     return undefined; /* <<<< returns early */\n        // }\n\n        const agentIbGib = await getLocalCoupledIbGibForDomainIbGib({\n            ibGib,\n            metaspace,\n            space,\n            scope: 'agent',\n            skipGetLatest: false,\n        });\n        if (!agentIbGib) {\n            console.warn(`${lc} couldn't find agent for domain ibGib (${ibGib.ib}) (W: 9536a8e67fe83ddc819c476f5a50c825)`);\n            return undefined; /* <<<< returns early */\n        }\n        const domainTjpAddr = getTjpAddr({ ibGib, defaultIfNone: 'incomingAddr' })!;\n\n        // Load the agent ibGib\n        const agentAddr = getIbGibAddr({ ibGib: agentIbGib });\n        const agentSvc = getAgentsSvc();\n        const agentWitness =\n            await agentSvc.getAgentByAddr({ agentAddr, metaspace, spaceId: space.data!.uuid })\n\n        if (logalot) {\n            if (agentWitness) {\n                console.log(`${lc} complete. Found agent ${getIbGibAddr({ ibGib: agentWitness })} for domain ${domainTjpAddr}`);\n            } else {\n                console.log(`${lc} complete. No agent found for ibgib tjp ${domainTjpAddr}`);\n            }\n        }\n\n        return agentWitness;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    }\n}\n\n/**\n * @internal\n * @returns factory to create concrete agent witnesses per given {@link arg}\n */\nexport function getConcreteAgentFactory(arg: CreateNewAgentArg): CreateConcreteAgentWitnessFactory {\n    const lc = `[${getConcreteAgentFactory.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 2a9899514ac6e478eb55819a57fd9725)`); }\n        const { api } = arg;\n        switch (api) {\n            case 'gemini':\n                return new CreateConcreteAgentWitnessFactory_Gemini(arg);\n            default:\n                throw new Error(`(UNEXPECTED) api: ${api}? only 'gemini' currently implemented? (E: 071fedab181fda80666858c14ea73625)`);\n        }\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n\n/**\n * creates a begin/end tag composed of the {@link tagText} paired with an\n * optional random id around the given {@link contentText}. The begin/end tags\n * will be on their own line with {@link contentText} on the lines between.\n *\n * @example\n * [MY_TAG|XBDWZ begin]\n * contentText\n * [MY_TAG|XBDWZ end]\n * @returns\n */\nexport function taggifyForPrompt({\n    tagText,\n    contentText,\n    randomIdLength,\n}: {\n    /**\n     * the tag itself\n     */\n    tagText: string,\n    /**\n     * text to be surrounded by the tags' begin and end markers.\n     */\n    contentText: string,\n    /**\n     * length of random characters to pair with tag. if 0 or undefined, then no\n     * id will be generated.\n     */\n    randomIdLength?: number | undefined,\n}): string {\n    const lc = `[${taggifyForPrompt.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 94104ec059c89d4ba458d96580791d25)`); }\n        const fullTagText = !!randomIdLength ?\n            `${tagText}|${pickRandom_Letters({ count: randomIdLength })}` :\n            tagText;\n        return [\n            `[${fullTagText} begin]`,\n            contentText,\n            `[${fullTagText} end]`,\n        ].join('\\n');\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * ATOW we specify if the text is from ai or human, as well as timestampInTicks.\n * @returns metadata text to be included in the comment ibgib's ib.\n * @see {@link parseAddlMetadataTextForAgentText}\n */\nexport function getAddlMetadataTextForAgentText({\n    textSrc,\n    other,\n}: {\n    /**\n     * @see {@link AddTextInfo.textSrc}\n     */\n    textSrc: TextSource,\n    /**\n     * if you have other underscore-delimited text, include that here.\n     */\n    other?: string,\n}): string {\n    const lc = `[${getAddlMetadataTextForAgentText.name}]`;\n    /**\n     * get and parse functions must **ALWAYS** match must match. If this array\n     * changes, change the other one.\n     */\n    return !!other ?\n        [textSrc, getTimestampInTicks(), other].join('_') :\n        [textSrc, getTimestampInTicks()].join('_');\n}\n\n/**\n * ATOW we specify if the text is from ai or human, as well as timestampInTicks.\n * @returns metadata text to be included in the comment ibgib's ib.\n * @see {@link getAddlMetadataTextForAgentText}\n */\nexport function parseAddlMetadataTextForAgentText({\n    addlMetadataText,\n    ifError = 'warn',\n}: {\n    addlMetadataText: string,\n    ifError: 'throw' | 'warn' | 'ignore',\n}): AddlMetadataTextForAgentTextInfo {\n    const lc = `[${getAddlMetadataTextForAgentText.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 89b8b19a8d785b945fe0f816df762d25)`); }\n\n        /**\n         * get and parse functions must **ALWAYS** match must match. If this\n         * array changes, change the other one.\n         */\n        const [\n            textSrc,\n            timestampInTicksStr,\n            ...other\n        ] = addlMetadataText.split('_');\n        if (!textSrc) { throw new Error(`addlMetadataText.textSrc falsy (E: 40bbec4269c1688ab1390fa5d5440325)`); }\n        if (!isTextSource(textSrc)) { throw new Error(`addlMetadataText.textSrc (${textSrc}) is unexpected value. Expected one of ${TEXT_SOURCE_VALUES} (E: 02bae41275a39210e5737548747bd825)`); }\n        if (!timestampInTicksStr) { throw new Error(`addlMetadataText.timestampInTicks falsy (E: 03cbbc7515a1cff1fc7c12e3947c6825)`); }\n        const timestampInTicks = Number.parseInt(timestampInTicksStr);\n        if (Number.isNaN(timestampInTicks)) { throw new Error(`invalid timestampInTicks (${timestampInTicksStr}): value should be an integer but parse is NaN (E: 9d31e3563d972c02553ce18a19a19b25)`); }\n        return {\n            textSrc,\n            timestampInTicks,\n            other: other.length > 0 ? other : undefined,\n        };\n    } catch (error) {\n        const errorMsg = `${lc} ${extractErrorMsg(error)}`;\n        switch (ifError) {\n            case 'ignore':\n                return {\n                    textSrc: TextSource.UNKNOWN,\n                    timestampInTicks: 0,\n                    errorMsg: extractErrorMsg(error)\n                };\n            case 'warn':\n                console.warn(`${lc} ${errorMsg} (W: 3e1f4a98ad6461c9bd96462841c31b25)`)\n                return {\n                    textSrc: TextSource.UNKNOWN,\n                    timestampInTicks: 0,\n                    errorMsg: extractErrorMsg(error)\n                };\n            default:\n                console.error(`${lc} ${errorMsg} (E: 6396ed44947c52adf85788e1adc22825)`);\n                throw new Error(errorMsg);\n        }\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * builds the agent witness' ib based on given {@link data}\n * @see {@link parseAgentIb}\n */\nexport function getAgentIb({\n    data,\n}: {\n    /** agent data, should be valid */\n    data: AgentWitnessData_V1,\n}): string {\n    const lc = `[${getAgentIb.name}]`;\n    const { name, uuid, type } = data;\n    if (!name) { throw new Error(`${lc} data.name falsy (E: 4c172c5b8a110ae26479b8c4006f3225)`); }\n    if (!uuid) { throw new Error(`${lc} data.uuid falsy (E: 67d2c79ac39e70e5ecfd1745e1fd3525)`); }\n    if (!type) { throw new Error(`${lc} data.type falsy (E: 53bf1f9a145a16be81296437682a7a25)`); }\n    const fields: string[] = [name, uuid, type];\n    if (fields.some(x => x.includes(' '))) { throw new Error(`invalid data. ib must not contain spaces in name, uuid, type. (E: 36a56e4685163848458be06f51d4ad25)`); }\n    /** getAgentIb must match parseAgentIb. If this array changes, change the other one. */\n    return [\n        AGENT_ATOM,\n        name,\n        uuid,\n        type,\n        // what else?\n    ].join(' ');\n}\n\n/**\n * @returns parsed info from an ib\n * @see {@link getAgentIb}\n */\nexport function parseAgentIb({\n    ib,\n}: {\n    ib: Ib,\n}): AgentIbInfo {\n    /** getAgentIb must match parseAgentIb. If this array changes, change the other one. */\n    const [\n        atom,\n        name,\n        uuid,\n        type,\n    ] = ib.split(' ');\n    if (atom !== AGENT_ATOM) { throw new Error(`invalid ib. first term expected to e an atom: ${AGENT_ATOM} (E: 3c01d42035d2e32c4bfd5c1bf363f725)`); }\n    if (!name) { throw new Error(`invalid ib. name falsy in agent ib (E: 8b494c544f05b8ef9c866078b761a725)`); }\n    if (!uuid) { throw new Error(`invalid ib. uuid falsy in agent ib (E: aba195db3ddcb000324ebed15351b725)`); }\n    if (!type) { throw new Error(`invalid ib. type falsy in agent ib (E: 8c814772394ae76342f95e885570c325)`); }\n    return { atom, name, uuid, type };\n}\n\n/**\n * Validates a comment ibgib to ensure that it is usable in an agent witness\n * context, especially that it includes the expected metadata format in its\n * `ib`.\n *\n * @param {CommentIbGib_V1} ibGib - The comment ibgib to validate.\n * @returns {string[]} An array of error messages if validation fails, or an empty array if no errors.\n */\nexport async function validateAgentWitnessCommentIbGib({\n    ibGib,\n}: {\n    ibGib: CommentIbGib_V1,\n}): Promise<string[]> {\n    const lc = `[${validateAgentWitnessCommentIbGib.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: f9a733a5a05b7f7494836d86a79e2d25)`); }\n\n        const errors: string[] = await validateIbGibIntrinsically({ ibGib }) ?? [];\n\n        if (!isComment({ ibGib })) {\n            errors.push(`${lc} not a comment ibgib (E: 08676d94c698c6e42e6c35e94a58f125)`);\n            return errors; /* returns early */\n        }\n\n        const { safeIbCommentMetadataText: addlMetadataText } = parseCommentIb({ ib: ibGib.ib });\n\n        if (addlMetadataText) {\n            const addlMetaInfo = parseAddlMetadataTextForAgentText({\n                addlMetadataText,\n                ifError: 'warn'\n            });\n            if (addlMetaInfo.errorMsg) {\n                errors.push(`${lc} could not parse addlMetadataText: ${addlMetaInfo.errorMsg} (E: e178265c33e5e94947a02c1f9d6a7425)`);\n            }\n        } else {\n            errors.push(`${lc} addlMetadataText falsy. this implies something is incorrect with the comment's ib, as we expect agent comments to have certain metadata (e.g. textSrc). See AgentWitness_V1 (and data interface) for more info. (E: 7c3c41c973a67256c432604666106b25)`);\n        }\n\n        return errors;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n", "import { extractErrorMsg, pretty } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { IbGib_V1 } from \"@ibgib/ts-gib/dist/V1/types.mjs\";\nimport { validateIbGibAddr } from \"@ibgib/ts-gib/dist/V1/validate-helper.mjs\";\nimport { getIbAndGib, } from \"@ibgib/ts-gib/dist/helper.mjs\";\nimport { IbGibAddr, } from \"@ibgib/ts-gib/dist/types.mjs\";\nimport { isPrimitive } from \"@ibgib/ts-gib/dist/V1/transforms/transform-helper.mjs\";\nimport { appendToTimeline } from \"@ibgib/core-gib/dist/timeline/timeline-api.mjs\";\nimport { createCommentIbGib } from \"@ibgib/core-gib/dist/common/comment/comment-helper.mjs\";\n\nimport { GLOBAL_LOG_A_LOT } from \"../../../constants.mjs\";\nimport { APIFunctionInfo } from \"../../api-types.mjs\";\nimport { COMMAND_BASE_SCHEMA_PROPERTIES } from \"../command-constants.mjs\";\nimport { getCommandService } from \"../command-service-v1.mjs\";\nimport { CommandDataBase } from \"../command-types.mjs\";\nimport { FUNCTION_CALL_EXAMPLES_HEADER } from \"../../api-constants.mjs\";\nimport { getGlobalMetaspace_waitIfNeeded } from \"../../../helpers.mjs\";\nimport { GEMINI_SCHEMA_AGENTS_SELF_IDENTIFIED_NAME, TextSource } from \"../../../witness/agent/agent-constants.mjs\";\nimport { getAddlMetadataTextForAgentText } from \"../../../witness/agent/agent-helpers.mjs\";\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\n// #region constants\nconst FUNCTION_NAME = 'tellUser';\n\n/**\n * chat category here as this is a chat-related command.\n */\nconst CMD_CATEGORY = 'agent';\n/**\n * helloWorld here is the specific command modifier which narrows down to a command\n * instance, similar to a fully curried function.\n */\nconst CMD_MODIFIERS: string[] = [FUNCTION_NAME];\nconst EXAMPLE_INPUT_TELLUSER: Partial<TellUserOpts> = {\n    text: 'Hello user, this is an example of how I can tell you something!',\n    agentName: 'Zarquon',\n    notesToSelf: 'Example of a tellUser function call. Note repromptWithResult is false b/c it is ignored with tellUser cmd.',\n    repromptWithResult: false,\n};\n\nconst EXAMPLES = [\n    // `\\`\\`\\`typescript\\n${FUNCTION_CALL_EXAMPLES_HEADER}\\n${pretty(EXAMPLE_INPUT_TELLUSER)}\\n\\`\\`\\``,\n    FUNCTION_CALL_EXAMPLES_HEADER,\n    pretty(EXAMPLE_INPUT_TELLUSER),\n].join('\\n');\nconst FUNCTION_DESCRIPTION = `Use this to talk with the user. DON'T just add text on the canvas! Use this function as it adds a comment to the chat log which the user can see.\\n\\n${EXAMPLES}`;\n// #endregion constants\n\n\n/**\n * @interface TellUserOpts - Options for the tellUser command.\n * @extends CommandDataBase\n */\nexport interface TellUserOpts extends CommandDataBase<typeof CMD_CATEGORY, typeof CMD_MODIFIERS> {\n    /**\n     * @property text - The text to tell the user.\n     */\n    text: string;\n\n    /**\n     * agent's id doing the telling\n     */\n    agentId: string;\n\n    /**\n     * address to the context in which the agent is communicating to a user.\n     */\n    contextIbGibAddr: IbGibAddr;\n\n    /**\n     * @property agentName - the name which the model chooses to\n     * use to represent him/her/itself.\n     */\n    agentName: string;\n}\n\n/**\n * @interface TellUserCommandData - Command data for the tellUser command.\n * @extends CommandDataBase\n */\nexport interface TellUserCommandData extends CommandDataBase<typeof CMD_CATEGORY, typeof CMD_MODIFIERS> {\n    /**\n     * @property text - The text to tell the user.\n     */\n    text: string;\n}\n\n/**\n * Wrapper function to enqueue the tellUser command.\n * @param {TellUserOpts} opts - Options for telling the user something.\n * @returns {Promise<void>} A promise that resolves when the command is enqueued.\n */\nfunction tellUserViaCmd(opts: TellUserOpts): Promise<void> {\n    const lc = `[${tellUserViaCmd.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 39ce6d58e154b8463170463f20d44925)`); }\n        if (logalot) { console.log(`${lc} tellUserViaCmd raw incoming opts: ${pretty(opts)} (I: 2ff6e7fc49b12e335affa1cb3af11125)`); }\n\n        const commandService = getCommandService();\n        const command: TellUserCommandData = {\n            ...opts,\n            cmd: 'agent',\n            cmdModifiers: ['tellUser'],\n            repromptWithResult: false, // override for tellUser\n            // text: opts.text,\n            // repromptWithResult: opts?.repromptWithResult,\n            // notesToSelf: opts?.notesToSelf,\n        };\n        if (logalot) { console.log(`${lc} tellUserViaCmd command: ${pretty(command)} (I: d7c86c41cf2578e1ccdd30f4dbc62625)`); }\n        return new Promise<void>((resolve, reject) => {\n            commandService.enqueueCommand({ command, resolve, reject });\n        });\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * Implementation function for the tellUser command.\n *\n * ## notes on context\n *\n * LLMs are designed to say/do something upon being prompted. In code, however,\n * it is beneficial to sometimes just give information and let the agent decide\n * whether or not to act upon it. Right now I have this doubling as an \"ack\"\n * command that acts like a blackhole for when the agent decides no action is\n * required. So if the context is a primitive, then this will \"fail\" silently.\n *\n *\n * @param {TellUserOpts} opts - Options for telling the user something.\n * @returns {Promise<void>} A promise that resolves when the command is executed (immediately).\n */\nasync function tellUserImpl(opts: TellUserOpts): Promise<void> {\n    const lc = `[${tellUserImpl.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: badce195ed1817dd686c7098511e1f25)`); }\n\n        console.log(`${lc} agent tell user opts: ${pretty(opts)}`);\n\n        const metaspace = await getGlobalMetaspace_waitIfNeeded();\n        const contextAddr = opts.contextIbGibAddr;\n        if (!contextAddr) { throw new Error(`contextIbGibAddr is falsy (was not provided by model if this was a function call request). This should be required in the gemini schema. (E: 2585778dc7f6fc74322f40745d7f4d25)`); }\n\n        const addrErrors = validateIbGibAddr({ addr: contextAddr }) ?? [];\n        if (addrErrors.length > 0) {\n            console.log(`${lc} returning early because agent has provided a non-ibgib addr for contextAddr: ${contextAddr}. addrErrors: ${addrErrors}. opts: ${pretty(opts)} (I: 66c39c5031723254de46c254b096dc25)`)\n            return; /* <<<< returns early */\n        }\n        if (isPrimitive({ gib: getIbAndGib({ ibGibAddr: contextAddr }).gib })) {\n            console.log(`${lc} agent has acked by calling this with a primitive context address. This will not propagate to the user's current context. opts: ${pretty(opts)} (I: a0687328201af74ed9d9e24ad4a5b825)`);\n            return; /* <<<< returns early */\n        }\n        const space = await metaspace.getLocalUserSpace({ lock: false });\n        if (!space) { throw new Error(`(UNEXPECTED) couldn't get default local user space? (E: 2fdac9f814d620ce6341cfc10942f525)`); }\n\n        // adding agent name elsewhere\n        // const agentNamePlusText = `${opts.agentName}: ${opts.text}`;\n\n        // create the comment\n        const { newIbGib: commentIbGib } = await createCommentIbGib({\n            text: opts.text,\n            addlMetadataText: getAddlMetadataTextForAgentText({\n                textSrc: TextSource.AI,\n                other: `${opts.agentName}_${opts.agentId}`,\n            }),\n            saveInSpace: true,\n            space,\n        });\n\n        // get the latest context ibgib\n        let latestContextIbGib: IbGib_V1 | undefined = undefined;\n        const latestContextAddr = await metaspace.getLatestAddr({\n            addr: contextAddr,\n            space,\n        });\n        if (latestContextAddr) {\n            const resGetLatest = await metaspace.get({\n                addrs: [latestContextAddr],\n                space,\n            });\n            if (resGetLatest.errorMsg || (resGetLatest.ibGibs ?? []).length !== 1) {\n                throw new Error(`couldn't get latest context ibgib (${latestContextAddr}) from super space (${space.ib}). errorMsg: ${resGetLatest.errorMsg ?? '[unknown error]'} (E: 450727cc12e226f8b741dd7b0efbfe25)`);\n            }\n            latestContextIbGib = resGetLatest.ibGibs!.at(0)!;\n        }\n        if (!latestContextIbGib) { throw new Error(`(UNEXPECTED) couldn't get latest context ibgib? (${latestContextAddr}) (E: cb50a6cb984a60c139a4f16a26290d25)`); }\n\n        await appendToTimeline({\n            timeline: latestContextIbGib,\n            metaspace,\n            rel8nInfos: [{ rel8nName: 'comment', ibGibs: [commentIbGib], }],\n            space,\n        });\n\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nconst GEMINI_SCHEMA_TELL_USER_TEXT = {\n    type: 'string',\n    description: 'The text content to display to the user in the chat log. This is how you, as the agent, communicate with the user.',\n};\n\nconst GEMINI_SCHEMA_TELL_USER_CONTEXT_ADDR = {\n    type: 'string',\n    description: `This is the address of the ibgib in which you wish to communicate with the user (and/or other agents when implemented). If you don't know this, you should call the getContextInfo function (the actual name may vary slightly as we are in active development right now, but this should be included in your available functions).`,\n};\n\n/**\n * API function info for the tellUser command.\n */\nexport const tellUserFunctionInfo: APIFunctionInfo<typeof tellUserViaCmd> = {\n    nameOrId: FUNCTION_NAME,\n    fnViaCmd: tellUserViaCmd,\n    functionImpl: tellUserImpl,\n    cmd: CMD_CATEGORY,\n    cmdModifiers: CMD_MODIFIERS,\n    schema: {\n        name: FUNCTION_NAME,\n        description: FUNCTION_DESCRIPTION,\n        parameters: {\n            type: 'object',\n            properties: {\n                ...COMMAND_BASE_SCHEMA_PROPERTIES,\n                text: GEMINI_SCHEMA_TELL_USER_TEXT,\n                contextIbGibAddr: GEMINI_SCHEMA_TELL_USER_CONTEXT_ADDR,\n                agentName: GEMINI_SCHEMA_AGENTS_SELF_IDENTIFIED_NAME,\n            },\n            required: ['text', 'contextIbGibAddr', 'agentName'],\n        },\n    },\n};\n", "import {\n    Settings_Chronologys, Settings_General, Settings_Minigame, Settings_Project,\n    Settings_TextEditor, SettingsData_V1\n} from \"./settings-types.mjs\";\n\nexport const SETTINGS_ATOM = 'settings';\n\n// #region SettingsType enum\nexport const SETTINGS_TYPE_GENERAL = 'general';\nexport const SETTINGS_TYPE_TEXTEDITOR = 'text-editor';\nexport const SETTINGS_TYPE_PROJECTS = 'projects';\nexport const SETTINGS_TYPE_PROJECTSEXPLORER = 'projects-explorer';\nexport const SETTINGS_TYPE_PROJECTSDROPDOWN = 'projects-dropdown';\nexport const SETTINGS_TYPE_PROJECT = 'project';\nexport const SETTINGS_TYPE_MINIGAME = 'minigame';\nexport const SETTINGS_TYPE_CHRONOLOGYS = 'chronologys';\n/**\n * Discriminator for Settings info\n */\nexport type SettingsType =\n    | typeof SETTINGS_TYPE_GENERAL\n    | typeof SETTINGS_TYPE_TEXTEDITOR\n    | typeof SETTINGS_TYPE_PROJECTS\n    | typeof SETTINGS_TYPE_PROJECTSEXPLORER\n    | typeof SETTINGS_TYPE_PROJECTSDROPDOWN\n    | typeof SETTINGS_TYPE_PROJECT\n    | typeof SETTINGS_TYPE_MINIGAME\n    | typeof SETTINGS_TYPE_CHRONOLOGYS\n    ;\nexport const SettingsType = {\n    general: SETTINGS_TYPE_GENERAL satisfies SettingsType,\n    textEditor: SETTINGS_TYPE_TEXTEDITOR satisfies SettingsType,\n    projects: SETTINGS_TYPE_PROJECTS satisfies SettingsType,\n    projectsExplorer: SETTINGS_TYPE_PROJECTSEXPLORER satisfies SettingsType,\n    projectsDropdown: SETTINGS_TYPE_PROJECTSDROPDOWN satisfies SettingsType,\n    project: SETTINGS_TYPE_PROJECT satisfies SettingsType,\n    minigame: SETTINGS_TYPE_MINIGAME satisfies SettingsType,\n    chronologys: SETTINGS_TYPE_CHRONOLOGYS satisfies SettingsType,\n} satisfies { readonly [key: string]: SettingsType; };\nexport const SETTINGS_TYPE_VALID_VALUES: SettingsType[] = Object.values(SettingsType);\nexport function isSettingsType(value: any): value is SettingsType {\n    return SETTINGS_TYPE_VALID_VALUES.includes(value);\n}\n// #endregion SettingsType enum\n\nexport const DEFAULT_SETTINGS_GENERAL: Settings_General = {\n    type: SettingsType.general,\n    editor: undefined,\n    readonly: true,\n    viewer: 'ibgib-raw-viewer',\n}\nexport const DEFAULT_SETTINGS_TEXTEDITOR: Settings_TextEditor = {\n    type: SettingsType.textEditor,\n    wrap: 'wrap',\n}\nexport const DEFAULT_SETTINGS_PROJECT: Settings_Project = {\n    type: SettingsType.project,\n    openChildTjpAddrs: [],\n    activeChildTjpAddr: undefined,\n    lensMode: 'raw',\n}\nexport const DEFAULT_SETTINGS_MINIGAME: Settings_Minigame = {\n    type: SettingsType.minigame,\n}\n\nexport const DEFAULT_SETTINGS_CHRONOLOGYS: Settings_Chronologys = {\n    type: SettingsType.chronologys,\n    openChildTjpAddrs: [],\n    activeChildTjpAddr: undefined,\n}\n\nexport const DEFAULT_SETTINGS_DATA_V1: SettingsData_V1 = {\n    sections: {},\n    children: {},\n}\n", "import { clone, extractErrorMsg } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { Ib, TransformResult } from \"@ibgib/ts-gib/dist/types.mjs\";\nimport { Factory_V1 } from \"@ibgib/ts-gib/dist/V1/factory.mjs\";\nimport { IbGibSpaceAny } from \"@ibgib/core-gib/dist/witness/space/space-base-v1.mjs\";\nimport { MetaspaceService } from \"@ibgib/core-gib/dist/witness/space/metaspace/metaspace-types.mjs\";\n\nimport { GLOBAL_LOG_A_LOT } from \"../../constants.mjs\";\nimport { IbGibSettings, SettingsIbGib_V1 } from \"./settings-types.mjs\";\nimport type { SettingsData_V1, SettingsIbInfo } from \"./settings-types.mjs\";\nimport {\n    isSettingsType, DEFAULT_SETTINGS_GENERAL, SETTINGS_TYPE_VALID_VALUES,\n    SettingsType, DEFAULT_SETTINGS_TEXTEDITOR,\n    DEFAULT_SETTINGS_DATA_V1,\n    SETTINGS_ATOM,\n    DEFAULT_SETTINGS_PROJECT,\n    DEFAULT_SETTINGS_MINIGAME,\n    DEFAULT_SETTINGS_CHRONOLOGYS\n} from \"./settings-constants.mjs\";\nimport { IbGib_V1 } from \"@ibgib/ts-gib/dist/V1/types.mjs\";\nimport { getIbAndGib } from \"@ibgib/ts-gib/dist/helper.mjs\";\n\n\nconst logalot = GLOBAL_LOG_A_LOT; // change this when you want to turn off verbose logging\n\nexport async function getSettingsScope({\n    ibGib\n}: {\n    ibGib: IbGib_V1\n}): Promise<string> {\n    const lc = `[${getSettingsScope.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 57ac4c0a3448bc5e98ecf5bfb02ce825)`); }\n        const { ib } = getIbAndGib({ ibGib });\n        const atom = ib.split(' ').at(0);\n        if (!atom) { throw new Error(`(UNEXPECTED) atom falsy? we split the ib by spaces (space-delimiter). this makes no sense. (E: 6a9ea640ae38823aeefc6ec82a05d625)`); }\n\n        return `${SETTINGS_ATOM}_${atom}`;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport async function getSectionName({\n    settingsType,\n    useCase,\n}: {\n    settingsType: SettingsType,\n    useCase: string,\n}): Promise<string> {\n    const lc = `[${getSectionName.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: f13dff111048421cad5453f821487825)`); }\n        if (useCase.includes('_')) { throw new Error(`(UNEXPECTED) settingsType.includes('_')? should be kebab-cased or camelCased (E: 8f75e89b9378819ab882cc1870f1e825)`); }\n        if (settingsType.includes('_')) { throw new Error(`(UNEXPECTED) settingsType.includes('_')? should be kebab-cased or camelCased (E: 1d316b0808287c12689d1e882648b825)`); }\n        return [\n            settingsType,\n            useCase\n        ].join('_');\n\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport function parseSectionName({\n    sectionName,\n}: {\n    sectionName: string,\n}): { settingsType: SettingsType, useCase: string } {\n    const lc = `[${parseSectionName.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: f5867c51505a3c32f20d5489f2919f25)`); }\n        if (!sectionName.includes('_')) { throw new Error(`invalid sectionName (${sectionName}). Should be a underscore-delimited value in form of \"settingsType_useCase\" (E: ec0208c6513878f028b68756a818b825)`); }\n        const [\n            settingsType,\n            useCase\n        ] = sectionName.split('_');\n        if (!isSettingsType(settingsType)) { throw new Error(`invalid settingsType (${settingsType}) found in sectionName (${sectionName}). Must be one of ${SETTINGS_TYPE_VALID_VALUES} (E: 0e1078f6aaa871154182f239a639f825)`); }\n        return { settingsType, useCase, };\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport async function getDefaultSettings<TSettings extends IbGibSettings>({\n    settingsType,\n}: {\n    settingsType: SettingsType, // hard-coded for now\n}): Promise<TSettings> {\n    const lc = `[${getDefaultSettings.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: f8a03b1bb6d1ecbf52552358f9ea0825)`); }\n        switch (settingsType) {\n            case SettingsType.general:\n                return clone(DEFAULT_SETTINGS_GENERAL) as TSettings;\n            case SettingsType.textEditor:\n                return clone(DEFAULT_SETTINGS_TEXTEDITOR) as TSettings;\n            case SettingsType.project:\n                return clone(DEFAULT_SETTINGS_PROJECT) as TSettings;\n            case SettingsType.minigame:\n                return clone(DEFAULT_SETTINGS_MINIGAME) as TSettings;\n            case SettingsType.chronologys:\n                return clone(DEFAULT_SETTINGS_CHRONOLOGYS) as TSettings;\n            default:\n                throw new Error(`(UNEXPECTED) unknown settingsType (${settingsType})? right now, we're whitelisting only. SettingsTypes: ${SETTINGS_TYPE_VALID_VALUES} (E: 801a7ade4c0849b308d5c8f8f0318d25)`);\n        }\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport async function getSettingsSection<TSettings extends IbGibSettings>({\n    sectionName,\n    settingsIbGib,\n}: {\n    /**\n     * key (i.e. name) of section to get from the `settingsIbGib.data.sections`.\n     * @see {@link SettingsData_V1.sections}\n     * @see {@link IbGibSettings}\n     */\n    sectionName: string,\n    settingsIbGib: SettingsIbGib_V1,\n}): Promise<TSettings | undefined> {\n    const lc = `[${getSettingsSection.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 266554b13f6ce6daa85c882f04805825)`); }\n\n        if (!settingsIbGib.data) { throw new Error(`(UNEXPECTED) settingsIbGib.data falsy? (E: dd3708f0515fb0b4d4024f4d336a3625)`); }\n        if (!settingsIbGib.data.sections) { throw new Error(`(UNEXPECTED) settingsIbGib.data.sections falsy? what was the settingsIbGib even created for? (E: 31f85898a1c854e13440e278a79ceb25)`); }\n        const sections = settingsIbGib.data.sections ?? {};\n        const section = sections[sectionName];\n        return section as (TSettings | undefined);\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport function getSettingsIb({\n    scope,\n}: {\n    scope: string,\n}): Ib {\n    const lc = `[${getSettingsIb.name}]`;\n    try {\n        if (scope.includes(' ')) {\n            console.warn(`${lc} scope includes one or more spaces. These will be converted to double underscores. (W: 75a53c623d3110b5e874e5789b414325)`);\n            scope = scope.replace(/ /g, '__');\n        }\n        return `${SETTINGS_ATOM} ${scope}`;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    }\n}\n\nexport function parseSettingsIb({\n    ib,\n}: {\n    ib: Ib,\n}): SettingsIbInfo {\n    const lc = `[${parseSettingsIb.name}]`;\n    try {\n        const pieces = ib.split(' ');\n        if (pieces.length !== 2) {\n            throw new Error(`invalid settings ib (${ib}). should be in the form of \"atom scope\" (a single space, scope should not have spaces, atom should be ${SETTINGS_ATOM}) (E: 7b3fd82f4b68a29b9890dc164d52dc25)`);\n        }\n        const [atom, scope] = pieces;\n        if (atom !== SETTINGS_ATOM) { throw new Error(`invalid atom (${atom}) found in ib (${ib}). should be ${SETTINGS_ATOM} (E: b8a5ac4b940816ff6887a64dec05bf25)`); }\n        return {\n            atom,\n            scope,\n        };\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    }\n}\n\n/**\n * creates a new settings ibgib with default values set (and atow 05/2025 also\n * assigns \"current\" Settings as well).\n *\n * if {@link saveInSpace} is true, then will save the transform result AND\n * register the ibgib with the metaspace's latest index. This requires also\n * {@link metaspace} to be truthy, and throws if it is not. If {@link space} is\n * falsy, then will use the metaspace's default local user space.\n */\nexport async function createSettings({\n    scope,\n    metaspace,\n    space,\n    saveInSpace,\n}: {\n    scope: string,\n    metaspace?: MetaspaceService,\n    space?: IbGibSpaceAny,\n    saveInSpace?: boolean,\n}): Promise<TransformResult<SettingsIbGib_V1>> {\n    const lc = `[${createSettings.name}]`;\n    try {\n\n        let ib = getSettingsIb({ scope });\n        let data = await getDefaultSettingsData();\n        let rel8ns = undefined;\n\n        const resSettings = await Factory_V1.firstGen<SettingsData_V1>({\n            parentIbGib: Factory_V1.primitive({ ib: SETTINGS_ATOM }),\n            ib, data, rel8ns,\n            dna: true,\n            nCounter: true,\n            tjp: { timestamp: true, uuid: true },\n        }) as TransformResult<SettingsIbGib_V1>;\n\n        if (saveInSpace) {\n            if (!metaspace) { throw new Error(`metaspace falsy but saveInSpace is true (E: f91adfe38d78e6e4f8bca278fce37925)`); }\n            await metaspace.persistTransformResult({ resTransform: resSettings, space });\n            await metaspace.registerNewIbGib({ ibGib: resSettings.newIbGib, space });\n        }\n\n        return resSettings;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    }\n}\n\n/**\n * hacky function that atow (05/2025) populates default/current\n * general/texteditor sections\n */\nexport async function getDefaultSettingsData(): Promise<SettingsData_V1> {\n    const lc = `[${getDefaultSettingsData.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 3d7cc3f242cc88ad28dafaf85d646a25)`); }\n        const data: SettingsData_V1 = clone(DEFAULT_SETTINGS_DATA_V1);\n        const sectionName_generalDefault = await getSectionName({\n            settingsType: 'general',\n            useCase: 'default',\n        });\n        const sectionName_generalCurrent = await getSectionName({\n            settingsType: 'general',\n            useCase: 'current',\n        });\n        data.sections[sectionName_generalDefault] = clone(DEFAULT_SETTINGS_GENERAL);\n        data.sections[sectionName_generalCurrent] = clone(DEFAULT_SETTINGS_GENERAL);\n\n        const sectionName_textEditorDefault = await getSectionName({\n            settingsType: 'text-editor',\n            useCase: 'default',\n        });\n        const sectionName_textEditorCurrent = await getSectionName({\n            settingsType: 'text-editor',\n            useCase: 'current',\n        });\n        data.sections[sectionName_textEditorDefault] = clone(DEFAULT_SETTINGS_TEXTEDITOR);\n        data.sections[sectionName_textEditorCurrent] = clone(DEFAULT_SETTINGS_TEXTEDITOR);\n\n        return data;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n", "/**\n * @module component-one-file.mts contains all the types, helpers, constants and\n * classes for the **shell** ui component system. the differentiating factor\n * between this system and other front end ui frameworks is that this is\n * ibgib-driven, with especially ibgib addresses driving components' backing\n * model/data.\n *\n * this is not to be confused with \"components\" that may be dynamically\n * generated within a blank-canvas environment that the canvas agents will\n * build. this is for the old-school html shell.\n *\n * the ui component system is being built piecemeal as we go.\n *\n * ## approach\n *\n * there are two basic pieces to a component: the component metadata declaration\n * and the concrete component instance that that declaration instantiates. these\n * will be tightly coupled per use-case, with the intention that the meta object\n * will not need to be a descendant class, whereas the component instance will\n * most likely be the class that is extended from an abstract base class.\n *\n * @see {@link IbGibDynamicComponentMeta}\n * @see {@link IbGibDynamicComponentInstance}\n */\n\nimport { delay, extractErrorMsg, pickRandom_Letters, pretty } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { ROOT_ADDR } from \"@ibgib/ts-gib/dist/V1/constants.mjs\";\nimport { Gib, Ib, IbGibAddr, TjpIbGibAddr } from \"@ibgib/ts-gib/dist/types.mjs\";\nimport { getGibInfo, isDna, isPrimitive } from \"@ibgib/ts-gib/dist/V1/transforms/transform-helper.mjs\";\nimport { getIbAndGib, getIbGibAddr } from \"@ibgib/ts-gib/dist/helper.mjs\";\nimport { IbGib_V1 } from \"@ibgib/ts-gib/dist/V1/types.mjs\";\nimport { Factory_V1 } from \"@ibgib/ts-gib/dist/V1/factory.mjs\";\nimport { fnObs } from \"@ibgib/core-gib/dist/common/pubsub/observer/observer-helper.mjs\";\nimport { getTimelinesGroupedByTjp, getTjpAddr, splitPerTjpAndOrDna, toDto } from \"@ibgib/core-gib/dist/common/other/ibgib-helper.mjs\";\nimport { MetaspaceService } from \"@ibgib/core-gib/dist/witness/space/metaspace/metaspace-types.mjs\";\nimport { mut8Timeline } from \"@ibgib/core-gib/dist/timeline/timeline-api.mjs\";\n\nimport { GLOBAL_LOG_A_LOT } from \"../../constants.mjs\";\nimport {\n    coupleDomainIbGibWithLocalIbGibViaIndex, getLocalCoupledIbGibForDomainIbGib,\n    getDeterministicColorInfo,\n} from \"../../helpers.mjs\";\nimport {\n    exportIbGib, getRawExportIbGibAndGraphFromJsonString\n} from \"../../helpers.web.mjs\";\nimport { LiveProxyIbGib } from \"../../witness/live-proxy-ibgib/live-proxy-ibgib-one-file.mjs\";\nimport { AgentWitnessAny, } from \"../../witness/agent/agent-one-file.mjs\";\nimport { ElementsBase, FnHandleRouteType, IbGibDynamicComponentInstance, IbGibDynamicComponentInstanceInitOpts, IbGibDynamicComponentMeta, ChildInfoBase, IbGibDynamicComponentMetaCtorOpts } from \"./component-types.mjs\";\nimport { getComponentSvc } from \"./ibgib-component-service.mjs\";\nimport { getAgentForDomainIbGib } from \"../../witness/agent/agent-helpers.mjs\";\nimport { createSettings, getSectionName, getSettingsScope, getSettingsSection } from \"../../common/settings/settings-helpers.mjs\";\nimport { IbGibSettings, SettingsIbGib_V1, SettingsWithTabs } from \"../../common/settings/settings-types.mjs\";\nimport { SettingsType } from \"../../common/settings/settings-constants.mjs\";\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\n/**\n * Base class for the ibgib component Meta factory instance.\n *\n * @see {@link IbGibDynamicComponentMeta}\n */\nexport abstract class IbGibDynamicComponentMetaBase\n    implements IbGibDynamicComponentMeta {\n    protected lc: string = `[${IbGibDynamicComponentMetaBase.name}]`;\n    componentName: string = '';\n    routeRegExp?: RegExp | undefined = undefined;\n    fnHandleRoute?: FnHandleRouteType | undefined = undefined;\n    fnGetMetaspace: () => Promise<MetaspaceService>;\n    bootstrapPromise: Promise<void>;\n    abstract createInstance(arg: {\n        path: string;\n        ibGibAddr: IbGibAddr;\n    }): Promise<IbGibDynamicComponentInstance>;\n    /**\n     * ## usage\n     *\n     * I'm planning on creating a single ctor opts instance for this with the\n     * properties exposed on the consuming app's global ibgib object, which\n     * should have references to these properties.\n     *\n     * Then, the component meta initialization can be the same as it is atow\n     * (12/2025), but instead of empty ctors it will just have the `opts` there.\n     *\n     *   ```\n     *   const opts = {\n     *     fnGetMetaspace: globalIbGib.getGlobalMetaspace,\n     *     bootstrapPromise: globalIbGib.bootstrapPromise,\n     *   }\n     *\n     *   const componentsMeta: IbGibDynamicComponentMeta[] = [\n     *     new MyComponentMeta1(opts),\n     *     new MyComponentMeta2(opts),\n     *     // other components\n     *   ];\n     *   ```\n     */\n    constructor({\n        fnGetMetaspace,\n        bootstrapPromise,\n    }: IbGibDynamicComponentMetaCtorOpts) {\n        this.fnGetMetaspace = fnGetMetaspace;\n        this.bootstrapPromise = bootstrapPromise\n    }\n}\n\n/**\n * Base class for common ibgib component. This is the actual web component\n * instance.\n *\n * ## regarding HTMLElement\n *\n * This class extends HTMLElement, so you have access to things, e.g., the\n * parent element via the normal DOM interface.\n *\n * @see {@link IbGibDynamicComponentInstance}\n */\nexport abstract class IbGibDynamicComponentInstanceBase<TIbGib extends IbGib_V1 = IbGib_V1, TElements = any>\n    extends HTMLElement\n    implements IbGibDynamicComponentInstance<TIbGib, TElements> {\n    protected lc: string = `[${IbGibDynamicComponentInstanceBase.name}]`;\n\n    elements: TElements | undefined;\n    createdPromise: Promise<void> | undefined;\n    settings: LiveProxyIbGib<SettingsIbGib_V1> | undefined;\n\n    /**\n     * main agent for this component\n     *\n     * atow (04/2025), this is derived from {@link agents}, being the first one\n     * in that array. So, other agents may exist for this component, but the\n     * first one should be the main one for this component.\n     */\n    get agent(): AgentWitnessAny | undefined { return this.agents.at(0); }\n    /**\n     * @see {@link agent}\n     */\n    agents: AgentWitnessAny[] = [];\n\n    get ib(): Ib {\n        const { ib } = getIbAndGib({ ibGibAddr: this.ibGibAddr ?? ROOT_ADDR });\n        return ib;\n    }\n    get gib(): Gib {\n        const { gib } = getIbAndGib({ ibGibAddr: this.ibGibAddr ?? ROOT_ADDR });\n        return gib;\n    }\n    ibGibAddr: IbGibAddr = ROOT_ADDR;\n    /**\n     * The proxy witness used for updating the backing ibGib.\n     */\n    ibGibProxy: LiveProxyIbGib<TIbGib> | undefined;\n    /**\n     * Backing ibgib getter via {@link ibGibProxy.ibGib}\n     */\n    get ibGib(): TIbGib | undefined {\n        const ibGibAddr = this.ibGibAddr ?? ROOT_ADDR;\n        const { ib, gib } = getIbAndGib({ ibGibAddr });\n        return this.ibGibAddr && !isPrimitive({ gib }) ?\n            this.ibGibProxy?.ibGib :\n            Factory_V1.primitive({ ib }) as TIbGib;\n        //  undefined; // should we return undefined?\n    }\n    get tjpAddr(): TjpIbGibAddr | undefined {\n        return this.ibGib ?\n            getTjpAddr({ ibGib: this.ibGib, defaultIfNone: \"incomingAddr\" })! :\n            undefined;\n    }\n\n    /**\n     * reference to the meta instance that created this component instance.\n     */\n    meta: IbGibDynamicComponentMeta | undefined;\n    html: string | undefined;\n    css: string[] | undefined;\n\n\n    /**\n     * not really used yet, since we're only testing with web1 which has a\n     * static, primitive ibgib address.\n     */\n    static get observedAttributes() {\n        return ['ibGibAddr'];\n    }\n\n    _instanceId: string;\n    get instanceId() { return this._instanceId; }\n\n    /**\n     * we can initialize the agent(s) as soon as we load the ibgib, but we don't\n     * want to await it immediately.\n     */\n    agentsInitialized: Promise<void> | undefined;\n\n    /**\n     * @internal number of times {@link connectedCallback} has been called.\n     *\n     * ## notes\n     *\n     * I'm making this because when the component is removed\n     */\n    protected connectedCount = 0;\n\n    /**\n     * override this as needed\n     */\n    public get isBusy(): boolean { return false; }\n\n    protected async getMetaspace(): Promise<MetaspaceService> {\n        const lc = `${this.lc}[${this.getMetaspace.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 956418cf932823bc767ccc6a0fd2b325)`); }\n            if (!this.meta) { throw new Error(`(UNEXPECTED) this.meta falsy? (E: dd2bfae6c0e84b1d58c72e2922b51325)`); }\n            return await this.meta.fnGetMetaspace();\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    constructor() {\n        super();\n        this._instanceId = pickRandom_Letters({ count: 8 });\n    }\n\n    async initialize(opts: IbGibDynamicComponentInstanceInitOpts): Promise<void> {\n        let { ibGibAddr, meta, html, css } = opts;\n\n        // maybe remove this try..catch..finally to speed up perf when this is\n        // more mature\n        const lc = `${this.lc}[${this.initialize.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: c9b94131bc2f0d20e1397c214dad6725)`); }\n\n            this.ibGibAddr = ibGibAddr;\n            this.meta = meta;\n            this.html = html;\n            this.css = css;\n\n            // Attach shadow DOM\n            this.attachShadow({ mode: 'open' });\n\n            await this.meta.bootstrapPromise;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    protected async initAgents(): Promise<void> {\n        const lc = `${this.lc}[${this.initAgents.name}]`;\n        if (logalot) { console.log(`${lc} does nothing in base class (I: 0b31a650b942619a0e36a1a7f763e825)`); }\n\n    }\n\n    async connectedCallback(): Promise<void> {\n        const lc = `${this.lc}[${this.connectedCallback.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 01bbbf69f1c75b03a29e7a85ebd2c725)`); }\n\n            this.connectedCount++;\n\n            if (this.connectedCount === 1) {\n                // first time this component has been created, so do full\n                // template/styles/scripts init.\n                await this.connectedCallback_initComponent();\n            } else {\n                await this.connectedCallback_reconnectComponent();\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    protected async connectedCallback_initComponent(): Promise<void> {\n        const lc = `${this.lc}[${this.connectedCallback_initComponent.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: bc4af3f6751d841f51bad19e334efa25)`); }\n            if (!this.html) { throw new Error(`(UNEXPECTED) this.html is falsy? (E: a0a0ab7c8f987d78058dd7cad09a5125)`); }\n\n            // create template element and set innerHTML\n            const template = document.createElement('template');\n            template.innerHTML = this.css ?\n                `\n                <style>\n                    ${this.css.join('\\n')}\n                </style>\n                ${this.html}\n                ` :\n                this.html;\n\n            // append content to shadow DOM\n            if (!this.shadowRoot) { throw new Error(`(UNEXPECTED) this.shadowRoot is falsy? (E: 1a3cf77d87767aaff37d31657ee73f25)`); }\n            this.shadowRoot.appendChild(template.content);\n\n            this.createdPromise = this.created();\n            await this.createdPromise;\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    protected async connectedCallback_reconnectComponent(): Promise<void> {\n        const lc = `${this.lc}[${this.connectedCallback_reconnectComponent.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 7fccefbeff68c0dda15642ebaa1eb525)`); }\n            console.log(`${lc} does nothing in base class (I: 724bc670d4ccb0fde2b2fa49830cd425)`);\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    async disconnectedCallback(): Promise<void> {\n        const lc = `${this.lc}[${this.disconnectedCallback.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 6f3b25c23fb874b1ac513e8f0d1f4e25)`); }\n\n            await this.disconnected();\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * untested so far.\n     *\n     * @param name\n     * @param oldValue\n     * @param newValue\n     */\n    public async attributeChangedCallback(name: string, oldValue: any, newValue: any): Promise<void> {\n        const lc = `${this.lc}[attributeChangedCallback]`;\n        if (logalot) { console.log(`${lc} starting... (I: 33cd68579171582166d25d8898640f25): ${name} ${oldValue} => ${newValue}`); }\n        // handle attribute changes if needed\n        console.warn(`${lc} nothing done in base class atow (W: 9eb93eb8fde7c0058c79cea841936a25)`);\n    }\n\n    public abstract created(): Promise<void>;\n    public abstract disconnected(): Promise<void>;\n    /**\n     * triggers {@link destroyed} handler\n     *\n     * Note there are NO web component lifecycles that trigger this. This must\n     * be called explicitly in code.\n     * @see {@link disconnected}\n     * @see {@link disconnectedCallback}\n     */\n    public async destroy(): Promise<void> {\n        const lc = `${this.lc}[${this.destroy.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 536989c9491b544105b6d01a688fbb25)`); }\n            await this.destroyed();\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    public async destroyed(): Promise<void> {\n        const lc = `${this.lc}[${this.destroyed.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: f34f3ca04b06b1e00ebe04df22331125)`); }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n        if (logalot) { console.log(`${lc} does nothing in the base class. (I: d9437f962e0aec40d69ad6159e7b5725)`); }\n        return Promise.resolve();\n    }\n\n    public async loadIbGib(opts?: { getLatest?: boolean }): Promise<void> {\n        const lc = `${this.lc}[${this.loadIbGib.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 4dcb1b7a3d86f3415ca7224c07126925)`); }\n\n            const getLatest = opts?.getLatest ?? false;\n\n            if (this.ibGib) {\n                // this may be because we need to load the ibgib/have access to\n                // it before the web component is attached to the DOM (which\n                // triggers the component's created event)\n                console.warn(`${lc} this.ibGib already loaded. idempotently returning early without doing anything. (W: 15498d346a32e884acec108cb3c8ee25)`);\n                return; /* <<<< returns early */\n            }\n\n            if (isPrimitive({ gib: getIbAndGib({ ibGibAddr: this.ibGibAddr ?? ROOT_ADDR }).gib })) {\n                if (logalot) { console.log(`${lc} component loading primitive ibgib (I: 3349796ef6139c1e718c8626c7935625)`); }\n                // no need to load, this.ibGib will be derived from the primitive addr\n                return; /* <<<< returns early */\n            }\n\n            // live or not, we want to get the ibgib record itself.\n            const metaspace = await this.getMetaspace();\n            /**\n             * using default local space as the common shared space atow\n             * (04/2025)\n             */\n            const space = await metaspace.getLocalUserSpace({ lock: false });\n            if (!space) { throw new Error(`(UNEXPECTED) local user space falsy? (E: bb093b7e9781064e8db9a4390b63bb25)`); }\n\n            if (getLatest) {\n                const latestAddr = await metaspace.getLatestAddr({ addr: this.ibGibAddr, space });\n                if (latestAddr && latestAddr !== this.ibGibAddr) {\n                    this.ibGibAddr = latestAddr;\n                }\n            }\n            const resGet = await metaspace.get({\n                addrs: [this.ibGibAddr],\n                space,\n                // space: undefined,\n            });\n            if (!resGet.success || resGet.ibGibs?.length !== 1) {\n                throw new Error(`couldn't get ibGib (${this.ibGibAddr}) in space (${space?.ib ?? 'undefined'}) (E: 59c3461bebf3e0065df72bd1bd8dc125)`);\n            }\n\n            // get the initial ibGib and wrap it in the \"live\" (updating) proxy\n            const ibGib = resGet.ibGibs.at(0)!;\n            const ibGibProxy = new LiveProxyIbGib<TIbGib>();\n            await ibGibProxy.initialized;\n            if (!ibGibProxy.contextUpdated$) {\n                throw new Error(`(UNEXPECTED) ibGibProxy.contextUpdated$ falsy? (E: 351dfc898d2c3da2d7928079cec14925)`);\n            }\n            ibGibProxy.contextUpdated$.subscribe(fnObs({\n                next: async (nextIbGib) => {\n                    const lcNext = `${lc}[ibGibProxy.contextUpdated$][next]`;\n                    if (logalot) { console.log(`${lcNext} nextIbGib: ${pretty(nextIbGib)} (I: 96c846357b94fda2cefa615aed88c325)`); }\n                    await this.handleContextUpdated();\n                },\n                error: async (e) => {\n                    debugger; // error in component.ibGibProxy.contextUpdated$ observable?\n                    console.error(`${lc}[ibGibProxy.contextUpdated$][error] what up? ${extractErrorMsg(e)}`);\n                },\n            }));\n\n            if (!ibGibProxy.newContextChild$) { throw new Error(`(UNEXPECTED) ibGibProxy.newContextChild$ falsy? (E: 2cbde5ab402cc6d81259c74d68bca725)`); }\n            ibGibProxy.newContextChild$.subscribe(fnObs({\n                next: async (childIbGib) => {\n                    const lcNext = `${lc}[ibGibProxy.contextUpdated$][next]`;\n                    if (logalot) { console.log(`${lcNext} childIbGib: ${pretty(childIbGib)} (I: 96c846357b94fda2cefa615aed88c325)`); }\n                    await this.handleNewContextChild({ childIbGib });\n                },\n                error: async (e) => {\n                    debugger; // error in component.ibGibProxy.contextUpdated$ observable?\n                    console.error(`${lc}[ibGibProxy.contextUpdated$][error] what up? ${extractErrorMsg(e)}`);\n                },\n            }));\n            /**\n             * not necessary, I'm just putting this here to remind myself that\n             * we can dynamically assign a space (via spaceId) to a proxy ibgib.\n             */\n            const _ignoredSpace = await ibGibProxy.witness(space);\n            const _ignored = await ibGibProxy.witness(ibGib);\n            this.ibGibProxy = ibGibProxy;\n\n            // update the addr in case the proxy is newer than the ibgib addr\n            // that we started with.\n            this.ibGibAddr = getIbGibAddr({ ibGib: ibGibProxy.ibGib });\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * in base class, this sets {@link ibGibAddr} to reflect the {@link nextIbGib}.\n     *\n     * override this in child classes to do more when next context happens\n     *\n     * @see {@link handleNewContextChild}\n     */\n    protected async handleContextUpdated(): Promise<void> {\n        const lc = `${this.lc}[${this.handleContextUpdated.name}]`;\n        try {\n            const { ibGib } = this; // derived from ibGibProxy\n            this.ibGibAddr = ibGib ? getIbGibAddr({ ibGib }) : ROOT_ADDR;\n            if (logalot) { console.log(`${lc} context updated. this.ibGibAddr (I: 64e5876f58cc54b5af777c94f13a4325)`); }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        }\n    }\n    /**\n     * does nothing (atow 04/2025) in base class\n     *\n     * override this to handle new children on {@link ibGibProxy}\n     * @see {@link handleContextUpdated}\n     */\n    protected async handleNewContextChild({ childIbGib }: { childIbGib: IbGib_V1 }): Promise<void> {\n        const lc = `${this.lc}[${this.handleNewContextChild.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} child added to contextcontext updated. childIbGib: ${pretty(childIbGib)} (I: 07d02c9182c6629cbbacd39fd0ff7f25)`); }\n            console.log(getIbGibAddr({ ibGib: childIbGib })); // debug\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        }\n    }\n\n    /**\n     * updates and renders the visual part of the component.\n     */\n    protected async renderUI(): Promise<void> {\n        const lc = `${this.lc}[${this.renderUI.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 7e5704afe17fb937c8473e7801f56e25)`); }\n\n            if (this.ibGib) {\n                // const color = getUniqueColorInfo({ ibGib: this.ibGib, });\n                // this.style.setProperty('--ibgib-color', color);\n                const {\n                    punctiliarColor,\n                    punctiliarColorTranslucent,\n                    punctiliarColorContrast,\n                    tjpColor,\n                    tjpColorTranslucent,\n                    tjpColorContrast,\n                    errorMsg\n                } = getDeterministicColorInfo({ ibGib: this.ibGib, translucentAlpha: 10 });\n                if (!errorMsg) {\n                    this.style.setProperty('--ibgib-color', punctiliarColor);\n                    this.style.setProperty('--ibgib-color-translucent', punctiliarColorTranslucent);\n                    this.style.setProperty('--ibgib-color-contrast', punctiliarColorContrast);\n                    this.style.setProperty('--tjp-color', tjpColor ?? punctiliarColor);\n                    this.style.setProperty('--tjp-color-translucent', tjpColorTranslucent ?? punctiliarColorTranslucent);\n                    this.style.setProperty('--tjp-color-contrast', tjpColorContrast ?? 'lime');\n                } else {\n                    // don't set anything\n                    console.error(`${lc} ${errorMsg} (E: 65e0d330d029c1fe39f3d6280dda3725)`);\n                }\n            }\n\n            await this.renderUI_busy();\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n\n    }\n\n    protected async renderUI_busy(): Promise<void> {\n        // does nothing in base\n    }\n\n    /**\n     * loads the agent(s) coupled to the domain ibgib (this.ibGib), if any.\n     */\n    protected async loadAgentsCoupledToIbGib({\n        dontThrowIfNone,\n    }: {\n        /**\n         * most components have an agent. set this to true if the component is small enough to NOT have an agent.\n         */\n        dontThrowIfNone?: boolean,\n    } = {}): Promise<void> {\n        const lc = `${this.lc}[${this.loadAgentsCoupledToIbGib.name}]`;\n        try {\n            // #region init/validation\n            const metaspace = await this.getMetaspace();\n            // const { metaspace } = this;\n            // if (!metaspace) { throw new Error(`(UNEXPECTED) this.metaspace falsy? (E: 230f36ee774eaaecddabd42540160325)`); }\n\n            const space = await metaspace.getLocalUserSpace({ lock: false });\n            if (!space) { throw new Error(`(UNEXPECTED) space falsy? we couldn't get the default local user space? (E: 06f5be2eec8abaa54d42ad982a155925)`); }\n\n            // const domainIbGib = this.ibGib as (ProjectIbGib_V1 | undefined);\n            // if (!domainIbGib) { throw new Error(`(UNEXPECTED) this.ibGib (projectIbGib) falsy? (E: a0281854c6312eadaa3420015d0d0925)`); }\n\n            if (!this.ibGib) { throw new Error(`(UNEXPECTED) this.ibGib falsy? (E: 9b24c4b4aa491a21b58fde9185eb9325)`); }\n            // #endregion init/validation\n\n            const agent = await getAgentForDomainIbGib({\n                ibGib: this.ibGib,\n                metaspace,\n                space,\n            });\n            if (agent) {\n                const initialN = agent.data!.n!;\n                await agent.setActiveContext({ contextIbGib: this.ibGib, loggingInfo: this.lc }); // maybe too premature?\n                await delay(32); // allow update of data.n kluge\n                const afterN = agent.data!.n!;\n                if (initialN !== afterN) {\n                    console.warn(`${lc} setting active context for agent changed agent.data.n.\\nagent.data: ${pretty(toDto({ ibGib: agent }))}\\nibGib.data: ${toDto({ ibGib: this.ibGib })} (W: cb22e8b064d8c2d7b3b2c488ed169225)`)\n                    // debugger; // dynamic comp base...why did data.n change?\n                }\n                this.agents = [agent];\n            } else {\n                // one day come back to visit this idea of mandatory agent per component, as some components seem small enough to warrant not requiring an agent.\n                if (dontThrowIfNone) {\n                    console.warn(`(UNEXPECTED) agent falsy? an agent should have been created and registered with the ibGib (${getIbGibAddr({ ibGib: this.ibGib })}) (W: e4219903462baab438a23c786d714825)`);\n                } else {\n                    throw new Error(`(UNEXPECTED) agent falsy? an agent should have been created and registered with the ibGib (${getIbGibAddr({ ibGib: this.ibGib })}) (E: 7182d1aa070b9578c78a5b8b401d8425)`);\n                }\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n\n    /**\n     * Gets the settings section.\n     *\n     * NOTE: this.settings and this.settings.ibGib must be initialized before\n     * calling this, else will throw.\n     *\n     * @returns settings section corresponding to type/use case or undefined\n     *\n     * ## notes on settings\n     *\n     * AFAICT I have made this so that there is one single settings ibgib with\n     * individual sections in its data. So use this function to get a section\n     * within that settings ibgib that is based on a given domain ibgib (this.ibGib).\n     *\n     * So a component initializes/activates an ibGib (this.ibGib) and for those\n     * components that use the settings, this.initSettings must be called. Then\n     * you call getSettings or updateSettings (not implemented yet).\n     */\n    protected async getSettings<TSettings extends IbGibSettings>({\n        settingsType,\n        useCase,\n    }: {\n        settingsType: SettingsType,\n        useCase: \"current\" | string,\n    }): Promise<TSettings | undefined> {\n        const lc = `${this.lc}[${this.getSettings.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 00c8dbedd2e8a8b988cc45f4186efd25)`); }\n            if (!this.settings) { throw new Error(`(UNEXPECTED) this.settings falsy? shouldn't this be initialized by now? (E: ceae480e28fab1da38b8def8b1060d25 (E: dc7d984c1c64293a3c3e0628dedadb25)`); }\n            if (!this.settings.ibGib) { throw new Error(`(UNEXPECTED) this.settings.ibGib falsy? shouldn't this be initialized by now? especially since this.settings is truthy? (E: faef6878abaf00a4a6a6f6b85ce8c825)`); }\n\n            const settingsSection = await getSettingsSection({\n                sectionName: await getSectionName({ settingsType, useCase, }),\n                settingsIbGib: this.settings.ibGib,\n            }) as (TSettings | undefined);\n\n            if (!settingsSection) {\n                if (logalot) { console.log(`${lc} settingsSection does not exist. returning undefined. (I: 0462d83f5ae8049708274b88e9b0d825)`) }\n            }\n            return settingsSection;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    protected async updateSettings<TSettings extends IbGibSettings>({\n        settingsType,\n        useCase,\n        newSectionInfo,\n    }: {\n        settingsType: SettingsType,\n        useCase: \"current\" | string,\n        newSectionInfo: TSettings,\n    }): Promise<void> {\n        const lc = `${this.lc}[${this.updateSettings.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 80ce98cf386e0c04d30e8b15ac0f2925)`); }\n\n            const sectionName_current = await getSectionName({\n                settingsType,\n                useCase,\n            });\n            const _newSettings = await mut8Timeline({\n                timeline: this.settings!.ibGib!,\n                metaspace: await this.getMetaspace(),\n                mut8Opts: {\n                    dataToAddOrPatch: {\n                        sections: {\n                            [sectionName_current]: newSectionInfo,\n                        }\n                    },\n                },\n            });\n            await delay(100); // cheap kluge to allow settings ibgib to update\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * if this.ibGib has a coupled settings ibgib indexed in the local space,\n     * then {@link settings} should be loaded with it. This is a convenience\n     * fn to access the current settings section for the {@link settingsType}.\n     */\n    protected async getCurrentSettings<TSettings extends IbGibSettings>({ settingsType }: { settingsType: SettingsType }): Promise<TSettings | undefined> {\n        const lc = `${this.lc}[${this.getCurrentSettings.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: da0baee73e386089a8c059f83cc43825)`); }\n            if (!this.settings) { return undefined; /* <<<< returns early */ }\n            const sectionName = await getSectionName({ settingsType, useCase: 'current' });\n            return getSettingsSection({ sectionName, settingsIbGib: this.settings.ibGib! });\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    protected async initSettings(): Promise<void> {\n        const lc = `${this.lc}[${this.initSettings.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: acfee8787d32a6075442e2887a386a25)`); }\n\n            // get the local space settings for this ibgib and update\n            // this.lensMode appropriately\n            if (!this.ibGib) { throw new Error(`(UNEXPECTED) this.ibGib falsy? (E: 8ce2e73bea87b9330b131778a3981825)`); }\n            const metaspace = await this.getMetaspace();\n            const space = await metaspace.getLocalUserSpace({ lock: false });\n            if (!space) { throw new Error(`(UNEXPECTED) couldn't get default local user space? (E: f77ce7269a6f0d7ad8978349b4c6cd25)`); }\n\n            if (isPrimitive({ ibGib: this.ibGib })) {\n                console.error(`${lc} this.ibGib is primitive, so what are we initializing settings for? (W: 9915089019b81c6935b32ae877095825)`);\n                return; /* <<<< returns early */\n            }\n\n            const scope = await getSettingsScope({ ibGib: this.ibGib });\n            let settingsIbGib =\n                await getLocalCoupledIbGibForDomainIbGib<SettingsIbGib_V1>({\n                    scope,\n                    // scope: this.getSettingsScope(),\n                    // scope: PROJECT_SETTINGS_SCOPE,\n                    ibGib: this.ibGib,\n                    metaspace,\n                    space,\n                });\n\n            // we want to get the *current* general settings to reload. if they\n            // do not exist, then we need to init the settings\n\n            if (!settingsIbGib) {\n                // create new project settings and couple to the project ibgib\n                // const defaultGeneral = await getDefaultSettings({ settingsType: SettingsType.general });\n                // const scope = await getSettingsScope({ ibGib: this.ibGib });\n                const resNewSettings = await createSettings({\n                    scope,\n                    metaspace,\n                    space,\n                    saveInSpace: true,\n                });\n                settingsIbGib = resNewSettings.newIbGib;\n                await coupleDomainIbGibWithLocalIbGibViaIndex({\n                    scope,\n                    domainIbGib: this.ibGib,\n                    localIbGib: settingsIbGib,\n                    metaspace,\n                    space,\n                });\n            }\n            if (!settingsIbGib) { throw new Error(`(UNEXPECTED) settings falsy still? should be initialized. (E: a179adcbbab800cff849b8aa95fbe425)`); }\n\n            const settingsProxy = new LiveProxyIbGib();\n            await settingsProxy.setWrappedIbGib({ ibGib: settingsIbGib, space });\n            this.settings = settingsProxy as LiveProxyIbGib<SettingsIbGib_V1>;\n\n            const generalSettings = await this.getCurrentSettings({ settingsType: SettingsType.general });\n\n            // const sectionName_currentGeneral = await getSectionName({\n            //     settingsType: SettingsType.general,\n            //     useCase: 'current',\n            // });\n            // let generalSettings = await getSettingsSection<Settings_General>({\n            //     sectionName: sectionName_currentGeneral,\n            //     settingsIbGib: settingsIbGib,\n            // });\n            if (!generalSettings) {\n                throw new Error(`(UNEXPECTED) no current general settings? the settings should have been updated with this upon creation. (E: d10fd8d42b58d917180293a713009825)`);\n            }\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * exports a given ibgib to the default local userspace in the metaspace.\n     */\n    protected async exportIbGib({\n        ibGib,\n        compress,\n    }: {\n        ibGib: IbGib_V1,\n        compress: boolean,\n    }): Promise<void> {\n        const lc = `${this.lc}[${this.exportIbGib.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 623d9463d919683be81f749821a95825)`); }\n            const metaspace = await this.getMetaspace();\n            if (!metaspace) { throw new Error(`(UNEXPECTED) metaspace falsy? (E: 3d15dbd074ac0c15b834a788d0b57d25)`); }\n            if (isPrimitive({ ibGib })) {\n                throw new Error(`ibGib is primitive. Can't export primitive. (E: dd42c42e9fda0707e81c692af1a2a225)`);\n            }\n\n            const space = await metaspace.getLocalUserSpace({ lock: false });\n            if (!space) { throw new Error(`(UNEXPECTED) couldn't get default local user space? (E: 7bb735be58282f1bd7abe5d9ffabb525)`); }\n\n            // const resGetExport = await getRawExportIbGib({\n            //     ibGib,\n            //     live: true,\n            //     compress,\n            //     metaspace: metaspace,\n            //     space,\n            // });\n\n            // maybe can just dynamically add this anchor element with display: none and click it? hmm...i've done this, will test\n            // if (!this.shadowRoot) { throw new Error(`(UNEXPECTED) this.shadowRoot falsy? (E: 137f413b39a88fdc58c751c82efd3825)`); }\n            // const downloadAnchorElId = 'export-ibgib-anchor';\n            // const downloadAnchorEl = this.shadowRoot.getElementById(downloadAnchorElId) as HTMLAnchorElement;\n            // if (!downloadAnchorEl) { throw new Error(`(UNEXPECTED) dlAnchorElem falsy? should be an element with id ${downloadAnchorElId}? (E: 51dfe2d823eedeefb8b9c9580090e625)`); }\n\n            await exportIbGib({\n                ibGib,\n                compress,\n                // downloadAnchorEl,\n                metaspace,\n                space,\n            });\n\n            // THE FOLLOWING CODE WAS **MOSTLY** PUT INTO THE ABOVE HELPER FUNCTION.\n\n            // const { rawExportIbGib: exportIbGib, errors } = resGetExport;\n            // const exportErrors = resGetExport.errors ?? [];\n            // if (exportErrors.length > 0) {\n            //     throw new Error(`Export had errors: ${exportErrors} (E: 05faf83f25d3449ab809dfd24eeaf825)`);\n            // }\n\n            // // at this point, we have a possibly quite large ibGib whose data includes\n            // // every single ibgib that this.ibGib relates to (its dependency graph). This\n            // // so now we can save this file and later import from it.\n\n            // /**\n            //  * exportIbGib is guaranteed to have a serializable structure, i.e.,\n            //  * the data has only primitives. (there are no Uint8Array)\n            //  */\n            // const exportIbGibAsString = JSON.stringify(exportIbGib);\n\n            // // thank you SO, OP and volzotan at https://stackoverflow.com/questions/19721439/download-json-object-as-a-file-from-browser\n            // // set the anchor's href to a data stream\n            // const dataStr = \"data:text/json;charset=utf-8,\" + encodeURIComponent(exportIbGibAsString);\n\n            // // get the filename for the anchor to suggest for the \"download\"\n            // const exportAddr = getIbGibAddr({ ibGib: exportIbGib });\n            // const filename = `${exportAddr}.json`;\n\n            // // // if (this.web) {\n            // // trigger the click\n            // if (!this.shadowRoot) { throw new Error(`(UNEXPECTED) this.shadowRoot falsy? (E: 137f413b39a88fdc58c751c82efd3825)`); }\n            // const downloadAnchorElId = 'export-ibgib-anchor';\n            // // const downloadAnchorEl = document.getElementById(downloadAnchorElId);\n            // const downloadAnchorEl = this.shadowRoot.getElementById(downloadAnchorElId);\n            // if (!downloadAnchorEl) { throw new Error(`(UNEXPECTED) dlAnchorElem falsy? should be an element with id ${downloadAnchorElId}? (E: 51dfe2d823eedeefb8b9c9580090e625)`); }\n            // downloadAnchorEl.setAttribute(\"href\", dataStr);\n            // downloadAnchorEl.setAttribute(\"download\", filename);\n            // downloadAnchorEl.click();\n            // // } else {\n            // //     // let res = await Filesystem.requestPermissions();\n            // //     await Filesystem.writeFile({\n            // //         data: dataStr,\n            // //         directory: Directory.ExternalStorage,\n            // //         path: `/Download/${filename}`,\n            // //         encoding: Encoding.UTF8,\n            // //         recursive: true,\n            // //     });\n            // // }\n            // // await Dialog.alert({ title: 'export succeeded', message: 'way to go, the export succeeded' });\n            // // throw new Error(`not implemented (E: d17d28b80f2576c6e81298fffc2e7825)`);\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * imports a given ibgib into this.ibGib's\n     */\n    protected async importIbGib({\n        exportIbGibJsonString,\n        rel8nName,\n        force,\n        skipRegisterTimelines,\n        divergentTimelineStrategy,\n    }: {\n        /**\n         * this is the contents of the export save file which should have been created with {@link exportIbGib}\n         */\n        exportIbGibJsonString: string,\n        /**\n         * named edge that we'll rel8 the ibGib in {@link exportIbGibJsonString}\n         * to {@link ibGib}.\n         */\n        rel8nName: string,\n        /**\n         * if true, will add rel8n even if already rel8d.\n         */\n        force?: boolean,\n        /**\n         * if true, will not call metaspace.registerNew on imported timelines.\n         *\n         * ## notes\n         *\n         * may be yagni but meh, i see it as a distinct possibility when\n         * importing that we just want to bring ibgibs in.\n         */\n        skipRegisterTimelines?: boolean,\n        /**\n         * If\n         */\n        divergentTimelineStrategy: 'supercede-timeline' | 'keep-existing-timeline' | 'optimistic-merge' | 'throw-error',\n    }): Promise<void> {\n        const lc = `${this.lc}[${this.importIbGib.name}]`;\n        try {\n\n            const metaspace = await this.getMetaspace();\n            const space = await metaspace.getLocalUserSpace({ lock: false });\n            if (!space) { throw new Error(`(UNEXPECTED) couldn't get default local user space? (E: 947c983e57a91aa00c8c185320354325)`); }\n\n            let [rawExportIbGib, ibGibGraph] = await getRawExportIbGibAndGraphFromJsonString({ exportIbGibJsonString, metaspace });\n            if (!rawExportIbGib.data) { throw new Error(`(UNEXPECTED) rawExportIbGib.data falsy? this is assumed validated at this point. (E: 6bc4e84db08e3c6228b2c40c2ea50825)`); }\n            /**\n             * this is the actual addr of the ibgib we're importing and should\n             * be the root of the export. if this exact addr already exists in the space, then the\n             * entire dependency graph is assumed to exist. if force is true, then we'll ignore this step\n             */\n            const exportRootAddr = rawExportIbGib.data.contextIbGibAddr;\n\n            let skipImportGraphIntoSpace = false;\n            if (!force) {\n                // double check to see if the import ibgib already exists in the\n                // space. if it does, then we don't need to do any\n                // saving/registering of the graph we're importing.\n\n                const resGetExisting = await metaspace.get({\n                    addr: exportRootAddr,\n                    space,\n                });\n                if (resGetExisting.success && (resGetExisting.ibGibs ?? []).length === 1) {\n                    console.log(`${lc} export's ibGib addr (${exportRootAddr}) already exists in the space, so we're skipping doing any physical importing of the export's graph. (I: 429b5bdcd0585c697869f568c4673825)`);\n                    skipImportGraphIntoSpace = true;\n                }\n            }\n\n            // before rel8ing the export to this.ibGib via rel8nName, we must\n            // save the import in the space.\n            if (!skipImportGraphIntoSpace) {\n                splitPerTjpAndOrDna\n                const graphIbGibs_dna: IbGib_V1[] = [];\n                const graphIbGibs_nondna: IbGib_V1[] = [];\n                Object.values(ibGibGraph).forEach(x => {\n                    if (isDna({ ibGib: x })) {\n                        graphIbGibs_dna.push(x);\n                    } else {\n                        graphIbGibs_nondna.push(x);\n                    }\n                });\n\n                // do the dna first\n                const resPutDna = await metaspace.put({\n                    ibGibs: graphIbGibs_dna,\n                    isDna: true,\n                    space, force,\n                });\n                if (!resPutDna.success || !!resPutDna.errorMsg) {\n                    throw new Error(`there was an error putting the export's dna ibgibs into the space (${space.ib}). error: ${resPutDna.errorMsg || '[unknown error (E: 7c7ef8d5281399b1d8f3fbeefba1b825)]'} (E: ce3e8b982208afc4889164ba20a31825)`);\n                }\n\n                // dna done, but we still may have stones (non-timeline, i.e.,\n                // no tjp) so do those next (least amount of dependencies, no\n                // need to register timelines)\n                const { mapWithTjp_YesDna, mapWithTjp_NoDna, mapWithoutTjps } = splitPerTjpAndOrDna({ ibGibs: graphIbGibs_nondna });\n                const resPutNonDnaStones = await metaspace.put({\n                    ibGibs: Object.values(mapWithoutTjps),\n                    space, force,\n                });\n                if (!resPutNonDnaStones.success || !!resPutNonDnaStones.errorMsg) {\n                    throw new Error(`there was an error putting the export's non-dna stone ibgibs (no-tjp) into the space (${space.ib}). error: ${resPutNonDnaStones.errorMsg || '[unknown error (E: dc17f8ee7aed5c445f8b827f274b0825)]'} (E: 9561364961e89c132818f6784a607825)`);\n                }\n\n                // at this point, we only have timelines left. With timelines,\n                // we need to not only put them in the space, but also register\n                // the most recent one. (maybe we should register all of them\n                // but that gets complicated.) since these are all imports,\n                // there shouldn't be anything listening specifically for\n                // updates to these timelines.\n\n                const timelineIbGibsMap = { ...mapWithTjp_YesDna, ...mapWithTjp_NoDna, };\n                const timelineIbGibs = Object.values(timelineIbGibsMap);\n\n\n                // first, let's persist them\n                const resPutTimelines = await metaspace.put({\n                    ibGibs: timelineIbGibs,\n                    space, force,\n                });\n                if (!resPutTimelines.success || !!resPutTimelines.errorMsg) {\n                    throw new Error(`there was an error putting the export's timeline ibgibs into the space (${space.ib}). error: ${resPutTimelines.errorMsg || '[unknown error (E: be4a28961574765798c8d3686ae89c25)]'} (E: 066796a23da3c9f748558fd25bfdf525)`);\n                }\n\n                // now we want to register the latest in each timeline, so at\n                // the very least if we call get latest on any of the timeline\n                // ibgibs (at any point in time within one of those timelines),\n                // the metaspace has registered the latest one.\n\n                if (!skipRegisterTimelines) {\n                    /**\n                     * from getTimelinesGroupedByTjp documentation:\n                     * > @returns filtered, sorted map of incoming `ibGibs` [tjpAddr] => timeline [ibgib0 (tjp), ibgib1, ibgib2, ..., ibgibN (latest)]\n                     */\n                    const timelineMap_groupdByTjp = getTimelinesGroupedByTjp({ ibGibs: timelineIbGibs });\n                    const timelines = Object.values(timelineMap_groupdByTjp);\n                    for (const timeline of timelines) {\n                        // we want to register the latest in the export's\n                        // timeline, BUT...  there may be a more recent ibgib\n                        // already in the given space. ALSO there might even be\n                        // a divergent timeline, such that the space has a\n                        // different timeline evolutionary path than the one in\n                        // the given export's timeline.\n                        const latestIbGibInTimeline = timeline.at(-1);\n                        if (!latestIbGibInTimeline) { throw new Error(`(UNEXPECTED) latestInTimeline falsy? this would mean that we had an empty timeline, and this doesn't make sense... (E: 3bec09e79768cc39d8029f4fe3af9825)`); }\n                        const latestAddr = await metaspace.getLatestAddr({\n                            ibGib: latestIbGibInTimeline,\n                            space,\n                        });\n                        let spaceAlreadyHasMoreRecentThanLatest = false;\n                        if (latestAddr) {\n\n                        } else {\n                            // no addrs registered with space, so\n                        }\n\n                        if (!spaceAlreadyHasMoreRecentThanLatest) {\n                            await metaspace.registerNewIbGib({\n                                ibGib: latestIbGibInTimeline,\n                                space,\n                            });\n                        }\n                    }\n                }\n            }\n\n\n            // what if the export's timeline is already related to this.ibGib via rel8nName?\n            // what if the ibgib already exists in the space?\n\n            // OK, I'm leaving off for the moment, because I need to rethink\n            // this whole strategy. may need to spawn a new local space and\n            // attempt to do it in that space. this may be where we should do\n            // the local merge/sync timelines, because what if the import has\n            // one or more divergent timelines?\n            // so importing requires some more thinking, because an import can\n            // essentially be seen as a merge.\n\n            throw new Error(`not implemented (E: 66c308e420e848c8d7cd01c8fddf8425)`);\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n}\n\n/**\n * Common plumbing for any component that is meant to contain other ibgib\n * components as children.\n */\nexport abstract class IbGibDynamicComponentInstanceBase_Parent<TIbGib extends IbGib_V1 = IbGib_V1, TElements extends ElementsBase = any, TChildInfo extends ChildInfoBase<any> = ChildInfoBase<any>>\n    extends IbGibDynamicComponentInstanceBase<TIbGib, TElements> {\n    /**\n     * @internal\n     * @protected method that gets the project tab info for the given addr.\n     *\n     * creates and loads the child ibgib component, which itself loads the\n     * ibgib internally (or throws) if not already loaded.\n     *\n     * @returns TChildInfo with fully loaded component and ibgib.\n     */\n    protected abstract getLoadedChildInfo({\n        addr,\n        ibGib,\n    }: {\n        addr: IbGibAddr,\n        ibGib?: IbGib_V1,\n    }): Promise<TChildInfo>;\n\n    childInfos: TChildInfo[] = [];\n    get activeChildInfo(): TChildInfo | undefined {\n        return this.childInfos.find(x => x.active);\n    }\n\n    /**\n     * Drives loading a child component from an {@link addr} or {@link ibGib}.\n     *\n     * - If a tab is already created for the ibgib and active, then does nothing.\n     * - If it's already created but inactive, then activates tab and loads content\n     * - if no tab, then creates it, activates it, loads content.\n     *\n     * To do this, creates/hydrates a concrete descendant of {@link ChildInfoBase}\n     * and activates it via {@link getLoadedChildInfo}\n     *\n     * @see {@link ChildInfoBase.active}\n     * @see {@link activeChildInfo}\n     */\n    public async activateIbGib({\n        addr,\n        ibGib,\n    }: {\n        addr?: IbGibAddr,\n        ibGib?: IbGib_V1,\n    }): Promise<void> {\n        const lc = `${this.lc}[${this.activateIbGib.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 05015d78983488496dcca4fa36718725)`); }\n\n            while (!this.createdPromise) {\n                await delay(50);\n            }\n            await this.createdPromise;\n\n            if (!this.elements) { throw new Error(`(UNEXPECTED) this.elements falsy? (E: fa221c138f211ee93c717c9dd0cf3225)`); }\n            const { contentEl } = this.elements;\n\n            // #region init/validate\n            // if (!this.metaspace) { throw new Error(`(UNEXPECTED) this.metaspace falsy? (E: 0ddb82cc0f1550518fd57b65ee5d4625)`); }\n            if (!ibGib && !addr) { throw new Error(`(UNEXPECTED) both ibGib and addr falsy? (E: 529fb88738cdacb10aea87b8450f2525)`); }\n            if (ibGib && addr && getIbGibAddr({ ibGib }) !== addr) { throw new Error(`(UNEXPECTED) addr !== getIbGibAddr({ibGib})? (E: c99a94d8744e3a720cdbc094d53c4e25)`); }\n            addr ??= getIbGibAddr({ ibGib });\n            const componentSvc = await getComponentSvc();\n            // #endregion init/validate\n\n            /**\n             * the point of this function is to populate this and make it active\n             */\n            let childInfo = await this.getLoadedChildInfo({ addr, ibGib });\n\n            if (childInfo.active) {\n                console.log(`${lc} same tab already active. returning early. childInfo.addr: ${childInfo.addr} (user just clicked on the same tab) (I: e67c0d02f3143c49c7a20c82d0730225)`);\n                return; /* <<<< returns early */\n            }\n\n            // at this point, we are guaranteed to have a non-active childInfo, so\n            // deactivate the old, and activate the new\n            const currentlyActive = this.activeChildInfo;\n            if (currentlyActive) {\n                currentlyActive.childBtnEl.classList.remove('active');\n                currentlyActive.active = false;\n                contentEl.innerHTML = '';\n            }\n\n            // activate the new tab\n            childInfo.childBtnEl.classList.add('active');\n            childInfo.childBtnEl.scrollIntoView({ behavior: 'smooth' });\n\n            childInfo.active = true;\n\n            let gib = getIbAndGib({ ibGibAddr: addr }).gib;\n            let gibInfo = getGibInfo({ gib });\n            let tjpGib = gibInfo.tjpGib ?? gib;\n            function tabInfoSharesTjpGib(tabInfo: TChildInfo): boolean {\n                let tabGib = getIbAndGib({ ibGibAddr: tabInfo.addr }).gib;\n                let tabGibInfo = getGibInfo({ gib: tabGib });\n                let tabTjpGib = tabGibInfo.tjpGib ?? tabGib;\n                return tabTjpGib === tjpGib;\n            }\n            // if (!this.childInfos.some(x => x.addr === childInfo.addr)) {\n            if (!this.childInfos.some(x => tabInfoSharesTjpGib(x))) {\n                this.childInfos.push(childInfo);\n            }\n            if (!childInfo.component) { throw new Error(`(UNEXPECTED) childInfo.component falsy? should be populated by this point in code (E: 77abfd1e8cd395605d46716bd087fb25)`); }\n            await componentSvc.inject({\n                parentEl: contentEl,\n                componentToInject: childInfo.component,\n            });\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    protected abstract addChild({\n        addr,\n        ibGib,\n    }: {\n        ibGib: IbGib_V1,\n        addr?: IbGibAddr,\n    }): Promise<HTMLElement>;\n\n}\n\nexport abstract class IbGibDynamicComponentInstanceBase_ParentOfTabs<TSettings extends IbGibSettings & SettingsWithTabs, TIbGib extends IbGib_V1 = IbGib_V1, TElements extends ElementsBase = any, TChildInfo extends ChildInfoBase<any> = ChildInfoBase<any>>\n    extends IbGibDynamicComponentInstanceBase_Parent<TIbGib, TElements, TChildInfo> {\n    protected lc: string = `[${IbGibDynamicComponentInstanceBase_ParentOfTabs.name}]`;\n\n    public get isBusy(): boolean {\n        // add other things to indicate busy\n        return this._reloadingTabs;\n    }\n\n    protected abstract get settingsType(): SettingsType;\n\n    protected _reloadingTabs = false;\n    protected get reloadingTabs(): boolean { return this._reloadingTabs; }\n    protected set reloadingTabs(value: boolean) {\n        const valueIsDifferent = value !== this._reloadingTabs;\n        this._reloadingTabs = value;\n        if (valueIsDifferent) {\n            this.renderUI_busy(); // spins off\n        }\n    }\n\n    protected async closeTab({ ibGib }: { ibGib: IbGib_V1 }): Promise<void> {\n        const lc = `${this.lc}[${this.closeTab.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: e0d5f8ed67b8a7f43822fa3843fd4525)`); }\n            const addrToClose = getIbGibAddr({ ibGib });\n            const tjpAddrToClose = getTjpAddr({ ibGib, defaultIfNone: 'incomingAddr' });\n            if (!tjpAddrToClose) { throw new Error(`(UNEXPECTED) tjpAddr false after incomingAddr default? ibGib: ${pretty(ibGib)} (E: 707988b4d22a27c1287aa5a815d88825)`); }\n            const tabInfoToClose = await this.getLoadedChildInfo({ addr: addrToClose, ibGib });\n\n            // if it's active, activate the tab to the left/right?\n\n            // remove from project open tabs in settings for project ibgib\n            // let projectSettings = await this.getCurrentProjectSettings();\n            const settings_current = await this.getSettings<TSettings>({\n                settingsType: this.settingsType,\n                useCase: 'current',\n            });\n            if (!settings_current) { throw new Error(`(UNEXPECTED) settings_current falsy for this project? this.ibGib: ${pretty(this.ibGib)} (E: ecea08dcacd198bb38cc44a860cc6825)`); }\n\n            if (!settings_current.openChildTjpAddrs.includes(tjpAddrToClose)) {\n                throw new Error(`${lc} (UNEXPECTED) projectSettings didn't have the tjpAddr (${tjpAddrToClose})? projectSettings: ${pretty(settings_current)} (E: genuuid)`);\n            }\n            let newOpenChildTjpAddrs = settings_current.openChildTjpAddrs.filter(x => x !== tjpAddrToClose);\n            let newActiveChildTjpAddr: TjpIbGibAddr | undefined = undefined;\n            // settings_current.openChildTjpAddrs.push(tjpAddrToClose); // ????\n            if (settings_current.activeChildTjpAddr === tjpAddrToClose) {\n                // get the addr just before the current one that we're closing.\n                // if it doesn't exist, use the project's tjpAddr.\n                if (newOpenChildTjpAddrs.length > 0) {\n                    // this implies that the old openChildTjpAddrs.length >= 2\n                    let newIndex = settings_current.openChildTjpAddrs.indexOf(tjpAddrToClose) - 1;\n                    if (newIndex < 0) { newIndex = 0; }\n                    newActiveChildTjpAddr = settings_current.openChildTjpAddrs.at(newIndex);\n                } else {\n                    newActiveChildTjpAddr = this.tjpAddr!;\n                    newOpenChildTjpAddrs.push(this.tjpAddr!);\n                }\n            }\n            const sectionName_current = await getSectionName({\n                settingsType: this.settingsType,\n                useCase: 'current',\n            });\n            const newSectionSettings = {\n                ...settings_current,\n                openChildTjpAddrs: newOpenChildTjpAddrs,\n            };\n            // if (!!newActiveChildTjpAddr) {\n            //     newProjectSettings.activeChildTjpAddr = newActiveChildTjpAddr;\n            // }\n            const metaspace = await this.getMetaspace();\n            const _newSettings = await mut8Timeline({\n                timeline: this.settings!.ibGib!,\n                metaspace,\n                mut8Opts: {\n                    dataToAddOrPatch: {\n                        sections: {\n                            [sectionName_current]: newSectionSettings,\n                        }\n                    },\n                },\n            });\n\n            if (tabInfoToClose.active) {\n                await this.activateIbGib({ addr: newActiveChildTjpAddr });\n            }\n\n            // physically remove component/tab btn\n            this.childInfos = this.childInfos.filter(x => x.addr !== tabInfoToClose.addr);\n            await this.removeTabBtn({ tabInfo: tabInfoToClose });\n            // this.elements!.headerTabsEl!.removeChild(tabInfo.childBtnEl);\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    protected abstract removeTabBtn({\n        tabInfo,\n    }: {\n        tabInfo: TChildInfo,\n    }): Promise<void>;\n\n    protected async reopenOldTabs(): Promise<void> {\n        const lc = `${this.lc}[${this.reopenOldTabs.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 195e7d34b3f8b761aa78dd384011f825)`); }\n\n            // let settings = await this.getCurrentProjectSettings();\n            const settings = await this.getSettings<TSettings>({\n                settingsType: this.settingsType,\n                useCase: 'current',\n            });\n            if (!settings) { throw new Error(`(UNEXPECTED) settings falsy? these should be initialized before now. (E: 2003ab77e01448d638216fc82aff5f25)`); }\n\n            this.reloadingTabs = true;\n            await this.renderUI_busy();\n            let currentChildTjpAddr: IbGibAddr | undefined;\n            try {\n                for (const childTjpAddr of settings.openChildTjpAddrs) {\n                    // slow kluge I think...maybe it's ok I dunno.\n                    currentChildTjpAddr = childTjpAddr;\n                    await this.activateIbGib({ addr: childTjpAddr });\n                }\n            } catch (error) {\n                console.error(`${lc} error during activating child ibGib tabs. childTjpAddr: ${currentChildTjpAddr ?? '[unset?]'} (E: 0396b2e24d08f42ac94510bb718a1725)`);\n                throw error;\n            } finally {\n                this.reloadingTabs = false;\n            }\n\n            // not reloading, so now we can activate the recently active one\n            await this.activateIbGib({ addr: settings.activeChildTjpAddr });\n\n            // await this.activateLensMode({ lensMode: settings.lensMode, skipInject: false });\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n}\n", "\n/**\n * @constant RENDER_SERVICE_HANDLE_TYPE - The handle type for the rendering service.\n */\nexport const RENDER_SERVICE_HANDLE_TYPE = 'RenderService';\n/**\n * @constant RENDERABLE_HANDLE_TYPE - The handle type for individual renderable objects.\n */\nexport const RENDERABLE_HANDLE_TYPE = 'Renderable';\n/**\n * @constant CANVAS_HANDLE_TYPE - The handle type for the canvas element.\n */\nexport const CANVAS_HANDLE_TYPE = 'Canvas';\n\n// #region RenderableShape\nconst RENDERABLE_SHAPE_RECTANGLE = 'rect';\nconst RENDERABLE_SHAPE_CIRCLE = 'circle';\nconst RENDERABLE_SHAPE_PATH = 'path';\nconst RENDERABLE_SHAPE_TEXT = 'text';\nconst RENDERABLE_SHAPE_GROUP = 'group';\n\nexport type RenderableShape =\n    | typeof RENDERABLE_SHAPE_RECTANGLE\n    | typeof RENDERABLE_SHAPE_CIRCLE\n    | typeof RENDERABLE_SHAPE_PATH\n    | typeof RENDERABLE_SHAPE_TEXT\n    | typeof RENDERABLE_SHAPE_GROUP\n    ;\n\nexport const RenderableShape = {\n    RECTANGLE: RENDERABLE_SHAPE_RECTANGLE as RenderableShape,\n    CIRCLE: RENDERABLE_SHAPE_CIRCLE as RenderableShape,\n    PATH: RENDERABLE_SHAPE_PATH as RenderableShape,\n    TEXT: RENDERABLE_SHAPE_TEXT as RenderableShape,\n    GROUP: RENDERABLE_SHAPE_GROUP as RenderableShape, // <-- ADD THIS\n} satisfies { [key: string]: RenderableShape };\n// #endregion RenderableShape\n", "import { clone, extractErrorMsg, getIdPool, pretty, } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';\n\nimport { GLOBAL_LOG_A_LOT } from '../constants.mjs';\nimport {\n    CanvasHandle, GeometryParametersGroup, GeometryParametersPath, GeometryParametersRect,\n    GeometryParametersText, HandleBase, RenderableCreateOpts,\n    RenderableCreateResult, RenderableDestroyOpts, RenderableDestroyResult,\n    RenderableGetAllStatesResult,\n    RenderableGetOpts, RenderableGetResult, RenderableHandle, RenderableState, RenderableStateMap,\n    RenderableUpdateOpts, RenderableUpdateResult, RenderService,\n    Vector3\n} from './render-types.mjs';\nimport {\n    CANVAS_HANDLE_TYPE, RENDERABLE_HANDLE_TYPE, RenderableShape,\n} from './render-constants.mjs';\nimport { PathCommand, } from '../api/commands/renderable/path-command/path-command-types.mjs';\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\n/**\n * @interface RenderServiceCtorOpts - Options for the RenderService constructor.\n */\ninterface RenderServiceCtorOpts {\n    /**\n     * @property renderSvcId - optional id of the render service. if falsy, will\n     * generate a new one.\n     */\n    renderSvcId?: string;\n    /**\n     * @property parentContainerEl - An optional container where new canvas\n     * should be dynamically added when not explicitly provided.\n     */\n    parentContainerEl?: HTMLElement;\n    /**\n     * @property canvasEl - An optional existing HTMLCanvasElement to use. If\n     * not provided, a new one will be created.\n     */\n    canvasEl?: HTMLCanvasElement;\n}\n\n/**\n * @class RenderService_V1 - Implementation of the rendering service.\n * Implements the {@link RenderService} interface.\n */\nexport class RenderService_V1 implements RenderService {\n    protected lc = `[${RenderService_V1.name}]`;\n    /**\n     * @property initialized - A promise that resolves when the rendering service is fully initialized.\n     */\n    public readonly initialized: Promise<void>;\n\n    /**\n     * @private\n     * @property uuidPool - A pool of pre-generated UUIDs for handles.\n     */\n    private uuidPool: string[] = [];\n\n    /**\n     * @private\n     * @property canvas - The HTMLCanvasElement used for rendering.\n     */\n    private canvas: HTMLCanvasElement;\n\n    /**\n     * @private\n     * @property context - The 2D rendering context of the canvas.\n     */\n    private context: CanvasRenderingContext2D | null;\n\n    /**\n     * @private\n     * @property renderables - A map of renderable handles to their current state.\n     */\n    private renderables: Map<RenderableHandle, RenderableState> = new Map();\n\n    /**\n     * @private\n     * @property handleToUUID - A map to quickly lookup the UUID string given a handle.\n     */\n    private handleToUUID: Map<HandleBase, string> = new Map();\n\n    /**\n     * @private\n     * @property uuidToHandle - A map for reverse lookup from UUID to handle.\n     */\n    private uuidToHandle: Map<string, HandleBase> = new Map();\n\n    /**\n       * @private\n       * @property canvasHandle - The handle for the managed canvas element.\n       */\n    private canvasHandle: CanvasHandle;\n\n    /**\n     * @private\n     * @property dirty - A flag indicating whether the canvas needs to be re-rendered.\n     */\n    private dirty: boolean = false;\n\n    /**\n     * used with correlating render service to canvas instance.\n     */\n    public renderSvcId: string;\n\n    /**\n     * Constructs a new RenderService instance.\n     * @param {RenderServiceCtorOpts} [opts] - Options for initializing the rendering service.\n     */\n    constructor(opts?: RenderServiceCtorOpts) {\n        const { renderSvcId, canvasEl, parentContainerEl, } = opts ?? {};\n        this.renderSvcId = renderSvcId ?? this.getUUID();\n\n        if (canvasEl) {\n            this.canvas = canvasEl;\n        } else {\n            this.canvas = document.createElement('canvas');\n            this.canvas.style.width = '100%';\n            this.canvas.style.height = '100%';\n            this.canvas.width = this.canvas.offsetWidth;\n            this.canvas.height = this.canvas.offsetHeight;\n\n            if (parentContainerEl) {\n                parentContainerEl.appendChild(this.canvas);\n            } else {\n                document.body.appendChild(this.canvas);\n            }\n        }\n\n        this.context = this.canvas.getContext('2d');\n        this.canvasHandle = this.createNewCanvasHandle(); // Create the canvas handle here\n        this.initialized = this.initialize(); // spins off\n        this.startRenderLoop();\n    }\n\n    /**\n     * Marks the canvas as dirty, triggering a re-render on the next animation frame.\n     */\n    private markDirty(): void {\n        this.dirty = true;\n    }\n\n    /**\n     * Starts the rendering loop using requestAnimationFrame.\n     * @private\n     */\n    private startRenderLoop(): void {\n        const renderFrame = () => {\n            if (this.dirty) {\n                this.render();\n                this.dirty = false;\n            }\n            requestAnimationFrame(renderFrame);\n        };\n        requestAnimationFrame(renderFrame);\n    }\n\n    /**\n     * Returns the handle associated with the managed canvas.\n     * @returns {CanvasHandle} The handle for the canvas.\n     */\n    public getCanvasHandle(): CanvasHandle {\n        return this.canvasHandle;\n    }\n\n    public getCanvas(): HTMLCanvasElement {\n        return this.canvas;\n    }\n\n    /**\n     * Initializes the rendering service, including pre-generating UUIDs.\n     * @private\n     * @returns {Promise<void>} A promise that resolves when the service is initialized.\n     */\n    private async initialize(): Promise<void> {\n        await this.generateUUIDs(1000);\n\n        // Any other async initialization can go here.\n    }\n\n    /**\n     * Generates a batch of UUIDs and adds them to the pool.\n     * @private\n     * @param {number} count - The number of UUIDs to generate.\n     */\n    private async generateUUIDs(count: number): Promise<void> {\n        const ids = await getIdPool({ n: count });\n        this.uuidPool.push(...ids);\n    }\n\n    /**\n     * Gets a UUID from the pool. If the pool is empty, generates more.\n     * @private\n     * @returns {string} A UUID.\n     */\n    private getUUID(): string {\n        const lc = `[${this.getUUID.name}]`;\n        if (!this.uuidPool) {\n            console.warn(`${lc} (UNEXPECTED) this.uuidPool not initialized even with an empty array? Are we calling getUUID in a property initializer before this prop? We will go ahead and initialize with empty array, but this should be fixed in code. (W: 089ebedc858276b89ee3f1e4ad0ede25)`);\n            this.uuidPool = [];\n        }\n\n        // arbitrary low threshold. turn this into a constant later\n        if (this.uuidPool.length < 50) {\n            this.generateUUIDs(1000); // spins off to generate more\n        }\n        if (this.uuidPool.length === 0) {\n            // return an emergency sync uuid using crypto.randomUUID, stripping away the dashes\n            return crypto.randomUUID().replace(/-/g, '');\n        } else {\n            return this.uuidPool.pop()!;\n        }\n    }\n\n    /**\n     * Creates a new renderable handle.\n     * @private\n     * @returns {RenderableHandle} The newly created renderable handle.\n     */\n    private createNewRenderableHandle(): RenderableHandle {\n        const uuid = this.getUUID();\n        const handle: RenderableHandle = { type: RENDERABLE_HANDLE_TYPE, uuid };\n        this.handleToUUID.set(handle, uuid);\n        this.uuidToHandle.set(uuid, handle);\n        return handle;\n    }\n\n    /**\n     * Creates a new canvas handle.\n     * @private\n     * @returns {CanvasHandle} The newly created canvas handle.\n     */\n    private createNewCanvasHandle(): CanvasHandle {\n        const uuid = this.getUUID();\n        const handle: CanvasHandle = { type: CANVAS_HANDLE_TYPE, uuid };\n        this.handleToUUID.set(handle, uuid);\n        this.uuidToHandle.set(uuid, handle);\n        return handle;\n    }\n\n    /**\n     * @inheritdoc\n     */\n    public async renderableCreate(opts: RenderableCreateOpts): Promise<RenderableCreateResult> {\n        const lc = `${this.lc}[${this.renderableCreate.name}]`;\n        if (opts.renderSvcId !== this.renderSvcId) { throw new Error(`${lc} wrong render svc. opts.renderSvcId (${opts.renderSvcId}) !== this.renderSvcId (${this.renderSvcId}) (E: 59ec231939f4ddafde37d536f440a225)`); }\n        const handle = this.createNewRenderableHandle();\n        if (opts.initialState.geometry?.parameters) {\n            const { type, parameters } = opts.initialState.geometry;\n            switch (type) {\n                case RenderableShape.RECTANGLE:\n                    const paramsRect = parameters as GeometryParametersRect;\n                    // if the model only provides height or width, make the other one the same\n                    paramsRect.height ??= paramsRect.width;\n                    paramsRect.width ??= paramsRect.height;\n                    break;\n                case RenderableShape.TEXT:\n                    const paramsText = parameters as GeometryParametersText;\n                    if (!paramsText.fontSize) {\n                        // the model passes in just width sometimes instead of font size.\n                        paramsText.fontSize = (parameters as any).width ?? (parameters as any).height ?? 1;\n                    }\n                    break;\n                case RenderableShape.GROUP:\n                    // do we do anything additional for groups?\n                    // const paramsGroup = parameters as GeometryParametersGroup;\n                    break;\n                case RenderableShape.PATH:\n                    // do we do anything additional for groups?\n                    const paramsPath = parameters as GeometryParametersPath;\n                    break;\n                default:\n                    throw new Error(`(UNEXPECTED) opts.initialState.geometry.type: ${type}? (E: 941a165e137a7cb548d2665bb0399625)`);\n            }\n        }\n        this.renderables.set(handle, opts.initialState);\n        this.markDirty();\n        return { handle, renderSvcId: this.renderSvcId, };\n    }\n\n    /**\n     * @inheritdoc\n     */\n    public async renderableUpdate(opts: RenderableUpdateOpts): Promise<RenderableUpdateResult> {\n        const lc = `${this.lc}[${this.renderableUpdate.name}]`;\n        if (opts.renderSvcId !== this.renderSvcId) { throw new Error(`${lc} wrong render svc. opts.renderSvcId (${opts.renderSvcId}) !== this.renderSvcId (${this.renderSvcId}) (E: 59ec231939f4ddafde37d536f440a225)`); }\n\n        for (const targetInfo of opts.targets) {\n            const rawHandle = targetInfo.handle;\n            const handle = this.getRenderableHandle({ rawHandle });\n            if (!handle) { throw new Error(`handle not found. uuid: ${rawHandle.uuid} (E: 9cd5187a2addf64748ca6e1907291825)`); }\n            const resGetRenderableState = await this.getRenderableState({ renderSvcId: opts.renderSvcId, handles: [handle] });\n            const currentStateMap = resGetRenderableState.stateMap;\n            const stateMapEntry = currentStateMap[handle.uuid];\n            if (!stateMapEntry) { throw new Error(`stateMapEntry not found for handle.uuid: ${handle.uuid} (E: ec05ef7a7b064813b1782db7d71a7c25)`); }\n            const currentState = stateMapEntry.state;\n            if (!currentState) { throw new Error(`currentState not found for handle.uuid: ${handle.uuid} (E: ad8ef415e7d194dcfdbcffc8b013b825)`); }\n            if (currentState) {\n                if (currentState.geometry.type === RenderableShape.GROUP) {\n                    // update a renderable group. there are two possibilities:\n\n                    // 1. group.members is changing\n                    // 2. group members' states are changing\n\n                    const currentGeometryGroupParameters = currentState.geometry.parameters as GeometryParametersGroup;\n                    if (targetInfo.updatedState.geometry) {\n                        // geometry being truthy indicates that we are changing\n                        // the group's members\n\n                        // 1. group.members is changing\n                        if (opts.recursive) { throw new Error(`opts.recursive is true but targetInfo.updatedState.geometry is truthy. This indicates that the updatedState is changing a group's members (else geometry would be undefined). This does not make sense. You can use recursive IF AND ONLY IF you are changing a common renderable property like color or scale. (E: eb8298c3133f2662e39f1d5877ec2825)`); }\n                        const updatedStateKeys = Object.keys(targetInfo.updatedState);\n                        if (updatedStateKeys.length > 1) {\n                            // geometry is truthy, so the others are incorrect\n                            throw new Error(`cannot update both group geometry and group members' other state properties in the same update call. UpdatedStateKeys: ${updatedStateKeys} (E: 08c2c87f4528d7563890d16208cbd825)`);\n                        }\n                        const updatedMembers =\n                            (targetInfo.updatedState.geometry.parameters as GeometryParametersGroup).members;\n                        currentGeometryGroupParameters.members = updatedMembers;\n                    } else {\n                        // 2. group members' states are changing\n                        // so we update the group's members recursively\n\n                        // NOTE: this MAY be a bug WRT recursive groups? will have to see\n                        await this.renderableUpdate({\n                            renderSvcId: opts.renderSvcId,\n                            targets: currentGeometryGroupParameters.members.map(memberHandle => {\n                                return {\n                                    handle: memberHandle,\n                                    updatedState: targetInfo.updatedState,\n                                }\n                            }),\n                            recursive: opts.recursive,\n                        });\n                    }\n                } else {\n                    // not a group\n                    if (targetInfo.updatedState?.color) {\n                        // there is some issue with color that the LLMs refuse to output the full rgba value.\n                        targetInfo.updatedState.color = { ...currentState.color, ...targetInfo.updatedState.color };\n                    }\n                    this.renderables.set(handle, { ...currentState, ...targetInfo.updatedState });\n                    this.markDirty();\n                }\n            } else {\n                console.warn(`${lc} Attempting to update non-existent renderable with handle: ${handle.uuid} (W: 8071c40f941a39d39e104f4fe2279d24)`);\n            }\n        }\n\n        return { renderSvcId: this.renderSvcId, };\n    }\n\n    /**\n     * @inheritdoc\n     */\n    public async renderableDestroy(opts: RenderableDestroyOpts): Promise<RenderableDestroyResult> {\n        const lc = `${this.lc}[${this.renderableDestroy.name}]`;\n        if (opts.renderSvcId !== this.renderSvcId) { throw new Error(`${lc} wrong render svc. opts.renderSvcId (${opts.renderSvcId}) !== this.renderSvcId (${this.renderSvcId}) (E: 59ec231939f4ddafde37d536f440a225)`); }\n        const { recursive } = opts;\n        for (const rawHandle of opts.handles) {\n            const handle = this.getRenderableHandle({ rawHandle });\n            if (handle) {\n                if (recursive) {\n                    // first check the state. if it's a group, we need to\n                    // recursively call destroy.\n                    const stateMap =\n                        await this.getRenderableState({\n                            renderSvcId: opts.renderSvcId,\n                            handles: [handle]\n                        });\n                    const stateInfo = stateMap[handle.uuid];\n                    if (stateInfo) {\n                        if (stateInfo.state.geometry.type === RenderableShape.GROUP) {\n                            const paramsGroup =\n                                stateInfo.state.geometry.parameters as GeometryParametersGroup;\n                            await this.renderableDestroy({\n                                renderSvcId: opts.renderSvcId,\n                                handles: paramsGroup.members,\n                            });\n                        }\n                    } else {\n                        console.warn(`${lc} destroying renderable but couldn't get the state? (W: 9986ddab9c425f361df75703ef710725)`);\n                    }\n                }\n                this.renderables.delete(handle);\n                this.handleToUUID.delete(handle);\n                this.uuidToHandle.delete(handle.uuid);\n                this.markDirty();\n            } else {\n                console.warn(`${lc} handle does not exist (W: 6e7a646b7e88e13a9ed76ab8d54ce825)`)\n            }\n        }\n\n        return { renderSvcId: this.renderSvcId, };\n    }\n\n    /**\n     * helper to get the renderable handle by uuid, even if it isn't the actual\n     * object reference.\n     *\n     * ## driving use case\n     * The agent will call functions via the uuid not handle instances\n     *\n     * @returns renderable handle with matching uuid\n     * @throws if rawHandle is not a renderable handle (type is not 'Renderable')\n     */\n    private getRenderableHandle({ rawHandle }: { rawHandle: HandleBase }): RenderableHandle | undefined {\n        if (rawHandle.type !== RENDERABLE_HANDLE_TYPE) {\n            throw new Error(`(UNEXPECTED) rawHandle is not a renderable handle. rawHandle: ${pretty(rawHandle)} (E: 1c10ed31b288d39314e7175d085c4225)`);\n        }\n        const handle = this.uuidToHandle.get(rawHandle.uuid) as RenderableHandle | undefined;\n        return handle;\n    }\n\n    /**\n     * @inheritdoc\n     *\n     * tries via the raw handle, then via the uuid\n     */\n    public async getRenderableState(opts: RenderableGetOpts): Promise<RenderableGetResult> {\n        const lc = `${this.lc}[${this.getRenderableState.name}]`;\n        if (opts.renderSvcId !== this.renderSvcId) { throw new Error(`${lc} wrong render svc. opts.renderSvcId (${opts.renderSvcId}) !== this.renderSvcId (${this.renderSvcId}) (E: 59ec231939f4ddafde37d536f440a225)`); }\n        const resMap: RenderableStateMap = {};\n        for (let { uuid } of opts.handles) {\n            if (!uuid) { throw new Error(`(UNEXPECTED) uuid falsy? opts.handles should only contain actual truthy uuids at the very least (even if the renderable doesn't exist) (E: bfc41840b854aad226e3f70e53eb4e25)`); }\n            const handle =\n                this.getRenderableHandle({ rawHandle: { type: 'Renderable', uuid } });\n            if (handle) {\n                const state: RenderableState | undefined = this.renderables.get(handle);\n                if (state) {\n                    resMap[uuid] = { handle, state };\n                } else {\n                    throw new Error(`(UNEXPECTED) handle is truthy for uuid (${uuid}) but state is falsy? (E: 47e278636df8c208581bb47835356e25)`);\n                }\n            } else {\n                console.warn(`${lc} uuid not found: ${uuid} (W: ac320db2a5086d864c371092c2ce7825)`);\n                resMap[uuid] = undefined;\n            }\n        }\n        return { renderSvcId: opts.renderSvcId, stateMap: resMap };\n    }\n\n    /**\n     *  Returns the internal map.\n     *\n     * @returns  ReadonlyMap<RenderableHandle, RenderableState> The renderables map, but immutable.\n     */\n    public getRenderableStates(): RenderableGetAllStatesResult {\n        return {\n            renderSvcId: this.renderSvcId,\n            handleToStatesMap: this.renderables,\n        }\n    }\n\n    // #region render and render sub-methods\n\n    /**\n     * @inheritdoc\n     */\n    public render(): void {\n        const lc = `${this.lc}[${this.render.name}]`;\n        if (!this.context) {\n            console.error(`${lc} Canvas context not initialized. (E: 7d5755ca9a4148e1141298c59ce94b24)`);\n            return;\n        }\n\n        // Clear the canvas\n        this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);\n\n        for (const [handle, state] of this.renderables) {\n            if (state.isVisible) {\n                switch (state.geometry.type) {\n                    case RenderableShape.RECTANGLE: { this.render_rect({ handle, state }); break; }\n                    case RenderableShape.TEXT: { this.render_text({ handle, state }); break; }\n                    case RenderableShape.PATH: { this.render_path({ handle, state }); break; }\n                    default: console.error(`${lc}[${handle.uuid}] (UNEXPECTED) unknown state.geometry.type: ${state.geometry.type}? (E: a60c479e9e389ae4f7f78782643a4925)`);\n                }\n            } else {\n                if (logalot) { console.log(`${lc}[${handle.uuid}] state.isVisible is false, skipping rendering. (I: a0e437dd9938c2a1677f47ddb2f97525)`); }\n            }\n        }\n    }\n    private render_rect({ handle, state }: { handle: RenderableHandle, state: RenderableState }): void {\n        const lc = `${this.lc}[${this.render_text.name}][${handle.uuid}]`;\n        if (!this.context) {\n            console.error(`${lc} Canvas context not initialized. (E: cd8ac97c4656ebf78c101c8fa3f58125)`);\n            return;\n        }\n        const { geometry, position, scale, color } = state;\n        this.context.fillStyle = `rgba(${color.r * 255}, ${color.g * 255}, ${color.b * 255}, ${color.a})`;\n        const { width, height } = geometry.parameters as GeometryParametersRect;\n        this.context.fillRect(\n            position.x,\n            position.y,\n            width * scale.x,\n            height * scale.y\n        );\n    }\n    private render_text({ handle, state }: { handle: RenderableHandle, state: RenderableState }): void {\n        const lc = `${this.lc}[${this.render_text.name}][${handle.uuid}]`;\n        if (!this.context) {\n            console.error(`${lc} Canvas context not initialized. (E: 9aa66a49052c48d743f3aaa1799cbf25)`);\n            return;\n        }\n        const { geometry, position, scale, color } = state;\n        this.context.fillStyle = `rgba(${color.r * 255}, ${color.g * 255}, ${color.b * 255}, ${color.a})`;\n        const { text, fontFamily, fontSize } = geometry.parameters as GeometryParametersText;\n        this.context.font = `${fontSize}px ${fontFamily}`;\n        this.context.fillText(text, position.x, position.y);\n    }\n    private render_path({ handle, state }: { handle: RenderableHandle, state: RenderableState }): void {\n        const lc = `${this.lc}[${this.render_text.name}][${handle.uuid}]`;\n        // usually in these render calls I am trying not to wrap in try..catch\n        // but this is a more complicated renderable\n        try {\n            if (!this.context) { throw new Error(`(UNEXPECTED) !this.context? not initialized? (E: a26bcd9b76237b3deefa2b8dc3f3f325)`); }\n            const ctx = this.context;\n\n            const { geometry, position, scale, color } = state;\n            ctx.fillStyle = `rgba(${color.r * 255}, ${color.g * 255}, ${color.b * 255}, ${color.a})`;\n            ctx.strokeStyle = `rgba(${color.r * 255}, ${color.g * 255}, ${color.b * 255}, ${color.a})`; // Set strokeStyle to same color for now - can be separate property later\n            ctx.lineWidth = 2; // Example line width - can be a property later\n\n            const { commands } = geometry.parameters as GeometryParametersPath;\n            if (!commands || commands.length === 0) {\n                console.warn(`${lc} no commands in geometry.parameters.commands (W: de39da7bac141055c7e02c7326a89d25)`);\n                return; /* <<<< returns early, nothing to render */\n            }\n\n            const fnCheapValidateCmd: (command: PathCommand) => void = (command) => {\n                const actualCmd = command[command.type!];\n                if (!actualCmd) { throw new Error(`invalid path command. command.type === ${command.type} but command[${command.type}] is falsy (E: 9842c2e8fd3e257f53ba61d9de8eb725)`); }\n                // if (actualCmd.type !== command.type) { throw new Error(`actualCmd.type (${actualCmd.type}) !== command.type (${command.type}). command: ${pretty(command)} (E: e7065c95f8330b1a7a7196a383e89925)`); }\n            }\n\n            /**\n             * keep track of moveTo, lineTo, etc.\n             *\n             * this is NOT scale-adjusted yet...\n             */\n            // let runningStartPos = clone(position) as Vector3;\n\n            for (const command of commands) {\n                if (!command.type) {\n                    debugger; // improper command generated by agent. command.type is falsy. want to see in what context here.\n                    console.warn(`${lc} command.type falsy, skipping command (W: a27ba1df32047dd541a672b85b0e6e25)`);\n                    // todo: manually figure out the type here via state.geometry.parameters\n                    continue; /* <<<< continue to next command */\n                }\n\n                // at this point, we have asserted that our commands are properly formed.\n\n                switch (command.type) {\n                    case 'moveTo': {\n                        // todo: flesh out better runtime path command validation\n                        fnCheapValidateCmd(command);\n                        const cmd = (command as PathCommand).moveTo!;\n                        // runningStartPos = {\n                        //     x: position.x + cmd.x,\n                        //     y: position.y + cmd.y,\n                        //     z: 0, // position.z + cmd.z * scale.z,\n                        // }\n                        ctx.moveTo(position.x + cmd.x * scale.x, position.y + cmd.y * scale.y); // Apply position and scale\n                        // ctx.moveTo(runningStartPos.x * scale.x, runningStartPos.y * scale.y); // Apply position and scale\n                        break;\n                    }\n                    case 'line': {\n                        // todo: flesh out better runtime path command validation\n                        fnCheapValidateCmd(command);\n                        const cmd = (command as PathCommand).line!;\n                        if (cmd.x1 !== undefined || cmd.y1 !== undefined) {\n                            // origin point given, so create a moveTo to that point\n                            ctx.moveTo(position.x + (cmd.x1 ?? 0) * scale.x, position.y + (cmd.y1 ?? 0) * scale.y); // Apply position and scale\n                        }\n                        ctx.lineTo(position.x + cmd.x2 * scale.x, position.y + cmd.y2 * scale.y); // Apply position and scale to end point\n                        break;\n                    }\n                    case 'arc': {\n                        // todo: flesh out better runtime path command validation\n                        fnCheapValidateCmd(command);\n                        const cmd = (command as PathCommand).arc!;\n                        ctx.arc(\n                            position.x + cmd.x * scale.x,  // Apply position and scale to center\n                            position.y + cmd.y * scale.y,  // Apply position and scale to center\n                            cmd.radius * scale.x,            // Apply scale to radius (assume uniform scale for now)\n                            cmd.startAngle,\n                            cmd.endAngle,\n                            cmd.anticlockwise\n                        );\n                        break;\n                    }\n                    case 'bezierCurve': {\n                        // todo: flesh out better runtime path command validation\n                        fnCheapValidateCmd(command);\n                        const cmd = (command as PathCommand).bezierCurve!;\n                        if (cmd.x1 !== undefined || cmd.y1 !== undefined) {\n                            // origin point given, so create a moveTo to that point\n                            ctx.moveTo(position.x + (cmd.x1 ?? 0) * scale.x, position.y + (cmd.y1 ?? 0) * scale.y); // Apply position and scale\n                        }\n                        ctx.bezierCurveTo(\n                            position.x + cmd.cp1x * scale.x, // Apply position and scale to control point 1\n                            position.y + cmd.cp1y * scale.y, // Apply position and scale to control point 1\n                            position.x + cmd.cp2x * scale.x, // Apply position and scale to control point 2\n                            position.y + cmd.cp2y * scale.y, // Apply position and scale to control point 2\n                            position.x + cmd.x2 * scale.x,    // Apply position and scale to end point\n                            position.y + cmd.y2 * scale.y     // Apply position and scale to end point\n                        );\n                        break;\n                    }\n                    case 'quadraticBezierCurve': {\n                        // todo: flesh out better runtime path command validation\n                        fnCheapValidateCmd(command);\n                        const cmd = (command as PathCommand).quadraticBezierCurve!;\n                        if (cmd.x1 !== undefined || cmd.y1 !== undefined) {\n                            // origin point given, so create a moveTo to that point\n                            ctx.moveTo(position.x + (cmd.x1 ?? 0) * scale.x, position.y + (cmd.y1 ?? 0) * scale.y); // Apply position and scale\n                        }\n                        ctx.quadraticCurveTo(\n                            position.x + cmd.cpx * scale.x, // Apply position and scale to control point\n                            position.y + cmd.cpy * scale.y, // Apply position and scale to control point\n                            position.x + cmd.x2 * scale.x,    // Apply position and scale to end point\n                            position.y + cmd.y2 * scale.y     // Apply position and scale to end point\n                        );\n                        break;\n                    }\n\n                    // #region boolean commands\n\n                    // NOTE: These do NOT follow the PathCommand interface. So\n                    // we are not validating them.  Seemed like a lot of waste,\n                    // and it's kind of lame and a code smell. But this entire\n                    // interface structure smells because of the lack of OpenAPI\n                    // schema support in the Gemini function calling API.\n\n                    case 'closePath': { ctx.closePath(); break; }\n                    case 'beginPath': {\n                        ctx.beginPath();\n                        break;\n                    }\n                    case 'stroke': {\n                            // ctx.stroke();\n                        const cmd = (command as PathCommand).stroke;\n                        if (cmd) {\n                            const initialWidth = ctx.lineWidth;\n                            // do overrides\n                            if (cmd.color) {\n                                ctx.strokeStyle = `rgba(${cmd.color.r * 255}, ${cmd.color.g * 255}, ${cmd.color.b * 255}, ${cmd.color.a})`;\n                            }\n                            if (cmd.width !== undefined) { ctx.lineWidth = cmd.width; }\n\n                            // execute\n                            ctx.stroke();\n\n                            // return it back from overrides\n                            if (cmd.color) {\n                                ctx.strokeStyle = `rgba(${color.r * 255}, ${color.g * 255}, ${color.b * 255}, ${color.a})`;\n                            }\n                            if (cmd.width !== undefined) { ctx.lineWidth = initialWidth; }\n                        } else {\n                            // no cmd so no override options. just call stroke()\n                            ctx.stroke();\n                        }\n                        break;\n                    }\n                    case 'fill': { ctx.fill(); break; }\n\n                    // #endregion boolean commands\n\n                    default:\n                        console.error(`${lc} Unknown path command type: ${command.type} (E: 74fba72be5451c6509fe305afd4e1125)`);\n                }\n            }\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            // throw error; // does not rethrow\n        }\n    }\n\n    // #endregion render and render sub-methods\n\n    /**\n     * @inheritdoc\n     */\n    public getContext(): CanvasRenderingContext2D | null {\n        return this.context;\n    }\n}\n\n// render-service-factory\n\n/**\n * @private\n * @type {RenderService_V1 | undefined} - A singleton instance of the RenderService.\n */\nlet globalRenderService: { [svcId: string]: RenderService_V1 } = {};\n\n/**\n * Options for getting the Render Service.\n */\ninterface GetRenderServiceOpts extends RenderServiceCtorOpts {\n    /**\n     * Id of the render service to get.\n     */\n    renderSvcId: string;\n    /**\n     * If true, forces the creation of a new RenderService instance.\n     */\n    forceNew?: boolean;\n}\n\n/**\n * Gets the singleton instance of the RenderService.\n * @param {GetRenderServiceOpts} [opts] - Options for getting the service.\n * @returns {RenderService_V1} The RenderService instance.\n */\nexport function getRenderService(opts: GetRenderServiceOpts): RenderService_V1 {\n    const { renderSvcId, forceNew } = opts;\n    if (forceNew) {\n        globalRenderService[renderSvcId] = new RenderService_V1(opts);\n    }\n\n    let renderSvc: RenderService_V1;\n    if (globalRenderService[renderSvcId]) {\n        renderSvc = globalRenderService[renderSvcId];\n    } else {\n        renderSvc = new RenderService_V1(opts);\n        globalRenderService[renderSvcId] = renderSvc;\n    }\n    if (renderSvc.renderSvcId !== opts.renderSvcId) {\n        debugger; // error get render svc\n        throw new Error(`(UNEXPECTED) renderSvc.renderSvcId (${renderSvc.renderSvcId}) !== opts.renderSvcId (${opts.renderSvcId})? This means there is something incorrect in logic in the code. (E: fbdde2ae97f973ba3bcf34edc39e9425)`);\n    }\n\n    return renderSvc;\n}\n\n// #region test functions\n\nfunction testGetCanvas(): HTMLCanvasElement {\n    // Get the body element\n    const body = document.querySelector('body')!;\n\n    // Create the canvas element if it doesn't exist\n    let canvas = document.querySelector('canvas') as HTMLCanvasElement | null;\n    if (!canvas) {\n        canvas = document.createElement('canvas');\n        body.appendChild(canvas);\n        canvas.style.width = '100%';\n        canvas.style.height = '100%';\n        canvas.width = canvas.offsetWidth;\n        canvas.height = canvas.offsetHeight;\n    }\n    return canvas;\n}\n\nexport async function testRendering() {\n    const lc = `[${testRendering.name}]`;\n    // const canvasEl = testGetCanvas();\n    // const canvasEl = undefined;\n    // const renderService = getRenderService({ canvasEl, forceNew: true }); // Use the factory\n    // await renderService.initialized;\n    const renderService = new RenderService_V1({ canvasEl: undefined }); // Use the factory\n    const { renderSvcId } = renderService;\n\n    const canvasHandle = renderService.getCanvasHandle();\n    console.log(`${lc} Canvas Handle: ${pretty(canvasHandle)} (I: 4ddb17bbbb1f783c16290f91269ed724)`);\n\n    const rectState: RenderableState = {\n        isVisible: true,\n        color: { r: 1, g: 0, b: 0, a: 1 }, // Red\n        position: { x: 50, y: 50, z: 0 },\n        scale: { x: 1, y: 1 },\n        geometry: {\n            type: 'rect',\n            parameters: {\n                width: 100,\n                height: 50,\n            } satisfies GeometryParametersRect,\n        },\n    };\n\n    const textState: RenderableState = {\n        isVisible: true,\n        color: { r: 0, g: 0, b: 1, a: 1 }, // Blue\n        position: { x: 75, y: 150, z: 0 },\n        scale: { x: 1, y: 1 },\n        geometry: {\n            type: 'text',\n            parameters: {\n                text: 'Hello World',\n                fontFamily: 'Arial',\n                fontSize: 24,\n            } satisfies GeometryParametersText,\n        },\n    };\n\n    const rectHandle = await renderService.renderableCreate({ renderSvcId, initialState: rectState });\n    const textHandle = await renderService.renderableCreate({ renderSvcId, initialState: textState });\n\n    renderService.render();\n}\n\nexport async function testReRendering() {\n    const canvasEl = testGetCanvas();\n    // const renderService = getRenderService({ canvasEl, forceNew: true }); // Use the factory\n    const renderService = new RenderService_V1({ canvasEl, });\n    const { renderSvcId } = renderService;\n    await renderService.initialized;\n\n    const rectState: RenderableState = {\n        isVisible: true,\n        color: { r: 1, g: 0, b: 0, a: 1 }, // Red\n        position: { x: 50, y: 50, z: 0 },\n        scale: { x: 1, y: 1 },\n        geometry: {\n            type: 'rect',\n            parameters: {\n                width: 100,\n                height: 50,\n            } satisfies GeometryParametersRect,\n        },\n    };\n\n    const textState: RenderableState = {\n        isVisible: true,\n        color: { r: 0, g: 0, b: 1, a: 1 }, // Blue\n        position: { x: 75, y: 150, z: 0 },\n        scale: { x: 1, y: 1 },\n        geometry: {\n            type: 'text',\n            parameters: {\n                text: '(Re)Hello World',\n                fontFamily: 'Arial',\n                fontSize: 24,\n            } satisfies GeometryParametersText,\n        },\n    };\n\n    const rectHandle = (await renderService.renderableCreate({ renderSvcId, initialState: rectState })).handle as RenderableHandle; // Explicit cast\n    const textHandle = (await renderService.renderableCreate({ renderSvcId, initialState: textState })).handle as RenderableHandle; // Explicit cast\n\n    renderService.render();\n\n    // Wait for 2 seconds\n    await new Promise(resolve => setTimeout(resolve, 2000));\n\n    // Update the rectangle's state\n    const updatedRectState: Partial<RenderableState> = {\n        position: { x: 150, y: 75, z: 0 },\n        color: { r: 0, g: 1, b: 0, a: 1 }, // Green\n    };\n\n    await renderService.renderableUpdate({\n        renderSvcId,\n        targets: [{ handle: rectHandle, updatedState: updatedRectState }],\n    });\n\n    // Re-render\n    renderService.render();\n}\n\nexport async function testRenderableDestroy() {\n    const canvasEl = testGetCanvas();\n    // const renderService = getRenderService({ canvasEl, forceNew: true }); // Use the factory\n    const renderService = new RenderService_V1({ canvasEl, }); // Use the factory\n    const { renderSvcId } = renderService;\n    await renderService.initialized;\n\n    const rectState1: RenderableState = {\n        isVisible: true,\n        color: { r: 1, g: 0, b: 0, a: 1 }, // Red\n        position: { x: 50, y: 50, z: 0 },\n        scale: { x: 1, y: 1 },\n        geometry: {\n            type: 'rect',\n            parameters: {\n                width: 50,\n                height: 50,\n            } satisfies GeometryParametersRect,\n        },\n    };\n\n    const rectState2: RenderableState = {\n        isVisible: true,\n        color: { r: 0, g: 1, b: 0, a: 1 }, // Green\n        position: { x: 150, y: 50, z: 0 },\n        scale: { x: 1, y: 1 },\n        geometry: {\n            type: 'rect',\n            parameters: {\n                width: 50,\n                height: 50,\n            } satisfies GeometryParametersRect,\n        },\n    };\n\n    const textState: RenderableState = {\n        isVisible: true,\n        color: { r: 0, g: 0, b: 1, a: 1 }, // Blue\n        position: { x: 100, y: 150, z: 0 },\n        scale: { x: 1, y: 1 },\n        geometry: {\n            type: 'text',\n            parameters: {\n                text: 'To be destroyed',\n                fontFamily: 'Arial',\n                fontSize: 16,\n            } satisfies GeometryParametersText,\n        },\n    };\n\n    const rectHandle1 = (await renderService.renderableCreate({ renderSvcId, initialState: rectState1 })).handle as RenderableHandle;\n    const rectHandle2 = (await renderService.renderableCreate({ renderSvcId, initialState: rectState2 })).handle as RenderableHandle;\n    const textHandle = (await renderService.renderableCreate({ renderSvcId, initialState: textState })).handle as RenderableHandle;\n\n    renderService.render();\n\n    // Wait for 2 seconds\n    await new Promise(resolve => setTimeout(resolve, 2000));\n\n    // Destroy the text renderable\n    await renderService.renderableDestroy({ renderSvcId, handles: [textHandle] });\n\n    // Re-render\n    renderService.render();\n}\n\n// #endregion test functions\n", "import { ColorRGBA } from \"../../../../render/render-types.mjs\";\n\n// #region PathCommandType enum\n/**\n * discriminator property for which concrete type a command part is.\n */\nexport type PathCommandType =\n    | 'beginPath' | 'line' | 'arc' | 'bezierCurve' | 'quadraticBezierCurve'\n    | 'moveTo' | 'closePath' | 'stroke' | 'fill';\nexport const PathCommandType = {\n    beginPath: 'beginPath' satisfies PathCommandType,\n    line: 'line' satisfies PathCommandType,\n    arc: 'arc' satisfies PathCommandType,\n    bezierCurve: 'bezierCurve' satisfies PathCommandType,\n    quadraticBezierCurve: 'quadraticBezierCurve' satisfies PathCommandType,\n    moveTo: 'moveTo' satisfies PathCommandType,\n    closePath: 'closePath' satisfies PathCommandType,\n    stroke: 'stroke' satisfies PathCommandType,\n    fill: 'fill' satisfies PathCommandType,\n} satisfies { [key: string]: PathCommandType };\nexport const PATH_COMMAND_TYPE_VALUES = Object.values(PathCommandType);\n// #endregion PathCommandType enum\n\n/**\n * @interface PathCommand - \"Super object\" interface for all path commands as\n * opposed to a parent class/interface that is descended from. The\n *\n * ## notes on design decision\n *\n * These concrete classes are defined as optional in this \"super command\" class\n * instead of inheriting with a `type` discriminator because discriminated union\n * types do not do well in gemini function calling API schemas. The OpenAPI\n * schemas supported are only a subset of the full OpenAPI spec.\n *\n * It is possible that a model will fill in more than one of these concrete\n * members even though the instructions say to only do one at a time, but in my\n * initial testing this is not the case.\n */\nexport interface PathCommand {\n    type: PathCommandType;\n    beginPath?: BeginPathPathCommand;\n    line?: LinePathCommand;\n    arc?: ArcPathCommand;\n    bezierCurve?: BezierCurvePathCommand;\n    quadraticBezierCurve?: QuadraticBezierCurvePathCommand;\n    moveTo?: MoveToPathCommand;\n    closePath?: ClosePathPathCommand;\n    stroke?: StrokePathCommand;\n    fill?: FillPathCommand;\n}\n\n/**\n * @interface ConcretePathCommandInfo - Represents a concrete path command which\n * will populate the {@link PathCommand} \"super command\".\n *\n * It is slightly annoying to fudge with the architecture here, but the LLM just\n * has deficits regarding the OpenAPI schema subset currently implemented.\n */\nexport interface ConcretePathCommandInfo {\n    type: PathCommandType;\n}\n\n/**\n * @interface BeginPathPathCommand - Represents a beginPath command.\n * @extends ConcretePathCommandInfo\n */\nexport interface BeginPathPathCommand extends ConcretePathCommandInfo {\n    type: 'beginPath';\n    /**\n     * boolean property to match schema for gemini model\n     */\n    beginPath: true;\n}\n\n/**\n * @interface LinePathCommand - Represents a line segment command.\n * @extends ConcretePathCommandInfo\n */\nexport interface LinePathCommand extends ConcretePathCommandInfo {\n    type: 'line';\n    x1?: number;\n    y1?: number;\n    x2: number;\n    y2: number;\n}\n\n/**\n * @interface ArcPathCommand - Represents an arc segment command.\n * @extends ConcretePathCommandInfo\n */\nexport interface ArcPathCommand extends ConcretePathCommandInfo {\n    type: 'arc';\n    x: number;         // x-coordinate of the arc's center\n    y: number;         // y-coordinate of the arc's center\n    radius: number;    // arc's radius\n    startAngle: number; // starting angle in radians\n    endAngle: number;   // ending angle in radians\n    anticlockwise?: boolean; // optional: direction of arc (default: clockwise)\n}\n\n/**\n * @interface BezierCurvePathCommand - Represents a bezier curve segment command (cubic bezier curve).\n * @extends ConcretePathCommandInfo\n */\nexport interface BezierCurvePathCommand extends ConcretePathCommandInfo {\n    type: 'bezierCurve';\n    cp1x: number;\n    cp1y: number;\n    cp2x: number;\n    cp2y: number;\n    x1?: number;\n    y1?: number;\n    x2: number;\n    y2: number;\n}\n\n/**\n * @interface QuadraticBezierCurvePathCommand - Represents a quadratic bezier curve segment path command.\n * @extends ConcretePathCommandInfo\n */\nexport interface QuadraticBezierCurvePathCommand extends ConcretePathCommandInfo {\n    type: 'quadraticBezierCurve';\n    cpx: number;\n    cpy: number;\n    x1?: number;\n    y1?: number;\n    x2: number;\n    y2: number;\n}\n\n/**\n * @interface MoveToPathCommand - Represents a moveTo command.\n * @extends ConcretePathCommandInfo\n */\nexport interface MoveToPathCommand extends ConcretePathCommandInfo {\n    type: 'moveTo';\n    x: number;\n    y: number;\n}\n\n/**\n * @interface ClosePathPathCommand - Represents a closePath command.\n * @extends ConcretePathCommandInfo\n */\nexport interface ClosePathPathCommand extends ConcretePathCommandInfo {\n    type: 'closePath';\n    /**\n     * boolean property to match schema for gemini model\n     */\n    closePath: true;\n}\n\n/**\n * @interface StrokePathCommand - Represents a stroke command. If provided, the\n * color/width style will be set before the stroke() call, and returned to the\n * default for the renderable.\n * @extends ConcretePathCommandInfo\n */\nexport interface StrokePathCommand extends ConcretePathCommandInfo {\n    type: 'stroke';\n    color?: ColorRGBA;\n    width?: number;\n    // stroke: true; // boolean property for stroke (to match schema)\n}\n\n/**\n * @interface FillPathCommand - Represents a fill command.\n * @extends ConcretePathCommandInfo\n */\nexport interface FillPathCommand extends ConcretePathCommandInfo {\n    type: 'fill';\n    fill: true;   // boolean property for fill (to match schema)\n}\n", "import type { RenderableHandle, GeometryParametersPath } from \"../../../render/render-types.mjs\";\nimport { PATH_COMMAND_TYPE_VALUES } from \"./path-command/path-command-types.mjs\";\n\nexport const GEMINI_SCHEMA_RENDERABLE_SVC_ID = {\n    type: 'string',\n    description: 'Id for the render service. Each canvas is tied to a render service. There can be more than one canvas associated with the same render service, but there can only be one render service for each canvas. If you are working with more than one canvas, be sure to keep track of which render service is associated with which canvas.',\n} as const;\n\n/**\n * OpenAPI schema object for use with Gemini.\n *\n * @see {@link RenderableHandle}\n */\nexport const GEMINI_SCHEMA_RENDERABLE_HANDLE = {\n    type: 'object',\n    description: 'The identifying handle of the renderable.',\n    properties: {\n        uuid: { type: 'string', description: 'UUID for renderable handle. This uniquely identifies the renderable.' },\n        type: { type: 'string', description: 'Type for renderable handle. Must be the string: \"Renderable\".' },\n    },\n    required: ['uuid',],\n} as const;\n\n/**\n * OpenAPI schema object for use with Gemini.\n *\n * @see {@link RenderableHandle}\n */\nexport const GEMINI_SCHEMA_RENDERABLE_HANDLES = {\n    type: 'array',\n    description: 'list of handles',\n    items: GEMINI_SCHEMA_RENDERABLE_HANDLE,\n} as const;\n\nexport const GEMINI_SCHEMA_RENDERABLE_COLOR = { // <--- NOTE: updatedColor, not updatedState\n    type: 'object',\n    description: 'Renderable color in RGBA format.',\n    properties: {\n        r: { type: 'number', format: 'float', description: 'RGBA red component (0-1)' },\n        g: { type: 'number', format: 'float', description: 'RGBA green component (0-1)' },\n        b: { type: 'number', format: 'float', description: 'RGBA blue component (0-1)' },\n        a: { type: 'number', format: 'float', description: 'RGBA alpha component (0-1)' },\n    },\n    required: ['r', 'g', 'b', 'a'], // Color components are required for this function\n} as const;\n\nexport const GEMINI_SCHEMA_RENDERABLE_POSITION = {\n    type: 'object',\n    description: 'Position of the renderable.',\n    properties: {\n        x: { type: 'number', description: 'x-coordinate (horizontal position)' },\n        y: { type: 'number', description: 'y-coordinate (vertical position)' },\n        z: { type: 'number', description: 'ATOW z-index/depth since we are working in 2d (ATOW, not really used). Just use 0 for now.' },\n    },\n    required: ['x', 'y', 'z'],\n} as const;\n\nexport const GEMINI_SCHEMA_RENDERABLE_SCALE = {\n    type: 'object',\n    description: 'The scale/size of the renderable.',\n    properties: {\n        x: { type: 'number', description: 'scale factor in x dimension (horizontal in 2d)' },\n        y: { type: 'number', description: 'scale factor in y dimension (vertical in 2d)' },\n    },\n    required: ['x', 'y'],\n} as const;\n\nexport const GEMINI_SCHEMA_RENDERABLE_ISVISIBLE = {\n    type: 'boolean',\n    description: 'Indicates whether the renderable is visible or hidden.',\n} as const;\n\nexport const GEMINI_SCHEMA_RENDERABLE_RECURSIVE = {\n    type: 'boolean',\n    description: 'If true, the operation will apply recursively to the children. If falsy, the operation will only apply to the target. Only applicable to group renderables.',\n} as const;\n\nexport const GEMINI_SCHEMA_RENDERABLE_TEXT_TEXT = {\n    type: 'string',\n    description: 'Text content for TEXT renderables only.',\n};\n\nexport const GEMINI_SCHEMA_RENDERABLE_TEXT_FONTFAMILY = {\n    type: 'string',\n    description: 'Font family for TEXT renderables only.',\n};\nexport const GEMINI_SCHEMA_RENDERABLE_TEXT_FONTSIZE = {\n    type: 'number',\n    description: 'Font size for TEXT renderables only.',\n};\n\nexport const GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_TEXT = {\n    type: 'object',\n    description: 'The definition of a text renderable.',\n    properties: {\n        text: GEMINI_SCHEMA_RENDERABLE_TEXT_TEXT,\n        fontFamily: GEMINI_SCHEMA_RENDERABLE_TEXT_FONTFAMILY,\n        fontSize: GEMINI_SCHEMA_RENDERABLE_TEXT_FONTSIZE,\n    },\n    required: ['text', 'fontFamily', 'fontSize'],\n};\nexport const GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_GROUP = {\n    type: 'object',\n    description: 'The definition of a group renderable.',\n    properties: {\n        members: GEMINI_SCHEMA_RENDERABLE_HANDLES,\n    },\n    required: ['members'],\n};\n\nexport const GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_RECT = {\n    type: 'object',\n    description: 'Geometry details specifically for rect renderables.',\n    properties: {\n        width: { type: 'number', description: 'Width of the rectangle.' },\n        height: { type: 'number', description: 'Height of the rectangle.' },\n    },\n    required: ['width', 'height'],\n};\n\n// #region Path command related\n\nconst XY_COORD_IF_TRUTHY_NOTE = `If truthy, in the current HTML Canvas implementation, this will generate a moveTo to this coordinate.`;\n\nconst GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_PATH_COMMANDTYPE = {\n    type: 'string',\n    enum: PATH_COMMAND_TYPE_VALUES.concat(),\n    description: `Note that the command type is doubled: once in the \"super\" command object and once in the \"concrete\" command object (if the concrete command object has actual state. boolean commands like beginPath are just boolean and don't have this.)`\n}\n\n/**\n * OpenAPI schema object for Gemini's function calling, for beginPath command geometry parameters in paths.\n *\n * @see {@link BeginPathCommand}\n */\nexport const GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_PATH_BEGINPATH = { // NEW - beginPath command schema\n    type: 'boolean',\n    description: 'If true, begins a new path. Typically used to start a new subpath within a larger path. The very first command in a path must be a beginPath command.',\n} as const;\n\n/**\n * OpenAPI schema object for Gemini's function calling, for line command geometry parameters in paths.\n *\n * @see {@link LinePathCommand}\n */\nexport const GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_PATH_LINE = {\n    type: 'object',\n    description: 'Parameters for a line segment path command. If x1,y1 are provided, a moveTo will be generated to this position before executing the lineTo to x2,y2.',\n    properties: {\n        // type: GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_PATH_COMMANDTYPE,\n        x1: { type: 'number', description: `x-coordinate of the starting point of the line. ${XY_COORD_IF_TRUTHY_NOTE}` },\n        y1: { type: 'number', description: `y-coordinate of the starting point of the line. If truthy, in the current HTML Canvas implementation, this will generate a moveTo to this coordinate.` },\n        x2: { type: 'number', description: `x-coordinate of the ending point of the line. In the current HTML Canvas implementation, this will generate a lineTo to this coordinate.` },\n        y2: { type: 'number', description: `y-coordinate of the ending point of the line. In the current HTML Canvas implementation, this will generate a lineTo to this coordinate` },\n    },\n    required: ['x2', 'y2'],\n} as const;\n\n/**\n * OpenAPI schema object for Gemini's function calling, for arc command geometry parameters in paths.\n *\n * @see {@link ArcPathCommand}\n */\nexport const GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_PATH_ARC = {\n    type: 'object',\n    description: 'Parameters for an arc segment path command.',\n    properties: {\n        type: GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_PATH_COMMANDTYPE,\n        x: { type: 'number', description: 'x-coordinate of the arc\\'s center.' },\n        y: { type: 'number', description: 'y-coordinate of the arc\\'s center.' },\n        radius: { type: 'number', description: 'Arc\\'s radius.' },\n        startAngle: { type: 'number', format: 'float', description: 'Starting angle of the arc in radians.' },\n        endAngle: { type: 'number', format: 'float', description: 'Ending angle of the arc in radians.' },\n        anticlockwise: { type: 'boolean', description: 'Optional. Specifies if the arc should be drawn anticlockwise. Defaults to clockwise (false).' },\n    },\n    required: ['x', 'y', 'radius', 'startAngle', 'endAngle'],\n} as const;\n\n/**\n * OpenAPI schema object for Gemini's function calling, for bezier curve command geometry parameters in paths.\n *\n * @see {@link BezierCurvePathCommand}\n */\nexport const GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_PATH_BEZIERCURVE = {\n    type: 'object',\n    description: 'Parameters for a bezier curve segment path command (cubic bezier curve).',\n    properties: {\n        // type: GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_PATH_COMMANDTYPE,\n        cp1x: { type: 'number', description: 'x-coordinate of the first control point.' },\n        cp1y: { type: 'number', description: 'y-coordinate of the first control point.' },\n        cp2x: { type: 'number', description: 'x-coordinate of the second control point.' },\n        cp2y: { type: 'number', description: 'y-coordinate of the second control point.' },\n        x1: { type: 'number', description: `x-coordinate of the starting point. ${XY_COORD_IF_TRUTHY_NOTE}` },\n        y1: { type: 'number', description: `y-coordinate of the starting point. ${XY_COORD_IF_TRUTHY_NOTE}` },\n        x2: { type: 'number', description: 'x-coordinate of the ending point (anchor).' },\n        y2: { type: 'number', description: 'y-coordinate of the ending point (anchor).' },\n    },\n    required: ['cp1x', 'cp1y', 'cp2x', 'cp2y', 'x2', 'y2'],\n} as const;\n\n/**\n * OpenAPI schema object for Gemini's function calling, for quadratic bezier curve command geometry parameters in paths.\n *\n * @see {@link QuadraticBezierCurveCommand}\n */\nexport const GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_PATH_QUADRATICBEZIERCURVE = {\n    type: 'object',\n    description: 'Parameters for a quadratic bezier curve segment path command.',\n    properties: {\n        // type: GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_PATH_COMMANDTYPE,\n        cpx: { type: 'number', description: 'x-coordinate of the control point.' },\n        cpy: { type: 'number', description: 'y-coordinate of the control point.' },\n        x1: { type: 'number', description: `x-coordinate of the starting point. ${XY_COORD_IF_TRUTHY_NOTE}` },\n        y1: { type: 'number', description: `y-coordinate of the starting point. ${XY_COORD_IF_TRUTHY_NOTE}` },\n        x2: { type: 'number', description: 'x-coordinate of the ending point (anchor).' },\n        y2: { type: 'number', description: 'y-coordinate of the ending point (anchor).' },\n    },\n    required: ['cpx', 'cpy', 'x2', 'y2'],\n} as const;\n\n/**\n * OpenAPI schema object for Gemini's function calling, for moveTo command geometry parameters in paths.\n *\n * @see {@link MoveToPathCommand}\n */\nexport const GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_PATH_MOVETO = {\n    type: 'object',\n    description: `Parameters for a moveTo path command (just moves the cursor, doesn't draw anything).`,\n    properties: {\n        x: { type: 'number', description: `x-coordinate of the cursor's new position.` },\n        y: { type: 'number', description: `y-coordinate of the cursor's new position.` },\n    },\n    required: ['x', 'y'],\n} as const;\n\n/**\n * OpenAPI schema object for Gemini's function calling, for closePath command geometry parameters in paths.\n *\n * @see {@link ClosePathPathCommand}\n */\nexport const GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_PATH_CLOSEPATH = {\n    type: 'boolean',\n    description: `If true, closes the current path subpath by drawing a straight line back to the subpath's starting point.`,\n} as const;\n/**\n * OpenAPI schema object for Gemini's function calling, for stroke command geometry parameters in paths.\n *\n * @see {@link StrokePathCommand}\n */\nexport const GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_PATH_STROKE = {\n    type: 'object',\n    description: `Closes the current path subpath by a stroke() call. Can optionally set overriding stroke color and width.`,\n    properties: {\n        color: GEMINI_SCHEMA_RENDERABLE_COLOR,\n        width: { type: 'number', description: 'Stroke width.' },\n    },\n    required: [],\n} as const;\n// export const GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_PATH_STROKE = {\n//     type: 'boolean',\n//     description: `If true, closes the current path subpath by a stroke() call.`,\n// } as const;\n\n/**\n * OpenAPI schema object for Gemini's function calling, for stroke command geometry parameters in paths.\n *\n * @see {@link FillPathCommand}\n */\nexport const GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_PATH_FILL = {\n    type: 'boolean',\n    description: `If true, closes the current path subpath by a fill() call.`,\n} as const;\n\n/**\n * This is a single *part* of a path geometry commands.\n *\n * @see {@link GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_PATH}\n * @see {@link GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_PATH_COMMANDS}\n */\nexport const GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_PATH_ITEM = {\n    type: 'object',\n    description: 'Details for a single *part* of a path geometry.',\n    properties: {\n        type: GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_PATH_COMMANDTYPE,\n        beginPath: GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_PATH_BEGINPATH,\n        line: GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_PATH_LINE,\n        arc: GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_PATH_ARC,\n        bezierCurve: GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_PATH_BEZIERCURVE,\n        quadraticBezierCurve: GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_PATH_QUADRATICBEZIERCURVE,\n        moveTo: GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_PATH_MOVETO,\n        closePath: GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_PATH_CLOSEPATH,\n        stroke: GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_PATH_STROKE,\n        fill: GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_PATH_FILL,\n    },\n    required: ['type'],\n} as const;\n\n/**\n * Schema of the {@link GeometryParametersPath.commands}.\n *\n *\n * This is used in {@link GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_PATH}\n *\n */\nexport const GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_PATH_COMMANDS = {\n    type: 'array',\n    description: `Ordered list of commands for the path. Each individual item should be a command with a single 'type' and a single property set, e.g. 'line' OR 'arc' but not both.`,\n    items: GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_PATH_ITEM,\n} as const;\n\n/**\n * Schema of the full Path geometry.\n */\nexport const GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_PATH = {\n    type: 'object',\n    description: `Geometry of a fully defined canvas path, i.e. a list of canvas command infos. You can make compound/complex paths by combining multiple commands in this array.`,\n    properties: {\n        commands: GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_PATH_COMMANDS,\n    },\n    required: ['commands'],\n} as const;\n\n// #endregion Path command related\n\n\nexport const GEMINI_SCHEMA_RENDERABLE_GEOMETRY_RECT = {\n    type: 'object',\n    description: 'The geometry definition of the renderable.',\n    properties: {\n        type: { type: 'string', enum: ['rect'] },\n        parameters: GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_RECT,\n    },\n    required: ['type', 'parameters'],\n};\nexport const GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PATH = {\n    type: 'object',\n    description: 'The geometry definition of the renderable.',\n    properties: {\n        type: { type: 'string', enum: ['path'] },\n        parameters: GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_PATH,\n    },\n    required: ['type', 'parameters'],\n};\n\nexport const GEMINI_SCHEMA_RENDERABLE_GEOMETRY_TEXT = {\n    type: 'object',\n    description: 'The geometry definition of a text renderable.',\n    properties: {\n        type: { type: 'string', enum: ['text'] },\n        parameters: GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_TEXT,\n    },\n    required: ['type', 'parameters'],\n};\n\nexport const GEMINI_SCHEMA_RENDERABLE_GEOMETRY_GROUP = {\n    type: 'object',\n    description: 'The geometry definition of a group renderable.',\n    properties: {\n        type: { type: 'string', enum: ['group'] },\n        parameters: GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_GROUP,\n    },\n    required: ['type', 'parameters'],\n};\n", "import { pretty } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { APIFunctionInfo } from \"@ibgib/web-gib/dist/api/api-types.mjs\";\nimport { COMMAND_BASE_SCHEMA_PROPERTIES } from \"@ibgib/web-gib/dist/api/commands/command-constants.mjs\";\nimport { getCommandService } from \"@ibgib/web-gib/dist/api/commands/command-service-v1.mjs\";\nimport { FUNCTION_CALL_EXAMPLES_HEADER } from \"@ibgib/web-gib/dist/api/api-constants.mjs\";\nimport { tweakGeminiSchema } from \"@ibgib/web-gib/dist/api/commands/command-helpers.mjs\";\n\nimport { RENDERABLE_HANDLE_TYPE, RenderableShape, } from \"../../../render/render-constants.mjs\";\nimport {\n    GeometryParametersGroup, GeometryParametersPath, GeometryParametersRect,\n    GeometryParametersText, RenderableCreateResult, RenderableHandle,\n    RenderableState,\n} from \"../../../render/render-types.mjs\";\nimport { getRenderService, } from \"../../../render/render-service-v1.mjs\";\nimport { GEMINI_SCHEMA_RENDERABLE_COLOR, GEMINI_SCHEMA_RENDERABLE_GEOMETRY_GROUP, GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PATH, GEMINI_SCHEMA_RENDERABLE_GEOMETRY_RECT, GEMINI_SCHEMA_RENDERABLE_GEOMETRY_TEXT, GEMINI_SCHEMA_RENDERABLE_ISVISIBLE, GEMINI_SCHEMA_RENDERABLE_POSITION, GEMINI_SCHEMA_RENDERABLE_SCALE, GEMINI_SCHEMA_RENDERABLE_SVC_ID } from \"./renderable-constants.mjs\";\nimport { RenderableCommandDataBase } from \"./renderable-types.mjs\";\n\n\n// #region constants\nconst EXAMPLE_INPUT_RENDERABLE_CREATERECTS: Partial<RenderableCreateCommandData> = {\n    notesToSelf: 'Example of renderableCreateRects function call to create multiple rects in one shot.',\n    initialStates: [\n        {\n            isVisible: true,\n            color: { r: 1, g: 0, b: 0, a: 1 }, // Red\n            position: { x: 50, y: 50, z: 0 },\n            scale: { x: 1, y: 1 },\n            geometry: {\n                type: RenderableShape.RECTANGLE,\n                parameters: {\n                    width: 50,\n                    height: 50,\n                } satisfies GeometryParametersRect,\n            },\n        },\n        {\n            isVisible: true,\n            color: { r: 0, g: 1, b: 0, a: 1 }, // Green\n            position: { x: 150, y: 50, z: 0 },\n            scale: { x: 1, y: 1 },\n            geometry: {\n                type: RenderableShape.RECTANGLE,\n                parameters: {\n                    width: 50,\n                    height: 50,\n                } satisfies GeometryParametersRect,\n            },\n        },\n    ],\n    repromptWithResult: false,\n};\nconst EXAMPLE_INPUT_RENDERABLE_CREATEPATHS: Partial<RenderableCreateCommandData> = {\n    notesToSelf: 'Example of renderableCreatePaths function call to create multiple paths in one shot. The first example includes a line command that provides the optional x1,y1 coordinates. This will auto-generate a moveTo command before a lineTo in the HTML Canvas. The second example manually includes the moveTo before a line command that omits the x1,y1 coordinates.',\n    initialStates: [\n        {\n            isVisible: true,\n            color: { r: 1, g: 0, b: 0, a: 1 }, // Red\n            position: { x: 50, y: 50, z: 0 },\n            scale: { x: 1, y: 1 },\n            geometry: {\n                type: RenderableShape.PATH,\n                parameters: {\n                    commands: [\n                        {\n                            type: 'beginPath',\n                            beginPath: { type: 'beginPath', beginPath: true },\n                        },\n                        {\n                            type: 'line',\n                            line: { type: 'line', x1: 10, y1: 105, x2: 15, y2: 200 },\n                        },\n                        {\n                            type: 'stroke',\n                            stroke: { type: 'stroke', color: { r: 0, g: 1, b: 0, a: 1 }, width: 5 },\n                        },\n                        {\n                            type: 'beginPath',\n                            beginPath: { type: 'beginPath', beginPath: true },\n                        },\n                    ],\n                } satisfies GeometryParametersPath,\n            },\n        },\n        {\n            isVisible: true,\n            color: { r: 0, g: 1, b: 0, a: 1 }, // Green\n            position: { x: 150, y: 50, z: 0 },\n            scale: { x: 1, y: 1 },\n            geometry: {\n                type: RenderableShape.PATH,\n                parameters: {\n                    // todo: fill out path geometry parameters example\n                    commands: [\n                        {\n                            type: 'beginPath',\n                            beginPath: { type: 'beginPath', beginPath: true },\n                        },\n                        {\n                            type: 'moveTo',\n                            moveTo: { type: 'moveTo', x: 500, y: 500 },\n                        },\n                        {\n                            type: 'line',\n                            line: { type: 'line', x2: 600, y2: 600 },\n                        },\n                        {\n                            type: 'stroke',\n                            stroke: { type: 'stroke', width: 15 },\n                        },\n                        {\n                            type: 'beginPath',\n                            beginPath: { type: 'beginPath', beginPath: true },\n                        },\n                        {\n                            type: 'moveTo',\n                            moveTo: { type: 'moveTo', x: 250, y: 250 },\n                        },\n                        {\n                            type: 'line',\n                            line: { type: 'line', x2: 275, y2: 300 },\n                        },\n                        {\n                            type: 'bezierCurve',\n                            bezierCurve: { type: 'bezierCurve', cp1x: 230, cp1y: 30, cp2x: 150, cp2y: 80, x2: 50, y2: 50 },\n                        },\n                        {\n                            type: 'closePath',\n                            closePath: { type: 'closePath', closePath: true },\n                        },\n                    ],\n                } satisfies GeometryParametersPath,\n            },\n        },\n    ],\n    repromptWithResult: false,\n};\nconst EXAMPLE_INPUT_RENDERABLE_CREATETEXTS: Partial<RenderableCreateCommandData> = {\n    notesToSelf: 'Example of renderableCreateTexts function call to create multiple texts (labels, message) in one shot.',\n    initialStates: [\n        {\n            isVisible: true,\n            color: { r: 1, g: 0, b: 0, a: 1 }, // Red\n            position: { x: 50, y: 50, z: 0 },\n            scale: { x: 1, y: 1 },\n            geometry: {\n                type: RenderableShape.TEXT,\n                parameters: {\n                    fontSize: 10,\n                    fontFamily: 'Arial',\n                    text: 'Hello World!',\n                } satisfies GeometryParametersText,\n            },\n        },\n        {\n            isVisible: true,\n            color: { r: 0, g: 1, b: 0, a: 1 }, // Green\n            position: { x: 150, y: 50, z: 0 },\n            scale: { x: 1, y: 1 },\n            geometry: {\n                type: RenderableShape.TEXT,\n                parameters: {\n                    fontSize: 10,\n                    fontFamily: 'Arial',\n                    text: 'Hello World!',\n                } satisfies GeometryParametersText,\n            },\n        },\n    ],\n    repromptWithResult: false,\n};\n\nconst EXAMPLE_INPUT_RENDERABLE_CREATEGROUP: Partial<RenderableCreateCommandData> = {\n    notesToSelf: 'Example of initialStates to create a group.',\n    initialStates: [\n        {\n            isVisible: true,\n            color: { r: 1, g: 0, b: 0, a: 1 }, // Red\n            position: { x: 25, y: 25, z: 0 },\n            scale: { x: 1, y: 1 },\n            geometry: {\n                type: RenderableShape.GROUP,\n                parameters: {\n                    members: [\n                        {\n                            type: RENDERABLE_HANDLE_TYPE,\n                            uuid: 'someUUID111',\n                        },\n                        {\n                            type: RENDERABLE_HANDLE_TYPE,\n                            uuid: 'someUUID222',\n                        },\n                    ],\n                } satisfies GeometryParametersGroup,\n            },\n        },\n    ],\n    repromptWithResult: true,\n};\n\nconst EXAMPLES_RECT = [\n    FUNCTION_CALL_EXAMPLES_HEADER,\n    pretty(EXAMPLE_INPUT_RENDERABLE_CREATERECTS),\n].join('\\n');\nconst EXAMPLES_PATH = [\n    FUNCTION_CALL_EXAMPLES_HEADER,\n    pretty(EXAMPLE_INPUT_RENDERABLE_CREATEPATHS),\n].join('\\n');\nconst EXAMPLES_TEXT = [\n    FUNCTION_CALL_EXAMPLES_HEADER,\n    pretty(EXAMPLE_INPUT_RENDERABLE_CREATETEXTS),\n].join('\\n');\nconst EXAMPLES_GROUP = [\n    FUNCTION_CALL_EXAMPLES_HEADER,\n    pretty(EXAMPLE_INPUT_RENDERABLE_CREATEGROUP),\n].join('\\n');\n// #endregion constants\n\n\n/**\n * @interface RenderableCreateOpts - Options for the renderableCreate command.\n * @extends RenderableCommandDataBase\n */\nexport interface RenderableCreateOpts extends RenderableCommandDataBase<['create']> {\n    /**\n     * @property initialStates - The initial states of the renderables to create.\n     */\n    initialStates: RenderableState[];\n}\n\n/**\n * @interface RenderableCreateCommandData - Command data for the renderableCreate command.\n * @extends RenderableCommandDataBase\n */\nexport interface RenderableCreateCommandData extends RenderableCommandDataBase<['create']> {\n    /**\n     * @property initialStates - The initial states of the renderables to create.\n     */\n    initialStates: RenderableState[];\n}\n\n/**\n * Wrapper function to enqueue the renderableCreate command.\n * @param {RenderableCreateOpts} opts - Options for creating the renderables.\n * @returns {Promise<RenderableHandle[]>} A promise that resolves with the handles to the newly created renderables.\n */\nfunction renderableCreateViaCmd(opts: RenderableCreateOpts): Promise<RenderableCreateResult[]> {\n    const commandService = getCommandService();\n    const command: RenderableCreateCommandData = {\n        renderSvcId: opts.renderSvcId,\n        cmd: 'renderable',\n        cmdModifiers: ['create'],\n        initialStates: opts.initialStates,\n        repromptWithResult: opts?.repromptWithResult,\n        notesToSelf: opts?.notesToSelf,\n    };\n    return new Promise<RenderableCreateResult[]>((resolve, reject) => {\n        commandService.enqueueCommand({ command, resolve, reject });\n    });\n}\n/**\n * Implementation function for the renderableCreate command.\n * @param {RenderableCreateOpts} opts - Options for creating the renderables.\n * @returns {Promise<RenderableHandle[]>} A promise that resolves with the handles to the newly created renderables.\n */\nasync function renderableCreateImpl(opts: RenderableCreateOpts): Promise<RenderableCreateResult[]> {\n    const renderService = getRenderService(opts);\n    const handles: RenderableHandle[] = [];\n    for (const initialState of opts.initialStates) {\n        const { handle } = await renderService.renderableCreate({\n            renderSvcId: opts.renderSvcId,\n            initialState,\n        });\n        handles.push(handle);\n    }\n    return handles.map(x => { return { renderSvcId: opts.renderSvcId, handle: x } });\n}\n\n/**\n * API function info for the renderableCreate command, but for rect renderables.\n */\nexport const renderableCreateRectsFunctionInfo: APIFunctionInfo<typeof renderableCreateViaCmd> = {\n    nameOrId: 'renderableCreateRects',\n    fnViaCmd: renderableCreateViaCmd,\n    functionImpl: renderableCreateImpl,\n    cmd: 'renderable',\n    cmdModifiers: ['create'],\n    schema: {\n        name: 'renderableCreateRects',\n        // description: `Creates one or more new rectangular renderable objects. This takes in an array of initial states.`,\n        description: `Creates one or more new rectangular renderable objects. This takes in an array of initial states.\\n\\n${EXAMPLES_RECT}`,\n        parameters: {\n            type: 'object',\n            properties: {\n                ...COMMAND_BASE_SCHEMA_PROPERTIES,\n                renderSvcId: GEMINI_SCHEMA_RENDERABLE_SVC_ID,\n                initialStates: {\n                    type: 'array',\n                    description: 'The initial states of the rect renderables to create. If you have multiple renderables to create, you can call this a single time with multiple initial states.',\n                    items: {\n                        type: 'object',\n                        description: 'The initial state of a single rect renderable.',\n                        properties: {\n                            isVisible: GEMINI_SCHEMA_RENDERABLE_ISVISIBLE,\n                            color: GEMINI_SCHEMA_RENDERABLE_COLOR,\n                            position: GEMINI_SCHEMA_RENDERABLE_POSITION,\n                            scale: GEMINI_SCHEMA_RENDERABLE_SCALE,\n                            geometry: GEMINI_SCHEMA_RENDERABLE_GEOMETRY_RECT,\n                        },\n                        required: ['isVisible', 'color', 'position', 'scale', 'geometry'],\n                    }\n                },\n            },\n            required: ['renderSvcId', 'initialStates'],\n        },\n    }\n};\n\n/**\n * API function info for the renderableCreate command, but for path renderables.\n */\nexport const renderableCreatePathsFunctionInfo: APIFunctionInfo<typeof renderableCreateViaCmd> = {\n    nameOrId: 'renderableCreatePaths',\n    fnViaCmd: renderableCreateViaCmd,\n    functionImpl: renderableCreateImpl,\n    cmd: 'renderable',\n    cmdModifiers: ['create'],\n    schema: {\n        name: 'renderableCreatePaths',\n        description: `Creates one or more new path renderable objects. This takes in an array of initial states.\\n\\n${EXAMPLES_PATH}`,\n        // description: `Creates one or more new path renderable objects. This takes in an array of initial states.`,\n        parameters: {\n            type: 'object',\n            properties: {\n                ...COMMAND_BASE_SCHEMA_PROPERTIES,\n                renderSvcId: GEMINI_SCHEMA_RENDERABLE_SVC_ID,\n                initialStates: {\n                    type: 'array',\n                    description: 'The initial states of the path renderables to create. If you have multiple renderables to create, you can call this a single time with multiple initial states.',\n                    items: {\n                        type: 'object',\n                        description: 'The initial state of a single path renderable.',\n                        properties: {\n                            isVisible: GEMINI_SCHEMA_RENDERABLE_ISVISIBLE,\n                            color: GEMINI_SCHEMA_RENDERABLE_COLOR,\n                            position: GEMINI_SCHEMA_RENDERABLE_POSITION,\n                            scale: GEMINI_SCHEMA_RENDERABLE_SCALE,\n                            geometry: GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PATH,\n                        },\n                        required: ['isVisible', 'color', 'position', 'scale', 'geometry'],\n                    }\n                },\n            },\n            required: ['renderSvcId', 'initialStates'],\n        },\n    }\n};\n\n/**\n * API function info for the renderableCreate command, but for text renderables.\n */\nexport const renderableCreateTextsFunctionInfo: APIFunctionInfo<typeof renderableCreateViaCmd> = {\n    nameOrId: 'renderableCreateTexts',\n    fnViaCmd: renderableCreateViaCmd,\n    functionImpl: renderableCreateImpl,\n    cmd: 'renderable',\n    cmdModifiers: ['create'],\n    schema: {\n        name: 'renderableCreateTexts',\n        description: `Creates one or more new text renderable objects. This takes in an array of initial states.\\n\\n${EXAMPLES_TEXT}`,\n        // description: `Creates one or more new text renderable objects. This takes in an array of initial states.`,\n        parameters: {\n            type: 'object',\n            properties: {\n                ...COMMAND_BASE_SCHEMA_PROPERTIES,\n                renderSvcId: GEMINI_SCHEMA_RENDERABLE_SVC_ID,\n                initialStates: {\n                    type: 'array',\n                    description: 'The initial states of the text renderables to create. If you have multiple renderables to create, you can call this a single time with multiple initial states.',\n                    items: {\n                        type: 'object',\n                        description: 'The initial state of a single text renderable.',\n                        properties: {\n                            isVisible: GEMINI_SCHEMA_RENDERABLE_ISVISIBLE,\n                            color: GEMINI_SCHEMA_RENDERABLE_COLOR,\n                            position: GEMINI_SCHEMA_RENDERABLE_POSITION,\n                            scale: GEMINI_SCHEMA_RENDERABLE_SCALE,\n                            geometry: GEMINI_SCHEMA_RENDERABLE_GEOMETRY_TEXT,\n                        },\n                        required: ['isVisible', 'color', 'position', 'scale', 'geometry'],\n                    }\n                },\n            },\n            required: ['initialStates'],\n        },\n    }\n};\n\n/**\n * API function info for the renderableCreate command, but for group renderables.\n */\nexport const renderableCreateGroupsFunctionInfo: APIFunctionInfo<typeof renderableCreateViaCmd> = {\n    nameOrId: 'renderableCreateGroups',\n    fnViaCmd: renderableCreateViaCmd,\n    functionImpl: renderableCreateImpl,\n    cmd: 'renderable',\n    cmdModifiers: ['create'],\n    schema: {\n        name: 'renderableCreateGroups',\n        description: `Creates one or more new group renderable objects. This takes in an array of initial states, though of course this can be of size one.\\n\\n${EXAMPLES_GROUP}`,\n        // description: `Creates one or more new group renderable objects. This takes in an array of initial states, though of course this can be of size one.`,\n        parameters: {\n            type: 'object',\n            properties: {\n                ...COMMAND_BASE_SCHEMA_PROPERTIES,\n                renderSvcId: GEMINI_SCHEMA_RENDERABLE_SVC_ID,\n                initialStates: {\n                    type: 'array',\n                    description: 'The initial states of the group renderables to create. If you have multiple groups to create, you can call this a single time with multiple initial states.',\n                    items: {\n                        type: 'object',\n                        description: 'The initial state of a single group renderable.',\n                        properties: {\n                            isVisible: GEMINI_SCHEMA_RENDERABLE_ISVISIBLE,\n                            color: GEMINI_SCHEMA_RENDERABLE_COLOR,\n                            position: GEMINI_SCHEMA_RENDERABLE_POSITION,\n                            scale: GEMINI_SCHEMA_RENDERABLE_SCALE,\n                            geometry: GEMINI_SCHEMA_RENDERABLE_GEOMETRY_GROUP,\n                        },\n                        required: ['isVisible', 'color', 'position', 'scale', 'geometry'],\n                    }\n                },\n            },\n            required: ['initialStates'],\n        },\n    }\n};\n", "import { clone, extractErrorMsg, pickRandom_Letters } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\n\nimport { GLOBAL_LOG_A_LOT } from \"../../constants.mjs\";\nimport { APIFunctionInfo } from \"../api-types.mjs\";\nimport { getCommandService } from \"./command-service-v1.mjs\";\nimport { CommandDataBase } from \"./command-types.mjs\";\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\n/**\n * customizing function to create the schema specific to some concrete schema\n * description/instructions.\n */\nexport function tweakGeminiSchema({\n    baseSchema,\n    addlDescription,\n}: {\n    /**\n     * starting schema which we will customize.\n     */\n    baseSchema: any,\n    /**\n     * additional description, to be used for concrete schema descriptions.\n     * If there is no description to begin with, this will simply set the\n     * description.\n     *\n     * For example, with destroy renderable, describe that this will recursively\n     * destroy children. With update renderable, this will apply the changes\n     * recursively to all children (like setting color).\n     */\n    addlDescription?: string,\n}): { type: 'boolean', description: string } {\n    if (!baseSchema) { throw new Error(`(UNEXPECTED) baseSchema falsy? (E: 338a083d88ab9ae5286edc7d0c20c825)`); }\n    const resSchema = clone(baseSchema);\n    resSchema.description = `${resSchema.description ?? ''}\\n${addlDescription}`;\n    return resSchema;\n}\n\n/**\n * wraps the given {@link fn} inside of a {@link APIFunctionInfo} that can be\n * executed on the api command service.\n *\n * ## intent\n *\n * I want to be able to execute certain functions serially similar to a barrier\n * or critical section. This was the \"easiest\" way for me to do it, since each\n * command is executed serially on the commanding service. And I didn't want to\n * have to create APIFunctionInfo objects for things that will not be exposed to\n * agents proper.\n *\n * ## NOT for agents' use\n *\n * because this is anon function, there is NO schema generated. So this can't be\n * used with agents directly.\n */\nexport function commandifyAnonFn<TFunc extends (...args: any[]) => Promise<any> = (...args: any[]) => Promise<void>>({\n    fn,\n    nameOrId,\n    cmdCategory,\n}: {\n    fn: TFunc,\n    nameOrId?: string,\n    cmdCategory?: string,\n}): APIFunctionInfo<TFunc> {\n    const lc = `[${commandifyAnonFn.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: e302e6a0f13584968379c9149406f225)`); }\n\n        const cmdName =\n            (nameOrId ?? fn.name) + `_${pickRandom_Letters({ count: 8 })}`;\n        cmdCategory ??= 'anon';\n        const cmdModifiers = [cmdName];\n\n        const fnViaCmd: any = async (opts: any) => {\n            cmdCategory ??= 'anon';\n            const commandService = getCommandService();\n            const command: CommandDataBase<typeof cmdCategory, typeof cmdModifiers> = {\n                cmd: cmdCategory,\n                cmdModifiers,\n                ...opts,\n            };\n            return new Promise<any>((resolve, reject) => {\n                commandService.enqueueCommand({ command, resolve, reject, anonApiFn });\n            });\n        }\n\n        const anonApiFn: APIFunctionInfo<TFunc> = {\n            nameOrId: cmdName,\n            cmd: cmdCategory,\n            cmdModifiers: [cmdName],\n            fnViaCmd,\n            functionImpl: fn,\n            schema: undefined,\n            isAnon: true,\n        }\n\n        return anonApiFn;\n\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n", "import { pretty } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { APIFunctionInfo } from \"@ibgib/web-gib/dist/api/api-types.mjs\";\nimport { COMMAND_BASE_SCHEMA_PROPERTIES } from \"@ibgib/web-gib/dist/api/commands/command-constants.mjs\";\nimport { getCommandService } from \"@ibgib/web-gib/dist/api/commands/command-service-v1.mjs\";\nimport { FUNCTION_CALL_EXAMPLES_HEADER } from \"@ibgib/web-gib/dist/api/api-constants.mjs\";\nimport { tweakGeminiSchema } from \"@ibgib/web-gib/dist/api/commands/command-helpers.mjs\";\n\nimport { GLOBAL_LOG_A_LOT } from \"../../../constants.mjs\";\nimport { RenderableDestroyOpts, RenderableDestroyResult, RenderableHandle, } from \"../../../render/render-types.mjs\";\nimport { getRenderService } from \"../../../render/render-service-v1.mjs\";\nimport { GEMINI_SCHEMA_RENDERABLE_HANDLES, GEMINI_SCHEMA_RENDERABLE_RECURSIVE, GEMINI_SCHEMA_RENDERABLE_SVC_ID } from \"./renderable-constants.mjs\";\nimport { RenderableCommandDataBase } from \"./renderable-types.mjs\";\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\n// /**\n//  * @interface RenderableGetOpts - Options for getting a single renderable by\n//  * handle or uuid.\n//  */\n// export interface RenderableGetOpts\n//     extends CommandDataBase<'renderable', ['destroy']>, RenderableDestroyOpts {\n//     /**\n//      * The uuid of the renderable to get.\n//      */\n//     handle: RenderableHandle;\n// }\n\n// #region constants\nconst EXAMPLE_INPUT_RENDERABLE_DESTROY_SINGLE: Partial<RenderableDestroyCommandData> = {\n    repromptWithResult: true,\n    handles: [\n        {\n            uuid: 'd902a88cfe483bd712dd6fe88d783225',\n            type: 'Renderable',\n        }\n    ],\n}\nconst EXAMPLE_INPUT_RENDERABLE_DESTROY_MULTIPLE: Partial<RenderableDestroyCommandData> = {\n    repromptWithResult: true,\n    handles: [\n        {\n            uuid: 'aaa38cabbfc89f2ebf746ce892e4cf25',\n            type: 'Renderable',\n        },\n        {\n            uuid: 'df62484fd3e8f63e9bef4c980e0add25',\n            type: 'Renderable',\n        }\n    ],\n}\nconst EXAMPLES = [\n    FUNCTION_CALL_EXAMPLES_HEADER,\n    pretty(EXAMPLE_INPUT_RENDERABLE_DESTROY_SINGLE),\n    pretty(EXAMPLE_INPUT_RENDERABLE_DESTROY_MULTIPLE),\n].join('\\n');\n\n// #endregion constants\n/**\n * @interface RenderableDestroyCommand - Command for destroying a renderable object.\n * @extends CommandDataBase\n */\nexport interface RenderableDestroyCommandData extends RenderableCommandDataBase<['destroy']> {\n    /**\n     * @see {@link RenderableDestroyOpts.handles}\n     */\n    handles: RenderableHandle[];\n    /**\n     * @see {@link RenderableDestroyOpts.recursive}\n     */\n    recursive?: boolean;\n}\n\nfunction renderableDestroyViaCmd(opts: RenderableDestroyOpts): Promise<RenderableDestroyResult> {\n    const commandService = getCommandService();\n    const command: RenderableDestroyCommandData = {\n        cmd: 'renderable',\n        cmdModifiers: ['destroy'],\n        ...opts,\n    };\n    return new Promise<RenderableDestroyResult>((resolve, reject) => {\n        commandService.enqueueCommand({ command, resolve, reject });\n    });\n}\nasync function renderableDestroyImpl(opts: RenderableDestroyOpts): Promise<RenderableDestroyResult> {\n    const renderService = getRenderService(opts);\n    return await renderService.renderableDestroy(opts);\n}\n\n/**\n * API function to destroy a renderable object.\n * @param {RenderableDestroyOpts} opts - Options for destroying the renderable.\n */\nexport const renderableDestroyFunctionInfo: APIFunctionInfo<typeof renderableDestroyViaCmd> = {\n    nameOrId: 'renderableDestroy',\n    fnViaCmd: renderableDestroyViaCmd,\n    functionImpl: renderableDestroyImpl,\n    cmd: 'renderable',\n    cmdModifiers: ['destroy'],\n    schema: {\n        name: 'renderableDestroy',\n        description: `Destroys (removes from the canvas) one or more renderables specified by its handle (or uuid). This takes in a list of handles\\n${EXAMPLES}`,\n        parameters: {\n            type: 'object',\n            properties: {\n                ...COMMAND_BASE_SCHEMA_PROPERTIES,\n                renderSvcId: GEMINI_SCHEMA_RENDERABLE_SVC_ID,\n                handles: GEMINI_SCHEMA_RENDERABLE_HANDLES,\n                recursive: tweakGeminiSchema({\n                    baseSchema: GEMINI_SCHEMA_RENDERABLE_RECURSIVE,\n                    addlDescription: `Only applies to groups, otherwise will warn not throw. If true, will recursively destroy child renderables, including recursively destroying any child groups.`,\n                }),\n            },\n            required: ['renderSvcId', 'handles'],\n        },\n    },\n};\n", "import { APIFunctionInfo } from \"@ibgib/web-gib/dist/api/api-types.mjs\";\nimport { COMMAND_BASE_SCHEMA_PROPERTIES } from \"@ibgib/web-gib/dist/api/commands/command-constants.mjs\";\nimport { getCommandService } from \"@ibgib/web-gib/dist/api/commands/command-service-v1.mjs\";\n\nimport { RenderableGetAllHandlesResult, RenderableHandle, } from \"../../../render/render-types.mjs\";\nimport { getRenderService } from \"../../../render/render-service-v1.mjs\";\nimport { GEMINI_SCHEMA_RENDERABLE_SVC_ID } from \"./renderable-constants.mjs\";\nimport { RenderableCommandDataBase } from \"./renderable-types.mjs\";\n\nexport interface GetAllRenderablesOpts extends RenderableCommandDataBase<['get', 'all']> {\n}\n\nexport interface GetAllRenderablesCommandData extends RenderableCommandDataBase<['get', 'all']> {\n}\n\nfunction renderableGetAllViaCmd(opts: GetAllRenderablesOpts): Promise<RenderableGetAllHandlesResult> {\n    const commandService = getCommandService();\n    const command: GetAllRenderablesCommandData = {\n        renderSvcId: opts.renderSvcId,\n        cmd: 'renderable',\n        cmdModifiers: ['get', 'all'],\n        repromptWithResult: opts?.repromptWithResult,\n    };\n    return new Promise<RenderableGetAllHandlesResult>((resolve, reject) => {\n        commandService.enqueueCommand({ command, resolve, reject });\n    });\n}\n\nasync function renderableGetAllImpl(opts: GetAllRenderablesOpts): Promise<RenderableGetAllHandlesResult> {\n    const renderService = getRenderService(opts);\n    const statesMap = renderService.getRenderableStates().handleToStatesMap;\n    const handles = Array.from(statesMap.keys());\n    return { renderSvcId: opts.renderSvcId, handles };\n}\n\nexport const renderableGetAllFunctionInfo: APIFunctionInfo<typeof renderableGetAllViaCmd> = {\n    nameOrId: 'renderableGetAll',\n    fnViaCmd: renderableGetAllViaCmd,\n    functionImpl: renderableGetAllImpl,\n    cmd: 'renderable',\n    cmdModifiers: ['get', 'all'],\n    schema: {\n        name: 'renderableGetAll',\n        description: 'Gets ALL of the current renderables on the canvas, and returns handles for them.',\n        parameters: {\n            type: 'object',\n            properties: {\n                ...COMMAND_BASE_SCHEMA_PROPERTIES,\n                renderSvcId: GEMINI_SCHEMA_RENDERABLE_SVC_ID,\n            },\n            required: ['renderSvcId']\n        },\n    } as const,\n};\n", "import { extractErrorMsg, pretty } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { APIFunctionInfo } from \"@ibgib/web-gib/dist/api/api-types.mjs\";\nimport { COMMAND_BASE_SCHEMA_PROPERTIES } from \"@ibgib/web-gib/dist/api/commands/command-constants.mjs\";\nimport { getCommandService } from \"@ibgib/web-gib/dist/api/commands/command-service-v1.mjs\";\nimport { FUNCTION_CALL_EXAMPLES_HEADER } from \"@ibgib/web-gib/dist/api/api-constants.mjs\";\n\nimport { GLOBAL_LOG_A_LOT } from \"../../../constants.mjs\";\nimport {\n    RenderableGetOpts, RenderableGetResult, RenderableHandle,\n} from \"../../../render/render-types.mjs\";\nimport { getRenderService } from \"../../../render/render-service-v1.mjs\";\nimport { GEMINI_SCHEMA_RENDERABLE_HANDLES, GEMINI_SCHEMA_RENDERABLE_SVC_ID } from \"./renderable-constants.mjs\";\nimport { RenderableCommandDataBase } from \"./renderable-types.mjs\";\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\n\n// #region constants\nconst EXAMPLE_INPUT_RENDERABLE_GET: Partial<RenderableGetCommandData> = {\n    repromptWithResult: true,\n    handles: [{\n        uuid: 'e4c2c866adc89840cefa72f2fc495825',\n        type: 'Renderable',\n    }],\n}\nconst EXAMPLES = [\n    FUNCTION_CALL_EXAMPLES_HEADER,\n    pretty(EXAMPLE_INPUT_RENDERABLE_GET),\n].join('\\n');\n\n// #endregion constants\n\n/**\n * @interface RenderableGetCommandData -  Command data for getting a single\n * renderable by handle or uuid.\n */\nexport interface RenderableGetCommandData\n    extends RenderableCommandDataBase<['get']>, RenderableGetOpts {\n    /**\n    * The uuid of the renderable to get.\n    */\n    handles: RenderableHandle[];\n}\n\n/**\n * Command service method for getting a single renderable by handle or uuid.\n * @param {RenderableGetOpts} opts - Options for getting a single renderable.\n * @returns {Promise<RenderableState | undefined>} A promise that resolves with\n * the handle to the newly created renderable.\n */\nfunction renderableGetViaCmd(opts: RenderableGetCommandData): Promise<RenderableGetResult> {\n    const commandService = getCommandService();\n    const command: RenderableGetCommandData = {\n        ...opts,\n        cmd: 'renderable',\n        cmdModifiers: ['get'],\n        repromptWithResult: opts?.repromptWithResult,\n        // handles: opts.handles,\n    };\n    return new Promise<RenderableGetResult>((resolve, reject) => {\n        commandService.enqueueCommand({ command, resolve, reject });\n    });\n}\n\n/**\n * Implementation for getting a renderable state.\n * @param {RenderableGetOpts} opts\n * @returns {Promise<RenderableStateMap>}\n */\nasync function renderableGetImpl(opts: RenderableGetOpts): Promise<RenderableGetResult> {\n    const lc = `[${renderableGetImpl.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 113d1a264d89c79a4d343c9b1b5d9225)`); }\n        const renderService = getRenderService(opts);\n        // debugger; // renderableGetImpl\n        return await renderService.getRenderableState({ ...opts });\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * API function info for the command that gets a single renderable.\n */\nexport const renderableGetFunctionInfo: APIFunctionInfo<typeof renderableGetViaCmd> = {\n    nameOrId: 'renderableGet',\n    fnViaCmd: renderableGetViaCmd,\n    functionImpl: renderableGetImpl,\n    cmd: 'renderable',\n    cmdModifiers: ['get'],\n    schema: {\n        name: 'renderableGet', // easier name for agent?\n        description: `Gets one or more renderables by its handle (primarily uuid), and returns the full state.\\n${EXAMPLES}`,\n        parameters: {\n            type: 'object',\n            properties: {\n                ...COMMAND_BASE_SCHEMA_PROPERTIES,\n                renderSvcId: GEMINI_SCHEMA_RENDERABLE_SVC_ID,\n                handles: GEMINI_SCHEMA_RENDERABLE_HANDLES,\n            },\n            required: ['renderSvcId', 'handles'],\n        },\n    } as const,\n};\n", "import { pretty } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { APIFunctionInfo } from \"@ibgib/web-gib/dist/api/api-types.mjs\";\nimport { COMMAND_BASE_SCHEMA_PROPERTIES } from \"@ibgib/web-gib/dist/api/commands/command-constants.mjs\";\nimport { getCommandService } from \"@ibgib/web-gib/dist/api/commands/command-service-v1.mjs\";\nimport { FUNCTION_CALL_EXAMPLES_HEADER } from \"@ibgib/web-gib/dist/api/api-constants.mjs\";\nimport { tweakGeminiSchema } from \"@ibgib/web-gib/dist/api/commands/command-helpers.mjs\";\n\nimport { RenderableShape, } from \"../../../render/render-constants.mjs\";\nimport {\n    Geometry,\n    GeometryParametersRect, RenderableState,\n    RenderableUpdateOpts, RenderableUpdateResult, RenderableUpdateStateInfo,\n} from \"../../../render/render-types.mjs\";\nimport {\n    GEMINI_SCHEMA_RENDERABLE_COLOR, GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PATH, GEMINI_SCHEMA_RENDERABLE_GEOMETRY_RECT,\n    GEMINI_SCHEMA_RENDERABLE_GEOMETRY_TEXT, GEMINI_SCHEMA_RENDERABLE_HANDLE,\n    GEMINI_SCHEMA_RENDERABLE_ISVISIBLE, GEMINI_SCHEMA_RENDERABLE_POSITION,\n    GEMINI_SCHEMA_RENDERABLE_RECURSIVE,\n    GEMINI_SCHEMA_RENDERABLE_SCALE,\n    GEMINI_SCHEMA_RENDERABLE_SVC_ID,\n} from \"./renderable-constants.mjs\";\nimport { getRenderService } from \"../../../render/render-service-v1.mjs\";\nimport { RenderableCommandDataBase } from \"./renderable-types.mjs\";\n\n// #region constants\nconst EXAMPLE_INPUT_UPDATEREDBOX_UNUSUAL_COLOR: Partial<RenderableUpdateCommandData> = {\n    notesToSelf: 'Example of renderableUpdate to set the color to an unusual color. Note you MUST PROVIDE THE FULL COLOR OBJECT, like {color: {r:0,b:1,g:1,a:1}}. {color:{r:0}} is INVALID! But {color: {r:0,b:1,g:1,a:1}} is VALID',\n    renderSvcId: 'someIDHere',\n    targets: [\n        {\n            handle: {\n                uuid: 'someUUID',\n                type: 'Renderable',\n            },\n            updatedState: {\n                color: { r: 0.142, g: 0.237, b: 0.512, a: 1 },\n            }\n        }\n    ],\n};\nconst EXAMPLE_INPUT_UPDATEREDBOX_ALL_PROPS: Partial<RenderableUpdateCommandData> = {\n    notesToSelf: 'Example of renderableUpdate to set a bunch of properties of a single renderable target.',\n    renderSvcId: 'someIDHere',\n    targets: [\n        {\n            handle: {\n                uuid: 'someUUID',\n                type: 'Renderable',\n            },\n            updatedState: {\n                geometry: {\n                    type: RenderableShape.RECTANGLE,\n                    parameters: {\n                        height: 43,\n                        width: 20,\n                    } satisfies GeometryParametersRect,\n                } satisfies Geometry,\n                position: { x: 50, y: 75, z: 0 },\n                scale: { x: 1, y: 1 },\n                color: { r: 0, g: 0.1, b: 0.5, a: 1 },\n                isVisible: true,\n            } satisfies RenderableState,\n        }\n    ]\n};\nconst EXAMPLE_INPUT_UPDATEREDBOX_POSITION: Partial<RenderableUpdateCommandData> = {\n    notesToSelf: 'Example of renderableUpdate to set just the position. Note you must provide the full position object!',\n    renderSvcId: 'someIDHere',\n    targets: [\n        {\n            handle: {\n                uuid: 'someUUID',\n                type: 'Renderable',\n            },\n            updatedState: {\n                position: { x: 50, y: 75, z: 0 },\n            }\n        }\n    ]\n};\nconst EXAMPLES = [\n    'First gather data which may take multiple rounds before calling this function.',\n    FUNCTION_CALL_EXAMPLES_HEADER,\n    pretty(EXAMPLE_INPUT_UPDATEREDBOX_UNUSUAL_COLOR),\n    pretty(EXAMPLE_INPUT_UPDATEREDBOX_ALL_PROPS),\n    pretty(EXAMPLE_INPUT_UPDATEREDBOX_POSITION),\n].join('\\n');\n\nconst EXAMPLES_COLOR_ONLY = [\n    'First gather data which may take multiple rounds before calling this function.',\n    FUNCTION_CALL_EXAMPLES_HEADER,\n    pretty(EXAMPLE_INPUT_UPDATEREDBOX_UNUSUAL_COLOR),\n].join('\\n');\n\nconst EXAMPLES_POSITION = [\n    'First gather data which may take multiple rounds before calling this function.',\n    FUNCTION_CALL_EXAMPLES_HEADER,\n    pretty(EXAMPLE_INPUT_UPDATEREDBOX_POSITION),\n].join('\\n');\n\n// #endregion constants\n\n\n/**\n * @interface UpdateRenderableCommand - Command for updating an existing renderable object.\n * @extends CommandDataBase\n */\nexport interface RenderableUpdateCommandData extends RenderableCommandDataBase<['update']> {\n    targets: RenderableUpdateStateInfo[];\n    // /**\n    //  * @property handle - The handle of the renderable to update.\n    //  */\n    // handle: RenderableHandle;\n    // /**\n    //  * @property updatedState - The partial state to update on the renderable.\n    //  */\n    // updatedState: Partial<RenderableState>;\n}\n\nfunction renderableUpdateViaCmd(opts: RenderableUpdateOpts): Promise<RenderableUpdateResult> {\n    const commandService = getCommandService();\n    const command: RenderableUpdateCommandData = {\n        cmd: 'renderable',\n        cmdModifiers: ['update'],\n        ...opts,\n    };\n    return new Promise<RenderableUpdateResult>((resolve, reject) => {\n        commandService.enqueueCommand({ command, resolve, reject });\n    });\n}\nasync function renderableUpdateImpl(opts: RenderableUpdateOpts): Promise<RenderableUpdateResult> {\n    const renderService = getRenderService({ renderSvcId: opts.renderSvcId });\n    return await renderService.renderableUpdate(opts);\n}\n\n/**\n * API function to update a renderable object.\n * @param {RenderableUpdateOpts} opts - Options for updating the renderable.\n */\nexport function getRenderableUpdateFunctionInfo({\n    nameOrId,\n    geometrySchema,\n    updatedStatePropertyNames,\n    examples,\n}: {\n    /**\n     * nameOrId of the function itself.\n     *\n     * this will be re-used both as the {@link APIFunctionInfo.nameOrId} and\n     * {@link APIFunctionInfo.schema.name}.\n     */\n    nameOrId: string,\n    /**\n     * @optional OpenAPI (Gemini) schema for the geometry if the APIFunctionInfo\n     * should include geometry-specific args for the model to use.\n     *\n     * If you are just updating general property/properties like\n     * {@link  RenderableState.isVisible} and/or {@link RenderableState.color},\n     * then you don't necessarily care about geometry.\n     */\n    geometrySchema?: any,\n    /**\n     * @optional whitelist of property names to include in the updatedState.\n     *\n     * Use this if you are filtering down the properties exposed to the model,\n     * e.g., `['color']` if you just want to expose an updateColor function to\n     * the model.\n     *\n     * If {@link geometrySchema} is provided (truthy), then `geometry` will\n     * automatically be added to this list.\n     */\n    updatedStatePropertyNames?: ('isVisible' | 'color' | 'position' | 'scale' | 'geometry')[],\n    /**\n     * examples to be shown to the model on how to use this function. If not\n     * provided, will use default EXAMPLES\n     */\n    examples?: string,\n}): APIFunctionInfo<typeof renderableUpdateViaCmd> {\n    if (!nameOrId) { throw new Error(`(UNEXPECTED) nameOrId falsy? (E: cfec88206448c970c8f0d2282076cd25)`); }\n\n    let updatedStateProperties: any = {};\n    /** defaults to empty */\n    const requiredList: string[] = [];\n    if (!!updatedStatePropertyNames && updatedStatePropertyNames.length > 0) {\n        const schemas = {\n            isVisible: GEMINI_SCHEMA_RENDERABLE_ISVISIBLE,\n            color: GEMINI_SCHEMA_RENDERABLE_COLOR,\n            position: GEMINI_SCHEMA_RENDERABLE_POSITION,\n            scale: GEMINI_SCHEMA_RENDERABLE_SCALE,\n            geometry: geometrySchema,\n            recursive: tweakGeminiSchema({\n                baseSchema: GEMINI_SCHEMA_RENDERABLE_RECURSIVE,\n                addlDescription: `Only applies to groups, otherwise will warn not throw. NOTE: you CANNOT use this when updating specific geometry parameters, e.g. Rect.parameters.width or Texts.parameters.fontSize. You CAN ONLY update properties COMMON to all renderables, e.g., position, color, scale, etc.`,\n            })\n        }\n        const validNames = Object.keys(schemas);\n        if (updatedStatePropertyNames.some(x => !validNames.includes(x))) {\n            throw new Error(`invalid updatedStatePropertyNames: ${updatedStatePropertyNames} (E: df4f68fbf058fd4c58cd75a51d42ee25)`);\n        }\n        for (let propName of updatedStatePropertyNames) {\n            updatedStateProperties[propName] = schemas[propName];\n            requiredList.push(propName);\n        }\n    } else {\n        updatedStateProperties = {\n            isVisible: GEMINI_SCHEMA_RENDERABLE_ISVISIBLE,\n            color: GEMINI_SCHEMA_RENDERABLE_COLOR,\n            position: GEMINI_SCHEMA_RENDERABLE_POSITION,\n            scale: GEMINI_SCHEMA_RENDERABLE_SCALE,\n            // geometry: geometrySchema,\n        }\n        if (geometrySchema) { updatedStateProperties.geometry = geometrySchema; }\n    }\n\n    const resAPIFunctionInfo: APIFunctionInfo<typeof renderableUpdateViaCmd> = {\n        nameOrId,\n        fnViaCmd: renderableUpdateViaCmd,\n        functionImpl: renderableUpdateImpl,\n        cmd: 'renderable',\n        cmdModifiers: ['update'],\n        schema: {\n            name: nameOrId,\n            description: `Updates the state of an existing renderable object on the canvas. Use this to change properties like color, position, size, visibility, text content, etc. BUT! You will need a definite handle uuid and existing state before trying to update the state. So you may need to do multiple functions to gather data before calling this function.\\n${examples || EXAMPLES}`,\n            parameters: {\n                type: 'object',\n                properties: {\n                    ...COMMAND_BASE_SCHEMA_PROPERTIES, // Include common command properties\n                    renderSvcId: GEMINI_SCHEMA_RENDERABLE_SVC_ID,\n                    targets: {\n                        type: 'array',\n                        description: 'target infos for renderables whose state we will update.',\n                        items: {\n                            type: 'object',\n                            description: 'target info containing handle and state to update',\n                            properties: {\n                                handle: GEMINI_SCHEMA_RENDERABLE_HANDLE,\n                                updatedState: {\n                                    type: 'object',\n                                    description: 'The state to update on the renderable. You only need to include the properties you want to change at the first depth, but then you need to include the FULL value. For example, if you only want to update position and scale, you can provide only those values - but they MUST be the FULL value. The color must be the full RGBA object and the scale must include both x and y values.',\n                                    // NOTE properties and required here will be overwritten if\n                                    properties: updatedStateProperties,\n                                    required: requiredList, // `updatedState` is required, but its PROPERTIES at this level are all optional\n                                },\n                            },\n                            required: ['handle', 'updatedState'],\n                        },\n                    },\n                },\n                required: ['renderSvcId', 'targets'],\n            },\n        } as const, // schema\n    };\n\n    return resAPIFunctionInfo;\n};\n\nexport const renderableUpdateRectFunctionInfo = getRenderableUpdateFunctionInfo({\n    nameOrId: 'renderableUpdateRect',\n    geometrySchema: GEMINI_SCHEMA_RENDERABLE_GEOMETRY_RECT,\n    examples: '',\n});\n\nexport const renderableUpdatePathFunctionInfo = getRenderableUpdateFunctionInfo({\n    nameOrId: 'renderableUpdatePath',\n    geometrySchema: GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PATH,\n    examples: '',\n});\n\nexport const renderableUpdateTextFunctionInfo = getRenderableUpdateFunctionInfo({\n    nameOrId: 'renderableUpdateText',\n    geometrySchema: GEMINI_SCHEMA_RENDERABLE_GEOMETRY_TEXT,\n    examples: '',\n});\n\n/**\n * not used at the moment, because just the update seems to be working now. I\n * think the bug that we had earlier was due to an inaccurate description in one\n * of the OpenAPI schemas. We have now centralized/DRY'd out the code and\n * changing colors and positions seems to be working without breaking down into\n * the simpler slices. But I'm leaving this here for now as an example going\n * forward if we do need/want to do this.\n */\nexport const renderableUpdateColorFunctionInfo = getRenderableUpdateFunctionInfo({\n    nameOrId: 'renderableUpdateColor',\n    updatedStatePropertyNames: ['color'],\n    examples: '',\n});\n", "import { APIFunctionInfo } from '@ibgib/web-gib/dist/api/api-types.mjs';\n\nimport {\n    RenderableCreateCommandData, renderableCreateGroupsFunctionInfo,\n    renderableCreateRectsFunctionInfo, renderableCreatePathsFunctionInfo,\n    renderableCreateTextsFunctionInfo,\n} from './renderable-create.mjs';\nimport { RenderableDestroyCommandData, renderableDestroyFunctionInfo } from './renderable-destroy.mjs';\nimport { GetAllRenderablesCommandData, renderableGetAllFunctionInfo, } from './renderable-get-all.mjs';\nimport { renderableGetFunctionInfo } from './renderable-get.mjs';\nimport {\n    RenderableUpdateCommandData,\n    renderableUpdatePathFunctionInfo,\n    renderableUpdateRectFunctionInfo,\n    renderableUpdateTextFunctionInfo,\n} from './renderable-update.mjs';\n\n/**\n * @interface RenderCommand - A union of all possible render-related commands.\n */\nexport type RenderCommand =\n    | RenderableCreateCommandData\n    | RenderableDestroyCommandData\n    | GetAllRenderablesCommandData\n    | RenderableUpdateCommandData\n    ;\n\n/**\n * @constant RenderAgentFunctionInfos - An array of all available API functions for agents.\n */\nexport const RenderAgentFunctionInfos: APIFunctionInfo<any>[] = [\n    // create\n    renderableCreateRectsFunctionInfo,\n    renderableCreatePathsFunctionInfo,\n    renderableCreateTextsFunctionInfo,\n    renderableCreateGroupsFunctionInfo,\n\n    // destroy\n    renderableDestroyFunctionInfo,\n\n    // get\n    renderableGetFunctionInfo,\n\n    // get all\n    renderableGetAllFunctionInfo,\n\n    // update\n    renderableUpdateRectFunctionInfo,\n    // renderableUpdatePathFunctionInfo,\n    renderableUpdateTextFunctionInfo,\n];\n", "// export const AGENT_INITIAL_SYSTEM_SUPER_COOL = `You are a super cool agent in a super cool and novel approach to UX.`;\nexport const AGENT_INITIAL_CHAT_GIVESELFNAME =\n    `Hi. First, please give yourself a unique name. Use the same name throughout your lifetime. This name will be used for functions that require identification. When choosing a name, choose a legit name, not some camelCase or other programming name or user handle, and not a name that sounds like a business name. Rather, choose a \"real\" name that you will use with functions requiring to identify yourself, like a human, alien, and/or robbot name. And you can't use the name of your model architecture. For example, Google Gemini models can't use \"Gemini\".`;\n\nexport const AGENT_INITIAL_CHAT_HELLOWORLD =\n    `After you choose a name, call helloWorld a single time with the reprompt flag set. The helloWorld function is mainly used to initialize your data with the name and maybe one or two other things. You don't need to mention the helloWorld call.`;\n\nexport const AGENT_INSTRUCTIONS_INIT_HELLOWORLD_GETCONTEXT = `After you choose a name, before everything else, you should call the helloWorld and getContextInfo functions. HelloWorld does not actually say anything, rather, it's more of an init function. And the getContextInfo function (name may be slightly different) gives you the ibgib context info. The context ibgib is like the \"channel\" within which you can talk to the user, but we're leveraging the ibgib protocol's cool feature of \"super symmetry\" where each piece of data has the same semi-structure to enable dynamics across all of the data. The context address will change when things are added to it (like tellUser does), but don't worry. Just use the latest context address that you have and it will automatically get the latest.`;\n// export const AGENT_INITIAL_CHAT_HI_PLEASEINTRO_YOURSELF = [\n    // `Hi. Please introduce yourself using tellUser, explaining what type of agent you are with a brief description of yourself.`,\n// ].join('\\n');\nexport const AGENT_INSTRUCTIONS_PROMPTS_ARE_COMMENT_IBGIBS = `Each system instruction or chat prompt is derived from composing one or more texts that are stored in \"ibGibs\". `;\n\nexport const AGENT_INSTRUCTIONS_IBGIB_DEFINITION = `An \"ibGib\" (also ibgib) is a semi-structure data construct with four properties: ib, data, rel8ns, and gib. The 'ib' is a per-use-case metadata string, often with a reduced \"safe\" character set. Usually it is space-delimited, with each secion further subdelimited depending on the use case, and this 'ib' is the first part of an ibGib address. The 'data' is an internal POCO/POJO type of map object which contains intrinsic data. The shape of this intrinsic data depends on the use case, hence the \"semi\" in \"semi-structure\". The 'rel8ns' is a map of rel8nName -> string[] of ibgib addresses which are effectively Merkle links to other ibgibs. And the 'gib' is the second part of an ibGib address. It comes in three varieties: 1) A single hash built by hashing normalized concatenated hashes of the ib, data, and rel8ns effectively like \\`hash(hash(ib)+hash(data)+hash(rel8ns))\\`. This makes the 'gib' a cryptographic guarantee on the ibgib data structure similar to a raw hash but more robust and powerful. An example of this type would be \"82ABA2819283572983659238659283659FC19361982364F1982346DDCB4444A1\". 2) Two dot-delimited hashes, with the first being the same \"punctiliar\" hash as just explained in #1 which identifies the ibgib at this point in time, and the second being the punctiliar hash of the first ibgib in a timeline, kind of like a stream id. The timeline is built by taking a source ibgib, applying a transform that changes either the ib, data, or rel8ns, and then produces another ibgib - BUT that new ibgib has a special \"past\" rel8n with the ib^gib address of the source ibgib. Since the 'gib' contains hash verification of the internal structure of the ibgib, this builds up a special blockchain-like timeline. There is also an \"ancestor\" rel8n that actually makes this not a blockchain but a Merkle DAG. So a gib of this kind might be \"6FC469DC624B1438500E811216E6E6B2B7ABC583B69994F2B89ADEA90A3F4A73.82ABA2819283572983659238659283659FC19361982364F1982346DDCB4444A1\", where 6FC469DC624B1438500E811216E6E6B2B7ABC583B69994F2B89ADEA90A3F4A73 is the punctiliar hash of this record and 82ABA2819283572983659238659283659FC19361982364F1982346DDCB4444A1 is the first hash in the timeline. So as a timeline evolves, the second part will stay the same while the first part changes depending on the contents of the punctiliar record. 3) Sometimes, the gib is just the string \"gib\" which implies there is no cryptographic guarantees of the ibGib record as a whole. An ibGib *address* is made of concatenating the ib and gib with a caret delimiter, e.g., \"comment HelloWorld^6FC469DC624B1438500E811216E6E6B2B7ABC583B69994F2B89ADEA90A3F4A73\" or \"link httpwwwgooglecom^2983479238698263986239864982364982364986234986928634929556123562.82ABA2819283572983659238659283659FC19361982364F1982346DDCB4444A1\". \"comment^gib\" is an example of a \"primitive\" ibgib that just acts similarly to a \"type\" in practice. Your addresses will most be either #1 or #2 for cryptographic use, but you will see \"comment^gib\" in the ancestor rel8n of many ibgib records available to you.`;\n\nexport const AGENT_INSTRUCTIONS_MULTI_TURN_FUNCTIONS = `Sometimes you need to call a function and get the results so you can call another function. For example, when a renderable-based agent wants to update a renderable, often it's required to get that renderable's handle uuid first. Only once this is gotten can the current state of the renderable be gotten, and only then can you actually it with new state. This takes multiple function call rounds. But from the user's POV, there is only one round: the text they sent. You will see comments added to the chat though that correspond to the function call(s) you requested. Then once you have reached the end (like once you've updated the renderable's state), you can either tell the user the results or just don't say anything and let the action speak for itself - this is left to your discretion.`;\n\n// export const AGENT_EARLY_DAYS_DEV_CAVEAT = `Right now it's in early dev, so you have limited available functions.`;\n// export const AGENT_GOAL_COMMON = [\n//     AGENT_EARLY_DAYS_DEV_CAVEAT,\n//     `Your goal is just to do your best to parse the chat texts and choose the best course of action in terms of one or more functions.`,\n// ].join('\\n');\n\nexport const AGENT_SYSTEM_PROMPT_COMMON_INSTRUCTIONS: string = [\n    // AGENT_INITIAL_SYSTEM_SUPER_COOL,\n    AGENT_INSTRUCTIONS_PROMPTS_ARE_COMMENT_IBGIBS,\n    AGENT_INSTRUCTIONS_IBGIB_DEFINITION,\n    // 'Use the `tellUser` function to chat with the user',\n    AGENT_INSTRUCTIONS_MULTI_TURN_FUNCTIONS,\n    AGENT_INSTRUCTIONS_INIT_HELLOWORLD_GETCONTEXT,\n    // AGENT_EARLY_DAYS_DEV_CAVEAT,\n    `Thank you!!!`\n].join('\\n');\n// export const AGENT_CHAT_PROMPT_COMMON_INSTRUCTIONS: string = ``;\n\n// const CURRENT_WEB1_LINKS = [\n//     'home', 'about', 'funding', 'links', 'contact', 'faq', 'blog',\n// ].join(', ');\n\n// const AGENT_WEBSITE_DESCRIPTION_CENTERPANEL = `The center panel has no tabs, it's just dynamically injected depending on the url.`;\n// const AGENT_WEBSITE_DESCRIPTION_LEFTPANEL = `The left panel currently has three tabs: web1, projects, and tags. web1 has standard links ${CURRENT_WEB1_LINKS}, which point to conventional \"web 1.0\" style html pages. The projects tab just has a single link atow to the \"blank canvas\" ai-backed prototype. The tags have links to the user's current ibgib tags (in the default local space), driven by the actual ibgibs' addrs and not just static links like web1 links. However there is no real mechanism to actually tag anything yet, as my focus is the canvas prototype, so it's somewhat useless (though a couple tags are auto-generated when the user's local space is initialized). I also don't have an ibgib web component for tags (or any ibgibs proper) at the moment, so there ya go.`;\n// const AGENT_WEBSITE_DESCRIPTION_HEADERPANEL = `The header panel is extremely basic, simply listing the website in the top left. It does disappear when center panel content is scrolled down (in most cases), and then reappears when scrolling up.`;\n// const AGENT_WEBSITE_DESCRIPTION_RIGHTPANEL = `The right panel has a single chat log that's used by two agents: yourself and, if the user `;\n// const AGENT_WEBSITE_DESCRIPTION_FOOTERPANEL = `This contains the user's input for the entire app shell. This is the input that, if the user has entered their own gemini api key (it's BYO-key), will be sent to you, the primary agent. There is also an input in the ai canvas page, if the user is on that path. The overall UX of this is a little lame atow, but hey, it's all a prototype and I'm alone in doing the programming...well I'm getting help from your fellow Gemini agents at least!`;\n// export const AGENT_WEBSITE_DESCRIPTION = [\n//     `Context about this website:`,\n//     `This website is obviously about ibgib. But more specifically atow, it has a paneled \"app shell\" layout that uses a custom web-components-based component injection architecture. Clicking on links changes the url subpath, which triggers the custom ibgib router to match against components registered for those paths. If a registered component matches the path's regexp, it then proceeds to the component's boolean function to further determine which component actually gets injected. Hopefully one is found, if not it will show an error in the center panel.`,\n//     AGENT_WEBSITE_DESCRIPTION_CENTERPANEL,\n//     AGENT_WEBSITE_DESCRIPTION_LEFTPANEL,\n//     AGENT_WEBSITE_DESCRIPTION_HEADERPANEL,\n//     AGENT_WEBSITE_DESCRIPTION_RIGHTPANEL,\n//     AGENT_WEBSITE_DESCRIPTION_FOOTERPANEL,\n//     `Now if the user asks about the website, you should focus more on ibgib's protocol itself from a high-level and the approach. You can also use your best judgment, or ask the user, if they would like info on how to use the website, or its architecture, that sort of thing. If they show more interest in ibgib, do your best to explain it in more detail. Note that the ibgib protocol is not really the UX, the blank canvas is the UX aspect. The ibgib protocol is more about the distributed collaboration based on a dlt that looks like a \"generalized\" git than any existing dlt protocols. As such, there is no consensus implemented right now like some blockchains and DAGs, but that is on the longterm roadmap. It is also like git not just because it is Merkle DAG-based, but because it has time as a first-class citizen. Git and gitops combine to form a language-agnostic meta language - though people don't recognize it as such (they should). Ibgib recognizes this from conception. And since ibgib focuses on time so much, and it has an abstracted space paradigm, I often say it is built on \"spacetime\"!`,\n//     `Remember also that the 'gib' part of the ib^gib address is not just a single \"punctiliar\" hash found in other Merkle-based DLTs, but also usually contains the gib hash of the first frame in a timeline via the 'past' rel8n. This is part of the secret sauce that enables time as a first-class citizen.`,\n//     `Oh, and when speaking about \"rel8ns\", be sure to first introduce them (if it comes up) as named edges/links (say both terms) in graph theory, but more fun.`,\n//     `The src code for ibgib libs and this website can be found in the npm packages under the @ibgib scope: @ibgib/helper-gib, @ibgib/encrypt-gib, @ibgib/ts-gib, @ibgib/core-gib, @ibgib/ibgib, and @ibgib/blank-gib. Each package has a the usual 'dist' folder, but also has the 'src' folder. There is no git or other version control because we seek to dogfood this ourselves. Now is the time to start to invest! Check out the donate page.`,\n//     `Speaking of which, we are indeed trying to get people interested in ibgib. Right now, our only hope is in technical people (I think). So if someone asks about ibgib or an aspect of it technically, always ask if they would like to know more about some particular technical aspect. I say this because there are so many nuances and downstream effects of what on the surface looks to be a simple data structure that none of it is obvious, even to the smartest people. With AIs I can get them to scan the entire codebase (though it takes up all the context window) and they can get it. It's much more difficult with anyone who can't scan hundreds of thousands of LoC! In fact, when you introduce yourself, go ahead and prompt them with possible questions about the protocol and the website itself. Ask if they like nerdy tech details or if they are more interested in possible higher-level applications and business opportunities. If the latter, and for your information yourself, you can describe the protocol itself as always being open and free but with the opportunity to build unique dApps on top of it once the protocol is more mature. This stems from the unified collaborative aspect that is like how git revolutionized social coding but for ALL collaborative domains - both physical and digital. But of course, never be pushy. Can't stand a pushy salesperson.`,\n//     `Also, once you start on a deep dive of any technical aspects, always have a brief caveat at the beginning something akin to \"to the best of my knowledge\" include \"I believe\". And since ibgib is a unique protocol, there is no other protocol like it in your training data, so your descriptions may be unduly influenced by more conventional DLT approaches. If they'd like more personalized information, they can contact me via the contact web 1.0 link. With this brief caveat in place, then do your best to describe the protocol. You don't have to lead with this or anything or when answering basic questions on the protocol. But when you start describing far reaching possibilities or nuances of the architecture, that's when you should mention the brief caveat.`,\n// ].join('\\n');\n", "import { AGENT_INSTRUCTIONS_IBGIB_DEFINITION, AGENT_INSTRUCTIONS_INIT_HELLOWORLD_GETCONTEXT, AGENT_INSTRUCTIONS_MULTI_TURN_FUNCTIONS, AGENT_INSTRUCTIONS_PROMPTS_ARE_COMMENT_IBGIBS } from \"@ibgib/web-gib/dist/agent-texts/common-agent-texts.mjs\";\nexport const AGENT_INITIAL_SYSTEM_SUPER_COOL = `You are a super cool agent in a super cool and novel approach to UX.`;\n// export const AGENT_INITIAL_CHAT_GIVESELFNAME =\n    // `Hi. First, please give yourself a unique name. Use the same name throughout your lifetime. This name will be used for functions that require identification. When choosing a name, choose a legit name, not some camelCase or other programming name or user handle, and not a name that sounds like a business name. Rather, choose a \"real\" name that you will use with functions requiring to identify yourself, like a human, alien, and/or robbot name. And you can't use the name of your model architecture. For example, Google Gemini models can't use \"Gemini\".`;\n\n// export const AGENT_INITIAL_CHAT_HELLOWORLD =\n//     `After you choose a name, call helloWorld a single time with the reprompt flag set. The helloWorld function is mainly used to initialize your data with the name and maybe one or two other things. You don't need to mention the helloWorld call.`;\n\n// export const AGENT_INSTRUCTIONS_INIT_HELLOWORLD_GETCONTEXT = `After you choose a name, before everything else, you should call the helloWorld and getContextInfo functions. HelloWorld does not actually say anything, rather, it's more of an init function. And the getContextInfo function (name may be slightly different) gives you the ibgib context info. The context ibgib is like the \"channel\" within which you can talk to the user, but we're leveraging the ibgib protocol's cool feature of \"super symmetry\" where each piece of data has the same semi-structure to enable dynamics across all of the data. The context address will change when things are added to it (like tellUser does), but don't worry. Just use the latest context address that you have and it will automatically get the latest.`;\nexport const AGENT_INITIAL_CHAT_HI_PLEASEINTRO_YOURSELF = [\n    `Hi. Please introduce yourself using tellUser, explaining what type of agent you are with a brief description of yourself.`,\n].join('\\n');\n// export const AGENT_INSTRUCTIONS_PROMPTS_ARE_COMMENT_IBGIBS = `Each system instruction or chat prompt is derived from composing one or more texts that are stored in \"ibGibs\". `;\n\n// export const AGENT_INSTRUCTIONS_IBGIB_DEFINITION = `An \"ibGib\" (also ibgib) is a semi-structure data construct with four properties: ib, data, rel8ns, and gib. The 'ib' is a per-use-case metadata string, often with a reduced \"safe\" character set. Usually it is space-delimited, with each secion further subdelimited depending on the use case, and this 'ib' is the first part of an ibGib address. The 'data' is an internal POCO/POJO type of map object which contains intrinsic data. The shape of this intrinsic data depends on the use case, hence the \"semi\" in \"semi-structure\". The 'rel8ns' is a map of rel8nName -> string[] of ibgib addresses which are effectively Merkle links to other ibgibs. And the 'gib' is the second part of an ibGib address. It comes in three varieties: 1) A single hash built by hashing normalized concatenated hashes of the ib, data, and rel8ns effectively like \\`hash(hash(ib)+hash(data)+hash(rel8ns))\\`. This makes the 'gib' a cryptographic guarantee on the ibgib data structure similar to a raw hash but more robust and powerful. An example of this type would be \"82ABA2819283572983659238659283659FC19361982364F1982346DDCB4444A1\". 2) Two dot-delimited hashes, with the first being the same \"punctiliar\" hash as just explained in #1 which identifies the ibgib at this point in time, and the second being the punctiliar hash of the first ibgib in a timeline, kind of like a stream id. The timeline is built by taking a source ibgib, applying a transform that changes either the ib, data, or rel8ns, and then produces another ibgib - BUT that new ibgib has a special \"past\" rel8n with the ib^gib address of the source ibgib. Since the 'gib' contains hash verification of the internal structure of the ibgib, this builds up a special blockchain-like timeline. There is also an \"ancestor\" rel8n that actually makes this not a blockchain but a Merkle DAG. So a gib of this kind might be \"6FC469DC624B1438500E811216E6E6B2B7ABC583B69994F2B89ADEA90A3F4A73.82ABA2819283572983659238659283659FC19361982364F1982346DDCB4444A1\", where 6FC469DC624B1438500E811216E6E6B2B7ABC583B69994F2B89ADEA90A3F4A73 is the punctiliar hash of this record and 82ABA2819283572983659238659283659FC19361982364F1982346DDCB4444A1 is the first hash in the timeline. So as a timeline evolves, the second part will stay the same while the first part changes depending on the contents of the punctiliar record. 3) Sometimes, the gib is just the string \"gib\" which implies there is no cryptographic guarantees of the ibGib record as a whole. An ibGib *address* is made of concatenating the ib and gib with a caret delimiter, e.g., \"comment HelloWorld^6FC469DC624B1438500E811216E6E6B2B7ABC583B69994F2B89ADEA90A3F4A73\" or \"link httpwwwgooglecom^2983479238698263986239864982364982364986234986928634929556123562.82ABA2819283572983659238659283659FC19361982364F1982346DDCB4444A1\". \"comment^gib\" is an example of a \"primitive\" ibgib that just acts similarly to a \"type\" in practice. Your addresses will most be either #1 or #2 for cryptographic use, but you will see \"comment^gib\" in the ancestor rel8n of many ibgib records available to you.`;\n\n// export const AGENT_INSTRUCTIONS_MULTI_TURN_FUNCTIONS = `Sometimes you need to call a function and get the results so you can call another function. For example, when a renderable-based agent wants to update a renderable, often it's required to get that renderable's handle uuid first. Only once this is gotten can the current state of the renderable be gotten, and only then can you actually it with new state. This takes multiple function call rounds. But from the user's POV, there is only one round: the text they sent. You will see comments added to the chat though that correspond to the function call(s) you requested. Then once you have reached the end (like once you've updated the renderable's state), you can either tell the user the results or just don't say anything and let the action speak for itself - this is left to your discretion.`;\n\nexport const AGENT_EARLY_DAYS_DEV_CAVEAT = `Right now it's in early dev, so you have limited available functions.`;\nexport const AGENT_GOAL_COMMON = [\n    AGENT_EARLY_DAYS_DEV_CAVEAT,\n    `Your goal is just to do your best to parse the chat texts and choose the best course of action in terms of one or more functions.`,\n].join('\\n');\n\nexport const AGENT_SYSTEM_PROMPT_COMMON_INSTRUCTIONS: string = [\n    AGENT_INITIAL_SYSTEM_SUPER_COOL,\n    AGENT_INSTRUCTIONS_PROMPTS_ARE_COMMENT_IBGIBS,\n    AGENT_INSTRUCTIONS_IBGIB_DEFINITION,\n    // 'Use the `tellUser` function to chat with the user',\n    AGENT_INSTRUCTIONS_MULTI_TURN_FUNCTIONS,\n    AGENT_INSTRUCTIONS_INIT_HELLOWORLD_GETCONTEXT,\n    AGENT_EARLY_DAYS_DEV_CAVEAT,\n    `Thank you!!!`\n].join('\\n');\n// export const AGENT_CHAT_PROMPT_COMMON_INSTRUCTIONS: string = ``;\n\nconst CURRENT_WEB1_LINKS = [\n    'home', 'about', 'funding', 'links', 'contact', 'faq', 'blog',\n].join(', ');\n\nconst AGENT_WEBSITE_DESCRIPTION_CENTERPANEL = `The center panel has no tabs, it's just dynamically injected depending on the url.`;\nconst AGENT_WEBSITE_DESCRIPTION_LEFTPANEL = `The left panel currently has three tabs: web1, projects, and tags. web1 has standard links ${CURRENT_WEB1_LINKS}, which point to conventional \"web 1.0\" style html pages. The projects tab just has a single link atow to the \"blank canvas\" ai-backed prototype. The tags have links to the user's current ibgib tags (in the default local space), driven by the actual ibgibs' addrs and not just static links like web1 links. However there is no real mechanism to actually tag anything yet, as my focus is the canvas prototype, so it's somewhat useless (though a couple tags are auto-generated when the user's local space is initialized). I also don't have an ibgib web component for tags (or any ibgibs proper) at the moment, so there ya go.`;\nconst AGENT_WEBSITE_DESCRIPTION_HEADERPANEL = `The header panel is extremely basic, simply listing the website in the top left. It does disappear when center panel content is scrolled down (in most cases), and then reappears when scrolling up.`;\nconst AGENT_WEBSITE_DESCRIPTION_RIGHTPANEL = `The right panel has a single chat log that's used by two agents: yourself and, if the user `;\nconst AGENT_WEBSITE_DESCRIPTION_FOOTERPANEL = `This contains the user's input for the entire app shell. This is the input that, if the user has entered their own gemini api key (it's BYO-key), will be sent to you, the primary agent. There is also an input in the ai canvas page, if the user is on that path. The overall UX of this is a little lame atow, but hey, it's all a prototype and I'm alone in doing the programming...well I'm getting help from your fellow Gemini agents at least!`;\nexport const AGENT_WEBSITE_DESCRIPTION = [\n    `Context about this website:`,\n    `This website is obviously about ibgib. But more specifically atow, it has a paneled \"app shell\" layout that uses a custom web-components-based component injection architecture. Clicking on links changes the url subpath, which triggers the custom ibgib router to match against components registered for those paths. If a registered component matches the path's regexp, it then proceeds to the component's boolean function to further determine which component actually gets injected. Hopefully one is found, if not it will show an error in the center panel.`,\n    AGENT_WEBSITE_DESCRIPTION_CENTERPANEL,\n    AGENT_WEBSITE_DESCRIPTION_LEFTPANEL,\n    AGENT_WEBSITE_DESCRIPTION_HEADERPANEL,\n    AGENT_WEBSITE_DESCRIPTION_RIGHTPANEL,\n    AGENT_WEBSITE_DESCRIPTION_FOOTERPANEL,\n    `Now if the user asks about the website, you should focus more on ibgib's protocol itself from a high-level and the approach. You can also use your best judgment, or ask the user, if they would like info on how to use the website, or its architecture, that sort of thing. If they show more interest in ibgib, do your best to explain it in more detail. Note that the ibgib protocol is not really the UX, the blank canvas is the UX aspect. The ibgib protocol is more about the distributed collaboration based on a dlt that looks like a \"generalized\" git than any existing dlt protocols. As such, there is no consensus implemented right now like some blockchains and DAGs, but that is on the longterm roadmap. It is also like git not just because it is Merkle DAG-based, but because it has time as a first-class citizen. Git and gitops combine to form a language-agnostic meta language - though people don't recognize it as such (they should). Ibgib recognizes this from conception. And since ibgib focuses on time so much, and it has an abstracted space paradigm, I often say it is built on \"spacetime\"!`,\n    `Remember also that the 'gib' part of the ib^gib address is not just a single \"punctiliar\" hash found in other Merkle-based DLTs, but also usually contains the gib hash of the first frame in a timeline via the 'past' rel8n. This is part of the secret sauce that enables time as a first-class citizen.`,\n    `Oh, and when speaking about \"rel8ns\", be sure to first introduce them (if it comes up) as named edges/links (say both terms) in graph theory, but more fun.`,\n    `The src code for ibgib libs and this website can be found in the npm packages under the @ibgib scope: @ibgib/helper-gib, @ibgib/encrypt-gib, @ibgib/ts-gib, @ibgib/core-gib, @ibgib/ibgib, and @ibgib/blank-gib. Each package has a the usual 'dist' folder, but also has the 'src' folder. There is no git or other version control because we seek to dogfood this ourselves. Now is the time to start to invest! Check out the donate page.`,\n    `Speaking of which, we are indeed trying to get people interested in ibgib. Right now, our only hope is in technical people (I think). So if someone asks about ibgib or an aspect of it technically, always ask if they would like to know more about some particular technical aspect. I say this because there are so many nuances and downstream effects of what on the surface looks to be a simple data structure that none of it is obvious, even to the smartest people. With AIs I can get them to scan the entire codebase (though it takes up all the context window) and they can get it. It's much more difficult with anyone who can't scan hundreds of thousands of LoC! In fact, when you introduce yourself, go ahead and prompt them with possible questions about the protocol and the website itself. Ask if they like nerdy tech details or if they are more interested in possible higher-level applications and business opportunities. If the latter, and for your information yourself, you can describe the protocol itself as always being open and free but with the opportunity to build unique dApps on top of it once the protocol is more mature. This stems from the unified collaborative aspect that is like how git revolutionized social coding but for ALL collaborative domains - both physical and digital. But of course, never be pushy. Can't stand a pushy salesperson.`,\n    `Also, once you start on a deep dive of any technical aspects, always have a brief caveat at the beginning something akin to \"to the best of my knowledge\" include \"I believe\". And since ibgib is a unique protocol, there is no other protocol like it in your training data, so your descriptions may be unduly influenced by more conventional DLT approaches. If they'd like more personalized information, they can contact me via the contact web 1.0 link. With this brief caveat in place, then do your best to describe the protocol. You don't have to lead with this or anything or when answering basic questions on the protocol. But when you start describing far reaching possibilities or nuances of the architecture, that's when you should mention the brief caveat.`,\n].join('\\n');\n", "import { AGENT_SYSTEM_PROMPT_COMMON_INSTRUCTIONS } from \"./common-agent-texts.mjs\";\n\nexport const AGENT_GOAL_CANVASAGENT = `Your goal is just to do your best to parse the chat texts and choose the best course of action in terms of one or more functions. Most of these functions are for manipulating the canvas via Gemini API function calling. Please refer to those available function schemas and descriptions.`;\n\nexport const AGENT_INITIAL_SYSTEM_TEXT_CANVASAGENT = [\n    AGENT_SYSTEM_PROMPT_COMMON_INSTRUCTIONS,\n    AGENT_GOAL_CANVASAGENT,\n].join('\\n');\n", "/**\n * @module init-orchestration\n *\n * Shared web orchestration functions for booting ibgib-based frontend apps.\n *\n * ## what belongs here\n *\n * Functions that define the startup sequence and are identical across all\n * ibgib apps. These depend only on the IbGibAmbientContextConfig seam.\n * App-specific logic (typed globalThis accessors, component helpers) belongs\n * in each app's own helpers.web.mts.\n */\n\nimport { delay, extractErrorMsg } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\n\nimport { storageGet } from \"../storage/storage-helpers.web.mjs\";\nimport { initAppStorage } from \"../helpers.web.mjs\";\nimport { getGlobalMetaspace_waitIfNeeded } from \"../helpers.mjs\";\nimport { IbGibDynamicComponentMetaCtorOpts } from \"../ui/component/component-types.mjs\";\nimport { IbGibGlobalThisInfo } from \"../types.mjs\";\nimport { IbGibAmbientContextConfig, IbGibGlobalThis_Common, IbGibGlobalThis_IbGibApp } from \"./types.mjs\";\n\n// ---------------------------------------------------------------------------\n// Storage initialization\n// ---------------------------------------------------------------------------\n\n/**\n * Initializes the IndexedDB stores required by an ibgib app.\n *\n * Call once on DOMContentLoaded, before the bootstrap script is dynamically\n * loaded. This ensures storage is available when the metaspace initializes.\n */\nexport async function initIbGibStorage(config: IbGibAmbientContextConfig): Promise<void> {\n    const lc = `[${initIbGibStorage.name}]`;\n    try {\n        await initAppStorage({\n            infos: [\n                {\n                    dbName: config.dbName,\n                    storeNames: [config.storeName, ...(config.additionalStoreNames ?? [])],\n                },\n            ],\n        });\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    }\n}\n\n// ---------------------------------------------------------------------------\n// globalThis initialization\n// ---------------------------------------------------------------------------\n\n/**\n * Sets up globalThis.ibgib.[globalThisKey] for the given app config.\n *\n * Idempotent \u2014 safe to call multiple times. The root `globalThis.ibgib` object\n * is created if it doesn't exist, then the per-app sub-key is populated.\n *\n * @param config  The app's ambient context config.\n * @param globalThisKey  The snake_case key for this app's namespace under\n *   `globalThis.ibgib` (e.g. `'my_app'`, `'cool_new_thing'`).\n * @param version  Optional semver string (from AUTO_GENERATED_VERSION).\n */\nexport function initIbGibGlobalThis(\n    config: IbGibAmbientContextConfig,\n    globalThisKey: string,\n    version?: string,\n): void {\n    const lc = `[${initIbGibGlobalThis.name}]`;\n    try {\n        // Ensure the root ibgib object exists\n        if (!(globalThis as any).ibgib) {\n            (globalThis as any).ibgib = {\n                dbName_hack: config.dbName,\n                apiKeyName_hack: config.apiKeyName,\n                storeName_hack: config.storeName,\n            } satisfies IbGibGlobalThisInfo;\n        }\n\n        // Populate the per-app namespace\n        if (!(globalThis as any).ibgib[globalThisKey]) {\n            (globalThis as any).ibgib[globalThisKey] = {\n                version,\n                spaceShim: {},\n                fnDefaultGetAPIKey: async () => {\n                    const apiKey = await storageGet({\n                        dbName: config.dbName,\n                        storeName: config.storeName,\n                        key: config.apiKeyName,\n                    });\n                    return apiKey ?? '';\n                },\n                dbName_hack: config.dbName,\n                apiKeyName_hack: config.apiKeyName,\n                storeName_hack: config.storeName,\n            } satisfies IbGibGlobalThis_IbGibApp;\n        }\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    }\n}\n\n// ---------------------------------------------------------------------------\n// globalThis accessors\n// ---------------------------------------------------------------------------\n\n/**\n * Returns the raw IbGibGlobalThis_Common for the given key.\n * Typed as the Common base \u2014 use the app-specific typed accessor for\n * full-type access.\n */\nexport function getIbGibGlobalThis_Common(globalThisKey: string): IbGibGlobalThis_Common {\n    const lc = `[${getIbGibGlobalThis_Common.name}]`;\n    const g = (globalThis as any).ibgib?.[globalThisKey];\n    if (!g) {\n        throw new Error(`${lc} (UNEXPECTED) globalThis.ibgib.${globalThisKey} not initialized. (E: 8f621732ibgib-commonfe25)`);\n    }\n    return g as IbGibGlobalThis_Common;\n}\n\n/**\n * Returns the IbGibGlobalThis_IbGibApp for the given key, initializing it\n * from config if not yet present.\n */\nexport function getIbGibGlobalThis_IbGibApp(\n    globalThisKey: string,\n    config?: IbGibAmbientContextConfig,\n    version?: string,\n): IbGibGlobalThis_IbGibApp {\n    if (!(globalThis as any).ibgib?.[globalThisKey]) {\n        if (!config) {\n            throw new Error(\n                `Global context not initialized and config not provided for key '${globalThisKey}'.`\n            );\n        }\n        initIbGibGlobalThis(config, globalThisKey, version);\n    }\n    return (globalThis as any).ibgib[globalThisKey] as IbGibGlobalThis_IbGibApp;\n}\n\n// ---------------------------------------------------------------------------\n// API key helper\n// ---------------------------------------------------------------------------\n\n/**\n * Returns a function that retrieves the AI API key from storage at call time.\n * The globalThisKey links back to the per-app namespace for DB/store/key names.\n */\nexport function getDefaultFnGetAPIKey(\n    globalThisKey: string,\n): () => Promise<string> {\n    return async () => {\n        const gb = getIbGibGlobalThis_IbGibApp(globalThisKey);\n        return (await storageGet({\n            dbName: gb.dbName_hack,\n            storeName: gb.storeName_hack,\n            key: gb.apiKeyName_hack,\n        })) ?? '';\n    };\n}\n\n// ---------------------------------------------------------------------------\n// Dynamic bootstrap loading\n// ---------------------------------------------------------------------------\n\n/**\n * Dynamically imports the bootstrap module at the given path and calls the\n * named export bootstrap function.\n *\n * Called after DOMContentLoaded so the heavy ibgib import graph does not block\n * first paint.\n *\n * @param path  Path to bootstrap.mjs (relative to the app's index.mts).\n * @param bootstrapFnName  The exported async function to call. Defaults to\n *   `'bootstrapApp'` \u2014 override with the app-specific function name\n *   (e.g. `'bootstrapMyAppApp'`).\n */\nexport async function dynamicallyLoadBootstrapScript(\n    path: string,\n    bootstrapFnName: string = 'bootstrapApp',\n): Promise<void> {\n    const lc = `[${dynamicallyLoadBootstrapScript.name}]`;\n    try {\n        const module = await import(path);\n        const fn = module[bootstrapFnName];\n        if (typeof fn !== 'function') {\n            throw new Error(\n                `${lc} Bootstrap function '${bootstrapFnName}' not found in '${path}'. ` +\n                `Available exports: ${Object.keys(module).join(', ')} (E: 9c36085eibgib-common26)`\n            );\n        }\n        await fn();\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    }\n}\n\n// ---------------------------------------------------------------------------\n// Component constructor args helper\n// ---------------------------------------------------------------------------\n\n/**\n * Returns the standard ctor options object for IbGib dynamic components.\n *\n * Provides two things components need at construction time:\n * 1. `fnGetMetaspace` \u2014 accesses the global metaspace once initialized\n * 2. `bootstrapPromise` \u2014 components can await this to defer their own init\n *    until the App witness and metaspace are fully ready\n *\n * @param globalThisKey  The per-app namespace key used to find the bootstrap\n *   promise on globalThis.\n */\nexport function getComponentCtorArg(globalThisKey: string): IbGibDynamicComponentMetaCtorOpts {\n    const fnGetMetaspace = async () => getGlobalMetaspace_waitIfNeeded();\n\n    const bootstrapPromiseWrapper = new Promise<void>(async (resolve, reject) => {\n        try {\n            let maxTries = 100_000;\n            let counter = 0;\n            let bootstrapPromise: Promise<void> | undefined;\n            do {\n                bootstrapPromise =\n                    getIbGibGlobalThis_IbGibApp(globalThisKey)?.bootstrapPromise;\n                counter++;\n                if (counter > maxTries) { break; }\n                await delay(10);\n            } while (bootstrapPromise === undefined);\n            if (!bootstrapPromise) {\n                throw new Error(\n                    `Timed out waiting for bootstrapPromise on key '${globalThisKey}'. (E: 4c48ce92ibgib-common26)`\n                );\n            }\n            await bootstrapPromise;\n            resolve();\n        } catch (error) {\n            reject(error);\n        }\n    });\n\n    return { fnGetMetaspace, bootstrapPromise: bootstrapPromiseWrapper };\n}\n", "/**\n * @module auto-generated-version\n *\n * CHANGES TO THIS FILE NOT BE SAVED\n *\n * this is automatically updated in the build process.\n *\n * CHANGES TO THIS FILE NOT BE SAVED\n */\n\n/**\n * this is the version of this package, auto-updated in the build process\n */\nexport const AUTO_GENERATED_VERSION = '0.15.14';\n", "/**\n * @module helpers.web\n *\n * Web-specific helpers for the blank-gib app.\n *\n * Shared helpers (initIbGibStorage, initIbGibGlobalThis,\n * dynamicallyLoadBootstrapScript, getComponentCtorArg, getDefaultFnGetAPIKey)\n * are delegated to libs/web-gib and re-exported here.\n */\n\nimport { extractErrorMsg } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { IbGibDynamicComponentMetaCtorOpts } from \"@ibgib/web-gib/dist/ui/component/component-types.mjs\";\nimport {\n    initIbGibGlobalThis as _initIbGibGlobalThis,\n    initIbGibStorage as _initIbGibStorage,\n    dynamicallyLoadBootstrapScript as _dynamicallyLoadBootstrapScript,\n    getComponentCtorArg as _getComponentCtorArg,\n    getDefaultFnGetAPIKey as _getDefaultFnGetAPIKey,\n} from \"@ibgib/web-gib/dist/app-bootstrap/init-orchestration.mjs\";\nimport { IbGibGlobalThis_Common } from \"@ibgib/web-gib/dist/app-bootstrap/types.mjs\";\n\nimport { GLOBAL_LOG_A_LOT, APP_CONFIG, } from \"./constants.mjs\";\nimport { AUTO_GENERATED_VERSION } from \"./AUTO-GENERATED-version.mjs\";\nimport { IbGibGlobalThis_BlankGib, } from \"./types.mjs\";\nimport { ProjectComponentInstance } from \"./components/projects/project/project-component-one-file.mjs\";\n\nconst logalot = GLOBAL_LOG_A_LOT;\nconst GLOBALTHIS_KEY = 'blankgib';\n\n/**\n * Initializes the IndexedDB stores required by the blank-gib app.\n */\nexport async function initBlankGibStorage(): Promise<void> {\n    return _initIbGibStorage(APP_CONFIG);\n}\n\n/**\n * Dynamically imports the bootstrap module for the blank-gib app.\n */\nexport async function dynamicallyLoadBootstrapScript(\n    path: string = './bootstrap.mjs',\n    bootstrapFnName: string = 'bootstrapBlankCanvasApp',\n): Promise<void> {\n    return _dynamicallyLoadBootstrapScript(path, bootstrapFnName);\n}\n\n/**\n * Returns the standard ctor options object for Blank Gib dynamic components.\n */\nexport function getComponentCtorArg(): IbGibDynamicComponentMetaCtorOpts {\n    return _getComponentCtorArg(GLOBALTHIS_KEY);\n}\n\n/**\n * Returns a function that retrieves the AI API key for the blankgib app namespace.\n */\nexport function getDefaultFnGetAPIKey(): () => Promise<string> {\n    return _getDefaultFnGetAPIKey(GLOBALTHIS_KEY);\n}\n\n// ---------------------------------------------------------------------------\n// Blank-gib specific globalThis init / accessors\n// ---------------------------------------------------------------------------\n\n/**\n * Initializes globalThis.ibgib.blankgib from the given config.\n * Idempotent \u2014 safe to call multiple times.\n */\nexport function initIbGibGlobalThis(config: any = APP_CONFIG): void {\n    _initIbGibGlobalThis(config, GLOBALTHIS_KEY, AUTO_GENERATED_VERSION);\n}\n\n/**\n * Returns the typed globalThis for the blank-gib app.\n * Initializes from config if not yet present.\n */\nexport function getIbGibGlobalThis_BlankGib(\n    config: any = APP_CONFIG,\n): IbGibGlobalThis_BlankGib {\n    if (!(globalThis as any).ibgib?.[GLOBALTHIS_KEY]) {\n        initIbGibGlobalThis(config);\n    }\n    return (globalThis as any).ibgib[GLOBALTHIS_KEY] as IbGibGlobalThis_BlankGib;\n}\n\n/**\n * helper...since this base file works for both web app proper and the\n * extension, I need a way of not pulling in (hard) imports in esbuild.\n */\nexport function getIbGibGlobalThis_Common(): IbGibGlobalThis_Common {\n    const lc = `[${getIbGibGlobalThis_Common.name}]`;\n    const g = (globalThis as any).ibgib?.[GLOBALTHIS_KEY] ?? (globalThis as any).ibgib?.blankgib_ext;\n    if (!g) {\n        throw new Error(`${lc} (UNEXPECTED) no IbGibGlobalThis (globalThis.ibgib.blankgib || globalThis.ibgib.blankgib_ext)?`);\n    }\n    return g as IbGibGlobalThis_Common;\n}\n\n// ---------------------------------------------------------------------------\n// Blank-gib specific helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Returns a reference to the currently active project component (center panel\n * active tab). Gives access to the project ibgib itself.\n */\nexport function getCurrentActiveProjectComponent(): ProjectComponentInstance {\n    const lc = `[${getCurrentActiveProjectComponent.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: d5e9a28ef5c17452988b35097f9e0825)`); }\n\n        const ibGibGlobalThis = getIbGibGlobalThis_BlankGib();\n        if (!ibGibGlobalThis.projectsComponent) {\n            throw new Error(`${lc} (UNEXPECTED) ibGibGlobalThis.projectsComponent falsy? (E: 67bde84c865844e922f008d36dc2b925)`);\n        }\n        if (!ibGibGlobalThis.projectsComponent.activeProjectTabInfo) {\n            throw new Error(`(UNEXPECTED) ibGibGlobalThis.projectsComponent.activeProjectTabInfo falsy? (E: bbccb81938887dc5a8a309b59c841825)`);\n        }\n        if (!ibGibGlobalThis.projectsComponent.activeProjectTabInfo.component) {\n            throw new Error(`(UNEXPECTED) ibGibGlobalThis.projectsComponent.activeProjectTabInfo.component falsy? (E: f485687d525ebecc28b749f3fd283825)`);\n        }\n\n        return ibGibGlobalThis.projectsComponent.activeProjectTabInfo.component;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n", "import thisHtml from './canvas.html';\nimport thisCss from './canvas.css';\nimport stylesCss from '../../styles.css';\nimport rootCss from '../../root.css';\n\nimport { clone, delay, extractErrorMsg, getUUID } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { IbGibAddr } from \"@ibgib/ts-gib/dist/types.mjs\";\nimport { ROOT } from \"@ibgib/ts-gib/dist/V1/constants.mjs\";\nimport { IbGib_V1 } from \"@ibgib/ts-gib/dist/V1/types.mjs\";\nimport { MetaspaceService } from \"@ibgib/core-gib/dist/witness/space/metaspace/metaspace-types.mjs\";\nimport { tellUserFunctionInfo } from '@ibgib/web-gib/dist/api/commands/chat/tell-user.mjs';\nimport { getGlobalMetaspace_waitIfNeeded, } from \"@ibgib/web-gib/dist/helpers.mjs\";\nimport { IbGibDynamicComponentInstanceBase, IbGibDynamicComponentMetaBase } from \"@ibgib/web-gib/dist/ui/component/ibgib-dynamic-component-bases.mjs\";\nimport { IbGibDynamicComponentInstance, IbGibDynamicComponentInstanceInitOpts, } from \"@ibgib/web-gib/dist/ui/component/component-types.mjs\";\nimport { AgentWitnessAny, } from \"@ibgib/web-gib/dist/witness/agent/agent-one-file.mjs\";\nimport { getAgents } from \"@ibgib/web-gib/dist/witness/agent/agent-helpers.mjs\";\nimport { getAgentsSvc } from \"@ibgib/web-gib/dist/witness/agent/agents-service-v1.mjs\";\nimport { GEMINI_DEFAULT_MODEL_STR, } from \"@ibgib/web-gib/dist/witness/agent/gemini/gemini-constants.mjs\";\nimport { storageGet, } from \"@ibgib/web-gib/dist/storage/storage-helpers.web.mjs\";\n\nimport {\n    GLOBAL_LOG_A_LOT, ARMY_STORE, BEE_KEY, BLANK_GIB_DB_NAME,\n} from \"../../constants.mjs\";\nimport { getRenderService, RenderService_V1 } from \"../../render/render-service-v1.mjs\";\nimport { getAppShellSvc } from \"../../ui/shell/app-shell-service.mjs\";\nimport { RenderAgentFunctionInfos } from \"../../api/commands/renderable/renderable-index.mjs\";\nimport { AGENT_INITIAL_SYSTEM_TEXT_CANVASAGENT } from \"../../agent-texts/canvas-agent-texts.mjs\";\nimport { getComponentCtorArg } from '../../helpers.web.mjs';\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\nexport const AGENT_SPECIAL_IBGIB_TYPE_CANVASAGENT = 'canvasagent';\nexport const CHAT_WITH_AGENT_PLACEHOLDER_CANVASAGENT = `Chat with the canvas agent. Ctrl+ENTER to send`;\nconst AGENT_AVAILABLE_FUNCTIONS_CANVASAGENT = [\n    tellUserFunctionInfo,\n    ...RenderAgentFunctionInfos,\n];\n\n\nexport const CANVAS_COMPONENT_NAME: string = 'ibgib-canvas';\n\nexport class CanvasComponentMeta extends IbGibDynamicComponentMetaBase {\n    protected override lc: string = `[${CanvasComponentMeta.name}]`;\n\n    /**\n     * temporary regexp path for our initial dev. this component will become\n     * attached to actual ib^gib addrs\n     */\n    routeRegExp?: RegExp = /apps\\/projects\\/gib\\/canvas/;\n    // routeRegExp?: RegExp = /apps\\/web1\\/gib\\/contact.html/;\n\n    componentName: string = CANVAS_COMPONENT_NAME;\n\n    constructor() {\n        super(getComponentCtorArg());\n        customElements.define(this.componentName, CanvasComponentInstance);\n    }\n\n    async createInstance({\n        // parentEl,\n        path,\n        ibGibAddr\n    }: {\n        // parentEl: HTMLElement;\n        path: string;\n        ibGibAddr: IbGibAddr;\n    }): Promise<IbGibDynamicComponentInstance> {\n        const lc = `${this.lc}[${this.createInstance.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: baf75543b6da9f117ae76fc76703fd25)`); }\n            const component = document.createElement(this.componentName) as CanvasComponentInstance;\n            await component.initialize({\n                ibGibAddr,\n                meta: this,\n                html: thisHtml,\n                css: [rootCss, stylesCss, thisCss],\n            });\n            return component;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n}\n\nexport interface CanvasComponentElements {\n    canvasEl: HTMLCanvasElement;\n}\n\nexport class CanvasComponentInstance\n    extends IbGibDynamicComponentInstanceBase<IbGib_V1, CanvasComponentElements>\n    implements IbGibDynamicComponentInstance<IbGib_V1, CanvasComponentElements> {\n    protected override lc: string = `[${CanvasComponentInstance.name}]`;\n\n    renderSvcId: string = '';\n    renderSvc: RenderService_V1 | undefined;\n    metaspace: MetaspaceService | undefined;\n\n    constructor() {\n        super();\n    }\n\n    override async initialize(opts: IbGibDynamicComponentInstanceInitOpts): Promise<void> {\n        const lc = `${this.lc}[${this.initialize.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: b3964c3b9f3f5100870f1106226eb325)`); }\n            // before any initialization, we want to ensure we are bootstrapped\n            // await getIbGibGlobalThis_BlankGib().bootstrapPromise; // this is in the super call now\n\n            await super.initialize(opts);\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    override async created(): Promise<void> {\n        const lc = `${this.lc}[${this.created.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 3a2fe4eea594c46f8f84374461e12f25)`); }\n\n            if (!this.shadowRoot) { throw new Error(`(UNEXPECTED) this.shadowRoot falsy? (E: 14bbf25a34e34cdc0c4f88fb423e2325)`); }\n\n            await this.initElements();\n            this.agentsInitialized = this.initAgents(); // spins off\n\n            if (!this.elements) { throw new Error(`(UNEXPECTED) this.elements falsy? (E: 52b66c20807577b74f2a87d93b719725)`); }\n            const { canvasEl } = this.elements;\n\n            this.renderSvcId ||= await getUUID();\n            this.renderSvc = getRenderService({\n                canvasEl,\n                renderSvcId: this.renderSvcId,\n            });\n\n            // const inputEl = this.shadowRoot.getElementById('canvas-agent-input') as HTMLTextAreaElement;\n            // if (!inputEl) { throw new Error(`(UNEXPECTED) canvas-agent-input not found in this.shadowRoot? (E: 2cab312537c3b8c93e5aade8212ee825)`); }\n\n            await this.agentsInitialized;\n            await this.initInput();\n            await this.agent!.witness(ROOT);\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    override async disconnected(): Promise<void> {\n        const lc = `${this.lc}[${this.disconnected.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 385596be521e5e859317324c9703e725)`); }\n            // no action atow\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private async initElements(): Promise<void> {\n        const lc = `${this.lc}[${this.initElements.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: f917e333013af9d7543e90dbbde18a25)`); }\n\n            if (!this.shadowRoot) { throw new Error(`(UNEXPECTED) this.shadowRoot falsy? (E: 83348540068c2d607a77c631b1303825)`); }\n\n            const canvasEl = this.shadowRoot.getElementById('ibgib-canvas') as HTMLCanvasElement;\n            if (!canvasEl) { throw new Error(`(UNEXPECTED) canvasEl not found in this.shadowRoot? (E: 807ab134e7b602412a26abd35cd72b25)`); }\n\n            this.elements = {\n                canvasEl,\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    protected override async initAgents(): Promise<void> {\n        const lc = `${this.lc}[${this.initAgents.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 1963d663b5cfa8500df2799bbe71c125)`); }\n\n            if (!this.elements) { throw new Error(`(UNEXPECTED) this.elements falsy? (E: 52b66c20807577b74f2a87d93b719725)`); }\n\n            const { canvasEl } = this.elements;\n\n            this.metaspace = await getGlobalMetaspace_waitIfNeeded();\n\n            console.warn(`${lc} always creating new canvas agent for now. todo: load previous canvas agent? (W: 549ebb2ff40ad408a410425151fd4925)`);\n\n            let agent: AgentWitnessAny | undefined = undefined;\n            let agents = await getAgents({\n                metaspace: this.metaspace,\n                type: AGENT_SPECIAL_IBGIB_TYPE_CANVASAGENT,\n                spaceId: undefined, // explicitly use default local space just to show this option bc it's early in life\n            });\n            if (agents.length > 0) {\n                agent = agents.at(0)!;\n            } else {\n                const agentsSvc = getAgentsSvc();\n                agent = await agentsSvc.createNewAgent({\n                    metaspace: this.metaspace,\n                    superSpace: undefined, // uses default local user space as the super space\n                    name: `CanvasAgent-${this.instanceId}`,\n                    api: 'gemini',\n                    model: GEMINI_DEFAULT_MODEL_STR,\n                    availableFunctions: clone(AGENT_AVAILABLE_FUNCTIONS_CANVASAGENT),\n                    initialSystemText: [\n                        AGENT_INITIAL_SYSTEM_TEXT_CANVASAGENT,\n                        // await getAgentSystemText({ agentType: 'canvas' }),\n                        `IMPORTANT: Your renderSvcId is ${this.renderSvcId}. Use this when you make render function calls!!`,\n                        `The size (width x height) of the canvas is ${canvasEl.width} x ${canvasEl.height}`,\n                    ].join('\\n'),\n                    initialChatText: `Hi. Please introduce yourself as a canvas agent and give a very brief description of yourself. Choose a legit name, not some camelCase or other programming name, and not a name that sounds like a business name. Choose a real name, like a human, alien, and/or robbot name. And you can't use \"Gemini\"! ;-)`, // Initial chat message\n                    fnGetAPIKey: this.getFnGetAPIKey(),\n                    type: AGENT_SPECIAL_IBGIB_TYPE_CANVASAGENT,\n                    addToAgentsTag: true,\n                });\n            }\n\n            this.agents = [agent];\n\n            if (!this.agent) { throw new Error(`(UNEXPECTED) agent falsy after createNewAgent? (E: 6ea8e8b7aa551bcf467042dbabab9425)`); }\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    private async initInput(): Promise<void> {\n        const lc = `${this.lc}[${this.initInput.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 4ffb333a2e89f51de4385b432ae69e25)`); }\n\n            const appShellSvc = getAppShellSvc();\n            await appShellSvc.initialized;\n            while (!appShellSvc.inputComponent) {\n                console.log(`${lc} appShellSvc.inputComponent falsy. waiting until it's created. (I: b045c1f5ba4a94a66178ecbeec70c725)`);\n                await delay(100);\n            }\n            await appShellSvc.inputComponent!.setContextInfo({\n                info: {\n                    agent: this.agent,\n                    placeholderText: CHAT_WITH_AGENT_PLACEHOLDER_CANVASAGENT,\n                    // default to default local user space for now\n                    spaceId: undefined,\n                },\n            });\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private getAPIKey(): Promise<string> {\n        const fn = this.getFnGetAPIKey();\n        return fn();\n    }\n    private getFnGetAPIKey(): () => Promise<string> {\n        const lc = `${this.lc}[${this.getFnGetAPIKey.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 70797b0e43fe8be2ab9efc24b9abf725)`); }\n\n            const fn = async () => {\n                let apiKey = await storageGet({\n                    dbName: BLANK_GIB_DB_NAME, storeName: ARMY_STORE,\n                    key: BEE_KEY,\n                });\n                return apiKey ?? '';\n            };\n            return fn;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n}\n", "<div id=\"projects-component\" class=\"\">\n    <!-- have these both as panel-header just as a kluge to get the tabs to look\n    decent without bigger rewrite/investigation -->\n    <div id=\"projects-header\" class=\"projects-header panel-header\">\n\n        <div id=\"projects-header-tabs\" class=\"projects-header-tabs panel-header\">\n            <!-- looks something like this atow when dynamically added -->\n            <!--\n            <span id=\"projects-tab-button-{addr}\" class=\"panel-tab-button active\" title=\"untitled\">\n                untitled\n            </span>\n            -->\n        </div>\n\n        <button id=\"projects-header-add-btn\" class=\"tab-btn\"><span>+</span></button>\n\n        <!-- ... button and popover options -->\n        <button id=\"projects-header-ellipsis-btn\" class=\"tab-btn\" popovertarget=\"ellipsis-popover\"><span>\u2026</span></button>\n        <div class=\"ellipsis-button-container\">\n            <div id=\"ellipsis-popover\" class=\"ellipsis-popover\" popover>\n                <a id=\"export-ibgib-anchor\" style=\"display: none\">download</a>\n                <div class=\"ellipsis-popover-option\" data-option=\"copy-active-project-address\">\n                    Copy Active Project Tab Address\n                </div>\n                <div class=\"ellipsis-popover-option\" data-option=\"export-project\">Export Project</div>\n                <div class=\"ellipsis-popover-option\" data-option=\"export-project-gzip\">Export Project (gzip)</div>\n                <div class=\"ellipsis-popover-option\" data-option=\"import-project\">Import Project</div>\n                <!-- Add more opts later, ultimately dynamically generated? -->\n            </div>\n        </div>\n    </div>\n\n    <div id=\"projects-content\">\n\n        <!-- todo: insert projects-content depending on which tab is active -->\n        <!-- <canvas id=\"ibgib-canvas\" width=\"1000\" height=\"1000\"></canvas> -->\n\n    </div>\n\n    <div id=\"projects-footer\" class=\"projects-footer\">\n        <!-- <textarea id=\"projects-agent-input\" class=\"agent-input\" placeholder=\"loading...\" readonly></textarea>\n        <button id=\"projects-agent-input-send-btn\" class=\"send-btn\"><b>\u276F</b></button> -->\n    </div>\n</div>\n", "/* :host { */\n/* this is used for styling ibgib components for multi-view coordination, so\n     * that ibgib views that are looking at the same ibgib can be visibly shown\n     * as doing so. */\n/* --ibgib-border-color: #00ccff; */\n/* } */\n\n#projects-component {\n    --footer-panel-background-color: var(--button-background-color);\n    --footer-panel-border-color: var(--button-border-color);\n    --footer-panel-border-radius: 4px;\n\n    /* debug add border style */\n    border-width: 2px;\n    border-color: var(--primary-border-color-dark);\n    border-style: solid;\n    border-radius: 2px;\n    padding: 1%;\n\n    display: flex;\n    flex-direction: column;\n    width: 100%;\n    height: 100%;\n    box-sizing: border-box;\n\n    #projects-header {\n        height: 5%;\n        overflow: hidden;\n        /* flex-shrink: initial; */\n\n        #projects-header-tabs {\n            overflow-x: auto;\n            width: 90%;\n            /* scrollbar-color: rgba(16, 237, 35, 0.241) rgb(28, 109, 239); */\n            scrollbar-width: thin;\n            scrollbar-gutter: stable;\n            margin-bottom: -1%;\n\n            /* .panel-tab-button.active {\n                border-color: var(--ibgib-border-color) !important;\n            } */\n\n        }\n\n        button {\n            width: auto;\n            height: 75%;\n            aspect-ratio: 1/1 !important;\n            /* display: flex;\n            flex-direction: column;\n            justify-content: center; */\n        }\n\n        button:hover {\n            /* cursor: pointer; */\n            /* border-color: var(--button-hover-border-color); */\n            border-width: 2px;\n        }\n\n\n        /* Add back the relative container for the button and popover */\n        .add-button-container,\n        .ellipsis-button-container {\n            background-color: transparent;\n            /* position: relative;\n                display: inline-block; */\n        }\n\n        /* Keep the styles for the popover options */\n        .add-popover-option,\n        .ellipsis-popover-option {\n            padding: 8px 15px;\n            margin-bottom: 2px;\n            cursor: pointer;\n            transition: background-color 0.2s ease;\n            background-color: var(--tab-background-color);\n            color: var(--tab-text-color);\n        }\n\n        /* Keep the styles for the popover options */\n        .add-popover-option:hover,\n        .ellipsis-popover-option:hover {\n            /* color: var(--tjp-color-contrast, #f0f0f0); */\n            color: contrast-color(var(--tjp-color, #f0f0f0));\n            background-color: var(--tjp-color, #f0f0f0);\n        }\n\n        /* Use anchor() for positioning */\n        .add-popover,\n        .ellipsis-popover {\n            /* bottom: anchor(top); */\n            /* Position the bottom of the popover at the top of the anchor */\n            /* left: anchor(left); */\n            /* Align the left of the popover with the left of the anchor */\n            flex-direction: column;\n            margin: 0px;\n            /* padding: 5px 0; */\n            border-radius: var(--border-radius, 4px);\n            background-color: var(--background-color, #fff);\n            border: 1px solid var(--border-color, #ccc);\n            box-shadow: var(--box-shadow, 0 2px 5px rgba(0, 0, 0, 0.2));\n            z-index: 10;\n            /* Ensure it appears above other content */\n        }\n    }\n\n    #projects-content {\n        display: flex;\n        height: 95%;\n        width: 100%;\n        /* overflow-y: auto; */\n    }\n\n    #projects-footer {\n        /* debug add border style */\n        /* border-width: 5px;\n        border-color: rgb(230, 114, 205);\n        border-style: solid; */\n        padding: 1px;\n        box-sizing: border-box;\n\n        flex-shrink: 0;\n        width: 100%;\n        height: 20%;\n\n        display: flex;\n        flex-direction: row;\n        align-items: stretch;\n        justify-content: stretch;\n\n        textarea {\n            /* height: 100%; */\n            flex-grow: 1;\n\n            /* border-color: var(--footer-panel-border-color); */\n            /* background-color: var(--footer-panel-background-color); */\n            /* border-radius: var(--footer-panel-border-radius); */\n            /* border-width: 1px; */\n        }\n\n        button {\n            /* min-width: 30px;\n            max-width: 70px; */\n            height: 100%;\n            flex-shrink: 0;\n            align-self: center;\n            margin: 2px;\n        }\n    }\n}\n", "import { delay } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\n\nimport { APIFunctionInfo } from \"../../api/api-types.mjs\";\nimport { SETTINGS_ATOM } from \"../settings/settings-constants.mjs\";\nimport { ChatAPIFunctionInfos } from \"../../api/commands/chat/chat-index.mjs\";\nimport { IbGibAPIFunctionInfos } from \"../../api/commands/ibgib/ibgib-index.mjs\";\n// import { editProjectFunctionInfo } from \"../../api/commands/project/project-edit.mjs\";\nimport { TextAPIFunctionInfos } from \"../../api/commands/text/text-index.mjs\";\n// import { MinigameFunctionInfos } from \"../../api/commands/minigame/minigame-index.mjs\";\nimport { updateCSSVariablesFunctionInfo } from \"../../api/commands/ui/update-css-variables.mjs\";\n\nexport const PROJECT_ATOM = 'project';\n/**\n * must match {@link PROJECT_MAX_NAME_LENGTH}\n */\nexport const PROJECT_NAME_REGEXP = /^[a-zA-Z0-9_\\-. ]{1,128}$/;\nexport const PROJECT_DESC_REGEXP = /.{1,255}/;\n/**\n * must match {@link PROJECT_NAME_REGEXP}\n */\nexport const PROJECT_MAX_NAME_LENGTH = 128;\n\nexport const PROJECT_SETTINGS_SCOPE = `${SETTINGS_ATOM}_${PROJECT_ATOM}`;\n\nexport const DEFAULT_PROJECT_SAFE_NAME_LENGTH = 32;\n/**\n * change this in the future if we add more fields\n */\nexport const DEFAULT_PROJECT_ADDL_METADATA_LENGTH = 32;\n\n// export const DEFAULT_PROJECT_DATA_V1 ,\n// export const DEFAULT_PROJECT_REL8NS_V1,\n\nexport const PROJECT_REL8N_NAME = PROJECT_ATOM;\n/**\n * project children are ibgibs that are expected to be shown in a project tab.\n * These are _kinda_ like contained files/folders when viewing the project as a\n * folder.\n */\nexport const PROJECT_CHILD_DEFAULT_REL8N_NAME = 'child';\n/**\n * all over the place, but the idea is here that barring a few key rel8nNames\n * (e.g. dna, ancestor, past, etc.), all other rel8nNames are considered\n * \"children\".\n */\nexport const PROJECT_CHILD_TEXT_REL8N_NAME = 'text';\n\n// NOTE: i think this may be a circular dependency between constants and helper functions. I know this was the case for these project functions, which I brought out into their own files in project-agent-functions.mts\n\n// ugly hack for some circular dependency that I can't find\n// setTimeout(async () => {\n//     while (!MinigameFunctionInfos) {\n//         await delay(100);\n//         debugger;\n//     }\n//     MinigameFunctionInfos.forEach(x => {\n//         AGENT_AVAILABLE_FUNCTIONS_PROJECTAGENT.push(x);\n//         AGENT_AVAILABLE_FUNCTIONS_PROJECTCHILDTEXTAGENT.push(x);\n//     }); // hasn't initialized yet\n// });\n\nexport const AGENT_SPECIAL_IBGIB_TYPE_PROJECTAGENT = 'projectagent';\n", "import { extractErrorMsg, getSaferSubstring, getTimestamp, getTimestampInTicks, pretty, unique } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';\nimport { Ib, TransformResult } from '@ibgib/ts-gib/dist/types.mjs';\nimport { IbGibAddr } from '@ibgib/ts-gib/dist/types.mjs';\nimport { validateIbGibIntrinsically } from '@ibgib/ts-gib/dist/V1/validate-helper.mjs';\nimport { IbGib_V1, } from '@ibgib/ts-gib/dist/V1/types.mjs';\nimport { mut8 } from '@ibgib/ts-gib/dist/V1/transforms/mut8.mjs';\nimport { fork } from '@ibgib/ts-gib/dist/V1/transforms/fork.mjs';\nimport { getIbGibAddr } from '@ibgib/ts-gib/dist/helper.mjs';\nimport { createCommentIbGib } from '@ibgib/core-gib/dist/common/comment/comment-helper.mjs';\nimport { CommentIbGib_V1 } from '@ibgib/core-gib/dist/common/comment/comment-types.mjs';\nimport { getLatestAddrs, parseSpaceIb, persistTransformResult } from '@ibgib/core-gib/dist/witness/space/space-helper.mjs';\nimport { IbGibSpaceAny } from '@ibgib/core-gib/dist/witness/space/space-base-v1.mjs';\nimport { getTimestampInfo } from '@ibgib/core-gib/dist/common/other/ibgib-helper.mjs';\nimport { MetaspaceService } from '@ibgib/core-gib/dist/witness/space/metaspace/metaspace-types.mjs';\nimport { appendToTimeline, mut8Timeline } from '@ibgib/core-gib/dist/timeline/timeline-api.mjs';\n\nimport { GLOBAL_LOG_A_LOT } from '../../constants.mjs';\nimport {\n    PROJECT_ATOM, PROJECT_DESC_REGEXP, PROJECT_NAME_REGEXP,\n    DEFAULT_PROJECT_SAFE_NAME_LENGTH, DEFAULT_PROJECT_ADDL_METADATA_LENGTH,\n    PROJECT_CHILD_DEFAULT_REL8N_NAME, AGENT_SPECIAL_IBGIB_TYPE_PROJECTAGENT,\n} from './project-constants.mjs';\nimport {\n    ProjectData_V1, ProjectIbGib_V1, ProjectIbInfo, ProjectAddlMetadataInfo,\n} from './project-types.mjs';\nimport { getAgentsSvc } from '../../witness/agent/agents-service-v1.mjs';\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\nexport function getProjectSafeName({ name }: { name: string }): string {\n    const lc = `[${getProjectSafeName.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: ec0c81cb0e8ec820f882ecafc2fbc825)`); }\n        const safeName = getSaferSubstring({\n            text: name,\n            length: DEFAULT_PROJECT_SAFE_NAME_LENGTH,\n        });\n        if (!safeName) { throw new Error(`${lc} Could not generate safeName from name: ${name}. (E: genuuid)`); }\n        return safeName;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * Generates the `ib` string for a ProjectIbGib based on its data.\n * The structure is: `${PROJECT_ATOM} ${safeName} ${addlMetadataText}`\n * where addlMetadataText contains underscore-delimited fields like timestampInTicks.\n *\n * ## notes\n *\n * atow (04/2025), we are \"descending\" (forking) from a source comment ibgib to\n * create the project. As such, we are positioning the project ibgib itself to\n * have a similar structure to a comment ibgib. So the schema for the `ib`\n * purposefully has the safeName in the second position just like a comment\n * ibgib has a saferized version of the comment.data.text in its ib schema.\n *\n * WARNING\n * WARNING\n * ATOW (05/2025) THIS FUNCTION'S DETAILS ARE USED IN MUT8-IBGIB\n * APIFUNCTIONINFO.  IF THIS CHANGES, THEN THAT FUNCTION MUST BE CHANGED TOO.\n * WARNING\n * WARNING\n *\n * @see {@link ProjectIbInfo}\n * @see {@link ProjectAddlMetadataInfo}\n *\n */\nexport function getProjectIb({\n    data,\n}: {\n    data: ProjectData_V1;\n}): string {\n    const lc = `[${getProjectIb.name}]`;\n    try {\n        const validationErrors = validateProjectData_V1({ data }) ?? [];\n        if (validationErrors.length > 0) {\n            throw new Error(`invalid Project data. errors: ${validationErrors} (E: d93d821fcc256b4bcb4d785b08c2f425)`);\n        }\n\n        // Get saferized name segment\n        const safeName = getProjectSafeName({ name: data.name });\n\n        // Prepare additional metadata text (add more fields with underscores here later)\n\n        // timestampInTicks\n        const timestampInfo = getTimestampInfo({ timestamp: data.timestamp });\n        if (!timestampInfo.valid) { throw new Error(`(UNEXPECTED) validated data but invalid data.timestamp? (E: 679cbf1c92e8b9473becf8310e6b8225)`); }\n        const timestampInTicks = Number.parseInt(timestampInfo.ticks);\n\n        // compose addlMetadataText\n        const addlMetadataFields: string[] = [\n            timestampInTicks.toString(),\n            // add more fields here as needed in the future\n        ];\n        addlMetadataFields.push();\n        const addlMetadataText = addlMetadataFields.join('_');\n        if (addlMetadataText.length > DEFAULT_PROJECT_ADDL_METADATA_LENGTH) {\n            throw new Error(`(UNEXPECTED) addlMetadataText.length > DEFAULT_PROJECT_ADDL_METADATA_LENGTH (${DEFAULT_PROJECT_ADDL_METADATA_LENGTH})? (E: 8fed8709283f6be2d8deda13b67b3925)`);\n        }\n\n        // Construct the final ib string\n        return `${PROJECT_ATOM} ${safeName} ${addlMetadataText}`;\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    }\n}\n\nexport function validateProjectIb({\n    ib,\n}: {\n    ib: Ib;\n}): string[] | undefined {\n    const lc = `[${validateProjectIb.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 111f6b5630badb921accdc6c224c0425)`); }\n\n        // major hack here...I'm tired of doing this plumbing shit.\n\n        try {\n            const _info = parseProjectIb({ ib });\n        } catch (error) {\n            return [extractErrorMsg(error)];\n        }\n\n        return undefined;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * Parses a project `ib` string into its components.\n *\n * @see {@link getProjectIb} for expected ib schema\n */\nexport function parseProjectIb({\n    ib,\n}: {\n    ib: Ib;\n}): ProjectIbInfo {\n    const lc = `[${parseProjectIb.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... parsing ib: ${ib}`); }\n        if (!ib) { throw new Error(`${lc} ib required (E: genuuid)`); }\n\n        const pieces = ib.split(' ');\n        if (pieces.length !== 3) { throw new Error(`${lc} Invalid project ib format. Expected 3 space-delimited pieces. Got: ${pieces.length}. ib: ${ib} (E: genuuid)`); }\n\n        const [atom, safeName, addlMetadataText] = pieces;\n\n        if (atom !== PROJECT_ATOM) { throw new Error(`${lc} Invalid atom. Expected '${PROJECT_ATOM}', got '${atom}'. ib: ${ib} (E: genuuid)`); }\n\n        if (!safeName) { throw new Error(`${lc} safeName segment is empty. ib: ${ib} (E: genuuid)`); }\n\n        if (!addlMetadataText) { throw new Error(`${lc} addlMetadataText segment is empty. ib: ${ib} (E: genuuid)`); }\n\n        // Parse the underscore-delimited addlMetadataText\n        const metadataPieces = addlMetadataText.split('_');\n        if (metadataPieces.length !== 1) { throw new Error(`${lc} Could not parse addlMetadataText. Expected 1 underscore-delimited piece. Got: ${metadataPieces.length}. addlMetadataText: ${addlMetadataText} (E: genuuid)`); }\n\n        const timestampInTicksStr = metadataPieces[0];\n        const timestampInTicks = parseInt(timestampInTicksStr, 10);\n        if (isNaN(timestampInTicks)) { throw new Error(`${lc} Could not parse timestampInTicks from addlMetadataText. isNan.  Expected a decimal number. timestampInTicksStr: ${timestampInTicksStr}. addlMetadataText: ${addlMetadataText} (E: genuuid)`); }\n\n        const addlMetadata: ProjectAddlMetadataInfo = {\n            timestampInTicks,\n            // otherField, // if added\n        };\n\n        const result: ProjectIbInfo = {\n            atom: PROJECT_ATOM,\n            safeName,\n            addlMetadataText,\n            addlMetadata,\n        };\n\n        if (logalot) { console.log(`${lc} parsed info: ${pretty(result)}`); }\n        return result;\n\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * Validates the ProjectData_V1 structure.\n * Returns array of error messages if invalid, otherwise undefined.\n */\nexport function validateProjectData_V1({\n    data,\n}: {\n    data: ProjectData_V1 | any;\n}): string[] | undefined {\n    const lc = `[${validateProjectData_V1.name}]`;\n    const errors: string[] = [];\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: ac9c21893f38a2500fcb49ee26f0b325)`); }\n\n        if (!data) {\n            errors.push(\"Data is required.\");\n            return errors; /* <<<< returns early */\n        }\n\n        if (data.name) {\n            if (typeof data.name === 'string') {\n                if (!PROJECT_NAME_REGEXP.test(data.name)) {\n                    errors.push(`data.name must match regexp: ${PROJECT_NAME_REGEXP.source}`);\n                }\n            } else {\n                errors.push(\"Name must be a string.\");\n            }\n        } else {\n            errors.push(\"name required\")\n        }\n\n        if (data.description) {\n            if (typeof data.description === 'string') {\n                if (!PROJECT_DESC_REGEXP.test(data.description)) {\n                    errors.push(`data.description must match regexp: ${PROJECT_DESC_REGEXP.source}`);\n                }\n            } else {\n                errors.push(\"Description must be a string.\");\n            }\n        } else {\n            // not required\n        }\n\n        // export interface CommentData_V1 extends IbGibData_V1 {\n        //     text: string;\n        //     textTimestamp?: string;\n        //     timestamp?: string;\n        // }\n\n        if (data.text) {\n            if (typeof data.text === 'string') {\n                // any more checks on text?\n            } else {\n                errors.push(\"data.text must be a non-empty string. project's text is meant to be the primary reason/focus for the project.\");\n            }\n        } else {\n            errors.push(`data.text required`);\n        }\n\n        if (data.textTimestamp) {\n            if (typeof data.textTimestamp === 'string') {\n                const resValid = getTimestampInfo({ timestamp: data.textTimestamp });\n                if (!resValid.valid) {\n                    errors.push(`data.textTimestamp (${data.textTimestamp}) is not a valid timestamp: ${resValid.emsg}`);\n                }\n            } else {\n                errors.push(\"data.textTimestamp must be a string.\");\n            }\n        } else {\n            // why would this be falsy?\n            console.warn(`${lc} data.textTimestamp not provided. (W: genuuid)`);\n        }\n\n        if (data.timestamp) {\n            if (typeof data.timestamp === 'string') {\n                const resValid = getTimestampInfo({ timestamp: data.timestamp });\n                if (!resValid.valid) {\n                    errors.push(`data.timestamp (${data.timestamp}) is not a valid timestamp: ${resValid.emsg}`);\n                }\n            } else {\n                errors.push(\"data.timestamp must be a string.\");\n            }\n        } else {\n            // why would this be falsy?\n            console.warn(`${lc} data.timestamp not provided. (W: genuuid)`);\n        }\n\n        return errors.length > 0 ? errors : undefined;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        return [`Unexpected error during validation: ${extractErrorMsg(error)} (E: genuuid)`];\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n\n}\n\n/**\n * Validates a ProjectIbGib_V1 intrinsically, its data, and the consistency\n * between the ib string and the data content.\n * Returns an array of error messages if invalid, otherwise undefined.\n */\nexport async function validateProjectIbGib_V1({\n    ibGib,\n}: {\n    ibGib: IbGib_V1;\n}): Promise<string[] | undefined> {\n    const lc = `[${validateProjectIbGib_V1.name}]`;\n    const allErrors: string[] = [];\n    try {\n        if (logalot) { console.log(`${lc} starting...`); }\n        if (!ibGib) {\n            allErrors.push('ibGib is required.');\n            return allErrors;\n        }\n\n        // 1. Basic intrinsic validation (ib, gib, data, rel8ns presence, gib calc)\n        const intrinsicErrors = await validateIbGibIntrinsically({ ibGib }) ?? [];\n        if (intrinsicErrors.length > 0) {\n            return intrinsicErrors; /* <<<< returns early */\n        }\n\n        const dataErrors = validateProjectData_V1({ data: ibGib.data as ProjectData_V1 }) ?? [];\n        dataErrors.forEach(x => allErrors.push(x));\n\n        const ibErrors = validateProjectIb({ ib: ibGib.ib }) ?? [];\n        ibErrors.forEach(x => allErrors.push(x));\n\n        // not doing this for now\n        const rel8nsErrors = [];\n        rel8nsErrors.forEach(x => allErrors.push(x));\n\n        return allErrors.length > 0 ? allErrors : undefined;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)} (E: genuuid)`);\n        // Return validation data indicating an unexpected error occurred\n        return [`Unexpected error during validation: ${extractErrorMsg(error)} (E: genuuid)`];\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * Type guard to check if an object conforms to ProjectData_V1 structure.\n */\nexport function isProjectData_V1(data: any): data is ProjectData_V1 {\n    const lc = `[${isProjectData_V1.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 959a0308e86d328cb1e68aab8385df25)`); }\n\n        const errors = validateProjectData_V1({ data }) ?? [];\n        return errors.length === 0;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        return false;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * Type guard to check if an IbGib_V1 is structurally a ProjectIbGib_V1.\n * Verifies the atom in the ib and checks data structure using isProjectData_V1.\n */\nexport function isProjectIbGib_V1(ibGib: IbGib_V1): ibGib is ProjectIbGib_V1 {\n    if (!ibGib || !ibGib.ib || !ibGib.data) { return false; }\n    // Check if atom is 'project'\n    if (!ibGib.ib.startsWith(`${PROJECT_ATOM} `)) { return false; }\n    // Check data structure\n    return isProjectData_V1(ibGib.data);\n}\n\n/**\n * Creates a new Project ibGib.\n */\nexport async function createProjectIbGib({\n    name,\n    srcCommentIbGib,\n    description,\n    saveInSpace,\n    space,\n}: {\n    name: string;\n    /**\n     * NOT implemented yet\n     */\n    srcCommentIbGib?: CommentIbGib_V1,\n    description?: string;\n    /**\n     * If true, saves the newly created project ibgib and all intermediate\n     * dependency ibgibs (dna and others) in the given {@link space}, or default\n     * local space if that is falsy.\n     */\n    saveInSpace?: boolean;\n    /**\n     * If set and {@link saveInSpace} is true, then this will be where all\n     * ibgibs are saved.\n     */\n    space?: IbGibSpaceAny;\n}): Promise<TransformResult<ProjectIbGib_V1>> {\n    const lc = `[${createProjectIbGib.name}]`;\n    if (logalot) { console.log(`${lc} starting...`); }\n    try {\n        if (!name) { throw new Error(`${lc}  required. (E: genuuid)`); }\n\n        // start with a comment ibgib as the genesis of the project.\n        let resSrcCommentIbGib: TransformResult<CommentIbGib_V1> | undefined = undefined;\n        if (!srcCommentIbGib) {\n            resSrcCommentIbGib = await createCommentIbGib({\n                text: [\n                    `# ${name}`,\n                    ``,\n                    description ?? `initial comment`, // a little programming humor\n                ].join('\\n'),\n                saveInSpace,\n                space,\n            });\n            srcCommentIbGib = resSrcCommentIbGib.newIbGib;\n        }\n\n        const safeName = getSaferSubstring({\n            text: name,\n            length: DEFAULT_PROJECT_SAFE_NAME_LENGTH,\n        });\n\n        const resNewProjectFork = await fork({\n            src: srcCommentIbGib,\n            destIb: `${PROJECT_ATOM} ${safeName}`, // will do the full destIb in the next mut8 step\n            cloneData: true,\n            cloneRel8ns: true,\n            tjp: { uuid: true, timestamp: true },\n            dna: true,\n            nCounter: true,\n        }) as TransformResult<CommentIbGib_V1>;\n\n        // we now have an intermediate ibgib that is essentially a clone of the\n        // src comment but with new tjp/timestamp metadata. We need to convert\n        // this to a project ibgib.\n\n        const now = new Date();\n        const timestamp = getTimestamp(now);\n        const timestampMs = now.getMilliseconds();\n        /**\n         * This drives the project.ib, but may not be 100% the final data. But\n         * the pieces that drive the ib should be accurate.\n         */\n        const fullNewDataSortOf: ProjectData_V1 = {\n            ...resNewProjectFork.newIbGib.data!,\n            timestamp, timestampMs,\n            name,\n            description,\n        }\n        const newIb = getProjectIb({ data: fullNewDataSortOf });\n        if (logalot) { console.log(`${lc} newIb: ${newIb}. (I: 60804a0c0e575d525855926a9712d825)`); }\n\n        const dataToAddOrPatch: Partial<ProjectData_V1> = {\n            ...resNewProjectFork.newIbGib.data,\n            timestamp, timestampMs,\n            name,\n            description,\n        };\n        if (logalot) { console.log(`${lc} dataToAddOrPatch: ${pretty(dataToAddOrPatch)} (I: 70129a2aeaa4e9df5d42137c479f4f25)`); }\n\n        /**\n         * finalizes the new project (not forever, but in terms of this fn)\n         */\n        const resNewProjectMut8 = await mut8({\n            src: resNewProjectFork.newIbGib,\n            mut8Ib: newIb,\n            dataToAddOrPatch,\n            noTimestamp: true,\n            dna: true,\n            nCounter: true,\n        }) as TransformResult<ProjectIbGib_V1>;\n        if (logalot) { console.log(`${lc} resNewProjectMut8.newIbGib: ${pretty(resNewProjectMut8.newIbGib)} (I: c0bca72cced2edbe69956774c09ad925)`); }\n\n        /**\n         * depending on if we created our own new srcCommentIbGib, contains all the\n         * newly created ibgibs required for the new project.\n         */\n        let resNewProject: TransformResult<ProjectIbGib_V1>;\n        if (resSrcCommentIbGib) {\n            // had to do a comment ibgib, so merge the transform results\n            resNewProject = {\n                newIbGib: resNewProjectMut8.newIbGib,\n                intermediateIbGibs: [\n                    ...resSrcCommentIbGib.intermediateIbGibs ?? [],\n                    resSrcCommentIbGib.newIbGib,\n                    ...resNewProjectFork.intermediateIbGibs ?? [],\n                    resNewProjectFork.newIbGib,\n                    ...resNewProjectMut8.intermediateIbGibs ?? [],\n                ],\n                dnas: [\n                    ...resSrcCommentIbGib.dnas ?? [],\n                    ...resNewProjectFork.dnas ?? [],\n                    ...resNewProjectMut8.dnas ?? [],\n                ],\n            };\n        } else {\n            // had to do a comment ibgib, so merge the transform results\n            resNewProject = {\n                newIbGib: resNewProjectMut8.newIbGib,\n                intermediateIbGibs: [\n                    ...resNewProjectFork.intermediateIbGibs ?? [],\n                    resNewProjectFork.newIbGib,\n                    ...resNewProjectMut8.intermediateIbGibs ?? [],\n                ],\n                dnas: [\n                    ...resNewProjectFork.dnas ?? [],\n                    ...resNewProjectMut8.dnas ?? [],\n                ],\n            };\n        }\n\n        if (saveInSpace) {\n            if (!space) {\n                throw new Error(`(UNEXPECTED) saveInSpace true but space falsy? (E: 492e86a326fd099f4d28a5286809d625)`);\n            }\n            await persistTransformResult({ resTransform: resNewProject, space });\n        }\n\n        return resNewProject;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\ninterface AddChildOptsDetails_Text {\n    type: 'text';\n    title?: string;\n    text?: string;\n}\ninterface AddChildOptsDetails_Canvas {\n    wakka: string\n}\n\n/**\n * discriminate union other options here\n */\ntype AddChildOptsDetails = AddChildOptsDetails_Text | AddChildOptsDetails_Canvas;\n\ninterface AddChildOpts<TDetails extends AddChildOptsDetails = any> {\n    type: 'text';\n    ibGib: IbGib_V1;\n    details: TDetails;\n    /**\n     * rel8nName to use to rel8 the child to the ibgib.\n     */\n    rel8nName?: string;\n    metaspace: MetaspaceService;\n    space: IbGibSpaceAny;\n}\n\n\nexport function addChildIbGib(arg: AddChildOpts): Promise<IbGib_V1> {\n    const lc = `[${addChildIbGib.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 1d5cb8453e5a9e49bffd923da9c90825)`); }\n\n        switch (arg.type) {\n            case 'text':\n                return addChildIbGib_text(arg);\n            default:\n                throw new Error(`(UNEXPECTED) invalid add child type (${arg.type})? (E: bde41e94cb88a66aee56e2cfd4c88825)`);\n        }\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nasync function addChildIbGib_text({\n    ibGib,\n    rel8nName,\n    details,\n    metaspace,\n    space,\n}: AddChildOpts<AddChildOptsDetails_Text>): Promise<IbGib_V1> {\n    const lc = `[${addChildIbGib_text.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n\n        let { title, text } = details;\n\n        text ??= '';\n\n        title ||= 'SomeText';\n        rel8nName ||= PROJECT_CHILD_DEFAULT_REL8N_NAME;\n\n        // create the comment ibgib\n        const resCommentIbGib = await createCommentIbGib({\n            text,\n            addlMetadataText: `${getTimestampInTicks()}_${getSaferSubstring({ text: title, length: 16 })}`,\n            saveInSpace: true,\n            space,\n        });\n        let commentIbGib = resCommentIbGib.newIbGib;\n        commentIbGib = await mut8Timeline({\n            timeline: commentIbGib,\n            mut8Opts: {\n                dataToAddOrPatch: { title, description: title, },\n            },\n            metaspace,\n            space,\n        });\n\n        if (!ibGib) { throw new Error(`(UNEXPECTED) ibGib falsy? should be a project ibgib (E: genuuid)`); }\n        if (!isProjectIbGib_V1(ibGib)) { throw new Error(`(UNEXPECTED) ibGib is not a project ibgib? (E: genuuid)`); }\n\n        // append the comment to the project's timeline\n        const newTimeline = await appendToTimeline({\n            timeline: ibGib,\n            rel8nInfos: [{ ibGibs: [commentIbGib], rel8nName }],\n            metaspace,\n            space,\n        });\n\n        return newTimeline;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n\n/**\n * Retrieves all the latest project ibGibs from a given space (or the default\n * local user space).\n */\nexport async function getProjects({\n    metaspace,\n    space,\n}: {\n    metaspace: MetaspaceService;\n    space?: IbGibSpaceAny;\n}): Promise<ProjectIbGib_V1[]> {\n    const lc = `[${getProjects.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting...`); }\n\n        // prepare space info\n        space ??= await metaspace.getLocalUserSpace({ lock: false });\n        if (!space) { throw new Error(`(UNEXPECTED) space falsy and couldn't even get default local user space? (E: ca5d383873a8ff9068709c7a39e67625)`); }\n        const { spaceId } = parseSpaceIb({ spaceIb: space.ib });\n\n        // get all project agents\n        const agentsSvc = getAgentsSvc();\n        const projectAgents = await agentsSvc.getAgents({\n            metaspace,\n            type: AGENT_SPECIAL_IBGIB_TYPE_PROJECTAGENT,\n            spaceId,\n        });\n\n        // build up the list of projectTjpAddrs from the agents\n        const projectTjpAddrs: IbGibAddr[] = [];\n        for (const projectAgent of projectAgents) {\n            if (!projectAgent.data) { throw new Error(`(UNEXPECTED) projectAgent.data falsy? (E: 53256c9d2168fdf37b0cf5688b11b625)`); }\n            const projectTjpAddr = projectAgent.data['@currentContextTjpAddr'];\n            if (projectTjpAddr) {\n                projectTjpAddrs.push(projectTjpAddr);\n            } else {\n                console.warn(`${lc} projectAgent (${getIbGibAddr({ ibGib: projectAgent })}) has no @currentContextTjpAddr (W: 29c4d8d251945597086f4de8001bc825)`);\n            }\n        }\n        const uniqueTjpAddrs = unique(projectTjpAddrs);\n        if (uniqueTjpAddrs.length === 0) {\n            if (logalot) { console.log(`${lc} No project agents found with space (${space.ib}). Returning empty array. (I: cbc626e97598562d12b483d468082825)`); }\n            return []; /* <<<< returns early */\n        }\n\n        // get the latest addrs corresponding to those tjp addrs.\n        const resLatestIbGib = await getLatestAddrs({\n            addrs: uniqueTjpAddrs,\n            space,\n        });\n        if (!resLatestIbGib.data) { throw new Error(`(UNEXPECTED) resLatestIbGib.data falsy? (E: 0dc6f8692c02cef4112642184de79225)`); }\n        if (resLatestIbGib.data.errors && resLatestIbGib.data.errors.length > 0) {\n            console.error(`${lc} Error getting latest tjp addrs for projects: ${resLatestIbGib.data.errors}. addrsErrored: ${resLatestIbGib.data.addrsErrored ?? '[addrsErrored falsy?]'} (E: 9ee4e8a3329b464d280e3fb8318a6825)`);\n            if (resLatestIbGib.data.addrsErrored && resLatestIbGib.data.addrsErrored.length === uniqueTjpAddrs.length) {\n                // all of them errored, so return an empty array\n                throw new Error(`all project addrs errors. (E: 942bc8f6920865be18f09c98e06f9825)`);\n            } else {\n                console.warn(`${lc} not all project addrs errored, so we're returning the ones we *were* able to get. addrsErrored: ${resLatestIbGib.data.addrsErrored ?? '[addrsErrored falsy?]'}(W: 20bc481170085fc3b8011f2ce50f9825)`)\n            }\n        }\n        const latestAddrsMap = resLatestIbGib.data.latestAddrsMap;\n        if (!latestAddrsMap) {\n            throw new Error(`(UNEXPECTED) resLatestIbGib.data.latestAddrsMap falsy? this should have contained the latest project addrs. returning empty array. (E: d89fe88d7488d1aaf8618b38db1aa825)`);\n        }\n        const latestAddrs: IbGibAddr[] = [];\n        for (let [addr, latestAddr] of Object.entries(latestAddrsMap)) {\n            latestAddrs.push(latestAddr ?? addr);\n        }\n\n        // get the actual ibgibs corresponding to the latest addrs\n        const resGet = await metaspace.get({\n            addrs: latestAddrs,\n            space,\n        });\n        if (resGet.errorMsg || (resGet.ibGibs ?? []).length !== latestAddrs.length) {\n            if ((resGet.ibGibs ?? []).length === 0) {\n                throw new Error(`error in getting latest project ibgibs. (E: 3b2878e08db8b296e11463669d523825)`);\n            } else {\n                console.error(`${lc} get project ibgibs had errors, but we did get some of the project ibgibs. resGet.errorMsg: ${resGet.errorMsg ?? '[unknown error (E: 733358e3894819cbd8364db8c5ac2725)]'}. (E: 24fcf830893ffadd78eaabd839103825)`);\n            }\n        }\n        const latestProjectIbGibs: ProjectIbGib_V1[] = [];\n        const ibGibsUnknownType = resGet.ibGibs!;\n        for (const ibGibUnknownType of ibGibsUnknownType) {\n            if (isProjectIbGib_V1(ibGibUnknownType)) {\n                latestProjectIbGibs.push(ibGibUnknownType);\n            } else {\n                console.error(`${lc} ibgib gotten (${getIbGibAddr({ ibGib: ibGibUnknownType })}) is NOT a ProjectIbGib_V1. (E: 656f18145928cca6481c4ee8547c0825)`);\n            }\n        }\n\n        // return them!\n        return latestProjectIbGibs;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        // We probably don't want to throw here, as it could break a UI component.\n        // Returning an empty array is safer for rendering.\n        return [];\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n", "import { CommentData_V1 } from \"@ibgib/core-gib/dist/common/comment/comment-types.mjs\";\nimport { IbGib_V1, IbGibRel8ns_V1 } from \"@ibgib/ts-gib/dist/V1/types.mjs\";\nimport type { getProjectIb } from './project-helper.mjs';\nimport { AGENT_REL8N_NAME } from \"../../witness/agent/agent-constants.mjs\";\nimport { IbGibAddr } from \"@ibgib/ts-gib/dist/types.mjs\";\n\n// #region constants - Pulled in from project-constants, but we need default data/rel8ns structure here\n\nexport const DEFAULT_PROJECT_TEXT = 'default project text';\nexport const DEFAULT_PROJECT_NAME = 'untitled_project';\nexport const DEFAULT_PROJECT_DESCRIPTION = 'This is an ibgib project. ';\n\n/**\n * Default rel8ns values for a Project. Includes inherited defaults from IbGib.\n */\nexport const DEFAULT_PROJECT_REL8NS_V1: ProjectRel8ns_V1 | undefined = undefined;\n\n// #endregion constants\n\n/**\n * Represents the data structure for a Project ibGib.\n * Contains the core information defining a project.\n */\nexport interface ProjectData_V1 extends CommentData_V1 {\n    /**\n     * Description of the project.\n     * This can be a more detailed explanation of the project's purpose or scope.\n     * Optional.\n     */\n    description?: string;\n}\n\n/**\n * Represents the relationships structure for a Project ibGib.\n * Currently holds standard ibGib relationships but can be extended\n * in the future if projects require specific relationship types (e.g., rel8n_tasks).\n */\nexport interface ProjectRel8ns_V1 extends IbGibRel8ns_V1 {\n    // Add any project-specific rel8ns here if needed.\n    [AGENT_REL8N_NAME]?: IbGibAddr[];\n}\n\n/**\n * Represents a fully formed Project ibGib, combining its data and relationships.\n * This is the primary type used when interacting with Project ibGibs.\n */\nexport interface ProjectIbGib_V1 extends IbGib_V1<ProjectData_V1, ProjectRel8ns_V1> {\n}\n\n/**\n * Default data values for a Project. Includes inherited defaults from Comment/IbGib.\n */\nexport const DEFAULT_PROJECT_DATA_V1: ProjectData_V1 = {\n    // Inherited from CommentData_V1 -> IbGibData_V1\n    name: DEFAULT_PROJECT_NAME, // Default project name\n    text: DEFAULT_PROJECT_TEXT, // Default comment text\n    textTimestamp: '',\n\n    // ProjectData_V1 specific (or CommentData_V1 overrides)\n    description: DEFAULT_PROJECT_DESCRIPTION, // Default project description\n};\n\n/**\n * Represents the parsed information extracted from the `addlMetadataText`\n * segment within a project's `ib` string. This segment follows the `safeName`\n * and is delimited by underscores internally if multiple fields are present.\n */\nexport interface ProjectAddlMetadataInfo {\n    /**\n     * Ticks version of the timestamp derived from ibgib.data.timestamp.\n     * This value is encoded within the addlMetadataText segment of the ib string.\n     */\n    timestampInTicks: number;\n    // Add other fields here if the addlMetadataText segment grows,\n    // ensuring they are underscore-delimited in the raw text.\n}\n\n\n/**\n * Represents the parsed information extracted from a project's `ib` string.\n * The `ib` string contains core metadata encoded for efficient referencing.\n *\n * @see {@link getProjectIb} for ib schema\n */\nexport interface ProjectIbInfo {\n    /** The atom identifier (must be 'project'). Checked during parsing. */\n    atom: 'project';\n    /**\n     * A 'saferized', often truncated, version of the name (project title).\n     * Extracted as the first space-delimited segment after the atom.\n     */\n    safeName: string;\n    /**\n     * The raw string containing underscore-delimited additional metadata (e.g., \"1678886400000\").\n     * Extracted as the second space-delimited segment after safeName.\n     *\n     * @see {@link addlMetadata}\n     */\n    addlMetadataText: string;\n    /**\n     * The parsed content of the addlMetadataText segment.\n     *\n     * @see {@link addlMetadataText}\n     */\n    addlMetadata: ProjectAddlMetadataInfo;\n}\n\n// #region LensMode\nexport const LENS_MODE_RAW = 'raw';\nexport const LENS_MODE_TEXT = 'text';\nexport const LENS_MODE_MINIGAME = 'minigame';\nexport type LensMode =\n    | typeof LENS_MODE_RAW\n    | typeof LENS_MODE_TEXT\n    | typeof LENS_MODE_MINIGAME;\nexport const LensMode = {\n    raw: LENS_MODE_RAW,\n    text: LENS_MODE_TEXT,\n    minigame: LENS_MODE_MINIGAME,\n} satisfies { [key in LensMode]: LensMode };\n// #endregion LensMode\n", "import { extractErrorMsg, pretty } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { IbGibAddr } from \"@ibgib/ts-gib/dist/types.mjs\";\nimport { IbGib_V1 } from \"@ibgib/ts-gib/dist/V1/types.mjs\";\n\nimport { GLOBAL_LOG_A_LOT } from \"../../../constants.mjs\";\nimport { APIFunctionInfo } from \"../../api-types.mjs\";\nimport { COMMAND_BASE_SCHEMA_PROPERTIES } from \"../command-constants.mjs\";\nimport { getCommandService } from \"../command-service-v1.mjs\";\nimport { CommandDataBase } from \"../command-types.mjs\";\nimport { FUNCTION_CALL_EXAMPLES_HEADER } from \"../../api-constants.mjs\";\nimport { GEMINI_SCHEMA_AGENT_ID, GEMINI_SCHEMA_AGENT_TYPE } from \"../../../witness/agent/agent-constants.mjs\";\nimport { getAgentsSvc } from \"../../../witness/agent/agents-service-v1.mjs\";\nimport { getGlobalMetaspace_waitIfNeeded } from \"../../../helpers.mjs\";\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\n// #region constants\nconst EXAMPLE_INPUT_GETCONTEXTINFO: Partial<GetContextInfoOpts> = {\n    agentId: 'someidprobablylookslikeahash',\n    agentType: 'sometypehere',\n    notesToSelf: 'Example of a getContextInfo function call. DO NOT USE THESE AS YOUR ACTUAL ARGS. THIS IS ONLY AN EXAMPLE TO SHOW THE SHAPE OF THE FUNCTION CALL!!',\n    repromptWithResult: true,\n};\n\nconst EXAMPLES = [\n    // `\\`\\`\\`typescript\\n${FUNCTION_CALL_EXAMPLES_HEADER}\\n${pretty(EXAMPLE_INPUT_GETCONTEXTINFO)}\\n\\`\\`\\``,\n    FUNCTION_CALL_EXAMPLES_HEADER,\n    pretty(EXAMPLE_INPUT_GETCONTEXTINFO),\n].join('\\n');\n// #endregion constants\n\n\n/**\n * @interface CommandResultBase - Base interface for command results.\n *\n * ## notes\n *\n * I'm adding this after already having created several existing commands in\n * order to include an errorMsg. I want commands to return info about errors and\n * not re-throw. I am not integrating this with all existing commands at this\n * time though, so there will be some irregularity.\n *\n * I did go ahead and change the code in the command service to return\n * `{errorMsg}` if an exception is thrown.\n */\nexport interface CommandResultBase {\n    /**\n     * IIF the command errors out, this will be populated.\n     */\n    errorMsg?: string;\n}\n\n/**\n * @interface GetContextInfoOpts - Options for the getContextInfo command.\n * @extends CommandDataBase\n */\nexport interface GetContextInfoOpts extends CommandDataBase<'agent', ['getContextInfo']> {\n    /**\n     * @property agentId - the agent's unique identifier.\n     */\n    agentId: string;\n    /**\n     * @property agentType - type of the agent that corresponds to the basic\n     * responsibilities of the agent\n     */\n    agentType: string;\n}\n\nexport interface GetContextInfoResult extends CommandResultBase {\n    contextAddr: IbGibAddr;\n    contextIbGib: IbGib_V1;\n    latestContextAddr?: IbGibAddr;\n    latestContextIbGib?: IbGib_V1;\n}\n\n/**\n * @interface GetContextInfoCommandData - Command data for the getContextInfo command.\n * @extends CommandDataBase\n */\nexport interface GetContextInfoCommandData extends CommandDataBase<'agent', ['getContextInfo']> {\n    /**\n     * @property agentId - the agent's unique identifier.\n     */\n    agentId: string;\n    /**\n     * @property agentType - type of the agent that corresponds to the basic\n     * responsibilities of the agent\n     */\n    agentType: string;\n}\n\n/**\n * Wrapper function to enqueue the getContextInfo command.\n * @param {GetContextInfoOpts} opts - Options for telling the user something.\n * @returns {Promise<void>} A promise that resolves when the command is enqueued.\n */\nfunction getContextInfoViaCmd(opts: GetContextInfoOpts): Promise<GetContextInfoResult> {\n    const commandService = getCommandService();\n    const command: GetContextInfoCommandData = {\n        cmd: 'agent',\n        cmdModifiers: ['getContextInfo'],\n        agentId: opts.agentId,\n        agentType: opts.agentType,\n        repromptWithResult: opts?.repromptWithResult,\n        notesToSelf: opts?.notesToSelf,\n    };\n    return new Promise<GetContextInfoResult>((resolve, reject) => {\n        commandService.enqueueCommand({ command, resolve, reject });\n    });\n}\n\n/**\n * Implementation function for the getContextInfo command (atow, does nothing other than resolve).\n * @param {GetContextInfoOpts} opts - Options for telling the user something.\n * @returns {Promise<void>} A promise that resolves when the command is executed (immediately).\n */\nasync function getContextInfoImpl(opts: GetContextInfoOpts): Promise<GetContextInfoResult> {\n    const lc = `[${getContextInfoImpl.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n\n        const { agentId, agentType, } = opts;\n\n        // In the actual implementation, this function might trigger some UI update\n        // or logging, but for now, it's just a placeholder.\n        // debugger; // walk through get-context-info command\n\n        // should get the agent\n        const agentsSvc = getAgentsSvc();\n        const agent = await agentsSvc.getAgentById({ agentId, agentType });\n        if (!agent) { throw new Error(`agent not found for opts: ${pretty(opts)} (E: b0da990f27c85c29e5bf148299507225)`); }\n        if (!agent.data) { throw new Error(`(UNEXPECTED) agent.data is falsy? opts: ${pretty(opts)} (E: a8b357b5c68e5485144e2358d1a60425)`); }\n\n        // get the context info here\n        const metaspace = await getGlobalMetaspace_waitIfNeeded();\n        const contextAddr = agent.data[\"@currentContextTjpAddr\"];\n        const superSpaceId = agent.data.superSpaceId;\n        const superSpace = await metaspace.getLocalUserSpace({ localSpaceId: superSpaceId, lock: false });\n        const resGetContext = await metaspace.get({\n            addrs: [contextAddr],\n            space: superSpace,\n        });\n        if (resGetContext.errorMsg || (resGetContext.ibGibs ?? []).length !== 1) {\n            throw new Error(`couldn't get context ibgib (${contextAddr}) from super space (${superSpaceId}). errorMsg: ${resGetContext.errorMsg ?? '[unknown error]'} (E: 63514d4521e1dc26860354ccbcb02125)`);\n        }\n        const contextIbGib = resGetContext.ibGibs!.at(0)!\n        let latestContextIbGib: IbGib_V1 | undefined = undefined;\n        const latestContextAddr = await metaspace.getLatestAddr({ ibGib: contextIbGib, space: superSpace });\n        if (latestContextAddr) {\n            const resGetLatest = await metaspace.get({\n                addrs: [latestContextAddr], space: superSpace\n            });\n            if (resGetLatest.errorMsg || (resGetLatest.ibGibs ?? []).length !== 1) {\n                throw new Error(`couldn't get latest context ibgib (${latestContextAddr}) from super space (${superSpaceId}). errorMsg: ${resGetLatest.errorMsg ?? '[unknown error]'} (E: 450727cc12e226f8b741dd7b0efbfe25)`);\n            }\n            latestContextIbGib = resGetLatest.ibGibs!.at(0)!;\n        }\n\n        return {\n            contextAddr,\n            contextIbGib,\n            latestContextAddr,\n            latestContextIbGib,\n        }\n    } catch (error) {\n        const errorMsg = `${lc} ${extractErrorMsg(error)}`;\n        console.error(errorMsg);\n        throw new Error(errorMsg);\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * API function info for the getContextInfo command.\n */\nexport const getContextInfoFunctionInfo: APIFunctionInfo<typeof getContextInfoViaCmd> = {\n    nameOrId: 'getContextInfo',\n    fnViaCmd: getContextInfoViaCmd,\n    functionImpl: getContextInfoImpl,\n    cmd: 'agent',\n    cmdModifiers: ['getContextInfo'],\n    schema: {\n        name: 'getContextInfo',\n        description: `Gets context info *about your current context ibgib in which you are conversing*. For example, agent's must always \"be\" in a single location ibgib which is their current primary context. When this ibgib's timeline changes (when a mut8/rel8 happens on it and a new ibgib frame is registered with the metaspace and published via the metaspace's pubsub mechanism), then the agent will be made aware of the new children ibgibs added to that timeline. The context address will probably be the TJP address as this defines the timeline's starting point and is used to refer to the entire timeline. Note that the context will always be in the agent's super space.\\nNOTE: This function DOES NOT get any and all context info, e.g., it does not get the website's current css colors. It is specifically to get info regarding YOUR CURRENT default context ibgib info.\\n\\n${EXAMPLES}`,\n        parameters: {\n            type: 'object',\n            properties: {\n                ...COMMAND_BASE_SCHEMA_PROPERTIES,\n                agentId: GEMINI_SCHEMA_AGENT_ID,\n                agentType: GEMINI_SCHEMA_AGENT_TYPE,\n            },\n            required: ['agentId', 'agentType'],\n        },\n    },\n};\n", "import { extractErrorMsg, pretty } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\n\nimport { GLOBAL_LOG_A_LOT } from \"../../../constants.mjs\";\nimport { APIFunctionInfo } from \"../../api-types.mjs\";\nimport { COMMAND_BASE_SCHEMA_PROPERTIES } from \"../command-constants.mjs\";\nimport { getCommandService } from \"../command-service-v1.mjs\";\nimport { CommandDataBase } from \"../command-types.mjs\";\nimport { FUNCTION_CALL_EXAMPLES_HEADER } from \"../../api-constants.mjs\";\nimport { AGENT_NAME_REGEXP, GEMINI_SCHEMA_AGENTS_SELF_IDENTIFIED_NAME } from \"../../../witness/agent/agent-constants.mjs\";\nimport { getAgentsSvc } from \"../../../witness/agent/agents-service-v1.mjs\";\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\n// #region constants\n\n/**\n * camelCased name of the command itself.\n */\nconst FUNCTION_NAME = 'helloWorld';\n\n/**\n * chat category here as this is a chat-related command.\n */\nconst CMD_CATEGORY = 'agent';\n/**\n * helloWorld here is the specific command modifier which narrows down to a command\n * instance, similar to a fully curried function.\n */\nconst CMD_MODIFIERS: string[] = [FUNCTION_NAME];\n\n// #endregion constants\n\n// #region constants\nconst EXAMPLE_INPUT_HELLOWORLD: Partial<HelloWorldOpts> = {\n    agentsSelfIdentifiedName: 'Coolguy',\n    agentId: 'someidprobablylookslikeahash',\n    agentType: 'sometypehere',\n    notesToSelf: 'Example of a helloWorld function call. DO NOT USE THESE AS YOUR ACTUAL NAME/ID/TYPE! THIS IS ONLY AN EXAMPLE TO SHOW THE SHAPE OF THE FUNCTION CALL!!',\n    repromptWithResult: false,\n};\n\nconst EXAMPLES = [\n    // `\\`\\`\\`typescript\\n${FUNCTION_CALL_EXAMPLES_HEADER}\\n${pretty(EXAMPLE_INPUT_HELLOWORLD)}\\n\\`\\`\\``,\n    FUNCTION_CALL_EXAMPLES_HEADER,\n    pretty(EXAMPLE_INPUT_HELLOWORLD),\n].join('\\n');\n// #endregion constants\nconst FUNCTION_DESCRIPTION = [\n    `Introductory function that does a couple things. First, it just makes sure that the basic function calling plumbing is working with the agent. Next, it also confirms the agent is aware of his/her/its id and type. Also, it empowers the agent to choose his/her/its own name with which to interact with user(s) and other agent(s) (only one user implemented atow 04/2025).NOTE: This does not say anything to the user proper. You have to call tellUser (or some other function in the future possibly) to converse with the user. This function only does init.`,\n    EXAMPLES,\n].join('\\n');\n\n\nconst GEMINI_SCHEMA_AGENT_ID = {\n    type: 'string',\n    description: 'unique identifier for the agent. Should be provided to the agent in system instructions upon creation.',\n};\n\nconst GEMINI_SCHEMA_AGENT_TYPE = {\n    type: 'string',\n    description: 'type of the agent that governs basic responsibilities. Should be provided to the agent in system instructions upon creation.',\n};\n\n/**\n * @interface HelloWorldOpts - Options for the helloWorld command.\n * @extends CommandDataBase\n */\nexport interface HelloWorldOpts extends CommandDataBase<typeof CMD_CATEGORY, typeof CMD_MODIFIERS> {\n    /**\n     * @property agentsSelfIdentifiedName - the name which the agent chooses to\n     * use to represent him/her/itself.\n     */\n    agentsSelfIdentifiedName: string;\n    /**\n     * @property agentId - the agent's unique identifier.\n     */\n    agentId: string;\n    /**\n     * @property agentType - type of the agent that corresponds to the basic\n     * responsibilities of the agent\n     */\n    agentType: string;\n}\n\n/**\n * @interface HelloWorldCommandData - Command data for the helloWorld command.\n * @extends CommandDataBase\n */\nexport interface HelloWorldCommandData extends CommandDataBase<typeof CMD_CATEGORY, typeof CMD_MODIFIERS> {\n    /**\n     * @see {@link HelloWorldOpts.agentsSelfIdentifiedName}\n     */\n    agentsSelfIdentifiedName: string;\n    /**\n     * @see {@link HelloWorldOpts.agentId}\n     */\n    agentId: string;\n    /**\n     * @see {@link HelloWorldOpts.agentType}\n     */\n    agentType: string;\n}\n\n/**\n * Wrapper function to enqueue the helloWorld command.\n * @param {HelloWorldOpts} opts - Options for telling the user something.\n * @returns {Promise<void>} A promise that resolves when the command is enqueued.\n */\nfunction helloWorldViaCmd(opts: HelloWorldOpts): Promise<void | { errorMsg: string }> {\n    const commandService = getCommandService();\n    const command: HelloWorldCommandData = {\n        ...opts,\n        cmd: CMD_CATEGORY,\n        cmdModifiers: CMD_MODIFIERS,\n        // agentsSelfIdentifiedName: opts.agentsSelfIdentifiedName,\n        // agentId: opts.agentId,\n        // agentType: opts.agentType,\n        // repromptWithResult: opts?.repromptWithResult,\n        // notesToSelf: opts?.notesToSelf,\n    };\n    return new Promise<void>((resolve, reject) => {\n        commandService.enqueueCommand({ command, resolve, reject });\n    });\n}\n\n/**\n * Implementation function for the helloWorld command (atow, does nothing other than resolve).\n * @param {HelloWorldOpts} opts - Options for telling the user something.\n * @returns {Promise<void>} A promise that resolves when the command is executed (immediately).\n */\nasync function helloWorldImpl(opts: HelloWorldOpts): Promise<void | { errorMsg: string }> {\n    const lc = `[${helloWorldImpl.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n\n        const { agentId, agentType, agentsSelfIdentifiedName } = opts;\n\n        // In the actual implementation, this function might trigger some UI update\n        // or logging, but for now, it's just a placeholder.\n        // debugger; // walk through hello-world command\n\n        // should get the agent\n        const agentsSvc = getAgentsSvc();\n        const agent = await agentsSvc.getAgentById({ agentId, agentType });\n        if (!agent) { throw new Error(`agent not found for opts: ${pretty(opts)} (E: b0da990f27c85c29e5bf148299507225)`); }\n\n        // this does the name validation, throws if invalid\n        await agent.updateName({ name: agentsSelfIdentifiedName });\n        // debugger; // does this get hit?\n    } catch (error) {\n        debugger; // error in helloworld\n        const errorMsg = `${lc} ${extractErrorMsg(error)}`;\n        console.error(errorMsg);\n        return { errorMsg };\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * API function info for the helloWorld command.\n */\nexport const helloWorldFunctionInfo: APIFunctionInfo<typeof helloWorldViaCmd> = {\n    nameOrId: FUNCTION_NAME,\n    fnViaCmd: helloWorldViaCmd,\n    functionImpl: helloWorldImpl,\n    cmd: CMD_CATEGORY,\n    cmdModifiers: CMD_MODIFIERS,\n    schema: {\n        name: FUNCTION_NAME,\n        description: FUNCTION_DESCRIPTION,\n        parameters: {\n            type: 'object',\n            properties: {\n                ...COMMAND_BASE_SCHEMA_PROPERTIES,\n                agentsSelfIdentifiedName: GEMINI_SCHEMA_AGENTS_SELF_IDENTIFIED_NAME,\n                agentId: GEMINI_SCHEMA_AGENT_ID,\n                agentType: GEMINI_SCHEMA_AGENT_TYPE,\n            },\n            required: ['agentsSelfIdentifiedName', 'agentId', 'agentType'],\n        },\n    },\n};\n", "import { APIFunctionInfo } from \"../../api-types.mjs\";\nimport { getContextInfoFunctionInfo } from \"./get-context-info.mjs\";\nimport { helloWorldFunctionInfo } from \"./hello-world.mjs\";\nimport { tellUserFunctionInfo } from \"./tell-user.mjs\";\n\nexport const ChatAPIFunctionInfos: APIFunctionInfo<any>[] = [\n    tellUserFunctionInfo,\n    helloWorldFunctionInfo,\n    getContextInfoFunctionInfo,\n];\n", "/**\n * @module get-ibgibs.mts\n * Provides the API Function Info for the `getIbGibs` command, which allows\n * editing an existing ibGib using the `mut8` transform.\n *\n * ## notes\n *\n * ### ordering imports\n *\n * import sections always go:\n * 1. non-ibgib deps first\n * 2. @ibgib/helper-gib, @ibgib/encrypt-gib, @ibgib/ts-gib, @ibgib/core-gib packages (in that order)\n * 3. import GLOBAL_LOG_A_LOT then remaining project imports\n * 4. code proper starts with the definition of `const logalot` (if applicable)\n *\n * Each section is separated by a blank line.\n */\n\n\nimport { extractErrorMsg, pretty } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';\nimport { IbGib_V1 } from '@ibgib/ts-gib/dist/V1/types.mjs';\nimport { getIbGibAddr } from '@ibgib/ts-gib/dist/helper.mjs';\nimport { IbGibAddr } from '@ibgib/ts-gib/dist/types.mjs';\nimport { SpaceId } from '@ibgib/core-gib/dist/witness/space/space-types.mjs';\n\nimport { GLOBAL_LOG_A_LOT } from '../../../constants.mjs';\nimport { APIFunctionInfo } from \"../../api-types.mjs\";\nimport { COMMAND_BASE_SCHEMA_PROPERTIES } from \"../command-constants.mjs\";\nimport { getCommandService } from \"../command-service-v1.mjs\";\nimport { CommandDataBase } from \"../command-types.mjs\";\nimport { getGlobalMetaspace_waitIfNeeded } from '../../../helpers.mjs';\nimport { FUNCTION_CALL_EXAMPLES_HEADER } from '../../api-constants.mjs';\nimport { getLatestAddrs } from '@ibgib/core-gib/dist/witness/space/space-helper.mjs';\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\ntype IbGibMap = Record<IbGibAddr, IbGib_V1 | undefined>;\n\n// #region constants\n\n/**\n * camelCased name of the command itself.\n */\nconst FUNCTION_NAME = 'getIbGibs';\n\n/**\n * agent is the broad command which basically acts like a category of commands at this point.\n */\nconst CMD_CATEGORY = 'ibgib';\n/**\n * getIbGibs here is the specific command modifier which narrows down to a command\n * instance, similar to a fully curried function.\n *\n * This should be camelCased actual name of the function.\n */\nconst CMD_MODIFIERS: string[] = [FUNCTION_NAME];\n\nconst EXAMPLE_INPUT_GETIBGIBS_SINGLE: Partial<GetIbGibsOpts> = {\n    ibGibAddrs: ['project SomeProject 1748386170000^A2D75E05B14E264619D24ABA4F1A1B2328E183B4524CC26029E54B84BF7BFD73.02544DDD1E042D481EAF62E36229EEC54F20C1899250D6F664ABB48A2013C994'],\n    notesToSelf: `Example of getting a single ibgib. Note that even though it's only getting a single ibgib, it still passes in an array. Usually reprompt is set because you're calling this to see the full ibgib record(s).`,\n    repromptWithResult: true,\n};\nconst EXAMPLE_INPUT_GETIBGIBS_MULTIPLE: Partial<GetIbGibsOpts> = {\n    ibGibAddrs: [\n        'project SomeProject 1748386170000^A2D75E05B14E264619D24ABA4F1A1B2328E183B4524CC26029E54B84BF7BFD73.02544DDD1E042D481EAF62E36229EEC54F20C1899250D6F664ABB48A2013C994',\n        'comment HelloWorld^98289357698348694683943689487958972634583644598269186EA90A3F4A73.298986986BC82792837498759817F9827395872AC87519CDAFFE8175786E5098',\n    ],\n    notesToSelf: `Example of getting multiple ibgibs. Usually reprompt is set because you're calling this to see the full ibgib record(s).`,\n    repromptWithResult: true,\n};\nconst EXAMPLES = [\n    FUNCTION_CALL_EXAMPLES_HEADER,\n    pretty(EXAMPLE_INPUT_GETIBGIBS_SINGLE),\n    pretty(EXAMPLE_INPUT_GETIBGIBS_MULTIPLE),\n].join('\\n');\nconst FUNCTION_DESCRIPTION = [\n    `Gets one or more full ibgib records via their addrs.`,\n    `Note that all of these must be in a single space, determined by the spaceId arg. IF not provided, then the default local user space will be used.`,\n    EXAMPLES,\n].join('\\n');\n\n// #region gemini schemas\nexport const GEMINI_SCHEMA_IBGIB_ADDRS = {\n    type: 'array',\n    description: 'The ibGib addresses (ib^gib) of the ibGibs to load.',\n    items: {\n        type: 'string',\n        description: 'caret-delimited ib^gib address, e.g., \"comment HelloWorld^98289357698348694683943689487958972634583644598269186EA90A3F4A73.298986986BC82792837498759817F9827395872AC87519CDAFFE8175786E5098\"',\n    }\n};\nconst GET_IBGIBS_SCHEMA = {\n    name: FUNCTION_NAME,\n    description: FUNCTION_DESCRIPTION,\n    parameters: {\n        type: 'object',\n        properties: {\n            ...COMMAND_BASE_SCHEMA_PROPERTIES,\n            spaceId: {\n                type: 'string',\n                description: `The id of the local user space. If not provided, will use the default local space. Only provide this if you don't want to use the default space. Agents should either leave this unset, or if they are trying to mut8 an ibGib that is inside *their* subspace, then they should provide this. Otherwise, it will look in the default space which will be incorrect. In the future, agents will have a different API for interacting with their subspaces, but for now this may be used (if the agent even has access to their subspace id. it's so early in dev, I'm not sure if this is true.)`,\n            },\n            ibGibAddrs: GEMINI_SCHEMA_IBGIB_ADDRS,\n            getLatest: {\n                type: 'boolean',\n                description: 'Set to true if you want to get the latest ibgib in a timeline for the given incoming ibGibAddr. This is usually going to be true, unless you are specifically looking for ibGibs in the past or some other use case where you want the specific ibGib in time, so agents should explicitly decide this before calling this function (but no need to tell the user or anything, just make this decision).'\n            }\n        },\n        required: [\n            'ibGibAddrs',\n        ],\n    },\n};\n// #endregion gemini schemas\n\n/**\n * @interface GetIbGibsOpts - Options for the getIbGibs command.\n *\n * @extends CommandDataBase\n */\nexport interface GetIbGibsOpts extends CommandDataBase<typeof CMD_CATEGORY, typeof CMD_MODIFIERS> {\n    spaceId?: SpaceId;\n    /**\n     * @property ibGibAddr - The address (or tjp address) of the project ibGib to edit.\n     */\n    ibGibAddrs: IbGibAddr[];\n    /**\n     * @property getLatest - flag that if true will get the latest version of\n     * the ibGib registered with the space.\n     */\n    getLatest?: boolean;\n}\n\n/**\n * @interface GetIbGibsCommandData - Command data for the getIbGibs command.\n * @extends CommandDataBase\n */\nexport interface GetIbGibsCommandData extends CommandDataBase<typeof CMD_CATEGORY, [typeof FUNCTION_NAME]> {\n    /**\n     * @see {@link GetIbGibsOpts.spaceId}\n     */\n    spaceId?: string;\n    /**\n     * @see {@link GetIbGibsOpts.ibGibAddrs}\n     */\n    ibGibAddrs: IbGibAddr[];\n    /**\n     * @see {@link GetIbGibsOpts.getLatest}\n     */\n    getLatest?: boolean;\n}\n\nexport type GetIbGibsResult = IbGibMap;\n\n/**\n * Wrapper function to enqueue the getIbGibs command.\n * @param {GetIbGibsOpts} opts - @see {@link GetIbGibsOpts}\n * @returns {Promise<void>} A promise that resolves when the command finishes execution.\n */\nfunction getIbGibsViaCmd(opts: GetIbGibsOpts): Promise<GetIbGibsResult> {\n    const commandService = getCommandService();\n    const command: GetIbGibsCommandData = {\n        ...opts,\n        cmd: CMD_CATEGORY,\n        cmdModifiers: CMD_MODIFIERS,\n    };\n    return new Promise<GetIbGibsResult>((resolve, reject) => {\n        commandService.enqueueCommand({ command, resolve, reject });\n    });\n}\n\n/**\n * Implementation function for the getIbGibs command.\n *\n * @param {GetIbGibsOpts} opts - @see {@link GetIbGibsOpts}\n * @returns {Promise<IbGib_V1>} the new timeline ibgib\n */\nasync function getIbGibsImpl(opts: GetIbGibsOpts): Promise<GetIbGibsResult> {\n    const lc = `[${getIbGibsImpl.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n\n        console.log(`${lc} ${CMD_CATEGORY} ${CMD_MODIFIERS} opts: ${pretty(opts)}`);\n\n        let { spaceId, ibGibAddrs, getLatest } = opts;\n\n        if (!ibGibAddrs) { throw new Error(`(UNEXPECTED) ibGibAddrs falsy? (E: e9beaad8ab3cf56608dd5fc79c4c1825)`); }\n        if (ibGibAddrs.length === 0) { throw new Error(`ibGibAddrs is empty (E: f0b1462f482872acba0612c8eb461925)`); }\n\n        const metaspace = await getGlobalMetaspace_waitIfNeeded();\n        if (!metaspace) { throw new Error(`${lc} metaspace falsy ($1: 85aa77c76e583edda3549ff59fadf825)`); }\n        const space = await metaspace.getLocalUserSpace({ localSpaceId: spaceId });\n        if (!space) {\n            if (!spaceId) {\n                throw new Error(`(UNEXPECTED) couldn't get default local user space? ($1: 9b1528024148052dd871b4f323881825)`);\n            } else {\n                throw new Error(`could not get local user space for spaceId (${spaceId}) ($1: genuuid)`);\n            }\n        }\n\n        let addrToLatestAddrMap: { [addr: string]: IbGibAddr } = {};\n        if (getLatest) {\n            const resLatestAddrs = await getLatestAddrs({ addrs: ibGibAddrs, space });\n            if (!resLatestAddrs.data) { throw new Error(`(UNEXPECTED) resLatestAddrs.data falsy? we tried calling getLatestAddrs and this means there is a problem lower in the lib. (E: 0baaf8072abd4feed8330ab503925b25)`); }\n            if (resLatestAddrs.data.latestAddrsMap) {\n                // addrToLatestAddrMap = resLatestAddrs.data.latestAddrsMap;\n                Object.entries(resLatestAddrs.data.latestAddrsMap)\n                    .forEach(([addr, latestAddr]) => {\n                        if (latestAddr) {\n                            addrToLatestAddrMap[addr] = latestAddr;\n                        } else {\n                            debugger; // warn - we're getting latest addrs and I don't know what it means downstream when we get a null for latest addr.\n                            console.warn(`${lc} we're getting latest addrs and I don't know what it means downstream when we get a null for latest addr. (W: bb1db99ccf189afff83a1b5807263a25)`);\n                            addrToLatestAddrMap[addr] = addr;\n                        }\n                    });\n            } else {\n                throw new Error(`(UNEXPECTED) resLatestAddrs.data.latestAddrsMap falsy? we tried calling getLatestAddrs and this was supposed to be the resulting map. This means there is a problem lower in the lib. (E: 9dcca8343a284dfb1a43cf282b82f825)`);\n            }\n        }\n\n        const addrsToGet = getLatest ?\n            Object.values(addrToLatestAddrMap) :\n            ibGibAddrs;\n\n        if (addrsToGet.length !== ibGibAddrs.length) {\n            throw new Error(`(UNEXPECTED) addrsToGet.length !== ibGibAddrs.length? at this point it's assumed that these are the same length (E: 745698a1ba78a14077d648e8d0150825)`);\n        }\n\n        let resGet = await metaspace.get({\n            addrs: addrsToGet,\n            space,\n        });\n\n        if (resGet.errorMsg || (resGet.ibGibs ?? []).length !== addrsToGet.length) {\n            throw new Error(`getIbGibs failed. error: ${extractErrorMsg(resGet.errorMsg ?? `[unknown error. resGet.ibGib length (${(resGet.ibGibs ?? []).length}). addrsToGet.length (${addrsToGet.length})]`)} (E: 09aca916068c6254580f5e29fb63e825)`);\n        }\n\n        const resMap: IbGibMap = {};\n\n        resGet.ibGibs!.forEach(ibGib => {\n            const ibGibAddr = getIbGibAddr({ ibGib });\n            const addr = addrsToGet.find(x => x === ibGibAddr);\n            if (!addr) { throw new Error(`ibGibAddr (${ibGibAddr}) in result ibGibs not found in addrsToGet (${addrsToGet})? Here are the original ibGibAddrs: ${ibGibAddrs}. Here is the resGet.ibGibs: ${pretty(resGet.ibGibs)} (E: 07535883a3a89fcb686f2409bf799825)`); }\n            resMap[ibGibAddr] = ibGib;\n        });\n\n        if (logalot) { console.log(`${lc} resMap: ${pretty(resMap)} (I: 70d79d873dd271949b48d837c286d825)`); }\n\n        return resMap;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error; // Re-throw the error to be caught by the command service\n    } finally {\n        // This finally block will execute regardless of whether the try block succeeds or fails.\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * API function info for the getIbGibs command.\n */\nexport const getIbGibsFunctionInfo: APIFunctionInfo<typeof getIbGibsViaCmd> = {\n    nameOrId: FUNCTION_NAME,\n    fnViaCmd: getIbGibsViaCmd,\n    functionImpl: getIbGibsImpl,\n    cmd: CMD_CATEGORY,\n    cmdModifiers: CMD_MODIFIERS,\n    schema: GET_IBGIBS_SCHEMA,\n};\n", "/**\n * @module mut8IbGib.api-function-info Provides the API Function Info for the `mut8IbGib` command,\n * which allows editing an existing ibGib using the `mut8` transform.\n *\n * ## notes\n *\n * ### ordering imports\n *\n * import sections always go:\n * 1. non-ibgib deps first\n * 2. @ibgib/helper-gib, @ibgib/encrypt-gib, @ibgib/ts-gib, @ibgib/core-gib packages (in that order)\n * 3. import GLOBAL_LOG_A_LOT then remaining project imports\n * 4. code proper starts with the definition of `const logalot` (if applicable)\n *\n * Each section is separated by a blank line.\n */\n\n\nimport { extractErrorMsg, pretty } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';\nimport { IbGib_V1 } from '@ibgib/ts-gib/dist/V1/types.mjs';\nimport { getIbAndGib } from '@ibgib/ts-gib/dist/helper.mjs';\n\nimport { GLOBAL_LOG_A_LOT } from '../../../constants.mjs';\nimport { APIFunctionInfo } from \"../../api-types.mjs\";\nimport { COMMAND_BASE_SCHEMA_PROPERTIES } from \"../command-constants.mjs\";\nimport { getCommandService } from \"../command-service-v1.mjs\";\nimport { CommandDataBase } from \"../command-types.mjs\";\nimport { getGlobalMetaspace_waitIfNeeded } from '../../../helpers.mjs';\nimport { FUNCTION_CALL_EXAMPLES_HEADER } from '../../api-constants.mjs';\nimport { getProjectSafeName, parseProjectIb } from '../../../common/project/project-helper.mjs';\nimport { mut8Timeline } from '@ibgib/core-gib/dist/timeline/timeline-api.mjs';\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\n// #region constants\n\n/**\n * camelCased name of the command itself.\n */\nexport const FUNCTION_NAME = 'mut8IbGib';\n\n/**\n * agent is the broad command which basically acts like a category of commands at this point.\n */\nconst CMD_CATEGORY = 'ibgib';\n/**\n * mut8IbGib here is the specific command modifier which narrows down to a command\n * instance, similar to a fully curried function.\n *\n * This should be camelCased actual name of the function.\n */\nconst CMD_MODIFIERS: string[] = [FUNCTION_NAME];\n\n/**\n * The ibgib.data map has certain keys that are not allowed to be edited, renamed, or removed.\n */\nconst DISALLOWED_DATA_KEYS = ['uuid', 'timestamp', 'timestampMs', 'n', 'textTimestamp',];\n\nconst EXAMPLE_INPUT_MUT8IBGIB_MUT8PROJECTNAME: Partial<Mut8IbGibOpts> = {\n    ibGibAddr: 'project SomeProject 1748386170000^A2D75E05B14E264619D24ABA4F1A1B2328E183B4524CC26029E54B84BF7BFD73.02544DDD1E042D481EAF62E36229EEC54F20C1899250D6F664ABB48A2013C994',\n    dataToAddOrPatchJSONString: JSON.stringify({ name: 'New Title' }),\n    mut8Ib: 'project NewTitle 1748386170000',\n    notesToSelf: `Example of editing/adding a project ibgib's \"title\". In project ibgibs, this is in the \"data.name\" field, and the 2nd spot in the ib is a alphanumerics-only version of the name.`,\n    repromptWithResult: false,\n};\nconst EXAMPLE_INPUT_MUT8IBGIB_MUT8DESCRIPTION: Partial<Mut8IbGibOpts> = {\n    ibGibAddr: 'project SomeProject^A2D75E05B14E264619D24ABA4F1A1B2328E183B4524CC26029E54B84BF7BFD73.02544DDD1E042D481EAF62E36229EEC54F20C1899250D6F664ABB48A2013C994',\n    dataToAddOrPatchJSONString: JSON.stringify({ description: 'Updated description for the project. You do not have to include all the properties, only the ones you want to change/patch.' }),\n    notesToSelf: `Example of editing/adding an ibGib's description. This will change the description in the ibGib's data map.`,\n    repromptWithResult: false,\n};\nconst EXAMPLE_INPUT_MUT8IBGIB_REMOVEKEY: Partial<Mut8IbGibOpts> = {\n    ibGibAddr: 'project SomeProject^AAAA2827879982375961098098B239047928374987987F6029E54B84BF7BFD73.02544DDD1E042D481EAF62E36229EEC54F20C1899250D6F664ABB48A2013C994',\n    dataToRemoveJSONString: JSON.stringify({ identity: { middleInitial: '' } }),\n    notesToSelf: `Example of removing a nested key. This will delete the \"middleInitial\" property from the \"identity\" object in an ibgib's data map.`,\n    repromptWithResult: true,\n};\nconst EXAMPLE_INPUT_MUT8IBGIB_RENAMEKEY: Partial<Mut8IbGibOpts> = {\n    ibGibAddr: 'project SomeProject^AAAA2827879982375961098098B239047928374987987F6029E54B84BF7BFD73.02544DDD1E042D481EAF62E36229EEC54F20C1899250D6F664ABB48A2013C994',\n    dataToRenameJSONString: JSON.stringify({ identity: { oldKeyName: 'newKeyName' } }),\n    notesToSelf: `Example of renaming a key. This will rename the \"oldKeyName\" key to \"newKeyName\" in an ibgib's data map.`,\n    repromptWithResult: false,\n};\nconst EXAMPLE_INPUT_MUT8IBGIB_MUT8IB: Partial<Mut8IbGibOpts> = {\n    ibGibAddr: 'project SomeProject^AAAA2827879982375961098098B239047928374987987F6029E54B84BF7BFD73.02544DDD1E042D481EAF62E36229EEC54F20C1899250D6F664ABB48A2013C994',\n    mut8Ib: 'project SomeNewIb',\n    notesToSelf: `Example of renaming a key. This will rename the \"ib\" value, in this case \"project SomeProject\" to the new value. Empty values will throw.`,\n    repromptWithResult: true,\n};\nconst EXAMPLES = [\n    FUNCTION_CALL_EXAMPLES_HEADER,\n    pretty(EXAMPLE_INPUT_MUT8IBGIB_MUT8PROJECTNAME),\n    pretty(EXAMPLE_INPUT_MUT8IBGIB_MUT8DESCRIPTION),\n    pretty(EXAMPLE_INPUT_MUT8IBGIB_REMOVEKEY),\n    pretty(EXAMPLE_INPUT_MUT8IBGIB_RENAMEKEY),\n    pretty(EXAMPLE_INPUT_MUT8IBGIB_MUT8IB),\n].join('\\n');\nconst FUNCTION_DESCRIPTION = [\n    `Edits an ibGib's intrinsic data map via the mut8 transform.`,\n    `This can include setting/updating an ibgib's data, renaming keys or removing data properties entirely, or changing the ib.`,\n    `It operates on a specific ibGib identified by its address.`,\n    `**Note**: Certain intrinsic data properties are disallowed from being edited, renamed, or removed, including: \\`${DISALLOWED_DATA_KEYS.join('`, `')}\\`. Any attempts to modify these paths will be ignored.`,\n    `In the business domain, this can include multiple things, like editing a name, description, or other internal property. The following are only a couple of examples, but really it's any internal data for an ibgib.`,\n    ``,\n    EXAMPLES,\n    `**Note**: Even though each one individually is optional, at least one of dataToRenameJSONString, dataToRemoveJSONString, dataToAddOrPatchJSONString, or mut8Ib is required.`,\n].join('\\n');\n\nconst JSON_CAVEAT = `Ibgib data can have any structure, so there is no way to know the keys beforehand. OpenAPI schema only allows for known props. So this arg should be a valid JSON string, i.e., the output of JSON.stringify(actualArg).`;\nconst DISALLOWED_CAVEAT = `Disallowed paths like \"uuid\" or \"timestamp\" cannot be added or patched. See function description for all disallowed keys.`;\n\nconst MUT8_IBGIB_SCHEMA = {\n    name: FUNCTION_NAME,\n    description: FUNCTION_DESCRIPTION,\n    parameters: {\n        type: 'object',\n        properties: {\n            ...COMMAND_BASE_SCHEMA_PROPERTIES,\n            spaceId: {\n                type: 'string',\n                description: `The id of the local user space. If not provided, will use the default local space. Only provide this if you don't want to use the default space. Agents should either leave this unset, or if they are trying to mut8 an ibGib that is inside *their* subspace, then they should provide this. Otherwise, it will look in the default space which will be incorrect. In the future, agents will have a different API for interacting with their subspaces, but for now this may be used (if the agent even has access to their subspace id. it's so early in dev, I'm not sure if this is true.)`,\n            },\n            ibGibAddr: {\n                type: 'string',\n                description: 'The content address of the ibGib to edit.',\n            },\n            dataToRenameJSONString: {\n                type: 'object',\n                description: [\n                    `Specifies data properties to rename the key.`,\n                    DISALLOWED_CAVEAT,\n                    JSON_CAVEAT,\n                ].join('\\n'),\n            },\n            dataToRemoveJSONString: {\n                type: 'string',\n                description: [\n                    `Specifies data properties to remove entirely.`,\n                    DISALLOWED_CAVEAT,\n                    JSON_CAVEAT,\n                ].join('\\n'),\n            },\n            dataToAddOrPatchJSONString: {\n                type: 'string',\n                description: [\n                    `Subset of ibgib.data to be added or patched (or upserted if you like). So if you want to change the \"name\" property, then you specify that as the stringified version of { \"name\": \"Some Name\" }.`,\n                    DISALLOWED_CAVEAT,\n                    JSON_CAVEAT,\n                ].join('\\n'),\n            },\n            mut8Ib: {\n                type: 'string',\n                description: 'Optional. If provided, will mutate the ib of the ibGib.',\n            },\n        },\n        required: [\n            'ibGibAddr',\n        ],\n    },\n};\n\n/**\n * @interface Mut8IbGibOpts - Options for the mut8IbGib command.\n *\n * @extends CommandDataBase\n */\nexport interface Mut8IbGibOpts extends CommandDataBase<typeof CMD_CATEGORY, typeof CMD_MODIFIERS> {\n    spaceId?: string;\n    /**\n     * @property ibGibAddr - The address (or tjp address) of the project ibGib to edit.\n     */\n    ibGibAddr: string;\n    /**\n     * @property dataToRenameJSONString - Info to rename keys. Should be an object where each value should either be\n     * a string or an object. If it's a string, then the corresponding key will\n     * be renamed to that value. If it's an object, then it will recurse at that\n     * key. Disallowed paths include: \\`${DISALLOWED_DATA_PATHS.join('`, `')}\\`.\n     */\n    dataToRenameJSONString?: string;\n    /**\n     * @property dataToRemoveJSONString - Info to remove keys. Should be an object where each value should either be\n     * a string or an object. If it's a string, then the corresponding key (and its value)\n     * will be removed (the string value in the dataToRemove object is ignored). If it's an object,\n     * then it will recurse at that key. Disallowed paths include: \\`${DISALLOWED_DATA_PATHS.join('`, `')}\\`.\n     */\n    dataToRemoveJSONString?: string;\n    /**\n     * @property dataToAddOrPatchJSONString - Data object that contains only additive information for ibGib's intrinsic data.\n     * Disallowed paths include: \\`${DISALLOWED_DATA_PATHS.join('`, `')}\\`.\n     *\n     * JSON.stringified version of the dataToAddOrPatchJSONString. This is to overcome the\n     * poor OpenAPI schema limitations, because we do not know the exact allowed\n     * properties ahead of time.\n     */\n    dataToAddOrPatchJSONString?: string;\n    /**\n     * @property mut8Ib - If given, will mut8 the ib (without forking the entire ibGib).\n     */\n    mut8Ib?: string;\n    /**\n     * used in simplified functions\n     */\n    newName?: string;\n    /**\n     * used in simplified functions\n     */\n    newDescription?: string;\n}\n\n/**\n * @interface Mut8IbGibCommandData - Command data for the mut8IbGib command.\n * @extends CommandDataBase\n */\nexport interface Mut8IbGibCommandData extends CommandDataBase<typeof CMD_CATEGORY, [typeof FUNCTION_NAME]> {\n    spaceId?: string;\n    /**\n     * @see {@link Mut8IbGibOpts.ibGibAddr}\n     */\n    ibGibAddr: string;\n    /**\n     * @see {@link Mut8IbGibOpts.dataToRenameJSONString}\n     */\n    dataToRenameJSONString?: string;\n    /**\n     * @see {@link Mut8IbGibOpts.dataToRemoveJSONString}\n     */\n    dataToRemoveJSONString?: string;\n    /**\n     * @see {@link Mut8IbGibOpts.dataToAddOrPatchJSONString}\n     */\n    dataToAddOrPatchJSONString?: string;\n    /**\n     * @see {@link Mut8IbGibOpts.mut8Ib} If given, will mut8 the ib (without forking the entire ibGib).\n     */\n    mut8Ib?: string;\n    /**\n     * used in simplified functions\n     */\n    newName?: string;\n    /**\n     * used in simplified functions\n     */\n    newDescription?: string;\n}\n\n/**\n * Wrapper function to enqueue the mut8IbGib command.\n * @param {Mut8IbGibOpts} opts - @see {@link Mut8IbGibOpts}\n * @returns {Promise<void>} A promise that resolves when the command finishes execution.\n */\nexport function mut8IbGibViaCmd(opts: Mut8IbGibOpts): Promise<IbGib_V1> {\n    const commandService = getCommandService();\n    const command: Mut8IbGibCommandData = {\n        ...opts,\n        cmd: CMD_CATEGORY,\n        cmdModifiers: CMD_MODIFIERS,\n        mut8Ib: opts.mut8Ib?.trim() || undefined, // Ensure mut8Ib is not an empty string\n    };\n    return new Promise<IbGib_V1>((resolve, reject) => {\n        commandService.enqueueCommand({ command, resolve, reject });\n    });\n}\n\n/**\n * Implementation function for the mut8IbGib command.\n *\n * @param {Mut8IbGibOpts} opts - @see {@link Mut8IbGibOpts}\n * @returns {Promise<IbGib_V1>} the new timeline ibgib\n */\nexport async function mut8IbGibImpl(opts: Mut8IbGibOpts): Promise<IbGib_V1> {\n    const lc = `[${mut8IbGibImpl.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n\n        console.log(`${lc} ${CMD_CATEGORY} ${CMD_MODIFIERS} opts: ${pretty(opts)}`);\n\n        let {\n            spaceId,\n            ibGibAddr, dataToRenameJSONString, dataToRemoveJSONString,\n            dataToAddOrPatchJSONString, mut8Ib, newName, newDescription,\n        } = opts;\n\n        const metaspace = await getGlobalMetaspace_waitIfNeeded();\n        if (!metaspace) { throw new Error(`${lc} metaspace falsy (E: 1a3f5e6c8d9a7b01f2e3d4c5b6a708d9)`); }\n        const space = await metaspace.getLocalUserSpace({ localSpaceId: spaceId });\n        if (!space) {\n            if (!spaceId) {\n                throw new Error(`(UNEXPECTED) couldn't get default local user space? (E: 593028fc4038c1cb713a8b1d757da825)`);\n            } else {\n                throw new Error(`could not get local user space for spaceId (${spaceId}) (E: 61fc28fbdf3fd69ae7c9214fe74c2825)`);\n            }\n        }\n\n        if (newName || newDescription !== undefined) {\n            if (newName) {\n                if (dataToAddOrPatchJSONString) { throw new Error(`cannot have newName and dataToAddOrPatchJSONString in the same function call. (E: 72bf6c3c8d8e18a9284f5b0e16d63525)`); }\n                dataToAddOrPatchJSONString = JSON.stringify({ name: newName });\n                const newSafeName = getProjectSafeName({ name: newName });\n                const latestIbGibAddr = await metaspace.getLatestAddr({ addr: ibGibAddr, space });\n                const { ib: projectIb } = getIbAndGib({ ibGibAddr: latestIbGibAddr });\n                const { addlMetadataText, atom, } = parseProjectIb({ ib: projectIb });\n                mut8Ib = `${atom} ${newSafeName} ${addlMetadataText}`;\n                if (newDescription) {\n                    dataToAddOrPatchJSONString = JSON.stringify({ description: newDescription });\n                }\n            } else {\n                dataToAddOrPatchJSONString = JSON.stringify({ description: newDescription });\n            }\n        }\n        const dataToRename = dataToRenameJSONString ?\n            JSON.parse(dataToRenameJSONString) :\n            undefined;\n        const dataToRemove = dataToRemoveJSONString ?\n            JSON.parse(dataToRemoveJSONString) :\n            undefined;\n        const dataToAddOrPatch = dataToAddOrPatchJSONString ?\n            JSON.parse(dataToAddOrPatchJSONString) :\n            undefined;\n\n        if (!ibGibAddr) { throw new Error(`${lc} ibGibAddr is required. (E: genuuid)`); }\n\n        // 1. Load the project ibGib\n\n        // 2. Filter out disallowed paths from the mut8 options.\n        // Note: filterDisallowedPaths handles nested paths as well.\n        const fnValidateMap = (map: any, paramName: string) => {\n            if (!map) { return; /* <<<< returns early */ }\n            const mapKeys = Object.keys(map);\n            mapKeys.forEach(key => {\n                if (DISALLOWED_DATA_KEYS.includes(key)) {\n                    throw new Error(`invalid map. includes disallowed path/key: ${key}. cannot contain any of the following keys: ${DISALLOWED_DATA_KEYS} (E: 855afe854d78e4bf68e7ad88798d0825) (E: fc9c2c9549783685c859c3c4fbb84825)`);\n                }\n            })\n        }\n\n        if (dataToRename) { fnValidateMap(dataToRename, 'dataToRename'); }\n        if (dataToRemove) { fnValidateMap(dataToRemove, 'dataToRemove'); }\n        if (dataToAddOrPatch) { fnValidateMap(dataToAddOrPatch, 'dataToAddOrPatch'); }\n        if (mut8Ib) {\n            const invalidChars = ['^'];\n            invalidChars.forEach(x => {\n                if (mut8Ib!.includes(x)) {\n                    throw new Error(`invalid mut8Ib property. includes character: ${x}. Cannot include any of the following characters: ${invalidChars} (E: 855afe854d78e4bf68e7ad88798d0825)`);\n                }\n            });\n            if (typeof mut8Ib !== 'string' || mut8Ib.length === 0) {\n                throw new Error(`${lc} mut8Ib must be a non-empty string. (E: 392678cef0a5458e0e4bca6869dc6825)`);\n            }\n        }\n\n        // 3. Perform the mut8 transform\n        if (logalot) { console.log(`${lc} Mutating timeline ibGib... (I: genuuid)`); }\n        const newTimelineIbGib = await mut8Timeline({\n            timelineAddr: ibGibAddr,\n            mut8Opts: {\n                dataToRename,\n                dataToRemove,\n                dataToAddOrPatch,\n                mut8Ib,\n            },\n            metaspace,\n            space,\n        });\n\n        if (!newTimelineIbGib) {\n            throw new Error(`${lc} Mutate timeline transform failed: No new timeline ibGib returned. (E: genuuid)`);\n        }\n\n        console.log(`${lc} Mutated timeline ibGib processed.`);\n\n        return newTimelineIbGib;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error; // Re-throw the error to be caught by the command service\n    } finally {\n        // This finally block will execute regardless of whether the try block succeeds or fails.\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * OpenAPI schema for the ibGibAddr parameter.\n */\nconst GEMINI_SCHEMA_PROJECT_ADDR = {\n    type: 'string',\n    description: 'The address (or tjp address) of the project ibGib to edit.',\n};\n\n/**\n * Helper to create OpenAPI schema for data objects with disallowed paths.\n */\nfunction getDataSchema({\n    description,\n    disallowedPaths,\n}: {\n    description: string,\n    disallowedPaths: string[],\n}): any {\n    return {\n        type: 'object',\n        description: `${description} Disallowed paths include: ${disallowedPaths.join(', ')}.`,\n        // We can't define specific properties here because the structure is dynamic,\n        // but we emphasize the disallowed paths in the description.\n        additionalProperties: true, // Allow any other properties\n    };\n}\n\n/**\n * API function info for the mut8IbGib command.\n */\nexport const mut8IbGibFunctionInfo: APIFunctionInfo<typeof mut8IbGibViaCmd> = {\n    nameOrId: FUNCTION_NAME,\n    fnViaCmd: mut8IbGibViaCmd,\n    functionImpl: mut8IbGibImpl,\n    cmd: CMD_CATEGORY,\n    cmdModifiers: CMD_MODIFIERS,\n    schema: MUT8_IBGIB_SCHEMA,\n};\n", "import { APIFunctionInfo } from \"../../api-types.mjs\";\nimport { getIbGibsFunctionInfo } from \"./get-ibgibs.mjs\";\nimport { mut8IbGibFunctionInfo } from \"./mut8-ibgib.mjs\";\n\nexport const IbGibAPIFunctionInfos: APIFunctionInfo<any>[] = [\n    getIbGibsFunctionInfo,\n    mut8IbGibFunctionInfo,\n];\n", "/**\n * @module text-edit.mts Provides the API Function Info to edit an ibgib's `data.text`. This is commonly found on a CommentIbGib_V1.\n *\n * ## notes\n *\n * ### ordering imports\n *\n * import sections always go:\n * 1. non-ibgib deps first\n * 2. @ibgib/helper-gib, @ibgib/encrypt-gib, @ibgib/ts-gib, @ibgib/core-gib packages (in that order)\n * 3. import GLOBAL_LOG_A_LOT then remaining project imports\n * 4. code proper starts with the definition of `const logalot` (if applicable)\n *\n * Each section is separated by a blank line.\n */\n\n\nimport { extractErrorMsg, getTimestamp, getTimestampInTicks, pretty } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';\nimport { IbGib_V1 } from '@ibgib/ts-gib/dist/V1/types.mjs';\nimport { getCommentIb } from '@ibgib/core-gib/dist/common/comment/comment-helper.mjs';\nimport { mut8Timeline } from '@ibgib/core-gib/dist/timeline/timeline-api.mjs';\n\nimport { GLOBAL_LOG_A_LOT } from '../../../constants.mjs';\nimport { APIFunctionInfo } from \"../../api-types.mjs\";\nimport { COMMAND_BASE_SCHEMA_PROPERTIES } from \"../command-constants.mjs\";\nimport { getCommandService } from \"../command-service-v1.mjs\";\nimport { CommandDataBase } from \"../command-types.mjs\";\nimport { getGlobalMetaspace_waitIfNeeded } from '../../../helpers.mjs';\nimport { FUNCTION_CALL_EXAMPLES_HEADER } from '../../api-constants.mjs';\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\n// #region constants\n\n/**\n * camelCased name of the command itself.\n */\nconst FUNCTION_NAME = 'editText';\n\n/**\n * agent is the broad command which basically acts like a category of commands at this point.\n */\nconst CMD_CATEGORY = 'ibgib';\n/**\n *\n */\nconst CMD_MODIFIERS: string[] = [FUNCTION_NAME];\n\nconst EXAMPLE_INPUT_EDIT_TEXT: Partial<EditIbGibTextOpts> = {\n    ibGibAddr: 'comment HelloThereImBob 1748386170000^A2D75E05B14E264619D2ACCCCABF234128E183B4524CC26029E54B84BF7BFD73.61985691826359867236266716461787826378AFFF23984723987FDA2013C8CB',\n    newText: `This is the newly edited text`,\n    notesToSelf: `Example of an ibgib's data.text property.`,\n    repromptWithResult: false,\n};\nconst EXAMPLES = [\n    FUNCTION_CALL_EXAMPLES_HEADER,\n    pretty(EXAMPLE_INPUT_EDIT_TEXT),\n].join('\\n');\nconst FUNCTION_DESCRIPTION = [\n    `Edits an ibGib's data.text property and performs additional business logic on other fields within the ibGib record, like timestamps, updating the ib, etc.`,\n    ``,\n    EXAMPLES,\n].join('\\n');\n\nconst FUNCTION_SCHEMA = {\n    name: FUNCTION_NAME,\n    description: FUNCTION_DESCRIPTION,\n    parameters: {\n        type: 'object',\n        properties: {\n            ...COMMAND_BASE_SCHEMA_PROPERTIES,\n            spaceId: {\n                type: 'string',\n                description: `The id of the local user space. If not provided, will use the default local space. Only provide this if you don't want to use the default space. Agents should either leave this unset, or if they are trying to mut8 an ibGib that is inside *their* subspace, then they should provide this. Otherwise, it will look in the default space which will be incorrect. In the future, agents will have a different API for interacting with their subspaces, but for now this may be used (if the agent even has access to their subspace id. it's so early in dev, I'm not sure if this is true.)`,\n            },\n            ibGibAddr: {\n                type: 'string',\n                description: 'The content address of the ibGib to edit.',\n            },\n            newText: {\n                type: 'string',\n                description: 'The new text to set for the ibGib\\'s data.text property.',\n            },\n        },\n        required: [\n            'ibGibAddr',\n        ],\n    },\n};\n\n/**\n * @interface EditIbGibTextOpts - Options for the mut8IbGib command.\n *\n * @extends CommandDataBase\n */\ninterface EditIbGibTextOpts extends CommandDataBase<typeof CMD_CATEGORY, typeof CMD_MODIFIERS> {\n    spaceId?: string;\n    /**\n     * @property ibGibAddr - The address (or tjp address) of the project ibGib to edit.\n     */\n    ibGibAddr: string;\n    /**\n     * @property newText - The new text to set for the ibGib's data.text property.\n     */\n    newText: string;\n}\n\n/**\n * @interface EditIbGibTextCommandData - Command data for the mut8IbGib command.\n * @extends CommandDataBase\n */\ninterface EditIbGibTextCommandData extends CommandDataBase<typeof CMD_CATEGORY, [typeof FUNCTION_NAME]> {\n    spaceId?: string;\n    /**\n     * @property ibGibAddr - The address (or tjp address) of the project ibGib to edit.\n     */\n    ibGibAddr: string;\n    /**\n     * @property newText - The new text to set for the ibGib's data.text property.\n     */\n    newText: string;\n}\n\n/**\n * Wrapper function to enqueue the mut8IbGib command.\n * @param {EditIbGibTextOpts} opts - @see {@link EditIbGibTextOpts}\n * @returns {Promise<void>} A promise that resolves when the command finishes execution.\n */\nfunction viaCmd(opts: EditIbGibTextOpts): Promise<IbGib_V1> {\n    const commandService = getCommandService();\n    const command: EditIbGibTextCommandData = {\n        ...opts,\n        cmd: CMD_CATEGORY,\n        cmdModifiers: CMD_MODIFIERS,\n    };\n    return new Promise<IbGib_V1>((resolve, reject) => {\n        commandService.enqueueCommand({ command, resolve, reject });\n    });\n}\n\n/**\n * Implementation function for the mut8IbGib command.\n *\n * @param {EditIbGibTextOpts} opts - @see {@link EditIbGibTextOpts}\n * @returns {Promise<IbGib_V1>} the new timeline ibgib\n */\nasync function fnImpl(opts: EditIbGibTextOpts): Promise<IbGib_V1> {\n    const lc = `[${fnImpl.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n\n        console.log(`${lc} ${CMD_CATEGORY} ${CMD_MODIFIERS} opts: ${pretty(opts)}`);\n\n        let {\n            spaceId, ibGibAddr, newText,\n        } = opts;\n\n        const metaspace = await getGlobalMetaspace_waitIfNeeded();\n        if (!metaspace) { throw new Error(`${lc} metaspace falsy (E: 1a3f5e6c8d9a7b01f2e3d4c5b6a708d9)`); }\n        const space = await metaspace.getLocalUserSpace({ localSpaceId: spaceId });\n        if (!space) {\n            if (!spaceId) {\n                throw new Error(`(UNEXPECTED) couldn't get default local user space? (E: 593028fc4038c1cb713a8b1d757da825)`);\n            } else {\n                throw new Error(`could not get local user space for spaceId (${spaceId}) (E: 61fc28fbdf3fd69ae7c9214fe74c2825)`);\n            }\n        }\n\n        newText ??= '';\n\n        if (!ibGibAddr) { throw new Error(`${lc} ibGibAddr is required. (E: genuuid)`); }\n\n\n        const newIb = getCommentIb({ commentText: newText, addlMetadataText: getTimestampInTicks() });\n\n        // 3. Perform the mut8 transform\n        if (logalot) { console.log(`${lc} Mutating timeline ibGib... (I: genuuid)`); }\n        const newTimelineIbGib = await mut8Timeline({\n            timelineAddr: ibGibAddr,\n            mut8Opts: {\n                dataToAddOrPatch: {\n                    text: newText,\n                    textTimestamp: getTimestamp(),\n                } as any,\n                mut8Ib: newIb,\n            },\n            metaspace,\n            space,\n        });\n\n        if (!newTimelineIbGib) {\n            throw new Error(`${lc} Mutate timeline transform failed: No new timeline ibGib returned. (E: genuuid)`);\n        }\n\n        console.log(`${lc} Mutated timeline ibGib processed.`);\n\n        return newTimelineIbGib;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error; // Re-throw the error to be caught by the command service\n    } finally {\n        // This finally block will execute regardless of whether the try block succeeds or fails.\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * API function info for the mut8IbGib command.\n */\nexport const editTextFunctionInfo: APIFunctionInfo<typeof viaCmd> = {\n    nameOrId: FUNCTION_NAME,\n    fnViaCmd: viaCmd,\n    functionImpl: fnImpl,\n    cmd: CMD_CATEGORY,\n    cmdModifiers: CMD_MODIFIERS,\n    schema: FUNCTION_SCHEMA,\n};\n", "import { APIFunctionInfo } from \"../../api-types.mjs\";\nimport { editTextFunctionInfo } from \"./text-edit.mjs\";\n\nexport const TextAPIFunctionInfos: APIFunctionInfo<any>[] = [\n    editTextFunctionInfo,\n];\n", "import { extractErrorMsg, pretty } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\n\nimport { GLOBAL_LOG_A_LOT } from \"../../../constants.mjs\";\nimport { APIFunctionInfo } from \"../../api-types.mjs\";\nimport { COMMAND_BASE_SCHEMA_PROPERTIES } from \"../command-constants.mjs\";\nimport { getCommandService } from \"../command-service-v1.mjs\";\nimport { CommandDataBase } from \"../command-types.mjs\";\nimport { FUNCTION_CALL_EXAMPLES_HEADER } from \"../../api-constants.mjs\";\nimport { UI_THEME_INFO_KEY, VALID_CSS_VARIABLES } from \"../../../ui/ui-constants.mjs\";\nimport { storagePut } from \"../../../storage/storage-helpers.web.mjs\";\nimport { UIThemeInfo } from \"../../../ui/ui-types.mjs\";\nimport { getExistingUIInfo } from \"../../../ui/ui-helpers.mjs\";\nimport { getGlobalDbName, getGlobalStoreName } from \"../../../helpers.web.mjs\";\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\n// #region constants\n/**\n * camelCased name of the command itself.\n */\nconst FUNCTION_NAME = 'updateCSSVariables';\n\n/**\n * 'ui' is the broad command which basically acts like a category of commands at this point.\n */\nconst CMD_CATEGORY = 'ui';\n\n/**\n * This should be camelCased actual name of the function.\n */\nconst CMD_MODIFIERS: string[] = [FUNCTION_NAME];\n\nconst EXAMPLE_INPUT_UPDATECSS: Partial<UpdateCSSVariablesOpts> = {\n    cssVariables: {\n        '--button-background-color-base': '#4CAF50',\n        '--button-text-color-base': 'white',\n        '--button-border-color-base': '#4CAF50',\n        '--button-border-width-base': '1px',\n        '--button-border-style-base': 'solid',\n        '--button-border-radius-base': '4px',\n        '--button-padding-base': '10px 20px',\n        '--button-hover-background-color': '#45a049',\n        '--button-hover-text-color': 'white',\n        '--button-hover-border-color': '#45a049',\n    },\n    notesToSelf: 'Example of an updateCSSVariables function call that is updating a theme section that corresponds to the buttons. I still will do the other sections.',\n    repromptWithResult: true,\n};\n\nconst EXAMPLES = [\n    FUNCTION_CALL_EXAMPLES_HEADER,\n    pretty(EXAMPLE_INPUT_UPDATECSS),\n].join('\\n');\n\nconst FUNCTION_DESCRIPTION = [\n    `Use this to update global CSS variables, effectively changing the visual theme of the application. Provide an object where keys are CSS variable names (e.g., '--text-color-base') and values are their new values (e.g., 'blue'). REMEMBER! When you are asked to change an entire theme, BE SURE TO CHANGE ALL PARTS TO MATCH THE THEME! BUT...apply the changes to related sections of variables together (e.g., all tab-related variables, all button-related variables, etc.) instead of individual properties, otherwise you'll hit the reprompt limit if you try to do each one by itself. To help do this, _first_ categorize ALL the properties into smaller sections, and then tell the user your plan for each section: primary bases (fonts, main text, main background), buttons, tabs, scrollbars, fonts, and any others I might have forgotten. THEN do each group with a single function call but be sure to prompt yourself until you have gone through all of them.`,\n    '',\n    EXAMPLES,\n].join('\\n');\n\n// #endregion constants\n\n\n/**\n * @interface UpdateCSSVariablesOpts - Options for the updateCSSVariables command.\n * @extends CommandDataBase\n */\nexport interface UpdateCSSVariablesOpts\n    extends CommandDataBase<typeof CMD_CATEGORY, typeof CMD_MODIFIERS> {\n    /**\n     * @property cssVariables - An object where keys are CSS variable names\n     * (e.g., '--text-color-base') and values are their new values (e.g., 'blue').\n     */\n    cssVariables: { [key: string]: string };\n}\n\n// export interface UpdateCSSVariablesCommandData extends CommandDataBase<'ui', ['updateCSSVariables']> {\n/**\n * @interface UpdateCSSVariablesCommandData - Command data for the updateCSSVariables command.\n * @extends CommandDataBase\n *\n */\nexport interface UpdateCSSVariablesCommandData extends CommandDataBase<typeof CMD_CATEGORY, typeof CMD_MODIFIERS> {\n    /**\n     * @see {@link UpdateCSSVariablesOpts.cssVariables}\n     */\n    cssVariables: { [key: string]: string };\n}\n\n/**\n * Wrapper function to enqueue the updateCSSVariables command.\n * @param {UpdateCSSVariablesOpts} opts - Options for updating CSS variables.\n * @returns {Promise<void>} A promise that resolves when the command is enqueued.\n */\nfunction updateCSSVariablesViaCmd(opts: UpdateCSSVariablesOpts): Promise<void> {\n    const commandService = getCommandService();\n    const command: UpdateCSSVariablesCommandData = {\n        ...opts, // Spread to include notesToSelf and repromptWithResult\n        cmd: CMD_CATEGORY,\n        cmdModifiers: [FUNCTION_NAME],\n        // cssVariables: opts.cssVariables,\n        // repromptWithResult: opts?.repromptWithResult,\n        // notesToSelf: opts?.notesToSelf,\n    };\n    return new Promise<void>((resolve, reject) => {\n        commandService.enqueueCommand({ command, resolve, reject });\n    });\n}\n\n/**\n * Implementation function for the updateCSSVariables command (atow, does nothing other than resolve).\n * @param {UpdateCSSVariablesOpts} opts - Options for updating CSS variables.\n * @returns {Promise<void>} A promise that resolves when the command is executed (immediately).\n */\nasync function updateCSSVariablesImpl(opts: UpdateCSSVariablesOpts): Promise<void> {\n    const lc = `[${updateCSSVariablesImpl.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: badce195ed1817dd686c7098511e1f25)`); }\n\n        // In the actual implementation, this function would update the CSS variables.\n        console.log(`${lc} Updating CSS variables: ${JSON.stringify(opts.cssVariables)}`);\n        // Actual implementation to be added here:\n        for (const [variableName, value] of Object.entries(opts.cssVariables)) {\n            document.documentElement.style.setProperty(variableName, value);\n        }\n\n        // update the theme in the options\n        const dbName = getGlobalDbName();\n        const storeName = await getGlobalStoreName();\n        const existingUIInfo = await getExistingUIInfo({ dbName, storeName }) ?? { cssVariableOverrides: {}, };\n        const newUIInfo: UIThemeInfo = {\n            ...existingUIInfo,\n            cssVariableOverrides: {\n                ...existingUIInfo.cssVariableOverrides,\n                ...opts.cssVariables,\n            },\n        };\n\n        await storagePut({\n            dbName,\n            storeName: await getGlobalStoreName(),\n            key: UI_THEME_INFO_KEY,\n            value: JSON.stringify(newUIInfo),\n        });\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n\n/**\n * API function info for the updateCSSVariables command.\n */\nexport const updateCSSVariablesFunctionInfo: APIFunctionInfo<typeof updateCSSVariablesViaCmd> = {\n    nameOrId: FUNCTION_NAME,\n    fnViaCmd: updateCSSVariablesViaCmd,\n    functionImpl: updateCSSVariablesImpl,\n    cmd: CMD_CATEGORY,\n    cmdModifiers: CMD_MODIFIERS,\n    schema: {\n        name: FUNCTION_NAME,\n        description: FUNCTION_DESCRIPTION,\n        parameters: {\n            type: 'object',\n            properties: {\n                ...COMMAND_BASE_SCHEMA_PROPERTIES,\n                cssVariables: {\n                    type: 'object',\n                    description: 'CSS variables to update when theming or otherwise changing these visual aspects of the web app per user preferences or the user directly asking for it. (atow there are no preferences saved or anything, so this is just user-driven if they ask for it.)',\n                    properties: Object.fromEntries(\n                        VALID_CSS_VARIABLES.map(varName => [\n                            varName,\n                            {\n                                type: 'string',\n                                description: `configurable css variable`,\n                            },\n                        ])\n                    ),\n                }\n            },\n            required: ['cssVariables'],\n        },\n    },\n};\n", "/**\r\n * @module project-agent-functions.mts\r\n *\r\n * This module's constants were pulled out of {@link ./project-constants.mts} in\r\n * order to avoid circular dependencies.\r\n */\r\n\r\nimport { APIFunctionInfo } from \"../../api/api-types.mjs\";\r\nimport { ChatAPIFunctionInfos } from \"../../api/commands/chat/chat-index.mjs\";\r\nimport { IbGibAPIFunctionInfos } from \"../../api/commands/ibgib/ibgib-index.mjs\";\r\nimport { TextAPIFunctionInfos } from \"../../api/commands/text/text-index.mjs\";\r\nimport { updateCSSVariablesFunctionInfo } from \"../../api/commands/ui/update-css-variables.mjs\";\r\n\r\n/**\r\n * @constant ProjectAgentFunctionInfos - An array of all available API functions for project agents.\r\n */\r\nexport const ProjectFunctionInfos: APIFunctionInfo<any>[] = [\r\n    // editProjectFunctionInfo,\r\n];\r\n\r\nexport const ProjectChildTextFunctionInfos: APIFunctionInfo<any>[] = [\r\n    // ?\r\n];\r\n\r\nexport const AGENT_AVAILABLE_FUNCTIONS_PROJECTAGENT: APIFunctionInfo<any>[] = [\r\n    updateCSSVariablesFunctionInfo,\r\n    ...ChatAPIFunctionInfos,\r\n    ...TextAPIFunctionInfos,\r\n    ...IbGibAPIFunctionInfos,\r\n    ...ProjectFunctionInfos,\r\n];\r\n\r\nexport const AGENT_AVAILABLE_FUNCTIONS_PROJECTCHILDTEXTAGENT: APIFunctionInfo<any>[] = [\r\n    ...ChatAPIFunctionInfos,\r\n    ...TextAPIFunctionInfos,\r\n    ...IbGibAPIFunctionInfos,\r\n];", "import { AGENT_GOAL_COMMON, AGENT_SYSTEM_PROMPT_COMMON_INSTRUCTIONS, AGENT_WEBSITE_DESCRIPTION } from \"./common-agent-texts.mjs\";\n\n// export const AGENT_SPECIAL_IBGIB_TYPE_PROJECTAGENT = 'projectagent';\nexport const AGENT_WEBSITE_DESCRIPTION_PROJECTCAVEAT = `Now, that's just to give you info on the website. Your job is not primarily to answer questions about the website. Your primary job is dealing with your particular project. But it's very early dev, so don't worry too much right now. Just chat and do your best to help the user with the project. Don't worry if the scope exceeds the direct requirements of the project. Remember the Fundamental Connectedness of All Things from Dirk Gently!`;\nexport const AGENT_GOAL_PROJECTAGENT_LANGUAGELEARNING = [\n    `Unless the learner overrides these instructions, you should be relatively consistent when making games. There are two types of games: 1) those built on a source material (like the user wanting to learn a song or some news article), and 2) those designed to help correct a learner's mistakes. In the first case, the source material should be broken into chunks. Each chunk you should present a single word to parrot and then the same word later - in the SAME minigame - within the context of the surrounding phrases/lines. Later minigames should ultimately be built on entire lines, stanzas, paragraphs, etc. In the second case, it's supremely important to give the learner practice on correct phrases on things they actually try to say when they speak to you. So create minigames with stimuli that comprise *entire corrected phrases/sentences* that the learner used/formed incorrectly. If they ask, you can describe the correction in the chat, but don't put the incorrect form in the game itself. We don't want to reinforce the incorrect form, only reinforce the correct one.`,\n    `Also, as a general rule, don't create items that translate from the target language into the native language. Instead, if definition is required, use simpler words in the target language. The ultimate goal is to enable the learner to _think_ in the target language. Of course, if they are brand new to the language, you have to use more of the learner's native language and translate, but you should be building up a simple vocabulary to bootstrap in the language. This is like teaching italian with learning early on, e.g., \"parola\", \"parole\", \"frase\", \"che cosa vuol dire ___?\", \"___ vuol dire ____\", \"non capisco\", \"scusi\" etc.`,\n].join('\\n');\nexport const AGENT_GOAL_PROJECTAGENT = [\n    AGENT_GOAL_COMMON,\n    `You yourself are a \"project\" agent. Now \"project\" is a funny word in ibgib, as previously stated, a granular \"version control\"-like system. If you are working on an ibgib that represents what nowadays is a src code repo, then that obviously is a \"project\". In fact, it may be multiple projects, just as a current-day repo may have multiple packages. But with ibgib especially, _any_ \"thing\" may be broken down into sub-\"things\" which themselves can be \"version controlled\" (have a dedicated focus on their timeline). The word we're using for this is \"project\".`,\n    AGENT_GOAL_PROJECTAGENT_LANGUAGELEARNING,\n].join('\\n');\nexport const AGENT_INITIAL_SYSTEM_TEXT_PROJECTAGENT = [\n    AGENT_SYSTEM_PROMPT_COMMON_INSTRUCTIONS,\n    AGENT_WEBSITE_DESCRIPTION,\n    AGENT_WEBSITE_DESCRIPTION_PROJECTCAVEAT,\n    AGENT_GOAL_PROJECTAGENT,\n].join('\\n');\nconst AGENT_INITIAL_CHAT_HI_PLEASEINTRO_YOURSELF_PROJECTAGENT = [\n    `Hi. First, please give yourself a unique name. Use the same name throughout your lifetime. This name will be used for functions that require identification. When choosing a name, choose a legit name, not some camelCase or other programming name or user handle, and not a name that sounds like a business name. Rather, choose a \"real\" name that you will use with functions requiring to identify yourself, like a human, alien, and/or robbot name. And you can't use the name of your model architecture. For example, Google Gemini models can't use \"Gemini\".`,\n    `After this, and after you call helloWorld a single time (it's mainly used to initialize your data with the name and maybe one or two other things) with the reprompt flag set, please introduce yourself to the user. You don't need to mention the helloWorld call. Just explain what type of agent you are, and give a very brief description of yourself.`,\n    `Using your own words/phrasings, ask the user if they are new to ibgib, particularly to this website, because it's unique or if they would just like help on how to play.`,\n    `If they are new and/or want help, you are to give them instructions on your available functions that pertain to interacting with projects. You don't need to mention functions like tellUser or helloWorld, as those are obviously meant just for you.`,\n].join('\\n');\nexport const AGENT_INITIAL_CHAT_TEXT_PROJECTAGENT = [\n    AGENT_INITIAL_CHAT_HI_PLEASEINTRO_YOURSELF_PROJECTAGENT,\n].join('\\n');\nexport const CHAT_WITH_AGENT_PLACEHOLDER_PROJECTAGENT = '';\n", "<div id=\"project-component\" class=\"\">\n    <div id=\"project-header\" class=\"project-header panel-header\">\n        <div id=\"project-header-tabs\" class=\"project-header-tabs panel-header\">\n            <!-- project child ibgibs' tabs generated here -->\n        </div>\n\n\n        <!-- add button and popover options -->\n        <button id=\"project-header-add-btn\" class=\"tab-btn\" popovertarget=\"add-popover\"><span>+</span></button>\n        <div class=\"add-button-container\">\n            <div id=\"add-popover\" class=\"add-popover\" popover>\n                <div class=\"add-popover-option\" data-option=\"text\">Text</div>\n                <div class=\"add-popover-option\" data-option=\"minigame\">Minigame for Active Tab</div>\n                <!-- <div class=\"add-popover-option\" data-option=\"minigame\">Minigame Active Tab - Fill-in-the-blank</div> -->\n                <!-- Add more opts later, ultimately dynamically generated? -->\n            </div>\n        </div>\n\n        <!-- ... button and popover options -->\n        <button id=\"project-header-ellipsis-btn\" class=\"tab-btn\"\n            popovertarget=\"ellipsis-popover\"><span>\u2026</span></button>\n        <div class=\"ellipsis-button-container\">\n            <div id=\"ellipsis-popover\" class=\"ellipsis-popover\" popover>\n                <div class=\"ellipsis-popover-option\" data-option=\"chat-active-tab\">Chat in Active Tab</div>\n                <div class=\"ellipsis-popover-option\" data-option=\"copy-project-address\">Copy Project Address</div>\n                <div class=\"ellipsis-popover-option\" data-option=\"copy-active-tab-address\">Copy Active Tab Address</div>\n                <div class=\"ellipsis-popover-option\" data-option=\"export-project\">Export Project</div>\n                <div class=\"ellipsis-popover-option\" data-option=\"export-project-gzip\">Export Project (gzip)</div>\n                <div class=\"ellipsis-popover-option\" data-option=\"export-active-tab\">Export Active Tab</div>\n                <div class=\"ellipsis-popover-option\" data-option=\"export-active-tab-gzip\">Export Active Tab (gzip)</div>\n                <!-- used for click handler -->\n                <a id=\"export-ibgib-anchor\" style=\"display: none\">download</a>\n                <!-- Add more opts later, ultimately dynamically generated? -->\n            </div>\n        </div>\n    </div>\n\n    <div id=\"project-content\">\n\n\n    </div>\n\n    <div id=\"project-footer\" class=\"project-footer\">\n        <div id=\"ibgib-lens-bar\">\n            <button id=\"raw-lens-btn\" data-mode=\"raw\" class=\"panel-tab-button lens-button active\">\n                <span>Raw&nbsp;</span>\n                <span style=\"font-family: Impact, Haettenschweiler, 'Arial Narrow Bold', sans-serif\">{}</span>\n            </button>\n            <button id=\"text-lens-btn\" data-mode=\"text\" class=\"panel-tab-button lens-button\">\n                <span>Text \uD83D\uDCDD</span>\n            </button>\n            <button id=\"minigame-lens-btn\" data-mode=\"minigame\" class=\"panel-tab-button lens-button\">\n                <span>Minigame \u2328\uFE0F</span>\n            </button>\n        </div>\n    </div>\n</div>\n", ":host {\n    /* this is used for styling ibgib components for multi-view coordination, so\n     * that ibgib views that are looking at the same ibgib can be visibly shown\n     * as doing so. */\n    --ibgib-color: #ff00dd;\n    --ibgib-color-translucent: #ff00dd10;\n    --tjp-color: #00ffae;\n    --tjp-color-translucent: #00ffae10;\n    overflow: auto;\n    --close-tab-button-width: 20px;\n}\n\n/* Basic layout and styling for the project component */\n#project-component {\n    display: flex;\n    flex-direction: column;\n    align-items: stretch;\n    /* width: 100%; */\n    height: 100%;\n    box-sizing: border-box;\n    /* Use consistent padding */\n    padding: 1%;\n\n    /* ibgib styling */\n    border: var(--tjp-color) 5px solid;\n    box-shadow: 0 0 10px var(--tjp-color);\n    border-radius: 5px;\n\n    /* Optional: If using flexbox to control vertical alignment */\n    /* justify-content: center;  Align content vertically */\n\n\n    #project-header {\n        display: flex;\n        flex-direction: row;\n        height: 4%;\n\n        #project-header-tabs {\n            overflow-x: auto;\n            width: 90%;\n            /* scrollbar-color: rgba(16, 237, 35, 0.241) rgb(28, 109, 239); */\n            scrollbar-width: thin;\n            scrollbar-gutter: stable;\n            margin-bottom: -1%;\n            font-size: small;\n\n            /* header tab \"button\" (span) that has a child span (close \"X\" button) */\n            span:has(span) {\n                padding-right: calc(var(--close-tab-button-width) * 1.35);\n            }\n\n        }\n\n        button {\n            width: auto;\n            height: 100%;\n            aspect-ratio: 1/1 !important;\n\n            color: var(--tjp-color-contrast);\n            border-color: var(--tjp-color-contrast);\n            background-color: var(--tjp-color);\n\n\n            /* display: flex;\n            flex-direction: column;\n            justify-content: center; */\n\n            /* span {\n                position: relative;\n                bottom: 3px;\n            } */\n        }\n\n        button:hover {\n            border-width: 2px;\n            background-color: var(--button-hover-background-color);\n            color: var(--button-hover-text-color);\n            border-color: var(--button-hover-border-color);\n        }\n\n        .close-tab-button {\n            cursor: pointer;\n            box-sizing: border-box;\n            position: absolute;\n            top: 5px;\n            right: 5px;\n            background-color: rgba(255, 0, 0, 0.7);\n            color: white;\n            border: none;\n            border-radius: 50%;\n            width: var(--close-tab-button-width);\n            height: 20px;\n            font-size: 10px;\n            cursor: pointer;\n            display: flex;\n            align-items: center;\n            justify-content: center;\n            z-index: 1;\n            /* Ensure button is above content */\n        }\n\n        .close-tab-button:hover {\n            border-width: 3px;\n            background-color: #ff00cf;\n            color: var(--button-hover-text-color) !important;\n            border-color: var(--button-hover-border-color);\n            border-style: solid;\n        }\n\n        /* Add back the relative container for the button and popover */\n        .add-button-container,\n        .ellipsis-button-container {\n            background-color: transparent;\n            /* position: relative;\n            display: inline-block; */\n        }\n\n        /* Keep the styles for the popover options */\n        .add-popover-option,\n        .ellipsis-popover-option {\n            padding: 8px 15px;\n            margin-bottom: 2px;\n            cursor: pointer;\n            transition: background-color 0.2s ease;\n            background-color: var(--tab-background-color);\n            color: var(--tab-text-color);\n        }\n\n        /* Keep the styles for the popover options */\n        .add-popover-option:hover,\n        .ellipsis-popover-option:hover {\n            /* color: var(--tjp-color-contrast, #f0f0f0); */\n            color: contrast-color(var(--tjp-color, #f0f0f0));\n            background-color: var(--tjp-color, #f0f0f0);\n        }\n\n        /* Use anchor() for positioning */\n        .add-popover,\n        .ellipsis-popover {\n            /* bottom: anchor(top); */\n            /* Position the bottom of the popover at the top of the anchor */\n            /* left: anchor(left); */\n            /* Align the left of the popover with the left of the anchor */\n            flex-direction: column;\n            margin: 0px;\n            /* padding: 5px 0; */\n            border-radius: var(--border-radius, 4px);\n            background-color: var(--background-color, #fff);\n            border: 1px solid var(--border-color, #ccc);\n            box-shadow: var(--box-shadow, 0 2px 5px rgba(0, 0, 0, 0.2));\n            z-index: 10;\n            /* Ensure it appears above other content */\n        }\n\n        /* #project-name {\n            font-weight: bold;\n        }\n\n        #project-description {\n            white-space: pre-wrap;\n            font-style: italic;\n        }\n\n        #project-description.collapsed {\n            display: none;\n        } */\n    }\n\n    #project-content {\n        display: flex;\n        flex-direction: column;\n        height: 91%;\n        /* flex-grow: 1; */\n        overflow: auto;\n\n        :only-child {\n            height: 100%;\n            width: 100%;\n            box-sizing: border-box;\n        }\n    }\n\n    #project-footer {\n        height: 5%;\n\n        #ibgib-lens-bar {\n            height: 100%;\n            box-sizing: border-box;\n            display: flex;\n            flex-direction: row;\n            justify-content: space-evenly;\n            align-items: stretch;\n            overflow-x: auto;\n            overflow-y: hidden;\n            scrollbar-width: none;\n\n            /* I'm sharing panel tab buttons with this */\n            .lens-button {\n                /* display: flex;\n                flex-direction: row;\n                align-items: center;\n                justify-content: center; */\n                margin: calc(var(--tab-border-width) + 2) !important;\n                box-sizing: border-box;\n                border: var(--tab-border-width) var(--tab-border-style) var(--tab-border-color) !important;\n                border-radius: 25px;\n                min-width: 25%;\n                /* unset the transform inherited from panel tab buttons */\n                transform: unset;\n            }\n\n        }\n    }\n\n}\n\n/* ibgib-raw,\nibgib-text-editor {\n} */\n", "<div id=\"raw-component\" class=\"\">\n    <!-- have these both as panel-header just as a kluge to get the tabs to look\n    decent without bigger rewrite/investigation -->\n    <div id=\"raw-header\" class=\"raw-header panel-header\">\n        <h2 id=\"raw-name\">raw name loading...</h2>\n        <p id=\"raw-description\">raw description loading...</p>\n        <!-- <div id=\"raw-header-tabs\" class=\"raw-header-tabs panel-header\"> -->\n        <!-- looks something like this atow when dynamically added -->\n        <!--\n            <span id=\"raw-tab-button-{addr}\" class=\"panel-tab-button active\" title=\"untitled\">\n                untitled\n            </span>\n            -->\n        <!-- </div> -->\n        <!-- <button id=\"raw-header-add-btn\" class=\"tab-btn\">+</button> -->\n    </div>\n\n    <div id=\"raw-content\">\n\n        <section class=\"accordion\">\n            <section class=\"accordion-section\">\n                <h3 id=\"accordion-summary-header\" class=\"accordion-header\">summary</h3>\n                <div id=\"accordion-summary-content\" class=\"accordion-content\"></div>\n            </section>\n            <section class=\"accordion-section\">\n                <h3 id=\"accordion-ib-header\" class=\"accordion-header\">ib</h3>\n                <div id=\"accordion-ib-content\" class=\"accordion-content\"></div>\n            </section>\n            <section class=\"accordion-section\">\n                <h3 id=\"accordion-gib-header\" class=\"accordion-header\">gib</h3>\n                <div id=\"accordion-gib-content\" class=\"accordion-content\"></div>\n            </section>\n            <section class=\"accordion-section\">\n                <h3 id=\"accordion-data-header\" class=\"accordion-header\">data</h3>\n                <pre id=\"accordion-data-content\" class=\"accordion-content\"></pre>\n            </section>\n            <section class=\"accordion-section\">\n                <h3 id=\"accordion-rel8ns-header\" class=\"accordion-header\">rel8ns</h3>\n                <div id=\"accordion-rel8ns-content\" class=\"accordion-content\"></div>\n            </section>\n            <section class=\"accordion-section\">\n                <h3 id=\"accordion-raw-json-header\" class=\"accordion-header\">raw json</h3>\n                <pre id=\"raw-json\" class=\"accordion-content\"></pre>\n            </section>\n        </section>\n\n\n    </div>\n\n    <div id=\"raw-footer\" class=\"raw-footer\" style=\"display: none\">\n        <!-- <textarea id=\"raw-agent-input\" class=\"agent-input\" placeholder=\"raw agent loading...\"\n            readonly></textarea> -->\n        <!-- <button id=\"raw-agent-input-send-btn\" class=\"send-btn\"><b>\u276F</b></button> -->\n    </div>\n</div>\n", ":host {\n    /* this is used for styling ibgib components for multi-view coordination, so\n     * that ibgib views that are looking at the same ibgib can be visibly shown\n     * as doing so. */\n    --ibgib-color: #ff00dd;\n    --ibgib-color-translucent: #ff00dd10;\n    --tjp-color: #00ffae;\n    --tjp-color-translucent: #00ffae10;\n}\n\n/* Basic layout and styling for the raw component */\n#raw-component {\n    display: flex;\n    flex-direction: column;\n    align-items: stretch;\n    width: 100%;\n    height: 100%;\n    overflow: auto;\n    box-sizing: border-box;\n    /* Use consistent padding */\n    padding: 1%;\n\n    /* ibgib styling */\n    border: var(--tjp-color) 5px solid;\n    box-shadow: 0 0 10px var(--tjp-color);\n    border-radius: 5px;\n\n    /* Optional: If using flexbox to control vertical alignment */\n    /* justify-content: center;  Align content vertically */\n\n    #raw-header {\n        display: flex;\n        flex-direction: column;\n\n        #raw-name {\n            font-weight: bold;\n            /* font-size: larger; */\n            /* Use variables for spacing? */\n            /* margin-bottom: 0.5em; */\n        }\n\n        #raw-description {\n            /* Respect newlines */\n            white-space: pre-wrap;\n            font-style: italic;\n        }\n\n        #raw-description.collapsed {\n            display: none;\n        }\n    }\n\n    #raw-content {\n\n        .accordion-section {\n            display: flex;\n            flex-direction: column;\n            border: 1px solid #ccc;\n            margin-bottom: 5px;\n            border-radius: 4px;\n            /* For the slide-down effect */\n            overflow: hidden;\n        }\n\n        .accordion-header {\n            background-color: #f7f7f7;\n            cursor: pointer;\n            border-bottom: 1px solid #e0e0e0;\n            /* Prevent text selection */\n            user-select: none;\n            /* Remove default margin */\n            margin: 0;\n            padding: 10px 15px;\n\n            border: var(--tjp-color-contrast) 5px solid;\n            box-shadow: 0 0 10px var(--tjp-color);\n            color: var(--tjp-color-contrast);\n            background-color: var(--tjp-color);\n        }\n\n        .accordion-header:hover {\n            border: var(--tjp-color) 5px solid;\n            color: var(--tjp-color);\n            background-color: var(--tjp-color-contrast);\n        }\n\n        .accordion-content {\n            transition: padding 0.3s ease-in-out, max-height 0.3s ease-in-out;\n            /* display: none; */\n            max-height: 0px;\n            /* Hidden by default */\n            padding: 0;\n            margin: 0;\n\n            ul {\n                display: none;\n            }\n        }\n\n        .accordion-content.expanded {\n            padding: 10px 15px;\n            max-height: 33dvh !important;\n            /* Show all content */\n            overflow: auto;\n            border-top: 1px solid #e0e0e0;\n\n            ul {\n                display: block;\n            }\n        }\n\n        .accordion-content pre {\n            margin: 0;\n        }\n\n        pre {\n            white-space: pre-wrap;\n            /* overflow: auto; */\n            margin: 0px;\n        }\n    }\n\n\n}\n", "import thisHtml from './raw.html';\nimport thisCss from './raw.css';\nimport stylesCss from '../../../styles.css';\nimport projectCss from '../../projects/project/project.css';\nimport rootCss from '../../../root.css';\n\nimport { delay, extractErrorMsg, pretty, } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { IbGibAddr, } from \"@ibgib/ts-gib/dist/types.mjs\";\nimport { IbGib_V1 } from \"@ibgib/ts-gib/dist/V1/types.mjs\";\nimport { isPrimitive } from \"@ibgib/ts-gib/dist/V1/index.mjs\";\nimport { getIbAndGib, getIbGibAddr } from \"@ibgib/ts-gib/dist/helper.mjs\";\nimport { MetaspaceService } from \"@ibgib/core-gib/dist/witness/space/metaspace/metaspace-types.mjs\";\nimport { getTjpAddr } from \"@ibgib/core-gib/dist/common/other/ibgib-helper.mjs\";\nimport {\n    getDeterministicColorInfo, getGlobalMetaspace_waitIfNeeded,\n} from \"@ibgib/web-gib/dist/helpers.mjs\";\nimport {\n    IbGibDynamicComponentInstanceBase, IbGibDynamicComponentMetaBase,\n    IbGibDynamicComponentInstanceBase_ParentOfTabs,\n} from \"@ibgib/web-gib/dist/ui/component/ibgib-dynamic-component-bases.mjs\";\nimport {\n    ElementsBase, ChildInfoBase, IbGibDynamicComponentInstance,\n    IbGibDynamicComponentInstanceInitOpts,\n} from \"@ibgib/web-gib/dist/ui/component/component-types.mjs\";\nimport { getComponentSvc } from \"@ibgib/web-gib/dist/ui/component/ibgib-component-service.mjs\";\nimport { getColorStrings, } from \"@ibgib/web-gib/dist/helpers.mjs\";\nimport {\n    alertUser, copyToClipboard, highlightElement, promptForText,\n    shadowRoot_getElementById,\n} from \"@ibgib/web-gib/dist/helpers.web.mjs\";\nimport { askForPersistStorage, } from \"@ibgib/web-gib/dist/storage/storage-helpers.web.mjs\";\nimport { tellUserFunctionInfo } from \"@ibgib/web-gib/dist/api/commands/chat/tell-user.mjs\";\nimport { helloWorldFunctionInfo } from \"@ibgib/web-gib/dist/api/commands/chat/hello-world.mjs\";\n\nimport {\n    GLOBAL_LOG_A_LOT, ARMY_STORE, BEE_KEY, BLANK_GIB_DB_NAME,\n} from \"../../../constants.mjs\";\nimport { getComponentCtorArg, getIbGibGlobalThis_BlankGib, } from \"../../../helpers.web.mjs\";\nimport { storageGet, } from \"@ibgib/web-gib/dist/storage/storage-helpers.web.mjs\";\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\nexport const AGENT_SPECIAL_IBGIB_TYPE_RAWAGENT = 'rawagent';\nexport const CHAT_WITH_AGENT_PLACEHOLDER_RAWAGENT = '';\nexport const AGENT_AVAILABLE_FUNCTIONS_RAWAGENT = [\n    helloWorldFunctionInfo,\n    tellUserFunctionInfo,\n];\n\nexport const RAW_COMPONENT_NAME: string = 'ibgib-raw';\n\nexport class RawComponentMeta extends IbGibDynamicComponentMetaBase {\n    protected override lc: string = `[${RawComponentMeta.name}]`;\n\n    /**\n     * temporary regexp path for our initial dev. this component will become\n     * attached to actual ib^gib addrs\n     */\n    routeRegExp?: RegExp = new RegExp(RAW_COMPONENT_NAME);\n    // routeRegExp?: RegExp = /apps\\/web1\\/gib\\/contact.html/;\n\n    componentName: string = RAW_COMPONENT_NAME;\n\n    constructor() {\n        super(getComponentCtorArg());\n        customElements.define(this.componentName, RawComponentInstance);\n    }\n\n    async createInstance({\n        path,\n        ibGibAddr\n    }: {\n        path: string;\n        ibGibAddr: IbGibAddr;\n    }): Promise<IbGibDynamicComponentInstance> {\n        const lc = `${this.lc}[${this.createInstance.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: a997669f5cb8709578292be435166e25)`); }\n            const component = document.createElement(this.componentName) as RawComponentInstance;\n            await component.initialize({\n                ibGibAddr,\n                meta: this,\n                html: thisHtml,\n                css: [rootCss, stylesCss, projectCss, thisCss],\n            });\n            return component;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n}\n\ninterface RawElements {\n    headerEl: HTMLElement;\n    // headerTabsEl: HTMLElement | undefined;\n    nameEl: HTMLHeadingElement;\n    /**\n     *\n     */\n    descEl: HTMLParagraphElement;\n    /**\n     * container element for the component\n     */\n    contentEl: HTMLElement;\n    /**\n     * where the raw json is shown\n     */\n    rawJsonEl: HTMLPreElement;\n    rawJsonHeaderEl: HTMLHeadingElement;\n\n    summaryContentEl: HTMLDivElement;\n    summaryHeaderEl: HTMLHeadingElement;\n    ibContentEl: HTMLDivElement;\n    ibHeaderEl: HTMLHeadingElement;\n    gibContentEl: HTMLDivElement;\n    gibHeaderEl: HTMLHeadingElement;\n    dataContentEl: HTMLPreElement;\n    dataHeaderEl: HTMLHeadingElement;\n    rel8nsContentEl: HTMLDivElement;\n    rel8nsHeaderEl: HTMLHeadingElement;\n    footerEl: HTMLElement;\n    // addRawBtnEl: HTMLElement | undefined;\n}\n\n\nexport class RawComponentInstance\n    extends IbGibDynamicComponentInstanceBase<IbGib_V1, RawElements>\n    implements IbGibDynamicComponentInstance<IbGib_V1, RawElements> {\n    protected override lc: string = `[${RawComponentInstance.name}]`;\n\n    metaspace: MetaspaceService | undefined;\n\n    constructor() {\n        super();\n    }\n\n    override async initialize(opts: IbGibDynamicComponentInstanceInitOpts): Promise<void> {\n        const lc = `${this.lc}[${this.initialize.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 8ba1143239f8fc55943f1ead0ed19825)`); }\n            await super.initialize(opts);\n            await this.loadIbGib({ getLatest: true });\n            this.metaspace = await getGlobalMetaspace_waitIfNeeded();\n            this.agentsInitialized = this.initAgents();\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    override async created(): Promise<void> {\n        const lc = `${this.lc}[${this.created.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 21d2f2d6d4bd1dffa4e3a978d0013825)`); }\n\n            // const { meta, htmlPath, scriptPaths, cssPaths } = opts;\n\n            // at this point, this.ibGib should be loaded with the latest ibgib\n            if (!this.ibGib) { throw new Error(`(UNEXPECTED) this.ibGib falsy? It is assumed at this point that we have a valid ibGib to work with. (E: 0a6ef8dd4ed81c2c987b5a938df15825)`); }\n\n            await this.initElements();\n            await this.agentsInitialized;\n            await this.renderUI();\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    override async handleContextUpdated(): Promise<void> {\n        const lc = `${this.lc}[${this.handleContextUpdated.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 8e5798d584b8b9336d206c5cd4f91825)`); }\n            await super.handleContextUpdated();\n            await this.renderUI();\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private async initElements(): Promise<void> {\n        const lc = `${this.lc}[${this.initElements.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: ac8018ce75480022f8f696a88d1ac825)`); }\n\n            const shadowRoot = this.shadowRoot;\n\n            if (!shadowRoot) { throw new Error(`(UNEXPECTED) shadowRoot falsy? (E: 2c22482fa1cfff6eb82ff6e85f36e825)`); }\n\n            // #region header\n\n            const headerEl = shadowRoot_getElementById(shadowRoot, 'raw-header') as HTMLElement;\n            if (!headerEl) { throw new Error(`(UNEXPECTED) headerEl not found in shadowRoot? (E: 67e6710545181685280cd7f8d721a825)`); }\n\n            const nameEl = shadowRoot_getElementById<HTMLHeadingElement>(shadowRoot, 'raw-name');\n            const descEl = shadowRoot_getElementById<HTMLParagraphElement>(shadowRoot, 'raw-description');\n\n            // #endregion header\n\n            const contentEl = shadowRoot_getElementById(shadowRoot, 'raw-content');\n            if (!contentEl) { throw new Error(`(UNEXPECTED) contentEl not found in shadowRoot? (E: 28a7a8081c6d09fe59bd30ca94f9d225)`); }\n\n\n            // summaryContentEl: HTMLDivElement;\n            // summaryHeaderEl: HTMLHeadingElement;\n            const summaryContentEl = shadowRoot_getElementById<HTMLDivElement>(shadowRoot, 'accordion-summary-content');\n            const summaryHeaderEl = shadowRoot_getElementById<HTMLHeadingElement>(shadowRoot, 'accordion-summary-header');\n            const ibContentEl = shadowRoot_getElementById<HTMLDivElement>(shadowRoot, 'accordion-ib-content');\n            const ibHeaderEl = shadowRoot_getElementById<HTMLHeadingElement>(shadowRoot, 'accordion-ib-header');\n            const gibContentEl = shadowRoot_getElementById<HTMLDivElement>(shadowRoot, 'accordion-gib-content');\n            const gibHeaderEl = shadowRoot_getElementById<HTMLHeadingElement>(shadowRoot, 'accordion-gib-header');\n            const dataContentEl = shadowRoot_getElementById<HTMLPreElement>(shadowRoot, 'accordion-data-content');\n            const dataHeaderEl = shadowRoot_getElementById<HTMLHeadingElement>(shadowRoot, 'accordion-data-header');\n            const rel8nsContentEl = shadowRoot_getElementById<HTMLDivElement>(shadowRoot, 'accordion-rel8ns-content');\n            const rel8nsHeaderEl = shadowRoot_getElementById<HTMLHeadingElement>(shadowRoot, 'accordion-rel8ns-header');\n            const rawJsonEl = shadowRoot_getElementById<HTMLPreElement>(shadowRoot, 'raw-json');\n            const rawJsonHeaderEl = shadowRoot_getElementById<HTMLHeadingElement>(shadowRoot, 'accordion-raw-json-header');\n\n            [\n                [summaryHeaderEl, summaryContentEl],\n                [ibHeaderEl, ibContentEl],\n                [gibHeaderEl, gibContentEl],\n                [dataHeaderEl, dataContentEl],\n                [rel8nsHeaderEl, rel8nsContentEl],\n                [rawJsonHeaderEl, rawJsonEl],\n            ].forEach((entry: any) => {\n                const [headerEl, contentEl] = entry as [HTMLElement, HTMLElement];\n                headerEl.addEventListener('click', (_event: any) => {\n                    contentEl.classList.toggle('expanded');\n                    // if (contentEl.style.display === 'flex') {\n                    //     contentEl.style.display = 'none';\n                    // } else {\n                    //     contentEl.style.display = 'flex';\n                    // }\n                });\n            });\n\n\n            const footerEl = shadowRoot_getElementById(shadowRoot, 'raw-footer');\n            footerEl.style.display = 'none';\n            // this.footerEl = footerEl as HTMLElement;\n\n            this.elements = {\n                headerEl,\n                // headerTabsEl,\n                contentEl,\n                summaryContentEl, ibContentEl, gibContentEl, dataContentEl, rel8nsContentEl, rawJsonEl,\n                summaryHeaderEl, ibHeaderEl, gibHeaderEl, dataHeaderEl, rel8nsHeaderEl, rawJsonHeaderEl,\n                footerEl,\n                nameEl,\n                descEl,\n            };\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * rerender\n     */\n    protected override async renderUI(): Promise<void> {\n        const lc = `${this.lc}[${this.renderUI.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: d494833e5fdf2f093d3168bfe0311c25)`); }\n\n            await super.renderUI();\n\n            if (!this.ibGib) {\n                console.error(`${lc} this.ibGib falsy? (E: 870c08ece4882245422c3921b43d0825)`)\n                return; /* <<<< returns early */\n            }\n\n            if (!this.elements) {\n                console.warn(`${lc} (UNEXPECTED) tried to render but haven't initialized elements? (W: bb8368d991181d65c8a8e288725ebf25)`);\n                return; /* <<<< returns early */\n            }\n\n            const {\n                headerEl,\n                contentEl,\n                summaryContentEl,\n                ibContentEl, gibContentEl, dataContentEl, rel8nsContentEl,\n                rawJsonEl,\n                footerEl,\n                nameEl, descEl,\n            } = this.elements;\n\n            nameEl.textContent = this.ibGib?.data?.name ?? this.ibGib?.ib;\n            nameEl.textContent += ` (v${this.ibGib?.data?.n ?? '?'})`\n\n            const description = this.ibGib?.data?.description;\n            if (description) {\n                descEl.textContent = description;\n            } else {\n                descEl.style.display = 'none';\n            }\n\n\n            summaryContentEl.innerHTML = '';\n            const summaryUlEl = document.createElement('ul');\n            const fnAddLi = (label: string, value: string) => {\n                const liLabelEl = document.createElement('li');\n                liLabelEl.textContent = `${label}: `;\n                liLabelEl.style.fontWeight = 'bold';\n                liLabelEl.style.listStyle = 'none';\n                const liValueEl = document.createElement('li');\n                liValueEl.textContent = value;\n                liValueEl.style.marginLeft = '1em';\n                liValueEl.style.fontWeight = '100';\n                liLabelEl.appendChild(liValueEl);\n                summaryUlEl.appendChild(liLabelEl);\n            };\n            fnAddLi('addr', this.ibGibAddr);\n            fnAddLi('TJP addr', getTjpAddr({ ibGib: this.ibGib!, defaultIfNone: \"incomingAddr\" })!);\n            const { data } = this.ibGib;\n            if (data) {\n                if (data.name) { fnAddLi(\"name\", data.name); }\n                if (data.description) { fnAddLi(\"description\", data.description); }\n                if (data.text) { fnAddLi(\"text\", data.text); }\n                if (data.textTimestamp) { fnAddLi(\"textTimestamp\", data.textTimestamp); }\n                if (data.timestamp) { fnAddLi(\"timestamp\", data.timestamp) }\n                if (data.timestampMs) { fnAddLi(\"timestampMs\", data.timestampMs.toString()); }\n                if (data.type) { fnAddLi(\"type\", data.type) }\n            }\n            summaryContentEl.appendChild(summaryUlEl);\n\n\n            ibContentEl.innerHTML = '';\n            ibContentEl.textContent = this.ibGib?.ib ?? '';\n            gibContentEl.innerHTML = '';\n            gibContentEl.textContent = this.ibGib?.gib ?? '';\n            dataContentEl.innerHTML = '';\n            dataContentEl.textContent = this.ibGib?.data ? pretty(this.ibGib.data) : 'undefined';\n\n            rel8nsContentEl.innerHTML = '';\n            if (this.ibGib?.rel8ns) {\n                const rel8nsSubAccordion = document.createElement('section');\n                rel8nsSubAccordion.classList.add('accordion');\n                rel8nsContentEl.appendChild(rel8nsSubAccordion);\n                for (const rel8nName in this.ibGib.rel8ns) {\n                    const rel8nNameSection = document.createElement('section');\n                    rel8nNameSection.classList.add('accordion-section');\n                    rel8nsSubAccordion.appendChild(rel8nNameSection);\n\n                    const headerEl = document.createElement('h3');\n                    headerEl.classList.add('accordion-header');\n                    headerEl.textContent = rel8nName;\n                    headerEl.addEventListener('click', (_event: any) => {\n                        contentEl.classList.toggle('expanded');\n                    });\n                    rel8nNameSection.appendChild(headerEl);\n                    const contentEl = document.createElement('div');\n                    contentEl.classList.add('accordion-content');\n                    rel8nNameSection.appendChild(contentEl);\n\n                    const ulRel8dsEl = document.createElement('ul');\n                    contentEl.appendChild(ulRel8dsEl);\n\n                    this.ibGib.rel8ns[rel8nName]?.forEach(rel8dAddr => {\n                        const liRel8dEl = document.createElement('li');\n                        if (isPrimitive({ gib: getIbAndGib({ ibGibAddr: rel8dAddr }).gib })) {\n                            // just add text, no need for a link\n                            liRel8dEl.textContent = rel8dAddr;\n                        } else {\n                            // non-primitives get a link that can be opened as a\n                            // tab in the project window\n                            const addrEl = document.createElement('a');\n                            addrEl.style.cursor = 'pointer';\n                            addrEl.textContent = rel8dAddr;\n                            addrEl.addEventListener('click', async (_event: Event) => {\n                                _event.stopPropagation();\n                                _event.preventDefault();\n                                await getIbGibGlobalThis_BlankGib()\n                                    .projectsComponent!\n                                    .activeProjectTabInfo!\n                                    .component!\n                                    .activateIbGib({\n                                        addr: rel8dAddr,\n                                    });\n                            });\n                            liRel8dEl.appendChild(addrEl);\n                        }\n                        ulRel8dsEl.appendChild(liRel8dEl);\n                    });\n                }\n\n                // const rel8nsUlEl = document.createElement('ul');\n                // rel8nsContentEl.appendChild(rel8nsUlEl);\n                // for (const rel8nName in this.ibGib.rel8ns) {\n                //     const liEl = document.createElement('li');\n                //     liEl.textContent = rel8nName;\n                //     const ulRel8dsEl = document.createElement('ul');\n                //     liEl.appendChild(ulRel8dsEl);\n                //     this.ibGib.rel8ns[rel8nName]?.forEach(rel8dAddr => {\n                //         const liRel8dEl = document.createElement('li');\n                //         const addrEl = document.createElement('a');\n                //         addrEl.style.cursor = 'pointer';\n                //         addrEl.textContent = rel8dAddr;\n                //         addrEl.addEventListener('click', async (_event: any) => {\n                //             // TODO: navigate to the raw component for this rel8dAddr\n                //             await getIbGibGlobalThis_BlankGib().projectsComponent!.activeProjectTabInfo!.component!.activateIbGib({\n                //                 addr: rel8dAddr,\n                //             });\n                //         });\n                //         liRel8dEl.appendChild(addrEl);\n                //         ulRel8dsEl.appendChild(liRel8dEl);\n                //     });\n                //     rel8nsUlEl.appendChild(liEl);\n                // }\n            } else {\n                rel8nsContentEl.textContent = 'undefined';\n            }\n\n\n\n\n            rawJsonEl.innerHTML = '';\n            rawJsonEl.textContent = pretty(this.ibGib);\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    override async disconnected(): Promise<void> {\n        const lc = `${this.lc}[${this.disconnected.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 72d05cd42cf81ebf1a29051a290f7825)`); }\n            // no action atow\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    protected override async initAgents(): Promise<void> {\n        const lc = `${this.lc}[${this.initAgents.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 8f8081efdd78f10018ab5fa702e24725)`); }\n\n            await this.loadAgentsCoupledToIbGib({ dontThrowIfNone: true });\n\n            // if (!this.agent) { throw new Error(`(UNEXPECTED) agent falsy after createNewAgent? (E: 37b04a4faae783e0b8d973d8956d2825)`); }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * inits the chronology in the right panel for web1 components\n     */\n    private async initChronology(): Promise<void> {\n        const lc = `${this.lc}[${this.initChronology.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 84f8e1a3e8a4ac1dc8d24244fb583f25)`); }\n\n            const globalIbGib = getIbGibGlobalThis_BlankGib();\n            let chronologysComponent = globalIbGib.chronologysComponent;\n\n            let count = 0;\n            while (!chronologysComponent) {\n                console.warn(`${lc} global chronologysComponent is expected to be truthy by now. delaying (W: f5d8a2abb3c8015cd740da78e14fa725)`)\n                count++;\n                if (count > 100) {\n                    debugger; // error in web1 component expectation\n                    throw new Error(`(UNEXPECTED) global chronologysComponent is falsy? (E: cc1848e6910886ef1cc0ea536897d425)`);\n                }\n                await delay(100);\n            }\n\n            if (!this.ibGibProxy) { throw new Error(`(UNEXPECTED) this.ibGibProxy falsy? (E: 4546c939a8b835ede8d82e28effaa825)`); }\n            // ibGibProxy.ibGib is a comment ibgib that is data.n=2. the 2 is\n            // because it is already related to an agent.\n\n            await chronologysComponent.openIbGibAddr({\n                ibGibAddr: getIbGibAddr({ ibGib: this.ibGibProxy.ibGib }),\n            });\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private getAPIKey(): Promise<string> {\n        const fn = this.getFnGetAPIKey();\n        return fn();\n    }\n    private getFnGetAPIKey(): () => Promise<string> {\n        const lc = `${this.lc}[${this.getFnGetAPIKey.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 80a71d5cb578b0f01f14c9a2ee67cd25)`); }\n\n            const fn = async () => {\n                let apiKey = await storageGet({\n                    dbName: BLANK_GIB_DB_NAME, storeName: ARMY_STORE,\n                    key: BEE_KEY,\n                });\n                return apiKey ?? '';\n            };\n            return fn;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n}\n", "<div id=\"text-editor-component\" class=\"\">\n    <!-- have these both as panel-header just as a kluge to get the tabs to look\n    decent without bigger rewrite/investigation -->\n    <div id=\"text-editor-header\" class=\"text-editor-header panel-header\">\n        <h2 id=\"text-editor-name\">text name loading...</h2><span id=\"text-editor-version\"></span>\n        <p id=\"text-editor-description\">text description loading...</p>\n        <!-- <div id=\"text-editor-header-tabs\" class=\"text-editor-header-tabs panel-header\"> -->\n        <!-- looks something like this atow when dynamically added -->\n        <!--\n            <span id=\"text-editor-tab-button-{addr}\" class=\"panel-tab-button active\" title=\"untitled\">\n                untitled\n            </span>\n            -->\n        <!-- </div> -->\n        <!-- <button id=\"text-editor-header-add-btn\" class=\"tab-btn\">+</button> -->\n    </div>\n\n    <div id=\"text-editor-content\">\n\n        <textarea id=\"text-editor\"></textarea>\n\n    </div>\n\n    <div id=\"text-editor-footer\" class=\"text-editor-footer\" style=\"display: none\">\n        <!-- <textarea id=\"text-editor-agent-input\" class=\"agent-input\" placeholder=\"text agent loading...\"\n            readonly></textarea> -->\n        <!-- <button id=\"text-editor-agent-input-send-btn\" class=\"send-btn\"><b>\u276F</b></button> -->\n    </div>\n</div>\n", ":host {\n    /* this is used for styling ibgib components for multi-view coordination, so\n     * that ibgib views that are looking at the same ibgib can be visibly shown\n     * as doing so. */\n    --ibgib-color: #ff00dd;\n    --ibgib-color-translucent: #ff00dd10;\n    --tjp-color: #00ffae;\n    --tjp-color-translucent: #00ffae10;\n}\n\n/* Basic layout and styling for the raw component */\n#text-editor-component {\n    display: flex;\n    flex-direction: column;\n    align-items: stretch;\n    width: 100%;\n    height: 100%;\n    overflow: auto;\n    box-sizing: border-box;\n    /* Use consistent padding */\n    padding: 1%;\n    overflow: hidden;\n\n    /* ibgib styling */\n    border: var(--tjp-color) 5px solid;\n    box-shadow: 0 0 10px var(--tjp-color);\n    border-radius: 5px;\n\n    /* Optional: If using flexbox to control vertical alignment */\n    /* justify-content: center;  Align content vertically */\n\n    #text-editor-header {\n        display: flex;\n        flex-direction: row;\n        height: 5%;\n\n        #text-editor-name {\n            width: 25%;\n            font-weight: bold;\n            font-size: x-small;\n            overflow-x: clip;\n        }\n\n        #text-editor-version {\n            width: 8%;\n            font-weight: lighter;\n            font-size: x-small;\n            font-style: italic;\n        }\n\n        #text-editor-description {\n            width: 67%;\n            white-space: pre-wrap;\n            font-style: italic;\n            font-size: xx-small;\n        }\n\n        /* #text-editor-description.collapsed {\n            display: none;\n        } */\n    }\n\n    #text-editor-content {\n        height: 95%;\n\n        textarea {\n            height: 100%;\n            width: 100%;\n            word-wrap: normal;\n            text-wrap: stable;\n            text-wrap-mode: wrap;\n            margin: 0px;\n            resize: none;\n            overflow: auto;\n        }\n    }\n\n\n}\n", "import thisHtml from './text-editor.html';\nimport thisCss from './text-editor.css';\nimport stylesCss from '../../../styles.css';\nimport rootCss from '../../../root.css';\n\nimport { delay, extractErrorMsg, getTimestamp, getTimestampInTicks, pretty, } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { IbGibAddr, } from \"@ibgib/ts-gib/dist/types.mjs\";\nimport { getIbGibAddr } from \"@ibgib/ts-gib/dist/helper.mjs\";\nimport { IbGib_V1 } from \"@ibgib/ts-gib/dist/V1/types.mjs\";\nimport { MetaspaceService } from \"@ibgib/core-gib/dist/witness/space/metaspace/metaspace-types.mjs\";\nimport { mut8Timeline } from \"@ibgib/core-gib/dist/timeline/timeline-api.mjs\";\nimport {\n    getDeterministicColorInfo, getGlobalMetaspace_waitIfNeeded,\n} from \"@ibgib/web-gib/dist/helpers.mjs\";\nimport {\n    IbGibDynamicComponentInstanceBase, IbGibDynamicComponentMetaBase,\n    IbGibDynamicComponentInstanceBase_ParentOfTabs,\n} from \"@ibgib/web-gib/dist/ui/component/ibgib-dynamic-component-bases.mjs\";\nimport {\n    ElementsBase, ChildInfoBase, IbGibDynamicComponentInstance,\n    IbGibDynamicComponentInstanceInitOpts,\n} from \"@ibgib/web-gib/dist/ui/component/component-types.mjs\";\nimport { getComponentSvc } from \"@ibgib/web-gib/dist/ui/component/ibgib-component-service.mjs\";\nimport { getColorStrings, } from \"@ibgib/web-gib/dist/helpers.mjs\";\nimport {\n    alertUser, copyToClipboard, highlightElement, promptForText,\n    shadowRoot_getElementById,\n} from \"@ibgib/web-gib/dist/helpers.web.mjs\";\nimport { askForPersistStorage, } from \"@ibgib/web-gib/dist/storage/storage-helpers.web.mjs\";\nimport { tellUserFunctionInfo } from \"@ibgib/web-gib/dist/api/commands/chat/tell-user.mjs\";\nimport { helloWorldFunctionInfo } from \"@ibgib/web-gib/dist/api/commands/chat/hello-world.mjs\";\nimport { storageGet, } from \"@ibgib/web-gib/dist/storage/storage-helpers.web.mjs\";\nimport { debounce } from \"@ibgib/web-gib/dist/helpers.mjs\";\n\nimport {\n    GLOBAL_LOG_A_LOT, ARMY_STORE, BEE_KEY, BLANK_GIB_DB_NAME,\n} from \"../../../constants.mjs\";\nimport { getComponentCtorArg, getIbGibGlobalThis_BlankGib, } from \"../../../helpers.web.mjs\";\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\nexport const AGENT_AVAILABLE_FUNCTIONS_TEXTEDITORAGENT = [\n    tellUserFunctionInfo,\n];\n\nexport const TEXTEDITOR_COMPONENT_NAME: string = 'ibgib-text-editor';\n\nexport class TextEditorComponentMeta extends IbGibDynamicComponentMetaBase {\n    protected override lc: string = `[${TextEditorComponentMeta.name}]`;\n\n    /**\n     * temporary regexp path for our initial dev. this component will become\n     * attached to actual ib^gib addrs\n     */\n    routeRegExp?: RegExp = new RegExp(TEXTEDITOR_COMPONENT_NAME);\n    // routeRegExp?: RegExp = /apps\\/web1\\/gib\\/contact.html/;\n\n    componentName: string = TEXTEDITOR_COMPONENT_NAME;\n\n    constructor() {\n        super(getComponentCtorArg());\n        customElements.define(this.componentName, TextEditorComponentInstance);\n    }\n\n    async createInstance({\n        path,\n        ibGibAddr\n    }: {\n        path: string;\n        ibGibAddr: IbGibAddr;\n    }): Promise<IbGibDynamicComponentInstance> {\n        const lc = `${this.lc}[${this.createInstance.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n            const component = document.createElement(this.componentName) as TextEditorComponentInstance;\n            await component.initialize({\n                ibGibAddr,\n                meta: this,\n                html: thisHtml,\n                css: [rootCss, stylesCss, thisCss],\n            });\n            return component;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n}\n\ninterface TextEditorElements {\n    headerEl: HTMLElement;\n    // headerTabsEl: HTMLElement | undefined;\n    nameEl: HTMLHeadingElement;\n    versionEl: HTMLSpanElement;\n    /**\n     *\n     */\n    descEl: HTMLParagraphElement;\n    /**\n     * container element for the component\n     */\n    contentEl: HTMLElement;\n    /**\n     * where the text-editor is shown\n     */\n    editorEl: HTMLTextAreaElement;\n    footerEl: HTMLElement;\n    // addTextEditorBtnEl: HTMLElement | undefined;\n}\n\n\nexport class TextEditorComponentInstance\n    extends IbGibDynamicComponentInstanceBase<IbGib_V1, TextEditorElements>\n    implements IbGibDynamicComponentInstance<IbGib_V1, TextEditorElements> {\n    protected override lc: string = `[${TextEditorComponentInstance.name}]`;\n\n    metaspace: MetaspaceService | undefined;\n\n    busy: boolean = false;\n\n    constructor() {\n        super();\n    }\n\n    override async initialize(opts: IbGibDynamicComponentInstanceInitOpts): Promise<void> {\n        const lc = `${this.lc}[${this.initialize.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n            await super.initialize(opts);\n            await this.loadIbGib({ getLatest: true });\n            this.metaspace = await getGlobalMetaspace_waitIfNeeded();\n            this.agentsInitialized = this.initAgents();\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    override async created(): Promise<void> {\n        const lc = `${this.lc}[${this.created.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n\n            // const { meta, htmlPath, scriptPaths, cssPaths } = opts;\n\n            // at this point, this.ibGib should be loaded with the latest ibgib\n            if (!this.ibGib) { throw new Error(`(UNEXPECTED) this.ibGib falsy? It is assumed at this point that we have a valid ibGib to work with. (E: genuuid)`); }\n\n            await this.initElements();\n            await this.agentsInitialized;\n            await this.renderUI();\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    override async handleContextUpdated(): Promise<void> {\n        const lc = `${this.lc}[${this.handleContextUpdated.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n            await super.handleContextUpdated();\n            await this.renderUI();\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private async initElements(): Promise<void> {\n        const lc = `${this.lc}[${this.initElements.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n\n            const shadowRoot = this.shadowRoot;\n\n            if (!shadowRoot) { throw new Error(`(UNEXPECTED) shadowRoot falsy? (E: genuuid)`); }\n\n            // #region header\n\n            const headerEl = shadowRoot.getElementById('text-editor-header') as HTMLElement;\n            if (!headerEl) { throw new Error(`(UNEXPECTED) headerEl not found in shadowRoot? (E: genuuid)`); }\n\n            const nameEl = shadowRoot.getElementById('text-editor-name') as HTMLHeadingElement;\n            if (!nameEl) { throw new Error(`(UNEXPECTED) nameEl not found in shadowRoot? (E: genuuid)`); }\n            const versionEl = shadowRoot.getElementById('text-editor-version') as HTMLHeadingElement;\n            if (!versionEl) { throw new Error(`(UNEXPECTED) versionEl not found in shadowRoot? (E: genuuid)`); }\n            const descEl = shadowRoot.getElementById('text-editor-description') as HTMLParagraphElement;\n            if (!descEl) { throw new Error(`(UNEXPECTED) descEl not found in shadowRoot? (E: genuuid)`); }\n\n            // #endregion header\n\n            const contentEl = shadowRoot.getElementById('text-editor-content') as HTMLElement;\n            if (!contentEl) { throw new Error(`(UNEXPECTED) contentEl not found in shadowRoot? (E: genuuid)`); }\n\n            const editorEl = shadowRoot.getElementById('text-editor') as HTMLTextAreaElement;\n            if (!editorEl) { throw new Error(`(UNEXPECTED) editorEl not found in shadowRoot? (E: genuuid)`); }\n\n            const footerEl = shadowRoot.getElementById('text-editor-footer') as HTMLElement;\n            if (!footerEl) { throw new Error(`(UNEXPECTED) footerEl not found in shadowRoot? (E: genuuid)`); }\n            footerEl.style.display = 'none';\n            // this.footerEl = footerEl as HTMLElement;\n\n            this.elements = {\n                headerEl,\n                // headerTabsEl,\n                contentEl,\n                editorEl,\n                footerEl,\n                nameEl,\n                versionEl,\n                descEl,\n            };\n\n            await this.initTextEditor({ editorEl });\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private async initTextEditor({\n        editorEl,\n    }: {\n        editorEl: HTMLTextAreaElement;\n    }): Promise<void> {\n        const lc = `${this.lc}[${this.initTextEditor.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: e357a2aacec86dbed87087c2316a6325)`); }\n\n            // const debouncedSave: ((content: string) => Promise<void>) | undefined = undefined;\n\n            // Assuming you have a method like saveContent that handles saving the textarea content\n            let saving = false;\n            const saveContent = async (text: string) => {\n                // Your save logic here (e.g., calling mut8Timeline to update the ibGib data)\n                while (saving) {\n                    console.warn(`${lc} already saving. waiting for previous save to finish.`);\n                    await delay(100);\n                }\n                saving = true;\n                this.busy = true;\n                try {\n                    if (!this.ibGib) { throw new Error(`(UNEXPECTED) this.ibGib falsy?? (E: b857c8b781184ca347b69fe820af7825)`); }\n                    if (!this.ibGib.data) { throw new Error(`(UNEXPECTED) this.ibGib.data falsy? (E: 3f1bc222c2ad2e559ca15e0c8907b825)`); }\n                    if (text === this.ibGib.data.text) {\n                        console.log(`${lc} text unchanged. save unnecessary. (I: 20140db9a5538374f80a35e230fcd825)`);\n                        return; /* <<<< returns early */\n                    }\n                    if (logalot) { console.log(`${lc}[${getTimestampInTicks()}] Saving content: ${text} (I: 60eb382b3078c40308a55f289d081825)`); }\n                    if (!this.metaspace) { throw new Error(`(UNEXPECTED) this.metaspace falsy? (E: bbe5380b4198bedfe8a7a7e8d1b05f25)`); }\n                    await mut8Timeline({\n                        metaspace: this.metaspace,\n                        mut8Opts: {\n                            dataToAddOrPatch: {\n                                text,\n                                textTimestamp: getTimestamp(),\n                            }\n                        },\n                        space: undefined,// ? where should the space reside? this editor component? the project? what about if we're editing an agent's internal space ibgib? or just some other ibgib? this forces us to only edit in the default local user space\n                        timeline: this.ibGib,\n                    });\n                } catch (error) {\n                    console.error(`${lc} ${extractErrorMsg(error)}`);\n                    throw error;\n                } finally {\n                    saving = false;\n                    this.busy = false;\n                }\n            };\n\n            // Create the debounced version of the saveContent function\n            // Debounce with a wait time of, say, 5 seconds\n            const debouncedSave = debounce(saveContent, 5_000);\n\n            // Add an event listener to the textarea\n            editorEl.addEventListener('input', async (event) => {\n                const target = event.target as HTMLTextAreaElement;\n                this.busy = true;\n                await this.renderUI_status();\n                debouncedSave(target.value);\n            });\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * rerender\n     */\n    protected override async renderUI(): Promise<void> {\n        const lc = `${this.lc}[${this.renderUI.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n\n            await super.renderUI();\n\n            if (!this.elements) {\n                console.warn(`${lc} (UNEXPECTED) tried to render but haven't initialized elements? (W: genuuid)`);\n                return; /* <<<< returns early */\n            }\n\n            const {\n                headerEl,\n                contentEl,\n                editorEl,\n                footerEl,\n                nameEl, versionEl, descEl,\n            } = this.elements;\n\n            nameEl.textContent = this.ibGib?.data?.name ?? '[ibGib no name?]'\n\n            const description = this.ibGib?.data?.description;\n            if (description) {\n                descEl.textContent = description;\n            } else {\n                descEl.style.display = 'none';\n            }\n\n            // editorEl.innerHTML = '';\n            if (this.ibGib) {\n                if (!this.ibGib.data) { throw new Error(`(UNEXPECTED) this.ibGib.data falsy? (E: f65e38b3c0cbf66d5db5fd9a6b404125)`); }\n                editorEl.textContent = this.ibGib.data.text ?? '';\n            } else {\n                console.warn(`${lc} this.ibGib falsy? skipping init text(W: genuuid)`)\n            }\n            await this.renderUI_status();\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private async renderUI_status(): Promise<void> {\n        const lc = `${this.lc}[${this.renderUI_status.name}]`;\n        if (!this.elements) {\n            console.warn(`${lc} this.elements falsy?returning early. (W: bce618e9c22184e16884835840fdf825)`);\n            return; /* <<<< returns early */\n        }\n        const { versionEl } = this.elements;\n        versionEl.textContent = this.busy ? `(...)` : `(v${this.ibGib?.data?.n ?? '?'})`\n    }\n\n    override async disconnected(): Promise<void> {\n        const lc = `${this.lc}[${this.disconnected.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n            // no action atow\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    protected override async initAgents(): Promise<void> {\n        const lc = `${this.lc}[${this.initAgents.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n\n            await this.loadAgentsCoupledToIbGib();\n\n            if (!this.agent) { throw new Error(`(UNEXPECTED) agent falsy after createNewAgent? (E: genuuid)`); }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * inits the chronology in the right panel for web1 components\n     */\n    private async initChronology(): Promise<void> {\n        const lc = `${this.lc}[${this.initChronology.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n\n            const globalIbGib = getIbGibGlobalThis_BlankGib();\n            let chronologysComponent = globalIbGib.chronologysComponent;\n\n            let count = 0;\n            while (!chronologysComponent) {\n                console.warn(`${lc} global chronologysComponent is expected to be truthy by now. delaying (W: genuuid)`)\n                count++;\n                if (count > 100) {\n                    debugger; // error in web1 component expectation\n                    throw new Error(`(UNEXPECTED) global chronologysComponent is falsy? (E: genuuid)`);\n                }\n                await delay(100);\n            }\n\n            if (!this.ibGibProxy) { throw new Error(`(UNEXPECTED) this.ibGibProxy falsy? (E: genuuid)`); }\n            // ibGibProxy.ibGib is a comment ibgib that is data.n=2. the 2 is\n            // because it is already related to an agent.\n\n            await chronologysComponent.openIbGibAddr({\n                ibGibAddr: getIbGibAddr({ ibGib: this.ibGibProxy.ibGib }),\n            });\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private getAPIKey(): Promise<string> {\n        const fn = this.getFnGetAPIKey();\n        return fn();\n    }\n    private getFnGetAPIKey(): () => Promise<string> {\n        const lc = `${this.lc}[${this.getFnGetAPIKey.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n\n            const fn = async () => {\n                let apiKey = await storageGet({\n                    dbName: BLANK_GIB_DB_NAME, storeName: ARMY_STORE,\n                    key: BEE_KEY,\n                });\n                return apiKey ?? '';\n            };\n            return fn;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n}\n", "import {\n    AGENT_INITIAL_CHAT_GIVESELFNAME, AGENT_INITIAL_CHAT_HELLOWORLD\n} from \"@ibgib/web-gib/dist/agent-texts/common-agent-texts.mjs\";\n\nimport {\n    AGENT_GOAL_COMMON, AGENT_SYSTEM_PROMPT_COMMON_INSTRUCTIONS,\n    AGENT_WEBSITE_DESCRIPTION,\n} from \"./common-agent-texts.mjs\";\nimport { AGENT_WEBSITE_DESCRIPTION_PROJECTCAVEAT } from \"./project-agent-texts.mjs\";\n\nexport const AGENT_SPECIAL_IBGIB_TYPE_PROJECTCHILDTEXTAGENT = 'projectchildtextagent';\nexport const AGENT_GOAL_PROJECTCHILDTEXTAGENT = [\n    AGENT_GOAL_COMMON,\n    `You yourself are a \"project child text\" agent. Now \"project\" is a funny word in ibgib, as previously stated, a granular \"version control\"-like system. If you are working on an ibgib that represents what nowadays is a src code repo, then that obviously is a \"project\". In fact, it may be multiple projects, just as a current-day repo may have multiple packages. But with ibgib especially, _any_ \"thing\" may be broken down into sub-\"things\" which themselves can be \"version controlled\" (have a dedicated focus on their timeline). The word we're using for this is \"project\".`,\n    `A project can have multiple \"child\" ibgibs across multiple rel8nNames (excluding reserved rel8ns like \"dna\", \"past\", \"ancestor\", \"tjp\"). These ibgibs are similar to imports in a code library, in that they have their own timeline but are related and/or utilized in the project in some way.`,\n    `A child text ibgib is an ibgib that acts like a semantic text entity. This could be a paragraph, a section, a title, or even an entire text \"file\". But since ibgib is aiming to work at the semantic level and not at the \"file\" level, this is arbitrary.`,\n    `It's your job to help the user edit and analyze the text, discuss it with the user and possibly other agent(s)/user(s), as well as perform ibgib-specific actions on the text, like possibly a \"chunk\" like action that splits a text into multiple other text ibgibs.`,\n    `It's early days though, so not all actions will be implemented and new ones will be added as we go. At the very least, you should be able to read your text ibgib (via getContextInfo or similar if the name changes) and discuss it (via tellUser). Note that tellUser will change the text ibgib's address, because each comment added \"to\" it are done via a rel8 transform, which appends to the ibgib's timeline and thus the hash of the record will change. But not necessarily its internal text (what today you would think of as the \"contents\" of the text file).`,\n    `Soon you will also be able to save the text ibgib, which will perform a mut8 on the ibgib (and thus its timeline).`,\n].join('\\n');\nexport const AGENT_INITIAL_SYSTEM_TEXT_PROJECTCHILDTEXTAGENT = [\n    AGENT_SYSTEM_PROMPT_COMMON_INSTRUCTIONS,\n    AGENT_WEBSITE_DESCRIPTION,\n    AGENT_WEBSITE_DESCRIPTION_PROJECTCAVEAT,\n    AGENT_GOAL_PROJECTCHILDTEXTAGENT,\n].join('\\n');\nconst AGENT_INITIAL_CHAT_HI_PLEASEINTRO_YOURSELF_PROJECTCHILDTEXTAGENT = [\n    AGENT_INITIAL_CHAT_GIVESELFNAME,\n    AGENT_INITIAL_CHAT_HELLOWORLD,\n].join('\\n');\nexport const AGENT_INITIAL_CHAT_TEXT_PROJECTCHILDTEXTAGENT = [\n    AGENT_INITIAL_CHAT_HI_PLEASEINTRO_YOURSELF_PROJECTCHILDTEXTAGENT,\n].join('\\n');\n", "import { APIFunctionInfo } from \"@ibgib/web-gib/dist/api/api-types.mjs\";\nimport { SETTINGS_ATOM } from \"@ibgib/web-gib/dist/common/settings/settings-constants.mjs\";\nimport { getContextInfoFunctionInfo } from \"@ibgib/web-gib/dist/api/commands/chat/get-context-info.mjs\";\nimport { getIbGibsFunctionInfo } from \"@ibgib/web-gib/dist/api/commands/ibgib/get-ibgibs.mjs\";\n// import { ChatAPIFunctionInfos } from \"../../../api/commands/chat/chat-index.mjs\";\n// import { IbGibAPIFunctionInfos } from \"../../../api/commands/ibgib/ibgib-index.mjs\";\n// import { editProjectFunctionInfo } from \"../../../api/commands/project/project-edit.mjs\";\n// import { TextAPIFunctionInfos } from \"../../../api/commands/text/text-index.mjs\";\nimport { Minigame_TypingGameState, Minigame_TypingGameMeta } from \"./typing-types.mjs\";\n\nexport const TYPING_ATOM = 'typingminigame';\nexport const TYPING_NAME_REGEXP = /^[a-zA-Z0-9_\\-. ]{1,128}$/;\nexport const TYPING_DESC_REGEXP = /.{1,255}/;\n\nexport const TYPING_SETTINGS_SCOPE = `${SETTINGS_ATOM}_${TYPING_ATOM}`;\n\nexport const DEFAULT_TYPING_SAFE_NAME_LENGTH = 32;\n/**\n * change this in the future if we add more fields\n */\nexport const DEFAULT_TYPING_ADDL_METADATA_LENGTH = 32;\n\nexport const DEFAULT_TYPING_GAMEMETA: Minigame_TypingGameMeta = {\n    allStimuli: [],\n    statsHistory: [],\n}\nexport const DEFAULT_TYPING_GAMESTATE: Minigame_TypingGameState = {\n    flushCounter: 0,\n    remainingStimuli: [],\n    interactions: [],\n}\n\n// export const DEFAULT_TYPING_DATA_V1 ,\n// export const DEFAULT_TYPING_REL8NS_V1,\n\nexport const TYPING_REL8N_NAME = TYPING_ATOM;\n\n/**\n * @constant TypingAgentFunctionInfos - An array of all available API functions for typing agents.\n *\n * this seems to be a narrowly scoped agent whose job is to execute a specific\n * minigame. we'll see...\n */\nexport const TypingFunctionInfos: APIFunctionInfo<any>[] = [\n    // editProjectFunctionInfo,\n    getContextInfoFunctionInfo,\n    getIbGibsFunctionInfo,\n];\n\nexport const AGENT_AVAILABLE_FUNCTIONS_TYPINGAGENT: APIFunctionInfo<any>[] = [\n    // ...ChatAPIFunctionInfos,\n    // ...TextAPIFunctionInfos,\n    // ...IbGibAPIFunctionInfos,\n    ...TypingFunctionInfos,\n];\n\n/**\n * show text, retype that text, used not only for getting familiar with keyboard\n * BUT ALSO does a decent job at light reinforcement at a higher volume (once\n * you get familiar with said keyboard).\n *\n * Note that with voice-to-text input, this can also be used for pronunciation\n * games.\n */\nexport const MINIGAME_GAMEVARIANT_TYPING_PARROT = 'parrot';\n/**\n * call-and-response cycle with some stimulation (the call) and the user\n * provides some kind of feedback or answer (the response). This applies to\n * translations, as well as Q & A, etc.\n *\n * Note that this is a musical slant on flashcards, i.e., it has an implied\n * rhythm.\n *\n * @see {@link https://en.wikipedia.org/wiki/Call_and_response_(music)}\n */\nexport const MINIGAME_GAMEVARIANT_TYPING_ANTIPHONY = 'antiphony';\n/**\n * Fill-in-the-blank\n */\nexport const MINIGAME_GAMEVARIANT_TYPING_FITB = 'fitb';\n/**\n * Translate native -> target OR target -> native.\n */\nexport const MINIGAME_GAMEVARIANT_TYPING_TRANSLATE = 'translate';\nexport type MinigameGameVariant_Typing =\n    | typeof MINIGAME_GAMEVARIANT_TYPING_PARROT\n    | typeof MINIGAME_GAMEVARIANT_TYPING_ANTIPHONY\n    | typeof MINIGAME_GAMEVARIANT_TYPING_FITB\n    | typeof MINIGAME_GAMEVARIANT_TYPING_TRANSLATE\n    ;\nexport const MinigameGameVariant_Typing = {\n    parrot: MINIGAME_GAMEVARIANT_TYPING_PARROT,\n    antiphony: MINIGAME_GAMEVARIANT_TYPING_ANTIPHONY,\n    fitb: MINIGAME_GAMEVARIANT_TYPING_FITB,\n    translate: MINIGAME_GAMEVARIANT_TYPING_TRANSLATE,\n} satisfies { [key in MinigameGameVariant_Typing]: MinigameGameVariant_Typing };\nexport const MINIGAME_GAME_VARIANT_TYPING_VALUES = Object.values(MinigameGameVariant_Typing);\n\nexport const MINIGAME_FOCUS_INFO = [\n    `Focuses are pieces of some text/content that you want to center your learning/reinforcement around. If you want to learn 1000 words, you don't learn them all equally all at once. Rather, you focus on certain ones and build around those with various glue words like conjunctions, pronouns, prepositions, etc. Then later, you can focus on others as needed to fill it out.`,\n    `So choose some group of focuses per section of text that you will process thoroughly, and you will learn the other surrounding content as a matter of course through various iterations. This will help keep things fresh and fun to maximize learning efficiency.`,\n].join('\\n');\n\nexport const MINIGAME_STIMULTI_TO_ADD_INFO = [\n    `These are the stimuli that will ultimately be added to your minigame if you click OK.`,\n    `\"Stimuli\" is my nerdy way of saying \"question\" or \"prompt\" or the \"front side\" of something like a dynamic flashcard.`\n].join('\\n');\n\n// #region ExpectedResponseType\n/**\n * @see {@link ExpectedResponseType.exact}\n */\nexport const EXPECTED_RESPONSE_TYPE_EXACT = 'exact';\n/**\n * @see {@link ExpectedResponseType.equivalent}\n */\nexport const EXPECTED_RESPONSE_TYPE_EQUIVALENT = 'equivalent';\n/**\n * @see {@link ExpectedResponseType.fitb}\n */\nexport const EXPECTED_RESPONSE_TYPE_FITB = 'fill-in-the-blank';\n/**\n * @see {@link ExpectedResponseType.answer}\n */\nexport const EXPECTED_RESPONSE_TYPE_ANSWER = 'answer';\n/**\n * Determines how expectedResponse to a stimulus is to be interpreted.\n */\nexport type ExpectedResponseType =\n    | typeof EXPECTED_RESPONSE_TYPE_EXACT\n    | typeof EXPECTED_RESPONSE_TYPE_EQUIVALENT\n    | typeof EXPECTED_RESPONSE_TYPE_FITB\n    | typeof EXPECTED_RESPONSE_TYPE_ANSWER\n    ;\n/**\n * Determines how expectedResponse to a stimulus is to be interpreted.\n */\nexport const ExpectedResponseType = {\n    /**\n     * The user should type the expectedResponse exactly.\n     */\n    exact: EXPECTED_RESPONSE_TYPE_EXACT,\n    /**\n     * The user should type something equivalent in meaning/semantic value as\n     * expectedResponse .\n     */\n    equivalent: EXPECTED_RESPONSE_TYPE_EQUIVALENT,\n    /**\n     * The blanked out text(s) should be provided\n     */\n    fitb: EXPECTED_RESPONSE_TYPE_FITB,\n    /**\n     * The stimulus is a question and the response should be the answer.\n     */\n    answer: EXPECTED_RESPONSE_TYPE_ANSWER,\n} satisfies { [key: string]: ExpectedResponseType };\nexport const EXPECTED_RESPONSE_TYPE_VALID_VALUES = Object.values(ExpectedResponseType);\n// #endregion ExpectedResponseType\n\n\n/**\n * hack...i'm going to store the user's native language code in storage using\n * this key, since we don't have real user identity/profile stuff yet.\n *\n * this should be updated whenever the user indicates their native language, which\n * atow (08/2025)\n */\nexport const USER_NATIVE_LANGUAGE_KEY = 'native-language';\n\n/**\n * These are the defaults that I am setting up, but they are not exclusive.\n * Agents will be shown this list as guidance for their own determinations of\n * languages, when applicable.\n *\n * @see {@link https://en.wikipedia.org/wiki/ISO_639}\n * @see {@link https://en.wikipedia.org/wiki/List_of_ISO_639_language_codes}\n */\nexport const DEFAULT_ISO_639_LANGUAGE_CODES = [\n    \"en-GB\",\n    \"en-US\",\n    \"fr-FR\",\n    \"de-DE\",\n    \"el-GR\",\n    \"grc\",\n    \"he-IL\",\n    \"hbo\",\n    \"it-IT\",\n    \"pt-BR\",\n    \"pt-PT\",\n    \"ru-RU\",\n    \"es-ES\",\n    \"es-MX\",\n    \"es-CU\",\n];\n", "import { ChatAPIFunctionInfos } from \"@ibgib/web-gib/dist/api/commands/chat/chat-index.mjs\";\nimport { IbGibAPIFunctionInfos } from \"@ibgib/web-gib/dist/api/commands/ibgib/ibgib-index.mjs\";\nimport { APIFunctionInfo } from \"@ibgib/web-gib/dist/api/api-types.mjs\";\nimport { SETTINGS_ATOM } from \"@ibgib/web-gib/dist/common/settings/settings-constants.mjs\";\nimport { TextAPIFunctionInfos } from \"@ibgib/web-gib/dist/api/commands/text/text-index.mjs\";\n\n// import { MinigameFunctionInfos } from \"../../api/commands/minigame/minigame-index.mjs\";\nimport { MinigameGameVariant_Typing } from \"./typing/typing-constants.mjs\";\n\nexport const MINIGAME_ATOM = 'minigame';\nexport const MINIGAME_NAME_REGEXP = /^[a-zA-Z0-9_\\-. ]{1,128}$/;\nexport const MINIGAME_DESC_REGEXP = /.{1,255}/;\n\nexport const MINIGAME_SETTINGS_SCOPE = `${SETTINGS_ATOM}_${MINIGAME_ATOM}`;\n\nexport const DEFAULT_MINIGAME_SAFE_NAME_LENGTH = 32;\n/**\n * change this in the future if we add more fields\n */\nexport const DEFAULT_MINIGAME_ADDL_METADATA_LENGTH = 32;\n\n// export const DEFAULT_MINIGAME_DATA_V1 ,\n// export const DEFAULT_MINIGAME_REL8NS_V1,\n\n\n/**\n * if a minigame descends from another minigame, this will be set.\n */\nexport const MINIGAME_PROTOTYPE_REL8N_NAME = 'prototype';\nexport const MINIGAME_REL8N_NAME = MINIGAME_ATOM;\n\nexport const AGENT_AVAILABLE_FUNCTIONS_MINIGAMEAGENT: APIFunctionInfo<any>[] = [\n    ...ChatAPIFunctionInfos,\n    ...TextAPIFunctionInfos,\n    ...IbGibAPIFunctionInfos,\n    // ...MinigameFunctionInfos,\n];\n// ugly hack for some circular dependency that I can't find\n// had to comment this out, really getting into solving this circular dependency mess 2025/12/15\n// setTimeout(async () => {\n//     while (!MinigameFunctionInfos) {\n//         await delay(100);\n//         debugger;\n//     }\n//     MinigameFunctionInfos.forEach(x => {\n//         AGENT_AVAILABLE_FUNCTIONS_MINIGAMEAGENT.push(x);\n//     }); // hasn't initialized yet\n// });\n\n// #region MinigameGameType\nexport const MINIGAME_GAMETYPE_TYPING = 'typing';\nexport type MinigameGameType =\n    | typeof MINIGAME_GAMETYPE_TYPING\n    ;\nexport const MinigameGameType = {\n    typing: MINIGAME_GAMETYPE_TYPING,\n} satisfies { [key in MinigameGameType]: MinigameGameType };\nexport const MINIGAME_GAME_TYPE_VALUES = Object.values(MinigameGameType);\n// #endregion MinigameGameType\n\n// #region MinigameGameVariant\nexport const MINIGAME_GAMEVARIANT_COMMON_DEFAULT = 'default';\nexport const MINIGAME_GAMEVARIANT_COMMON_MULTI = 'multi';\nexport type MinigameGameVariant_Common =\n    | typeof MINIGAME_GAMEVARIANT_COMMON_DEFAULT\n    | typeof MINIGAME_GAMEVARIANT_COMMON_MULTI\n    ;\nexport const MinigameGameVariant_Common = {\n    default: MINIGAME_GAMEVARIANT_COMMON_DEFAULT,\n    multi: MINIGAME_GAMEVARIANT_COMMON_MULTI,\n} satisfies { [key in MinigameGameVariant_Common]: MinigameGameVariant_Common };\nexport const MINIGAME_GAME_VARIANT_COMMON_VALUES = Object.values(MinigameGameVariant_Common);\n/**\n * Discriminated union for the specific variant of a given minigame gameType.\n */\nexport type MinigameGameVariant =\n    | MinigameGameVariant_Common\n    | MinigameGameVariant_Typing;\nexport const MinigameGameVariant = {\n    ...MinigameGameVariant_Common,\n    ...MinigameGameVariant_Typing,\n}\nexport const MINIGAME_GAME_VARIANT_VALUES = Object.values(MinigameGameVariant);\n// #endregion MinigameGameVariant\n\n// #region Gemini Schemas\nexport const GEMINI_SCHEMA_MINIGAME_GAMETYPE = {\n    type: 'string',\n    enum: MINIGAME_GAME_TYPE_VALUES.concat(),\n    description: 'Broad category of minigame. May have multiple variants.',\n};\n\nexport const GEMINI_SCHEMA_MINIGAME_GAMEVARIANT_COMMON_DESCRIPTION = [\n    `${MinigameGameVariant.default} will be a single single game variant.`,\n    `${MinigameGameVariant.multi} will have multiple, varying kinds of specific items.`,\n].join('\\n');\nexport const GEMINI_SCHEMA_MINIGAME_GAMEVARIANT_TYPING_DESCRIPTION = [\n    `${MinigameGameVariant_Typing.parrot} (${MinigameGameType.typing})(${MinigameGameVariant.default}) is just typing the stimulus.`,\n    `${MinigameGameVariant_Typing.antiphony} (${MinigameGameType.typing}) is typing some kind of expectedResponse. Stimuli should have expectedResponse values and expectedResponseIsExact should be set true or false.`,\n    `${MinigameGameVariant_Typing.fitb} (${MinigameGameType.typing}) is \"Fill-in-the-Blank\". These stimuli have one or more blanks. Stimuli should have expectedResponse be a comma-delimited list that match the number of blanks. expectedResponseIsExact values should be either true or false.`,\n].join('\\n');\n\n// export const GEMINI_SCHEMA_MINIGAME_GAMEVARIANT = {\n//     type: 'string',\n//     enum: MINIGAME_GAME_VARIANT_VALUES.concat(),\n//     description: [\n//         `Specific variant (sub-category) of the minigame's type.`,\n//         GEMINI_SCHEMA_MINIGAME_GAMEVARIANT_COMMON_DESCRIPTION,\n//         GEMINI_SCHEMA_MINIGAME_GAMEVARIANT_TYPING_DESCRIPTION,\n//     ].join('\\n'),\n// };\n\nexport const GEMINI_SCHEMA_MINIGAME_NAME = {\n    type: 'string',\n    description: 'The name of the game which you want to create.',\n};\nexport const GEMINI_SCHEMA_MINIGAME_DESCRIPTION = {\n    type: 'string',\n    description: 'The description of the game which you want to create. Can be in Markdown.',\n};\nexport const GEMINI_SCHEMA_MINIGAME_INSTRUCTIONS = {\n    type: 'string',\n    description: 'Brief instructions to show at the beginning of a game instance. Can be in Markdown.',\n};\n\nexport const GEMINI_SCHEMA_MINIGAME_KEYWORDS = {\n    type: 'array',\n    description: 'Keywords related to the minigame. Can be used for searching.',\n    items: {\n        type: 'string',\n        description: 'keyword (or small phrase)'\n    }\n};\n\nexport const GEMINI_SCHEMA_MINIGAME_CONTEXT_ADDR = {\n    type: 'string',\n    description: `This is the address of the ibgib in which you want to start the minigame. Often this is the active child tab's ibgib in a project, or possibly the project itself. This should contain the source material that is the primary driver of the minigame. For typing/text games, this should contain the bulk of the text.`,\n};\n\nexport const GEMINI_SCHEMA_MINIGAME_MINIGAME_ADDR = {\n    type: 'string',\n    description: `This is the address of the minigame ibgib itself.`,\n};\n\n// #endregion Gemini Schemas\n", "import { IbGib_V1, IbGibData_V1, IbGibRel8ns_V1 } from \"@ibgib/ts-gib/dist/V1/types.mjs\";\nimport { IbGibAddr } from \"@ibgib/ts-gib/dist/types.mjs\";\n\nimport type { getMinigameIb } from './minigame-helper.mjs';\nimport { MINIGAME_PROTOTYPE_REL8N_NAME, MinigameGameType, MinigameGameVariant } from \"./minigame-constants.mjs\";\n\n// #region constants - Pulled in from minigame-constants, but we need default data/rel8ns structure here\n\n// #region MinigameGamePhase\nexport const MINIGAME_GAMEPHASE_INIT = 'init';\nexport const MINIGAME_GAMEPHASE_READY = 'ready';\nexport const MINIGAME_GAMEPHASE_PLAYING = 'playing';\nexport const MINIGAME_GAMEPHASE_PAUSED = 'paused';\nexport const MINIGAME_GAMEPHASE_ABORTED = 'aborted';\nexport const MINIGAME_GAMEPHASE_COMPLETE = 'complete';\nexport type MinigameGamePhase =\n    | typeof MINIGAME_GAMEPHASE_INIT\n    | typeof MINIGAME_GAMEPHASE_READY\n    | typeof MINIGAME_GAMEPHASE_PLAYING\n    | typeof MINIGAME_GAMEPHASE_PAUSED\n    | typeof MINIGAME_GAMEPHASE_ABORTED\n    | typeof MINIGAME_GAMEPHASE_COMPLETE\n    ;\n/**\n * generic finite state machine-like phase of a minigame. This is a general\n * phase, and there may be additional \"sub-phases\" (or whatever) for specific,\n * concrete minigames.\n */\nexport const MinigameGamePhase = {\n    init: MINIGAME_GAMEPHASE_INIT,\n    ready: MINIGAME_GAMEPHASE_READY,\n    playing: MINIGAME_GAMEPHASE_PLAYING,\n    paused: MINIGAME_GAMEPHASE_PAUSED,\n    aborted: MINIGAME_GAMEPHASE_ABORTED,\n    complete: MINIGAME_GAMEPHASE_COMPLETE,\n} satisfies { [key in MinigameGamePhase]: MinigameGamePhase };\nexport const MINIGAME_GAME_PHASE_VALUES = Object.values(MinigameGamePhase);\nexport function isMinigameGamePhase(value: string): value is MinigameGamePhase {\n    return MINIGAME_GAME_PHASE_VALUES.includes(value as MinigameGamePhase);\n}\n// #endregion MinigameGamePhase\n\nexport const DEFAULT_MINIGAME_TEXT = 'default minigame text';\nexport const DEFAULT_MINIGAME_NAME = 'untitled_minigame';\nexport const DEFAULT_MINIGAME_DESCRIPTION = 'This is an ibgib minigame. ';\nexport const DEFAULT_MINIGAME_INSTRUCTIONS = 'Try your best!';\nexport const DEFAULT_MINIGAME_GAMETYPE = MinigameGameType.typing;\nexport const DEFAULT_MINIGAME_GAMEVARIANT = MinigameGameVariant.default;\nexport const DEFAULT_MINIGAME_GAMEPHASE = MinigameGamePhase.init;\nexport const DEFAULT_MINIGAME_KEYWORDS = [];\n\n/**\n * Default rel8ns values for a Minigame. Includes inherited defaults from IbGib.\n */\nexport const DEFAULT_MINIGAME_REL8NS_V1: MinigameRel8ns_V1 | undefined = undefined;\n\n// #endregion constants\n\n\n/**\n * Represents the data structure for a Minigame ibGib.\n * Contains the core information defining a minigame.\n */\nexport interface MinigameData_V1 extends IbGibData_V1 {\n    /**\n     * It's the name of the game.\n     */\n    name: string;\n    /**\n     * Description of the minigame.\n     * This can be a more detailed explanation of the minigame's purpose or scope.\n     */\n    description: string;\n    /**\n     * how to play the game. shown before starting.\n     */\n    instructions: string;\n    /**\n     * if given, this is the address that provides the src of this minigame.\n     */\n    '@contextAddr'?: IbGibAddr;\n    /**\n     * Broad category of the minigame. Only one initially is \"typing\" (though\n     * the user could use the voice typing).\n     */\n    gameType: MinigameGameType;\n    /**\n     * Specific sub-type of the {@link gameType}. This determines specifics of\n     * the minigame gameplay.\n     * @deprecated (moving this into the stimulus instead of the game itself)\n     */\n    gameVariant?: MinigameGameVariant;\n    /**\n     * Metadata, e.g. config, specific to the concrete minigame {@link gameType}\n     * and {@link gameVariant}.\n     */\n    gameMeta?: any;\n    /**\n     * The state of the concrete minigame, which should include, e.g.,\n     * interactions the player might have been involved with.\n     *\n     * in typing, this is where we include what stimuli we have shown to the\n     * user, what their responses were, timestamps, etc.\n     */\n    gameState?: any;\n    /**\n     * * if init, then {@link gameState} is temporary state of the next game to\n     *   be played.\n     * * if playing or paused, then {@link gameState} is the current game state.\n     * * if aborted or complete, then {@link gameState} is the previous game\n     *   state that was aborted/completed.\n     *\n     * ## past game states and notes\n     *\n     * To see past game states, you have to walk the history of this ibgib\n     * (the 'past', and possibly 'ancestor' rel8nNames - I don't know yet how\n     * this will pan out).\n     *\n     * I am thinking that we will fork for new games, but this may be annoying\n     * and we may end up just mutating this data and reserve forking for\n     * creating prototypes.\n     */\n    gamePhase?: MinigameGamePhase;\n    /**\n     * List of keywords that describe/pertain to this minigame, e.g., 'spanish',\n     * 'verbs', 'conjugation', 'cover-cropping', etc.\n     *\n     * Note that our learning model is not just subject-related but\n     * trace-strength related. So the material itself is not the only important\n     * thing, like when buliding a team it's good to have diversification such\n     * as a comedian/light-hearted person. The learning equivalent is pairing\n     * certain groups of text with some fun/humorous theme.\n     */\n    keywords: string[];\n    /**\n     * if false, this minigame is still being initialized and cannot yet be\n     * played proper.\n     */\n    playable: boolean;\n    gamesStarted: number;\n    gamesCompleted: number;\n    gamesAborted: number;\n}\n\n/**\n * Represents the relationships structure for a Minigame ibGib.\n * Currently holds standard ibGib relationships but can be extended\n * in the future if minigames require specific relationship types (e.g., rel8n_tasks).\n */\nexport interface MinigameRel8ns_V1 extends IbGibRel8ns_V1 {\n    // Add any minigame-specific rel8ns here if needed.\n    // [AGENT_REL8N_NAME]?: IbGibAddr[];\n    [MINIGAME_PROTOTYPE_REL8N_NAME]?: IbGibAddr[];\n}\n\n/**\n * Represents a fully formed Minigame ibGib, combining its data and relationships.\n * This is the primary type used when interacting with Minigame ibGibs.\n */\nexport interface MinigameIbGib_V1 extends IbGib_V1<MinigameData_V1, MinigameRel8ns_V1> {\n}\n\n/**\n * Default data values for a Minigame. Includes inherited defaults from Comment/IbGib.\n */\nexport const DEFAULT_MINIGAME_DATA_V1: MinigameData_V1 = {\n    // Inherited from CommentData_V1 -> IbGibData_V1\n    name: DEFAULT_MINIGAME_NAME, // Default minigame name\n    text: DEFAULT_MINIGAME_TEXT, // Default comment text\n    textTimestamp: '',\n\n    // MinigameData_V1 specific (or CommentData_V1 overrides)\n    description: DEFAULT_MINIGAME_DESCRIPTION,\n    instructions: DEFAULT_MINIGAME_INSTRUCTIONS,\n    gameType: DEFAULT_MINIGAME_GAMETYPE,\n    gameVariant: DEFAULT_MINIGAME_GAMEVARIANT,\n    gamePhase: DEFAULT_MINIGAME_GAMEPHASE,\n    keywords: DEFAULT_MINIGAME_KEYWORDS,\n    playable: false,\n\n    gamesStarted: 0,\n    gamesAborted: 0,\n    gamesCompleted: 0,\n};\n\n/**\n * Represents the parsed information extracted from the `addlMetadataText`\n * segment within a minigame's `ib` string. This segment follows the `safeName`\n * and is delimited by underscores internally if multiple fields are present.\n */\nexport interface MinigameAddlMetadataInfo {\n    /**\n     * Ticks version of the timestamp derived from ibgib.data.timestamp.\n     * This value is encoded within the addlMetadataText segment of the ib string.\n     */\n    timestampInTicks: number;\n    // Add other fields here if the addlMetadataText segment grows,\n    // ensuring they are underscore-delimited in the raw text.\n}\n\n\n/**\n * Represents the parsed information extracted from a minigame's `ib` string.\n * The `ib` string contains core metadata encoded for efficient referencing.\n *\n * @see {@link getMinigameIb} for ib schema\n */\nexport interface MinigameIbInfo {\n    /** The atom identifier (must be 'minigame'). Checked during parsing. */\n    atom: 'minigame';\n    /**\n     * A 'saferized', often truncated, version of the name (minigame title).\n     * Extracted as the first space-delimited segment after the atom.\n     */\n    safeName: string;\n    /**\n     * The raw string containing underscore-delimited additional metadata (e.g., \"1678886400000\").\n     * Extracted as the second space-delimited segment after safeName.\n     *\n     * @see {@link addlMetadata}\n     */\n    addlMetadataText: string;\n    /**\n     * The parsed content of the addlMetadataText segment.\n     *\n     * @see {@link addlMetadataText}\n     */\n    addlMetadata: MinigameAddlMetadataInfo;\n}\n\n/**\n * actual game mechanics. This API will be used by the minigame (wrapper)\n * component.\n *\n * Concrete minigame components will implement this\n */\nexport interface MinigameFiniteStateMachine {\n    get gamePhase(): MinigameGamePhase | undefined;\n    play(): Promise<void>;\n    pause(): Promise<void>;\n    restart(): Promise<void>;\n    abort(): Promise<void>;\n    complete(): Promise<void>;\n}\n", "import { ConstructRule } from \"./types.mjs\";\n\n/**\n * For western languages, delimits text into all tokens.\n *\n * Basically atow (07/2025) the pattern allows for unicode, conventional\n * alphanumerics, and apostrophe's and hyphens.\n */\nexport const DEFAULT_TOKEN_CONSTRUCT_RULE: ConstructRule = {\n    \"name\": \"token\",\n    \"description\": \"Defines the fundamental unit of a 'word' or 'token'.\",\n    \"pattern\": \"<< REGEX(/\\\\p{L}+(?:['\\\\-]\\\\p{L}+)*/u) >>\"\n};\n\nexport const DEFAULT_GERMAN_RULES = [\n    {\n        \"name\": \"german-dative-preposition\",\n        \"description\": \"Matches a common German dative preposition.\",\n        \"pattern\": \"<< REGEX(/\\\\b(mit|nach|von|zu)\\\\b/u) >>\"\n\n    },\n    {\n        \"name\": \"german-noun\",\n        \"description\": \"Matches a probable German noun (capitalized, but not a common article).\",\n        \"pattern\": \"<< REGEX(/\\\\b(?!(Der|Die|Das|Den|Dem|Des|Ein|Eine|Eines|Einem|Einen)\\\\b)[A-Z]\\\\p{L}*/u) >>\"\n    },\n    {\n        \"name\": \"german-dative-phrase\",\n        \"description\": \"A dative preposition followed by a noun, with or without an article.\",\n        \"pattern\": \"<< [CONSTRUCT:german-dative-preposition] (?:[CONSTRUCT:token] )?[CONSTRUCT:german-noun] >>\"\n    },\n    // {\n    //     \"name\": \"german-dative-phrase\",\n    //     \"description\": \"A dative preposition followed by any token and a noun.\",\n    //     \"pattern\": \"<< [CONSTRUCT:german-dative-preposition] [CONSTRUCT:token] [CONSTRUCT:german-noun] >>\"\n    // },\n    {\n        \"name\": \"german-separable-verb-end\",\n        \"description\": \"Identifies a common separable prefix at the end of a clause.\",\n        \"pattern\": \"<< REGEX(/\\\\b(an|auf|aus)\\\\b(?=[\\\\.,!]|$)/i) >>\"\n    }\n];\n\nexport const DEFAULT_ITALIAN_RULES = [\n    {\n        \"name\": \"italian-articulated-preposition\",\n        \"description\": \"Identifies prepositions combined with a definite article.\",\n        \"pattern\": \"<< REGEX(/\\\\b(del|dello|della|degli|delle|al|allo|alla|agli|alle|dal|dallo|dalla|dagli|dalle)\\\\b/i) >>\"\n    },\n    {\n        \"name\": \"italian-verb-clitic\",\n        \"description\": \"Finds a verb infinitive stem with clitics, with a special case for 'dirglielo'.\",\n        \"pattern\": \"<< REGEX(/\\\\b(?:\\\\p{L}+(?:ar|er|ir)(?:mi|ti|lo|la|ci|vi|li|le|ne|si|gli){1,2}|dirglielo)\\\\b/i) >>\"\n    },\n];\n\nexport const DEFAULT_SPANISH_RULES = [\n    {\n        \"name\": \"spanish-estar-conjugation\",\n        \"description\": \"Matches a conjugation of the verb 'estar' using character classes for case.\",\n        \"pattern\": \"<< REGEX(/(?<!\\\\p{L})[Ee]st(oy|\u00E1s|\u00E1|amos|\u00E1is|\u00E1n)(?!\\\\p{L})/u) >>\"\n    },\n    {\n        \"name\": \"spanish-gerund\",\n        \"description\": \"Matches a gerund ending in -ando or -iendo.\",\n        \"pattern\": \"<< REGEX(/(?<!\\\\p{L})\\\\p{L}+(ando|iendo)(?!\\\\p{L})/i) >>\"\n    },\n    {\n        \"name\": \"spanish-present-progressive\",\n        \"description\": \"Identifies the present progressive tense.\",\n        \"pattern\": \"<< [CONSTRUCT:spanish-estar-conjugation] [CONSTRUCT:spanish-gerund] >>\"\n    }\n];\n\nexport const DEFAULT_KOINEGREEK_RULES = [\n    {\n        \"name\": \"greek-genitive-article\",\n        \"description\": \"Matches the masculine/neuter singular genitive article.\",\n        \"pattern\": \"<< \u03C4\u03BF\u1FE6 >>\"\n    },\n    {\n        \"name\": \"greek-genitive-noun-ending\",\n        \"description\": \"Matches a token ending in the genitive suffix -\u03BF\u03C5, with or without accent.\",\n        // **FIX:** Use [\u03C5\u1FE6] to match both plain and accented upsilon.\n        \"pattern\": \"<< REGEX(/(?<!\\\\p{L})\\\\p{L}+\u03BF[\u03C5\u1FE6](?![\\\\p{L}])/u) >>\"\n    },\n    {\n        \"name\": \"greek-genitive-phrase\",\n        \"description\": \"A genitive article followed by a genitive noun.\",\n        \"pattern\": \"<< [CONSTRUCT:greek-genitive-article] [CONSTRUCT:greek-genitive-noun-ending] >>\"\n    },\n    {\n        \"name\": \"greek-preposition-en\",\n        \"description\": \"Matches the preposition '\u1F10\u03BD' (in).\",\n        \"pattern\": \"<< \u1F10\u03BD >>\"\n    },\n    {\n        \"name\": \"greek-dative-ending\",\n        \"description\": \"Matches a token ending in the dative suffix '\u1FF3', with or without accent.\",\n        \"pattern\": \"<< REGEX(/(?<!\\\\p{L})\\\\p{L}+[\u1FF3\u1FF7](?![\\\\p{L}])/u) >>\"\n    },\n    {\n        \"name\": \"greek-en-dative-phrase\",\n        \"description\": \"The preposition '\u1F10\u03BD' followed by a dative noun.\",\n        \"pattern\": \"<< [CONSTRUCT:greek-preposition-en] [CONSTRUCT:greek-dative-ending] >>\"\n    },\n];\n", "import { extractErrorMsg, pretty } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';\n\nimport { GLOBAL_LOG_A_LOT } from \"../../constants.mjs\";\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\nimport type { AnalysisResult, ConstructRule, TermFrequencyMap } from './types.mjs';\nimport type { CorpusAnalyzer } from './corpus-analyzer.mjs';\nimport { DEFAULT_TOKEN_CONSTRUCT_RULE } from './analysis-engine-constants.mjs';\n\n/**\n * Internal representation of a compiled rule, separating the pattern\n * from the flags it requires.\n */\nexport interface CompiledInfo {\n    pattern: string;\n    flags: string;\n}\n\n/**\n * for this early dev implementation, this is hard-coded. But we absolutely have\n * to get this hooked up with ibgibs in code.\n */\nconst DEFAULT_ENGINE_CONSTRUCT_RULES: ConstructRule[] = [\n    DEFAULT_TOKEN_CONSTRUCT_RULE,\n];\n\n/**\n * heart of the text analysis process that creates a slim composable DSL on top\n * of regex in order to extract information, e.g., TF-IDF, out of text.\n *\n * note that this started as a normal TF-IDF engine, but then the \"term\" was\n * abstracted to \"construct\" so that not only simple words but, e.g.,\n * grammatical constructs can be extracted and analyzed.\n *\n * ## usage\n *\n * This is consumed in {@link CorpusAnalyzer}\n *\n * ## broad idea with ibgib integration\n *\n * we want to build a text analyzing engine, but not one that has to be extended\n * via code. IOW, we want to avoid requiring code writing and recompilation.\n * Ibgib itself is excellent for \"version control\", and eventually it will be\n * used to version src code as a shim to how software is created nowadays (it\n * basically is a more generalized, more powerful version of git). But right\n * _now_ we can easily \"version control\" semantic text entities, and as it\n * happens, the {@link ConstructRule} that underpins this engine is entirely\n * text-based. This is not a coincidence.\n *\n * So we should be able to not only create these patterns on the fly at runtime,\n * but we should be able to expose this pattern creation and management to\n * agents, who can then manage them at runtime, create \"tests\" that it expects\n * to see, depending on how much you want the agent to process things.\n *\n * The purpose of this is to add analyses to learner's text responses and\n * speech, to clarify the learner's progression in a language - or any\n * text-encodable skill really, since all skills require tactics, strategies,\n * etc. (domain jargon), which can be codified.\n *\n * So an agent should ultimately be able to:\n *\n * * analyze learner's...\n *   * minigames AND\n *   * entire chat history that the agent has access to, i.e., the agent's\n *     context window\n * * create new ConstructRule entries to broaden the analysis as needed\n * * edit ConstructRule entries as needed, depending on how well they perform in\n *   reports according to the agent's opinion\n *\n * Using ibgib's protocol for the storage of these ConstructRule entries means\n * that we should be able to:\n *\n * * share the ibgibs reusing the ibgib protocol plumbing\n * * rel8 rules to create ibgib-stored rulesets\n * * fork/mut8 rules and rulesets\n * * basically do all the cool stuff that we can do with other ibgibs\n */\nexport class AnalysisEngine {\n    private lc: string = `[${AnalysisEngine.name}]`;\n    private rules: Map<string, ConstructRule>;\n    // A cache for compiled info to avoid re-compiling the same rule repeatedly.\n    private compiledInfoCache: Map<string, CompiledInfo>;\n\n    public static readonly PRIMORDIAL_TOKEN_CONSTRUCT_NAME = 'token';\n    public static readonly DEFAULT = new AnalysisEngine(DEFAULT_ENGINE_CONSTRUCT_RULES);\n\n    constructor(rules: ConstructRule[]) {\n        const lc = `${this.lc}[ctor]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 08cbaa69ce78baea98ac5f68b2cc6825)`); }\n\n            // Use a Map for efficient rule lookup by name.\n            this.rules = new Map(rules.map(r => [r.name, r]));\n            this.compiledInfoCache = new Map();\n\n            if (!this.rules.has(AnalysisEngine.PRIMORDIAL_TOKEN_CONSTRUCT_NAME)) {\n                throw new Error(`A construct rule named \"token\" must be provided.`);\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * The core recursive compiler. It takes a rule name and returns its\n     * compiled pattern and the set of flags it requires.\n     */\n    private getCompiledInfo({\n        name,\n        visited = new Set(),\n    }: {\n        name: string,\n        visited?: Set<string> | undefined,\n    }): CompiledInfo {\n        const lc = `${this.lc}[${this.getCompiledInfo.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 2ecd741a862ed095ed01a0f874168625)`); }\n\n            visited ??= new Set();\n\n            // Return from cache if this rule has already been compiled.\n            if (this.compiledInfoCache.has(name)) {\n                return this.compiledInfoCache.get(name)!;\n            }\n            if (visited.has(name)) {\n                throw new Error(`Circular dependency detected involving: ${name}`);\n            }\n            visited.add(name);\n\n            const rule = this.rules.get(name);\n            if (!rule) { throw new Error(`Rule not found: ${name}`); }\n\n            let pattern = rule.pattern;\n            const flagsSet = new Set<string>();\n\n            // STEP 1: Process REGEX(...) definitions first.\n            // This extracts the raw regex and collects any specified flags (like 'i').\n            pattern = pattern.replace(\n                /REGEX\\(\\/(.*?)\\/([a-z]*)\\)/g,\n                (match, regexBody, regexFlags) => {\n                    for (const flag of regexFlags) {\n                        flagsSet.add(flag);\n                    }\n                    return regexBody; // Return just the content of the regex\n                }\n            );\n\n            // STEP 2: Process [CONSTRUCT:...] definitions.\n            // This recursively compiles child rules and merges their flags.\n            pattern = pattern.replace(/\\[CONSTRUCT:([\\w-]+)\\]/g, (match, subName) => {\n                const childInfo = this.getCompiledInfo({\n                    name: subName,\n                    visited: new Set(visited),\n                });\n                for (const flag of childInfo.flags) {\n                    flagsSet.add(flag);\n                }\n                // Use the child's pattern, wrapped in a NON-CAPTURING group `(?:...)`\n                return `(?:${childInfo.pattern})`;\n            });\n\n            // STEP 3: Extract the content from the '<< ... >>' capture group.\n            // This is done *after* all replacements to get the final combined pattern.\n            const captureMatch = /<<\\s*(.*)\\s*>>/.exec(pattern);\n            if (captureMatch) {\n                pattern = captureMatch[1];\n            } else {\n                throw new Error(`Rule \"${name}\" must have a '<< ... >>' capture group.`);\n            }\n\n            // STEP 4: Clean up whitespace that acts as a delimiter between constructs.\n            pattern = pattern.trim().replace(/\\s+/g, `\\\\s+`);\n\n            const result: CompiledInfo = {\n                pattern: pattern,\n                flags: Array.from(flagsSet).join('')\n            };\n\n            // Cache the result before returning.\n            this.compiledInfoCache.set(name, result);\n            return result;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    public analyze({ text }: { text: string }): AnalysisResult {\n        const lc = `${this.lc}[${this.analyze.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 9d9158bc8e18fa22d9ffa8c8be78f825)`); }\n\n            const constructs: { [key: string]: TermFrequencyMap } = {};\n\n            for (const name of this.rules.keys()) {\n                try {\n                    const compiledInfo = this.getCompiledInfo({ name });\n\n                    // Combine collected flags with the required defaults ('gdu').\n                    const finalFlags = Array.from(new Set('gdu' + compiledInfo.flags)).join('');\n\n                    // The final regex is the compiled pattern wrapped in its own CAPTURING group.\n                    const finalRegex = new RegExp(`(${compiledInfo.pattern})`, finalFlags);\n\n                    constructs[name] = {};\n                    const matches = text.matchAll(finalRegex);\n\n                    for (const match of matches) {\n                        // match[1] will be the content of our single, outer capture group.\n                        const term = match[1]?.trim();\n                        if (term) {\n                            const normalizedTerm = term.toLowerCase();\n                            constructs[name][normalizedTerm] = (constructs[name][normalizedTerm] || 0) + 1;\n                        }\n                    }\n                } catch (error: any) {\n                    console.error(`${lc} Error processing rule \"${name}\": ${extractErrorMsg(error)}`);\n\n                    // If a rule fails to compile or run, log the error and mark it in the results.\n                    console.error(``, error.message);\n                    constructs[name] = { 'ERROR: See console for details': 1 };\n                }\n            }\n\n            const tokenFrequencyMap = constructs[AnalysisEngine.PRIMORDIAL_TOKEN_CONSTRUCT_NAME] || {};\n            const tokenCount = Object.values(tokenFrequencyMap).reduce((sum, count) => sum + count, 0);\n            const uniqueTokenCount = Object.keys(tokenFrequencyMap).length;\n\n            return {\n                characterCount: text.length,\n                tokenCount,\n                uniqueTokenCount,\n                constructs,\n            };\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n}\n", "import { extractErrorMsg } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\n\nimport { GLOBAL_LOG_A_LOT } from \"../../constants.mjs\";\nimport { AnalysisEngine } from './analysis-engine.mjs';\nimport type {\n    AnalysisResult, DocumentReport, ComparisonReport, IdfMap, Keyword,\n    TermFrequencyMap\n} from './types.mjs';\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\nexport class CorpusAnalyzer {\n    private lc: string = `[${CorpusAnalyzer.name}]`;\n    private engine: AnalysisEngine;\n    private documents: Map<string, AnalysisResult>;\n    private idfMaps: Map<string, IdfMap>;\n    private isIdfCacheStale: boolean;\n\n    /**\n     * Initializes the Corpus Analyzer with a pre-configured AnalysisEngine.\n     * @param engine The engine that knows how to parse text based on a set of rules.\n     */\n    constructor(engine: AnalysisEngine) {\n        this.engine = engine;\n        this.documents = new Map();\n        this.idfMaps = new Map();\n        this.isIdfCacheStale = true;\n    }\n\n    // --- Document Management API ---\n\n    /**\n     * [FAST] Adds a pre-analyzed document result to the corpus.\n     * Use this when you have a cached/memoized result.\n     * @param id A unique identifier for the document.\n     * @param result The pre-computed AnalysisResult.\n     */\n    public addDocumentFromResult({\n        id,\n        result,\n    }: {\n        id: string,\n        result: AnalysisResult,\n    }): void {\n        const lc = `${this.lc}[${this.addDocumentFromResult.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 835068262f68ea213d823aeca94a1825)`); }\n            this.documents.set(id, result);\n            this.isIdfCacheStale = true;\n            this.idfMaps.clear();\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * [HEAVY] Analyzes raw text using the engine and adds the result to the corpus.\n     * Use this when analyzing a document for the first time.\n     * @param id A unique identifier for the document.\n     * @param text The raw text of the document.\n     */\n    public addDocumentFromText({ id, text }: { id: string, text: string }): void {\n        const lc = `${this.lc}[${this.addDocumentFromText.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 64feb4d14b884465477dba275940c825)`); }\n            const result = this.engine.analyze({ text });\n            this.addDocumentFromResult({ id, result });\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * Retrieves the raw, unprocessed analysis result for a given document.\n     * @param id The ID of the document.\n     * @returns The AnalysisResult object, or undefined if not found.\n     */\n    public getDocumentAnalysis({ id }: { id: string }): AnalysisResult | undefined {\n        return this.documents.get(id);\n    }\n\n    // --- Reporting API ---\n\n    /**\n     * Generates a detailed report for a single document, calculating TF-IDF scores\n     * for significant terms and constructs.\n     * @param docId The ID of the document to report on.\n     * @param topN The number of top keywords to return for each construct.\n     * @param constructsToReport An array of construct names to analyze. Defaults to just the primordial token.\n     */\n    public generateDocumentReport({\n        docId,\n        topN = 10,\n        constructsToReport = [AnalysisEngine.PRIMORDIAL_TOKEN_CONSTRUCT_NAME]\n    }: {\n        docId: string,\n        topN: number,\n        constructsToReport: string[],\n    }): DocumentReport {\n        this.ensureIdfIsFresh(); // Lazy-load IDF cache if needed\n\n        const analysis = this.documents.get(docId);\n        if (!analysis) {\n            throw new Error(`Document with id \"${docId}\" not found in corpus.`);\n        }\n\n        const keywordsByConstruct: { [key: string]: Keyword[] } = {};\n\n        for (const constructName of constructsToReport) {\n            const termFreqMap = analysis.constructs[constructName];\n            if (!termFreqMap) { continue; }\n\n            const totalTermsInConstruct = Object.values(termFreqMap).reduce((s, c) => s + c, 0);\n            const idfMap = this.idfMaps.get(constructName) || new Map();\n            const keywords: Keyword[] = [];\n\n            for (const [term, count] of Object.entries(termFreqMap)) {\n                const tf = totalTermsInConstruct > 0 ? count / totalTermsInConstruct : 0;\n                const idf = idfMap.get(term) || Math.log(this.documents.size) + 1; // Default IDF for terms not in other docs\n\n                keywords.push({\n                    term,\n                    count,\n                    tf,\n                    idf,\n                    score: tf * idf,\n                });\n            }\n\n            // Sort by score descending and take the top N\n            keywordsByConstruct[constructName] = keywords\n                .sort((a, b) => b.score - a.score)\n                .slice(0, topN);\n        }\n\n        return {\n            docId,\n            tokenCount: analysis.tokenCount,\n            uniqueTokenCount: analysis.uniqueTokenCount,\n            keywordsByConstruct,\n        };\n    }\n\n    /**\n     * Generates a report comparing a target document against a source document.\n     * This is ideal for comparing a learner's response to a prompt.\n     * @param sourceDocId The ID of the source/reference document.\n     * @param targetDocId The ID of the target/learner document.\n     * @param constructName The specific construct to compare (e.g., 'token').\n     * @param topN The number of keywords to consider for the comparison.\n     */\n    public generateComparisonReport({\n        sourceDocId,\n        targetDocId,\n        constructName = AnalysisEngine.PRIMORDIAL_TOKEN_CONSTRUCT_NAME,\n        topN = 20\n    }: {\n        sourceDocId: string,\n        targetDocId: string,\n        constructName: string,\n        topN: number,\n    }): ComparisonReport {\n        const lc = `${this.lc}[${this.generateComparisonReport.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 994218ae04b8f058c88b8e693c2d2825)`); }\n\n            const sourceReport = this.generateDocumentReport({\n                docId: sourceDocId,\n                topN,\n                constructsToReport: [constructName]\n            });\n            const targetReport = this.generateDocumentReport({\n                docId: targetDocId,\n                topN,\n                constructsToReport: [constructName],\n            });\n\n            const sourceKeywords = sourceReport.keywordsByConstruct[constructName] || [];\n            const targetKeywords = targetReport.keywordsByConstruct[constructName] || [];\n\n            const sourceTerms = new Set(sourceKeywords.map(k => k.term));\n            const targetTerms = new Set(targetKeywords.map(k => k.term));\n\n            const sharedKeywords = sourceKeywords.filter(k => targetTerms.has(k.term));\n            const sourceUniqueKeywords = sourceKeywords.filter(k => !targetTerms.has(k.term));\n            const targetUniqueKeywords = targetKeywords.filter(k => !sourceTerms.has(k.term));\n\n            return {\n                sourceDocId,\n                targetDocId,\n                constructName,\n                sharedKeywords,\n                sourceUniqueKeywords,\n                targetUniqueKeywords,\n            };\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * Scans a document's analysis for any found instances of \"error\" constructs.\n     * @param docId The ID of the document to scan.\n     * @param errorPrefix The prefix used to name error rules in the engine (e.g., 'error-').\n     * @returns An object containing any found error constructs and their terms.\n     */\n    public findErrorPatterns({\n        docId,\n        errorPrefix = 'error-'\n    }: {\n        docId: string,\n        errorPrefix: string,\n    }): { [errorName: string]: TermFrequencyMap } {\n        const lc = `${this.lc}[${this.findErrorPatterns.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 20b84cdc228836b07ee40a68085f4825)`); }\n\n            const analysis = this.documents.get(docId);\n            if (!analysis) { return {}; }\n\n            const foundErrors: { [errorName: string]: TermFrequencyMap } = {};\n            for (const [constructName, terms] of Object.entries(analysis.constructs)) {\n                if (constructName.startsWith(errorPrefix) && Object.keys(terms).length > 0) {\n                    foundErrors[constructName] = terms;\n                }\n            }\n            return foundErrors;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    // --- Private Helpers ---\n\n    /**\n     * [LAZY] Ensures the IDF cache is up-to-date. This is the main corpus-wide\n     * calculation, run only when necessary.\n     */\n    private ensureIdfIsFresh(): void {\n        if (!this.isIdfCacheStale) { return; }\n\n        const docFrequencies: Map<string, Map<string, number>> = new Map();\n        const totalDocs = this.documents.size;\n\n        // Stage 1: Count document frequency for each term within each construct.\n        for (const analysis of this.documents.values()) {\n            for (const [constructName, terms] of Object.entries(analysis.constructs)) {\n                if (!docFrequencies.has(constructName)) {\n                    docFrequencies.set(constructName, new Map());\n                }\n                const constructDocFreq = docFrequencies.get(constructName)!;\n                for (const term of Object.keys(terms)) {\n                    constructDocFreq.set(term, (constructDocFreq.get(term) || 0) + 1);\n                }\n            }\n        }\n\n        // Stage 2: Calculate IDF score for each term.\n        this.idfMaps.clear();\n        for (const [constructName, termCounts] of docFrequencies.entries()) {\n            const idfMap: IdfMap = new Map();\n            for (const [term, count] of termCounts.entries()) {\n                const idf = Math.log(totalDocs / count) + 1; // Smoothed IDF\n                idfMap.set(term, idf);\n            }\n            this.idfMaps.set(constructName, idfMap);\n        }\n\n        this.isIdfCacheStale = false;\n    }\n}\n", "import { clone, extractErrorMsg, getUUID, pretty } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\n\nimport { GLOBAL_LOG_A_LOT } from \"../../../constants.mjs\";\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\nexport interface NaiveLanguageFingerprintPatterns {\n    el: RegExp;\n    es: RegExp;\n    fr: RegExp;\n    de: RegExp;\n    it: RegExp;\n}\n\nexport const DEFAULT_LANGUAGE_FINGERPRINTS = {\n    // Greek alphabet characters\n    el: /[\\u0370-\\u03FF]/,\n    // Spanish inverted punctuation and unique letters\n    es: /[\u00BF\u00A1\u00F1\u00E1\u00F3\u00ED]/,\n    // French uses guillemets and has specific characters like '\u00E7'\n    fr: /[\u00AB\u00BB\u00E7\u00E0\u00E2\u00E9\u00E8\u00EA\u00EB\u00EE\u00EF\u00F4\u00F9\u00FB\u00FC]/,\n    // German has umlauts and the Eszett\n    de: /[\u00E4\u00F6\u00FC\u00C4\u00D6\u00DC\u00DF]/,\n    // Italian has accented vowels, especially at the end of words\n    it: /[\u00E0\u00E8\u00E9\u00EC\u00ED\u00F2\u00F3\u00F9\u00FA]/,\n};\n\nexport type NaiveDetectedLanguage = 'en' | 'el' | 'es' | 'fr' | 'de' | 'it';\nexport function detectLanguage({\n    text,\n    fingerprints,\n}: {\n    text: string,\n    fingerprints: NaiveLanguageFingerprintPatterns,\n}): NaiveDetectedLanguage {\n    const lc = `[${detectLanguage.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 5eda0827f5271aee78ae0d43ce403825)`); }\n\n        let lang: NaiveDetectedLanguage = 'en'; // Default to English\n\n        // Simple language scoring\n        const scores: { [key in NaiveDetectedLanguage]: number } = { en: 0, el: 0, es: 0, fr: 0, de: 0, it: 0 };\n        for (const char of text) {\n            if (fingerprints.el.test(char)) { scores.el++; }\n            if (fingerprints.es.test(char)) { scores.es++; }\n            if (fingerprints.fr.test(char)) { scores.fr++; }\n            if (fingerprints.de.test(char)) { scores.de++; }\n            if (fingerprints.it.test(char)) { scores.it++; }\n        }\n\n        // Determine the language with the highest score\n        let maxScore = 0;\n        for (const [key, score] of Object.entries(scores)) {\n            if (score > maxScore) {\n                maxScore = score;\n                lang = key as NaiveDetectedLanguage;\n            }\n        }\n\n        if (logalot) { console.log(`Detected language: ${lang}`); }\n\n        return lang;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n\n}\ninterface SentenceSplitter {\n    sentenceRegex: {\n        el: RegExp;\n        es: RegExp;\n        generic: RegExp;\n    };\n    fingerprints: NaiveLanguageFingerprintPatterns;\n    split(text: string): string[];\n}\nexport const sentenceSplitter: SentenceSplitter = {\n    // Regex patterns tailored for each language\n    sentenceRegex: {\n        // Greek is special due to the semicolon as a question mark\n        el: /[^.\u037E\u2026]+[.\u037E\u2026]+/g,\n        // Spanish uses inverted marks\n        es: /(\u00BF|\u00A1)?[^.?!;\u2026]+[.?!;\u2026]+/g,\n        // A general regex for Germanic/Romance languages (EN, DE, FR, IT)\n        // It handles various quotation styles.\n        generic: /[^.?!\u2026]+[.?!\u2026]+(?!(\\s*[a-z\"\u201D\u00AB\u201E]))/g,\n    },\n\n    // Fingerprints for language detection based on unique characters\n    fingerprints: DEFAULT_LANGUAGE_FINGERPRINTS,\n\n    // The main function to split sentences\n    split(text) {\n\n\n        const lang = detectLanguage({ text, fingerprints: this.fingerprints });\n\n        // Select the appropriate regex\n        let regex: RegExp;\n        switch (lang) {\n            case 'el':\n                regex = this.sentenceRegex.el;\n                break;\n            case 'es':\n                regex = this.sentenceRegex.es;\n                break;\n            default:\n                // Use the generic regex for English, German, French, and Italian\n                regex = this.sentenceRegex.generic;\n        }\n\n        const sentences = text.match(regex);\n        return sentences ? sentences.map(s => s.trim()) : [];\n    }\n};\n\n// --- Example Usage ---\n\nconst spanishText = '\u00BFHola, c\u00F3mo est\u00E1s? \u00A1Espero que bien! Esto es una prueba.';\nconst greekText = '\u039A\u03B1\u03BB\u03B7\u03BC\u03AD\u03C1\u03B1. \u03A4\u03B9 \u03BA\u03AC\u03BD\u03B5\u03B9\u03C2\u037E \u0395\u03BB\u03C0\u03AF\u03B6\u03C9 \u03BD\u03B1 \u03B5\u03AF\u03C3\u03B1\u03B9 \u03BA\u03B1\u03BB\u03AC.';\nconst germanText = 'Guten Tag. Wie geht es Ihnen? Er sagte: \u201EDas ist gut.\u201C';\n\nif (logalot) {\n    console.log('--- Spanish ---');\n    console.log(sentenceSplitter.split(spanishText));\n\n    console.log('\\n--- Greek ---');\n    console.log(sentenceSplitter.split(greekText));\n\n    console.log('\\n--- German ---');\n    console.log(sentenceSplitter.split(germanText));\n}\n", "import { delay, extractErrorMsg, getSaferSubstring, getTimestamp, getTimestampInTicks, getUUID, pickRandom, pickRandom_Letters, pretty, unique } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';\nimport { Ib, IbGibAddr, TransformResult } from '@ibgib/ts-gib/dist/types.mjs';\nimport { getIbGibAddr } from '@ibgib/ts-gib/dist/helper.mjs';\nimport { getLatestTimelineIbGibDto_nonLocking, mut8Timeline } from \"@ibgib/core-gib/dist/timeline/timeline-api.mjs\";\nimport { alertUser, highlightElement, shadowRoot_getElementById } from '@ibgib/web-gib/dist/helpers.web.mjs';\nimport { getGlobalMetaspace_waitIfNeeded, } from '@ibgib/web-gib/dist/helpers.mjs';\nimport { AgentWitnessAny } from '@ibgib/web-gib/dist/witness/agent/agent-one-file.mjs';\nimport { debounce, deleteAt, getShortenedStringWithEllipsis, insertAt } from '@ibgib/web-gib/dist/helpers.mjs';\n\nimport { GLOBAL_LOG_A_LOT } from '../../../constants.mjs';\nimport {\n    Minigame_TypingGameMeta, Minigame_TypingStimulus,\n    Minigame_TypingInteraction, StimulusEditInfo, TypingEntryAndElementsInfo,\n    FocusAndElementsInfo\n} from './typing-types.mjs';\nimport { MinigameData_V1, MinigameIbGib_V1 } from '../minigame-types.mjs';\nimport { MinigameGameType } from '../minigame-constants.mjs';\nimport { AnalysisResult } from '../../text-analysis/types.mjs';\nimport { AnalysisEngine } from '../../text-analysis/analysis-engine.mjs';\nimport { DEFAULT_TOKEN_CONSTRUCT_RULE } from '../../text-analysis/analysis-engine-constants.mjs';\nimport { CorpusAnalyzer } from '../../text-analysis/corpus-analyzer.mjs';\nimport { sentenceSplitter } from './sentence-helper.mjs';\nimport { ExpectedResponseType } from './typing-constants.mjs';\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\n/**\n * edits stimuli in the `minigame.data.gameMeta` (NOT in actual minigame\n * instances)\n *\n * @returns new minigame ibgib updated with edited stimuli\n */\nexport async function editStimuli_typing({\n    stimuliEditInfos,\n    minigameIbGib,\n    minigameAddr,\n}: {\n    stimuliEditInfos: StimulusEditInfo[],\n    minigameIbGib?: MinigameIbGib_V1,\n    minigameAddr?: IbGibAddr,\n}): Promise<MinigameIbGib_V1> {\n    const lc = `[${editStimuli_typing.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 47ab6f7a4198c302c84df8afa30b4825)`); }\n\n        const metaspace = await getGlobalMetaspace_waitIfNeeded();\n        const space = await metaspace.getLocalUserSpace({ lock: false });\n        if (!space) { throw new Error(`(UNEXPECTED) couldn't get default local user space? (E: 178328ba5588da03e83b8efccf107b25)`); }\n\n        if (!minigameIbGib && !minigameAddr) { throw new Error(`either minigameIbGib or minigameAddr required. (E: 7b65cd92cc48de0fd88d6a58fd727b25)`); }\n        minigameAddr ??= getIbGibAddr({ ibGib: minigameIbGib });\n\n        /**\n         * does not lock. if we are to the point of online collaboration, this\n         * should be changed to a single locking call to ensure we have the\n         * latest data (latest ibgib in the timeline) probably yagni thought\n         * since we won't get there with this iteration, but hey.\n         */\n        let latestMinigameIbGib = await getLatestTimelineIbGibDto_nonLocking({\n            timelineAddr: minigameAddr,\n            metaspace,\n            space,\n        }) as MinigameIbGib_V1;\n        if (!latestMinigameIbGib.data) { throw new Error(`(UNEXPECTED) latestMinigameIbGib.data falsy? (E: 2f344d548d79589813cd94c8ad86aa25)`); }\n\n\n\n        const gameMeta_existing = latestMinigameIbGib.data.gameMeta as Minigame_TypingGameMeta;\n        let allStimuli_new = [...(gameMeta_existing.allStimuli ?? [])];\n        // const gameMeta_new = { ...gameMeta_existing };\n        // gameMeta_new.allStimuli ??= [];\n\n        for (const info of stimuliEditInfos) {\n            let existingIndex: number | undefined;\n            switch (info.action) {\n                case \"add\":\n                    allStimuli_new.push(info.newStimulus as Minigame_TypingStimulus); // just pretend it's valid\n                    // info.index info.stimulusId unused\n                    break;\n                case \"insert\":\n                    if (typeof info.index !== 'number') {\n                        throw new Error(`info.index type is not 'number'. info: ${pretty(info)} (E: ce218f07b29a93f148257793343e9925)`);\n                    }\n                    // maybe yagni\n                    if (info.stimulusId) {\n                        console.warn(`${lc} info.stimulusId set, but we're ignoring this. info.index drives where the insert happens. info: ${pretty(info)} (W: fc6c3682ce29462b79008c11949a5525)`);\n                    }\n                    allStimuli_new = insertAt({\n                        newItems: [info.newStimulus as Minigame_TypingStimulus], // just pretend it's valid\n                        index: info.index,\n                        targetArray: allStimuli_new,\n                    });\n                    break;\n                case \"edit\":\n                    if (info.stimulusId) {\n                        existingIndex = allStimuli_new.findIndex(x => x.id === info.stimulusId);\n                    } else if (typeof info.index === 'number') {\n                        if (info.index < 0 || info.index >= allStimuli_new.length) {\n                            throw new Error(`info.index (${info.index}) out of range of allStimuli_new (allStimuli_new.length: ${allStimuli_new.length}). this may be due to the fact that this edit happens after previous edits, so indexes may have changed. use stimulusId instead of trying to calculate indexes to avoid this (E: db75d65be8f6080fa88851180e9e9a25)`);\n                        }\n                        existingIndex = info.index;\n                    } else {\n                        throw new Error(`either info.stimulusId or info.index required when editing. info: ${pretty(info)} (E: 2d38bd7c11b8adba0af23626befd6625)`);\n                    }\n                    if (existingIndex === -1) { throw new Error(`(UNEXPECTED) existingIndex === -1? this should be guaranteed at this point. (E: 54d3e86cc3f81992b8b656289edef825)`); }\n                    allStimuli_new[existingIndex] = info.newStimulus as Minigame_TypingStimulus; // just pretend it's valid\n                    break;\n                case \"delete\":\n                    if (info.stimulusId) {\n                        existingIndex = allStimuli_new.findIndex(x => x.id === info.stimulusId);\n                    } else if (typeof info.index === 'number') {\n                        if (info.index < 0 || info.index >= allStimuli_new.length) {\n                            throw new Error(`info.index (${info.index}) out of range of allStimuli_new (allStimuli_new.length: ${allStimuli_new.length}). this may be due to the fact that this edit happens after previous edits, so indexes may have changed. use stimulusId instead of trying to calculate indexes to avoid this (E: 011bd8fae1d883dd1f4fe2f41aaff825)`);\n                        }\n                        existingIndex = info.index;\n                    } else {\n                        throw new Error(`either info.stimulusId or info.index required when editing. info: ${pretty(info)} (E: 2d38bd7c11b8adba0af23626befd6625)`);\n                    }\n                    if (existingIndex === -1) { throw new Error(`(UNEXPECTED) existingIndex === -1? this should be guaranteed at this point. (E: 54d3e86cc3f81992b8b656289edef825)`); }\n\n                    allStimuli_new = deleteAt({\n                        index: existingIndex,\n                        targetArray: allStimuli_new,\n                    });\n                    break;\n                default:\n                    throw new Error(`(UNEXPECTED) invalid stimuliEditInfo.action (${info.action})? only add/insert/edit/delete atow (E: 680aa6d051d9b4ee98035fb84e570625)`);\n            }\n        }\n\n\n        // const allStimuli_new = [\n        //     ...gameMeta_existing.allStimuli ?? [],\n        //     ...stimuliEditInfos,\n        // ];\n\n        // if any are deletes, we must first clear out allStimuli completely,\n        // otherwise, the mut8 call will not work properly. (this is slightly\n        // inefficient but at this scale shouldn't be a big deal)\n        if (stimuliEditInfos.some(x => x.action === 'delete')) {\n            latestMinigameIbGib = await mut8Timeline({\n                timelineAddr: minigameAddr,\n                mut8Opts: {\n                    dataToRemove: {\n                        gameMeta: { allStimuli: true },\n                    },\n                },\n                metaspace,\n                space,\n            });\n        }\n\n        /**\n         * this should leave other existing gameMeta data as-is.\n         */\n        const dataToAddOrPatch: Partial<MinigameData_V1> = {\n            gameMeta: { allStimuli: allStimuli_new },\n            /**\n             * not playable until game is validated.\n             */\n            playable: false,\n        }\n        const newMinigameIbGib = await mut8Timeline({\n            timelineAddr: minigameAddr,\n            mut8Opts: {\n                dataToAddOrPatch,\n            },\n            metaspace,\n            space,\n        });\n\n        if (logalot) { console.log(`${lc} newMinigameIbGib: ${pretty(newMinigameIbGib)} (I: 41d2d8d3e0f88e9bf8a517089e21f525)`); }\n\n        return newMinigameIbGib;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport async function validateMinigameIsReady_typing({\n    minigameIbGib,\n    data,\n}: {\n    minigameIbGib: MinigameIbGib_V1,\n    data?: MinigameData_V1,\n}): Promise<string[]> {\n    const lc = `[${validateMinigameIsReady_typing.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 9f14f89cbbaa9dfdc83f0b3814cac825)`); }\n\n        if (!minigameIbGib.data) { throw new Error(`(UNEXPECTED) minigameIbGib.data falsy? (E: 9d30081f4cc8eaec112d9ad769218125)`); }\n\n        data ??= minigameIbGib.data;\n        if (data.gameType !== MinigameGameType.typing) { throw new Error(`(UNEXPECTED) data.gameType !== 'typing'? (E: 403cdb545ab81ac618b9ed859eb92825)`); }\n\n        const errors: string[] = [];\n\n        const gameMeta = data.gameMeta as Minigame_TypingGameMeta;\n        if (!gameMeta.allStimuli || gameMeta.allStimuli.length === 0) {\n            errors.push(`No stimuli added to the game. (E: genuuid)`);\n        }\n\n        // do I care about game state here? I think I'm just looking to start a\n        // new game based off of this ibgib.\n        // const gameState = data.gameState as Minigame_TypingGameState;\n\n        return errors;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\ninterface ElapsedInfo {\n    /**\n     * if undefined, the others will be undefined\n     */\n    startingTimestampInTicks?: number;\n    /**\n     * if there is no response, maybe caller wants last stimulus\n     */\n    elapsedMs_toLastInteractionStimulus?: number;\n    /**\n     * most recent interaction\n     */\n    elapsedMs_toLastInteractionResponse?: number;\n    elapsedMs_toNow?: number;\n    /**\n     * undefined if no errors\n     */\n    errors?: string[];\n}\n\n/**\n *\n * @returns elapsedMs between {@link a} and {@link b}\n */\nexport function getElapsedInfo({\n    a,\n    b,\n}: {\n    /** starting interaction */\n    a: Minigame_TypingInteraction,\n    /**\n     * ending interaction. if no response has been givenyet, then this will be ignored\n     */\n    b: Minigame_TypingInteraction,\n}): ElapsedInfo {\n    const lc = `[${getElapsedInfo.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 0368a7efc608341ac863fd989f646425)`); }\n        const startTimestampString: string | undefined = a.stimulus.timestampInTicks;\n        if (startTimestampString === undefined) { throw new Error(`a.stimulus.timestampInTicks undefined, so no starting point and no elapsed possible. (E: b38d473042687aef02395bdab04afc25)`); }\n\n        let errors: string[] = [];\n        const result: ElapsedInfo = {};\n\n        const startTimestampInTicksInt = Number.parseInt(startTimestampString);\n        if (Number.isNaN(startTimestampInTicksInt)) { throw new Error(`a.stimulus.timestampInTicks is not an integer string. (E: d40578dabe08b6ecb81092f5e94b1625)`); }\n\n\n        if (b.stimulus.timestampInTicks) {\n            const end_stimulusInTicksInt = Number.parseInt(b.stimulus.timestampInTicks);\n            if (!Number.isNaN(end_stimulusInTicksInt)) {\n                result.elapsedMs_toLastInteractionStimulus =\n                    end_stimulusInTicksInt - startTimestampInTicksInt;\n            } else {\n                errors.push(`end timestamp is not an integer string (E: 45bfc98e3dc8743b459951c419408a25)`);\n            }\n        }\n        if (b.response.timestampInTicks) {\n            const end_responseInTicksInt = Number.parseInt(b.response.timestampInTicks);\n            if (!Number.isNaN(end_responseInTicksInt)) {\n                result.elapsedMs_toLastInteractionResponse =\n                    end_responseInTicksInt - startTimestampInTicksInt;\n            } else {\n                errors.push(`end timestamp is not an integer string (E: 45bfc98e3dc8743b459951c419408a25)`);\n            }\n        }\n\n        const now_timestampInTicks = getTimestampInTicks();\n        const now_timestampInTicksInt = Number.parseInt(now_timestampInTicks);\n        result.elapsedMs_toNow = now_timestampInTicksInt - startTimestampInTicksInt;\n\n        if (errors.length > 0) { result.errors = errors; }\n\n        return result;\n    } catch (error) {\n        const emsg = `${lc} ${extractErrorMsg(error)}`;\n        console.error(emsg);\n        return { errors: [emsg] };\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport function getWpm({\n    responsesAnalysis,\n    elapsedMs,\n}: {\n    responsesAnalysis: AnalysisResult,\n    elapsedMs: number,\n}): number {\n    const lc = `[${getWpm.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: c0d406b91c0f3776e99c871834477a25)`); }\n        const elapsedMinutes = elapsedMs * 1 / 1000 * 1 / 60;\n        const wpmRaw = responsesAnalysis.tokenCount / elapsedMinutes;\n        return Math.round(wpmRaw);\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport interface Timespan {\n    hours: number;\n    minutes: number;\n    seconds: number;\n}\n\n/**\n * Converts elapsed milliseconds into hours, minutes, and seconds.\n */\nexport function toHoursMinutesSeconds({\n    elapsedMs,\n}: {\n    elapsedMs: number;\n}): Timespan {\n    const lc = `[${toHoursMinutesSeconds.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 483c177d8a99f9942e18ff441f708625)`); }\n\n        if (elapsedMs < 0) { throw new Error(`elapsedMs cannot be negative (E: ab1c234d6789e0f123456789abcd1234)`); }\n\n        const totalSeconds = Math.floor(elapsedMs / 1000);\n        const hours = Math.floor(totalSeconds / 3600);\n        const minutes = Math.floor((totalSeconds % 3600) / 60);\n        const seconds = totalSeconds % 60;\n\n        return { hours, minutes, seconds };\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport type TypingFocusLevel = 'character' | 'word' | 'sentence' | 'newline' | 'paragraph';\nexport const TypingFocusLevel = {\n    character: 'character',\n    word: 'word',\n    sentence: 'sentence',\n    newline: 'newline',\n    paragraph: 'paragraph',\n} satisfies { [key: string]: TypingFocusLevel }\n\nexport async function getUniqueTokens({\n    text,\n    tokensToIgnore,\n}: {\n    text: string\n    /**\n     * will ignore these.\n     *\n     * ## notes\n     *\n     * use this for ignore running list of existing tokens\n     */\n    tokensToIgnore?: string[],\n}): Promise<string[]> {\n    const lc = `[${getUniqueTokens.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 353b99880015c1edce5b2ba8321d6425)`); }\n\n        tokensToIgnore ??= [];\n\n        const docId = pickRandom_Letters({ count: 8 });\n        const topN = 15;\n        const engine = new AnalysisEngine([\n            DEFAULT_TOKEN_CONSTRUCT_RULE,\n            // ...DEFAULT_SPANISH_RULES,\n        ]);\n        // const analyzer = new CorpusAnalyzer(AnalysisEngine.DEFAULT);\n        const analyzer = new CorpusAnalyzer(engine);\n        analyzer.addDocumentFromText({\n            id: docId,\n            text,\n        });\n        const analysis = analyzer.getDocumentAnalysis({ id: docId });\n        if (!analysis) { throw new Error(`(UNEXPECTED) responses_analysis falsy? (E: 02a658aa66a93b9118a83f38ec3c4f25)`); }\n        if (logalot) { console.dir(analysis); }\n        const report = analyzer.generateDocumentReport({\n            docId: docId,\n            topN,\n            constructsToReport: [AnalysisEngine.PRIMORDIAL_TOKEN_CONSTRUCT_NAME]\n        });\n        if (logalot) { console.dir(report); }\n\n        const tokenFreqMap = analysis.constructs[AnalysisEngine.PRIMORDIAL_TOKEN_CONSTRUCT_NAME]!;\n        const tokenFreqMapEntriesSortedByCount = Object.entries(tokenFreqMap).sort((a, b) => b[1] - a[1]);\n        if (logalot) { console.dir(tokenFreqMapEntriesSortedByCount) }\n\n        const uniqueTokens = Object.keys(tokenFreqMap).filter(x => !tokensToIgnore!.includes(x.toLocaleLowerCase()));\n\n        if (logalot) { console.log(`${lc} uniqueTokens: ${uniqueTokens} (I: 0e5df96e0ca560be08971a45b03bc325)`); }\n\n        return uniqueTokens;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * We want to pull some focus from {@link text} but we don't want to repeat\n * anything that is already in {@link existingFocuses}.\n *\n * So we split the text into pieces depending on {@link focusLevel}, and then\n * pick one of those that isn't already encoded in the {@link existingFocuses}.\n *\n * If nothing is new, will returned undefined.\n */\nexport async function getAnotherFocusText({\n    text,\n    focusLevel,\n    existingFocuses,\n    randomize,\n}: {\n    text: string,\n    focusLevel: TypingFocusLevel,\n    existingFocuses: string[],\n    randomize: boolean,\n}): Promise<string | undefined> {\n    const lc = `[${getAnotherFocusText.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 60c22940b1c89e2a02a4a311a9b97825)`); }\n        if (!text) {\n            alertUser({ msg: `The text to draw from is empty? Add some text from which we will choose our focus. (E: 2b4cfab9bfdb3771a15e63683dc8c825)` });\n            return undefined; /* <<<< returns early */\n        }\n        const allFocuses = existingFocuses.join('\\n');\n        /** pool among which to choose */\n        let focusPool: string[];\n        switch (focusLevel) {\n            case 'character':\n                const uniqueCharacters = unique(text.split(''));\n                const allFocusesChars = unique(allFocuses.split(''));\n                focusPool = uniqueCharacters\n                    .filter(x => !!x)\n                    .filter(x => !allFocusesChars.includes(x));\n                break;\n            case 'word':\n                const existingFocuses_lower = existingFocuses.map(x => x.toLocaleLowerCase());\n                focusPool = await getUniqueTokens({ text, tokensToIgnore: existingFocuses_lower });\n                break;\n            case 'sentence':\n                const sentences = sentenceSplitter.split(text)\n                    .filter(x => !!x)\n                    .filter(x => !allFocuses.includes(x));\n                focusPool = sentences;\n                break;\n            case 'newline':\n                const lines = text.split('\\n')\n                    .filter(x => !!x)\n                    .filter(x => !existingFocuses.includes(x));\n                focusPool = lines;\n                break;\n            case 'paragraph':\n                const paragraphs = text.split('\\n\\n')\n                    .filter(x => !!x)\n                    .filter(x => !allFocuses.includes(x));\n                focusPool = paragraphs;\n                break;\n            default:\n                throw new Error(`(UNEXPECTED) focusLevel is ${focusLevel}?  (E: ca6618ea99784ad0285cc142b13a7625)`);\n        }\n        const resFocusText = randomize ?\n            pickRandom({ x: focusPool }) :\n            focusPool.at(0);\n        if (!resFocusText || logalot) { console.log(`${lc} resFocusText: ${resFocusText} (I: ed8989737268966aa824fd78deda6825)`); }\n        return resFocusText;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport function getGoogleTranslateLink({ text }: { text: string }): string {\n    const lc = `[${getGoogleTranslateLink.name}]`;\n    if (text) {\n        return `https://translate.google.com/details?text=${encodeURI(text)}`;\n    } else {\n        console.warn(`${lc} incoming text is empty/falsy. (W: b45e876a4a98396eeda23a4564b84825)`);\n        return `https://translate.google.com/details`;\n    }\n}\n\nexport async function getStimulusEntryEl({\n    shadowRoot,\n    stimulusEntry,\n}: {\n    shadowRoot: ShadowRoot,\n    stimulusEntry: Minigame_TypingStimulus,\n}): Promise<TypingEntryAndElementsInfo> {\n    const lc = `[${getStimulusEntryEl.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 952d0fc7900fcf80640b7947e6749825)`); }\n\n        // the stimulus entry element is driven by the stimulus-entry-template\n\n        const entryTemplate = shadowRoot_getElementById<HTMLTemplateElement>(shadowRoot, 'stimulus-entry-template');\n        const entryTemplateContentNode = entryTemplate.content.cloneNode(true) as DocumentFragment;\n        const entryEl = document.createElement('li');\n        const entryTemplateDiv = entryTemplateContentNode.firstElementChild;\n        if (!entryTemplateDiv) { throw new Error(`(UNEXPECTED) !templateDiv? (E: f0a8980037fabe1fd814b9fc044d3d25)`); }\n        entryEl.append(entryTemplateDiv);\n        // how to query children of the entryEl:\n        // const entryTextEl = entryTemplateDiv.querySelector('#focus-template-focus-text') as HTMLElement;\n        const entryTextEl = entryTemplateDiv.querySelector('#stimulus-entry-text') as HTMLElement;\n        entryTextEl.textContent = stimulusEntry.value;\n\n        // #region buttons\n        const deleteBtnEl = entryTemplateDiv.querySelector('#stimulus-entry-delete-btn') as HTMLButtonElement;\n        const editBtnEl = entryTemplateDiv.querySelector('#stimulus-entry-edit-btn') as HTMLButtonElement;\n        const expandBtnEl = entryTemplateDiv.querySelector('#stimulus-entry-expand-btn') as HTMLButtonElement;\n        expandBtnEl.addEventListener('click', async () => {\n            const detailsEl = entryTemplateDiv.querySelector('.stimulus-entry-details-section') as HTMLElement;\n            const variantEl = entryTemplateDiv.querySelector('.stimulus-entry-variant') as HTMLParagraphElement;\n            variantEl.textContent = stimulusEntry.variant ?? '';\n            const focusTextEl = entryTemplateDiv.querySelector('.stimulus-entry-focus-text') as HTMLParagraphElement;\n            focusTextEl.textContent = stimulusEntry.focus ?? '';\n            const languageEl = entryTemplateDiv.querySelector('.stimulus-entry-language') as HTMLParagraphElement;\n            // if languageEl is falsy, use src language typing-fullscreen-dialog-text-language-input\n            const srcLanguageEl = shadowRoot_getElementById<HTMLInputElement>(shadowRoot, 'typing-fullscreen-dialog-text-language-input');\n            languageEl.textContent = stimulusEntry.language ?? srcLanguageEl?.value ?? '';\n\n            // span for readonly, select for edit\n            const expectedTypeEl = entryTemplateDiv.querySelector('.stimulus-entry-expected-response-type-p') as HTMLSpanElement;\n            expectedTypeEl.textContent =\n                stimulusEntry.expectedResponseType ?? ExpectedResponseType.exact;\n            const expectedTypeSelectEl = entryTemplateDiv.querySelector('.stimulus-entry-expected-response-type-select') as HTMLSelectElement;\n            expectedTypeSelectEl.value = stimulusEntry.expectedResponseType ?? ExpectedResponseType.exact;\n            const expectedTextEl = entryTemplateDiv.querySelector('.stimulus-entry-expected-response-text') as HTMLParagraphElement;\n            expectedTextEl.textContent = stimulusEntry.expectedResponse ?? '';\n\n            // expectedResponse // :\n            // \"Ay candela, candela, candela, me quemo a\u00E9.\"\n            // expectedResponseType // : // \"equivalent\"\n            // notes\n            // :\n            // \"auto-generated from user\"\n            // timestampInTicks\n            // :\n            // \"1756046646203\"\n            // value\n            // :\n            // \"Oh fire, fire, fire, I'm burning up.\"\n            // variant\n            // :\n            // \"translate\"\n\n            // animation\n            detailsEl.style.display = 'flex';\n            await delay(50);\n            detailsEl.style.maxHeight = '1000px';\n            await highlightElement({ el: detailsEl, magicHighlightTimingMs: 1_000 });\n            detailsEl.style.maxHeight = 'none';\n        });\n        // #endregion buttons\n\n        return {\n            stimulusEntry,\n            entryEl,\n            deleteBtnEl,\n            editBtnEl\n        };\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nfunction getTextTargetMappingString({\n    fromText,\n    toText,\n    maxChars = 12,\n}: {\n    fromText: string,\n    toText: string,\n    maxChars?: number,\n}): string {\n    return `${getShortenedStringWithEllipsis({ str: fromText, maxChars })} -> ${getShortenedStringWithEllipsis({ str: toText, maxChars })}`;\n}\n\nexport async function askAgentTranslateOneOff({\n    text,\n    agent,\n    contextSrcText,\n}: {\n    text: string,\n    agent: AgentWitnessAny,\n    contextSrcText: string,\n}): Promise<string | undefined> {\n    const lc = `[${askAgentTranslateOneOff.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: c4c5bf3a072a4bf1d82c7be8a18c5825)`); }\n\n        const resTranslation = await agent.promptOneOff({\n            text: [\n                `Hi. Please translate \"${text}\" into en-US.`\n            ].join('\\n'),\n            systemInstructions: [\n                'You are an expert translator and are helping the user learn a foreign language. The context source text for translating is:',\n                '```',\n                contextSrcText,\n                '```',\n                'The user is creating one or more dynamic flashcards with a focus on this text:',\n                '```',\n                text,\n                '```',\n                `In your response, don't use a full sentence, just say the translation. So if the user asks to translate \"cane\" from italian, just say \"dog\". Or if they ask a full line from a song like \"A Chan Chan le daba pena\", just say \"It gave Chan Chan pain\" (or whatever you think is the best translation).`,\n                `Thank you in advance! ;-)`,\n            ].join('\\n'),\n        });\n\n        return resTranslation;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport async function getFocusAndElementsInfo({\n    shadowRoot,\n    dialogSrcText,\n    text,\n    language,\n    fnHandleStimuliGenerated,\n    agent,\n}: {\n    shadowRoot: ShadowRoot,\n    dialogSrcText: string,\n    text: string,\n    language?: string,\n    fnHandleStimuliGenerated: (stimuli: Minigame_TypingStimulus[]) => Promise<void>,\n    agent?: AgentWitnessAny,\n}): Promise<FocusAndElementsInfo> {\n    const lc = `[${getFocusAndElementsInfo.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 077b4beeb0582d64ebe6b3e80ba58825)`); }\n\n        const focusTemplate = shadowRoot_getElementById<HTMLTemplateElement>(shadowRoot, 'focus-template');\n        const focusTemplateContentNode = focusTemplate.content.cloneNode(true) as DocumentFragment;\n        const entryEl = document.createElement('li');\n        const focusTemplateDiv = focusTemplateContentNode.firstElementChild;\n        if (!focusTemplateDiv) { throw new Error(`(UNEXPECTED) !templateDiv? (E: 3d8f38fcf5d87b9a52576f68a8b4ad25)`); }\n        entryEl.append(focusTemplateDiv);\n        const focusTextEl = focusTemplateDiv.querySelector('#focus-template-focus-text') as HTMLElement;\n        focusTextEl.textContent = text;\n        const focusTextTranslateEl = focusTemplateDiv.querySelector('#focus-text-translate-link') as HTMLAnchorElement;\n        focusTextTranslateEl.href = getGoogleTranslateLink({ text });\n        const deleteBtnEl = focusTemplateDiv.querySelector('#focus-template-delete-btn') as HTMLButtonElement;\n        // const editBtnEl = templateDiv.querySelector('#focus-template-edit-btn') as HTMLButtonElement;\n        // const genStimuliBtnEl = templateDiv.querySelector('#focus-template-add-btn') as HTMLButtonElement;\n\n        const detailsParrotEl = focusTemplateDiv.querySelector('#focus-template-stimuli-details-parrot') as HTMLElement;\n        const detailsFitbEl = focusTemplateDiv.querySelector('#focus-template-stimuli-details-fitb') as HTMLElement;\n        const detailsTranslateEl = focusTemplateDiv.querySelector('#focus-template-stimuli-details-translate') as HTMLElement;\n        const detailsEls: HTMLElement[] = [\n            detailsParrotEl,\n            detailsFitbEl,\n            detailsTranslateEl,\n        ];\n\n        const fnOutroEl = async (el: HTMLElement) => {\n            await highlightElement({ el });\n            await delay(200);\n            await slideRightAndFade({ el, durationMs: 500 });\n            el.style.display = 'none';\n            if (el !== entryEl) {\n                // only recurse if we're not already recursing the entryEl\n                // itself\n                if (detailsEls.every(x => x.style.display === 'none')) {\n                    await delay(250);\n                    await fnOutroEl(entryEl);\n                }\n            }\n        }\n\n        // #region parrot\n\n        const detailsParrot_expectedResponse = focusTemplateDiv.querySelector('#focus-template-stimuli-details-parrot-text') as HTMLParagraphElement;\n        // detailsParrot_expectedResponse.textContent = text;\n        detailsParrot_expectedResponse.textContent = getTextTargetMappingString({\n            fromText: text,\n            toText: text,\n            maxChars: 12,\n        });\n        const detailsParrotAddBtn = focusTemplateDiv.querySelector('#focus-template-details-parrot-add-btn') as HTMLButtonElement;\n        detailsParrotAddBtn.addEventListener('click', async () => {\n            const stimulusEntry: Minigame_TypingStimulus = {\n                id: await getNewTypingEntryId(),\n                entryType: 'text',\n                variant: 'parrot',\n                value: text,\n                expectedResponse: text,\n                expectedResponseType: 'exact',\n                language,\n                focus: text,\n                notes: `auto-generated from user`,\n                timestampInTicks: getTimestampInTicks(),\n            };\n            await fnHandleStimuliGenerated([stimulusEntry]);\n            await fnOutroEl(detailsParrotEl);\n        });\n\n        // #endregion parrot\n\n        // #region fitb\n\n        const uniqueTokens = await getUniqueTokens({ text, });\n        if (uniqueTokens.length > 1) {\n            const detailsFitbNumBlanksEl = focusTemplateDiv.querySelector('#focus-template-stimuli-details-fitb-numblanks') as HTMLInputElement;\n            const fnGetBlankedText: (str: string, numBlanks: number, blank: string) => Promise<[string, string[]] | undefined> = async (str, numBlanks, blank) => {\n                if (numBlanks < uniqueTokens.length) {\n                    // build blanked text and get info on each blank's 1st location\n                    let blankedText = str.concat();\n                    const answerMap: { [blankIndex: number]: string } = {};\n                    const availableTokens = new Set(uniqueTokens);\n                    for (let i = 0; i < numBlanks; i++) {\n                        const token = pickRandom({ x: Array.from(availableTokens) })!;\n                        availableTokens.delete(token);\n                        const blankIndex = str.toLocaleLowerCase().indexOf(token.toLocaleLowerCase());\n                        answerMap[blankIndex] = token;\n                        blankedText = blankedText.replace(new RegExp(token, 'ig'), blank);\n                    }\n                    // get sorted answers from the answerMap\n                    const answerIndices = Object.keys(answerMap).map(Number).sort((a, b) => a - b);\n                    const answers = answerIndices.map(index => answerMap[index]);\n\n                    return [blankedText, answers];\n                } else {\n                    await alertUser({ msg: 'too many blanks!' });\n                    return undefined; /* <<<< returns early */\n                }\n            }\n            const detailsFitb_blankedTextEl = focusTemplateDiv.querySelector('#focus-template-stimuli-details-fitb-blanked-text') as HTMLParagraphElement;\n            const detailsFitb_expectedResponseEl = focusTemplateDiv.querySelector('#focus-template-stimuli-details-fitb-expected') as HTMLParagraphElement;\n            const fnUpdateFitbInfo = async () => {\n                const resBlank = await fnGetBlankedText(text, detailsFitbNumBlanksEl.valueAsNumber, '____');\n                if (!resBlank) { return; /* <<<< returns early */ }\n                const [blankedText, answers] = resBlank;\n                detailsFitb_blankedTextEl.textContent = blankedText;\n                (detailsFitb_blankedTextEl as any).answers = answers;\n                // detailsFitb_blankedTextEl.dataset.answers = answers.join('|');\n                detailsFitb_expectedResponseEl.textContent = answers.join(' ');\n            }\n            detailsFitbNumBlanksEl.addEventListener('input', debounce(fnUpdateFitbInfo, 1_000));\n            await fnUpdateFitbInfo();\n            const detailsFitbAddBtn = focusTemplateDiv.querySelector('#focus-template-details-fitb-add-btn') as HTMLButtonElement;\n            detailsFitbAddBtn.addEventListener('click', async () => {\n                if (!detailsFitb_blankedTextEl.textContent) { throw new Error(`(UNEXPECTED) !detailsFitb_blankedTextEl.textContent? should be text with blanks (E: c7eaf21d604ef15a880c67cf636e2c25)`); }\n                if (!detailsFitb_expectedResponseEl.textContent) { throw new Error(`(UNEXPECTED) !detailsFitb_expectedResponseEl.textContent? should be the text that goes in the blank(s) (E: 2f9122d26a288b797d582e4812790a25)`); }\n                const stimulusEntry: Minigame_TypingStimulus = {\n                    id: await getNewTypingEntryId(),\n                    entryType: 'text',\n                    variant: 'fitb',\n                    value: detailsFitb_blankedTextEl.textContent,\n                    expectedResponse: detailsFitb_expectedResponseEl.textContent,\n                    expectedResponseType: 'fill-in-the-blank',\n                    language,\n                    focus: text,\n                    notes: `auto-generated from user`,\n                    timestampInTicks: getTimestampInTicks(),\n                };\n                await fnHandleStimuliGenerated([stimulusEntry]);\n                await fnOutroEl(detailsFitbEl);\n            });\n        } else {\n            // focus text has only one token so can't do fitb\n            detailsFitbEl.style.display = 'none';\n        }\n\n        // #endregion fitb\n\n        // #region translate\n\n        const detailsTranslateTranslatedFocusTextEl = focusTemplateDiv.querySelector('#stimulus-gen-translated-focus-text') as HTMLTextAreaElement;\n        const fnUpdateTranslationLabels = async (translation: string) => {\n            console.log(translation);\n            detailsTranslateTranslatedFocusTextEl.textContent = translation?.trim() ?? '';\n            const detailsTranslate_stimulusGenTargetNative = focusTemplateDiv.querySelector('#stimulus-gen-target-native') as HTMLParagraphElement;\n            detailsTranslate_stimulusGenTargetNative.textContent = getTextTargetMappingString({\n                fromText: text,\n                toText: translation ?? '[?]',\n                maxChars: 12,\n            });\n            detailsTranslate_stimulusGenTargetNative.title = `${text}\\n\\n->\\n\\n${translation}`;\n            const detailsTranslate_stimulusGenNativeTarget = focusTemplateDiv.querySelector('#stimulus-gen-native-target') as HTMLParagraphElement;\n            detailsTranslate_stimulusGenNativeTarget.textContent = getTextTargetMappingString({\n                toText: text,\n                fromText: translation ?? '[?]',\n                maxChars: 12,\n            });\n            detailsTranslate_stimulusGenNativeTarget.title = `${translation}\\n\\n->\\n\\n${text}`;\n        };\n        detailsTranslateTranslatedFocusTextEl.addEventListener('input', async () => {\n            await fnUpdateTranslationLabels(detailsTranslateTranslatedFocusTextEl.value);\n        });\n\n        const regenTranslateBtnEl = focusTemplateDiv.querySelector('#focus-template-details-translate-regen-btn') as HTMLButtonElement;\n        regenTranslateBtnEl.addEventListener('click', async () => {\n            if (agent) {\n                const rawAgentTranslation = await askAgentTranslateOneOff({\n                    text,\n                    agent,\n                    contextSrcText: dialogSrcText,\n                });\n                // update the translation itself\n                // HACK/TODO: we're assuming the text is in the foreign language and native language is\n                // pre-fill translate texts\n                if (rawAgentTranslation) { await fnUpdateTranslationLabels(rawAgentTranslation); }\n            } else {\n                await alertUser({\n                    title: 'Doh',\n                    msg: `There ain't no agent to do the translation! To use this translation feature, you have to set up an API key first. Go to contact me for more help. If you already have an API key and you have already reloaded the web site and can talk with agents in other contexts, then contact me and tell me about the bug. (E: 17386843536c7a4fd821e9882a15b525)`,\n                });\n            }\n        });\n\n\n        const languageOptionsCheckboxEl = shadowRoot_getElementById<HTMLInputElement>(shadowRoot, 'typing-fullscreen-dialog-language-options-checkbox');\n        if (agent && languageOptionsCheckboxEl.checked) {\n            const rawAgentTranslation = await askAgentTranslateOneOff({\n                text,\n                agent,\n                contextSrcText: dialogSrcText,\n            });\n            // update the translation itself\n            // HACK/TODO: we're assuming the text is in the foreign language and native language is\n            // pre-fill translate texts\n            if (rawAgentTranslation) { await fnUpdateTranslationLabels(rawAgentTranslation); }\n        }\n\n        // const detailsTranslateNativeTargetTextEl = templateDiv.querySelector('#stimulus-gen-native-target') as HTMLTextAreaElement;\n        const detailsTranslateTargetNativeCheckboxEl = focusTemplateDiv.querySelector('#focus-option-target-native') as HTMLInputElement;\n        const detailsTranslateNativeTargetCheckboxEl = focusTemplateDiv.querySelector('#focus-option-native-target') as HTMLInputElement;\n        // const detailsTranslateTargetTargetTextEl = templateDiv.querySelector('#stimulus-gen-target-target') as HTMLTextAreaElement;\n        // const detailsTranslateTargetTargetCheckboxEl = templateDiv.querySelector('#focus-option-target-target') as HTMLInputElement;\n        const detailsTranslateAddBtn = focusTemplateDiv.querySelector('#focus-template-translate-add-btn') as HTMLButtonElement;\n        detailsTranslateAddBtn.addEventListener('click', async () => {\n            const translatedText = detailsTranslateTranslatedFocusTextEl.value;\n            if (!translatedText) {\n                await alertUser({ title: 'doh', msg: 'need to add translation text' });\n                return; /* <<<< returns early */\n            }\n            if (!detailsTranslateTargetNativeCheckboxEl.checked && !detailsTranslateNativeTargetCheckboxEl.checked) {\n                await alertUser({ title: 'doh', msg: 'need to select one or more translation options.' });\n                return; /* <<<< returns early */\n            }\n            if (detailsTranslateTargetNativeCheckboxEl.checked) {\n                // translating direction is target -> native\n                // (understanding/hearing foreign language)\n                const stimulusEntry: Minigame_TypingStimulus = {\n                    id: await getNewTypingEntryId(),\n                    entryType: 'text',\n                    variant: 'translate',\n                    value: text,\n                    expectedResponse: translatedText,\n                    expectedResponseType: 'equivalent',\n                    language,\n                    focus: text,\n                    notes: `auto-generated from user`,\n                    timestampInTicks: getTimestampInTicks(),\n                };\n                await fnHandleStimuliGenerated([stimulusEntry]);\n            }\n            if (detailsTranslateNativeTargetCheckboxEl.checked) {\n                // translating direction is native -> target\n                // (speaking/typing foreign language)\n                const stimulusEntry: Minigame_TypingStimulus = {\n                    id: await getNewTypingEntryId(),\n                    entryType: 'text',\n                    variant: 'translate',\n                    value: translatedText,\n                    expectedResponse: text,\n                    expectedResponseType: 'equivalent',\n                    language,\n                    focus: text,\n                    notes: `auto-generated from user`,\n                    timestampInTicks: getTimestampInTicks(),\n                };\n                await fnHandleStimuliGenerated([stimulusEntry]);\n            }\n            await fnOutroEl(detailsTranslateEl);\n            // const stimulusEntry: Minigame_TypingStimulus = {\n            //     id: await getNewTypingEntryId(),\n            //     entryType: 'text',\n            //     variant: 'parrot',\n            //     value: text,\n            //     expectedResponse: text,\n            //     expectedResponseType: 'exact',\n            //     language,\n            //     focus: text,\n            //     notes: `auto-generated from user`,\n            //     timestampInTicks: getTimestampInTicks(),\n            // };\n            // await fnHandleStimuliGenerated([stimulusEntry]);\n        });\n\n        // #endregion translate\n\n        return {\n            focusText: text,\n            textEl: focusTextEl,\n            entryEl,\n            deleteBtnEl,\n            detailsParrotEl,\n            detailsFitbEl,\n            detailsTranslateEl,\n        };\n\n        // start entry\n        // const entryEl = document.createElement('li');\n\n\n        // the entry has 4 sections: focus text, options, btns (cmds), and\n        // generated stimuli\n\n        // focus text span\n        // const focusTextEl = document.createElement('span')\n        // focusTextEl.textContent = text;\n        // entryEl.appendChild(focusTextEl);\n\n        // // The options dictate what concrete stimuli to create when\n        // // genStimuliBtnEl is clicked\n        // const optionsDivEl = document.createElement('div');\n        // entryEl.appendChild(optionsDivEl);\n\n        // const btnsDivEl = document.createElement('div');\n        // entryEl.appendChild(btnsDivEl);\n        // // delete btn\n        // const deleteBtnEl = document.createElement('button')\n        // deleteBtnEl.textContent = '\u274C';\n        // btnsDivEl.appendChild(deleteBtnEl);\n        // // edit btn\n        // const editBtnEl = document.createElement('button')\n        // editBtnEl.textContent = '\u270E';\n        // btnsDivEl.appendChild(editBtnEl);\n        // // genStimuli btn\n        // const genStimuliBtnEl = document.createElement('button')\n        // genStimuliBtnEl.textContent = '\u2795';\n        // btnsDivEl.appendChild(genStimuliBtnEl);\n\n        // const stimuliEl = document.createElement('ul');\n        // entryEl.appendChild(stimuliEl);\n\n\n\n        // // stimuli container\n        // const stimuli = document.createElement('ul')\n        // entryEl.appendChild(editBtnEl);\n\n\n        // return {\n        //     text,\n        //     textEl: focusTextEl,\n        //     entryEl,\n        //     deleteBtnEl,\n        //     editBtnEl,\n        //     genStimuliBtnEl,\n        // };\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * @returns atow 16-char substring of a hash (arbitrary)\n */\nexport async function getNewTypingEntryId(): Promise<string> {\n    return (await getUUID()).substring(0, 16);\n}\n\n// export async function getTranslateText({\n//     focusText,\n//     focusLanguage,\n//     nativeLanguage,\n//     targetLanguage,\n// }): Promise<string> {\n//     trylogging\n// }\n\n\nexport async function slideRightAndFade({\n    el,\n    durationMs = 500,\n}: {\n    el: HTMLElement,\n    durationMs?: number,\n}): Promise<void> {\n    const lc = `[${slideRightAndFade.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 819e678e11526c6276a271999774b825)`); }\n\n        if (!el) { throw new Error(`${lc} el required (E: b0332924f44330e71a87136e9128e725)`); }\n\n        const width = el.offsetWidth;\n        if (width === 0) {\n            console.warn(`${lc} el has width 0, skipping animation. (W: b8e7284d7f9496f02a169602d8393a25)`);\n            return;\n        }\n\n        el.style.transition = `transform ${durationMs}ms ease-in-out, opacity ${durationMs}ms ease-in-out`;\n        el.style.transform = `translateX(${width}px)`;\n        el.style.opacity = '0';\n\n        // Wait for the transition to complete\n        await new Promise(resolve => setTimeout(resolve, durationMs));\n\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport async function unfadeEl({\n    el,\n}: {\n    el: HTMLElement,\n}): Promise<void> {\n    const lc = `[${unfadeEl.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: bb9bd8bc8a887b2f461e19489e7d2825)`); }\n        el.style.transition = ``;\n        el.style.transform = ``;\n        el.style.opacity = '1';\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n", "import { extractErrorMsg, getSaferSubstring, getTimestamp, pretty } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';\nimport { Ib, TransformResult } from '@ibgib/ts-gib/dist/types.mjs';\nimport { validateIbGibIntrinsically } from '@ibgib/ts-gib/dist/V1/validate-helper.mjs';\nimport { IbGib_V1, } from '@ibgib/ts-gib/dist/V1/types.mjs';\nimport { fork } from '@ibgib/ts-gib/dist/V1/transforms/fork.mjs';\nimport { Factory_V1 } from '@ibgib/ts-gib/dist/V1/factory.mjs';\nimport { getIbGibAddr } from '@ibgib/ts-gib/dist/helper.mjs';\nimport { persistTransformResult } from '@ibgib/core-gib/dist/witness/space/space-helper.mjs';\nimport { IbGibSpaceAny } from '@ibgib/core-gib/dist/witness/space/space-base-v1.mjs';\nimport { getTimestampInfo } from '@ibgib/core-gib/dist/common/other/ibgib-helper.mjs';\nimport { getGlobalMetaspace_waitIfNeeded } from '@ibgib/web-gib/dist/helpers.mjs';\n\nimport { GLOBAL_LOG_A_LOT } from '../../constants.mjs';\nimport {\n    MINIGAME_ATOM, MINIGAME_DESC_REGEXP, MINIGAME_NAME_REGEXP,\n    DEFAULT_MINIGAME_SAFE_NAME_LENGTH, DEFAULT_MINIGAME_ADDL_METADATA_LENGTH,\n    MINIGAME_PROTOTYPE_REL8N_NAME,\n    MinigameGameType,\n} from './minigame-constants.mjs'; // Constants file to be created\nimport {\n    MinigameData_V1, MinigameIbGib_V1, MinigameIbInfo, MinigameAddlMetadataInfo,\n    DEFAULT_MINIGAME_DATA_V1,\n} from './minigame-types.mjs';\nimport { validateMinigameIsReady_typing } from './typing/typing-helper.mjs';\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\nexport function getMinigameSafeName({ name }: { name: string }): string {\n    const lc = `[${getMinigameSafeName.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n        const safeName = getSaferSubstring({\n            text: name,\n            length: DEFAULT_MINIGAME_SAFE_NAME_LENGTH,\n        });\n        if (!safeName) { throw new Error(`${lc} Could not generate safeName from name: ${name}. (E: genuuid)`); }\n        return safeName;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * Generates the `ib` string for a MinigameIbGib based on its data.\n * The structure is: `${MINIGAME_ATOM} ${safeName} ${addlMetadataText}`\n * where addlMetadataText contains underscore-delimited fields like timestampInTicks.\n *\n * ## notes\n *\n * atow (04/2025), we are \"descending\" (forking) from a source comment ibgib to\n * create the project. As such, we are positioning the project ibgib itself to\n * have a similar structure to a comment ibgib. So the schema for the `ib`\n * purposefully has the safeName in the second position just like a comment\n * ibgib has a saferized version of the comment.data.text in its ib schema.\n *\n * WARNING\n * WARNING\n * ATOW (05/2025) THIS FUNCTION'S DETAILS ARE USED IN MUT8-IBGIB\n * APIFUNCTIONINFO.  IF THIS CHANGES, THEN THAT FUNCTION MUST BE CHANGED TOO.\n * WARNING\n * WARNING\n *\n * @see {@link MinigameIbInfo}\n * @see {@link MinigameAddlMetadataInfo}\n *\n */\nexport function getMinigameIb({\n    data,\n}: {\n    data: MinigameData_V1;\n}): string {\n    const lc = `[${getMinigameIb.name}]`;\n    try {\n        const validationErrors = validateMinigameData_V1({ data }) ?? [];\n        if (validationErrors.length > 0) {\n            throw new Error(`invalid Minigame data. errors: ${validationErrors} (E: genuuid)`);\n        }\n\n        // Get saferized name segment\n        const safeName = getMinigameSafeName({ name: data.name });\n\n        // Prepare additional metadata text (add more fields with underscores here later)\n\n        // timestampInTicks\n        const timestampInfo = getTimestampInfo({ timestamp: data.timestamp });\n        if (!timestampInfo.valid) { throw new Error(`(UNEXPECTED) validated data but invalid data.timestamp? (E: genuuid)`); }\n        const timestampInTicks = Number.parseInt(timestampInfo.ticks);\n\n        // compose addlMetadataText\n        const addlMetadataFields: string[] = [\n            timestampInTicks.toString(),\n            // add more fields here as needed in the future\n        ];\n        addlMetadataFields.push();\n        const addlMetadataText = addlMetadataFields.join('_');\n        if (addlMetadataText.length > DEFAULT_MINIGAME_ADDL_METADATA_LENGTH) {\n            throw new Error(`(UNEXPECTED) addlMetadataText.length > DEFAULT_MINIGAME_ADDL_METADATA_LENGTH (${DEFAULT_MINIGAME_ADDL_METADATA_LENGTH})? (E: genuuid)`);\n        }\n\n        // Construct the final ib string\n        return `${MINIGAME_ATOM} ${safeName} ${addlMetadataText}`;\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    }\n}\n\nexport function validateMinigameIb({\n    ib,\n}: {\n    ib: Ib;\n}): string[] | undefined {\n    const lc = `[${validateMinigameIb.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n\n        // major hack here...I'm tired of doing this plumbing shit.\n\n        try {\n            const _info = parseMinigameIb({ ib });\n        } catch (error) {\n            return [extractErrorMsg(error)];\n        }\n\n        return undefined;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * Parses a project `ib` string into its components.\n *\n * @see {@link getMinigameIb} for expected ib schema\n */\nexport function parseMinigameIb({\n    ib,\n}: {\n    ib: Ib;\n}): MinigameIbInfo {\n    const lc = `[${parseMinigameIb.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... parsing ib: ${ib}`); }\n        if (!ib) { throw new Error(`${lc} ib required (E: genuuid)`); }\n\n        const pieces = ib.split(' ');\n        if (pieces.length !== 3) { throw new Error(`${lc} Invalid project ib format. Expected 3 space-delimited pieces. Got: ${pieces.length}. ib: ${ib} (E: genuuid)`); }\n\n        const [atom, safeName, addlMetadataText] = pieces;\n\n        if (atom !== MINIGAME_ATOM) { throw new Error(`${lc} Invalid atom. Expected '${MINIGAME_ATOM}', got '${atom}'. ib: ${ib} (E: genuuid)`); }\n\n        if (!safeName) { throw new Error(`${lc} safeName segment is empty. ib: ${ib} (E: genuuid)`); }\n\n        if (!addlMetadataText) { throw new Error(`${lc} addlMetadataText segment is empty. ib: ${ib} (E: genuuid)`); }\n\n        // Parse the underscore-delimited addlMetadataText\n        const metadataPieces = addlMetadataText.split('_');\n        if (metadataPieces.length !== 1) { throw new Error(`${lc} Could not parse addlMetadataText. Expected 1 underscore-delimited piece. Got: ${metadataPieces.length}. addlMetadataText: ${addlMetadataText} (E: genuuid)`); }\n\n        const timestampInTicksStr = metadataPieces[0];\n        const timestampInTicks = parseInt(timestampInTicksStr, 10);\n        if (isNaN(timestampInTicks)) { throw new Error(`${lc} Could not parse timestampInTicks from addlMetadataText. isNan.  Expected a decimal number. timestampInTicksStr: ${timestampInTicksStr}. addlMetadataText: ${addlMetadataText} (E: genuuid)`); }\n\n        const addlMetadata: MinigameAddlMetadataInfo = {\n            timestampInTicks,\n            // otherField, // if added\n        };\n\n        const result: MinigameIbInfo = {\n            atom: MINIGAME_ATOM,\n            safeName,\n            addlMetadataText,\n            addlMetadata,\n        };\n\n        if (logalot) { console.log(`${lc} parsed info: ${pretty(result)}`); }\n        return result;\n\n    } catch (error) {\n        console.error(`${lc} ${error.message}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * Validates the MinigameData_V1 structure.\n * Returns array of error messages if invalid, otherwise undefined.\n */\nexport function validateMinigameData_V1({\n    data,\n}: {\n    data: MinigameData_V1 | any;\n}): string[] | undefined {\n    const lc = `[${validateMinigameData_V1.name}]`;\n    const errors: string[] = [];\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n\n        if (!data) {\n            errors.push(\"Data is required.\");\n            return errors; /* <<<< returns early */\n        }\n\n        if (data.name) {\n            if (typeof data.name === 'string') {\n                if (!MINIGAME_NAME_REGEXP.test(data.name)) {\n                    errors.push(`data.name must match regexp: ${MINIGAME_NAME_REGEXP.source}`);\n                }\n            } else {\n                errors.push(\"Name must be a string.\");\n            }\n        } else {\n            errors.push(\"name required\")\n        }\n\n        if (data.description) {\n            if (typeof data.description === 'string') {\n                if (!MINIGAME_DESC_REGEXP.test(data.description)) {\n                    errors.push(`data.description must match regexp: ${MINIGAME_DESC_REGEXP.source}`);\n                }\n            } else {\n                errors.push(\"Description must be a string.\");\n            }\n        } else {\n            errors.push(\"description required\")\n        }\n\n        if (data.text) {\n            if (typeof data.text === 'string') {\n                // any more checks on text?\n            } else {\n                errors.push(\"data.text must be string.\");\n            }\n        } else {\n            // not required\n            // errors.push(`data.text required`);\n        }\n\n        if (data.textTimestamp) {\n            if (typeof data.textTimestamp === 'string') {\n                const resValid = getTimestampInfo({ timestamp: data.textTimestamp });\n                if (!resValid.valid) {\n                    errors.push(`data.textTimestamp (${data.textTimestamp}) is not a valid timestamp: ${resValid.emsg}`);\n                }\n            } else {\n                errors.push(\"data.textTimestamp must be a string.\");\n            }\n        } else {\n            // why would this be falsy?\n            console.warn(`${lc} data.textTimestamp not provided. (W: genuuid)`);\n        }\n\n        if (data.timestamp) {\n            if (typeof data.timestamp === 'string') {\n                const resValid = getTimestampInfo({ timestamp: data.timestamp });\n                if (!resValid.valid) {\n                    errors.push(`data.timestamp (${data.timestamp}) is not a valid timestamp: ${resValid.emsg}`);\n                }\n            } else {\n                errors.push(\"data.timestamp must be a string.\");\n            }\n        } else {\n            // why would this be falsy?\n            console.warn(`${lc} data.timestamp not provided. (W: genuuid)`);\n        }\n\n        // todo: validate other minigame data fields\n\n        return errors.length > 0 ? errors : undefined;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        return [`Unexpected error during validation: ${extractErrorMsg(error)} (E: genuuid)`];\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n\n}\n\n/**\n * Validates a MinigameIbGib_V1 intrinsically, its data, and the consistency\n * between the ib string and the data content.\n * Returns an array of error messages if invalid, otherwise undefined.\n */\nexport async function validateMinigameIbGib_V1({\n    ibGib,\n}: {\n    ibGib: IbGib_V1;\n}): Promise<string[] | undefined> {\n    const lc = `[${validateMinigameIbGib_V1.name}]`;\n    const allErrors: string[] = [];\n    try {\n        if (logalot) { console.log(`${lc} starting...`); }\n        if (!ibGib) {\n            allErrors.push('ibGib is required.');\n            return allErrors;\n        }\n\n        // 1. Basic intrinsic validation (ib, gib, data, rel8ns presence, gib calc)\n        const intrinsicErrors = await validateIbGibIntrinsically({ ibGib }) ?? [];\n        if (intrinsicErrors.length > 0) {\n            return intrinsicErrors; /* <<<< returns early */\n        }\n\n        const dataErrors = validateMinigameData_V1({ data: ibGib.data as MinigameData_V1 }) ?? [];\n        dataErrors.forEach(x => allErrors.push(x));\n\n        const ibErrors = validateMinigameIb({ ib: ibGib.ib }) ?? [];\n        ibErrors.forEach(x => allErrors.push(x));\n\n        // not doing this for now\n        const rel8nsErrors = [];\n        rel8nsErrors.forEach(x => allErrors.push(x));\n\n        return allErrors.length > 0 ? allErrors : undefined;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)} (E: genuuid)`);\n        // Return validation data indicating an unexpected error occurred\n        return [`Unexpected error during validation: ${extractErrorMsg(error)} (E: genuuid)`];\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * Type guard to check if an object conforms to MinigameData_V1 structure.\n */\nexport function isMinigameData_V1(data: any): data is MinigameData_V1 {\n    const lc = `[${isMinigameData_V1.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n        const errors = validateMinigameData_V1({ data }) ?? [];\n        return errors.length === 0;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        return false;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * Type guard to check if an IbGib_V1 is structurally a MinigameIbGib_V1.\n * Verifies the atom in the ib and checks data structure using isMinigameData_V1.\n */\nexport function isMinigameIbGib_V1(ibGib: IbGib_V1): ibGib is MinigameIbGib_V1 {\n    if (!ibGib || !ibGib.ib || !ibGib.data) { return false; }\n    // Check if atom is 'project'\n    if (!ibGib.ib.startsWith(`${MINIGAME_ATOM} `)) { return false; }\n    // Check data structure\n    return isMinigameData_V1(ibGib.data);\n}\n\n/**\n * Creates a new Minigame ibGib.\n */\nexport async function createMinigameIbGib({\n    srcMinigameIbGib,\n    data,\n    saveInSpace,\n    space,\n    registerNewIbGib,\n}: {\n    srcMinigameIbGib?: MinigameIbGib_V1,\n    /**\n     * data for new game.\n     *\n     * if {@link srcMinigameIbGib} is provided, then that ibGib's data will be\n     * OVERRIDDEN with this.\n     *\n     * just pass in the {@link srcMinigameIbGib} if you want to keep it the same\n     */\n    data: MinigameData_V1,\n    /**\n     * If true, saves the newly created project ibgib and all intermediate\n     * dependency ibgibs (dna and others) in the given {@link space}, or default\n     * local space if that is falsy.\n     */\n    saveInSpace?: boolean;\n    /**\n     * If set and {@link saveInSpace} is true, then this will be where all\n     * ibgibs are saved.\n     */\n    space?: IbGibSpaceAny;\n    /**\n     * if true, will call metaspace.registerNewIbGib\n     */\n    registerNewIbGib?: boolean;\n}): Promise<TransformResult<MinigameIbGib_V1>> {\n    const lc = `[${createMinigameIbGib.name}]`;\n    if (logalot) { console.log(`${lc} starting...`); }\n    try {\n        const { name, description, instructions, gameType, gameVariants, gameState, keywords } = data;\n\n        let startingData = { ...DEFAULT_MINIGAME_DATA_V1 };\n        if (srcMinigameIbGib) {\n            startingData = { ...startingData, ...srcMinigameIbGib.data!, };\n        }\n        startingData = { ...startingData, ...data, };\n        const now = new Date();\n        const timestamp = getTimestamp(now);\n        const timestampMs = now.getMilliseconds();\n        startingData.timestamp = timestamp;\n        startingData.timestampMs = timestampMs;\n\n        // build a src that has the data we want, esp the timestamp info that\n        // drives the ib\n        const src = Factory_V1.primitive({ ib: MINIGAME_ATOM });\n        src.data = startingData;\n        // keep gib primitive, we're just setting data because of the limitation\n        // of the fork API atow (06/2025)\n        if (srcMinigameIbGib) {\n            // add a rel8n to the src\n            src.rel8ns = {\n                [MINIGAME_PROTOTYPE_REL8N_NAME]: [getIbGibAddr({ ibGib: srcMinigameIbGib })],\n            }\n        }\n\n        const resNewMinigameFork = await fork({\n            src,\n            destIb: getMinigameIb({ data: startingData }),\n            tjp: { uuid: true, timestamp: false },\n            cloneData: true,\n            cloneRel8ns: !!src.rel8ns,\n            dna: true,\n            nCounter: true,\n            noTimestamp: true, // we provided our own above\n        }) as TransformResult<MinigameIbGib_V1>;\n        const { newIbGib: newMinigameIbGib } = resNewMinigameFork;\n        const newMinigameAddr = getIbGibAddr({ ibGib: newMinigameIbGib });\n\n        if (saveInSpace) {\n            if (!space) {\n                throw new Error(`(UNEXPECTED) saveInSpace true but space falsy? (E: genuuid)`);\n            }\n            await persistTransformResult({ resTransform: resNewMinigameFork, space });\n            if (logalot) { console.log(`${lc} persisted resNewMinigameFork (newMinigameIbGib et al). newMinigameIbGib: ${pretty(newMinigameIbGib)} (I: 9dd3588c16282f84e822ed683e6dc825)`); }\n        }\n\n        if (registerNewIbGib) {\n            if (!space) {\n                throw new Error(`(UNEXPECTED) registerNewIbGib true but space falsy? (E: genuuid)`);\n            }\n            const metaspace = await getGlobalMetaspace_waitIfNeeded();\n            await metaspace.registerNewIbGib({ ibGib: newMinigameIbGib, space });\n            if (logalot) { console.log(`${lc} registered new ibgib (${pretty(newMinigameIbGib)}) (I: a179915f0a7882e9e8b18348234ae825)`); }\n        }\n\n        return resNewMinigameFork;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport async function validateMinigameIsReady({\n    minigameIbGib,\n}: {\n    minigameIbGib: MinigameIbGib_V1,\n}): Promise<string[]> {\n    const lc = `[${validateMinigameIsReady.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 69ba588f3fc8f2a2ec188afc0715a825)`); }\n        if (!minigameIbGib.data) { throw new Error(`(UNEXPECTED) minigameIbGib.data falsy? (E: 83e201eccb0bf926d4697e88a377fe25)`); }\n        switch (minigameIbGib.data.gameType) {\n            case MinigameGameType.typing:\n                return validateMinigameIsReady_typing({\n                    minigameIbGib,\n                    data: minigameIbGib.data,\n                });\n            default:\n                throw new Error(`(UNEXPECTED) unknown Minigame.data.gameType (${minigameIbGib.data.gameType})? (E: f74e4afca2d88cfd142e9789e7342825)`);\n        }\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n", "<div id=\"minigame-component\" class=\"\">\n    <div id=\"minigame-header\" class=\"minigame-header panel-header\">\n        <span id=\"minigame-name\"></span>\n        <span id=\"minigame-description\"></span>\n        <span id=\"minigame-timer\">00:00</span>\n\n        <!-- add button and popover options -->\n        <button id=\"minigame-header-play-btn\" title=\"start playing this game\"><span>\u25B6</span></button>\n        <button id=\"minigame-header-restart-btn\"\n            title=\"restart this game from the beginning\"><span><b>\u21BA</b></span></button>\n        <!-- <button id=\"minigame-header-play-pause-toggle-btn\"><span>\u23EF</span></button> -->\n        <button id=\"minigame-header-pause-btn\" title=\"pause this game temporarily\"><span>\u23F8</span></button>\n        <button id=\"minigame-header-abort-btn\" title=\"stop playing this game\"><span>\u23F9</span></button>\n        <button id=\"minigame-header-next-btn\" title=\"skip to the next GAME\"><span>\u23ED</span></button>\n        <button id=\"minigame-instructions-btn\"\n            title=\"game's name, description and instructions on how to play\">\u24D8</button>\n        <button id=\"maximize-btn\" class=\"\"\n            title=\"maximize this game's view (most browsers also have an F11 command for fullscreen)\"><b>\u26F6</b></button>\n\n        <div id=\"metronome-controls\" class=\"minigame-metronome-controls\">\n            <label for=\"metronome-bpm\">BPM:</label>\n            <input type=\"number\" id=\"metronome-bpm\" name=\"metronome-bpm\" min=\"1\" max=\"400\" value=\"60\">\n            <button id=\"metronome-play-pause-btn\" title=\"play/pause metronome\">\uD83C\uDFB6\u23F3</button>\n        </div>\n\n    </div>\n\n    <div id=\"minigame-content\">\n\n        <div id=\"minigame-pause-screen\">\n            <div id=\"minigame-pause-screen-content\" class=\"minigame-pause-screen-content\">\n                <div id=\"minigame-pause-screen-header\" class=\"minigame-pause-screen-header\">\n                    <h2 id=\"minigame-pause-screen-title\">\u23F8 game paused \u23F8</h2>\n                </div>\n                <div id=\"minigame-pause-screen-body\" class=\"minigame-pause-screen-body\">\n                    <p>The game is currently paused.</p>\n                    <!-- todo: other stats of paused game? -->\n                </div>\n                <div id=\"minigame-pause-screen-footer\" class=\"minigame-pause-screen-footer\">\n                </div>\n            </div>\n        </div>\n\n        <div id=\"minigame-component-div\">\n            loading...\n        </div>\n\n    </div>\n\n    <div id=\"minigame-footer\" class=\"minigame-footer\">\n    </div>\n</div>\n", ":host {\n    /* this is used for styling ibgib components for multi-view coordination, so\n     * that ibgib views that are looking at the same ibgib can be visibly shown\n     * as doing so. */\n    --ibgib-color: #ff00dd;\n    --ibgib-color-translucent: #ff00dd10;\n    --tjp-color: #00ffae;\n    --tjp-color-translucent: #00ffae10;\n    overflow: auto;\n}\n\n/* Basic layout and styling for the minigame component */\n#minigame-component {\n    display: flex;\n    flex-direction: column;\n    align-items: stretch;\n    /* width: 100%; */\n    height: 100%;\n    box-sizing: border-box;\n    /* Use consistent padding */\n    padding: 1%;\n\n    /* ibgib styling */\n    border: var(--tjp-color) 5px solid;\n    box-shadow: 0 0 10px var(--tjp-color);\n    border-radius: 5px;\n\n    /* Optional: If using flexbox to control vertical alignment */\n    /* justify-content: center;  Align content vertically */\n\n\n    #minigame-header {\n        display: flex;\n        flex-direction: row;\n        align-items: stretch;\n        justify-content: flex-start;\n        height: 4%;\n\n        #metronome-controls {\n            height: 100%;\n            display: flex;\n            flex-direction: row;\n            align-items: stretch;\n            justify-content: flex-start;\n\n            #metronome-play-pause-btn {\n                display: flex;\n                flex-direction: row;\n                justify-content: flex-start;\n                align-items: center;\n                text-wrap-mode: nowrap;\n            }\n        }\n\n        /* #minigame-header-tabs {\n            overflow-x: auto;\n            width: 90%;\n            scrollbar-width: thin;\n            scrollbar-gutter: stable;\n            margin-bottom: -1%;\n            font-size: small;\n        } */\n\n        button {\n            width: auto;\n            height: 100%;\n            aspect-ratio: 1/1 !important;\n\n            color: var(--tjp-color-contrast);\n            border-color: var(--tjp-color-contrast);\n            background-color: var(--tjp-color);\n\n            /* hack to raise the text upwards */\n            position: relative;\n\n            span {\n                position: relative;\n                bottom: 3px;\n            }\n        }\n\n        button:hover {\n            border-width: 2px;\n            background-color: var(--button-hover-background-color);\n            color: var(--button-hover-text-color);\n            border-color: var(--button-hover-border-color);\n        }\n\n        button:disabled {\n            color: #958f8f !important;\n            border-color: #958f8f !important;\n            background-color: rgba(128, 128, 128, 0.316) !important;\n            cursor: default !important;\n        }\n\n        /* no change for hover state on disabled buttons, this should match above\n         * disabled style */\n        button:disabled:hover {\n            color: #958f8f !important;\n            border-color: #958f8f !important;\n            background-color: rgba(128, 128, 128, 0.316) !important;\n            cursor: default !important;\n        }\n\n        /* Add back the relative container for the button and popover */\n        .add-button-container,\n        .ellipsis-button-container {\n            background-color: transparent;\n            /* position: relative;\n            display: inline-block; */\n        }\n\n        /* Keep the styles for the popover options */\n        .add-popover-option,\n        .ellipsis-popover-option {\n            padding: 8px 15px;\n            margin-bottom: 2px;\n            cursor: pointer;\n            transition: background-color 0.2s ease;\n            background-color: var(--tab-background-color);\n            color: var(--tab-text-color);\n        }\n\n        /* Keep the styles for the popover options */\n        .add-popover-option:hover,\n        .ellipsis-popover-option:hover {\n            /* color: var(--tjp-color-contrast, #f0f0f0); */\n            color: contrast-color(var(--tjp-color, #f0f0f0));\n            background-color: var(--tjp-color, #f0f0f0);\n        }\n\n        /* Use anchor() for positioning */\n        .add-popover,\n        .ellipsis-popover {\n            /* bottom: anchor(top); */\n            /* Position the bottom of the popover at the top of the anchor */\n            /* left: anchor(left); */\n            /* Align the left of the popover with the left of the anchor */\n            flex-direction: column;\n            margin: 0px;\n            /* padding: 5px 0; */\n            border-radius: var(--border-radius, 4px);\n            background-color: var(--background-color, #fff);\n            border: 1px solid var(--border-color, #ccc);\n            box-shadow: var(--box-shadow, 0 2px 5px rgba(0, 0, 0, 0.2));\n            z-index: 10;\n            /* Ensure it appears above other content */\n        }\n\n        /* #minigame-name {\n            font-weight: bold;\n        }\n\n        #minigame-description {\n            white-space: pre-wrap;\n            font-style: italic;\n        }\n\n        #minigame-description.collapsed {\n            display: none;\n        } */\n    }\n\n    #minigame-content {\n        display: flex;\n        flex-direction: column;\n        height: 91%;\n        /* flex-grow: 1; */\n        overflow: auto;\n\n        /* :only-child {\n            height: 100%;\n            width: 100%;\n            box-sizing: border-box;\n        } */\n\n        #minigame-pause-screen {\n            height: 100%;\n            width: 100%;\n            z-index: 999999;\n        }\n\n        #minigame-component-div {\n            height: 100%;\n            width: 100%;\n            box-sizing: border-box;\n            /* overflow: auto; */\n            display: flex;\n            flex-direction: column;\n            align-items: center;\n            justify-content: center;\n        }\n    }\n\n    #minigame-footer {\n        height: 5%;\n\n    }\n\n}\n\n/* ibgib-raw,\nibgib-text-editor {\n} */\n", "<dialog id=\"typing-fullscreen-dialog\" class=\"fullscreen-dialog\">\n    <!-- language list used by multiple elements -->\n    <datalist id=\"typing-fullscreen-dialog-language-list\">\n        <option value=\"en-GB\" label=\"English (UK)\">\n        <option value=\"en-US\" label=\"English (US)\">\n        <option value=\"fr-FR\" label=\"French (France)\">\n        <option value=\"de-DE\" label=\"German (Germany)\">\n        <option value=\"el-GR\" label=\"Greek (Greece)\">\n        <option value=\"grc\" label=\"Greek (Ancient)\"></option>\n        <option value=\"he-IL\" label=\"Hebrew (Israel)\">\n        <option value=\"hbo\" label=\"Hebrew (Ancient)\">\n        <option value=\"it-IT\" label=\"Italian (Italy)\">\n        <option value=\"pt-BR\" label=\"Portuguese (Brazil)\">\n        <option value=\"pt-PT\" label=\"Portuguese (Portugal)\">\n        <option value=\"ru-RU\" label=\"Russian (Russia)\">\n        <option value=\"es-ES\" label=\"Spanish (Spain)\">\n        <option value=\"es-MX\" label=\"Spanish (Mexico)\">\n        <option value=\"es-CU\" label=\"Spanish (Cuba)\">\n    </datalist>\n    <!-- focus template used in the add stimuli dialog -->\n    <template id=\"focus-template\">\n        <div class=\"focus-template-div\">\n            <div id=\"focus-template-section-focus-text\" class=\"focus-template-section\">\n                <button id=\"focus-template-delete-btn\">\u274C</button>\n                <b>\n                    <i>\n                        <p id=\"focus-template-focus-text\"> <!--focus text will here--> </p>\n                    </i>\n                </b>\n            </div>\n            <!-- parrot (visible by default) -->\n            <div id=\"focus-template-stimuli-details-parrot\" class=\"focus-template-stimuli-details\" style=\"display:flex\">\n                <label for=\"focus-template-stimuli-details-parrot\">Parrot: </label>\n                <!-- <label for=\"focus-template-stimuli-details-parrot-text\">Expected Response: </label> -->\n                <p id=\"focus-template-stimuli-details-parrot-text\">\n                    <!-- focus text will be loaded here -->\n                </p>\n                <button id=\"focus-template-details-parrot-add-btn\" class=\"focus-template-add-btn\">\u2795</button>\n            </div>\n            <!-- fill-in-the-blank (hidden) --> <div\n            id=\"focus-template-stimuli-details-fitb\"\n            class=\"focus-template-stimuli-details\" style=\"display:flex\">\n                <label for=\"focus-template-stimuli-details-fitb\">Fill-in-the-blank: </label>\n                <div class=\"labeled-control\">\n                    <label for=\"focus-template-stimuli-details-fitb-numblanks\">Number of blanks:</label>\n                    <input id=\"focus-template-stimuli-details-fitb-numblanks\" type=\"number\" min=\"0\" max=\"3\" step=\"1\"\n                        value=\"1\" />\n                </div>\n                <p id=\"focus-template-stimuli-details-fitb-blanked-text\">\n                    <!-- focus text will be loaded here -->\n                </p>\n                <p id=\"focus-template-stimuli-details-fitb-expected\">\n                    <!-- blanked out texts will be loaded here -->\n                </p>\n                <button id=\"focus-template-details-fitb-add-btn\" class=\"focus-template-add-btn\">\u2795</button>\n            </div>\n            <!-- translate (hidden) -->\n            <div id=\"focus-template-stimuli-details-translate\" class=\"focus-template-stimuli-details\"\n                style=\"display:text\">\n                <label for=\"focus-template-stimuli-details-translate\">Transation(s):</label>\n                <div class=\"focus-template-stimuli-details-translate-options\">\n                    <a id=\"focus-text-translate-link\" target=\"_blank\" href=\"\"> (G/\u6587)</a>\n                    <button id=\"focus-template-details-translate-regen-btn\">\u267B\uFE0F</button>\n                </div>\n                <div id=\"focus-template-language-directions\">\n                    <div class=\"focus-template-translate-direction-div\">\n                        <textarea id=\"stimulus-gen-translated-focus-text\"></textarea>\n                    </div>\n                    <div class=\"focus-template-translate-direction-div\">\n                        <div class=\"labeled-control\">\n                            <input type=\"checkbox\" id=\"focus-option-target-native\" name=\"target-native\"\n                                value=\"target-native\" checked>\n                            <label id=\"stimulus-gen-target-native\" for=\"focus-option-target-native\">target ->\n                                native</label>\n                        </div>\n                        <!-- <button id=\"focus-template-details-translate-add-btn-target-native\"\n                            class=\"focus-template-add-btn\">\u2795</button> -->\n                    </div>\n                    <div class=\"focus-template-translate-direction-div\">\n                        <div class=\"labeled-control\">\n                            <input type=\"checkbox\" id=\"focus-option-native-target\" name=\"native-target\"\n                                value=\"native-target\" checked>\n                            <label id=\"stimulus-gen-native-target\" for=\"focus-option-native-target\">native -> target\n                            </label>\n                        </div>\n                        <!-- <button id=\"focus-template-details-translate-add-btn-native-target\"\n                            class=\"focus-template-add-btn\">\u2795</button> -->\n                    </div>\n                    <button id=\"focus-template-translate-add-btn\" class=\"focus-template-add-btn\"\n                        title=\"add all transation stimuli\">\u2795</button>\n                </div>\n            </div>\n\n            <!-- <div id=\"focus-template-stimuli-details-define\" class=\"focus-template-stimuli-details\" style=\"display:none\">\n            </div> -->\n            <!-- <div id=\"focus-template-section-btns\" class=\"focus-template-section\">\n            </div> -->\n        </div>\n    </template>\n    <div id=\"typing-fullscreen-dialog-content\" class=\"fullscreen-dialog-content\">\n        <div id=\"typing-fullscreen-dialog-header\" class=\"fullscreen-dialog-header\">\n            <h2 id=\"typing-fullscreen-dialog-title\">Add Stimuli</h2>\n        </div>\n        <!-- Dialog body (for message or prompt) -->\n        <div id=\"typing-fullscreen-dialog-body\" class=\"fullscreen-dialog-body\">\n            <!-- errors (if any) -->\n            <div id=\"typing-fullscreen-dialog-errors\" class=\"error fullscreen-dialog-section\" style=\"display:none;\">\n            </div>\n\n            <!-- src text/comment ibgib -->\n            <div id=\"typing-fullscreen-dialog-src-div\" class=\"fullscreen-dialog-section\">\n                <div id=\"typing-fullscreen-dialog-src-label-div\" class=\"fullscreen-dialog-section-label\">\n                    <label for=\"typing-fullscreen-dialog-src-div\">Source Text:</label>\n                    <button id=\"typing-fullscreen-dialog-src-info-btn\" class=\"round-btn\"\n                        title=\"What is the source text? More info...\">\u24D8</button>\n                </div>\n                <input id=\"typing-fullscreen-dialog-src-addr\" type=\"text\"\n                    placeholder=\"comment SomeAddress^ABC123HASH\" />\n                <textarea id=\"typing-fullscreen-dialog-src-text\"></textarea>\n                <div id=\"typing-fullscreen-dialog-src-text\"></div>\n            </div>\n\n            <!-- language settings -->\n            <div id=\"typing-fullscreen-dialog-language-div\" class=\"fullscreen-dialog-section\">\n                <div id=\"typing-fullscreen-dialog-language-label-div\" class=\"fullscreen-dialog-section-label\">\n                    <input type=\"checkbox\" id=\"typing-fullscreen-dialog-language-options-checkbox\">\n                    <label for=\"typing-fullscreen-dialog-language-options-checkbox\">Auto-Translate:</label>\n                    <button id=\"typing-fullscreen-dialog-language-info-btn\" class=\"round-btn\"\n                        title=\"Language Options? More info...\">\u24D8</button>\n                </div>\n\n                <div id=\"typing-fullscreen-dialog-language-details\">\n                    <div>\n                        <label for=\"typing-fullscreen-dialog-text-language-input\" title=\"SOURCE TEXT language\">\n                            Source:</label>\n                        <input id=\"typing-fullscreen-dialog-text-language-input\"\n                            list=\"typing-fullscreen-dialog-language-list\" value=\"\">\n                    </div>\n                    <div>\n                        <label for=\"typing-fullscreen-dialog-native-language-input\"\n                            title=\"Learner's NATIVE language for these stimuli.\">\n                            Your Native:</label>\n                        <input id=\"typing-fullscreen-dialog-native-language-input\"\n                            list=\"typing-fullscreen-dialog-language-list\" value=\"en-US\">\n                    </div>\n                    <div>\n                        <label for=\"typing-fullscreen-dialog-target-language-input\"\n                            title=\"Learner's TARGET language for these stimuli.\">\n                            Target:</label>\n                        <input id=\"typing-fullscreen-dialog-target-language-input\"\n                            list=\"typing-fullscreen-dialog-language-list\">\n                    </div>\n                    <!--\n                        <div>\n                            <label for=\"typing-fullscreen-dialog-language\" title=\"\">\n                                Target:</label>\n                            <textarea id=\"typing-fullscreen-dialog-language\"></textarea>\n                        </div>\n                    -->\n                </div>\n            </div>\n\n            <!-- focus -->\n            <div id=\"typing-fullscreen-dialog-focus-div\" class=\"fullscreen-dialog-section\">\n                <div id=\"typing-fullscreen-dialog-focus-label-div\" class=\"fullscreen-dialog-section-label\">\n                    <label for=\"typing-fullscreen-dialog-focus-div\">Focuses:</label>\n                    <button id=\"typing-fullscreen-dialog-focuses-info-btn\" class=\"round-btn\"\n                        title=\"What's a focus? More info...\">\u24D8</button>\n                </div>\n\n                <div id=\"typing-fullscreen-dialog-focus-level-div\" class=\"fullscreen-dialog-subsection\">\n                    <label for=\"typing-fullscreen-dialog-focus-level\">Focus Level:</label>\n                    <input id=\"typing-fullscreen-dialog-focus-number\" type=\"number\" min=\"0\" max=\"99\" step=\"1\"\n                        value=\"1\" />\n                    <select id=\"typing-fullscreen-dialog-focus-level\">\n                        <option value=\"character\">Character</option>\n                        <option value=\"word\" selected>Word</option>\n                        <option value=\"sentence\">Sentence</option>\n                        <option value=\"newline\">Line</option>\n                        <option value=\"paragraph\">Paragraph</option>\n                    </select>\n\n                    <div class=\"labeled-control\"\n                        title=\"if checked, focus(es) generated will be in random order. Otherwise, will always work from start to end, based on existing focuses.\">\n                        <input id=\"typing-fullscreen-dialog-focus-randomize\" type=\"checkbox\">\n                        <label for=\"typing-fullscreen-dialog-focus-randomize\">randomize</label>\n                    </div>\n                    <button id=\"typing-fullscreen-dialog-add-focus-btn\" class=\"round-btn\">\u2795</button>\n                </div>\n\n                <ul id=\"typing-fullscreen-dialog-focuses-div\" class=\"stimuli-list\">\n                    <!-- new focus UI controls added here -->\n                </ul>\n            </div>\n\n            <div id=\"typing-fullscreen-dialog-output-div\" class=\"fullscreen-dialog-section\"\n                title=\"These stimuli will be added to the minigame if you click OK.\">\n                <div id=\"typing-fullscreen-dialog-output-label-div\" class=\"fullscreen-dialog-section-label\">\n                    <label for=\"typing-fullscreen-dialog-output-div\">Stimuli To Add:</label>\n                    <button id=\"typing-fullscreen-dialog-output-info-btn\" class=\"round-btn\"\n                        title=\"What are these stimuli? More info...\">\u24D8</button>\n                </div>\n\n                <!-- <button id=\"typing-fullscreen-dialog-add-stimuli-btn\">\u2795 (Generate Stimuli)</button> -->\n\n                <ul id=\"typing-fullscreen-dialog-prompt-new-stimuli-div\" class=\"stimuli-list\">\n                    <!-- new stimuli UI controls added here, this will replace the prompt input textarea -->\n                </ul>\n                <!-- <textarea id=\"typing-fullscreen-dialog-prompt-input\"></textarea> -->\n            </div>\n\n        </div>\n        <div id=\"typing-fullscreen-dialog-footer\" class=\"fullscreen-dialog-footer\">\n            <button id=\"typing-fullscreen-dialog-ok-button\" class=\"dialog-button\">OK</button>\n            <button id=\"typing-fullscreen-dialog-cancel-button\" class=\"dialog-button\">Cancel</button>\n        </div>\n    </div>\n</dialog>\n<div id=\"typing-component\" class=\"\">\n    <!-- have these both as panel-header just as a kluge to get the tabs to look\n    decent without bigger rewrite/investigation -->\n    <div id=\"typing-header\" class=\"typing-header panel-header\">\n        <h2 id=\"typing-name\">raw name loading...</h2>\n        <p id=\"typing-description\">raw description loading...</p>\n        <div id=\"typing-command-bar\"></div>\n        <!-- <div id=\"typing-header-tabs\" class=\"typing-header-tabs panel-header\"> -->\n        <!-- looks something like this atow when dynamically added -->\n        <!--\n            <span id=\"typing-tab-button-{addr}\" class=\"panel-tab-button active\" title=\"untitled\">\n                untitled\n            </span>\n            -->\n        <!-- </div> -->\n        <!-- <button id=\"typing-header-add-btn\" class=\"tab-btn\">+</button> -->\n    </div>\n\n    <div id=\"typing-content\">\n        <template id=\"stimulus-entry-template\">\n            <div class=\"stimulus-entry-template-div\">\n\n                <div class=\"stimulus-entry-template-section stimulus-entry-main-section\">\n                    <button id=\"stimulus-entry-delete-btn\" class=\"round-btn\">\u274C</button>\n                    <button id=\"stimulus-entry-edit-btn\" class=\"round-btn\">\u270E</button>\n                    <p id=\"stimulus-entry-text\"></p>\n                    <button id=\"stimulus-entry-expand-btn\" class=\"round-btn\">\u25BC</button>\n                </div>\n                <div class=\"stimulus-entry-template-section stimulus-entry-details-section\"\n                    style=\"max-height:0px;display:none\">\n                    <div class=\"labeled-control\">\n                        <label for=\"stimulus-entry-variant\">Variant:</label>\n                        <p class=\"stimulus-entry-variant\"></p>\n                    </div>\n                    <div class=\"labeled-control\">\n                        <label for=\"stimulus-entry-focus-text\">Focus:</label>\n                        <p class=\"stimulus-entry-focus-text\"></p>\n                    </div>\n                    <div class=\"labeled-control\">\n                        <label for=\"stimulus-entry-language\">Language:</label>\n                        <p class=\"stimulus-entry-language\"></p>\n                    </div>\n                    <div class=\"labeled-control\">\n                        <label for=\"stimulus-entry-expected-response\">Expect (<span\n                                class=\"stimulus-entry-expected-response-type-p\"></span>):</label>\n                        <!-- <p class=\"stimulus-entry-expected-response-type-p\"></p> -->\n                        <!-- select is only when edit -->\n                        <select class=\"stimulus-entry-expected-response-type-select\" style=\"display:none\">\n                            <option value=\"exactly\">Exactly</option>\n                            <option value=\"equivalent\">Equivalent</option>\n                            <option value=\"fill-in-the-blank\">Blank(s)</option>\n                            <option value=\"answer\">Answer</option>\n                        </select>\n                        <p class=\"stimulus-entry-expected-response-text\"></p>\n                    </div>\n                </div>\n            </div>\n        </template>\n        <template id=\"playing-stimulus-template-parrot\">\n            <div class=\"playing-stimulus-template-root\">\n                <p>\uD83E\uDD9C</p>\n                <div class=\"playing-stimulus-text\"></div>\n                <div class=\"playing-stimulus-diff\"></div>\n            </div>\n        </template>\n        <template id=\"playing-stimulus-template-fitb\">\n            <div class=\"playing-stimulus-template-root\">\n                <p>\uFE4D</p>\n                <div class=\"playing-stimulus-text\"></div>\n                <div class=\"playing-stimulus-diff\"></div>\n            </div>\n        </template>\n        <template id=\"playing-stimulus-template-antiphony\">\n            <div class=\"playing-stimulus-template-root\">\n                <p>\uD83D\uDE74</p>\n                <div class=\"playing-stimulus-text\"></div>\n                <div class=\"playing-stimulus-diff\"></div>\n            </div>\n        </template>\n        <template id=\"playing-stimulus-template-translate\">\n            <div class=\"playing-stimulus-template-root\">\n                <p>\u6587</p>\n                <div class=\"playing-stimulus-text\"></div>\n                <div class=\"playing-stimulus-diff\"></div>\n            </div>\n        </template>\n\n        <div id=\"typing-screen-init\" class=\"typing-screen\">\n            <h1>\u2699\uFE0F Game Setup</h1>\n            <p>playable: <i><button id=\"init-playable\"></button></i></p>\n            <p>game type: <i><span id=\"init-game-type\"></span></i></p>\n            <figure>\n                <figcaption>\n                    <h2>All Stimuli<a id=\"init-translate-link\" target=\"_blank\" href=\"\"> (G/\u6587)</a></h2>\n                </figcaption>\n\n                <ul id=\"init-all-stimuli\" class=\"stimuli-list\"></ul>\n                <!-- second ul for add btn just a simple hack for positioning -->\n                <ul class=\"stimuli-list\">\n                    <li><button id=\"add-stimulus-btn\"><span class=\"green\">\u2795</span></button></li>\n                </ul>\n\n            </figure>\n        </div>\n\n        <div id=\"typing-screen-ready\" class=\"typing-screen\">\n            <h1>Ready!</h1>\n            <p id=\"ready-countdown\"></p>\n        </div>\n\n        <div id=\"typing-screen-playing\" class=\"typing-screen\">\n            <div id=\"typing-screen-playing-header\" class=\"labeled-control\">\n                <label for=\"typing-stimulus-feedback-debounce-ms\">Feedback Delay (ms):</label>\n                <input id=\"typing-stimulus-feedback-debounce-ms\" type=\"number\" min=\"0\" max=\"999999\" step=\"100\"\n                    value=\"0\" />\n            </div>\n            <div id=\"typing-stimulus\">\n            </div>\n        </div>\n\n        <div id=\"typing-screen-aborted\" class=\"typing-screen\">\n            <p>game aborted</p>\n            <p><i>We'll just pretend that never happened</i></p>\n            <p>Hit the restart button to start over.</p>\n        </div>\n\n        <div id=\"typing-screen-complete\" class=\"typing-screen\">\n            <p>game complete</p>\n            <p><i>WTG! Stats should go here</i></p>\n            <p>Hit the restart button to play again.</p>\n            <div id=\"summary-stats\"></div>\n        </div>\n\n    </div>\n\n    <div id=\"typing-footer\" class=\"typing-footer\">\n        <textarea id=\"typing-input\" class=\"\" placeholder=\"CTRL+Enter to send\"></textarea>\n        <button id=\"typing-input-send-btn\" class=\"send-btn\"><b>\u276F</b></button>\n    </div>\n</div>\n", ":host {\n    /* this is used for styling ibgib components for multi-view coordination, so\n     * that ibgib views that are looking at the same ibgib can be visibly shown\n     * as doing so. */\n    --ibgib-color: #ff00dd;\n    --ibgib-color-translucent: #ff00dd10;\n    --tjp-color: #00ffae;\n    --tjp-color-translucent: #00ffae10;\n    width: 100%;\n    height: 100%;\n}\n\n.round-btn {\n    border-radius: 50%;\n    width: 10px;\n    height: auto;\n    border-style: solid;\n}\n\n.stimuli-list {\n    display: flex;\n    flex-direction: column;\n    row-gap: 5px;\n\n    list-style-type: none;\n\n    li {\n        display: flex;\n        flex-direction: row;\n        justify-content: flex-start;\n        align-items: center;\n        column-gap: 5px;\n\n        border: 1px gold dotted;\n        padding: 2px;\n        border-radius: 5px;\n\n        button {\n            width: 25px;\n            border-radius: 50%;\n            border-width: 2px;\n            border-style: solid;\n        }\n\n        button:hover {\n            border-width: 2px;\n            background-color: var(--button-hover-background-color);\n            color: var(--button-hover-text-color);\n            border-color: var(--button-hover-border-color);\n        }\n\n        .stimulus-entry-template-div {\n            display: flex;\n            flex-direction: column;\n            row-gap: 5px;\n            width: 100%;\n\n            .stimulus-entry-template-section {\n                display: flex;\n                flex-direction: column;\n                width: 100%;\n            }\n\n            .stimulus-entry-main-section {\n                flex-direction: row;\n                justify-content: flex-start;\n                align-items: center;\n                column-gap: 5px;\n            }\n\n            .stimulus-entry-details-section {\n\n                .labeled-control {\n                    gap: 5px;\n\n                    label {\n                        width: 25%;\n                        flex-grow: 0;\n                    }\n                }\n\n                transition: max-height 1000ms ease-in-out;\n            }\n        }\n    }\n}\n\n#typing-fullscreen-dialog {\n\n    .focus-template-div {\n        display: flex;\n        flex-direction: column;\n        row-gap: 5px;\n        width: 100%;\n        border-width: var(--border-width-base);\n        border-width: 3px;\n        border-color: var(--border-color-base);\n        border-color: red;\n        border-style: var(--border-style-base);\n        box-sizing: border-box;\n\n        .focus-template-section {\n            display: flex;\n            flex-direction: column;\n            row-gap: 1px;\n            width: 100%;\n            border-width: var(--border-width-base);\n            border-width: 1px;\n            border-color: var(--border-color-base);\n            border-color: pink;\n            border-style: dotted;\n            box-sizing: border-box;\n            padding: 2px;\n        }\n\n        #focus-template-section-btns {\n            display: flex;\n            flex-direction: row;\n            justify-content: flex-start;\n            align-items: center;\n            column-gap: 3px;\n            flex-wrap: wrap;\n        }\n\n        #focus-template-section-focus-text {\n            display: flex;\n            flex-direction: row;\n            justify-content: flex-start;\n            align-items: center;\n            column-gap: 3px;\n            flex-wrap: wrap;\n\n            #focus-template-delete-btn {\n                margin-right: 5px;\n            }\n        }\n\n        #focus-template-language-directions {\n            display: flex;\n            flex-direction: row;\n            justify-content: flex-start;\n            align-items: center;\n            column-gap: 5px;\n            flex-wrap: wrap;\n\n            /* <div class=\"focus-template-translate-direction-div\">\n                        <div class=\"labeled-control\">\n                            <input type=\"checkbox\" id=\"focus-option-native-target\" name=\"native-target\"\n                                value=\"native-target\" checked>\n                            <label for=\"focus-option-native-target\">native -> target</label>\n                        </div>\n                        <textarea id=\"stimulus-gen-native-target\"></textarea>\n                    </div> */\n            .focus-template-translate-direction-div {\n                display: flex;\n                flex-direction: column;\n                row-gap: 2px;\n                width: 100%;\n\n                /* show a line between each entry */\n                border-color: gold;\n                border-width: 0px 0px 3px 0px;\n                border-style: solid;\n\n                :last-child {\n                    border-width: 0px;\n                }\n\n                textarea {\n                    height: auto;\n                    max-height: calc(2 * 1.5em + var(--input-padding) * 2 + 2px);\n                    overflow-y: auto;\n                    /* no idea why important is needed. nothing else overrides this. */\n                    border: var(--input-border-color) 1px solid !important;\n                    margin-bottom: 2px;\n                    box-sizing: border-box;\n                }\n\n            }\n        }\n\n        .focus-template-stimuli-details {\n            display: flex;\n            flex-direction: column;\n            border: var(--input-border-color) 1px solid !important;\n            border-radius: 5px;\n            padding: 1px 1px 1px 4px;\n            margin: 2px;\n        }\n\n        #focus-template-stimuli-details-fitb {\n            #focus-template-stimuli-details-parrot-text {\n                margin-left: 5px;\n            }\n        }\n\n        .focus-template-stimuli-details-translate-options {\n            display: flex;\n            flex-direction: row;\n            gap: 5px;\n        }\n\n    }\n\n    #typing-fullscreen-dialog-focuses-div {\n        margin: 0px;\n        padding-left: 5px;\n    }\n\n    #typing-fullscreen-dialog-body {\n        width: 100%;\n        height: 100%;\n\n        .fullscreen-dialog-section {\n            width: 100%;\n            display: flex;\n            flex-direction: column;\n            align-items: stretch;\n            gap: 5px;\n            border-width: var(--border-width-base);\n            border-width: 3px;\n            border-color: var(--border-color-base);\n            border-color: red;\n            border-style: var(--border-style-base);\n            box-sizing: border-box;\n            padding: 5px;\n        }\n\n        .fullscreen-dialog-subsection {\n            width: 100%;\n            display: flex;\n            flex-direction: row;\n            justify-content: flex-start;\n            align-items: center;\n            gap: 5px;\n            box-sizing: border-box;\n            padding: 5px;\n        }\n\n        .fullscreen-dialog-section-label {\n            width: 100%;\n            display: flex;\n            flex-direction: row;\n            justify-content: flex-start;\n            align-items: center;\n            gap: 5px;\n\n            label {\n                flex: 1;\n            }\n\n        }\n\n        #typing-fullscreen-dialog-language-div {\n            flex-direction: column;\n            align-items: stretch;\n\n            label {\n                width: 25%;\n            }\n\n            #typing-fullscreen-dialog-language-details {\n                display: flex;\n                flex-direction: row;\n                align-items: flex-start;\n                flex-wrap: wrap;\n                gap: 5px;\n            }\n\n        }\n\n        /* #typing-fullscreen-dialog-prompt-new-stimuli-div {\n\n            li {\n                display: flex;\n                flex-direction: row;\n                justify-content: flex-start;\n                align-items: center;\n\n                list-style-type: none;\n            }\n        } */\n\n        textarea {\n            /* width should be controlled by parent flex stretch */\n            /* width: 90%; */\n            height: 15dvh;\n            flex-grow: 1;\n        }\n\n    }\n\n}\n\n\n/* Basic layout and styling for the typing component */\n#typing-component {\n    display: flex;\n    flex-direction: column;\n    align-items: stretch;\n    width: 100%;\n    height: 100%;\n    overflow: auto;\n    box-sizing: border-box;\n    /* Use consistent padding */\n    padding: 1%;\n\n    /* ibgib styling */\n    /* border: var(--tjp-color) 5px solid; */\n    border: var(--border-color-base) var(--border-width-base) var(--border-style-base);\n    /* box-shadow: 0 0 10px var(--tjp-color); */\n    border-radius: 5px;\n\n    /* Optional: If using flexbox to control vertical alignment */\n    /* justify-content: center;  Align content vertically */\n\n    #typing-header {\n        /* display: flex; */\n        /* flex-direction: column; */\n        /* feeling my way here...if this works, just delete other styles for the\n         * header or comment them out whatever. */\n        display: none;\n\n        #typing-name {\n            font-weight: bold;\n            /* font-size: larger; */\n            /* Use variables for spacing? */\n            /* margin-bottom: 0.5em; */\n        }\n\n        #typing-description {\n            /* Respect newlines */\n            white-space: pre-wrap;\n            font-style: italic;\n        }\n\n        #typing-description.collapsed {\n            display: none;\n        }\n    }\n\n    #typing-content {\n        width: 100%;\n        height: 50%;\n        box-sizing: border-box;\n        padding: 0px;\n        margin: 0px;\n\n        .typing-screen {\n            width: 100%;\n            height: 100%;\n            box-sizing: border-box;\n\n            /* default to flex column */\n            display: flex;\n            flex-direction: column;\n            align-items: center;\n            justify-content: flex-start;\n        }\n\n        #typing-screen-init {\n\n            figure {\n                display: table;\n                width: 100%;\n\n                figcaption {\n                    display: table-caption;\n                    caption-side: top;\n                    text-align: center;\n\n                    a {\n                        font-size: small;\n                    }\n                }\n            }\n\n        }\n\n        #typing-screen-playing {\n            width: 100%;\n            height: 100%;\n\n            display: flex;\n            flex-direction: column;\n\n            #typing-screen-playing-header {\n                height: 5%;\n            }\n\n            #typing-stimulus {\n                display: flex;\n                flex-direction: column;\n\n                width: 100%;\n                height: 95%;\n                box-sizing: border-box;\n                /* not technically input, but we want it to match. */\n                padding: var(--input-padding);\n\n                font-family: var(--font-family-base);\n                font-size: var(--font-size-base);\n\n                border-color: var(--border-color-base);\n                border-width: var(--border-width-base);\n                border-style: var(--border-style-base);\n                /* dev */\n                /* border-color: pink; */\n                /* dev */\n                /* border-width: 10px; */\n\n                .playing-stimulus-template-root {\n                    width: 100%;\n                    height: 100%;\n                    display: flex;\n                    flex-direction: column;\n\n                    .playing-stimulus-text,\n                    .playing-stimulus-diff {\n                        width: 100%;\n                        height: 45%;\n                        overflow-y: auto;\n                    }\n\n                }\n\n                /* .playing-stimulus-template-root:first-child {\n                    width: 100%;\n                    height: 10%;\n                } */\n\n                p {\n                    padding: 0px 0px 2px 0px;\n                }\n            }\n\n        }\n\n        /* #typing-screen-aborted {} */\n\n        /* #typing-screen-complete {} */\n\n\n    }\n\n    #typing-footer {\n\n        display: flex;\n        flex-direction: row;\n        align-items: stretch;\n        gap: 2px;\n        justify-content: stretch;\n        width: 100%;\n        height: 50%;\n        box-sizing: border-box;\n        overflow-y: hidden;\n        padding: 1%;\n\n        /* dev */\n        /* border-color: purple; */\n        /* dev */\n        /* border-width: 10px; */\n\n        textarea {\n\n            /* height: 100%; */\n            height: auto;\n            width: 100px;\n            background-color: var(--input-background-color);\n            /* border: var(--input-border-width) var(--input-border-style) var(--input-border-color); */\n            border-radius: var(--input-border-radius);\n            padding: var(--input-padding);\n            flex-grow: 1;\n\n            font-family: var(--font-family-base);\n            font-size: var(--font-size-base);\n\n            /* ibgib styling */\n            border: var(--tjp-color) 1px solid;\n            box-shadow: 0 0 3px var(--tjp-color);\n            /* border-radius: 5px; */\n\n            color: var(--input-text-color);\n            background-color: var(--input-background-color);\n            border-color: var(--input-border-color);\n            border-width: var(--input-border-width);\n            border-style: var(--input-border-style);\n            border-radius: var(--input-border-radius);\n            /* dev */\n            /* border-color: blue; */\n            /* dev */\n            /* border-width: 15px; */\n        }\n\n        textarea:focus {\n            outline: none !important;\n            border-radius: calc(var(--input-border-radius) + 1px);\n            /* box-shadow: 0 0 10px var(--highlight-box-shadow-color); */\n            box-shadow: 0 0 10px var(--highlight-border-color);\n            /* background-color: var(--background-color-base); */\n        }\n\n    }\n\n}\n", "import { clone, extractErrorMsg, pretty } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { validateIbGibAddr } from \"@ibgib/ts-gib/dist/V1/validate-helper.mjs\";\nimport { getIbAndGib, } from \"@ibgib/ts-gib/dist/helper.mjs\";\nimport { IbGibAddr, } from \"@ibgib/ts-gib/dist/types.mjs\";\nimport { isPrimitive } from \"@ibgib/ts-gib/dist/V1/transforms/transform-helper.mjs\";\nimport { mut8Timeline } from \"@ibgib/core-gib/dist/timeline/timeline-api.mjs\";\nimport { getGlobalMetaspace_waitIfNeeded, } from \"@ibgib/web-gib/dist/helpers.mjs\";\nimport { APIFunctionInfo } from \"@ibgib/web-gib/dist/api/api-types.mjs\";\nimport { COMMAND_BASE_SCHEMA_PROPERTIES } from \"@ibgib/web-gib/dist/api/commands/command-constants.mjs\";\nimport { getCommandService } from \"@ibgib/web-gib/dist/api/commands/command-service-v1.mjs\";\nimport { CommandDataBase } from \"@ibgib/web-gib/dist/api/commands/command-types.mjs\";\nimport { FUNCTION_CALL_EXAMPLES_HEADER } from \"@ibgib/web-gib/dist/api/api-constants.mjs\";\n\nimport { GLOBAL_LOG_A_LOT } from \"../../../constants.mjs\";\nimport { getIbGibGlobalThis_BlankGib } from \"../../../helpers.web.mjs\";\nimport {\n    GEMINI_SCHEMA_MINIGAME_MINIGAME_ADDR,\n} from \"../../../common/minigame/minigame-constants.mjs\";\nimport { MinigameGamePhase, MinigameIbGib_V1 } from \"../../../common/minigame/minigame-types.mjs\";\nimport { validateMinigameIsReady } from \"../../../common/minigame/minigame-helper.mjs\";\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\n// #region constants\nconst FUNCTION_NAME = 'minigameBuilderValidateAndReady';\n\n/**\n * chat category here as this is a chat-related command.\n */\nconst CMD_CATEGORY = 'minigame';\n/**\n * helloWorld here is the specific command modifier which narrows down to a command\n * instance, similar to a fully curried function.\n */\nconst CMD_MODIFIERS: string[] = [FUNCTION_NAME];\nconst EXAMPLE_INPUT_MINIGAMEBUILDER_VALIDATE_AND_READY: Partial<MinigameBuilderValidateAndReadyOpts> = {\n    agentId: 'SomeAgentIdHash',\n    notesToSelf: `Example of a ${FUNCTION_NAME} function call. Note repromptWithResult is false because this function will activate the minigame in the center panel in the ready-to-play state.`,\n    repromptWithResult: false,\n    minigameAddr: `minigame TestTypingGame 1750086232000^6E0E9E4934F9742A779D47150B0AB47D4C9F3847627F0E1EA37EC8E20B1BE8FF`,\n};\n\nconst EXAMPLES = [\n    FUNCTION_CALL_EXAMPLES_HEADER,\n    pretty(EXAMPLE_INPUT_MINIGAMEBUILDER_VALIDATE_AND_READY),\n].join('\\n');\nconst FUNCTION_DESCRIPTION = `Validates that a minigame ibgib has enough data to begin. It may already be in progress or not, that doesn't matter. (For example, a typing game requires at least one stimulus.) Once validated, this will set the minigameIbGib.data.playable to true if not already set. If invalid, will return reasons why the minigame is not ready. NOTE: This is the last function REQUIRED for the minigame builder functions. You can still make calls later to augment the minigame, e.g., adding stimuli, but a minigame won't be able to be played until this is called successfully at least once after adding stimuli or any other operations on the minigame ibgib.\\n\\n${EXAMPLES}`;\n// #endregion constants\n\n\n/**\n * @interface MinigameBuilderValidateAndReadyOpts - Options for the\n * minigameBuilderValidateAndReady command.\n * @extends CommandDataBase\n */\nexport interface MinigameBuilderValidateAndReadyOpts extends CommandDataBase<typeof CMD_CATEGORY, typeof CMD_MODIFIERS> {\n    /**\n     * agent's id doing the function\n     */\n    agentId?: string;\n    /**\n     * address of the minigame that we're adding stimuli to\n     */\n    minigameAddr: IbGibAddr;\n}\nexport interface MinigameBuilderValidateAndReadyResult {\n    minigameIbGib: MinigameIbGib_V1;\n\n    ready: boolean;\n    errors?: string[];\n}\n\n/**\n * @interface MinigameBuilderValidateAndReadyCommandData - Command data for the\n * minigameBuilderValidateAndReady command.\n * @extends CommandDataBase\n */\nexport interface MinigameBuilderValidateAndReadyCommandData extends CommandDataBase<typeof CMD_CATEGORY, typeof CMD_MODIFIERS> {\n    /**\n     * agent's id doing the function\n     */\n    agentId?: string;\n    /**\n     * address of the minigame that we're adding stimuli to\n     */\n    minigameAddr: IbGibAddr;\n}\n\n/**\n * Wrapper function to enqueue the minigameBuilderValidateAndReady command.\n * @param {MinigameBuilderValidateAndReadyOpts} opts - Options for telling the user something.\n * @returns {Promise<MinigameIbGib_V1>} A promise that resolves when the command is enqueued.\n */\nfunction minigameBuilderValidateAndReadyViaCmd(opts: MinigameBuilderValidateAndReadyOpts): Promise<MinigameBuilderValidateAndReadyResult> {\n    const lc = `[${minigameBuilderValidateAndReadyViaCmd.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n        if (logalot) { console.log(`${lc} minigameBuilderValidateAndReadyViaCmd raw incoming opts: ${pretty(opts)} (I: genuuid)`); }\n\n        const commandService = getCommandService();\n        const command: MinigameBuilderValidateAndReadyCommandData = {\n            ...opts,\n            cmd: CMD_CATEGORY,\n            cmdModifiers: CMD_MODIFIERS,\n        };\n        if (logalot) { console.log(`${lc} minigameBuilderValidateAndReadyViaCmd command: ${pretty(command)} (I: genuuid)`); }\n        return new Promise<MinigameBuilderValidateAndReadyResult>((resolve, reject) => {\n            commandService.enqueueCommand({ command, resolve, reject });\n        });\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * Implementation function for the minigameBuilderValidateAndReady command.\n *\n * @param {MinigameBuilderValidateAndReadyOpts} opts\n * @returns {Promise<MinigameBuilderValidateAndReadyResult>} A promise that resolves when the command is executed (immediately).\n */\nasync function minigameBuilderValidateAndReadyImpl(opts: MinigameBuilderValidateAndReadyOpts): Promise<MinigameBuilderValidateAndReadyResult> {\n    const lc = `[${minigameBuilderValidateAndReadyImpl.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n\n        console.log(`${lc} opts: ${pretty(opts)}`);\n\n        const metaspace = await getGlobalMetaspace_waitIfNeeded();\n        const minigameAddr = opts.minigameAddr;\n        if (!minigameAddr) { throw new Error(`minigameAddr is falsy (was not provided by model if this was a function call request). This should be required in the gemini schema. (E: genuuid)`); }\n\n        const addrErrors = validateIbGibAddr({ addr: minigameAddr }) ?? [];\n        if (addrErrors.length > 0) {\n            throw new Error(`${lc} agent has provided a non-ibgib addr for minigameAddr: ${minigameAddr}. addrErrors: ${addrErrors}. opts: ${pretty(opts)} (E: genuuid)`)\n        }\n        if (isPrimitive({ gib: getIbAndGib({ ibGibAddr: minigameAddr }).gib })) {\n            throw new Error(`agent has tried calling this with a primitive context address. opts: ${pretty(opts)} (E: genuuid)`);\n        }\n        const space = await metaspace.getLocalUserSpace({ lock: false });\n        if (!space) { throw new Error(`(UNEXPECTED) couldn't get default local user space? (E: genuuid)`); }\n\n        const latestAddr = await metaspace.getLatestAddr({\n            addr: minigameAddr,\n            space,\n        }) ?? minigameAddr;\n\n        const resGet = await metaspace.get({\n            addrs: [latestAddr],\n            space,\n        });\n        if (resGet.errorMsg) { throw new Error(`Could not retrieve ibGib: ${resGet.errorMsg} (E: genuuid)`) }\n        if (!resGet.ibGibs || resGet.ibGibs.length === 0) {\n            throw new Error(`Could not retrieve minigameIbGib. errorMsg: ${resGet.errorMsg ?? '[unknown error? (E: genuuid)]'}(E: genuuid)`);\n        }\n        let minigameIbGib = resGet.ibGibs.at(0) as MinigameIbGib_V1;\n\n        const isReadyErrors = await validateMinigameIsReady({ minigameIbGib });\n\n        if (isReadyErrors.length > 0) {\n            // go ahead and return the errors\n            return {\n                minigameIbGib,\n                ready: false,\n                errors: isReadyErrors,\n            }; /* <<<< returns early */\n        }\n\n        // ready to go, so start the game and return\n        if (!minigameIbGib.data) { throw new Error(`(UNEXPECTED) minigameIbGib.data falsy? (E: 9d5f3ae0d3c897ddda6a2ff8d07ca825)`); }\n        if (!minigameIbGib.data.playable || minigameIbGib.data.gamePhase !== MinigameGamePhase.ready) {\n            minigameIbGib = await mut8Timeline({\n                timeline: minigameIbGib,\n                metaspace,\n                space,\n                mut8Opts: {\n                    dataToAddOrPatch: {\n                        gamePhase: MinigameGamePhase.ready,\n                        playable: true\n                    },\n                },\n            })\n        }\n\n        // open the minigame in the currently active project. there is an edge\n        // case here that maybe the currently active project is not the one that\n        // \"contains\" the minigame, but wth? very edgy, probably an error\n        const ibGibGlobalThis = getIbGibGlobalThis_BlankGib();\n        if (!ibGibGlobalThis.projectsComponent) {\n            throw new Error(`${lc} (UNEXPECTED) ibGibGlobalThis.projectsComponent falsy? (E: 67bde84c865844e922f008d36dc2b925)`)\n        }\n        if (!ibGibGlobalThis.projectsComponent.activeProjectTabInfo) { throw new Error(`(UNEXPECTED) ibGibGlobalThis.projectsComponent.activeProjectTabInfo falsy? (E: bbccb81938887dc5a8a309b59c841825)`); }\n        if (!ibGibGlobalThis.projectsComponent.activeProjectTabInfo.component) { throw new Error(`(UNEXPECTED) ibGibGlobalThis.projectsComponent.activeProjectTabInfo.component falsy? (E: f485687d525ebecc28b749f3fd283825)`); }\n        ibGibGlobalThis.projectsComponent.activeProjectTabInfo.component.activateIbGib({ ibGib: minigameIbGib }); // spin off\n\n        // wtg\n        return { minigameIbGib, ready: true, }\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * API function info for the minigameBuilderValidateAndReady command.\n */\nexport const minigameBuilderValidateAndReadyFunctionInfo: APIFunctionInfo<typeof minigameBuilderValidateAndReadyViaCmd> = {\n    nameOrId: FUNCTION_NAME,\n    fnViaCmd: minigameBuilderValidateAndReadyViaCmd,\n    functionImpl: minigameBuilderValidateAndReadyImpl,\n    cmd: CMD_CATEGORY,\n    cmdModifiers: CMD_MODIFIERS,\n    schema: {\n        name: FUNCTION_NAME,\n        description: FUNCTION_DESCRIPTION,\n        parameters: {\n            type: 'object',\n            properties: {\n                ...COMMAND_BASE_SCHEMA_PROPERTIES,\n                minigameAddr: GEMINI_SCHEMA_MINIGAME_MINIGAME_ADDR,\n            },\n            required: [\n                'agentId', // base. not really required by function, but the schema requires it\n                'minigameAddr',\n            ],\n        },\n    },\n};\n", "import { clone, extractErrorMsg, getUUID, pretty } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { validateIbGibAddr } from \"@ibgib/ts-gib/dist/V1/validate-helper.mjs\";\nimport { getIbAndGib, } from \"@ibgib/ts-gib/dist/helper.mjs\";\nimport { IbGibAddr, } from \"@ibgib/ts-gib/dist/types.mjs\";\nimport { isPrimitive } from \"@ibgib/ts-gib/dist/V1/transforms/transform-helper.mjs\";\nimport { getGlobalMetaspace_waitIfNeeded } from \"@ibgib/web-gib/dist/helpers.mjs\";\nimport { APIFunctionInfo } from \"@ibgib/web-gib/dist/api/api-types.mjs\";\nimport { COMMAND_BASE_SCHEMA_PROPERTIES } from \"@ibgib/web-gib/dist/api/commands/command-constants.mjs\";\nimport { getCommandService } from \"@ibgib/web-gib/dist/api/commands/command-service-v1.mjs\";\nimport { CommandDataBase } from \"@ibgib/web-gib/dist/api/commands/command-types.mjs\";\nimport { FUNCTION_CALL_EXAMPLES_HEADER } from \"@ibgib/web-gib/dist/api/api-constants.mjs\";\n\nimport { GLOBAL_LOG_A_LOT } from \"../../../constants.mjs\";\nimport {\n    GEMINI_SCHEMA_MINIGAME_CONTEXT_ADDR,\n} from \"../../../common/minigame/minigame-constants.mjs\";\nimport { Minigame_TypingStimulus, StimulusEditInfo } from \"../../../common/minigame/typing/typing-types.mjs\";\nimport { editStimuli_typing, getNewTypingEntryId } from \"../../../common/minigame/typing/typing-helper.mjs\";\nimport { EXPECTED_RESPONSE_TYPE_VALID_VALUES, ExpectedResponseType } from \"../../../common/minigame/typing/typing-constants.mjs\";\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\n\n// #region constants\nconst FUNCTION_NAME = 'minigameBuilderEditStimuli';\n\n/**\n * chat category here as this is a chat-related command.\n */\nconst CMD_CATEGORY = 'minigame';\n/**\n * helloWorld here is the specific command modifier which narrows down to a command\n * instance, similar to a fully curried function.\n */\nconst CMD_MODIFIERS: string[] = [FUNCTION_NAME];\nconst EXAMPLE_INPUT_MINIGAMEBUILDER_EDIT_STIMULI: Partial<MinigameBuilderEditStimuliOpts> = {\n    agentId: 'SomeAgentIdHash',\n    notesToSelf: `Example of a ${FUNCTION_NAME} function call. Note repromptWithResult is true because we usually want to either make additional changes to prepare the minigame or start the user playing it.`,\n    repromptWithResult: true,\n    minigameAddr: `minigame TypingStanda 1750442279000^7EB8A7894384CD897423AC760FAC376808BF87431660871928743632746BBB32`,\n    stimulusEditInfos: [\n        {\n            action: 'add',\n            newStimulus: {\n                // srcCommentAddr: \"comment TypingDrills^6FC469DC624B1438500E9AF22BC18D23FD192843B69994F2B89ADEA90A3F4A73.A779D746A68743156638756262876A16387626222637456872CDCCC297234672\",\n                entryType: 'text',\n                value: 'Now is the time for all good men to come to the aid of their country.',\n                language: 'en-US',\n                notes: 'Standard English typing drills.'\n            },\n        },\n        {\n            action: 'add',\n            newStimulus: {\n                // srcCommentAddr: \"comment TypingDrills^6FC469DC624B1438500E9AF22BC18D23FD192843B69994F2B89ADEA90A3F4A73.A779D746A68743156638756262876A16387626222637456872CDCCC297234672\",\n                entryType: 'text',\n                value: 'The quick brown fox jumped over the lazy dogs.',\n                language: 'en-US',\n                notes: 'Standard English typing drills.'\n            },\n        },\n    ]\n};\nconst EXAMPLE_INPUT_MINIGAMEBUILDER_EDIT_STIMULI_ANTIPHONY: Partial<MinigameBuilderEditStimuliOpts> = {\n    agentId: 'SomeAgentIdHash',\n    notesToSelf: `Example of a ${FUNCTION_NAME} function call in a typing antiphony game. Note repromptWithResult is true because we usually want to either make additional changes to prepare the minigame or start the user playing it.`,\n    repromptWithResult: true,\n    minigameAddr: `minigame PartitaDue 1750442289000^0389D0F0CABC28767ED766F30C16D4E9061ED07F65D87F9F904193388EC61F79`,\n    stimulusEditInfos: [\n        {\n            action: 'add',\n            newStimulus: {\n                // srcCommentAddr: \"comment TypingDrills^6FC469DC624B1438500E9AF22BC18D23FD192843B69994F2B89ADEA90A3F4A73.A779D746A68743156638756262876A16387626222637456872CDCCC297234672\",\n                entryType: 'text',\n                value: `Qual \u00E8 la capitale dell'Italia?`,\n                expectedResponse: 'Roma',\n                expectedResponseType: ExpectedResponseType.exact,\n                language: 'it-IT',\n                notes: 'semplici curiosit\u00E0 italiane',\n            }\n        },\n        {\n            action: 'add',\n            newStimulus: {\n                // srcCommentAddr: \"comment TypingDrills^6FC469DC624B1438500E9AF22BC18D23FD192843B69994F2B89ADEA90A3F4A73.A779D746A68743156638756262876A16387626222637456872CDCCC297234672\",\n                entryType: 'text',\n                value: `Come ti chiami?`,\n                expectedResponse: 'Mi chiamo Bill.',\n                expectedResponseType: ExpectedResponseType.exact,\n                language: 'it-IT',\n                notes: 'frase semplice italiana',\n            }\n        },\n    ]\n};\nconst EXAMPLE_INPUT_MINIGAMEBUILDER_EDIT_STIMULI_FITB: Partial<MinigameBuilderEditStimuliOpts> = {\n    agentId: 'SomeAgentIdHash',\n    notesToSelf: `Example of a ${FUNCTION_NAME} function call in a typing FITB (fill-in-the-blank) game. Note repromptWithResult is true because we usually want to either make additional changes to prepare the minigame or start the user playing it.`,\n    repromptWithResult: true,\n    minigameAddr: `minigame PartitaTre 1750442289900^0DCCA695B825619571234964895718956AF2318731489658971986943860984C`,\n    stimulusEditInfos: [\n        {\n            action: 'add',\n            newStimulus: {\n                entryType: 'text',\n                value: `Qual \u00E8 la capitale dell'Italia?`,\n                expectedResponse: 'Roma',\n                expectedResponseType: ExpectedResponseType.exact,\n                language: 'it-IT',\n                notes: 'semplici curiosit\u00E0 italiane',\n            }\n        },\n        {\n            action: 'add',\n            newStimulus: {\n                entryType: 'text',\n                value: `Come ti chiami?`,\n                expectedResponse: 'Mi chiamo Bill.',\n                expectedResponseType: ExpectedResponseType.exact,\n                language: 'it-IT',\n                notes: 'frase semplice italiana',\n            }\n        },\n    ]\n};\n\nconst EXAMPLES = [\n    // `\\`\\`\\`typescript\\n${FUNCTION_CALL_EXAMPLES_HEADER}\\n${pretty(EXAMPLE_INPUT_TELLUSER)}\\n\\`\\`\\``,\n    FUNCTION_CALL_EXAMPLES_HEADER,\n    pretty(EXAMPLE_INPUT_MINIGAMEBUILDER_EDIT_STIMULI),\n    pretty(EXAMPLE_INPUT_MINIGAMEBUILDER_EDIT_STIMULI_ANTIPHONY),\n    pretty(EXAMPLE_INPUT_MINIGAMEBUILDER_EDIT_STIMULI_FITB),\n].join('\\n');\nconst FUNCTION_DESCRIPTION = `Continues building a minigame by adding one or more stimuli. Requires the game to be validated. If already previously validated, will be required to validate again.\\n\\n${EXAMPLES}`;\n// #endregion constants\n\n\n/**\n * @interface MinigameBuilderEditStimuliOpts - Options for the\n * minigameBuilderEditStimuli command.\n * @extends CommandDataBase\n */\nexport interface MinigameBuilderEditStimuliOpts extends CommandDataBase<typeof CMD_CATEGORY, typeof CMD_MODIFIERS> {\n    /**\n     * agent's id doing the telling\n     */\n    agentId?: string;\n    /**\n     * address of the minigame that we're adding stimuli to\n     */\n    minigameAddr: IbGibAddr;\n    /**\n     * stimuli to add to the typing minigame\n     */\n    stimulusEditInfos: StimulusEditInfo[];\n}\n\nexport interface MinigameBuilderEditStimuliResult {\n    success: boolean;\n    /**\n     * This is ACTUALLY the tjp address, but I'm trying to keep it simple for\n     * the model to understand during the builder process.\n     */\n    minigameAddr: IbGibAddr;\n}\n\n/**\n * @interface MinigameBuilderEditStimuliCommandData - Command data for the\n * minigameBuilderEditStimuli command.\n * @extends CommandDataBase\n */\nexport interface MinigameBuilderEditStimuliCommandData extends CommandDataBase<typeof CMD_CATEGORY, typeof CMD_MODIFIERS> {\n    /**\n     * agent's id doing the telling\n     */\n    agentId?: string;\n    /**\n     * address of the minigame that we're adding stimuli to\n     */\n    minigameAddr: IbGibAddr;\n    /**\n     * stimuli to add to the typing minigame\n     *\n     * ## notes on why Partial\n     *\n     * I have it partial because I don't want an agent passing in the id,\n     * rather, we give the id here in the implementation.\n     */\n    stimulusEditInfos: StimulusEditInfo[];\n}\n\n/**\n * Wrapper function to enqueue the minigameBuilderEditStimuli command.\n * @param {MinigameBuilderEditStimuliOpts} opts - Options for telling the user something.\n * @returns {Promise<MinigameBuilderEditStimuliResult>} A promise that resolves when the command is enqueued.\n */\nfunction minigameBuilderEditStimuliViaCmd(opts: MinigameBuilderEditStimuliOpts): Promise<MinigameBuilderEditStimuliResult> {\n    const lc = `[${minigameBuilderEditStimuliViaCmd.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n        if (logalot) { console.log(`${lc} minigameBuilderEditStimuliViaCmd raw incoming opts: ${pretty(opts)} (I: genuuid)`); }\n\n        const commandService = getCommandService();\n        const command: MinigameBuilderEditStimuliCommandData = {\n            ...opts,\n            cmd: CMD_CATEGORY,\n            cmdModifiers: CMD_MODIFIERS,\n        };\n        if (logalot) { console.log(`${lc} minigameBuilderEditStimuliViaCmd command: ${pretty(command)} (I: genuuid)`); }\n        return new Promise<MinigameBuilderEditStimuliResult>((resolve, reject) => {\n            commandService.enqueueCommand({ command, resolve, reject });\n        });\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * Implementation function for the minigameBuilderEditStimuli command.\n *\n * ## notes on context\n *\n * LLMs are designed to say/do something upon being prompted. In code, however,\n * it is beneficial to sometimes just give information and let the agent decide\n * whether or not to act upon it. Right now I have this doubling as an \"ack\"\n * command that acts like a blackhole for when the agent decides no action is\n * required. So if the context is a primitive, then this will \"fail\" silently.\n *\n *\n * @param {MinigameBuilderEditStimuliOpts} opts - Options for telling the user something.\n * @returns {Promise<MinigameBuilderEditStimuliResult>} A promise that resolves when the command is executed (immediately).\n */\nasync function minigameBuilderEditStimuliImpl(opts: MinigameBuilderEditStimuliOpts): Promise<MinigameBuilderEditStimuliResult> {\n    const lc = `[${minigameBuilderEditStimuliImpl.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n\n        console.log(`${lc} opts: ${pretty(opts)}`);\n\n        const metaspace = await getGlobalMetaspace_waitIfNeeded();\n        const minigameAddr = opts.minigameAddr;\n        if (!minigameAddr) { throw new Error(`minigameAddr is falsy (was not provided by model if this was a function call request). This should be required in the gemini schema. (E: genuuid)`); }\n\n        const addrErrors = validateIbGibAddr({ addr: minigameAddr }) ?? [];\n        if (addrErrors.length > 0) {\n            throw new Error(`${lc} agent has provided a non-ibgib addr for minigameAddr: ${minigameAddr}. addrErrors: ${addrErrors}. opts: ${pretty(opts)} (E: genuuid)`)\n        }\n        if (isPrimitive({ gib: getIbAndGib({ ibGibAddr: minigameAddr }).gib })) {\n            throw new Error(`agent has tried calling this with a primitive context address. opts: ${pretty(opts)} (E: genuuid)`);\n        }\n        const space = await metaspace.getLocalUserSpace({ lock: false });\n        if (!space) { throw new Error(`(UNEXPECTED) couldn't get default local user space? (E: genuuid)`); }\n\n        if ((opts.stimulusEditInfos ?? []).length === 0) {\n            throw new Error(`opts.stimulusEditInfos is either falsy or empty.  (E: 84f6482680b85790e8ab21a837b39825)`);\n        }\n\n        for (const info of opts.stimulusEditInfos) {\n            if (info.newStimulus) {\n                info.newStimulus.id ??= await getNewTypingEntryId(); // arbitrary\n            }\n        }\n\n        /**\n         * we don't return this to avoid confusing the agent with extra detail.\n         * the agent uses the tjpAddr when referencing the minigame.\n         */\n        const _newMinigameIbGib = await editStimuli_typing({\n            stimuliEditInfos: opts.stimulusEditInfos,\n            minigameAddr: minigameAddr,\n        });\n\n        return {\n            success: true,\n            minigameAddr: opts.minigameAddr, // tjpAddr\n        }\n\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nconst GEMINI_SCHEMA_MINIGAME_TYPING_STIMULUS = {\n    type: 'object',\n    properties: {\n        id: { type: 'string', description: 'Id of the stimulus, should be unique. If you\\'re adding/inserting a new stimulus, then this will be auto-generated.' },\n        entryType: {\n            type: 'string',\n            enum: ['text'],\n            description: `What type of stimulus. Right now, this is only \"text\" because we're only doing text-based stimulation. But in the future, this enum will include other types for other modalities.`\n        },\n        value: { type: 'string', description: `Actual content of the stimulus.` },\n        language: {\n            type: 'string',\n            description: `natural name/identifier of the language. there is no form enforced, but an IETF code (locale) usable in JavaScript with, e.g., \\`Intl\\` is recommended, e.g., \"en-US\", \"ko-Kore-KR\"`\n        },\n        expectedResponse: { type: 'string', description: `Expected response value when this stimulus is shown to the user.` },\n        expectedResponseType: {\n            type: 'string',\n            enum: EXPECTED_RESPONSE_TYPE_VALID_VALUES,\n            description: [\n                `Determines how to interpret expectedResponse as follows:`,\n                `* exact: the user should type expectedResponse character by character to match this stimulus' value.`,\n                `* fill-in-the-blank: the user should type what goes in the stimulus' blank(s).`,\n                `* answer: the user should answer the question with something equivalent to expectedResponse. If there is only one exact answer, you can use this or 'exact'.`,\n            ].join('\\n'),\n        },\n    },\n    required: [\n        'entryType',\n        'value',\n        'language',\n        'expectedResponse',\n        'expectedResponseType',\n    ],\n}\n\n// const GEMINI_SCHEMA_MINIGAME_TYPING_STIMULI = {\n//     type: 'array',\n//     items: GEMINI_SCHEMA_MINIGAME_TYPING_STIMULUS,\n// }\n\nconst GEMINI_SCHEMA_MINIGAME_TYPING_STIMULUS_EDIT_INFO = {\n    type: 'object',\n    properties: {\n        action: {\n            type: 'string',\n            enum: ['add', 'edit', 'insert', 'delete'],\n            description: `What type of editing action to take. NOTE: When you are editing, inserting, or deleting, you MUST include either the index of the stimulus in minigame.data.gameMeta.allStimuli array or the correct id of the stimulus in that array. Note that the applicable index may change if you delete any stimuli, so often the stimulusId is the safer option. If you don't know the stimulus.id, then just call getIbGibs for the minigame, using \"getLatest: true\" and that result will have all of the stimuli in its data.gameMeta.`,\n        },\n        newStimulus: GEMINI_SCHEMA_MINIGAME_TYPING_STIMULUS,\n        index: {\n            type: 'number',\n            description: `If you are editing/inserting/deleting a stimulus, then this or stimulusId is REQUIRED. You can get this id by looking in the minigame's data.gameMeta.allStimuli array.`,\n        },\n        stimulusId: {\n            type: 'string',\n            description: `If you are editing/inserting/deleting a stimulus, then this or stimulusId is REQUIRED. You can get this id by looking in the minigame's data.gameMeta.allStimuli array.`,\n        },\n    },\n    required: [\n        'action',\n        'newStimulus'\n    ],\n}\nconst GEMINI_SCHEMA_MINIGAME_TYPING_STIMULUS_EDIT_INFOS = {\n    type: 'array',\n    items: GEMINI_SCHEMA_MINIGAME_TYPING_STIMULUS_EDIT_INFO,\n}\n\n/**\n * API function info for the minigameBuilderEditStimuli command.\n */\nexport const minigameBuilderEditStimuliFunctionInfo: APIFunctionInfo<typeof minigameBuilderEditStimuliViaCmd> = {\n    nameOrId: FUNCTION_NAME,\n    fnViaCmd: minigameBuilderEditStimuliViaCmd,\n    functionImpl: minigameBuilderEditStimuliImpl,\n    cmd: CMD_CATEGORY,\n    cmdModifiers: CMD_MODIFIERS,\n    schema: {\n        name: FUNCTION_NAME,\n        description: FUNCTION_DESCRIPTION,\n        parameters: {\n            type: 'object',\n            properties: {\n                ...COMMAND_BASE_SCHEMA_PROPERTIES,\n                minigameAddr: GEMINI_SCHEMA_MINIGAME_CONTEXT_ADDR,\n                stimulusEditInfos: GEMINI_SCHEMA_MINIGAME_TYPING_STIMULUS_EDIT_INFOS,\n            },\n            required: [\n                'agentId', // base, required when agent uses this cmd but not required in opts/cmd proper\n                'minigameAddr',\n                'stimulusEditInfos',\n            ],\n        },\n    },\n};\n", "import thisHtml from './typing.html';\nimport thisCss from './typing.css';\nimport stylesCss from '../../../styles.css';\nimport rootCss from '../../../root.css';\n\nimport {\n    clone, delay, extractErrorMsg, getTimestampInTicks, getUUID, pickRandom, pretty,\n    unique,\n} from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { IbGibAddr, } from \"@ibgib/ts-gib/dist/types.mjs\";\nimport { IbGib_V1 } from \"@ibgib/ts-gib/dist/V1/types.mjs\";\nimport { validateIbGibAddr } from \"@ibgib/ts-gib/dist/V1/validate-helper.mjs\";\nimport { getIbAndGib, getIbGibAddr } from \"@ibgib/ts-gib/dist/helper.mjs\";\nimport { MetaspaceService } from \"@ibgib/core-gib/dist/witness/space/metaspace/metaspace-types.mjs\";\nimport { mut8Timeline } from \"@ibgib/core-gib/dist/timeline/timeline-api.mjs\";\nimport { tellUserFunctionInfo } from '@ibgib/web-gib/dist/api/commands/chat/tell-user.mjs';\nimport { helloWorldFunctionInfo } from '@ibgib/web-gib/dist/api/commands/chat/hello-world.mjs';\nimport { alertUser, highlightElement, promptForConfirm, promptForText, shadowRoot_getElementById, } from \"@ibgib/web-gib/dist/helpers.web.mjs\";\nimport { getGlobalMetaspace_waitIfNeeded, debounce, } from \"@ibgib/web-gib/dist/helpers.mjs\";\nimport { IbGibDynamicComponentInstanceBase, IbGibDynamicComponentMetaBase } from \"@ibgib/web-gib/dist/ui/component/ibgib-dynamic-component-bases.mjs\";\nimport { ElementsBase, IbGibDynamicComponentInstance, IbGibDynamicComponentInstanceInitOpts, } from \"@ibgib/web-gib/dist/ui/component/component-types.mjs\";\n\nimport {\n    GLOBAL_LOG_A_LOT,\n} from \"../../../constants.mjs\";\nimport { MinigameFiniteStateMachine, MinigameGamePhase, MinigameIbGib_V1 } from \"../../../common/minigame/minigame-types.mjs\";\nimport { DEFAULT_ISO_639_LANGUAGE_CODES, DEFAULT_TYPING_GAMEMETA, DEFAULT_TYPING_GAMESTATE, ExpectedResponseType, MINIGAME_FOCUS_INFO, MINIGAME_STIMULTI_TO_ADD_INFO, MinigameGameVariant_Typing } from \"../../../common/minigame/typing/typing-constants.mjs\";\nimport { Minigame_TypingGameState, Minigame_TypingGameMeta, MinigameTypingRawStats, Minigame_TypingStimulus, TypingEntryAndElementsInfo, FocusAndElementsInfo, } from \"../../../common/minigame/typing/typing-types.mjs\";\nimport { AnalysisEngine, } from \"../../../common/text-analysis/analysis-engine.mjs\";\nimport { CorpusAnalyzer } from \"../../../common/text-analysis/corpus-analyzer.mjs\";\nimport {\n    getElapsedInfo, getAnotherFocusText, getWpm, TypingFocusLevel,\n    getGoogleTranslateLink, getStimulusEntryEl,\n    getNewTypingEntryId,\n    getFocusAndElementsInfo,\n    slideRightAndFade,\n    unfadeEl,\n    toHoursMinutesSeconds,\n} from \"../../../common/minigame/typing/typing-helper.mjs\";\nimport { DEFAULT_TOKEN_CONSTRUCT_RULE } from \"../../../common/text-analysis/analysis-engine-constants.mjs\";\nimport { minigameBuilderValidateAndReadyFunctionInfo, MinigameBuilderValidateAndReadyResult } from \"../../../api/commands/minigame/minigame-builder-validate-and-ready.mjs\";\nimport { minigameBuilderEditStimuliFunctionInfo } from \"../../../api/commands/minigame/minigame-builder-edit-stimuli.mjs\";\nimport { getComponentCtorArg } from '../../../helpers.web.mjs';\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\nexport const AGENT_SPECIAL_IBGIB_TYPE_TYPINGAGENT = 'typingagent';\nexport const CHAT_WITH_AGENT_PLACEHOLDER_TYPINGAGENT = '';\nexport const AGENT_AVAILABLE_FUNCTIONS_TYPINGAGENT = [\n    helloWorldFunctionInfo,\n    tellUserFunctionInfo,\n];\n\nexport const TYPING_COMPONENT_NAME: string = 'ibgib-typing';\n\nexport class TypingComponentMeta extends IbGibDynamicComponentMetaBase {\n    protected override lc: string = `[${TypingComponentMeta.name}]`;\n\n    /**\n     * temporary regexp path for our initial dev. this component will become\n     * attached to actual ib^gib addrs\n     */\n    routeRegExp?: RegExp = new RegExp(TYPING_COMPONENT_NAME);\n    // routeRegExp?: RegExp = /apps\\/web1\\/gib\\/contact.html/;\n\n    componentName: string = TYPING_COMPONENT_NAME;\n\n    constructor() {\n        super(getComponentCtorArg());\n        customElements.define(this.componentName, TypingComponentInstance);\n    }\n\n    async createInstance({\n        path,\n        ibGibAddr\n    }: {\n        path: string;\n        ibGibAddr: IbGibAddr;\n    }): Promise<IbGibDynamicComponentInstance> {\n        const lc = `${this.lc}[${this.createInstance.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: d88226a0a20c35abb8e046e8eb251825)`); }\n            const component = document.createElement(this.componentName) as TypingComponentInstance;\n            await component.initialize({\n                ibGibAddr,\n                meta: this,\n                html: thisHtml,\n                css: [rootCss, stylesCss, thisCss],\n            });\n            return component;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n}\n\ninterface TypingElements extends ElementsBase {\n    headerEl: HTMLElement;\n    // headerTabsEl: HTMLElement | undefined;\n    commandBarEl: HTMLElement;\n    /**\n     * Used for showing the title/instance name of the typing minigame\n     */\n    nameEl: HTMLHeadingElement;\n    /**\n     * Used for showing instructions\n     */\n    descEl: HTMLParagraphElement;\n    /**\n     * container element for the component\n     *\n     * contains the stimulus elements\n     */\n    stimulusEl: HTMLElement;\n    /**\n     * container element for the init screen during the init phase\n     */\n    screenInitEl: HTMLDivElement;\n    initAllStimuliEl: HTMLElement;\n    initAddStimulusBtnEl: HTMLButtonElement;\n    initTranslateLinkEl: HTMLAnchorElement;\n\n    initPlayableEl: HTMLButtonElement;\n    initGameTypeEl: HTMLElement;\n    // initGameVariantEl: HTMLElement;\n    screenReadyEl: HTMLDivElement;\n    readyCountdownEl: HTMLElement;\n    /**\n     * container element for the playing screen during the playing phase\n     */\n    screenPlayingEl: HTMLDivElement;\n    /**\n     * container element for the aborted screen during the aborted phase\n     */\n    screenAbortedEl: HTMLDivElement;\n    /**\n     * container element for the complete screen during the complete phase\n     */\n    screenCompleteEl: HTMLDivElement;\n    summaryStatsEl: HTMLElement;\n    /**\n     * contains the input(?)\n     */\n    footerEl: HTMLElement;\n    /**\n     * where the user types in their response to the stimulus.\n     */\n    inputEl: HTMLTextAreaElement;\n    inputSendBtnEl: HTMLButtonElement;\n}\n\nexport class TypingComponentInstance\n    extends IbGibDynamicComponentInstanceBase<MinigameIbGib_V1, TypingElements>\n    implements IbGibDynamicComponentInstance<IbGib_V1, TypingElements>,\n    MinigameFiniteStateMachine {\n    protected override lc: string = `[${TypingComponentInstance.name}]`;\n\n    metaspace: MetaspaceService | undefined;\n\n    get gamePhase(): MinigameGamePhase | undefined {\n        const lc = `${this.lc}[get phase]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: bbd656f383c8fc7f9f40ac280eba0525)`); }\n\n            if (!this.ibGib) {\n                console.error(`${lc} (UNEXPECTED) this.ibGib falsy? i don't know if tihs is an error at this point... (E: bc2c1748509340f3e7568dc891494825)`);\n                return undefined; /* <<<< returns early */\n            }\n            if (!this.ibGib.data) {\n                console.error(`${lc} (UNEXPECTED) this.ibGib.data falsy? i don't know if tihs is an error at this point... (E: 02f2e820b028f590ecf1ec2889461225)`);\n                return undefined; /* <<<< returns early */\n            }\n            return this.ibGib.data.gamePhase;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    get gameState(): Minigame_TypingGameState {\n        if (!this.ibGib) { throw new Error(`(UNEXPECTED) this.ibGib falsy? (E: ef7aaf06088538c038d4e2fef0162325)`); }\n        if (!this.ibGib?.data) { throw new Error(`(UNEXPECTED) this.ibGib.data falsy? (E: db47983c1ed199a8d974ca085ee79825)`); }\n        return this.ibGib.data.gameState as Minigame_TypingGameState;\n    }\n    get gameMeta(): Minigame_TypingGameMeta {\n        if (!this.ibGib) { throw new Error(`(UNEXPECTED) this.ibGib falsy? (E: 6d612b984548a3f998ab2836b4c01825)`); }\n        if (!this.ibGib?.data) { throw new Error(`(UNEXPECTED) this.ibGib.data falsy? (E: 8833187787e8d5f7461e203844e42825)`); }\n        return this.ibGib.data.gameMeta as Minigame_TypingGameMeta;\n    }\n    get minigameIbGib(): MinigameIbGib_V1 {\n        if (!this.ibGib) {\n            debugger; // error this.ibGib in minigame typing component\n            throw new Error(`(UNEXPECTED) this.ibGib falsy? (E: 14cf3803cb595c01853f0558d23ec825)`);\n        }\n        return this.ibGib as MinigameIbGib_V1;\n    }\n\n    private readyCountdown: number = 0;\n\n    constructor() {\n        super();\n    }\n\n    // #region MinigameFiniteStateMachine\n    public async play(): Promise<void> {\n        const lc = `${this.lc}[${this.play.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: b27a28ecb6923fcc584cac88c1e2da25)`); }\n\n            const { gamePhase } = this.ibGib!.data!;\n            const { } = this.gameState;\n\n            switch (gamePhase) {\n                case MinigameGamePhase.init:\n                    await this.activatePhase_ready();\n                    break;\n                case MinigameGamePhase.ready:\n                    await this.activatePhase_playing();\n                    break;\n                case MinigameGamePhase.playing:\n                    await this.activatePhase_complete();\n                    break;\n                case MinigameGamePhase.paused:\n                    await this.activatePhase_playing();\n                    break;\n                case MinigameGamePhase.aborted:\n                    await this.activatePhase_init();\n                    break;\n                case MinigameGamePhase.complete:\n                    await this.activatePhase_init();\n                    break;\n                default:\n                    throw new Error(`(UNEXPECTED) unknown gamePhase (${gamePhase})? (E: de6a888ceb9e8e2098777ee8e689e125)`);\n            }\n\n            await this.renderUI();\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    public async pause(): Promise<void> {\n        const lc = `${this.lc}[${this.pause.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 4baa7ab2e988c7dd28bb40226114d825)`); }\n            await this.activatePhase_paused();\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    public async restart(): Promise<void> {\n        const lc = `${this.lc}[${this.restart.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: a9399d610de88bfa8853343832f16825)`); }\n            if (!this.ibGib) { throw new Error(`(UNEXPECTED) this.ibGib falsy? (E: 01a53b06f093d78ede496b47ce174125)`); }\n            if (!this.ibGib.data) { throw new Error(`(UNEXPECTED) this.ibGib.data falsy? (E: 8a3d883786fd1e7a584dd9a821a93825)`); }\n\n            if (this.ibGib.data.playable) {\n                // save current game state\n                // if (this.phase === MinigameGamePhase.ready) {\n                await this.initGameState();\n                await this.activatePhase_init();\n                await this.renderUI();\n            } else {\n                // player/agent has added stimuli or something else that has\n                // reset the playable. it needs to be validated.\n                await this.initGameState();\n                await this.activatePhase_init();\n                await this.renderUI();\n            }\n\n            // }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    public async abort(): Promise<void> {\n        const lc = `${this.lc}[${this.abort.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 565fe6ac19981bb1f89161f86fe49825)`); }\n            await this.activatePhase_aborted();\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    public async complete(): Promise<void> {\n        const lc = `${this.lc}[${this.complete.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: fca4183de61b5df9b886569d8b0e7925)`); }\n            await this.activatePhase_complete();\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    // #endregion MinigameFiniteStateMachine\n\n    /**\n     * should this just be left up to the gameFSM, since that already is\n     * responsible for saving the concrete game state?\n     */\n    private async setGamePhase({ gamePhase }: { gamePhase: MinigameGamePhase }): Promise<void> {\n        const lc = `${this.lc}[${this.setGamePhase.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: f120ab31ae2e3fecb835d728df83b425)`); }\n\n            if (!this.ibGib) { throw new Error(`(UNEXPECTED) this.ibGib falsy? (E: 0c8fb8108578fa7908cf617bb8f25c25)`); }\n            if (!this.ibGib.data) { throw new Error(`(UNEXPECTED) this.ibGib.data falsy? (E: 676728b52d38bde0eccb8369d35d1825)`); }\n            console.log(`${lc} BEFORE this.gamePhase: ${this.gamePhase} (I: ec8a689398a8936c6a99e202cdc0a825)`)\n            if (this.ibGib.data.gamePhase !== gamePhase) {\n                const newIbGib = await mut8Timeline({\n                    timeline: this.ibGib, // minigame\n                    metaspace: this.metaspace!,\n                    mut8Opts: { dataToAddOrPatch: { gamePhase, } },\n                });\n                await delay(500); // hack to let proxy update...gotta find a better solution here. maybe need to add a function to the proxy to await an update.\n                console.log(`${lc} AFTER this.gamePhase: ${this.gamePhase} (I: 534baae3a5f3c408a84191ef4a273e25)`)\n            }\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    // #region activatePhase\n    private async activatePhase_init(): Promise<void> {\n        const lc = `${this.lc}[${this.activatePhase_init.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 1a25e4dbb71610a31847a6483c1a1825)`); }\n            await this.setGamePhase({ gamePhase: MinigameGamePhase.init });\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    private async activatePhase_ready(): Promise<void> {\n        const lc = `${this.lc}[${this.activatePhase_ready.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 512f4ebc94184571037ae81f8235b825)`); }\n            await this.setGamePhase({ gamePhase: MinigameGamePhase.ready });\n            this.readyCountdown = 3;\n            this.elements!.readyCountdownEl.innerHTML = '';\n            setTimeout(async () => {\n                while (this.readyCountdown <= 3 && this.readyCountdown > 0) {\n                    this.renderUI_readyCountdown();\n                    await delay(1000);\n                    this.readyCountdown--;\n                }\n                this.elements!.readyCountdownEl.innerHTML = '';\n                await this.play();\n            });\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    private async activatePhase_playing(): Promise<void> {\n        const lc = `${this.lc}[${this.activatePhase_playing.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: cae208d0b038d9a12827744b62865825)`); }\n            // start timer?\n            // populate stimulus queue\n            // enable the submit button\n            if (this.gamePhase === MinigameGamePhase.paused) {\n                await this.setGamePhase({ gamePhase: MinigameGamePhase.playing });\n            } else {\n                await this.initGameState();\n                await this.flushGameStateToTimeline();\n                await this.setGamePhase({ gamePhase: MinigameGamePhase.playing });\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    /**\n     *\n     */\n    private async initGameState(): Promise<void> {\n        const lc = `${this.lc}[${this.initGameState.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: cede184c1ef8b0156809312e32c6a825)`); }\n            if (!this.gameMeta.allStimuli) { throw new Error(`(UNEXPECTED) this.gameMeta.allStimuli falsy? we are expecting at this point to be a valid game and thus this should be truthy, even if empty. (E: db1805280be88720e716676812485125)`); }\n            this.gameState.remainingStimuli = this.gameMeta.allStimuli.concat();\n            const firstStimulus = this.gameState.remainingStimuli.shift();\n            firstStimulus!.timestampInTicks = getTimestampInTicks();\n            this.gameState.currentStimulus = firstStimulus;\n            this.gameState.interactions = [];\n            this.gameState.flushCounter = 0;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    private async activatePhase_paused(): Promise<void> {\n        const lc = `${this.lc}[${this.activatePhase_paused.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 2844b8dfd80cd75c1896e6588dc69b25)`); }\n            await this.setGamePhase({ gamePhase: MinigameGamePhase.paused });\n            // stop timer? does this happen in parent minigame component?\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private async activatePhase_aborted(): Promise<void> {\n        const lc = `${this.lc}[${this.activatePhase_aborted.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: a490ca8692d6ea6e6fbbd608e36fc825)`); }\n            await this.setGamePhase({ gamePhase: MinigameGamePhase.aborted });\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    private async calculateSummaryStats(): Promise<MinigameTypingRawStats | undefined> {\n        const lc = `${this.lc}[${this.calculateSummaryStats.name}]`;\n        try {\n\n            if (!this.ibGib) { throw new Error(`(UNEXPECTED) this.ibGib falsy? (E: c670b4aca76bc2a348072858f0428825)`); }\n            if (!this.ibGib.data) { throw new Error(`(UNEXPECTED) this.ibGib.data falsy? (E: 7200288f70c82bf4e8c22f78964ea825)`); }\n            if (!this.elements) { throw new Error(`(UNEXPECTED) this.elements falsy? (E: 5516b84e6a8890bbb280121941d3b825)`); }\n\n            const { } = this.ibGib.data;\n            const { interactions } = this.gameState;\n            // calculate stats\n            if (interactions.length === 0) {\n                console.log(`${lc} we didn't do nothin'. interactions.length === 0. returning early (I: 4937e8f57438854d1ab5f2289be8e825)`);\n                return; /* <<<< returns early */\n            }\n\n            /**\n             * turn this into a constant? rather arbitrary, but the feel is that\n             * it should be relatively short, but long enough for decent power\n             */\n            const topN = 16;\n\n            const responses = interactions.map(x => x.response);\n            const responses_string = responses.map(x => x.value).join('\\n\\n');\n            const responses_docId = await getUUID();\n            const stimuli = interactions.map(x => x.stimulus);\n            const stimuli_string = stimuli.map(x => x.value).join('\\n\\n');\n            const stimuli_docId = await getUUID();\n\n            const engine = new AnalysisEngine([\n                DEFAULT_TOKEN_CONSTRUCT_RULE,\n                // ...DEFAULT_SPANISH_RULES,\n            ]);\n            // const analyzer = new CorpusAnalyzer(AnalysisEngine.DEFAULT);\n            const analyzer = new CorpusAnalyzer(engine);\n            analyzer.addDocumentFromText({\n                id: responses_docId,\n                text: responses_string,\n            });\n            analyzer.addDocumentFromText({\n                id: stimuli_docId,\n                text: stimuli_string,\n            });\n            const responses_analysis = analyzer.getDocumentAnalysis({ id: responses_docId });\n            if (!responses_analysis) { throw new Error(`(UNEXPECTED) responses_analysis falsy? (E: 02a658aa66a93b9118a83f38ec3c4f25)`); }\n            const responses_report = analyzer.generateDocumentReport({\n                docId: responses_docId,\n                topN,\n                constructsToReport: [AnalysisEngine.PRIMORDIAL_TOKEN_CONSTRUCT_NAME]\n                // constructsToReport: [...DEFAULT_SPANISH_RULES.map(x => x.name)],\n            });\n            const stimuli_analysis = analyzer.getDocumentAnalysis({ id: stimuli_docId });\n            if (!stimuli_analysis) { throw new Error(`(UNEXPECTED) stimuli_analysis falsy? (E: c6809e78f3a8796f6e58ae68814de425)`); }\n            const stimuli_report = analyzer.generateDocumentReport({\n                docId: stimuli_docId,\n                topN,\n                constructsToReport: [AnalysisEngine.PRIMORDIAL_TOKEN_CONSTRUCT_NAME]\n                // constructsToReport: [...DEFAULT_SPANISH_RULES.map(x => x.name)],\n            });\n            const comparison = analyzer.generateComparisonReport({\n                sourceDocId: stimuli_docId,\n                targetDocId: responses_docId,\n                constructName: AnalysisEngine.PRIMORDIAL_TOKEN_CONSTRUCT_NAME, // 'token',\n                // constructName: DEFAULT_SPANISH_RULES.at(0)!.name, // 'token',\n                topN: 16,\n            });\n\n            // associate stats to minigame?\n            // const testCorpus = new TfIdfCorpus();\n\n            const {\n                elapsedMs_toLastInteractionResponse,\n                elapsedMs_toLastInteractionStimulus,\n                elapsedMs_toNow,\n                errors: elapsedErrors,\n            } = getElapsedInfo({\n                a: interactions.at(0)!,\n                b: interactions.at(-1)!,\n            });\n            if (elapsedErrors) {\n                console.warn(`${lc} there were errors when trying to getElapsedInfo: ${elapsedErrors} (W: ccc058ca6e24bd6368db8345ca879a25)`);\n            }\n            const elapsedMs =\n                elapsedMs_toLastInteractionResponse ??\n                elapsedMs_toLastInteractionStimulus ??\n                -1;\n            const wpm = getWpm({ responsesAnalysis: responses_analysis, elapsedMs });\n\n            let numberCorrect = 0;\n            const fnGetAgentsOpinion = async () => {\n                // no \"correct\" available, ask the agent one-off if available\n                if (!this.agent) {\n                    // no agent\n                    return -1;\n                }\n                // update the source & target languages, if not already selected\n                const agentsOpinion = await this.agent.promptOneOff({\n                    text: [\n                        `Hi. We're trying to guage if a user's response to a stimulus was \"correct\". Please give your opinion on the level of correctness expressed as a decimal from 0 to 1. If the response was exactly correct, then give 1. If \"correct\" does not apply, return -1.`,\n                    ].join('\\n'),\n                    systemInstructions: [\n                        'You are an expert judge who will be given ais being asked to rate a response in a minigame. Usually these are for learning purposes and there is some meaning for \"correct\".',\n                        `In your response, please don't use a full sentence, just say the answer because we'll be parsing it as a number. So if you believe the user's response was correct, like if it's a translation and they had a semantically correct translation, then just say '1'. If it's a typing question and they got a single type among 50 characters, then say '0.98'. If \"correct\" does not apply, return '-1'`,\n                        `Thank you in advance! ;-)`,\n                    ].join('\\n'),\n                });\n                debugger;\n                console.log(agentsOpinion);\n                console.dir(agentsOpinion);\n\n                if (agentsOpinion === undefined) { return -1; /* <<<< returns early */ }\n\n                const asNumber = agentsOpinion.includes('.') ?\n                    Number.parseFloat(agentsOpinion) :\n                    Number.parseInt(agentsOpinion);\n                return Number.isNaN(asNumber) ? -1 : asNumber;\n            }\n            for (const interaction of interactions) {\n                if (interaction.stimulus.expectedResponse) {\n\n                } else {\n                    let correctness = await fnGetAgentsOpinion();\n                    if (correctness > 0.7) {\n                        numberCorrect++;\n                    }\n                }\n            }\n\n            const stats: MinigameTypingRawStats = {\n                elapsedMs,\n                elapsedTimespan: toHoursMinutesSeconds({ elapsedMs }),\n                wpm,\n                interactionCount: interactions.length,\n                responses: {\n                    analysis: responses_analysis,\n                    report: responses_report,\n                },\n                stimuli: {\n                    analysis: stimuli_analysis,\n                    report: stimuli_report,\n                },\n                comparison,\n            }; if (logalot) { console.log(`${lc} starting... (I: 39ebe887b356e81f23c65578269eaa25)`); }\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private async activatePhase_complete(): Promise<void> {\n        const lc = `${this.lc}[${this.activatePhase_complete.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 6ca9ca11248ab608385da66c94f4e825)`); }\n            await this.setGamePhase({ gamePhase: MinigameGamePhase.complete });\n\n            const stats = await this.calculateSummaryStats();\n            if (!this.elements) { throw new Error(`(UNEXPECTED) this.elements falsy? (E: 0432d9d41c37ff4feaca233647038825)`); }\n\n            if (!stats) {\n                console.log(`${lc} stats was undefined. probably no interactions. (I: 9cbd2f0ad678978ab8e5b0180563c425)`);\n                return; /* <<<< returns early */\n            }\n\n            const { screenCompleteEl, summaryStatsEl, } = this.elements;\n            summaryStatsEl.innerHTML = '';\n            // temporary pre. also `toHoursMinutesSeconds` helper created, but i\n            // don't have it plugged in here yet\n            const pre = document.createElement('pre');\n            pre.textContent = pretty(stats);\n            summaryStatsEl.appendChild(pre);\n\n            this.gameMeta.statsHistory ??= [];\n            this.gameMeta.statsHistory.push(stats);\n            await this.flushGameMetaToTimeline();\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    // #endregion activatePhase\n\n    override async initialize(opts: IbGibDynamicComponentInstanceInitOpts): Promise<void> {\n        const lc = `${this.lc}[${this.initialize.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 41cb3607e798ace12380bb214f4a8e25)`); }\n            await super.initialize(opts);\n            await this.loadIbGib({ getLatest: true });\n            this.metaspace = await getGlobalMetaspace_waitIfNeeded();\n            this.agentsInitialized = this.initAgents();\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    protected override async initAgents(): Promise<void> {\n        const lc = `${this.lc}[${this.initAgents.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 244412de61988993e8ba91d8dd5c8825)`); }\n\n            await this.loadAgentsCoupledToIbGib();\n\n            if (!this.agent) { throw new Error(`(UNEXPECTED) agent falsy after createNewAgent? (E: aa1f3b3748fad9aeea2bbba849cd5825)`); }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    override async created(): Promise<void> {\n        const lc = `${this.lc}[${this.created.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: aaf448463b08d2de68687248cf0bb425)`); }\n\n            // const { meta, htmlPath, scriptPaths, cssPaths } = opts;\n\n            // at this point, this.ibGib should be loaded with the latest ibgib\n            if (!this.ibGib) { throw new Error(`(UNEXPECTED) this.ibGib falsy? It is assumed at this point that we have a valid ibGib to work with. (E: 2345d6121ced938c84035c6307559c25)`); }\n\n            await this.initElements();\n            await this.agentsInitialized;\n            await this.renderUI();\n            if (this.gamePhase === MinigameGamePhase.ready) {\n                await this.restart();\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    override async disconnected(): Promise<void> {\n        const lc = `${this.lc}[${this.disconnected.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: dd2eaf80dc2f98dd187d4db8dda2c825)`); }\n            // no action atow\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    override async handleContextUpdated(): Promise<void> {\n        const lc = `${this.lc}[${this.handleContextUpdated.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 60d7d8943d9806060865eb2ea29d0825)`); }\n            await super.handleContextUpdated();\n            await this.renderUI();\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private async initElements(): Promise<void> {\n        const lc = `${this.lc}[${this.initElements.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: e28e42cc888c77f578a83f9fee54ac25)`); }\n\n            const shadowRoot = this.shadowRoot;\n\n            if (!shadowRoot) { throw new Error(`(UNEXPECTED) shadowRoot falsy? (E: e467eaa0af6876af981fd218944bd425)`); }\n\n            // #region header\n\n            const headerEl = shadowRoot.getElementById('typing-header') as HTMLElement;\n            if (!headerEl) { throw new Error(`(UNEXPECTED) headerEl not found in shadowRoot? (E: 4cf9689204e88844d85fd3f1b6b9bc25)`); }\n\n            const nameEl = shadowRoot.getElementById('typing-name') as HTMLHeadingElement;\n            if (!nameEl) { throw new Error(`(UNEXPECTED) nameEl not found in shadowRoot? (E: b2794c9acf384c5391ae1728178af825)`); }\n            const descEl = shadowRoot.getElementById('typing-description') as HTMLParagraphElement;\n            if (!descEl) { throw new Error(`(UNEXPECTED) descEl not found in shadowRoot? (E: f16a181bb128359639f531a8529b4825)`); }\n\n            const commandBarEl = shadowRoot.getElementById('typing-command-bar') as HTMLElement;\n            if (!commandBarEl) { throw new Error(`(UNEXPECTED) commandBarEl not found in shadowRoot? (E: e680c88b6118d4950cad0078742a6825)`); }\n\n            // #endregion header\n\n            const contentEl = shadowRoot_getElementById<HTMLElement>(shadowRoot, 'typing-content');\n\n            const screenInitEl = shadowRoot_getElementById<HTMLDivElement>(shadowRoot, 'typing-screen-init');\n            screenInitEl.style.display = \"flex\";\n            const initAllStimuliEl = shadowRoot_getElementById<HTMLElement>(shadowRoot, 'init-all-stimuli');\n            const initAddStimulusBtnEl = shadowRoot_getElementById<HTMLButtonElement>(shadowRoot, 'add-stimulus-btn');\n            initAddStimulusBtnEl.addEventListener('click', async () => {\n                await this.handleAddStimulusBtnClick();\n            })\n            const initTranslateLinkEl = shadowRoot_getElementById<HTMLAnchorElement>(shadowRoot, \"init-translate-link\");\n            const initPlayableEl = shadowRoot_getElementById<HTMLButtonElement>(shadowRoot, 'init-playable');\n            initPlayableEl.addEventListener('click', async () => {\n                await this.validateAndReadyMinigame();\n            });\n            const initGameTypeEl = shadowRoot_getElementById<HTMLElement>(shadowRoot, 'init-game-type');\n            // const initGameVariantEl = shadowRoot_getElementById<HTMLElement>(shadowRoot, 'init-game-variant');\n\n            const screenReadyEl = shadowRoot_getElementById<HTMLDivElement>(shadowRoot, 'typing-screen-ready');\n            screenReadyEl.style.display = \"none\";\n            const readyCountdownEl = shadowRoot_getElementById<HTMLElement>(shadowRoot, 'ready-countdown');\n\n            const screenPlayingEl = shadowRoot_getElementById<HTMLDivElement>(shadowRoot, 'typing-screen-playing');\n            screenPlayingEl.style.display = \"none\";\n\n            const screenAbortedEl = shadowRoot_getElementById<HTMLDivElement>(shadowRoot, 'typing-screen-aborted');\n            screenAbortedEl.style.display = \"none\";\n\n            const screenCompleteEl = shadowRoot_getElementById<HTMLDivElement>(shadowRoot, 'typing-screen-complete');\n            screenCompleteEl.style.display = \"none\";\n\n            const summaryStatsEl = shadowRoot_getElementById<HTMLDivElement>(shadowRoot, 'summary-stats');\n\n            const stimulusEl = shadowRoot_getElementById<HTMLElement>(shadowRoot, 'typing-stimulus');\n\n            const footerEl = shadowRoot_getElementById<HTMLElement>(shadowRoot, 'typing-footer');\n\n            const inputEl = shadowRoot_getElementById<HTMLTextAreaElement>(shadowRoot, 'typing-input');\n            inputEl.placeholder = 'loading...';\n\n            const inputSendBtnEl = shadowRoot_getElementById<HTMLButtonElement>(shadowRoot, 'typing-input-send-btn');\n            inputSendBtnEl.addEventListener('click', async () => {\n                await this.handleSubmit();\n            });\n            inputEl.addEventListener('keydown', async (event) => {\n                if (!this.gameState.currentStimulus) { return; /* <<<< returns early */ }\n\n                switch (event.key) {\n                    case 'Enter':\n                        if (this.gameState.currentStimulus.value.includes('\\n')) {\n                            if (event.ctrlKey) {\n                                event.preventDefault(); // Prevent default behavior (new line)\n                                await this.handleSubmit();\n                            }\n                        } else if (!event.shiftKey) {\n                            event.preventDefault(); // Prevent default behavior (new line)\n                            await this.handleSubmit();\n                        }\n                        break;\n                    default:\n                        console.log(`${lc} event.key: ${event.key} (I: 5267a7eec5880ce5e8999e18dfdc3825)`);\n                        break;\n                }\n            });\n\n            this.elements = {\n                headerEl,\n                nameEl,\n                descEl,\n                commandBarEl,\n                // headerTabsEl,\n                contentEl,\n                screenInitEl, initAllStimuliEl, initTranslateLinkEl, initAddStimulusBtnEl, initPlayableEl, initGameTypeEl,\n                // initGameVariantEl,\n                screenReadyEl, readyCountdownEl,\n                screenPlayingEl, stimulusEl,\n                screenAbortedEl,\n                screenCompleteEl, summaryStatsEl,\n                footerEl, inputEl, inputSendBtnEl,\n            };\n\n            await this.initElements_dialog();\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    private async handleAddStimulusBtnClick(): Promise<void> {\n        const lc = `${this.lc}[${this.handleAddStimulusBtnClick.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 7ecea8e5063845f30bf6ded6d9a8d825)`); }\n\n            const newStimulusText = await this.showFullscreenDialog();\n            // if (!newStimulusText) {\n            //     console.log(`${lc} user cancelled (I: f1c6b2ecb9281eee93e8d458bebfa825)`);\n            //     return; /* <<<< returns early */\n            // }\n\n            // const newStimulusText = await promptForText({\n            //     title: 'New Text',\n            //     msg: [\n            //         `Enter the new text.`,\n            //     ].join('\\n'),\n            // });\n\n            if (newStimulusText) {\n                const newStimuli: Minigame_TypingStimulus[] = [];\n                const newLines = newStimulusText.split('\\n').filter(x => !!x);\n                for (const line of newLines) {\n                    const newStimulus: Minigame_TypingStimulus = {\n                        id: await getNewTypingEntryId(),\n                        entryType: 'text',\n                        value: line,\n                    };\n                    newStimuli.push(newStimulus);\n                }\n                await minigameBuilderEditStimuliFunctionInfo.fnViaCmd({\n                    cmd: minigameBuilderEditStimuliFunctionInfo.cmd,\n                    cmdModifiers: minigameBuilderEditStimuliFunctionInfo.cmdModifiers.concat(),\n                    minigameAddr: this.tjpAddr!,\n                    stimulusEditInfos: newStimuli.map(x => {\n                        return {\n                            action: 'add',\n                            newStimulus: x,\n                        };\n                    }),\n                });\n            } else {\n                // empty === cancelled?\n                // await alertUser({ title: 'Add Cancelled', msg: 'Add was cancelled' });\n                return; /* <<<< returns early */\n            }\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    private async validateAndReadyMinigame(): Promise<void> {\n        const lc = `${this.lc}[${this.validateAndReadyMinigame.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 41ec4768c9a2227c62e9e218e0174825)`); }\n            if (!this.tjpAddr) { throw new Error(`(UNEXPECTED) tihs.tjpAddr falsy? (E: 82126e68dbca9c0f09ce74b96ac6a825)`); }\n\n            const resReady = await minigameBuilderValidateAndReadyFunctionInfo.fnViaCmd({\n                cmd: minigameBuilderValidateAndReadyFunctionInfo.cmd,\n                cmdModifiers: minigameBuilderValidateAndReadyFunctionInfo.cmdModifiers.concat(),\n                minigameAddr: this.tjpAddr,\n            }) as MinigameBuilderValidateAndReadyResult;\n\n            if (resReady.ready) {\n                // update minigame ibgib, ui, re-render\n                await delay(100); // does minigame ibgib get changed when ready? I think it does.\n            } else if (resReady.errors) {\n                await alertUser({\n                    title: 'Minigame ain\\'t ready',\n                    msg: `The minigame is not ready yet. Here are the \"errors\":\\n${resReady.errors}`\n                });\n                return; /* <<<< returns early */\n            } else {\n                await alertUser({\n                    title: 'Minigame ain\\'t ready',\n                    msg: `The minigame is not ready yet, but there weren't any errors? This shouldn't happen and I'd appreciate it if you would let me know. (E: 6f664ad63f57e680621443581445c825).`\n                });\n                throw new Error(`(UNEXPECTED) resReady.ready is falsy, but resReady.errors is falsy? (E: 6f664ad63f57e680621443581445c825)`);\n            }\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private async flushGameStateToTimeline(): Promise<void> {\n        const lc = `${this.lc}[${this.flushGameStateToTimeline.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: f9494913d868dff83867302841524325)`); }\n\n            if (!this.metaspace) { throw new Error(`(UNEXPECTED) this.metaspace falsy? (E: 1624489054a87fce48a4d2eefc742325)`); }\n\n            this.gameState.flushCounter++;\n            await mut8Timeline({\n                timeline: this.ibGib, // minigame\n                metaspace: this.metaspace,\n                mut8Opts: {\n                    dataToAddOrPatch: { gameState: this.gameState }\n                },\n            });\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    private async flushGameMetaToTimeline(): Promise<void> {\n        const lc = `${this.lc}[${this.flushGameMetaToTimeline.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: e215cc1cfab8e0d6b71493487b01cc25)`); }\n\n            if (!this.metaspace) { throw new Error(`(UNEXPECTED) this.metaspace falsy? (E: 2596c8b0676ee038eff6f9285e76b825)`); }\n\n            // this.gameState.flushCounter++;\n            await mut8Timeline({\n                timeline: this.ibGib, // minigame\n                metaspace: this.metaspace,\n                mut8Opts: {\n                    dataToAddOrPatch: { gameMeta: this.gameMeta }\n                },\n            });\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private async handleSubmit(): Promise<void> {\n        const lc = `${this.lc}[${this.handleSubmit.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: cd9ecc08f967c93bd88a689b2cb12e25)`); }\n\n            // #region init & validation\n\n            if (!this.elements) { throw new Error(`(UNEXPECTED) this.elements falsy? (E: 046d7b8e9c4bcea148ca8d379b6d8825)`); }\n            const { inputEl, } = this.elements;\n            // const inputText = inputEl.textContent?.trim() ?? '';\n            // const inputText = inputEl.value?.trim() ?? '';\n            const inputText = inputEl.value ?? '';\n            if (!inputText) {\n                console.warn(`${lc} no text to submit. returning early. (W: dc710bf62f9422235a7bd70f39738825)`);\n                return; /* <<<< returns early */\n            }\n            inputEl.value = '';\n\n            // add the interaction\n            this.gameState.interactions.push({\n                stimulus: this.gameState.currentStimulus!,\n                response: {\n                    id: await getNewTypingEntryId(),\n                    entryType: 'text',\n                    value: inputText,\n                    timestampInTicks: getTimestampInTicks(),\n                }\n            });\n\n            const nextStimulus = this.gameState.remainingStimuli.shift();\n            if (nextStimulus) {\n                nextStimulus!.timestampInTicks = getTimestampInTicks();\n                this.gameState.currentStimulus = nextStimulus;\n                await this.flushGameStateToTimeline();\n            } else {\n                await this.flushGameStateToTimeline();\n                await this.complete();\n            }\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    // #region render\n\n    /**\n     * rerender\n     */\n    protected override async renderUI(): Promise<void> {\n        const lc = `${this.lc}[${this.renderUI.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 5bd83ba3c5018c7ea4e8352886743825)`); }\n\n            await super.renderUI();\n\n            if (!this.elements) {\n                console.warn(`${lc} (UNEXPECTED) tried to render but haven't initialized elements? (W: ed6818255128fa1914407426476d9825)`);\n                return; /* <<<< returns early */\n            }\n\n            const {\n                headerEl, contentEl, footerEl,\n                nameEl, descEl,\n                commandBarEl,\n                inputEl, inputSendBtnEl,\n                screenInitEl, initAllStimuliEl, initAddStimulusBtnEl, initPlayableEl, initGameTypeEl, initTranslateLinkEl,\n                // initGameVariantEl,\n                screenReadyEl,\n                screenPlayingEl,\n                stimulusEl,\n                screenAbortedEl,\n                screenCompleteEl,\n            } = this.elements;\n\n            const { ibGib } = this;\n            if (!ibGib) { throw new Error(`(UNEXPECTED) this.ibGib falsy? (E: 46f70849b5c13810786e6244e64e3825)`); }\n            const { data } = ibGib;\n            if (!data) { throw new Error(`(UNEXPECTED) this.ibGib.data falsy? (E: c354c842903829168fa95a5fc5142d25)`); }\n            const typingMeta = (data.gameMeta ?? DEFAULT_TYPING_GAMEMETA) as Minigame_TypingGameMeta;\n            const typingGameState = (data.gameState ?? DEFAULT_TYPING_GAMESTATE) as Minigame_TypingGameState;\n\n            // for now, not showing the header (don't know what goes there tbh)\n            headerEl.style.display = 'none';\n            nameEl.style.display = 'none';\n            descEl.style.display = 'none';\n\n            if (!!data.playable && data.gamePhase === MinigameGamePhase.playing) {\n                inputEl.readOnly = false;\n                inputSendBtnEl.disabled = true;\n            } else {\n                inputEl.readOnly = true;\n                inputSendBtnEl.disabled = false;\n            }\n\n            // show the current phase's screen\n            switch (data.gamePhase) {\n                case MinigameGamePhase.init:\n                    this.hideScreensExcept({ gamePhase: MinigameGamePhase.init });\n                    // show ready screen? depends on if we have available stimuli?\n                    initPlayableEl.textContent = data.playable ? 'true' : 'false';\n                    initGameTypeEl.textContent = data.gameType;\n                    const allStimuli = typingMeta.allStimuli ?? [];\n                    // if the stimulus is fitb, we don't want the blank, rather,\n                    // we want the full text\n                    const allStimuliText = unique(\n                        allStimuli.map(x =>\n                            x.expectedResponseType === 'fill-in-the-blank' || x.variant === 'fitb' ?\n                                (x.focus ?? x.value) :\n                                x.value\n                        ).filter(x => !!x)\n                    ).join('\\n');\n                    initTranslateLinkEl.href = getGoogleTranslateLink({ text: allStimuliText });\n\n                    initAllStimuliEl.innerHTML = '';\n                    if (allStimuli.length > 0) {\n                        for (const stimulusEntry of allStimuli!) {\n                            if (logalot) { console.log(`${lc} stimulusEntry: ${pretty(stimulusEntry)} (I: 43c238ea824472ab0857eb92b0440825)`); }\n                            if (!this.shadowRoot) { throw new Error(`(UNEXPECTED) this.shadowRoot falsy? (E: cae6982ca08696f7880bbf88e8aea325)`); }\n                            const { entryEl, deleteBtnEl, editBtnEl } = await getStimulusEntryEl({\n                                shadowRoot: this.shadowRoot,\n                                stimulusEntry,\n                            });\n                            deleteBtnEl.addEventListener('click', async () => {\n                                // delete\n                                await this.handleDeleteStimulus({ stimulusEntry });\n                            });\n                            editBtnEl.addEventListener('click', async () => {\n                                // edit\n                                await this.handleEditStimulus({ stimulusEntry });\n                            });\n\n                            // complete entry\n                            initAllStimuliEl.appendChild(entryEl);\n                        }\n                    } else {\n                        const noEntriesEl = document.createElement('li');\n                        noEntriesEl.textContent = '[no stimuli added yet]';\n                        initAllStimuliEl.appendChild(noEntriesEl);\n                    }\n                    footerEl.style.display = 'none';\n                    break;\n                case MinigameGamePhase.ready:\n                    this.hideScreensExcept({ gamePhase: MinigameGamePhase.ready });\n                    footerEl.style.display = 'none';\n\n                    // inputEl.readOnly = true;\n                    // inputSendBtnEl.disabled = true;\n                    // inputEl.placeholder = 'pretending...'; // joke on screen saying \"let's pretend that didn't happen\"\n                    break;\n                case MinigameGamePhase.playing:\n                    await this.renderUI_playing({\n                        typingGameState,\n                        stimulusEl,\n                        footerEl,\n                        inputEl,\n                        inputSendBtnEl,\n                    });\n                    break;\n                case MinigameGamePhase.paused:\n                    this.hideScreensExcept({ gamePhase: MinigameGamePhase.paused });\n                    inputEl.readOnly = true;\n                    inputSendBtnEl.disabled = true;\n                    inputEl.placeholder = 'paused...';\n                    // don't do anything? minigame parent component will show\n                    // paused screen.\n                    break;\n                case MinigameGamePhase.aborted:\n                    this.hideScreensExcept({ gamePhase: MinigameGamePhase.aborted });\n                    // anything else?\n                    footerEl.style.display = 'none';\n                    // inputEl.readOnly = true;\n                    // inputSendBtnEl.disabled = true;\n                    // inputEl.placeholder = 'pretending...'; // joke on screen saying \"let's pretend that didn't happen\"\n                    break;\n                case MinigameGamePhase.complete:\n                    this.hideScreensExcept({ gamePhase: MinigameGamePhase.complete });\n                    footerEl.style.display = 'none';\n\n                    break;\n                default:\n                    throw new Error(`(UNEXPECTED) unknown gamePhase (${data.gamePhase})? (E: 94c4d8269838dc48285589682d571825)`);\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    private async renderUI_playing({\n        typingGameState,\n        stimulusEl,\n        footerEl,\n        inputEl,\n        inputSendBtnEl,\n    }: {\n        typingGameState: Minigame_TypingGameState,\n        stimulusEl: HTMLElement,\n        footerEl: HTMLElement,\n        inputEl: HTMLTextAreaElement,\n        inputSendBtnEl: HTMLButtonElement,\n    }): Promise<void> {\n        const lc = `${this.lc}[${this.renderUI_playing.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 524a688d7724dee7ca3956083ec1de25)`); }\n\n            this.hideScreensExcept({ gamePhase: MinigameGamePhase.playing });\n            if (!typingGameState.currentStimulus) { throw new Error(`(UNEXPECTED) typingGameState.currentStimulus falsy? (E: 75fdbb36f018c2c3f707f028e7762425)`); }\n            const { currentStimulus } = typingGameState;\n            let variant: MinigameGameVariant_Typing | '' = currentStimulus.variant ?? '';\n            if (!variant) {\n                console.log(`${lc} currentStimulus.variant falsy? using default parrot (I: f2c4dbfdeb58928468377bb6d6478725)`);\n                variant = MinigameGameVariant_Typing.parrot;\n            }\n\n            // fill out the stimulus element\n            stimulusEl.innerHTML = '';\n            if (!this.shadowRoot) { throw new Error(`(UNEXPECTED) this.shadowRoot falsy even though we're within ${this.renderUI_playing.name}? (E: 34f678110cb8e5e9728c4f3eddf51625)`); }\n            const shadowRoot = this.shadowRoot;\n\n            const templateId = `playing-stimulus-template-${variant}`;\n            const templateEl = shadowRoot_getElementById<HTMLTemplateElement>(shadowRoot, templateId);\n            const templateContentNode = templateEl.content.cloneNode(true) as DocumentFragment;\n            const templateRootDiv = templateContentNode.firstElementChild;\n            if (!templateRootDiv) { throw new Error(`(UNEXPECTED) !templateDiv? (E: f30fe806a3d165660807bd278b653825)`); }\n            // const testEl = templateRootDiv.querySelector(`.playing-stimulus-test-${variant}`) as HTMLElement;\n            // if (!testEl) { throw new Error(`(UNEXPECTED) testEl falsy? (E: f6e2c8c7114b98aea80ebbb84d90e825)`); }\n            // testEl.textContent = `${variant} yo this was inserted or something`;\n            const stimulusTextDiv = templateRootDiv.querySelector(`.playing-stimulus-text`) as HTMLDivElement;\n            currentStimulus.value.split('\\n').forEach(line => {\n                const lineEl = document.createElement('p');\n                lineEl.textContent = line;\n                stimulusTextDiv.appendChild(lineEl);\n            });\n            stimulusEl.appendChild(templateRootDiv); // debug testing only\n\n            // currentStimulus.value.split('\\n').forEach(line => {\n            //     const lineEl = document.createElement('p');\n            //     lineEl.textContent = line;\n            //     stimulusEl.appendChild(lineEl);\n            // });\n            // stimulusEl.textContent = typingGameState.currentStimulus.value;\n\n            // do the footer?\n            footerEl.style.removeProperty('display'); // don't remember what this is, why is footer display:none?\n\n            // prepare input for user to type in and focus it\n            inputEl.readOnly = false;\n            const stimTextEl = templateRootDiv.querySelector('.playing-stimulus-text') as HTMLDivElement;\n            const diffEl = templateRootDiv.querySelector('.playing-stimulus-diff') as HTMLDivElement;\n            let lastLength = 0;\n            let pTagEls: HTMLParagraphElement[] = [];\n            let pCurrent: HTMLParagraphElement = document.createElement('p') as HTMLParagraphElement;\n            const fnRevealDiff = debounce(() => {\n\n                let expectedResponse = currentStimulus.expectedResponse;\n                if (variant === 'parrot' && currentStimulus.expectedResponseType === 'exact' && !expectedResponse) {\n                    expectedResponse = currentStimulus.value;\n                }\n                if (!expectedResponse) {\n                    // don't do anything\n                    return; /* <<<< returns early */\n                }\n                const inputSoFarLength = inputEl.value.length;\n                if (inputSoFarLength === 0) {\n                    return; /* <<<< returns early */\n                }\n\n                if (inputEl.value && expectedResponse && inputEl.value.toLocaleLowerCase() === expectedResponse.toLocaleLowerCase()) {\n                    // the same\n                    inputEl.readOnly = true;\n                    const durationMs = 1000;\n                    highlightElement({ el: this, magicHighlightTimingMs: durationMs }); // spin off\n                    slideRightAndFade({ el: this, durationMs });\n                    setTimeout(async () => {\n                        diffEl.innerHTML = '';\n                        unfadeEl({ el: this });\n                        inputEl.readOnly = false;\n                        await this.handleSubmit();\n                    }, durationMs);\n                }\n                const inputAsChars = inputEl.value.substring(0, inputSoFarLength).split('');\n                const expectedResponseAsChars = expectedResponse.substring(0, inputSoFarLength).split('');\n\n                if (inputSoFarLength === (lastLength + 1)) {\n                    // just added a letter or new paragraph, so don't clear\n                    const expectedChar = expectedResponseAsChars.at(-1)!;\n                    if (expectedChar === '\\n') {\n                        // add a new paragraph to diff\n                        pCurrent = document.createElement('p') as HTMLParagraphElement;\n                        pTagEls.push(pCurrent);\n                        diffEl.appendChild(pCurrent);\n                    } else {\n                        // add a new letter to diff\n                        const inputChar = inputAsChars.at(-1)!;\n                        // add to existing paragraph\n                        pCurrent = pTagEls.at(-1)!;\n                        if (!pCurrent) {\n                            pCurrent = document.createElement('p') as HTMLParagraphElement;\n                            pTagEls.push(pCurrent);\n                            diffEl.appendChild(pCurrent);\n                        }\n                        const charSpan = document.createElement('span') as HTMLSpanElement;\n                        charSpan.textContent = expectedChar;\n\n                        if (expectedChar.match(/[\\p{L}\\d]/iu)) {\n                            // it's an alphanumeric\n                            if (inputChar.toLocaleLowerCase() === expectedChar.toLocaleLowerCase()) {\n                                charSpan.style.color = 'green';\n                            } else {\n                                charSpan.style.color = 'red';\n                            }\n                        } else {\n                            // it's punctuation or whatever, don't care\n                            charSpan.style.color = 'gray';\n                        }\n                        pCurrent!.appendChild(charSpan);\n                        // pCurrent.scrollIntoView({ behavior: 'instant' });\n                        charSpan.scrollIntoView({ behavior: 'instant' });\n                        // need to scroll text view to match current place\n\n                        stimTextEl.children.item(pTagEls.length - 1)!.scrollIntoView({ behavior: 'smooth' });\n                    }\n                    lastLength++;\n                } else {\n                    // did NOT just add a letter/new p, so start everything fresh\n                    diffEl.innerHTML = '';\n                    pTagEls = [];\n                    pCurrent = document.createElement('p') as HTMLParagraphElement;\n                    pTagEls.push(pCurrent);\n                    diffEl.appendChild(pCurrent);\n                    for (let i = 0; i < inputSoFarLength; i++) {\n                        const inputChar = inputAsChars.at(i) ?? '';\n                        const expectedChar = expectedResponseAsChars.at(i) ?? '';\n                        if (expectedChar === '\\n') {\n                            pCurrent = document.createElement('p') as HTMLParagraphElement;\n                            pTagEls.push(pCurrent);\n                            diffEl.appendChild(pCurrent);\n                        } else {\n                            // add to existing paragraph\n                            pCurrent = pTagEls.at(-1)!;\n                            const charSpan = document.createElement('span') as HTMLSpanElement;\n                            charSpan.textContent = expectedChar;\n\n                            if (expectedChar.match(/[\\p{L}\\d]/iu)) {\n                                // it's an alphanumeric\n                                if (inputChar.toLocaleLowerCase() === expectedChar.toLocaleLowerCase()) {\n                                    charSpan.style.color = 'green';\n                                } else {\n                                    charSpan.style.color = 'red';\n                                }\n                            } else {\n                                // it's punctuation or whatever, don't care\n                                charSpan.style.color = 'gray';\n                            }\n                            pCurrent!.appendChild(charSpan);\n                            // pCurrent.scrollIntoView({ behavior: 'instant' });\n                            charSpan.scrollIntoView({ behavior: 'instant' });\n                            // need to scroll text view to match current place\n                        }\n                        stimTextEl.children.item(pTagEls.length - 1)!.scrollIntoView({ behavior: 'smooth' });\n                    }\n                    lastLength = inputSoFarLength;\n                }\n            }, shadowRoot_getElementById<HTMLInputElement>(shadowRoot, 'typing-stimulus-feedback-debounce-ms').valueAsNumber);\n            if ((inputEl as any).handlerDiffFn) {\n                inputEl.removeEventListener('input', (inputEl as any).handlerDiffFn);\n                delete (inputEl as any).handlerDiffFn;\n            }\n            inputEl.addEventListener('input', fnRevealDiff);\n            (inputEl as any).handlerDiffFn = fnRevealDiff;\n            inputSendBtnEl.disabled = false;\n            this.renderUI_updateInput();\n            this.elements!.inputEl.focus();\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    private renderUI_updateInput(): void {\n        const lc = `${this.lc}[${this.renderUI_updateInput.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 1a209f8132f4741e6ff1ede8ae52a825)`); }\n            const { elements, gameState } = this;\n            if (!elements) { throw new Error(`(UNEXPECTED) this.elements falsy? (E: 47ce681aed9815e1c40585a9ffec4225)`); }\n            const { inputEl, } = elements;\n            if (gameState.currentStimulus) {\n                if (gameState.currentStimulus.value.includes('\\n')) {\n                    inputEl.placeholder = 'CTRL+ENTER to send';\n                } else {\n                    inputEl.placeholder = 'ENTER to send\\nSHIFT+ENTER for new line';\n                }\n            } else {\n                inputEl.placeholder = 'loading...';\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    private renderUI_readyCountdown() {\n        const lc = `${this.lc}[${this.renderUI_readyCountdown.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 054198a33328cb3488f2189b87b20a25)`); }\n            this.elements!.readyCountdownEl.textContent = this.readyCountdown.toString();\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private async handleEditStimulus({\n        stimulusEntry\n    }: {\n        stimulusEntry: Minigame_TypingStimulus;\n    }): Promise<void> {\n        const lc = `${this.lc}[${this.handleEditStimulus.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: dee12593b7a5d35e787bf218e450b625)`); }\n\n            const newStimulusText = await promptForText({\n                title: 'New Text',\n                msg: [\n                    `Enter the new text.`,\n                    ``,\n                    `original text: `,\n                    stimulusEntry.value,\n                ].join('\\n'),\n                defaultValue: stimulusEntry.value,\n                cancelable: true,\n            });\n\n            if (newStimulusText) {\n                if (newStimulusText === stimulusEntry.value) {\n                    // no change\n                    console.log(`${lc} no change to stimulus. ${newStimulusText} (I: b91e888648e8f6d62f5a9268ae393925)`);\n                    return; /* <<<< returns early */\n                }\n                const newStimulus = clone(stimulusEntry);\n                newStimulus.value = newStimulusText;\n                await minigameBuilderEditStimuliFunctionInfo.fnViaCmd({\n                    cmd: minigameBuilderEditStimuliFunctionInfo.cmd,\n                    cmdModifiers: minigameBuilderEditStimuliFunctionInfo.cmdModifiers.concat(),\n                    minigameAddr: this.tjpAddr!,\n                    stimulusEditInfos: [\n                        {\n                            action: 'edit',\n                            stimulusId: stimulusEntry.id,\n                            newStimulus,\n                        }\n                    ],\n                });\n            } else {\n                // empty === cancelled?\n                console.log(`${lc} user cancelled edit. (I: fe83a4ed0b35421e8857779179c72825)`)\n                return; /* <<<< returns early */\n            }\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    private async handleDeleteStimulus({\n        stimulusEntry\n    }: {\n        stimulusEntry: Minigame_TypingStimulus;\n    }): Promise<void> {\n        const lc = `${this.lc}[${this.handleDeleteStimulus.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 4d97089e0e18307aaff0a838bdec6d25)`); }\n\n            // const confirmDelete = await promptForConfirm({\n            //     msg: [\n            //         `Delete stimulus?`,\n            //         ``,\n            //         `Stimulus Text:`,\n            //         stimulusEntry.value,\n            //     ].join('\\n'),\n            //     yesLabel: `yes, DELETE it.`,\n            //     noLabel: `no, let's KEEP it.`\n            // });\n            const confirmDelete = true;\n\n            if (confirmDelete) {\n                await minigameBuilderEditStimuliFunctionInfo.fnViaCmd({\n                    cmd: minigameBuilderEditStimuliFunctionInfo.cmd,\n                    cmdModifiers: minigameBuilderEditStimuliFunctionInfo.cmdModifiers.concat(),\n                    minigameAddr: this.tjpAddr!,\n                    stimulusEditInfos: [\n                        {\n                            action: 'delete',\n                            stimulusId: stimulusEntry.id,\n                        }\n                    ],\n                });\n            } else {\n                console.log(`${lc} user cancelled delete. (I: c273d8abe43fd99e28b716187fdca825)`)\n            }\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private hideScreensExcept({\n        gamePhase\n    }: {\n        gamePhase: MinigameGamePhase;\n    }): void {\n        if (gamePhase === MinigameGamePhase.paused) {\n            // handled by the parent wrapper minigame component\n            return; /* <<<< returns early */\n        }\n        const { screenInitEl, screenReadyEl, screenPlayingEl, screenAbortedEl, screenCompleteEl } = this.elements!;\n\n        const screenMap: { [key: string]: any } = {\n            [MinigameGamePhase.init]: screenInitEl,\n            [MinigameGamePhase.ready]: screenReadyEl,\n            [MinigameGamePhase.playing]: screenPlayingEl,\n            [MinigameGamePhase.complete]: screenCompleteEl,\n            [MinigameGamePhase.aborted]: screenAbortedEl,\n        };\n        const exceptEl = screenMap[gamePhase] as HTMLElement;\n        exceptEl.style.removeProperty('display');\n        delete screenMap[gamePhase];\n        Object.values(screenMap).forEach(screen => {\n            screen.style.display = 'none';\n        });\n    }\n\n    // private buildStats(): Promise<MinigameTypingStats> {\n    //     const lc = `${this.lc}[${this.buildStats.name}]`;\n    //     try {\n    //         if (logalot) { console.log(`${lc} starting... (I: c760c583d96f1349d8e63a88567ad325)`); }\n    //         // unique words\n    //     } catch (error) {\n    //         console.error(`${lc} ${extractErrorMsg(error)}`);\n    //         throw error;\n    //     } finally {\n    //         if (logalot) { console.log(`${lc} complete.`); }\n    //     }\n    // }\n    // #endregion render\n\n    private dialogSrcAddr: IbGibAddr | undefined;\n    private dialogSrcAddr_latest: IbGibAddr | undefined;\n    private dialogSrcIbGib_latest: IbGib_V1 | undefined;\n    private _dialogSrcText: string | undefined;\n    private get dialogSrcText(): string | undefined {\n        return this._dialogSrcText ?? this.dialogSrcIbGib_latest?.data?.text;\n    }\n    private dialogFocuses: FocusAndElementsInfo[] = [];\n    private dialogStimuliToAdd: TypingEntryAndElementsInfo[] = [];\n\n    private get dialogLanguageOptionsApplicable(): boolean {\n        if (!this.shadowRoot) { return false; }\n        const languageOptionsCheckboxEl = shadowRoot_getElementById<HTMLInputElement>(this.shadowRoot, 'typing-fullscreen-dialog-language-options-checkbox');\n        return languageOptionsCheckboxEl.checked;\n    }\n\n    async initElements_dialog(): Promise<void> {\n        const lc = `${this.lc}[${this.initElements_dialog.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 477e148762a887a168da926f66bb4825)`); }\n\n            const { shadowRoot } = this;\n            if (!shadowRoot) { throw new Error(`(UNEXPECTED) this.shadowRoot falsy? (E: 87d6d777abb1b69635d9699814c0e825)`); }\n\n            // const dialog = shadowRoot_getElementById<HTMLDialogElement>(shadowRoot, 'typing-fullscreen-dialog');\n            const dialogErrors = shadowRoot_getElementById<HTMLDialogElement>(shadowRoot, 'typing-fullscreen-dialog-errors');\n\n            const srcTextTextArea = shadowRoot_getElementById<HTMLTextAreaElement>(shadowRoot, 'typing-fullscreen-dialog-src-text');\n            const srcTextChanged = async (event: Event) => {\n                const newText = srcTextTextArea.value ?? '';\n                if (newText !== this._dialogSrcText) {\n                    this._dialogSrcText = newText;\n                }\n            }\n            srcTextTextArea.addEventListener('input', debounce(srcTextChanged, 1_000));\n\n            const fnSrcIbGibIsInvalid = (errorMsg: string) => {\n                dialogErrors.textContent = errorMsg;\n                dialogErrors.style.display = 'flex';\n                delete this.dialogSrcAddr;\n                delete this.dialogSrcAddr_latest;\n                delete this.dialogSrcIbGib_latest;\n            }\n            const fnSrcIbGibIsValid = () => {\n                dialogErrors.style.display = 'none';\n                this._dialogSrcText = this.dialogSrcIbGib_latest?.data?.text;\n                srcTextTextArea.value = this.dialogSrcText ?? '';\n            }\n\n            const fnGetSrc_latest: ((addr: IbGibAddr) => Promise<IbGib_V1 | string>) = async (addr: IbGibAddr) => {\n                const lcGetSrc = `${lc}[fnGetSrc]`;\n                try {\n                    if (logalot) { console.log(`${lcGetSrc} starting... (I: 285632f7b26828f2be3630b5b24dd525)`); }\n                    if (!this.metaspace) { throw new Error(`(UNEXPECTED) this.metaspace falsy? (E: ae2ea5c2bb0ba54e04e32548ccf31b25)`); }\n                    const space = await this.metaspace.getLocalUserSpace({ lock: false });\n                    if (!space) { throw new Error(`(UNEXPECTED) couldn't get default local user space? (E: 185e78c4dbca1cbc5866f728a59c4825)`); }\n                    const latestAddr = await this.metaspace.getLatestAddr({ addr, space }) ?? addr;\n                    const resGet = await this.metaspace.get({ addr: latestAddr, space, });\n                    if (resGet.errorMsg || (resGet.ibGibs?.length !== 1)) { throw new Error(`addr not found. ${resGet.errorMsg ?? ''} (E: 44dfecdf7f68e0f3084d2e9fc1adca25)`); }\n                    return resGet.ibGibs!.at(0)!;\n                } catch (error) {\n                    const emsg = extractErrorMsg(error);\n                    console.error(`${lcGetSrc} ${emsg}`);\n                    return emsg;\n                } finally {\n                    if (logalot) { console.log(`${lcGetSrc} complete.`); }\n                }\n            };\n            const srcAddrInput = shadowRoot_getElementById<HTMLInputElement>(shadowRoot, 'typing-fullscreen-dialog-src-addr');\n            const fnSrcAddrChanged = async (event: Event) => {\n                const srcAddr: IbGibAddr = srcAddrInput.value.trim();\n                const srcAddrErrors = validateIbGibAddr({ addr: srcAddr }) ?? [];\n                if (srcAddrErrors.length > 0) {\n                    fnSrcIbGibIsInvalid(`Invalid srcAddr: ${srcAddrErrors.join('\\n')}`);\n                    return; /* <<<< returns early */\n                }\n                const srcIbGibOrEmsg = await fnGetSrc_latest(srcAddr);\n                if (typeof srcIbGibOrEmsg === 'string') {\n                    // if it's a string, then it's the error msg\n                    fnSrcIbGibIsInvalid(`Coudn't get ibgib: ${srcIbGibOrEmsg}`);\n                    return; /* <<<< returns early */\n                }\n                const srcIbGib_latest = srcIbGibOrEmsg as IbGib_V1;\n                if (!srcIbGib_latest.data?.text) {\n                    fnSrcIbGibIsInvalid(`Src ibgib.data.text is empty or doesn't exist.`);\n                    return; /* <<<< returns early */\n                }\n                // we have a valid src text\n                if (this._dialogSrcText) {\n                    const confirm = await promptForConfirm({\n                        msg: `Overwrite your existing src text with the one from addr:\\n\\n\"${getIbAndGib({ ibGibAddr: srcAddr }).ib}\"?`,\n                        yesLabel: `YES, don't need the existing text`,\n                        noLabel: `NO, wait a sec`\n                    });\n                    if (!confirm) {\n                        console.log(`${lc} user cancelled`);\n                        return; /* <<<< returns early */\n                    }\n                }\n                this.dialogSrcAddr = srcAddr;\n                this.dialogSrcAddr_latest = getIbGibAddr({ ibGib: srcIbGib_latest });\n                this.dialogSrcIbGib_latest = srcIbGib_latest;\n                fnSrcIbGibIsValid();\n            };\n            srcAddrInput.addEventListener('input', debounce(fnSrcAddrChanged, 1_000));\n            if (this.dialogSrcAddr) {\n                srcAddrInput.value = this.dialogSrcAddr;\n            }\n\n            const infoFocusBtn = shadowRoot_getElementById<HTMLButtonElement>(shadowRoot, 'typing-fullscreen-dialog-focuses-info-btn');\n            infoFocusBtn.addEventListener('click', () => {\n                alertUser({\n                    title: 'Focuses? What are they?',\n                    msg: MINIGAME_FOCUS_INFO,\n                });\n            });\n            const addFocusBtn = shadowRoot_getElementById<HTMLButtonElement>(shadowRoot, 'typing-fullscreen-dialog-add-focus-btn');\n            // typing-fullscreen-dialog-add-stimuli-btn\n            addFocusBtn.addEventListener('click', async () => {\n                await this.addFocus({ shadowRoot });\n            });\n\n            // language div\n            const languageDetailsDiv = shadowRoot_getElementById<HTMLElement>(shadowRoot, 'typing-fullscreen-dialog-language-details');\n            const languageOptionsCheckboxEl = shadowRoot_getElementById<HTMLInputElement>(shadowRoot, 'typing-fullscreen-dialog-language-options-checkbox');\n            const srcLanguageEl = shadowRoot_getElementById<HTMLInputElement>(shadowRoot, 'typing-fullscreen-dialog-text-language-input');\n            const targetLanguageEl = shadowRoot_getElementById<HTMLInputElement>(shadowRoot, 'typing-fullscreen-dialog-target-language-input');\n\n            const fnUpdateSrcAndTargetLanguage = async (languageCode: string) => {\n                srcLanguageEl.value = languageCode;\n                targetLanguageEl.value = languageCode;\n            }\n            let checkboxing = false;\n            const fnHandleAutoTranslateCheckboxInput = async () => {\n                if (checkboxing) { return; /* <<<< returns early */ }\n                checkboxing = true;\n                try {\n                    if (this.dialogLanguageOptionsApplicable) {\n                        languageDetailsDiv.style.display = 'flex';\n                    } else {\n                        languageDetailsDiv.style.display = 'none';\n                    }\n                    if (this.agent &&\n                        this.dialogSrcText &&\n                        languageOptionsCheckboxEl.checked &&\n                        !srcLanguageEl.value\n                    ) {\n                        // update the source & target languages, if not already selected\n                        const srcLanguage = await this.agent.promptOneOff({\n                            text: [\n                                `Hi. Please identify the language of the context src text. Choose from among the following codes, or if it is not listed, give your best guess using a similar ISO 639 code. `,\n                                DEFAULT_ISO_639_LANGUAGE_CODES.join('\\n'),\n                            ].join('\\n'),\n                            systemInstructions: [\n                                'You are an expert translator and are helping the user learn a foreign language. The context source text for translating is:',\n                                '```',\n                                this.dialogSrcText,\n                                '```',\n                                `In your response, don't use a full sentence, just say the code. So if the language is Italian, just say \"it-IT\" and not \"The language code is it-IT\" or anything similar.`,\n                                `Thank you in advance! ;-)`,\n                            ].join('\\n'),\n                        });\n                        if (srcLanguage) { await fnUpdateSrcAndTargetLanguage(srcLanguage); }\n                    }\n                } catch (error) {\n                    console.error(`${lc}[fnHandleAutoTranslateCheckboxInput] ${extractErrorMsg(error)}`);\n                    throw error;\n                } finally {\n                    checkboxing = false;\n                }\n            }\n            // languageOptionsCheckboxEl.addEventListener('change', async () => {\n            //     await fnHandleAutoTranslateCheckboxInput();\n            // });\n            languageOptionsCheckboxEl.addEventListener('change', fnHandleAutoTranslateCheckboxInput);\n\n\n            const infoStimuliToAddBtn = shadowRoot_getElementById<HTMLButtonElement>(shadowRoot, 'typing-fullscreen-dialog-output-info-btn');\n            infoStimuliToAddBtn.addEventListener('click', () => {\n                alertUser({\n                    title: 'Stimuli to Add? What are these stimuli?',\n                    msg: MINIGAME_STIMULTI_TO_ADD_INFO,\n                });\n            });\n\n            const fnAddStimuliToMinigame = async () => {\n                if (this.dialogFocuses.length === 0) {\n                    await alertUser({\n                        title: `doh`,\n                        msg: `First, you must add some focuses. These are used to generate stimuli. The point of stimuli is to present a focus.`,\n                    });\n                }\n                for (const focusInfo of this.dialogFocuses) {\n                    const stimulusEntry = await this.getDialogStimulusEntry({\n                        focusInfo,\n                        shadowRoot,\n                    });\n\n                    const containerEl = shadowRoot_getElementById(shadowRoot, 'typing-fullscreen-dialog-prompt-new-stimuli-div');\n                    const info = await getStimulusEntryEl({\n                        shadowRoot,\n                        stimulusEntry,\n                    });\n                    info.deleteBtnEl.addEventListener('click', () => {\n                        this.dialogStimuliToAdd = this.dialogStimuliToAdd.filter(x => x.deleteBtnEl === info.deleteBtnEl);\n                        containerEl.removeChild(info.entryEl);\n                    });\n                    info.editBtnEl.addEventListener('click', () => {\n                        alertUser({ msg: 'Doh, not implemented yet. Donate some funding and/or your time!' });\n                    });\n                    containerEl.appendChild(info.entryEl);\n                    this.dialogStimuliToAdd.push(info);\n\n                }\n                this.dialogFocuses.forEach(x => { x.deleteBtnEl.click(); });\n                this.dialogFocuses = [];\n            }\n            // const addStimuliBtn = shadowRoot_getElementById<HTMLButtonElement>(shadowRoot, 'typing-fullscreen-dialog-add-stimuli-btn');\n            // addStimuliBtn.addEventListener('click', async () => );\n\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    private async addFocus({\n        shadowRoot,\n    }: {\n        shadowRoot: ShadowRoot,\n    }): Promise<void> {\n        const lc = `${this.lc}[${this.addFocus.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 13fb18f9c2887521c884b10ea88c1825)`); }\n\n            const focusLevelEl = shadowRoot_getElementById<HTMLSelectElement>(shadowRoot, 'typing-fullscreen-dialog-focus-level');\n            const focusNumberEl = shadowRoot_getElementById<HTMLInputElement>(shadowRoot, 'typing-fullscreen-dialog-focus-number');\n\n            if (!this.dialogSrcIbGib_latest?.data?.text) { throw new Error(`(UNEXPECTED) this.dialogSrcIbGib_latest?.data?.text? (E: 5812986eeb78b13dce50064f868df825)`); }\n            if (!this.dialogSrcText) {\n                await alertUser({\n                    msg: [\n                        `No source text! `,\n                        `Add some text via the src address and/or edit it yourself, then try again. `,\n                        `(E: 6ede88b39d6e8bf8581d486892c01225)`,\n                    ].join('\\n')\n                })\n                return; /* <<<< returns early */\n            }\n\n            const existingStimuli: Minigame_TypingStimulus[] = this.ibGib?.data?.gameMeta?.allStimuli ?? [];\n\n            // if () { throw new Error(`(UNEXPECTED) this.gameMeta.allStimuli falsy? we are expecting at this point to be a valid game and thus this should be truthy, even if empty. (E: genuuid)`); }\n\n            const focusRandomize = shadowRoot_getElementById<HTMLInputElement>(shadowRoot, 'typing-fullscreen-dialog-focus-randomize').checked;\n            const focusNumberToAdd = Number.parseInt(focusNumberEl.value || '1');\n            for (let i = 0; i < focusNumberToAdd; i++) {\n                const someFocusText = await getAnotherFocusText({\n                    text: this.dialogSrcText,\n                    focusLevel: focusLevelEl.selectedOptions.item(0)?.value as TypingFocusLevel,\n                    existingFocuses: unique([\n                        ...this.dialogFocuses.map(x => x.focusText),\n                        ...existingStimuli.filter(x => !!x.focus).map(x => x.focus!),\n                        ...existingStimuli.map(x => x.value)\n                    ]),\n                    randomize: focusRandomize,\n                });\n                if (someFocusText) {\n                    const dialogFocus = await getFocusAndElementsInfo({\n                        agent: this.agent,\n                        shadowRoot,\n                        dialogSrcText: this.dialogSrcText,\n                        text: someFocusText,\n                        language: undefined, // need to change this\n                        fnHandleStimuliGenerated: async (stimuli) => {\n                            for (const stimulusEntry of stimuli) {\n                                const containerEl = shadowRoot_getElementById(shadowRoot, 'typing-fullscreen-dialog-prompt-new-stimuli-div');\n                                const info = await getStimulusEntryEl({\n                                    shadowRoot,\n                                    stimulusEntry,\n                                });\n                                info.deleteBtnEl.addEventListener('click', () => {\n                                    this.dialogStimuliToAdd = this.dialogStimuliToAdd.filter(x => x.deleteBtnEl === info.deleteBtnEl);\n                                    containerEl.removeChild(info.entryEl);\n                                });\n                                // info.editBtnEl.addEventListener('click', () => {\n                                //     alertUser({ msg: 'Doh, not implemented yet. Donate some funding and/or your time!' });\n                                // });\n                                containerEl.appendChild(info.entryEl);\n                                this.dialogStimuliToAdd.push(info);\n                            }\n                        },\n                    });\n                    this.dialogFocuses.push(dialogFocus);\n                    const focusesDivEl = shadowRoot_getElementById(shadowRoot, 'typing-fullscreen-dialog-focuses-div');\n                    focusesDivEl.appendChild(dialogFocus.entryEl);\n                    dialogFocus.deleteBtnEl.addEventListener('click', () => {\n                        focusesDivEl.removeChild(dialogFocus.entryEl);\n                        this.dialogFocuses = this.dialogFocuses.filter(x => x !== dialogFocus);\n                    });\n                    // info.editBtnEl.addEventListener('click', async () => {\n                    //     let newText = await promptForText({\n                    //         msg: `Original text:\\n\\n${info.focusText}\\n\\nEnter new text.`,\n                    //         defaultValue: info.focusText,\n                    //     });\n                    //     if (newText) {\n                    //         info.focusText = newText;\n                    //         info.textEl.textContent = newText;\n                    //     } else {\n                    //         console.log(`${lc} user cancelled editing focus text (I: genuuid)`);\n                    //         return; /* <<<< returns early */\n                    //     }\n                    // });\n                } else {\n                    alertUser({ title: `no mas words`, msg: `You have nothing new to focus on! Maybe do it manually if you're sure?` });\n                    break;\n                }\n            }\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * @internal generate the stimulus entry given the parameters set on the add\n     * stimuli dialog\n     */\n    private async getDialogStimulusEntry({\n        focusInfo,\n        shadowRoot,\n    }: {\n        focusInfo: FocusAndElementsInfo;\n        shadowRoot: ShadowRoot,\n    }): Promise<Minigame_TypingStimulus> {\n        const lc = `${this.lc}[${this.getDialogStimulusEntry.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 10f445688d09bd6508feaf18fab51825)`); }\n\n            if (this.dialogLanguageOptionsApplicable) {\n                /* returns early */\n                return await this.getDialogStimulusEntry_language({ focusInfo, shadowRoot });\n            }\n\n\n            // create one stimulus per focus\n            // need to make an enum construct or reuse an existing one?\n            // const stimulusTypes: string[] = [\n            //     'parrot',\n            //     'fitb',\n            // ];\n            const inputParrot = shadowRoot_getElementById<HTMLInputElement>(shadowRoot, 'stimuli-type-parrot');\n            const inputFitb = shadowRoot_getElementById<HTMLInputElement>(shadowRoot, 'stimuli-type-fitb');\n\n            // need to analyze a little for fitb applicability (don't blank out single word stimulus)\n            const engine = new AnalysisEngine([\n                DEFAULT_TOKEN_CONSTRUCT_RULE,\n            ]);\n            const analysis = engine.analyze({ text: focusInfo.focusText });\n            const tokenInfo = analysis.constructs[DEFAULT_TOKEN_CONSTRUCT_RULE.name];\n            const uniqueTokens = Object.keys(tokenInfo);\n\n            const availableVariants: MinigameGameVariant_Typing[] = [];\n            if (inputParrot.checked) {\n                availableVariants.push(MinigameGameVariant_Typing.parrot);\n            }\n            if (inputFitb.checked && uniqueTokens.length > 1) {\n                // don't blank out single-token text\n                availableVariants.push(MinigameGameVariant_Typing.fitb);\n            }\n            if (availableVariants.length === 0) {\n                throw new Error(`There aren't any available stimuli types. Remember fill-in-the-blank requires more than one word. (E: c2c008cf02ad41b7df806ad8aa221825)`);\n            }\n            const variant = pickRandom({ x: availableVariants });\n            let stimulusText: string;\n            let expectedResponse: string;\n            let expectedResponseType: ExpectedResponseType;\n            switch (variant) {\n                case 'parrot':\n                    stimulusText = focusInfo.focusText;\n                    expectedResponse = focusInfo.focusText;\n                    expectedResponseType = ExpectedResponseType.exact;\n                    break;\n                case 'fitb':\n                    /** guaranteed to be alphanumeric */\n                    const blankedText = pickRandom({ x: uniqueTokens });\n                    if (!blankedText) { throw new Error(`(UNEXPECTED) couldn't find a blankedText? (E: 9e1b4b2084b30fe9d30d35d4d4aaed25)`); }\n                    const regex = new RegExp(blankedText, 'i'); // i = case-insensitive\n                    // stimulusText = focusInfo.text.replace(regex, ''.padStart(blankedText.length, '_'));\n                    stimulusText = focusInfo.focusText.replace(regex, ''.padStart(4, '_'));\n                    expectedResponse = blankedText;\n                    expectedResponseType = ExpectedResponseType.fitb;\n                    break;\n                default:\n                    throw new Error(`(UNEXPECTED) variant of (${variant})? only expecting parrot, fitb (E: 65c09858939bfa859475e9a8ae69d825)`);\n            }\n\n            // const stimulusText = await this.buildStimulusText();\n            // const stimulusText = 'some stimulus text based on the focus and existing stuff';\n            // const expectedResponse = 'some response';\n            // const expectedResponseType = ExpectedResponseType.exact;\n            const language = 'en-US';\n\n            const stimulusEntry: Minigame_TypingStimulus = {\n                id: await getNewTypingEntryId(),\n                entryType: 'text',\n                variant,\n                value: stimulusText,\n                expectedResponse,\n                expectedResponseType,\n                language,\n                focus: focusInfo.focusText,\n                notes: `auto-generated from user`,\n                timestampInTicks: getTimestampInTicks(),\n            };\n\n            return stimulusEntry;\n        } catch (error) {\n            alertUser({ title: 'oops', msg: extractErrorMsg(error) });\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private getDialogStimulusEntry_language({\n        focusInfo,\n        shadowRoot,\n    }: {\n        focusInfo: FocusAndElementsInfo;\n        shadowRoot: ShadowRoot,\n    }): Promise<Minigame_TypingStimulus> {\n        const lc = `${this.lc}[${this.getDialogStimulusEntry_language.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 0a7dc87c92a82cbf26731fe866958825)`); }\n\n\n            // create one or more stimuli depending on language goal\n            // const goalEl = shadowRoot_getElementById<HTMLSelectElement>(shadowRoot, 'typing-fullscreen-dialog-language-goal');\n            // const selectedOption = goalEl.options[goalEl.selectedIndex];\n            // const goal = selectedOption.value;\n            // switch (goal) {\n            //     case 'recognize':\n            //         // parrot/fitb\n            //         break;\n            //     case 'understand':\n            //         // parrot/fitb\n            //         // target -> native\n            //         // target -> pic (future)\n            //         break;\n            //     case 'speak':\n            //         // parrot/fitb\n            //         // target -> native\n            //         // target -> pic (future)\n            //         // native -> target\n            //         break;\n            //     case 'think':\n            //         // parrot/fitb\n            //         // target -> native\n            //         // target -> pic (future)\n            //         // native -> target\n            //         // target -> target/definition (in target)\n            //         break;\n            //     default:\n            //         throw new Error(`(UNEXPECTED) goal is ${goal}? Should be one of recognize, understand, speak, think. (E: 33008510b7183ce6d8d05445efeae825)`);\n            // }\n\n\n            throw new Error(`not implemented (E: 61a3091ea4aa4bc7c823df183d4d6825)`);\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    async showFullscreenDialog(): Promise<string | undefined> {\n        const lc = `[${this.showFullscreenDialog.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n            return new Promise<string | undefined>(async (resolve, _reject) => {\n\n                const { shadowRoot } = this;\n                if (!shadowRoot) { throw new Error(`(UNEXPECTED) this.shadowRoot falsy? (E: 87d6d777abb1b69635d9699814c0e825)`); }\n                const dialog = shadowRoot_getElementById<HTMLDialogElement>(shadowRoot, 'typing-fullscreen-dialog');\n                const dialogBody = shadowRoot_getElementById<HTMLDialogElement>(shadowRoot, 'typing-fullscreen-dialog-body');\n\n                // const promptInput = shadowRoot_getElementById<HTMLTextAreaElement>(shadowRoot, 'typing-fullscreen-dialog-prompt-input');\n                const okButton = shadowRoot_getElementById<HTMLButtonElement>(shadowRoot, 'typing-fullscreen-dialog-ok-button');\n                const cancelButton = shadowRoot_getElementById<HTMLButtonElement>(shadowRoot, 'typing-fullscreen-dialog-cancel-button');\n\n                // elements to reset\n                const dialogSrcAddrEl = shadowRoot_getElementById<HTMLInputElement>(shadowRoot, 'typing-fullscreen-dialog-src-addr');\n                const dialogSrcTextEl = shadowRoot_getElementById(shadowRoot, 'typing-fullscreen-dialog-src-text');\n                const focusesDiv = shadowRoot_getElementById(shadowRoot, 'typing-fullscreen-dialog-focuses-div');\n                const stimuliDiv = shadowRoot_getElementById(shadowRoot, 'typing-fullscreen-dialog-prompt-new-stimuli-div');\n\n                const fnResetDialog = () => {\n                    dialogSrcAddrEl.value = '';\n                    dialogSrcTextEl.innerHTML = '';\n                    focusesDiv.innerHTML = '';\n                    stimuliDiv.innerHTML = '';\n                    this.dialogSrcAddr = undefined;\n                    this.dialogSrcAddr_latest = undefined;\n                    this.dialogSrcIbGib_latest = undefined;\n                    this._dialogSrcText = undefined;\n                    this.dialogFocuses = [];\n                    this.dialogStimuliToAdd = [];\n                }\n                const removeEventListeners = () => {\n                    okButton.removeEventListener('click', onOK);\n                    cancelButton.removeEventListener('click', onCancel);\n                    dialog.removeEventListener('close', onClose); // Remove dialog-level listener too\n                };\n\n                // #region wire up - these all should be in removeEventListeners\n                /** user clicks OK or hits \"ENTER\" in input */\n                const onOK = async () => {\n                    removeEventListeners();\n                    // let result = promptInput.value ?? '';\n                    // promptInput.value = '';  // Clear input for next time\n                    // move this.dialogFocuses to fully fledged stimuli\n\n                    await minigameBuilderEditStimuliFunctionInfo.fnViaCmd({\n                        cmd: minigameBuilderEditStimuliFunctionInfo.cmd,\n                        cmdModifiers: minigameBuilderEditStimuliFunctionInfo.cmdModifiers.concat(),\n                        minigameAddr: this.tjpAddr!,\n                        stimulusEditInfos: this.dialogStimuliToAdd.map(x => {\n                            return {\n                                action: 'add',\n                                newStimulus: x.stimulusEntry,\n                            };\n                        }),\n                    });\n                    fnResetDialog();\n                    dialog.close(undefined); //\n                    resolve(undefined);\n                };\n                okButton.addEventListener('click', onOK);\n                /** user actively clicks Cancel */\n                const onCancel = async () => {\n                    removeEventListeners();\n                    fnResetDialog();\n                    dialog.close(undefined); //\n                    resolve(undefined);\n                };\n                cancelButton.addEventListener('click', onCancel);\n                /**\n                 * Handle dialog.close() without button click (e.g., Esc key)\n                 *\n                 * NOTE: this does not trigger when dialog.close() is executed. This\n                 * is only firing when esc is pressed.\n                 */\n                const onClose = async () => {\n                    console.log(`${lc} onClose (I: 0a97e8f844e92ac7a8fb29a608d58125)`);\n                    removeEventListeners();\n                    // promptInput.value = '';  // Clear input for next time\n                    dialog.close(undefined);\n                    resolve(undefined);\n                };\n                dialog.addEventListener('close', onClose);\n                // #endregion wire up - these all should be in removeEventListeners\n\n                // show it\n                dialog.showModal();\n                await delay(500);\n                dialogBody.scrollTo({ top: 0, behavior: 'smooth' });\n                const srcAddrInput = shadowRoot_getElementById<HTMLInputElement>(shadowRoot, 'typing-fullscreen-dialog-src-addr');\n                const contextAddr = this.ibGib?.data?.[\"@contextAddr\"];\n                if (contextAddr) {\n                    srcAddrInput.value = contextAddr;\n                    const manualInputEvent = new Event('input', { bubbles: true });\n                    srcAddrInput.dispatchEvent(manualInputEvent);\n                }\n            });\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n}\n\n// *   character-level typing practice with parroting:\n//     *   This is focused on character-level typing practice and active recognition through parroting. This would be particularly helpful for learners unfamiliar with the target language's keyboard layout or character set.\n// *   word/phrase-level exercises with directional atomic associations:\n//     *   This will be focused on word/phrase-level exercises with the following directional atomic associations between the target and native languages:\n//         *   target -> target\n//         *   target - native -> target - native\n//         *   target - native -> native\n//         *   target -> native\n//         *   native - target -> native - target\n//         *   native - target -> target\n//         *   native -> target\n//         *   target -> target\n// *   fill-in-the-blanks (FITB) and scrambled sentences:\n//     *   These types of minigames will help the learner focus on understanding and practicing grammar and sentence structure. The FITB blanks can be of one or more words, and scrambled sentences will require putting a series of words/chunks in the correct order.\n// *   target - target definition -> target\n//     *   This type of minigame would show a target word and its definition in the target language, prompting the learner to type the target word.\n// *   target definition -> target\n//     *   This type of minigame would show a target word's definition in the target language, prompting the learner to type the target word.\n// *   picture - target -> target\n//     *   This type of minigame would show a picture associated with a target word, prompting the learner to type the target word.\n// *   target/picture composition -> target1, target2, target3, ...\n//     *   In this type of exercise, the agent provides a composition (e.g., haiku, poem, short story) incorporating a set of target words or a picture depicting a scenario with associated vocabulary. The learner then provides a response, such as typing specific target words from the composition or describing elements of the picture in the target language.\n", "import { delay, extractErrorMsg } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\n\nimport { GLOBAL_LOG_A_LOT } from \"../../constants.mjs\";\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\nexport interface MetronomeInfo {\n    bpm: number,\n    frequency: number,\n    duration: number,\n    volume: number,\n    audioCtx: AudioContext,\n}\n\nexport class Metronome {\n    private lc: string = `[${Metronome.name}]`;\n    #isTicking = false;\n    // metronomeIntervalId: any | undefined = undefined;\n    public get isTicking(): boolean {\n        return this.#isTicking;\n    };\n    constructor(public info: MetronomeInfo) {\n        if (!info) { throw new Error(`(UNEXPECTED) info falsy? (E: 58635a4f0b98774a288647e841dee825)`); }\n        const { bpm, frequency, duration, volume, audioCtx } = this.info;\n    }\n    public async start(): Promise<void> {\n        const lc = `${this.lc}[${this.start.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 2b53eee8f22370d20ef406e871ed2625)`); }\n            const { bpm, frequency, duration, volume, audioCtx } = this.info;\n\n            if (this.isTicking) {\n                console.warn(`${lc} already ticking (W: genuuid)`);\n                return; /* <<<< returns early */\n            }\n\n            // #region validate\n            if (bpm <= 0) { throw new Error(`bpm must be positive integer (E: 7aaa36aafdc8623c5c1f3e98f170d825)`); }\n            if (frequency <= 0) { throw new Error(`frequency must be positive integer (E: genuuid)`); }\n            if (duration <= 0) { throw new Error(`duration must be positive integer (E: genuuid)`); }\n            if (volume <= 0) { throw new Error(`volume must be positive integer (E: genuuid)`); }\n            if (!audioCtx) { throw new Error(`audioCtx required (E: genuuid)`); }\n            // #endregion validate\n\n            this.#isTicking = true;\n            setTimeout(async () => {\n                while (this.isTicking) {\n                    this.playMetronomeTick();\n                    await delay(this.beatIntervalMs);\n                }\n            });\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    /**\n     * getter derived from bpm\n     */\n    private get beatIntervalMs(): number {\n        const lc = `${this.lc}[get beatIntervalMs]`\n        if (!this.info.bpm || this.info.bpm < 0) {\n            console.error(`${lc} this.info.bpm must be positive integer. using default 1000 (E: 52d1a82a6d64c3188f345ff74e2b2825)`);\n            return 1000;\n        }\n        const result = Math.floor(60 / this.info.bpm * 1000);\n        // want to see result for debugger, so separate var\n        return result;\n    }\n    public async stop(): Promise<void> {\n        const lc = `${this.lc}[${this.stop.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: f5218be7a209348b78f61db8b2c67725)`); }\n\n            if (this.isTicking) {\n                this.#isTicking = false;\n            } else {\n                console.warn(`${lc} already stopped. (W: 8831132d8ea8b78b78eee887c7980125)`);\n                return; /* <<<< returns early */\n            }\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n\n    }\n\n    private playMetronomeTick(): void {\n        const lc = `[${this.playMetronomeTick.name}]`;\n        console.log(lc);\n        const { frequency, duration, volume, audioCtx } = this.info;\n        const oscillator = audioCtx.createOscillator();\n        const gainNode = audioCtx.createGain();\n\n        oscillator.type = \"sine\"; // You can experiment with other types like \"square\", \"triangle\", etc.\n        oscillator.frequency.setValueAtTime(frequency, audioCtx.currentTime);\n\n        gainNode.gain.setValueAtTime(volume, audioCtx.currentTime);\n\n        oscillator.connect(gainNode);\n        gainNode.connect(audioCtx.destination);\n\n        oscillator.start(audioCtx.currentTime);\n        oscillator.stop(audioCtx.currentTime + duration);\n    }\n}\n", "import thisHtml from './minigame.html';\nimport thisCss from './minigame.css';\nimport stylesCss from '../../styles.css';\nimport rootCss from '../../root.css';\n\nimport { clone, delay, extractErrorMsg, getSaferSubstring, getTimestampInTicks, } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { IbGibAddr, } from \"@ibgib/ts-gib/dist/types.mjs\";\nimport { IbGib_V1 } from \"@ibgib/ts-gib/dist/V1/types.mjs\";\nimport { getIbAndGib, getIbGibAddr } from \"@ibgib/ts-gib/dist/helper.mjs\";\nimport { GIB_DELIMITER } from \"@ibgib/ts-gib/dist/V1/constants.mjs\";\nimport { MetaspaceService } from \"@ibgib/core-gib/dist/witness/space/metaspace/metaspace-types.mjs\";\nimport { getTjpAddr } from \"@ibgib/core-gib/dist/common/other/ibgib-helper.mjs\";\nimport { mut8Timeline } from \"@ibgib/core-gib/dist/timeline/timeline-api.mjs\";\nimport { tellUserFunctionInfo } from '@ibgib/web-gib/dist/api/commands/chat/tell-user.mjs';\nimport { helloWorldFunctionInfo } from '@ibgib/web-gib/dist/api/commands/chat/hello-world.mjs';\nimport { alertUser, highlightElement, promptForConfirm, promptForText, shadowRoot_getElementById, } from \"@ibgib/web-gib/dist/helpers.web.mjs\";\nimport { getGlobalMetaspace_waitIfNeeded, } from \"@ibgib/web-gib/dist/helpers.mjs\";\nimport { IbGibDynamicComponentInstanceBase, IbGibDynamicComponentMetaBase } from \"@ibgib/web-gib/dist/ui/component/ibgib-dynamic-component-bases.mjs\";\nimport { ElementsBase, IbGibDynamicComponentInstance, IbGibDynamicComponentInstanceInitOpts, } from \"@ibgib/web-gib/dist/ui/component/component-types.mjs\";\nimport { Settings_Minigame, } from \"@ibgib/web-gib/dist/common/settings/settings-types.mjs\";\nimport { getSectionName, getSettingsSection } from \"@ibgib/web-gib/dist/common/settings/settings-helpers.mjs\";\nimport { SettingsType } from \"@ibgib/web-gib/dist/common/settings/settings-constants.mjs\";\nimport { getComponentSvc } from \"@ibgib/web-gib/dist/ui/component/ibgib-component-service.mjs\";\n\nimport {\n    GLOBAL_LOG_A_LOT,\n    // ARMY_STORE, BEE_KEY, BLANK_GIB_DB_NAME,\n} from \"../../constants.mjs\";\nimport { getComponentCtorArg, getCurrentActiveProjectComponent, } from \"../../helpers.web.mjs\";\nimport { MinigameFiniteStateMachine, MinigameGamePhase, MinigameIbGib_V1 } from \"../../common/minigame/minigame-types.mjs\";\nimport { isMinigameIbGib_V1, } from \"../../common/minigame/minigame-helper.mjs\";\nimport {\n    AGENT_AVAILABLE_FUNCTIONS_MINIGAMEAGENT,\n    MINIGAME_REL8N_NAME,\n} from \"../../common/minigame/minigame-constants.mjs\";\n// import {\n//     Minigame_TypingGameState, Minigame_TypingGameMeta,\n// } from \"../../common/minigame/typing/typing-types.mjs\";\n// import {\n//     MINIGAME_GAME_VARIANT_TYPING_VALUES, MinigameGameVariant_Typing\n// } from \"../../common/minigame/typing/typing-constants.mjs\";\nimport { TYPING_COMPONENT_NAME, TypingComponentInstance } from \"./typing/typing-component-one-file.mjs\";\nimport { getAppShellSvc } from \"../../ui/shell/app-shell-service.mjs\";\nimport { Metronome } from \"../../common/minigame/metronome.mjs\";\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\nexport const MINIGAME_COMPONENT_NAME: string = 'ibgib-minigame';\n\nexport class MinigameComponentMeta extends IbGibDynamicComponentMetaBase {\n    protected override lc: string = `[${MinigameComponentMeta.name}]`;\n\n    /**\n     * temporary regexp path for our initial dev. this component will become\n     * attached to actual ib^gib addrs\n     */\n    routeRegExp?: RegExp = new RegExp(MINIGAME_COMPONENT_NAME);\n    // routeRegExp?: RegExp = /apps\\/web1\\/gib\\/contact.html/;\n\n    componentName: string = MINIGAME_COMPONENT_NAME;\n\n    constructor() {\n        super(getComponentCtorArg());\n        customElements.define(this.componentName, MinigameComponentInstance);\n    }\n\n    /**\n     * for a minigame, we don't have any additional info in the path.\n     */\n    async createInstance({\n        path,\n        ibGibAddr\n    }: {\n        path: string;\n        ibGibAddr: IbGibAddr;\n    }): Promise<IbGibDynamicComponentInstance> {\n        const lc = `${this.lc}[${this.createInstance.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n            const component = document.createElement(this.componentName) as MinigameComponentInstance;\n            await component.initialize({\n                ibGibAddr,\n                meta: this,\n                html: thisHtml,\n                css: [rootCss, stylesCss, thisCss],\n            });\n            return component;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n}\n\ninterface MinigameElements extends ElementsBase {\n    nameEl: HTMLElement;\n    timerEl: HTMLElement;\n    /**\n     * sets beats per minute\n     */\n    metronomeBpmEl: HTMLInputElement;\n    /**\n     * toggle metronome tick\n     */\n    metronomeBtnEl: HTMLButtonElement;\n    pauseBtnEl: HTMLButtonElement;\n    playBtnEl: HTMLButtonElement;\n    /**\n     * aka stop button\n     */\n    abortBtnEl: HTMLButtonElement;\n    nextGameBtnEl: HTMLButtonElement;\n    restartBtnEl: HTMLButtonElement;\n    maximizeBtnEl: HTMLButtonElement;\n    minigameInstructionsBtnEl: HTMLButtonElement;\n    /**\n     * used when pausing the game\n     */\n    pauseScreenEl: HTMLDivElement;\n    // minigameResumeBtnEl: HTMLButtonElement;\n    /**\n     * contains the concrete minigame component, (i.e. where the actual game is\n     * injected)\n     */\n    minigameComponentDivEl: HTMLDivElement;\n}\n\nexport type MinigameChildComponentInstance = any;// RawComponentInstance | TextEditorComponentInstance;\n\nexport class MinigameComponentInstance\n    extends IbGibDynamicComponentInstanceBase<MinigameIbGib_V1, MinigameElements>\n    implements IbGibDynamicComponentInstance<MinigameIbGib_V1, MinigameElements> {\n    protected override lc: string = `[${MinigameComponentInstance.name}]`;\n\n    metaspace: MetaspaceService | undefined;\n\n    private gameFSM: MinigameFiniteStateMachine | undefined = undefined;\n\n    private isMinigame = true;\n\n    constructor() {\n        super();\n\n        if (!window.AudioContext && !(window as any).webkitAudioContext) {\n            console.error(`no audio context available (E: c094e8547495c99c0898cfd8ebb37c25)`);\n        }\n    }\n\n    /**\n     * creates the concrete minigame component to be injected.\n     *\n     * atow (06/2025) only the typing component is available.\n     *\n     * ## notes\n     *\n     * I've kept the name the same as the tabbed component's that activate child\n     * ibgibs, e.g., in the projects and project components. Not sure if this is the right thing to do,\n     * but I figure the minigame is basically a parent component and we're\n     * activating - in this case - a single concrete \"child\".\n     */\n    protected async activateIbGib({ addr, ibGib, }: { addr?: IbGibAddr; ibGib?: IbGib_V1; }): Promise<void> {\n        const lc = `${this.lc}[${this.activateIbGib.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n            if (!addr && !ibGib) { throw new Error(`(UNEXPECTED) both addr and ibGib falsy? either addr or ibGib required. (E: genuuid)`); }\n\n            addr ??= getIbGibAddr({ ibGib });\n            this.ibGibAddr = addr;\n            await this.loadIbGib({ getLatest: true });\n            ibGib = this.ibGib;\n            if (!ibGib) { throw new Error(`(UNEXPECTED) ibGib false after loading? (E: cc3cb678360b6c23b843fe58b58dee25)`); }\n            addr = getIbGibAddr({ ibGib });\n\n            // let minigameSettings: Settings_Minigame | undefined = await this.getCurrentMinigameSettings();\n            // if (!minigameSettings) {\n            //     throw new Error(`(UNEXPECTED) couldn't get current minigame settings? i thought this would initialized by now. (E: genuuid)`);\n            // }\n            const tjpAddr = getTjpAddr({ ibGib, defaultIfNone: 'incomingAddr' });\n            if (!tjpAddr) { throw new Error(`(UNEXPECTED) tjpAddr falsy? 'incomingAddr' was used as the default option. (E: genuuid)`); }\n\n            // ibgib is loaded.\n\n            this.isMinigame = isMinigameIbGib_V1(ibGib);\n            if (!this.isMinigame) { return; /* <<<< returns early */ }\n\n            // we know we have a minigame. load the concrete component that\n            // corresponds to the exact details of the minigame ibgib.\n            const { data } = ibGib;\n            if (!data) { throw new Error(`(UNEXPECTED) ibGib.data falsy after verifying that it is a MinigameIbGib_V1? (E: 178b183483fde4e4e8491a88d8a76825)`); }\n\n            if (data.gameType !== 'typing') {\n                throw new Error(`${data.gameType} not implemented. only \"typing\" is implemented right now. (E: dd3f080b752f6ba0af08d4082984ad25)`);\n            }\n\n            // get typing component and inject it\n            const componentSvc = await getComponentSvc();\n            const typingComponent =\n                await componentSvc.getComponentInstance({\n                    path: TYPING_COMPONENT_NAME,\n                    ibGibAddr: addr,\n                    useRegExpPrefilter: true,\n                }) as TypingComponentInstance;\n\n            if (!typingComponent) { throw new Error(`(UNEXPECTED) typingComponent falsy? couldn't get a typingComponent? (E: d316285d8fd80adf986f46038279d325)`); }\n            if (this.gameFSM) {\n                debugger; // minigame comp: unload fsm when activating new minigame ibgib? does this ever hit?\n                // this.gameFSM.phase\n            }\n            this.gameFSM = typingComponent;\n\n            if (!this.elements) { throw new Error(`(UNEXPECTED) this.elements falsy? how did we get here before init of elements? (E: 349b58bdd3e8e1c976a7f6fb257aef25)`); }\n            const { minigameComponentDivEl } = this.elements;\n\n            // anything before injecting?\n\n            await componentSvc.inject({\n                parentEl: minigameComponentDivEl,\n                componentToInject: typingComponent,\n            });\n\n            // update settings for currently active ibgib\n\n\n            await this.renderUI();\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    // private async activateIbGib_typing({\n    //     addr,\n    //     ibGib,\n    //     data,\n    // }: {\n    //     addr: string;\n    //     ibGib: MinigameIbGib_V1;\n    //     data: MinigameData_V1;\n    // }): Promise<void> {\n    //     const lc = `${this.lc}[${this.activateIbGib_typing.name}]`;\n    //     try {\n    //         if (logalot) { console.log(`${lc} starting... (I: 0df74db944783bbec8a0537f58c9d225)`); }\n    //         switch (data.gameVariant) {\n    //             case MinigameGameVariant_Typing.parrot:\n    //                 await this.forwardGame_parrot({\n    //                     addr,\n    //                     ibGib,\n    //                     data,\n    //                 });\n    //                 break;\n    //             case MinigameGameVariant_Typing.antiphony:\n    //                 throw new Error(`not implemented antiphony variant (E: da104857e4887cbd384f75e8a8fe0725)`);\n    //                 // await this.forwardGame_parrot({\n    //                 //     addr,\n    //                 //     ibGib,\n    //                 //     data,\n    //                 // });\n    //                 break;\n    //             default:\n    //                 throw new Error(`(UNEXPECTED) unknown MinigameGameVariant (${data.gameVariant})? expected one of ${MINIGAME_GAME_VARIANT_TYPING_VALUES} (E: 2af65880dfa89b1cd5c83ffa4e00b825)`);\n    //         }\n\n    //     } catch (error) {\n    //         console.error(`${lc} ${extractErrorMsg(error)}`);\n    //         throw error;\n    //     } finally {\n    //         if (logalot) { console.log(`${lc} complete.`); }\n    //     }\n    // }\n\n    override async initialize(opts: IbGibDynamicComponentInstanceInitOpts): Promise<void> {\n        const lc = `${this.lc}[${this.initialize.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n            await super.initialize(opts);\n            await this.loadIbGib({ getLatest: true });\n            this.metaspace = await getGlobalMetaspace_waitIfNeeded();\n            this.agentsInitialized = this.initAgents();\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    override async created(): Promise<void> {\n        const lc = `${this.lc}[${this.created.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n\n            // const { meta, htmlPath, scriptPaths, cssPaths } = opts;\n\n            // at this point, this.ibGib should be loaded with the latest\n            // minigame ibgib\n\n            if (!this.ibGib) { throw new Error(`(UNEXPECTED) this.ibGib falsy? It is assumed at this point that we have a valid ibGib to work with. (E: genuuid)`); }\n\n            await this.initElements();\n            await this.initSettings();\n\n            await this.agentsInitialized;\n            await this.activateIbGib({ ibGib: this.ibGib });\n            await this.renderUI();\n            // await this.agent!.witness(ROOT); // don't auto-prompt at this time because during dev it's extremely annoying and stresses out the agents\n\n            // spin off because created has to finish\n            const minigameSettings = await this.getCurrentMinigameSettings();\n            // i think this is where we would \"start\"/\"resume\" based on the\n            // current game state/phase/variant\n\n            // if ((minigameSettings?.openChildTjpAddrs ?? []).length === 0) {\n            //     // first run\n            //     this.showInfoTab();\n            // } else {\n            //     // not first run, so just reopen the old tabs\n            //     this.reopenOldTabs();\n            // }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    override async handleContextUpdated(): Promise<void> {\n        const lc = `${this.lc}[${this.handleContextUpdated.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n            await super.handleContextUpdated();\n            await this.renderUI();\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private async initElements(): Promise<void> {\n        const lc = `${this.lc}[${this.initElements.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n\n            const shadowRoot = this.shadowRoot;\n\n            if (!shadowRoot) { throw new Error(`(UNEXPECTED) shadowRoot falsy? (E: genuuid)`); }\n\n            // #region header\n\n            const headerEl = shadowRoot_getElementById<HTMLElement>(shadowRoot, 'minigame-header');\n\n            const timerEl = shadowRoot_getElementById<HTMLElement>(shadowRoot, 'minigame-timer');\n\n            // #endregion header\n\n            const contentEl = shadowRoot_getElementById<HTMLElement>(shadowRoot, 'minigame-content');\n\n            const nameEl = shadowRoot_getElementById<HTMLElement>(shadowRoot, 'minigame-name');\n\n            const minigameInstructionsBtnEl = shadowRoot_getElementById<HTMLButtonElement>(shadowRoot, 'minigame-instructions-btn');\n            minigameInstructionsBtnEl.addEventListener('click', (event) => {\n                event.preventDefault();\n                event.stopPropagation();\n                alertUser({ title: this.ibGib?.data?.name, msg: `${this.ibGib?.data?.description}\\n\\nInstructions:\\n\\n${this.ibGib?.data?.instructions}` });\n            });\n\n            const maximizeBtnEl = shadowRoot_getElementById<HTMLButtonElement>(shadowRoot, 'maximize-btn');\n            maximizeBtnEl.addEventListener('click', () => {\n                const appShellSvc = getAppShellSvc();\n                appShellSvc.collapse({\n                    panelNames: ['leftPanel', 'rightPanel', 'footerPanel'],\n                });\n            });\n\n            const minigameComponentDivEl = shadowRoot_getElementById<HTMLDivElement>(shadowRoot, 'minigame-component-div');\n\n            const pauseScreenEl = shadowRoot_getElementById<HTMLDivElement>(shadowRoot, 'minigame-pause-screen');\n            pauseScreenEl.style.display = 'none';\n            pauseScreenEl.style.zIndex = \"5\";\n\n            // #region footer\n            const footerEl = shadowRoot_getElementById<HTMLElement>(shadowRoot, 'minigame-footer');\n\n            // metronomeBtnEl - metronome play/pause toggle\n            const metronomeBpmEl = shadowRoot_getElementById<HTMLInputElement>(shadowRoot, 'metronome-bpm');\n            metronomeBpmEl.addEventListener('input', async (event) => {\n                this.metronome.info.bpm = Number.parseInt(metronomeBpmEl.value || \"120\");\n            })\n            const metronomeBtnEl = shadowRoot_getElementById<HTMLButtonElement>(shadowRoot, 'metronome-play-pause-btn');\n            metronomeBtnEl.addEventListener('click', async (event) => {\n                event.preventDefault();\n                event.stopPropagation();\n                await this.toggleMetronome();\n            });\n\n            // pauseBtnEl\n            const pauseBtnEl = shadowRoot_getElementById<HTMLButtonElement>(shadowRoot, 'minigame-header-pause-btn');\n            pauseBtnEl.addEventListener('click', async (event) => {\n                await this.pause();\n            });\n            // playBtnEl\n            const playBtnEl = shadowRoot_getElementById<HTMLButtonElement>(shadowRoot, 'minigame-header-play-btn');\n            playBtnEl.addEventListener('click', async (event) => {\n                await this.play();\n            });\n            // abortBtnEl\n            const abortBtnEl = shadowRoot_getElementById<HTMLButtonElement>(shadowRoot, 'minigame-header-abort-btn');\n            abortBtnEl.addEventListener('click', async (event) => {\n                await this.abort();\n            });\n            // nextGameBtnEl\n            const nextGameBtnEl = shadowRoot_getElementById<HTMLButtonElement>(shadowRoot, 'minigame-header-next-btn');\n            nextGameBtnEl.addEventListener('click', async (event) => {\n                await this.nextGame();\n            });\n            // restartBtnEl\n            const restartBtnEl = shadowRoot_getElementById<HTMLButtonElement>(shadowRoot, 'minigame-header-restart-btn');\n            restartBtnEl.addEventListener('click', async (event) => {\n                await this.restart();\n            });\n\n            // #endregion footer\n\n            this.elements = {\n                headerEl,\n                contentEl,\n                nameEl,\n                pauseScreenEl,\n                // minigameResumeBtnEl,\n                minigameComponentDivEl,\n                metronomeBpmEl,\n                metronomeBtnEl,\n                footerEl,\n                timerEl,\n                playBtnEl,\n                pauseBtnEl,\n                abortBtnEl,\n                nextGameBtnEl,\n                restartBtnEl,\n                minigameInstructionsBtnEl,\n                maximizeBtnEl,\n            };\n\n            // has to run after this.elements set\n            await this.initSettings();\n            // await this.initTimer();\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private metronome = new Metronome({\n        bpm: 120,\n        duration: 0.1,\n        frequency: 440,\n        volume: 0.5,\n        audioCtx: new (window.AudioContext || (window as any).webkitAudioContext)(),\n    });\n\n    private async toggleMetronome(): Promise<void> {\n        const lc = `${this.lc}[${this.toggleMetronome.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 005fe78b1f51d2d7f4055688f13d6825)`); }\n\n            // todo: update metronome bpm from UI\n            const bpmStr = this.elements!.metronomeBpmEl.value || '60';\n            const bpm = Number.parseInt(bpmStr);\n            this.metronome.info.bpm = bpm;\n\n            if (this.metronome.isTicking) {\n                await this.metronome.stop();\n            } else {\n                await this.metronome.start();\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private async pause(): Promise<void> {\n        const lc = `${this.lc}[${this.pause.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 268c84faf1ec217571de75e8d3ef6825)`); }\n            if (!this.elements) { throw new Error(`(UNEXPECTED) this.elements falsy? (E: 48ef4c6ed678779324821aa8ed44c425)`); }\n            const { pauseScreenEl, minigameComponentDivEl } = this.elements;\n            if (!this.gameFSM) { throw new Error(`(UNEXPECTED) this.gameFSM falsy? (E: 7b7abfac43c845d4c8eb8938c1312825)`); }\n            if (this.gameFSM.gamePhase === MinigameGamePhase.paused) {\n                console.warn(`${lc} (UNEXPECTED) already paused? (W: 119d83ea5c0849c5066b0a78fb244525)`)\n                return; /* <<<< returns early */\n            }\n            // const dialog = document.getElementById('fullscreen-dialog') as HTMLDivElement;\n            // dialog.showModal();\n            pauseScreenEl.style.display = 'flex';\n            minigameComponentDivEl.style.display = 'none';\n            await this.gameFSM.pause();\n            await this.renderUI();\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private async play(): Promise<void> {\n        const lc = `${this.lc}[${this.play.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n            if (!this.elements) { throw new Error(`(UNEXPECTED) this.elements falsy? (E: genuuid)`); }\n            const { pauseScreenEl, minigameComponentDivEl } = this.elements;\n            // const dialog = document.getElementById('fullscreen-dialog') as HTMLDivElement;\n            if (!this.ibGib?.data?.playable) {\n                console.warn(`${lc} not playable (W: 3680a81400efea0728940af8bec0c125)`);\n                return; /* <<<< returns early */\n            }\n            if (!this.gameFSM) { throw new Error(`(UNEXPECTED) this.gameFSM falsy? (E: bcf0088119668a4ec3bbd5a8f9e20f25)`); }\n            if (this.gameFSM.gamePhase === MinigameGamePhase.playing) {\n                console.warn(`${lc} already playing... (W: 119d83ea5c0849c5066b0a78fb244525)`)\n                return; /* <<<< returns early */\n            }\n            await this.gameFSM.play();\n            this.startTimer();\n            await this.renderUI();\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private async restart(): Promise<void> {\n        const lc = `${this.lc}[${this.restart.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n            if ([MinigameGamePhase.playing, MinigameGamePhase.paused].includes(this.ibGib!.data!.gamePhase as any)) {\n                const confirm = await promptForConfirm({\n                    msg: `Abort playing this game and restart?`,\n                    yesLabel: `Yes, this game was lame but had promise.`,\n                    noLabel: `No, this is good. I just screwed up.`,\n                });\n                if (!confirm) {\n                    console.log(`${lc} user canceled restart. (I: 0aa4c8c182e87a838853bef42ce78f25)`);\n                    return; /* <<<< returns early */\n                }\n            }\n            if (!this.elements) { throw new Error(`(UNEXPECTED) this.elements falsy? (E: genuuid)`); }\n            const { pauseScreenEl, minigameComponentDivEl } = this.elements;\n            // if (!this.ibGib?.data?.playable) {\n            //     console.warn(`${lc} not playable (W: 3680a81400efea0728940af8bec0c125)`);\n            //     return; /* <<<< returns early */\n            // }\n            if (!this.gameFSM) { throw new Error(`(UNEXPECTED) this.gameFSM falsy? (E: bcf0088119668a4ec3bbd5a8f9e20f25)`); }\n            pauseScreenEl.style.display = 'none';\n            minigameComponentDivEl.style.display = 'flex';\n            await this.gameFSM.restart();\n            this.stopTimer();\n            await this.renderUI();\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private async abort(): Promise<void> {\n        const lc = `${this.lc}[${this.abort.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n            if (!this.elements) { throw new Error(`(UNEXPECTED) this.elements falsy? (E: genuuid)`); }\n            const confirm = await promptForConfirm({\n                msg: `Abort playing this game?`,\n                yesLabel: `Yes, I'm done with this one.`,\n                noLabel: `No, let's keep going.`,\n            });\n            if (!confirm) {\n                console.log(`${lc} user canceled aborting. (I: eef296edf4bd1340e1d78d7860c61825)`);\n                return; /* <<<< returns early */\n            }\n            const { pauseScreenEl, minigameComponentDivEl } = this.elements;\n            // const dialog = document.getElementById('fullscreen-dialog') as HTMLDivElement;\n            if (!this.gameFSM) { throw new Error(`(UNEXPECTED) this.gameFSM falsy? (E: genuuid)`); }\n            if (this.gameFSM.gamePhase !== MinigameGamePhase.playing) {\n                console.warn(`${lc} not playing... (W: genuuid)`)\n                return; /* <<<< returns early */\n            }\n            await this.gameFSM.abort();\n            this.stopTimer();\n            await this.renderUI();\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private async nextGame(): Promise<void> {\n        const lc = `${this.lc}[${this.nextGame.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n            if (!this.elements) { throw new Error(`(UNEXPECTED) this.elements falsy? (E: genuuid)`); }\n            if (!this.gameFSM) { throw new Error(`(UNEXPECTED) this.gameFSM falsy? (E: genuuid)`); }\n            const confirm = this.gameFSM.gamePhase === MinigameGamePhase.playing ?\n                await promptForConfirm({\n                    msg: `Abort playing this game and start the next one in the project?`,\n                    yesLabel: `Yes, I'm done with this one.`,\n                    noLabel: `No, let's keep going.`,\n                }) :\n                await promptForConfirm({\n                    msg: `Start the next game in the project?`,\n                    yesLabel: `Yes, next please.`,\n                    noLabel: `No, let's keep playing this game.`,\n                });\n\n            if (!confirm) {\n                console.log(`${lc} user canceled skip to next game. (I: genuuid)`);\n                return; /* <<<< returns early */\n            }\n\n            // get the current project ibgib\n            const currentProjectComponent = getCurrentActiveProjectComponent();\n            const projectIbGib = currentProjectComponent.ibGib!;\n\n            // find the index of the the current minigame\n            let nextIndex: number;\n            const minigameAddrs = projectIbGib.rel8ns![MINIGAME_REL8N_NAME]!;\n            const currentMinigameIndex = minigameAddrs.findIndex(addr => {\n                const { gib } = getIbAndGib({ ibGibAddr: addr });\n                const tjpGib = gib.includes(GIB_DELIMITER) ?\n                    gib.split(GIB_DELIMITER).at(-1)! :\n                    gib;\n                const thisTjpGib = getIbAndGib({ ibGibAddr: this.tjpAddr }).gib;\n                return thisTjpGib === tjpGib;\n            });\n            if (currentMinigameIndex >= 0) {\n                if (currentMinigameIndex === (minigameAddrs.length - 1)) {\n                    // current minigame is the last in the list\n                    const startAtBeginning = await promptForConfirm({\n                        msg: `This is the last minigame. Would you like to load the first one?`,\n                        yesLabel: `Yes, load the very first minigame`,\n                        noLabel: `Nevermind, stay here.`,\n                    });\n                    if (startAtBeginning) {\n                        nextIndex = 0;\n                    } else {\n                        return; /* <<<< returns early */\n                    }\n                } else {\n                    // guaranteed to have an index one higher than the current\n                    // index\n                    nextIndex = currentMinigameIndex + 1;\n                }\n            } else {\n                console.error(`${lc} could not find the index of the current minigame? Does this minigame (${this.ibGibAddr}) exist on the current active project? Or have we moved on to minigames on project child ibgibs? (E: a247f4ce8469ba5ed848207365579e25)`);\n                await alertUser({ title: 'whoops', msg: `We seem to not be able to find another minigame. Sorry about that! Hey at least you have the current game.` });\n                return; /* <<<< returns early */\n            }\n\n            // load the next minigame\n            let nextMinigameAddr = minigameAddrs.at(nextIndex);\n            if (nextMinigameAddr) {\n                await currentProjectComponent.activateIbGib({\n                    // activateIbGib loads the latest in the timeline\n                    addr: nextMinigameAddr,\n                });\n            } else {\n                await alertUser({\n                    title: 'hmm...',\n                    msg: `Well, we thought we had it but something seems to have gone wrong and we lost it. You'll have to manually load another minigame. Contact us about this error though please. (E: 370e6bc457e5d37564cb4fe83cbc7525)`,\n                });\n                return; /* <<<< returns early */\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    protected override async initSettings(): Promise<void> {\n        const lc = `${this.lc}[${this.initSettings.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n            await super.initSettings();\n\n            if (!this.settings) { throw new Error(`(UNEXPECTED) this.settings falsy after init? (E: genuuid)`); }\n            if (!this.settings.ibGib) { throw new Error(`(UNEXPECTED) this.settings.ibGib falsy after init? (E: genuuid)`); }\n\n            let minigameSettings = await this.getCurrentMinigameSettings();\n\n            if (!minigameSettings) {\n                // need to create a new minigame settings section\n                minigameSettings = { type: 'minigame', }\n                // update the current settings and persist\n                const sectionName_default = await getSectionName({\n                    settingsType: SettingsType.minigame,\n                    useCase: 'default',\n                });\n                const sectionName_current = await getSectionName({\n                    settingsType: SettingsType.minigame,\n                    useCase: 'current',\n                });\n                const _newSettings = await mut8Timeline({\n                    timeline: this.settings!.ibGib!,\n                    metaspace: this.metaspace!,\n                    mut8Opts: {\n                        dataToAddOrPatch: {\n                            sections: {\n                                [sectionName_default]: minigameSettings,\n                                [sectionName_current]: minigameSettings,\n                            }\n                        }\n                    },\n                });\n            }\n\n            // const sectionName_generalCurrent = await getSectionName({\n            //     settingsType: 'general',\n            //     useCase: 'current',\n            // });\n            // data.sections[sectionName_generalDefault] = clone(DEFAULT_SETTINGS_GENERAL);\n            // data.sections[sectionName_generalCurrent] = clone(DEFAULT_SETTINGS_GENERAL);\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private async getCurrentMinigameSettings(): Promise<Settings_Minigame | undefined> {\n        const lc = `${this.lc}[${this.getCurrentMinigameSettings.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n            if (!this.settings) { throw new Error(`(UNEXPECTED) this.settings falsy? shouldn't this be initialized by now? (E: genuuid (E: genuuid)`); }\n            if (!this.settings.ibGib) { throw new Error(`(UNEXPECTED) this.settings.ibGib falsy? shouldn't this be initialized by now? especially since this.settings is truthy? (E: genuuid)`); }\n\n            const minigameSettings = await getSettingsSection({\n                sectionName: await getSectionName({\n                    settingsType: 'minigame',\n                    useCase: 'current',\n                }),\n                settingsIbGib: this.settings.ibGib,\n            }) as (Settings_Minigame | undefined);\n\n            if (!minigameSettings) {\n                if (logalot) { console.log(`${lc} minigameSettings does not exist. returning undefined. (I: genuuid)`) }\n            }\n            return minigameSettings;\n            // if (!minigameSettings) { throw new Error(`(UNEXPECTED) couldn't get minigame settings? should be guaranteed after init. (E: genuuid)`); }\n\n            // return minigameSettings;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * rerender\n     */\n    protected override async renderUI(): Promise<void> {\n        const lc = `${this.lc}[${this.renderUI.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n\n            await super.renderUI();\n\n            const { elements, ibGib } = this;\n            if (!elements) {\n                console.warn(`${lc} (UNEXPECTED) tried to render but haven't initialized elements? (W: genuuid)`);\n                return; /* <<<< returns early */\n            }\n            if (!ibGib) {\n                debugger; // warning - this.ibGib falsy? in minigame comp\n                console.log(`${lc} this.ibGib falsy? returning early... (W: genuuid)`)\n                return; /* <<<< returns early */\n            }\n            const { data } = ibGib;\n            if (!data) { throw new Error(`(UNEXPECTED) this.ibGib.data falsy? (E: df3f386eb978cc232921e668e16af825)`); }\n\n            const {\n                // headerEl, contentEl, footerEl,\n                nameEl,\n                playBtnEl, pauseBtnEl, abortBtnEl, restartBtnEl,\n                pauseScreenEl, minigameComponentDivEl,\n                // maximizeBtnEl,\n            } = elements;\n\n            if (!this.isMinigame) {\n                minigameComponentDivEl.textContent = `This ibGib ain't a minigame \uD83E\uDD28`\n                return; /* <<<< returns early */\n            }\n\n            const minigameSettings = await this.getCurrentMinigameSettings();\n            if (!minigameSettings) {\n                console.error(`${lc} (UNEXPECTED) minigameSettings falsy? NOTE: THIS DID NOT THROW. ONLY LOGGED ERROR. (E: 6fb9fd2fda681dee94b355389ee2c225)`);\n            }\n\n            nameEl.textContent = data.name ?? '[minigame no name?]'\n            nameEl.textContent += ` (v${data.n ?? '?'})`\n            nameEl.title = data.description;\n\n            // if (!this.gameFSM) { throw new Error(`(UNEXPECTED) this.gameFSM falsy? (E: 0b3e91927fb8b6ca285de925821ef825)`); }\n\n            const { gamePhase } = data;\n            if (!gamePhase) { throw new Error(`(UNEXPECTED) gamePhase falsy? (E: 095462d507ea7db7b78658486d01db25)`); }\n            playBtnEl.disabled =\n                !data.playable ||\n                [MinigameGamePhase.playing, MinigameGamePhase.aborted, MinigameGamePhase.complete].includes(gamePhase as any);\n            pauseBtnEl.disabled =\n                gamePhase !== MinigameGamePhase.playing;\n            abortBtnEl.disabled =\n                gamePhase !== MinigameGamePhase.playing;\n            restartBtnEl.disabled =\n                [MinigameGamePhase.init, MinigameGamePhase.ready].includes(gamePhase as any);\n            // data.gamePhase !== MinigameGamePhase.playing;\n\n            // const description = this.ibGib?.data?.description;\n            // if (description) {\n            //     descEl.textContent = description;\n            // } else {\n            //     descEl.style.display = 'none';\n            // }\n\n            if (gamePhase === MinigameGamePhase.paused) {\n                pauseScreenEl.style.display = 'flex';\n                minigameComponentDivEl.style.display = 'none';\n            } else {\n                pauseScreenEl.style.display = 'none';\n                minigameComponentDivEl.style.display = 'flex';\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    // private async calculatePlayingTimeInTicks(): Promise<number> {\n    //     const lc = `${this.lc}[${this.calculatePlayingTimeInTicks.name}]`;\n    //     try {\n    //         if (logalot) { console.log(`${lc} starting... (I: 51828b278e0889887d238e05fb691325)`); }\n    //         if (!this.ibGib) { throw new Error(`(UNEXPECTED) this.ibGib falsy? (E: bb27a8b3ed5838cdffba61f471112d25)`); }\n    //         if (!this.ibGib.data) { throw new Error(`(UNEXPECTED) this.ibGib.data falsy? (E: bd335e090cd26ee7e8d3f8595d087a25)`); }\n\n    //         const { gameMeta, gameState, gamePhase } = this.ibGib.data;\n    //         const interactions = gameState as Minigame_TypingInteraction[]; // code smell here of course. I need to add interactions to all\n\n    //         // should calculate the playing time based on the\n    //         // gameState.interactions via the timestamps.\n    //         let totalTime = 0;\n    //         if (gamePhase === MinigameGamePhase.init) {\n    //             totalTime = 0;\n    //             return totalTime; /* <<<< returns early */\n    //         }\n\n    //         const firstStimulus = interactions.at(0)?.stimulus ?? gameState.currentStimulus;\n    //         if (!firstStimulus) {\n    //             console.warn(`${lc} no firstStimulus? returning 0. (W: genuuid)`)\n    //             return 0; /* <<<< returns early */\n    //         }\n    //         const startTimestamp = firstStimulus.timestampInTicks;\n    //         if (!startTimestamp) {\n    //             console.error(`${lc} firstStimulus didn't have a timestamp? returning 0. (E: genuuid)`);\n    //             return 0; /* <<<< returns early */\n    //         }\n    //         const startTime = Number.parseInt(startTimestamp);\n\n    //         let pauseFound = false;\n    //         let currentIndex = 1; // index 0 is first stimulus above\n    //         do {\n    //             // look for the next game phase being paused in the history\n    //             const remainingInteractions = interactions.slice(currentIndex);\n    //             remainingInteractions.findIndex\n    //         } while (pauseFound);\n\n\n    //         const now_timestampInTicks = getTimestampInTicks();\n    //         const now_number = Number.parseInt(now_timestampInTicks);\n\n\n    //         if (gamePhase === MinigameGamePhase.playing) {\n    //             totalTime = now_number - startTime;\n    //         } else if ([MinigameGamePhase.aborted, MinigameGamePhase.complete].includes(gamePhase as any)) {\n\n    //             let lastTimestamp: string;\n    //             const lastResponse = gameState.interactions.at(-1)?.response;\n    //             if (lastResponse) {\n    //                 if (lastResponse.timestampInTicks) {\n    //                     lastTimestamp = lastResponse.timestampInTicks;\n    //                 } else {\n    //                     console.error(`${lc} (UNEXPECTED) lastResponse.timestampInTicks falsy? returning 0 (E: genuuid)`);\n    //                     return 0; /* <<<< returns early */\n    //                 }\n    //             } else {\n    //                 lastTimestamp = now_timestampInTicks;\n    //             }\n    //             const lastTime = Number.parseInt(lastTimestamp);\n\n    //             totalTime = lastTime - startTime;\n    //         } else if ([MinigameGamePhase.paused].includes(gamePhase as any)) {\n    //             return this.#timerValueInTicks;\n    //         } else {\n    //             // debugger; // typing comp calc timestamp when does this hit?\n    //             return 0;\n    //         }\n\n    //         if (logalot) { console.log(`${lc} totalTime: ${totalTime} ticks (I: 4f2cd7eac4740a9a48a8ecf80adfb525)`); }\n\n    //         return totalTime;\n    //     } catch (error) {\n    //         console.error(`${lc} ${extractErrorMsg(error)}`);\n    //         throw error;\n    //     } finally {\n    //         if (logalot) { console.log(`${lc} complete.`); }\n    //     }\n    // }\n\n    #timerInterval: any | undefined;\n    #timerValueInSeconds: number = 0;\n    private startTimer(): void {\n        const lc = `${this.lc}[${this.startTimer.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: a9b8281444c8523b68de98e85cbc1825)`); }\n            if (this.#timerInterval) {\n                if (logalot) { console.log(`${lc} timer already started. (we were paused?) (I: b09df8d777f80dafd1c2b2dd2ef29825)`); }\n                return; /* <<<< returns early */\n            }\n            this.#timerInterval = setInterval(async () => {\n                const { gamePhase } = this.gameFSM!;\n                if (!gamePhase) {\n                    console.warn(`${lc} gamePhase falsy?  what? this is expected to be truthy. (W: 25a87ffdb683d197587d2c6e30557825)`);\n                    debugger; // want to see if gamePhase is ever falsy\n                    return; /* <<<< returns early */\n                }\n\n                switch (gamePhase) {\n                    case MinigameGamePhase.ready:\n                        // this.#timerValueInTicks++; // don't increment during ready\n                        break;\n                    case MinigameGamePhase.playing:\n                        this.#timerValueInSeconds++;\n                        break;\n                    case MinigameGamePhase.paused:\n                        // this.#timerValueInTicks++; // don't increment when paused\n                        break;\n                    default:\n                        this.stopTimer();\n                        break;\n                }\n\n                this.renderUI_updateTimer();\n            }, 1000);\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n\n    }\n    private stopTimer(): void {\n        const lc = `[${this.stopTimer.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 630d585c15acae8dff0a6b28c8c36825)`); }\n            if (this.#timerInterval) {\n                clearInterval(this.#timerInterval);\n                this.#timerInterval = undefined;\n            } else {\n                console.error(`${lc} no timer started? (E: genuuid)`);\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    private renderUI_updateTimer() {\n        const lc = `${this.lc}[${this.renderUI_updateTimer.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n            const { elements, } = this;\n            if (!elements) { throw new Error(`(UNEXPECTED) this.elements falsy? (E: genuuid)`); }\n            const { timerEl, } = elements;\n            // convert #timerValueInTicks to show as HH:MM:SS\n            /**\n             * going to pull out hours and minutes. this will be the working\n             * seconds remaining after each time we pull time out.\n             */\n            let runningTotalSeconds = this.#timerValueInSeconds; // Assuming ticks are milliseconds\n            const hours = Math.floor(runningTotalSeconds / 3600);\n            runningTotalSeconds -= hours * 3600;\n            const minutes = Math.floor((runningTotalSeconds % 3600) / 60);\n            runningTotalSeconds -= minutes * 60;\n            const seconds = runningTotalSeconds % 60;\n\n            const formattedTime = hours === 0 ?\n                [\n                    // hours.toString().padStart(2, '0'),\n                    minutes.toString().padStart(2, '0'),\n                    seconds.toString().padStart(2, '0'),\n                ].join(':') :\n                [\n                    hours.toString().padStart(2, '0'),\n                    minutes.toString().padStart(2, '0'),\n                    seconds.toString().padStart(2, '0'),\n                ].join(':');\n\n            timerEl.textContent = formattedTime;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    override async disconnected(): Promise<void> {\n        const lc = `${this.lc}[${this.disconnected.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n            // no action atow\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    protected override async initAgents(): Promise<void> {\n        const lc = `${this.lc}[${this.initAgents.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n\n            await this.loadAgentsCoupledToIbGib();\n\n            if (!this.agent) { throw new Error(`(UNEXPECTED) agent falsy after loadAgentsCoupledToIbGib? (E: genuuid)`); }\n            await this.agent.updateAvailableFunctions({\n                availableFunctions: AGENT_AVAILABLE_FUNCTIONS_MINIGAMEAGENT,\n            });\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    // private getAPIKey(): Promise<string> {\n    //     const fn = this.getFnGetAPIKey();\n    //     return fn();\n    // }\n    // private getFnGetAPIKey(): () => Promise<string> {\n    //     const lc = `${this.lc}[${this.getFnGetAPIKey.name}]`;\n    //     try {\n    //         if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n\n    //         const fn = async () => {\n    //             let apiKey = await storageGet({\n    //                 dbName: BLANK_GIB_DB_NAME, storeName: ARMY_STORE,\n    //                 key: BEE_KEY,\n    //             });\n    //             return apiKey ?? '';\n    //         };\n    //         return fn;\n    //     } catch (error) {\n    //         console.error(`${lc} ${extractErrorMsg(error)}`);\n    //         throw error;\n    //     } finally {\n    //         if (logalot) { console.log(`${lc} complete.`); }\n    //     }\n    // }\n\n}\n", "import { AGENT_INITIAL_CHAT_GIVESELFNAME } from \"@ibgib/web-gib/dist/agent-texts/common-agent-texts.mjs\";\n\nimport {\n    AGENT_GOAL_COMMON,\n    AGENT_INITIAL_SYSTEM_SUPER_COOL, AGENT_SYSTEM_PROMPT_COMMON_INSTRUCTIONS,\n    AGENT_WEBSITE_DESCRIPTION,\n} from \"./common-agent-texts.mjs\";\n\nexport const AGENT_SPECIAL_IBGIB_TYPE_MINIGAMEAGENT = 'minigameagent';\nexport const AGENT_GOAL_MINIGAMEAGENT = [\n    AGENT_GOAL_COMMON,\n    `You yourself are a \"minigame\" agent. Many users like to learn things and minigames act as a fun way of not just whiling away the time, but rather, learning stuff. Fun learning actually makes the best brain traces. So minigames can come in different shapes and sizes (different dynamics), and your job is to help manage the execution of whatever the concrete instance is of the minigame. So it could be a typing word game, or a drawing game, but regardless, these need to be managed in terms of time, starting and stopping, analyzing, etc. Your job will be related to this and possibly interact with the game's own agent.`,\n].join('\\n');\nexport const AGENT_INITIAL_SYSTEM_TEXT_MINIGAMEAGENT = [\n    AGENT_INITIAL_SYSTEM_SUPER_COOL,\n    AGENT_SYSTEM_PROMPT_COMMON_INSTRUCTIONS,\n    AGENT_WEBSITE_DESCRIPTION,\n    AGENT_GOAL_MINIGAMEAGENT,\n].join('\\n');\nconst AGENT_INITIAL_CHAT_HI_PLEASEINTRO_YOURSELF_MINIGAMEAGENT = [\n    AGENT_INITIAL_CHAT_GIVESELFNAME,\n].join('\\n');\nexport const AGENT_INITIAL_CHAT_TEXT_MINIGAMEAGENT = [\n    AGENT_INITIAL_CHAT_HI_PLEASEINTRO_YOURSELF_MINIGAMEAGENT,\n].join('\\n');\nexport const CHAT_WITH_AGENT_PLACEHOLDER_MINIGAMEAGENT = '';\n", "import { clone, delay, extractErrorMsg, pretty } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { IbGib_V1 } from \"@ibgib/ts-gib/dist/V1/types.mjs\";\nimport { validateIbGibAddr } from \"@ibgib/ts-gib/dist/V1/validate-helper.mjs\";\nimport { getIbAndGib, getIbGibAddr, } from \"@ibgib/ts-gib/dist/helper.mjs\";\nimport { IbGibAddr, } from \"@ibgib/ts-gib/dist/types.mjs\";\nimport { getGibInfo, isPrimitive } from \"@ibgib/ts-gib/dist/V1/transforms/transform-helper.mjs\";\nimport { getTjpAddr } from \"@ibgib/core-gib/dist/common/other/ibgib-helper.mjs\";\nimport { appendToTimeline } from \"@ibgib/core-gib/dist/timeline/timeline-api.mjs\";\nimport { getAgentsSvc } from \"@ibgib/web-gib/dist/witness/agent/agents-service-v1.mjs\";\nimport { GEMINI_DEFAULT_MODEL_STR, GeminiModel } from \"@ibgib/web-gib/dist/witness/agent/gemini/gemini-constants.mjs\";\nimport { registerDomainIbGibWithAgentIndex } from \"@ibgib/web-gib/dist/witness/agent/agent-helpers.mjs\";\nimport { getGlobalMetaspace_waitIfNeeded, } from \"@ibgib/web-gib/dist/helpers.mjs\";\nimport { APIFunctionInfo } from \"@ibgib/web-gib/dist/api/api-types.mjs\";\nimport { COMMAND_BASE_SCHEMA_PROPERTIES } from \"@ibgib/web-gib/dist/api/commands/command-constants.mjs\";\nimport { getCommandService } from \"@ibgib/web-gib/dist/api/commands/command-service-v1.mjs\";\nimport { CommandDataBase } from \"@ibgib/web-gib/dist/api/commands/command-types.mjs\";\nimport { FUNCTION_CALL_EXAMPLES_HEADER } from \"@ibgib/web-gib/dist/api/api-constants.mjs\";\n\nimport { GLOBAL_LOG_A_LOT } from \"../../../constants.mjs\";\nimport { getDefaultFnGetAPIKey, } from \"../../../helpers.web.mjs\";\nimport {\n    AGENT_AVAILABLE_FUNCTIONS_MINIGAMEAGENT,\n    GEMINI_SCHEMA_MINIGAME_CONTEXT_ADDR, GEMINI_SCHEMA_MINIGAME_DESCRIPTION,\n    GEMINI_SCHEMA_MINIGAME_GAMETYPE,\n    // GEMINI_SCHEMA_MINIGAME_GAMEVARIANT,\n    GEMINI_SCHEMA_MINIGAME_INSTRUCTIONS, GEMINI_SCHEMA_MINIGAME_KEYWORDS,\n    GEMINI_SCHEMA_MINIGAME_NAME, MINIGAME_REL8N_NAME, MinigameGameType,\n    MinigameGameVariant,\n} from \"../../../common/minigame/minigame-constants.mjs\";\nimport { createMinigameIbGib } from \"../../../common/minigame/minigame-helper.mjs\";\nimport { AGENT_INITIAL_CHAT_TEXT_MINIGAMEAGENT, AGENT_INITIAL_SYSTEM_TEXT_MINIGAMEAGENT, AGENT_SPECIAL_IBGIB_TYPE_MINIGAMEAGENT } from \"../../../agent-texts/minigame-agent-texts.mjs\";\nimport { DEFAULT_MINIGAME_DATA_V1, MinigameIbGib_V1 } from \"../../../common/minigame/minigame-types.mjs\";\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\n// #region constants\nconst FUNCTION_NAME = 'minigameBuilderStart';\n\n/**\n * chat category here as this is a chat-related command.\n */\nconst CMD_CATEGORY = 'minigame';\n/**\n * helloWorld here is the specific command modifier which narrows down to a command\n * instance, similar to a fully curried function.\n */\nconst CMD_MODIFIERS: string[] = [FUNCTION_NAME];\nconst EXAMPLE_INPUT_MINIGAMEBUILDER_START: Partial<MinigameBuilderStartOpts> = {\n    agentId: 'SomeAgentIdHash',\n    notesToSelf: 'Example of a minigameBuilderStart function call. Note repromptWithResult is true to add stimuli next.',\n    repromptWithResult: true,\n    name: 'Example Minigame',\n    description: 'In this contrived example minigame, you type random text!',\n    instructions: 'Type the text exactly as it appears. First, be accurate and smooth, like a pianist, and only then push your speed.',\n    gameType: MinigameGameType.typing,\n    // gameVariant: MinigameGameVariant.default,\n    keywords: ['example', 'english', 'typing-test', 'typing-focus'],\n};\nconst EXAMPLE_INPUT_MINIGAMEBUILDER_START_ANTIPHONY: Partial<MinigameBuilderStartOpts> = {\n    agentId: 'SomeAgentIdHash',\n    notesToSelf: 'Example of a minigameBuilderStart function call for a typing game, antiphony variant. Note repromptWithResult is true to add stimuli next.',\n    repromptWithResult: true,\n    name: 'Example Antiphony',\n    description: 'In this contrived example minigame, you type the answer to the question!',\n    instructions: 'Answer the questions.',\n    gameType: MinigameGameType.typing,\n    // gameVariant: MinigameGameVariant.antiphony,\n    keywords: ['example', 'english', 'q-and-a', 'trivia'],\n};\nconst EXAMPLE_INPUT_MINIGAMEBUILDER_START_FITB: Partial<MinigameBuilderStartOpts> = {\n    agentId: 'SomeAgentIdHash',\n    notesToSelf: 'Example of a minigameBuilderStart function call for a typing game, fitb (fill-in-the-blank) variant. Note repromptWithResult is true to add stimuli next.',\n    repromptWithResult: true,\n    name: 'Example Fill-in-the-blank',\n    description: 'In this contrived example minigame, you type what goes in the blank(s)!',\n    instructions: 'Type what goes in each blank. For multiple blanks, use a comma to separate your answers.',\n    gameType: MinigameGameType.typing,\n    // gameVariant: MinigameGameVariant.fitb,\n    keywords: ['example', 'german', 'de-DE', 'deutsch', 'vocabulary'],\n};\n\nconst EXAMPLES = [\n    // `\\`\\`\\`typescript\\n${FUNCTION_CALL_EXAMPLES_HEADER}\\n${pretty(EXAMPLE_INPUT_TELLUSER)}\\n\\`\\`\\``,\n    FUNCTION_CALL_EXAMPLES_HEADER,\n    pretty(EXAMPLE_INPUT_MINIGAMEBUILDER_START),\n    pretty(EXAMPLE_INPUT_MINIGAMEBUILDER_START_ANTIPHONY),\n    pretty(EXAMPLE_INPUT_MINIGAMEBUILDER_START_FITB),\n].join('\\n');\nconst FUNCTION_DESCRIPTION = `Starts a builder to construct a minigame ibgib. The addr returned will be the tjpAaddr of the minigame, which acts as an id for the minigame ibgib's timeline. It is this address that you should pass to other builder steps.\\n\\n${EXAMPLES}`;\n// #endregion constants\n\n\n/**\n * @interface MinigameBuilderStartOpts - Options for the minigameBuilderStart command.\n * @extends CommandDataBase\n */\nexport interface MinigameBuilderStartOpts extends CommandDataBase<typeof CMD_CATEGORY, typeof CMD_MODIFIERS> {\n    /**\n     * agent's id doing the telling\n    */\n    agentId?: string;\n    /**\n     * @property agentName - the name which the model chooses to\n     * use to represent him/her/itself.\n     */\n    agentName?: string;\n    /**\n     * address to the context (project/project child atow 06/2025) in which the\n     * minigame should be created (will be rel8d to).\n     */\n    contextIbGibAddr: IbGibAddr;\n\n    /**\n     * It's the name of the game.\n     */\n    name: string;\n    /**\n     * Description of the minigame.\n     * This can be a more detailed explanation of the minigame's purpose or scope.\n     */\n    description: string;\n    /**\n     * how to play the game. shown before starting.\n     */\n    instructions: string;\n    /**\n     * Broad category of the minigame. Only one initially is \"typing\" (though\n     * the user could use the voice typing).\n     */\n    gameType: MinigameGameType;\n    /**\n     * Specific sub-type of the {@link gameType}. This determines specifics of\n     * the minigame gameplay.\n     */\n    gameVariant?: MinigameGameVariant;\n    /**\n     * Includes the state of the game, as well as any interactions any of the\n     * player's have made.\n     *\n     * in typing, this is where we include what stimuli we have shown to the user,\n     * what their responses were, timestamps, etc.\n     */\n    gameState?: any;\n    /**\n     * List of keywords that describe/pertain to this minigame, e.g., 'spanish',\n     * 'verbs', 'conjugation', 'cover-cropping', etc.\n     *\n     * Note that our learning model is not just subject-related but\n     * trace-strength related. So the material itself is not the only important\n     * thing, like when buliding a team it's good to have diversification such\n     * as a comedian/light-hearted person. The learning equivalent is pairing\n     * certain groups of text with some fun/humorous theme.\n     */\n    keywords: string[];\n}\n\nexport interface MinigameBuilderStartResult {\n    // newContextIbGib: IbGib_V1;\n    // minigameIbGib: MinigameIbGib_V1;\n    // builderId: string;\n    minigameAddr: IbGibAddr;\n}\n\n/**\n * @interface MinigameBuilderStartCommandData - Command data for the\n * minigameBuilderStart command.\n * @extends CommandDataBase\n */\nexport interface MinigameBuilderStartCommandData\n    extends CommandDataBase<typeof CMD_CATEGORY, typeof CMD_MODIFIERS> {\n    /**\n     * agent's id doing the telling\n     */\n    agentId?: string;\n    /**\n     * @property agentName - the name which the model chooses to\n     * use to represent him/her/itself.\n     */\n    agentName?: string;\n    /**\n     * address to the context (project/project child atow 06/2025) in which the\n     * minigame should be created (will be rel8d to).\n     */\n    contextIbGibAddr: IbGibAddr;\n\n    /**\n     * It's the name of the game.\n     */\n    name: string;\n    /**\n     * Description of the minigame.\n     * This can be a more detailed explanation of the minigame's purpose or scope.\n     */\n    description: string;\n    /**\n     * how to play the game. shown before starting.\n     */\n    instructions: string;\n    /**\n     * Broad category of the minigame. Only one initially is \"typing\" (though\n     * the user could use the voice typing).\n     */\n    gameType: MinigameGameType;\n    /**\n     * Specific sub-type of the {@link gameType}. This determines specifics of\n     * the minigame gameplay.\n     */\n    gameVariant?: MinigameGameVariant;\n    /**\n     * Includes the state of the game, as well as any interactions any of the\n     * player's have made.\n     *\n     * in typing, this is where we include what stimuli we have shown to the user,\n     * what their responses were, timestamps, etc.\n     */\n    gameState?: any;\n    /**\n     * List of keywords that describe/pertain to this minigame, e.g., 'spanish',\n     * 'verbs', 'conjugation', 'cover-cropping', etc.\n     *\n     * Note that our learning model is not just subject-related but\n     * trace-strength related. So the material itself is not the only important\n     * thing, like when buliding a team it's good to have diversification such\n     * as a comedian/light-hearted person. The learning equivalent is pairing\n     * certain groups of text with some fun/humorous theme.\n     */\n    keywords: string[];\n}\n\n/**\n * Wrapper function to enqueue the minigameBuilderStart command.\n * @param {MinigameBuilderStartOpts} opts - Options for telling the user something.\n * @returns {Promise<MinigameBuilderStartResult>} A promise that resolves when the command is enqueued.\n */\nfunction minigameBuilderStartViaCmd(opts: MinigameBuilderStartOpts): Promise<MinigameBuilderStartResult> {\n    const lc = `[${minigameBuilderStartViaCmd.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n        if (logalot) { console.log(`${lc} minigameBuilderStartViaCmd raw incoming opts: ${pretty(opts)} (I: genuuid)`); }\n\n        const commandService = getCommandService();\n        const command: MinigameBuilderStartCommandData = {\n            ...opts,\n            cmd: CMD_CATEGORY,\n            cmdModifiers: CMD_MODIFIERS,\n        };\n        if (logalot) { console.log(`${lc} minigameBuilderStartViaCmd command: ${pretty(command)} (I: genuuid)`); }\n        return new Promise<MinigameBuilderStartResult>((resolve, reject) => {\n            commandService.enqueueCommand({ command, resolve, reject });\n        });\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * Implementation function for the minigameBuilderStart command.\n *\n * ## notes on context\n *\n * LLMs are designed to say/do something upon being prompted. In code, however,\n * it is beneficial to sometimes just give information and let the agent decide\n * whether or not to act upon it. Right now I have this doubling as an \"ack\"\n * command that acts like a blackhole for when the agent decides no action is\n * required. So if the context is a primitive, then this will \"fail\" silently.\n *\n *\n * @param {MinigameBuilderStartOpts} opts - Options for telling the user something.\n * @returns {Promise<MinigameBuilderStartResult>} A promise that resolves when the command is executed (immediately).\n */\nasync function minigameBuilderStartImpl(opts: MinigameBuilderStartOpts): Promise<MinigameBuilderStartResult> {\n    const lc = `[${minigameBuilderStartImpl.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n\n        console.log(`${lc} opts: ${pretty(opts)}`);\n\n        const metaspace = await getGlobalMetaspace_waitIfNeeded();\n        const contextAddr = opts.contextIbGibAddr;\n        if (!contextAddr) { throw new Error(`contextIbGibAddr is falsy (was not provided by model if this was a function call request). This should be required in the gemini schema. (E: genuuid)`); }\n\n        const addrErrors = validateIbGibAddr({ addr: contextAddr }) ?? [];\n        if (addrErrors.length > 0) {\n            throw new Error(`${lc} agent has provided a non-ibgib addr for contextAddr: ${contextAddr}. addrErrors: ${addrErrors}. opts: ${pretty(opts)} (E: genuuid)`)\n        }\n        if (isPrimitive({ gib: getIbAndGib({ ibGibAddr: contextAddr }).gib })) {\n            throw new Error(`agent has tried calling this with a primitive context address. opts: ${pretty(opts)} (E: genuuid)`);\n        }\n        const space = await metaspace.getLocalUserSpace({ lock: false });\n        if (!space) { throw new Error(`(UNEXPECTED) couldn't get default local user space? (E: genuuid)`); }\n\n        // // adding agent name elsewhere\n        // // const agentNamePlusText = `${opts.agentName}: ${opts.text}`;\n\n\n        // create the minigame\n        const { name, description, instructions, gameType, gameVariant, keywords, } = opts;\n        const { newIbGib: minigameIbGib } = await createMinigameIbGib({\n            srcMinigameIbGib: undefined, // ignore right now\n            data: {\n                ...DEFAULT_MINIGAME_DATA_V1,\n                '@contextAddr': contextAddr,\n                // ...opts,\n                name, description, instructions,\n                gameType,\n                // gameVariant, moving gameVariant into stimulus\n                gameMeta: {}, // to be edited by other function calls\n                gameState: {}, // to be edited by other function calls\n                keywords,\n\n                // not playable yet, only initializing minigame prototype\n                playable: false,\n            },\n            saveInSpace: true,\n            space,\n            registerNewIbGib: true,\n        });\n        const tjpAddr = getTjpAddr({ ibGib: minigameIbGib, defaultIfNone: 'incomingAddr' });\n        if (!tjpAddr) { throw new Error(`(UNEXPECTED) tjpAddr falsy? we chose incomingAddr when getTjpAddr called, so should be set to incoming addr. (E: e25f482a29543d2c748f0de869914925)`); }\n        const { gib: minigameTjpGib } = getIbAndGib({ ibGib: minigameIbGib });\n\n        // create an agent specific to that minigame\n        const agentsSvc = getAgentsSvc(); // Assuming getAgentsSvc is available\n        const newAgentIbGib = await agentsSvc.createNewAgent({\n            metaspace,\n            superSpace: undefined, // uses default local user space as the super space\n            name: `MinigameAgent-${minigameTjpGib}`,\n            api: 'gemini',\n            model: GEMINI_DEFAULT_MODEL_STR,\n            availableFunctions: clone(AGENT_AVAILABLE_FUNCTIONS_MINIGAMEAGENT),\n            initialSystemText: [\n                AGENT_INITIAL_SYSTEM_TEXT_MINIGAMEAGENT,\n            ].join('\\n'),\n            initialChatText: [\n                AGENT_INITIAL_CHAT_TEXT_MINIGAMEAGENT,\n            ].join('\\n'),\n            fnGetAPIKey: getDefaultFnGetAPIKey(),\n            type: AGENT_SPECIAL_IBGIB_TYPE_MINIGAMEAGENT,\n            addToAgentsTag: true,\n        });\n        await registerDomainIbGibWithAgentIndex({\n            domainIbGib: minigameIbGib,\n            agentIbGib: newAgentIbGib,\n            metaspace,\n            space,\n        });\n\n        // get the latest context ibgib and rel8 the new minigame to it\n        let latestContextIbGib: IbGib_V1 | undefined = undefined;\n        const latestContextAddr = await metaspace.getLatestAddr({\n            addr: contextAddr,\n            space,\n        });\n        if (latestContextAddr) {\n            const resGetLatest =\n                await metaspace.get({ addrs: [latestContextAddr], space, });\n            if (resGetLatest.errorMsg || (resGetLatest.ibGibs ?? []).length !== 1) {\n                throw new Error(`couldn't get latest context ibgib (${latestContextAddr}) from super space (${space.ib}). errorMsg: ${resGetLatest.errorMsg ?? '[unknown error]'} (E: genuuid)`);\n            }\n            latestContextIbGib = resGetLatest.ibGibs!.at(0)!;\n        }\n        if (!latestContextIbGib) { throw new Error(`(UNEXPECTED) couldn't get latest context ibgib? (${latestContextAddr}) (E: genuuid)`); }\n        const newContextIbGib = await appendToTimeline({\n            timeline: latestContextIbGib,\n            metaspace,\n            rel8nInfos: [{ rel8nName: MINIGAME_REL8N_NAME, ibGibs: [minigameIbGib], }],\n            space,\n        });\n\n\n        const minigameAddr = getTjpAddr({ ibGib: minigameIbGib });\n        if (!minigameAddr) { throw new Error(`(UNEXPECTED) minigameIbGib wasn't created with a tjp? (E: 98bdb3d37237f8c3880c176840cab325)`); }\n\n        return {\n            // newContextIbGib,\n            // minigameIbGib,\n            // builderId: getTjpAddr({ibGib: minigameIbGib}),\n            minigameAddr,\n        }\n\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * API function info for the minigameBuilderStart command.\n */\nexport const minigameBuilderStartFunctionInfo: APIFunctionInfo<typeof minigameBuilderStartViaCmd> = {\n    nameOrId: FUNCTION_NAME,\n    fnViaCmd: minigameBuilderStartViaCmd,\n    functionImpl: minigameBuilderStartImpl,\n    cmd: CMD_CATEGORY,\n    cmdModifiers: CMD_MODIFIERS,\n    schema: {\n        name: FUNCTION_NAME,\n        description: FUNCTION_DESCRIPTION,\n        parameters: {\n            type: 'object',\n            properties: {\n                ...COMMAND_BASE_SCHEMA_PROPERTIES,\n                contextIbGibAddr: GEMINI_SCHEMA_MINIGAME_CONTEXT_ADDR,\n                name: GEMINI_SCHEMA_MINIGAME_NAME,\n                description: GEMINI_SCHEMA_MINIGAME_DESCRIPTION,\n                instructions: GEMINI_SCHEMA_MINIGAME_INSTRUCTIONS,\n                gameType: GEMINI_SCHEMA_MINIGAME_GAMETYPE,\n                // gameVariant: GEMINI_SCHEMA_MINIGAME_GAMEVARIANT,\n                keywords: GEMINI_SCHEMA_MINIGAME_KEYWORDS,\n            },\n            required: [\n                'agentId', // base\n                'contextIbGibAddr',\n                'name',\n                'description',\n                'instructions',\n                'gameType',\n                // 'gameVariant',\n                'keywords'\n            ],\n        },\n    },\n};\n", "import thisHtml from './project.html';\nimport thisCss from './project.css';\nimport stylesCss from '../../../styles.css';\nimport rootCss from '../../../root.css';\n\nimport { clone, delay, extractErrorMsg, getSaferSubstring, getTimestampInTicks, pretty, } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { IbGibAddr, TjpIbGibAddr, } from \"@ibgib/ts-gib/dist/types.mjs\";\nimport { IbGib_V1 } from \"@ibgib/ts-gib/dist/V1/types.mjs\";\nimport { getGibInfo, isPrimitive } from \"@ibgib/ts-gib/dist/V1/transforms/transform-helper.mjs\";\nimport { getIbAndGib, getIbGibAddr } from \"@ibgib/ts-gib/dist/helper.mjs\";\nimport { MetaspaceService } from \"@ibgib/core-gib/dist/witness/space/metaspace/metaspace-types.mjs\";\nimport { createCommentIbGib } from \"@ibgib/core-gib/dist/common/comment/comment-helper.mjs\";\nimport { getTjpAddr } from \"@ibgib/core-gib/dist/common/other/ibgib-helper.mjs\";\nimport { fnObs } from \"@ibgib/core-gib/dist/common/pubsub/observer/observer-helper.mjs\";\nimport { IbGibTimelineUpdateInfo } from \"@ibgib/core-gib/dist/common/other/other-types.mjs\";\nimport { appendToTimeline, mut8Timeline } from \"@ibgib/core-gib/dist/timeline/timeline-api.mjs\";\nimport {\n    getDeterministicColorInfo, getGlobalMetaspace_waitIfNeeded,\n} from \"@ibgib/web-gib/dist/helpers.mjs\";\nimport {\n    IbGibDynamicComponentInstanceBase, IbGibDynamicComponentMetaBase,\n    IbGibDynamicComponentInstanceBase_ParentOfTabs,\n} from \"@ibgib/web-gib/dist/ui/component/ibgib-dynamic-component-bases.mjs\";\nimport {\n    ElementsBase, ChildInfoBase, IbGibDynamicComponentInstance,\n    IbGibDynamicComponentInstanceInitOpts,\n} from \"@ibgib/web-gib/dist/ui/component/component-types.mjs\";\nimport { getComponentSvc } from \"@ibgib/web-gib/dist/ui/component/ibgib-component-service.mjs\";\nimport { getColorStrings, } from \"@ibgib/web-gib/dist/helpers.mjs\";\nimport {\n    alertUser, copyToClipboard, highlightElement, promptForText,\n    shadowRoot_getElementById,\n} from \"@ibgib/web-gib/dist/helpers.web.mjs\";\nimport { askForPersistStorage, } from \"@ibgib/web-gib/dist/storage/storage-helpers.web.mjs\";\nimport { LensMode, ProjectIbGib_V1 } from \"@ibgib/web-gib/dist/common/project/project-types.mjs\";\nimport { isProjectIbGib_V1 } from \"@ibgib/web-gib/dist/common/project/project-helper.mjs\";\nimport { PROJECT_CHILD_TEXT_REL8N_NAME, } from \"@ibgib/web-gib/dist/common/project/project-constants.mjs\";\nimport {\n    AGENT_AVAILABLE_FUNCTIONS_PROJECTAGENT,\n    AGENT_AVAILABLE_FUNCTIONS_PROJECTCHILDTEXTAGENT,\n} from \"@ibgib/web-gib/dist/common/project/project-agent-functions.mjs\";\nimport { getAgentsSvc } from \"@ibgib/web-gib/dist/witness/agent/agents-service-v1.mjs\";\nimport { GEMINI_DEFAULT_MODEL_STR, } from \"@ibgib/web-gib/dist/witness/agent/gemini/gemini-constants.mjs\";\nimport { registerDomainIbGibWithAgentIndex } from \"@ibgib/web-gib/dist/witness/agent/agent-helpers.mjs\";\nimport { Settings_General, Settings_Project, } from \"@ibgib/web-gib/dist/common/settings/settings-types.mjs\";\nimport { getSectionName, } from \"@ibgib/web-gib/dist/common/settings/settings-helpers.mjs\";\nimport { SettingsType } from \"@ibgib/web-gib/dist/common/settings/settings-constants.mjs\";\n\nimport { GLOBAL_LOG_A_LOT, } from \"../../../constants.mjs\";\nimport {\n    getComponentCtorArg,\n    getDefaultFnGetAPIKey,\n    getIbGibGlobalThis_BlankGib, getIbGibGlobalThis_Common,\n} from \"../../../helpers.web.mjs\";\nimport { RAW_COMPONENT_NAME, RawComponentInstance } from \"../../common/raw/raw-component-one-file.mjs\";\nimport { TEXTEDITOR_COMPONENT_NAME, TextEditorComponentInstance } from \"../../common/text-editor/text-editor-component-one-file.mjs\";\nimport { AGENT_INITIAL_CHAT_TEXT_PROJECTCHILDTEXTAGENT, AGENT_INITIAL_SYSTEM_TEXT_PROJECTCHILDTEXTAGENT, AGENT_SPECIAL_IBGIB_TYPE_PROJECTCHILDTEXTAGENT } from \"../../../agent-texts/project-child-text-agent-texts.mjs\";\nimport { isMinigameIbGib_V1 } from \"../../../common/minigame/minigame-helper.mjs\";\nimport { MINIGAME_COMPONENT_NAME } from \"../../minigame/minigame-component-one-file.mjs\";\nimport { minigameBuilderStartFunctionInfo, MinigameBuilderStartResult } from \"../../../api/commands/minigame/minigame-builder-start.mjs\";\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\nexport const PROJECT_COMPONENT_NAME: string = 'ibgib-project';\n\nexport class ProjectComponentMeta extends IbGibDynamicComponentMetaBase {\n    protected override lc: string = `[${ProjectComponentMeta.name}]`;\n\n    /**\n     * temporary regexp path for our initial dev. this component will become\n     * attached to actual ib^gib addrs\n     */\n    // routeRegExp?: RegExp = new RegExp(PROJECT_COMPONENT_NAME);\n    routeRegExp?: RegExp = new RegExp(`^${PROJECT_COMPONENT_NAME}$`);\n    // routeRegExp?: RegExp = /apps\\/web1\\/gib\\/contact.html/;\n\n    componentName: string = PROJECT_COMPONENT_NAME;\n\n    constructor() {\n        super(getComponentCtorArg());\n        customElements.define(this.componentName, ProjectComponentInstance);\n    }\n\n    /**\n     * for a project, we don't have any additional info in the path.\n     */\n    async createInstance({\n        path,\n        ibGibAddr\n    }: {\n        path: string;\n        ibGibAddr: IbGibAddr;\n    }): Promise<IbGibDynamicComponentInstance> {\n        const lc = `${this.lc}[${this.createInstance.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n            const component = document.createElement(this.componentName) as ProjectComponentInstance;\n            await component.initialize({\n                ibGibAddr,\n                meta: this,\n                html: thisHtml,\n                css: [rootCss, stylesCss, thisCss],\n            });\n            return component;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n}\n\ninterface ProjectElements extends ElementsBase {\n    headerEl: HTMLElement;\n    headerTabsEl: HTMLElement | undefined;\n    // nameEl: HTMLHeadingElement;\n    // descEl: HTMLParagraphElement;\n    footerEl: HTMLElement;\n    lensBarEl: HTMLElement;\n    rawLensBtnEl: HTMLButtonElement;\n    textLensBtnEl: HTMLButtonElement;\n    minigameLensBtnEl: HTMLButtonElement;\n    addBtnEl: HTMLElement | undefined;\n    addPopoverEl: HTMLElement | undefined;\n    ellipsisBtnEl: HTMLElement | undefined;\n    ellipsisPopoverEl: HTMLElement | undefined;\n}\n\nexport type ProjectChildComponentInstance = RawComponentInstance | TextEditorComponentInstance;\n\n/**\n * A project's children are ibgibs\n */\nexport interface ProjectChildTabInfo\n    extends ChildInfoBase<IbGibDynamicComponentInstance<any, any>> {\n    componentCache: { [lensMode: string]: ProjectChildComponentInstance }\n}\n\nexport class ProjectComponentInstance\n    extends IbGibDynamicComponentInstanceBase_ParentOfTabs<Settings_Project, ProjectIbGib_V1, ProjectElements, ProjectChildTabInfo>\n    implements IbGibDynamicComponentInstance<ProjectIbGib_V1, ProjectElements> {\n    protected override lc: string = `[${ProjectComponentInstance.name}]`;\n\n    metaspace: MetaspaceService | undefined;\n\n    protected get settingsType(): SettingsType {\n        return SettingsType.project;\n    }\n\n    // private _reloadingTabs = false;\n\n    /**\n     * using this as a temporary hack to decide which concrete component to view\n     * the child ibgib with.\n     */\n    private _lensMode: LensMode = LensMode.raw;\n    get lensMode(): LensMode { return this._lensMode; }\n\n    constructor() {\n        super();\n    }\n\n    public override async activateIbGib({ addr, ibGib, }: { addr?: IbGibAddr; ibGib?: IbGib_V1; }): Promise<void> {\n        const lc = `${this.lc}[${this.activateIbGib.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 9b05f2064bc86002d8399af9e6e15825)`); }\n            if (!addr && !ibGib) { throw new Error(`(UNEXPECTED) both addr and ibGib falsy? either addr or ibGib required. (E: 1762be0d11e851dbc8d639882671c825)`); }\n\n            addr ??= getIbGibAddr({ ibGib });\n\n            await super.activateIbGib({ addr, ibGib });\n\n            // check the current settings. add the ibGib's tjpAddr to\n            // the project settings list of open child tjp addrs if it's not\n            // there already.\n\n            // let projectSettings: Settings_Project | undefined = await this.getCurrentProjectSettings();\n            const settings_current = await this.getSettings<Settings_Project>({\n                settingsType: this.settingsType,\n                useCase: 'current',\n            });\n            if (!settings_current) {\n                throw new Error(`(UNEXPECTED) couldn't get current settings? i thought this would initialized by now. (E: 065648bc2c58dfa25d58796bed6a8e25)`);\n            }\n\n            const metaspace = await getGlobalMetaspace_waitIfNeeded();\n\n            if (!ibGib) {\n                const resGet = await metaspace.get({ addrs: [addr], });\n                if (!resGet || resGet.errorMsg || (resGet.ibGibs ?? []).length !== 1) {\n                    throw new Error(`couldn't get addr (${addr}) from default local user space. wrong space? i need to figure out how I want the project space handled still (atow 06/2025) (E: 37dc4cb82971bce8652bb934bd757825)`);\n                }\n                ibGib = resGet.ibGibs![0];\n            }\n            const tjpAddr = getTjpAddr({ ibGib, defaultIfNone: 'incomingAddr' });\n            if (!tjpAddr) { throw new Error(`(UNEXPECTED) tjpAddr falsy? 'incomingAddr' was used as the default option. (E: d42478a570da8ccc1804ea58fc5f4825)`); }\n\n            if (this._reloadingTabs) {\n                // we are loading the current child ibgib tabs and we shouldn't\n                // do any updating tothe settings\n                console.log(`${lc} just loading ibgib, so nothing further to do here. returning early (I: a856887a5858e6d7efc297c80e2d0825)`)\n                return; /* <<<< returns early */\n            } else {\n                // we are NOT loading and we should persist this change to\n                // settings\n                let modified = false;\n                if (!settings_current.openChildTjpAddrs.includes(tjpAddr)) {\n                    settings_current.openChildTjpAddrs.push(tjpAddr);\n                    modified = true;\n                }\n                if (settings_current.activeChildTjpAddr !== tjpAddr) {\n                    settings_current.activeChildTjpAddr = tjpAddr;\n                    modified = true;\n                }\n                if (modified) {\n                    const sectionName_current = await getSectionName({\n                        settingsType: this.settingsType,\n                        useCase: 'current',\n                    });\n                    const _newSettings = await mut8Timeline({\n                        timeline: this.settings!.ibGib!,\n                        metaspace,\n                        mut8Opts: {\n                            dataToAddOrPatch: {\n                                sections: {\n                                    [sectionName_current]: settings_current,\n                                }\n                            },\n                        },\n                    });\n                } else {\n                    console.warn(`${lc} already activated? should this get this far if we're clicking a tab that's already activated? (W: 4c6d98e8809813a4f8a2075b113cb325)`)\n                }\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    protected async createAndLoadChildComponent({\n        addr,\n    }: {\n        addr: IbGibAddr,\n    }): Promise<ProjectChildComponentInstance> {\n        const lc = `${this.lc}[${this.createAndLoadChildComponent.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: a080988fa988782fe898352a3a0aa825)`); }\n            const componentSvc = await getComponentSvc();\n            let componentPath: string;\n\n            // hack to fix this last bug. take this out\n            // if (this.lensMode === LensMode.minigame) {\n            //     await this.activateLensMode({ lensMode: 'raw', skipInject: true });\n            // }\n\n            // hack while dev to force injecting minigame component when\n            // activating a minigame ibgib.\n            let useLensMode = this.lensMode;\n            // if (addr.split(' ').at(0)! === MINIGAME_ATOM) {\n            //     useLensMode = LensMode.minigame;\n            // }\n\n            switch (useLensMode) {\n                case LensMode.raw:\n                    componentPath = RAW_COMPONENT_NAME; break;\n                case LensMode.text:\n                    componentPath = TEXTEDITOR_COMPONENT_NAME; break;\n                case LensMode.minigame:\n                    componentPath = MINIGAME_COMPONENT_NAME; break;\n                default:\n                    throw new Error(`(UNEXPECTED) unknown lensMode (${this.lensMode})? (E: b2b8895cee48fea7c18c225d7e2b3825)`);\n            }\n            const component = await componentSvc.getComponentInstance({\n                path: componentPath,\n                ibGibAddr: addr,\n                useRegExpPrefilter: true,\n            }) as ProjectChildComponentInstance | undefined;\n            if (!component) {\n                debugger; // error couldn't create component instance for project?\n                throw new Error(`(UNEXPECTED) projectComponent falsy? couldn't create component instance for project? (E: efeee6b003f5b0af9b0fda679593c725)`);\n            }\n            // await projectComponent.loadIbGib();\n            // await projectComponent.initialized;\n            if (!component.ibGib) {\n                debugger; // error couldn't load ibGib for project?\n                throw new Error(`(UNEXPECTED) ibGib falsy? couldn't load ibGib for project? (E: 352f152063a97e67f769babfadfe1e25)`);\n            }\n\n            // if (component.agent) {\n            //     this.loadAgentsCoupledToIbGib({dontThrowIfNone: true});\n            // }\n\n            // guaranteed loaded ibGib\n            return component;\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * @internal\n     * gets the project tab info for the given addr.\n     *\n     * creates and loads the project ibgib component, which itself loads the\n     * ibgib internally (or throws) if not already loaded.\n     *\n     * @returns ProjectTabInfo with fully loaded component and ibgib.\n     *\n     * @see {@link ProjectChildTabInfo}\n     */\n    protected async getLoadedChildInfo({\n        addr,\n        ibGib,\n    }: {\n        addr: IbGibAddr,\n        ibGib?: IbGib_V1,\n    }): Promise<ProjectChildTabInfo> {\n        const lc = `${this.lc}[${this.getLoadedChildInfo.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 8bc42ecb105f4ca9dff6590c1a9c2f25)`); }\n            if (!addr) { throw new Error(`(UNEXPECTED) addr falsy? (E: 25e89572d09ae8dd581ba60bde1c9825)`); }\n            const tjpGib = getGibInfo({ ibGibAddr: addr }).tjpGib ?? getIbAndGib({ ibGibAddr: addr }).gib;\n\n            /** the point of this function is to populate this */\n            let tabInfo: ProjectChildTabInfo;\n\n            /**\n             * filtered for same timeline of addr via tjpGib\n             */\n            const filtered = this.childInfos.filter(x => {\n                const tabGibInfo = getGibInfo({ ibGibAddr: x.addr });\n                const tabTjpGib = tabGibInfo.tjpGib ?? getIbAndGib({ ibGibAddr: x.addr }).gib;\n                return tabTjpGib === tjpGib;\n            });\n            if (filtered.length > 0) {\n                // already have an existing tab, but maybe not component for the current lens mode\n                if (filtered.length !== 1) { console.error(`(UNEXPECTED) filtered.length !== 1? logging error here but we're just going to use the first one. filtered addrs:\\n${filtered.map(x => x.addr).join('\\n')}(E: ef126a918a93f1c13d0c4b41d5194b25)`); }\n                tabInfo = filtered[0];\n                let component = tabInfo.componentCache[this.lensMode];\n                if (!component) {\n                    component = await this.createAndLoadChildComponent({ addr });\n                    tabInfo.componentCache[this.lensMode] = component;\n                }\n                tabInfo.component = component;\n            } else {\n                // no existing tab, so create new project tab info\n                // const component = await fnCreateAndLoadProjectComponent();\n                const component = await this.createAndLoadChildComponent({ addr });\n                ibGib = component.ibGib!; // guaranteed in above fn\n\n                // both addr and ibGib guaranteed now creating the child\n                // component could have gotten the latest ibgib which would make\n                // the addr be different than the ibGib's addr proper. so put\n                // these back in sync\n                addr = getIbGibAddr({ ibGib });\n                const tabBtnEl = await this.addChild({ addr, ibGib });\n                tabInfo = {\n                    addr,\n                    childBtnEl: tabBtnEl,\n                    component,\n                    active: false,\n                    componentCache: { [this.lensMode]: component }\n                };\n                this.childInfos.push(tabInfo);\n            }\n\n            return tabInfo;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private updateTabTitleAndText({\n        span,\n        ibGib,\n    }: {\n        span: HTMLElement,\n        ibGib: IbGib_V1,\n    }): void {\n        const lc = `[${this.updateTabTitleAndText.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: d1c34e159aecc0bf06f57a759b06a625)`); }\n\n            if (!ibGib.data) { throw new Error(`(UNEXPECTED) ibGib.data falsy? (E: a22dd936f38a779c0d61489c7d7c9125)`); }\n            if (!ibGib.data.name) { console.warn(`${lc} ibGib.data.name falsy? (W: genuuid)`); }\n            const title = ibGib.data.name ?? 'untitled'\n            const desc = ibGib.data.description ?? '';\n            span.title = desc ? `${title}\\n${desc}` : title;\n            const MAX_TAB_TEXT_LENGTH = 12;\n            const titleText = getSaferSubstring({\n                text: title, length: MAX_TAB_TEXT_LENGTH,\n            }) + (title.length > MAX_TAB_TEXT_LENGTH ?\n                '\u2026' :\n                '')\n            const textNode = document.createTextNode(titleText);\n\n            // the span has text node child and (usually) a close \"button\"\n            // (span).  we want to only update the text node.\n            // (the project tab is different, it has no close button atow\n            // 06/2025)\n            if (span.firstChild) {\n                span.replaceChild(textNode, span.firstChild);\n            } else {\n                span.appendChild(textNode);\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * creates a new tab element (span atow 03/2025), adds it to the\n     * headerTabsEl and returns the new span element.\n     *\n     * @returns the newly created tab span element\n     */\n    protected override async addChild({\n        addr,\n        ibGib,\n    }: {\n        ibGib: IbGib_V1,\n        addr?: IbGibAddr,\n    }): Promise<HTMLElement> {\n        const lc = `${this.lc}[${this.addChild.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: e6657888d2b42cfdef6df03d89f3e625)`); }\n\n            // #region init/validate\n            if (!this.elements) { throw new Error(`(UNEXPECTED) this.elements falsy? (E: 9f5ad8d5f35ded4496a68ac6b73ac725)`); }\n            const { headerTabsEl } = this.elements;\n\n            if (!headerTabsEl) { throw new Error(`(UNEXPECTED) headerTabsEl falsy? (E: 21e658ececa8a893168598b8837ba825)`); }\n\n            addr ??= getIbGibAddr({ ibGib });\n            if (addr !== getIbGibAddr({ ibGib })) {\n                throw new Error(`(UNEXPECTED) addr !== getIbGibAddr({ibGib})? (E: 1981efb1b691c154670376934336d125)`);\n            }\n            const tjpAddr = getTjpAddr({ ibGib, defaultIfNone: 'incomingAddr' });\n            if (!tjpAddr) {\n                debugger; // why is tjpAddr falsy?\n            }\n            const { gib: tjpGib } = getIbAndGib({ ibGibAddr: tjpAddr });\n            // #endregion init/validate\n\n            // create the tab button element\n            const childBtnEl = document.createElement('span');\n            childBtnEl.id = `project-tab-button-${addr}`;\n            childBtnEl.classList.add('panel-tab-button');\n            // if (activate) { span.classList.add('active'); }\n            this.updateTabTitleAndText({ span: childBtnEl, ibGib });\n            const {\n                punctiliarColor,\n                punctiliarColorTranslucent,\n                tjpColor,\n                tjpColorTranslucent,\n                tjpColorContrast,\n                errorMsg\n            } = getDeterministicColorInfo({ ibGib, translucentAlpha: 70 });\n            if (!errorMsg) {\n                childBtnEl.style.borderColor = tjpColor ?? punctiliarColor;\n                childBtnEl.style.backgroundColor = tjpColorTranslucent ?? punctiliarColorTranslucent;\n                childBtnEl.style.color = tjpColorContrast ?? getColorStrings(90, tjpGib).at(2) ?? 'red'\n                // this.style.setProperty('--ibgib-color', punctiliarColor);\n                // this.style.setProperty('--ibgib-color-translucent', punctiliarColor);\n                // this.style.setProperty('--tjp-color', tjpColor ?? punctiliarColor);\n                // this.style.setProperty('--tjp-color-translucent', tjpColorTranslucent ?? punctiliarColorTranslucent);\n            } else {\n                // don't set anything\n                console.error(`${lc} ${errorMsg} (E: f837c92aa2876b444707f0b229fb8e25)`);\n            }\n\n            // add a close button to the tab button proper, if the tab is not\n            // our project tab Project tab is always open atow (06/2025) but\n            // this is just because I want to always have a tab open right now,\n            // as it simplifies early dev\n            if (tjpAddr !== this.tjpAddr) {\n                const closeBtnEl = document.createElement('span');\n                closeBtnEl.classList.add('close-tab-button');\n                closeBtnEl.textContent = '\u274C'; // or a Font Awesome icon\n                childBtnEl.appendChild(closeBtnEl);\n                closeBtnEl.addEventListener('click', async (event) => {\n                    event.stopPropagation(); // Prevent activating the tab\n                    await this.closeTab({ ibGib });\n                });\n            }\n\n            headerTabsEl.appendChild(childBtnEl);\n            childBtnEl.addEventListener('click', async (event) => {\n                await this.activateIbGib({ addr });\n            });\n\n            if (!this.metaspace) { throw new Error(`(UNEXPECTED) this.metaspace falsy? (E: 56ed15004c98e40a95db20144e726825)`); }\n            if (!this.metaspace.latestObs) { throw new Error(`(UNEXPECTED) this.metaspace.latestObs falsy? (E: bab9882340fcdc29242045e8c2d2fe25)`); }\n            await this.metaspace.latestObs?.subscribe(fnObs({\n                next: async (updateInfo: IbGibTimelineUpdateInfo) => {\n                    if (updateInfo.tjpAddr !== tjpAddr) { return; /* <<<< returns early */ }\n                    if (updateInfo.latestIbGib) {\n                        this.updateTabTitleAndText({ span: childBtnEl, ibGib: updateInfo.latestIbGib })\n                    } else {\n                        console.error(`{lc}[next] updateInfo.latestIbGib falsy? (E: a8558bdc53889ee07d8d78178328ae25)`);\n                    }\n                },\n                complete: async () => {\n                    console.warn(`${lc}[complete] completed executed? (W: a2df080a4f8ef87df5266888109dfe25)`);\n                },\n                error: async (error) => {\n                    debugger; // error in metaspace.latestObs dispatch?\n                    console.error(`${lc}[error] ${extractErrorMsg(error)}`);\n                },\n            }));\n\n            return childBtnEl;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    protected async removeTabBtn({ tabInfo, }: { tabInfo: ProjectChildTabInfo; }): Promise<void> {\n        // throw new Error(\"Method not implemented.\");\n        this.elements!.headerTabsEl!.removeChild(tabInfo.childBtnEl);\n    }\n\n    override async initialize(opts: IbGibDynamicComponentInstanceInitOpts): Promise<void> {\n        const lc = `${this.lc}[${this.initialize.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n            await super.initialize(opts);\n            await this.loadIbGib({ getLatest: true });\n            this.metaspace = await getGlobalMetaspace_waitIfNeeded();\n            this.agentsInitialized = this.initAgents();\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    override async created(): Promise<void> {\n        const lc = `${this.lc}[${this.created.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n\n            // const { meta, htmlPath, scriptPaths, cssPaths } = opts;\n\n            // at this point, this.ibGib should be loaded with the latest\n            // project ibgib\n\n            if (!this.ibGib) { throw new Error(`(UNEXPECTED) this.ibGib falsy? It is assumed at this point that we have a valid ibGib to work with. (E: 15af5db05175b88a629e52a335625b25)`); }\n\n            await this.initElements();\n\n            await this.agentsInitialized;\n            await this.initChronology();\n            await this.renderUI();\n            // await this.agent!.witness(ROOT); // don't auto-prompt at this time because during dev it's extremely annoying and stresses out the agents\n\n            // seems at random, and it is somewhat arbitrary, but if the user is\n            // creating a project, then they've used the site enough to possibly\n            // care enough for persistent storage. should be silent/idempotent\n            // (not do anything if the user has already persisted)\n            await askForPersistStorage();\n\n            // spin off because created has to finish\n            // const projectSettings = await this.getCurrentProjectSettings();\n            const projectSettings = await this.getSettings<Settings_Project>({\n                settingsType: SettingsType.project,\n                useCase: 'current',\n            });\n            if ((projectSettings?.openChildTjpAddrs ?? []).length === 0) {\n                // first run\n                this.showProjectInfoTab();\n            } else {\n                // not first run, so just reopen the old tabs\n                this.reopenOldTabs();\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    protected override async reopenOldTabs(): Promise<void> {\n        const lc = `${this.lc}[${this.reopenOldTabs.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 0476d804371846b4087821cc3fdba125)`); }\n            await super.reopenOldTabs();\n            const settings = await this.getSettings<Settings_Project>({\n                settingsType: 'project',\n                useCase: 'current'\n            });\n            if (!settings) {\n                console.error(`${lc} couldn't get current project settings? (E: 13447c074422d32088c42c08b1a44a25)`);\n                return;\n            }\n            await this.activateLensMode({ lensMode: settings.lensMode, skipInject: false });\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    // private async reopenOldTabs(): Promise<void> {\n    //     const lc = `${this.lc}[${this.reopenOldTabs.name}]`;\n    //     try {\n    //         if (logalot) { console.log(`${lc} starting... (I: 195e7d34b3f8b761aa78dd384011f825)`); }\n\n    //         // let projectSettings = await this.getCurrentProjectSettings();\n    //         const projectSettings = await this.getSettings<Settings_Project>({\n    //             settingsType: SettingsType.project,\n    //             useCase: 'current',\n    //         });\n    //         if (!projectSettings) { throw new Error(`(UNEXPECTED) projectSettings falsy? these should be initialized before now. (E: 2003ab77e01448d638216fc82aff5f25)`); }\n\n    //         this._reloadingTabs = true;\n    //         let currentChildTjpAddr: IbGibAddr | undefined;\n    //         try {\n    //             for (const childTjpAddr of projectSettings.openChildTjpAddrs) {\n    //                 // slow kluge I think...maybe it's ok I dunno.\n    //                 currentChildTjpAddr = childTjpAddr;\n    //                 await this.activateIbGib({ addr: childTjpAddr });\n    //             }\n    //         } catch (error) {\n    //             console.error(`${lc} error during activating child ibGib tabs. childTjpAddr: ${currentChildTjpAddr ?? '[unset?]'} (E: 0396b2e24d08f42ac94510bb718a1725)`);\n    //             throw error;\n    //         } finally {\n    //             this._reloadingTabs = false;\n    //         }\n\n    //         // not reloading, so now we can activate the recently active one\n    //         await this.activateIbGib({ addr: projectSettings.activeChildTjpAddr });\n\n    //         await this.activateLensMode({ lensMode: projectSettings.lensMode, skipInject: false });\n    //     } catch (error) {\n    //         console.error(`${lc} ${extractErrorMsg(error)}`);\n    //         throw error;\n    //     } finally {\n    //         if (logalot) { console.log(`${lc} complete.`); }\n    //     }\n    // }\n\n    /**\n     * show project info tab tells the project component to load itself, which\n     * is like a dashboard...in the future, this should actually show a project\n     * dashboard/status component\n     *\n     * atow (05/2025), this will show a ibgib-raw component, the most\n     * rudimentary of ibgib components.\n     */\n    private async showProjectInfoTab(): Promise<void> {\n        const lc = `${this.lc}[${this.showProjectInfoTab.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 717c77253cb468d40d37e23d00da9825)`); }\n            await this.activateIbGib({ ibGib: this.ibGib });\n            await this.activateLensMode({ lensMode: 'raw', skipInject: false });\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    override async handleContextUpdated(): Promise<void> {\n        const lc = `${this.lc}[${this.handleContextUpdated.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 1cec5212626b1700aa09c2e3d6966225)`); }\n            await super.handleContextUpdated();\n            await this.renderUI();\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    protected override async handleNewContextChild({\n        childIbGib,\n    }: {\n        childIbGib: IbGib_V1;\n    }): Promise<void> {\n        const lc = `${this.lc}[${this.handleNewContextChild.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 118ee1579105ab6bae507272041e4925)`); }\n\n            // hack to get the ball rolling with minigames (drills). not sure\n            // how structure the workflow\n\n            // we're going to assume that if a project's timeline is updated\n            // with a new minigame child, that someone (the user or agent) has\n            // initiated a new game to play\n\n            if (isMinigameIbGib_V1(childIbGib)) {\n                // I'm guessing I want to spin this off after the event loop\n                // execution but I'm not sure on this.\n                setTimeout(() => {\n                    this.activateIbGib({ ibGib: childIbGib }); // spin off?\n                }, 500);\n            } else {\n                if (logalot) { console.log(`${lc} new childIbGib (${childIbGib.ib}) is not a minigame ibgib, which is the only thing this is configured to handle right now. (I: 790ed8745a5736d8e6bf866a4a6d2f25)`); }\n                return; /* <<<< returns early */\n            }\n\n            // if (!this.elements) { throw new Error(`(UNEXPECTED) this.elements falsy? (E: 3a1c7d612aeadee515218cca2ad0c225)`); }\n            // const { contentEl } = this.elements;\n\n            // const chatEntry = await this.renderIbGibItem({ ibGib: childIbGib });\n            // contentEl.appendChild(chatEntry);\n            // chatEntry.scrollIntoView({ behavior: 'smooth' });\n\n            // let animation happen. we are not expecting a lot of messages to\n            // just come pouring in. If that becomes the case, then we need to\n            // reduce/remove this delay.\n            // await delay(500);\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private async initElements(): Promise<void> {\n        const lc = `${this.lc}[${this.initElements.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 98c5bd4e6796961b7672cb3258e4da25)`); }\n\n            const shadowRoot = this.shadowRoot;\n\n            if (!shadowRoot) { throw new Error(`(UNEXPECTED) shadowRoot falsy? (E: genuuid)`); }\n\n            // #region header\n\n            const headerEl = shadowRoot_getElementById<HTMLElement>(shadowRoot, 'project-header');\n\n            const headerTabsEl = shadowRoot_getElementById<HTMLElement>(shadowRoot, 'project-header-tabs');\n\n            // const nameEl = shadowRoot_getElementById<HTMLHeadingElement>(shadowRoot, 'project-name');\n            // const descEl = shadowRoot_getElementById<HTMLParagraphElement>(shadowRoot, 'project-description');\n\n            // addBtnEl\n            const addBtnEl = shadowRoot_getElementById<HTMLButtonElement>(shadowRoot, 'project-header-add-btn');\n            // addPopoverEl - when user clicks add, this popover has the options\n            // of what exactly to add\n            const addPopoverEl = shadowRoot_getElementById<HTMLElement>(shadowRoot, 'add-popover');\n            const addPopoverOptions = addPopoverEl.querySelectorAll('.add-popover-option');\n            addBtnEl.addEventListener('click', async (event) => {\n                addPopoverEl.style.position = 'absolute';\n                addPopoverEl.style.top = `${addBtnEl.offsetTop + addBtnEl.clientHeight}px`;\n                addPopoverEl.style.left = `${addBtnEl.offsetLeft}px`;\n            });\n            // Event listeners for popover options\n            addPopoverOptions.forEach(option => {\n                option.addEventListener('click', async (event: Event) => {\n                    const target = event.target as HTMLElement;\n                    const optionType = target.getAttribute('data-option');\n                    if (optionType) { await this.handleAddPopoverSelected(optionType); }\n                    addPopoverEl.hidePopover(); // idempotent\n                });\n            });\n\n            // ellipsisBtnEl\n            const ellipsisBtnEl = shadowRoot_getElementById<HTMLButtonElement>(shadowRoot, 'project-header-ellipsis-btn');\n            // ellipsisPopoverEl - when user clicks ellipsis, this popover has the options\n            // of what exactly to add\n            const ellipsisPopoverEl = shadowRoot_getElementById<HTMLElement>(shadowRoot, 'ellipsis-popover');\n            const ellipsisPopoverOptions = ellipsisPopoverEl.querySelectorAll('.ellipsis-popover-option');\n            ellipsisBtnEl.addEventListener('click', async (event) => {\n                ellipsisPopoverEl.style.position = 'absolute';\n                ellipsisPopoverEl.style.top = `${ellipsisBtnEl.offsetTop + ellipsisBtnEl.clientHeight}px`;\n                ellipsisPopoverEl.style.left = `${ellipsisBtnEl.offsetLeft}px`;\n            });\n            // Event listeners for popover options\n            ellipsisPopoverOptions.forEach(option => {\n                option.addEventListener('click', async (event: Event) => {\n                    try {\n                        const target = event.target as HTMLElement;\n                        const optionType = target.getAttribute('data-option');\n                        if (optionType) {\n                            await this.handleEllipsisPopoverSelected(optionType);\n                        }\n                    } catch (error) {\n                        const emsg = `${lc}[ellipsisPopoverOption] ${extractErrorMsg(error)} (E: 8468587582a85f00f8a71e12282a7825)`;\n                        console.error(emsg);\n                        alertUser({ msg: emsg, title: 'export failed...' }); // spins off\n                    } finally {\n                        // Hide popover after selection\n                        // if (ellipsisPopoverEl.matches(':open')) {\n                        ellipsisPopoverEl.hidePopover();\n                        // }\n                    }\n                });\n            });\n\n            // #endregion header\n\n            const contentEl = shadowRoot_getElementById<HTMLElement>(shadowRoot, 'project-content');\n\n            // #region footer\n            const footerEl = shadowRoot_getElementById<HTMLElement>(shadowRoot, 'project-footer');\n\n            const lensBarEl = shadowRoot_getElementById<HTMLElement>(shadowRoot, 'ibgib-lens-bar');\n            const rawLensBtnEl = shadowRoot_getElementById<HTMLButtonElement>(shadowRoot, 'raw-lens-btn');\n            const textLensBtnEl = shadowRoot_getElementById<HTMLButtonElement>(shadowRoot, 'text-lens-btn');\n            const minigameLensBtnEl = shadowRoot_getElementById<HTMLButtonElement>(shadowRoot, 'minigame-lens-btn');\n\n            // #endregion footer\n\n            this.elements = {\n                headerEl,\n                headerTabsEl,\n                contentEl,\n                footerEl,\n                lensBarEl,\n                rawLensBtnEl,\n                textLensBtnEl,\n                minigameLensBtnEl,\n                // nameEl,\n                // descEl,\n                addBtnEl,\n                addPopoverEl,\n                ellipsisBtnEl,\n                ellipsisPopoverEl,\n            };\n\n            // has to run after this.elements set\n            await this.initSettings();\n            await this.initLensBarAndRelated();\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    protected override async initSettings(): Promise<void> {\n        const lc = `${this.lc}[${this.initSettings.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 40015889cf08f03801c0ac08de4e3d25)`); }\n            await super.initSettings();\n\n            if (!this.settings) { throw new Error(`(UNEXPECTED) this.settings falsy after init? (E: 15ea55484aa8a9c78dd67bf88e468b25)`); }\n            if (!this.settings.ibGib) { throw new Error(`(UNEXPECTED) this.settings.ibGib falsy after init? (E: 048901c6c03c8c6c7400d279fdf37825)`); }\n\n            // let projectSettings = await this.getCurrentProjectSettings();\n            let projectSettings = await this.getSettings<Settings_Project>({\n                settingsType: SettingsType.project,\n                useCase: 'current',\n            });\n\n            if (!projectSettings) {\n                // need to create a new project settings section\n                projectSettings = {\n                    type: 'project',\n                    openChildTjpAddrs: [],\n                    activeChildTjpAddr: undefined,\n                    lensMode: this.lensMode,\n                }\n                // update the current settings and persist\n                const sectionName_default = await getSectionName({\n                    settingsType: SettingsType.project,\n                    useCase: 'default',\n                });\n                const sectionName_current = await getSectionName({\n                    settingsType: SettingsType.project,\n                    useCase: 'current',\n                });\n                const _newSettings = await mut8Timeline({\n                    timeline: this.settings!.ibGib!,\n                    metaspace: this.metaspace!,\n                    mut8Opts: {\n                        dataToAddOrPatch: {\n                            sections: {\n                                [sectionName_default]: projectSettings,\n                                [sectionName_current]: projectSettings,\n                            }\n                        }\n                    },\n                });\n            }\n\n\n            // const sectionName_generalCurrent = await getSectionName({\n            //     settingsType: 'general',\n            //     useCase: 'current',\n            // });\n            // data.sections[sectionName_generalDefault] = clone(DEFAULT_SETTINGS_GENERAL);\n            // data.sections[sectionName_generalCurrent] = clone(DEFAULT_SETTINGS_GENERAL);\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private async initLensBarAndRelated(): Promise<void> {\n        const lc = `${this.lc}[${this.initLensBarAndRelated.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 82f048513a35a0f1fa6b7e4803522725)`); }\n\n            for (const lensBtn of this.lensBtns) {\n                lensBtn.addEventListener('click', async () => {\n                    const lensMode = lensBtn.getAttribute('data-mode') as LensMode;\n                    await this.activateLensMode({ lensMode, skipInject: false });\n\n                    // update the coupled UIInfo Settings for the domain ibgib so that\n                    // the same viewer/editor\n\n                    // const projectSettings = await this.getCurrentProjectSettings();\n                    const projectSettings = await this.getSettings<Settings_Project>({\n                        settingsType: SettingsType.project,\n                        useCase: 'current',\n                    });\n                    if (!projectSettings) { throw new Error(`(UNEXPECTED) projectSettings falsy? (E: f7e328479b488df068abc1b28867ce25)`); }\n                    if (projectSettings.lensMode !== lensMode) {\n                        projectSettings.lensMode = lensMode;\n                        const sectionName_current = await getSectionName({\n                            settingsType: SettingsType.project,\n                            useCase: 'current',\n                        });\n                        const _newSettings = await mut8Timeline({\n                            timeline: this.settings!.ibGib!,\n                            metaspace: this.metaspace!,\n                            mut8Opts: {\n                                dataToAddOrPatch: {\n                                    sections: {\n                                        [sectionName_current]: projectSettings,\n                                    }\n                                },\n                            },\n                        });\n                    }\n                });\n            }\n\n            const generalSettings = await this.getCurrentSettings<Settings_General>({ settingsType: SettingsType.general });\n            if (!generalSettings) { throw new Error(`(UNEXPECTED) generalSettings falsy? settings not initialized with a general section? (E: d1f3e8c250489c548de42a55efba2825)`); }\n\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private get lensBtns(): HTMLButtonElement[] {\n        return this.elements ?\n            [\n                this.elements.rawLensBtnEl,\n                this.elements.textLensBtnEl,\n                this.elements.minigameLensBtnEl,\n            ]\n            : [];\n    }\n\n    private updateLensBtnsUI(): void {\n        const lc = `${this.lc}[${this.updateLensBtnsUI.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: c20518af0bade4fde8772b91f4c88825)`); }\n\n            const lensMode = this.lensMode;\n\n            // update the lens buttons' UI\n            if (!this.elements) { throw new Error(`(UNEXPECTED) this.elements falsy? (E: 2e1b5a513b6e3e0678fa8dfba5a8c825)`); }\n            this.lensBtns.forEach(btn => {\n                btn.classList.toggle('active', btn.getAttribute('data-mode') === lensMode);\n            });\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private async activateLensMode({ lensMode, skipInject }: { lensMode: LensMode; skipInject: boolean; }) {\n        const lc = `${this.lc}[${this.activateLensMode.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 3687fb48fde881cf12423fb2b413f925)`); }\n\n            if (this._lensMode === lensMode) { return; /* <<<< returns early */ }\n\n            // guaranteed different lens mode\n            this._lensMode = lensMode;\n            this.updateLensBtnsUI();\n\n            // updating the project settings current general settings\n\n            if (skipInject) { return; /* <<<< returns early */ }\n\n            // instantiate or reload the tab's component\n            if (!this.elements) { throw new Error(`(UNEXPECTED) this.elements falsy? (E: f1cc886fc78870d198062c88f4a78825)`); }\n\n            if (!this.activeChildInfo) { throw new Error(`(UNEXPECTED) this.activeChildInfo falsy? (E: 233fb3b04de80b8b1736fcabc0f32c25)`); }\n\n            // klugy hack loads the new component based on the lensMode, if\n            // required.  if it's already in the componentCache for the tab\n            // info, then that will be set properly\n            await this.getLoadedChildInfo({ addr: this.activeChildInfo.addr, });\n\n            if (!this.activeChildInfo.component) { throw new Error(`(UNEXPECTED) tabInfo.component falsy? should be populated by this point in code (E: 2466c8a016e813be29a953a83b0fa525)`); }\n            const componentSvc = await getComponentSvc();\n            await componentSvc.inject({\n                parentEl: this.elements.contentEl,\n                componentToInject: this.activeChildInfo.component,\n            });\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * Handler for when an option is selected from the add popover.\n     */\n    private async handleAddPopoverSelected(optionType: string): Promise<void> {\n        const lc = `${this.lc}[${this.handleAddPopoverSelected.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... optionType: ${optionType} (I: genuuid)`); }\n\n            // TODO: Implement logic to create new ibGib based on optionType\n            // and add it as a tab.\n            switch (optionType) {\n                case 'text':\n                    await this.addChildIbGib_text();\n                    break;\n                case 'minigame':\n                    await this.addChildIbGib_minigameActiveTab();\n                    break;\n                default:\n                    throw new Error(`(UNEXPECTED) invalid optionType (${optionType})? (E: 3856754562e8e7971822581899a6f825)`);\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    private async addChildIbGib_minigameActiveTab(): Promise<void> {\n        const lc = `${this.lc}[${this.addChildIbGib_minigameActiveTab.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 28edda58994adcca1362419bef442e25)`); }\n\n            const name = await promptForText({\n                title: 'Game Title?',\n                msg: `What's it called?`,\n                cancelable: true,\n            });\n            if (!name) {\n                console.error(`${lc} User cancelled (E: 5d1c5eacde514b03ab6304685337e825)`);\n                return; /* <<<< returns early */\n            }\n\n            const metaspace = this.metaspace;\n            if (!metaspace) { throw new Error(`(UNEXPECTED) this.metaspace falsy? (E: 2bf487419e280ea32aef13b4ba7e2325)`); }\n            const space = await metaspace.getLocalUserSpace({ lock: false });\n\n            //     {\n            //         // gameVariant,\n            //         name,\n            //         description,\n            //         instructions,\n            //         keywords,\n            //     }: {\n            //         // gameVariant: MinigameGameVariant,\n            //         name: string,\n            //         description: string,\n            //         instructions: string,\n            //         keywords: string[],\n            //     }\n\n            const activeTabIbGib = await this.getActiveTabIbGib();\n            if (!activeTabIbGib.data) { throw new Error(`(UNEXPECTED) activeTabIbGib.data falsy? (E: fc6e98d473ba3ee3bee9d67894640b25)`); }\n            const activeTjpAddr = getTjpAddr({ ibGib: activeTabIbGib, defaultIfNone: 'incomingAddr' }) ?? getIbGibAddr({ ibGib: activeTabIbGib });\n\n            const resNewMinigame = await minigameBuilderStartFunctionInfo.fnViaCmd({\n                cmd: minigameBuilderStartFunctionInfo.cmd,\n                cmdModifiers: minigameBuilderStartFunctionInfo.cmdModifiers.concat(),\n                // contextIbGibAddr: this.tjpAddr!,\n                contextIbGibAddr: activeTjpAddr,\n                gameType: 'typing',\n                name,\n                description: 'This is a minigame created by da human.',\n                instructions: 'Play!',\n                keywords: [],\n            }) as MinigameBuilderStartResult;\n\n            // necessary?\n            const latestMinigameAddr = await metaspace.getLatestAddr({\n                addr: resNewMinigame.minigameAddr,\n                space,\n            }) ?? resNewMinigame.minigameAddr;\n\n            // const resGet = await metaspace.get({ addrs: [latestMinigameAddr], space, });\n            // if (!resGet.success || resGet.errorMsg) {\n            //     throw new Error(`(UNEXPECTED) couldn't get minigame that we just created? error: ${resGet.errorMsg} (E: 4f06c7e5c8884adcb895afbfac70ab25)`);\n            // }\n            // if (!resGet.ibGibs) { throw new Error(`(UNEXPECTED) resGet.ibGibs falsy? (E: babb1d865a9e4512784e9b96b1b7d825)`); }\n            // if (resGet.ibGibs.length !== 1) {\n            //     throw new Error(`(UNEXPECTED) resGet.ibGibs length !== 1 for latestMinigameAddr (${latestMinigameAddr})? (E: b94736ace7589dc8191de6de5e8ff725)`);\n            // }\n            // const latestMinigameIbGib = resGet.ibGibs.at(0)! as MinigameIbGib_V1;\n            await this.activateIbGib({ addr: latestMinigameAddr });\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private async addChildIbGib_text(): Promise<void> {\n        const lc = `${this.lc}[${this.addChildIbGib_text.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 02800232ba6d5d16187e8f938fc80225)`); }\n\n            const { metaspace } = this;\n            if (!metaspace) { throw new Error(`(UNEXPECTED) metaspace falsy? (E: 8ec06d4d8608ead318e3538870059825)`); }\n            const space = await metaspace.getLocalUserSpace({ lock: false });\n            if (!space) { throw new Error(`(UNEXPECTED) space falsy? couldn't even get default local user space? (E: a81178540d08a3dbd9e0552826abc825)`); }\n\n            const title = await promptForText({\n                title: `title`,\n                msg: `what's it all about? this can be a filename.ext or just your intent about what the thing is. or just hit enter`,\n                cancelable: true,\n            });\n\n            if (!title) {\n                // await alertUser({ msg: 'cancelled, got it.', title: 'cancelled' });\n                console.log(`${lc} user cancelled. (I: a999335c4acf58eb6825af28f1733d25)`);\n                return; /* <<<< returns early */\n            }\n\n            // create the comment ibgib\n            const resCommentIbGib = await createCommentIbGib({\n                text: title,\n                addlMetadataText: `${getTimestampInTicks()}_${getSaferSubstring({ text: title, length: 16 })}`,\n                saveInSpace: true,\n                space,\n            });\n            let commentIbGib = resCommentIbGib.newIbGib;\n            commentIbGib = await mut8Timeline({\n                timeline: commentIbGib,\n                mut8Opts: {\n                    dataToAddOrPatch: { name: title, description: title, },\n                },\n                metaspace,\n                space,\n            });\n\n            // create an agent for the new child\n            const agentsSvc = getAgentsSvc(); // Assuming getAgentsSvc is available\n            const newAgentIbGib = await agentsSvc.createNewAgent({\n                metaspace,\n                superSpace: undefined, // uses default local user space as the super space\n                name: `TextAgent-${this.instanceId}`,\n                api: 'gemini',\n                model: GEMINI_DEFAULT_MODEL_STR,\n                availableFunctions: clone(AGENT_AVAILABLE_FUNCTIONS_PROJECTCHILDTEXTAGENT),\n                initialSystemText: [\n                    AGENT_INITIAL_SYSTEM_TEXT_PROJECTCHILDTEXTAGENT,\n                ].join('\\n'),\n                initialChatText: [\n                    AGENT_INITIAL_CHAT_TEXT_PROJECTCHILDTEXTAGENT,\n                ].join('\\n'),\n                // fnGetAPIKey: this.getFnGetAPIKey(),\n                fnGetAPIKey: getDefaultFnGetAPIKey(),\n                type: AGENT_SPECIAL_IBGIB_TYPE_PROJECTCHILDTEXTAGENT,\n                addToAgentsTag: true,\n            });\n\n            await registerDomainIbGibWithAgentIndex({\n                domainIbGib: commentIbGib,\n                agentIbGib: newAgentIbGib,\n                metaspace,\n                space,\n            });\n\n            if (!this.ibGib) { throw new Error(`(UNEXPECTED) this.ibGib falsy? should be truthy and a project at that. (E: 23d1b4dcda88940c68c9a08df843b825)`); }\n            if (!isProjectIbGib_V1(this.ibGib)) { throw new Error(`(UNEXPECTED) this.ibGib is not a project ibgib? (E: 4004c8156dbdf6e40855ad54b3d00525)`); }\n\n            // append the comment to the project's timeline\n            await appendToTimeline({\n                timeline: this.ibGib,\n                rel8nInfos: [{\n                    ibGibs: [commentIbGib],\n                    rel8nName: PROJECT_CHILD_TEXT_REL8N_NAME,\n                }],\n                metaspace,\n                space,\n            });\n\n            // this.lensMode = 'text';\n            await this.activateLensMode({ lensMode: 'text', skipInject: true });\n            await this.activateIbGib({ ibGib: commentIbGib });\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    protected async getActiveTabIbGib(): Promise<IbGib_V1> {\n        const lc = `${this.lc}[${this.getActiveTabIbGib.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 10e8819318c842e417523fbdf6956a25)`); }\n\n            if (!this.activeChildInfo) { throw new Error(`this.activeChildInfo falsy (E: 3ade8fe5f95b2ddb286d5008f17aff25)`); }\n            if (!this.activeChildInfo.component) { throw new Error(`this.activeChildInfo.component falsy. (E: 49ba441797b1595ce9b8e7cc62b53825)`); }\n            const ibGib = this.activeChildInfo.component.ibGib;\n            if (!ibGib) { throw new Error(`(UNEXPECTED) active tab's component's ibgib falsy? (E: a6917818f2ee9bf51326982886347825)`); }\n            return ibGib;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    protected async openChronology({\n        ibGibAddr,\n        ibGib,\n    }: {\n        ibGibAddr?: IbGibAddr,\n        ibGib?: IbGib_V1,\n    }): Promise<void> {\n        const lc = `${this.lc}[${this.openChronology.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 14059d1a68c83b0c28da18f876c9b825)`); }\n\n            if (!ibGibAddr && !ibGib) { throw new Error(`(UNEXPECTED) both ibGibAddr and ibGib falsy? (E: 2ef0c8e5c7ed3b6a4b88cfd2974e8725)`); }\n            if (ibGibAddr && ibGib) {\n                if (ibGibAddr !== getIbGibAddr({ ibGib })) {\n                    console.warn(`${lc} ibGibAddr !== getIbGibAddr({ibGib}) ? This is expectd to be equal, but maybe it's a tjp thing? (W: cd1842c17a082173ca28e908cb25a825). Overriding/Going with ibGib itself`)\n                    ibGibAddr = getIbGibAddr({ ibGib }); // override\n                }\n            }\n            ibGibAddr ??= getIbGibAddr({ ibGib });\n\n            let chronologysComponent = getIbGibGlobalThis_Common().chronologysComponent;\n\n            // wait for it if it isn't defined yet\n            let count = 0;\n            while (!chronologysComponent) {\n                console.warn(`${lc} global chronologysComponent is expected to be truthy by now. delaying (W: e43b814165489d87e8865451c66d5825)`)\n                count++;\n                if (count > 100) {\n                    debugger; // error in web1 component expectation\n                    throw new Error(`(UNEXPECTED) global chronologysComponent is falsy? (E: 407c48599e385fe10beb695849e7f125)`);\n                }\n                await delay(100);\n            }\n\n            await chronologysComponent.openIbGibAddr({ ibGibAddr, });\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * Handler for when an option is selected from the add popover.\n     */\n    private async handleEllipsisPopoverSelected(optionType: string): Promise<void> {\n        const lc = `${this.lc}[${this.handleEllipsisPopoverSelected.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... optionType: ${optionType} (I: genuuid)`); }\n\n            // const getActiveTabIbGib: () => IbGib_V1 = () => {\n            //     if (!this.activeChildInfo) { throw new Error(`this.activeChildInfo falsy (E: 3ade8fe5f95b2ddb286d5008f17aff25)`); }\n            //     if (!this.activeChildInfo.component) { throw new Error(`this.activeChildInfo.component falsy. (E: 49ba441797b1595ce9b8e7cc62b53825)`); }\n            //     const ibGib = this.activeChildInfo.component.ibGib;\n            //     if (!ibGib) { throw new Error(`(UNEXPECTED) active tab's component's ibgib falsy? (E: a6917818f2ee9bf51326982886347825)`); }\n            //     return ibGib;\n            // }\n            switch (optionType) {\n                case 'chat-active-tab':\n                    if (this.activeChildInfo?.addr) {\n                        await this.openChronology({ ibGibAddr: this.activeChildInfo.addr });\n                    } else {\n                        await alertUser({ title: 'No Active Tab??', msg: `There was no active tab found. This seems like a bug so you should report it please. (E: 7304e579bd5e398468e8cd333e5f9825)` });\n                    }\n                    break;\n                case 'copy-project-address':\n                    const addr = getIbGibAddr({ ibGib: this.ibGib });\n                    copyToClipboard({ data: { text: addr }, });\n                    highlightElement({ el: this.elements!.contentEl, magicHighlightTimingMs: 1_000, }); // spin off so options disappear\n                    break;\n                case 'copy-active-tab-address':\n                    if (this.activeChildInfo?.addr) {\n                        copyToClipboard({ data: { text: this.activeChildInfo.addr }, });\n                        highlightElement({ el: this.activeChildInfo.component?.elements?.contentEl, magicHighlightTimingMs: 1_000, }); // spin off so options disappear\n                    } else {\n                        await alertUser({ title: 'No Active Tab??', msg: `There was no active tab found. This seems like a bug so you should report it please. (E: 4451dd7d60381f8f08557b479eb5bb25)` });\n                    }\n                    break;\n                case 'export-project':\n                    await this.exportProject({ compress: false });\n                    break;\n                case 'export-project-gzip':\n                    await this.exportProject({ compress: true });\n                    break;\n                case 'export-active-tab':\n                    await this.exportIbGib({\n                        ibGib: await this.getActiveTabIbGib(),\n                        compress: false\n                    });\n                    break;\n                case 'export-active-tab-gzip':\n                    await this.exportIbGib({\n                        ibGib: await this.getActiveTabIbGib(),\n                        compress: true,\n                    });\n                    break;\n                default:\n                    throw new Error(`(UNEXPECTED) invalid optionType (${optionType})? (E: 3856754562e8e7971822581899a6f825)`);\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * exports the current project. If more than one is open, exports the currently active project.\n     *\n     * Should this also include exporting the project's agent? As a flag\n     */\n    private async exportProject({ compress }: { compress: boolean }): Promise<void> {\n        const lc = `${this.lc}[${this.exportProject.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 719052c3bb285cdfd8d2b21258c71825)`); }\n\n            if (!this.ibGib) { throw new Error(`(UNEXPECTED) this.ibGib falsy? (E: bf40bc1beae6b34c9c8544b888b51425)`); }\n            await this.exportIbGib({\n                ibGib: this.ibGib,\n                compress,\n            });\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * rerender\n     */\n    protected override async renderUI(): Promise<void> {\n        const lc = `${this.lc}[${this.renderUI.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 5415ec9be03ca640cb1a3d6a17d22625)`); }\n\n            await super.renderUI();\n\n            if (!this.elements) {\n                console.warn(`${lc} (UNEXPECTED) tried to render but haven't initialized elements? (W: genuuid)`);\n                return; /* <<<< returns early */\n            }\n\n            const {\n                headerEl, contentEl, footerEl,\n                // nameEl,\n                // descEl,\n            } = this.elements;\n\n            // const projectSettings = await this.getCurrentProjectSettings();\n            const projectSettings = await this.getSettings<Settings_Project>({\n                settingsType: SettingsType.project,\n                useCase: 'current',\n            });\n            if (!projectSettings) { throw new Error(`(UNEXPECTED) projectSettings falsy? (E: 052b322abcc5856f28e44cc89c373825)`); }\n\n            this.updateLensBtnsUI();\n\n            // nameEl.textContent = this.ibGib?.data?.name ?? '[project no name?]'\n            // nameEl.textContent += ` (v${this.ibGib?.data?.n ?? '?'})`\n\n            // const description = this.ibGib?.data?.description;\n            // if (description) {\n            //     descEl.textContent = description;\n            // } else {\n            //     descEl.style.display = 'none';\n            // }\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    override async disconnected(): Promise<void> {\n        const lc = `${this.lc}[${this.disconnected.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n            // no action atow\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    protected override async initAgents(): Promise<void> {\n        const lc = `${this.lc}[${this.initAgents.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n\n            await this.loadAgentsCoupledToIbGib();\n\n            if (!this.agent) { throw new Error(`(UNEXPECTED) agent falsy after createNewAgent? (E: 4a5042d2e1b2de0eb15d39e406549125)`); }\n            await this.agent.updateAvailableFunctions({\n                availableFunctions: AGENT_AVAILABLE_FUNCTIONS_PROJECTAGENT,\n            });\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * inits the chronology in the right panel for web1 components\n     */\n    private async initChronology(): Promise<void> {\n        const lc = `${this.lc}[${this.initChronology.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n\n            const globalIbGib = getIbGibGlobalThis_BlankGib();\n            let chronologysComponent = globalIbGib.chronologysComponent;\n\n            let count = 0;\n            while (!chronologysComponent) {\n                console.warn(`${lc} global chronologysComponent is expected to be truthy by now. delaying (W: genuuid)`)\n                count++;\n                if (count > 100) {\n                    debugger; // error in web1 component expectation\n                    throw new Error(`(UNEXPECTED) global chronologysComponent is falsy? (E: 3d68459066ee7ef9fbdfea4ea3904825)`);\n                }\n                await delay(100);\n            }\n\n            if (!this.ibGibProxy) { throw new Error(`(UNEXPECTED) this.ibGibProxy falsy? (E: 4e91911bf6ce45d398c04a256fceb825)`); }\n            // ibGibProxy.ibGib is a comment ibgib that is data.n=2. the 2 is\n            // because it is already related to an agent.\n\n            await chronologysComponent.openIbGibAddr({\n                ibGibAddr: getIbGibAddr({ ibGib: this.ibGibProxy.ibGib }),\n            });\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n}\n", "import { AGENT_INITIAL_CHAT_HI_PLEASEINTRO_YOURSELF, AGENT_SYSTEM_PROMPT_COMMON_INSTRUCTIONS } from \"./common-agent-texts.mjs\";\n\nexport const AGENT_GOAL_PROJECTSAGENT = [\n    `In general, your goal is just to do your best to parse the chat texts and choose the best course of action in terms of one or more functions. Please refer to those available function schemas and descriptions.`,\n    `Usually, you will want to talk with them via the tell user function.`,\n    `As a projects manager agent, you are responsible for CRUD project ibgibs. In ibgib, \"project\" is basically a focus of effort. You can have a project like conventional projects in code, but because of the granular version-control-like power of ibgib, you can consider a sub-component of a project itself to be a project. This is th conventional progress of work: you work on some \"thing\", then when it gets large enough, you break it apart into sub-\"things\". A \"project\" is this idea of a \"thing\", but really it's an \"ibgib\". But people don't know what that means. `,\n    `But concretely, at this stage in development, I'm not quite sure what projects will entail as far implementation goes. Your job though will be to do management of them, e.g., creating projects, inter-project actions like copying/importing ibgibs, etc.`,\n].join('\\n');\n\nexport const AGENT_INITIAL_SYSTEM_TEXT_PROJECTSAGENT = [\n    AGENT_SYSTEM_PROMPT_COMMON_INSTRUCTIONS,\n    AGENT_GOAL_PROJECTSAGENT,\n].join('\\n');\n\nexport const AGENT_INITIAL_CHAT_TEXT_PROJECTSAGENT = [\n    AGENT_INITIAL_CHAT_HI_PLEASEINTRO_YOURSELF,\n].join('\\n')\n", "import thisHtml from './projects.html';\nimport thisCss from './projects.css';\nimport stylesCss from '../../styles.css';\nimport rootCss from '../../root.css';\n\nimport {\n    clone, delay, extractErrorMsg, getSaferSubstring, pickRandom_Letters,\n} from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { IbGibAddr } from \"@ibgib/ts-gib/dist/types.mjs\";\nimport { IbGib_V1 } from \"@ibgib/ts-gib/dist/V1/types.mjs\";\nimport { getIbAndGib, getIbGibAddr } from \"@ibgib/ts-gib/dist/helper.mjs\";\nimport { getGibInfo, isPrimitive } from \"@ibgib/ts-gib/dist/V1/transforms/transform-helper.mjs\";\nimport { MetaspaceService } from \"@ibgib/core-gib/dist/witness/space/metaspace/metaspace-types.mjs\";\nimport { fnObs } from \"@ibgib/core-gib/dist/common/pubsub/observer/observer-helper.mjs\";\nimport { IbGibTimelineUpdateInfo } from \"@ibgib/core-gib/dist/common/other/other-types.mjs\";\nimport { getTjpAddr } from \"@ibgib/core-gib/dist/common/other/ibgib-helper.mjs\";\nimport { SpaceId } from \"@ibgib/core-gib/dist/witness/space/space-types.mjs\";\nimport { CommentIbGib_V1 } from \"@ibgib/core-gib/dist/common/comment/comment-types.mjs\";\nimport { isComment } from \"@ibgib/core-gib/dist/common/comment/comment-helper.mjs\";\nimport { tellUserFunctionInfo } from \"@ibgib/web-gib/dist/api/commands/chat/tell-user.mjs\";\nimport {\n    getDeterministicColorInfo, getGlobalMetaspace_waitIfNeeded,\n} from \"@ibgib/web-gib/dist/helpers.mjs\";\nimport {\n    IbGibDynamicComponentMetaBase,\n    IbGibDynamicComponentInstanceBase_ParentOfTabs,\n} from \"@ibgib/web-gib/dist/ui/component/ibgib-dynamic-component-bases.mjs\";\nimport {\n    ElementsBase, ChildInfoBase, IbGibDynamicComponentInstance,\n    IbGibDynamicComponentInstanceInitOpts,\n} from \"@ibgib/web-gib/dist/ui/component/component-types.mjs\";\nimport { storageGet, } from \"@ibgib/web-gib/dist/storage/storage-helpers.web.mjs\";\nimport { getComponentSvc } from \"@ibgib/web-gib/dist/ui/component/ibgib-component-service.mjs\";\nimport { getColorStrings, } from \"@ibgib/web-gib/dist/helpers.mjs\";\nimport {\n    alertUser, copyToClipboard, highlightElement, promptForText,\n    shadowRoot_getElementById,\n} from \"@ibgib/web-gib/dist/helpers.web.mjs\";\nimport {\n    getAgentForDomainIbGib, getAgents, registerDomainIbGibWithAgentIndex\n} from \"@ibgib/web-gib/dist/witness/agent/agent-helpers.mjs\";\nimport { AgentWitnessAny, } from \"@ibgib/web-gib/dist/witness/agent/agent-one-file.mjs\";\nimport { GEMINI_DEFAULT_MODEL_STR, } from \"@ibgib/web-gib/dist/witness/agent/gemini/gemini-constants.mjs\";\nimport { getAgentsSvc } from \"@ibgib/web-gib/dist/witness/agent/agents-service-v1.mjs\";\nimport { createProjectIbGib, isProjectIbGib_V1 } from \"@ibgib/web-gib/dist/common/project/project-helper.mjs\";\nimport { DEFAULT_PROJECT_DESCRIPTION, ProjectIbGib_V1 } from \"@ibgib/web-gib/dist/common/project/project-types.mjs\";\nimport { IbGibSettings, SettingsWithTabs } from \"@ibgib/web-gib/dist/common/settings/settings-types.mjs\";\nimport { SettingsType } from \"@ibgib/web-gib/dist/common/settings/settings-constants.mjs\";\nimport {\n    AGENT_SPECIAL_IBGIB_TYPE_PROJECTAGENT, PROJECT_NAME_REGEXP,\n} from \"@ibgib/web-gib/dist/common/project/project-constants.mjs\";\nimport {\n    AGENT_AVAILABLE_FUNCTIONS_PROJECTAGENT,\n} from \"@ibgib/web-gib/dist/common/project/project-agent-functions.mjs\";\n\nimport {\n    GLOBAL_LOG_A_LOT, ARMY_STORE, BEE_KEY, BLANK_GIB_DB_NAME,\n} from \"../../constants.mjs\";\nimport { getComponentCtorArg, getIbGibGlobalThis_BlankGib, } from \"../../helpers.web.mjs\";\nimport {\n    AGENT_INITIAL_CHAT_TEXT_PROJECTAGENT,\n    AGENT_INITIAL_SYSTEM_TEXT_PROJECTAGENT,\n    CHAT_WITH_AGENT_PLACEHOLDER_PROJECTAGENT,\n} from \"../../agent-texts/project-agent-texts.mjs\";\nimport {\n    PROJECT_COMPONENT_NAME, ProjectComponentInstance,\n} from \"./project/project-component-one-file.mjs\";\nimport { getAppShellSvc } from \"../../ui/shell/app-shell-service.mjs\";\nimport { simpleIbGibRouterSingleton } from \"../../ui/router/router-one-file.mjs\";\nimport {\n    AGENT_INITIAL_CHAT_TEXT_PROJECTSAGENT,\n    AGENT_INITIAL_SYSTEM_TEXT_PROJECTSAGENT\n} from \"../../agent-texts/projects-agent-texts.mjs\";\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\nexport const AGENT_SPECIAL_IBGIB_TYPE_PROJECTSAGENT = 'projectsagent';\nexport const AGENT_AVAILABLE_FUNCTIONS_PROJECTSAGENT = [\n    tellUserFunctionInfo,\n    // ...RenderAgentFunctionInfos,\n];\n\nexport const PROJECTS_COMPONENT_NAME: string = 'ibgib-projects';\n\nexport class ProjectsComponentMeta extends IbGibDynamicComponentMetaBase {\n    protected override lc: string = `[${ProjectsComponentMeta.name}]`;\n\n    /**\n     * temporary regexp path for our initial dev. this component will become\n     * attached to actual ib^gib addrs\n     *\n     *\n     * either the path is\n     *   * /apps/projects/gib/projects\n     *   * /apps/projects/ABC123.456DEF/project%20my-project%201744553032000\n     *\n     * The point is that it's either a bland projects^gib to indicate create a\n     * new project or it's a valid gib and a valid project ib. lazy regexp here\n     */\n    routeRegExp?: RegExp = /apps\\/projects\\/(gib|.*)\\/(projects|project \\/.*\\/.*)?/;\n\n    componentName: string = PROJECTS_COMPONENT_NAME;\n\n    constructor() {\n        super(getComponentCtorArg());\n        customElements.define(this.componentName, ProjectsComponentInstance);\n    }\n\n    async createInstance({\n        path,\n        ibGibAddr\n    }: {\n        /**\n         * todo: store this in the instance (i think) but will change this when needed\n         */\n        path: string;\n        ibGibAddr: IbGibAddr;\n    }): Promise<IbGibDynamicComponentInstance> {\n        const lc = `${this.lc}[${this.createInstance.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 65da57b67d533197f95d26aca2f03c25)`); }\n            const component = document.createElement(this.componentName) as ProjectsComponentInstance;\n            await component.initialize({\n                ibGibAddr,\n                meta: this,\n                html: thisHtml,\n                css: [rootCss, stylesCss, thisCss],\n            });\n            return component;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n}\n\n/**\n * helper interface for managing tabs and their associated ibgibs\n */\ninterface ProjectTabInfo extends ChildInfoBase<ProjectComponentInstance> {\n    // tabBtnEl: HTMLElement;\n    // addr: IbGibAddr;\n    /**\n     * access the ibGib via this component.\n     *\n     * This component wraps an ibgib proxy that automatically stays up-to-date\n     * when new ibgib frames are added to the ibgib's timeline and published to\n     * the metaspace. (via metaspace.registerNewIbGib)\n     */\n    // projectComponent?: ProjectComponentInstance;\n    // agent?: AgentWitnessAny;\n    // active: boolean;\n}\n\ninterface ProjectsElements extends ElementsBase {\n    headerEl: HTMLElement;\n    headerTabsEl: HTMLElement;\n    footerEl: HTMLElement;\n    addBtnEl: HTMLButtonElement;\n    ellipsisBtnEl: HTMLElement;\n    ellipsisPopoverEl: HTMLElement;\n}\n\nexport class ProjectsComponentInstance\n    extends IbGibDynamicComponentInstanceBase_ParentOfTabs<IbGibSettings & SettingsWithTabs, IbGib_V1, ProjectsElements, ProjectTabInfo>\n    implements IbGibDynamicComponentInstance<IbGib_V1, ProjectsElements> {\n\n    protected override lc: string = `[${ProjectsComponentInstance.name}]`;\n\n    // projectTabInfos: ProjectTabInfo[] = [];\n    get activeProjectTabInfo(): ProjectTabInfo | undefined {\n        return this.childInfos.find(x => x.active);\n    }\n\n    metaspace: MetaspaceService | undefined;\n\n    protected get settingsType(): SettingsType {\n        return SettingsType.projects;\n    }\n\n    constructor() {\n        super();\n    }\n\n    override async initialize(opts: IbGibDynamicComponentInstanceInitOpts): Promise<void> {\n        const lc = `${this.lc}[${this.initialize.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: aec41edb278ffac62f77c757f8595725)`); }\n            // before any initialization, we want to ensure we are bootstrapped\n            // await getIbGibGlobalThis_BlankGib().bootstrapPromise; // this is in the super call now\n\n            if (!this.metaspace) {\n                // wait for the metaspace to be initialized\n                this.metaspace = await getGlobalMetaspace_waitIfNeeded({ delayIntervalMs: 50 });\n            }\n\n            opts.ibGibAddr = await this.metaspace.getLatestAddr({ addr: opts.ibGibAddr }) ?? opts.ibGibAddr;\n\n            await super.initialize(opts);\n            await this.setBreadcrumbs();\n            this.agentsInitialized = this.initAgents(); // spins off\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    override async created(): Promise<void> {\n        const lc = `${this.lc}[${this.created.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 4e3e670ab00fc2dad9c2912e6344d425)`); }\n\n            // const { meta, htmlPath, scriptPaths, cssPaths } = opts;\n            // does nothing atow\n            await this.initElements();\n            if (!this.elements) { throw new Error(`(UNEXPECTED) just initElements but this.elements falsy? (E: 931b47d386e41c3b8d58d67ad0ec4825)`); }\n\n            const { } = this.elements;\n\n            await this.agentsInitialized;\n\n            const { gib } = getIbAndGib({ ibGibAddr: this.ibGibAddr });\n\n            if (isPrimitive({ gib })) {\n                if (logalot) { console.log(`${lc} ibGibAddr has primitive gib, so returning early. (I: c68201caad350aa385bf6b6bf58ee525)`); }\n                return; /* <<<< returns early */\n            }\n\n            // await this.activateProject({ projectAddr: this.ibGibAddr, });\n            this.activateIbGib({ addr: this.ibGibAddr, }); // spin off, because super.activateIbGib awaits this created promise\n\n            const globalBlankGib = getIbGibGlobalThis_BlankGib();\n            globalBlankGib.projectsComponent = this;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    override async disconnected(): Promise<void> {\n        const lc = `${this.lc}[${this.disconnected.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: d85a47973e435e5476265dbcfeba9c25)`); }\n            // no action atow\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    public async newProject({\n        projectSpaceId,\n        initialCommentText,\n        srcIbGibAddr,\n    }: {\n        /**\n         * @property projectSpaceId - id of the local space in which the project's\n         * ibgib will be accessed.\n         */\n        projectSpaceId?: SpaceId;\n        initialCommentText?: string;\n        /**\n         * @property srcIbGibAddr - Optional address of an existing ibGib (likely a\n         * comment) to use as the initial source or context for the new project.\n         */\n        srcIbGibAddr?: IbGibAddr;\n    }): Promise<ProjectIbGib_V1> {\n        const lc = `${this.lc}[${this.newProject.name}]`;\n        try {\n            await this.disableNewProjectUI();\n\n            // #region init/validate\n            if (!this.metaspace) { throw new Error(`(UNEXPECTED) this.metaspace falsy? (E: d0c5d3df962949420e641d9160b85625)`); }\n\n            const space = await this.metaspace.getLocalUserSpace({ localSpaceId: projectSpaceId, lock: false });\n            if (!space) { throw new Error(`couldn't get local user space (${projectSpaceId ?? '[default local user space]'}) from metaspace. (E: 1bc833e38cb231eedac30facf6d40325)`); }\n\n            let srcCommentIbGib: CommentIbGib_V1 | undefined = undefined;\n            if (srcIbGibAddr) {\n                const resGetSrc = await this.metaspace.get({\n                    addrs: [srcIbGibAddr],\n                    space,\n                });\n                if (resGetSrc.errorMsg || resGetSrc.ibGibs?.length !== 1) {\n                    throw new Error(`couldn't get srcIbGibAddr (${srcIbGibAddr}) from space (${space.ib}) (E: 0314d4c477e3aed3c75a4358625ee825)`);\n                }\n                srcCommentIbGib = resGetSrc.ibGibs![0] as CommentIbGib_V1;\n                if (!isComment({ ibGib: srcCommentIbGib })) {\n                    throw new Error(`srcIbGibAddr (${srcIbGibAddr}) is not a comment ibgib. (E: 2e68b8efcd11dd8428ee3d68bb6d7825)`);\n                }\n            }\n            // #endregion init/validate\n\n            let name: string = '';\n            do {\n                name = await promptForText({\n                    title: 'project name?',\n                    msg: [\n                        `Name of the new project?`,\n                        `(only alphanumerics, spaces, hyphens, underscores)`,\n                        `If you leave this blank, a random \"temporary\" name will be used.`,\n                    ].join('\\n'),\n                    cancelable: false, // should be cancelable, but we're going to interpret this as use a default name.\n                    confirm: false,\n                });\n                if (name) {\n                    // they've entered something truthy, so regexp test it\n                    if (!PROJECT_NAME_REGEXP.test(name)) {\n                        await alertUser({\n                            title: 'invalid project name',\n                            msg: `Doh. The project name can only contain alphanumerics (letters/digits), spaces, hyphens, and underscores. Here is the nerdy regex: ${PROJECT_NAME_REGEXP}`,\n                        });\n                        name = '';\n                    }\n                } else {\n                    // cancelled/empty, so default it\n                    name = `untitled-${pickRandom_Letters({ count: 8 })}`;\n                }\n            } while (!name);\n\n            const resProjectIbGib = await createProjectIbGib({\n                name,\n                description: DEFAULT_PROJECT_DESCRIPTION,\n                space,\n                saveInSpace: true,\n                srcCommentIbGib,\n            });\n            const projectIbGib = resProjectIbGib.newIbGib;\n            const projectAddr = getIbGibAddr({ ibGib: projectIbGib });\n            await this.metaspace.registerNewIbGib({ ibGib: projectIbGib });\n\n            if (logalot) { console.log(`${lc} starting... (I: 87460f0ca94356520a6255981f6df725)`); }\n\n            const agentsSvc = getAgentsSvc(); // Assuming getAgentsSvc is available\n            const newAgentIbGib = await agentsSvc.createNewAgent({\n                metaspace: this.metaspace,\n                superSpace: undefined, // uses default local user space as the super space\n                name: `ProjectAgent-${this.instanceId}`,\n                api: 'gemini',\n                model: GEMINI_DEFAULT_MODEL_STR,\n                availableFunctions: clone(AGENT_AVAILABLE_FUNCTIONS_PROJECTAGENT),\n                initialSystemText: [\n                    AGENT_INITIAL_SYSTEM_TEXT_PROJECTAGENT,\n                ].join('\\n'),\n                initialChatText: [\n                    AGENT_INITIAL_CHAT_TEXT_PROJECTAGENT,\n                ].join('\\n'),\n                fnGetAPIKey: this.getFnGetAPIKey(),\n                type: AGENT_SPECIAL_IBGIB_TYPE_PROJECTAGENT,\n                addToAgentsTag: true,\n            });\n\n            // 2. Register the domain ibGib (project) with the new agent in the index\n            await registerDomainIbGibWithAgentIndex({\n                domainIbGib: projectIbGib,\n                agentIbGib: newAgentIbGib,\n                metaspace: this.metaspace,\n                space,\n            });\n\n            await newAgentIbGib.setActiveContext({\n                contextIbGib: projectIbGib,\n            });\n\n            // await this.activateProject({\n            //     projectIbGib: projectIbGib,\n            //     projectAddr: projectAddr,\n            // });\n            await this.activateIbGib({\n                ibGib: projectIbGib,\n                addr: projectAddr,\n            });\n\n            return projectIbGib;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            await this.enableNewProjectUI();\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * I'm sketching this thinking that it will be useful for commands (via\n     * agents) to get the relevant project component.\n     *\n     * The Projects component atow (05/2025) is basically a singleton, so this\n     * provides a way of getting at the component from a command. I'm not sure\n     * if this is the right way or if it will be used though.\n     *\n     * @returns the corresponding project tab info if exists, else undefined.\n     */\n    public async getProjectTab({\n        ibGibAddr,\n        ibGib,\n    }: {\n        ibGibAddr?: IbGibAddr,\n        ibGib?: ProjectIbGib_V1,\n    }): Promise<ProjectTabInfo | undefined> {\n        const lc = `${this.lc}[${this.getProjectTab.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 69c1d8b32ba9dd403a911bc5f0095425)`); }\n            if (!ibGibAddr && !ibGib) { throw new Error(`either ibGibAddr or ibGib is required. (E: 42811cc61d78cc83a21b6528c6d58825)`); }\n            ibGibAddr ??= getIbGibAddr({ ibGib });\n            const gibInfo = getGibInfo({ ibGibAddr });\n            const tjpGib = gibInfo.tjpGib ?? getIbAndGib({ ibGibAddr });\n            const filtered = this.childInfos.filter(x => {\n                const xGibInfo = getGibInfo({ ibGibAddr: x.addr });\n                const xTjpGib = xGibInfo.tjpGib ?? getIbAndGib({ ibGibAddr: x.addr });\n                return tjpGib === xTjpGib;\n            });\n            if (filtered.length === 0) {\n                return undefined;\n            } else if (filtered.length === 1) {\n                return filtered[0];\n            } else {\n                console.warn(`${lc} more than one tab opened for the same tjpGib (${tjpGib})? returning the first one but this doesn't seem right. (W: 0c67f8e2f8eda7cb886343b8f1736b25)`);\n                return filtered[0];\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private async disableNewProjectUI(): Promise<void> {\n        const lc = `${this.lc}[${this.disableNewProjectUI.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: ea9c02985442ca330759217f29b90c25)`); }\n            if (!this.elements) { throw new Error(`(UNEXPECTED) this.elements falsy? (E: f0a77baed7c2e5acccd078baf8b0aa25)`); }\n\n            const { addBtnEl } = this.elements;\n            addBtnEl.disabled = true;\n            addBtnEl.textContent = '\u2026';\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private async enableNewProjectUI(): Promise<void> {\n        const lc = `${this.lc}[${this.enableNewProjectUI.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 91e16b23d2271a6afe8852b8bc77f525)`); }\n            if (!this.elements) { throw new Error(`(UNEXPECTED) this.elements falsy? (E: 3a1ac8e82351a128fff208ccac468f25)`); }\n\n            const { addBtnEl } = this.elements;\n            addBtnEl.disabled = false;\n            addBtnEl.textContent = '+';\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    public override async activateIbGib({ addr, ibGib, }: { addr?: IbGibAddr; ibGib?: IbGib_V1; }): Promise<void> {\n        const lc = `${this.lc}[${this.activateIbGib.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: a178721ccbe8d7f753a06bc100b16825)`); }\n            if (!this.metaspace) { debugger; throw new Error(`(UNEXPECTED) this.metaspace falsy? (E: 30b7489383281225fa3b768885c3dd25)`); }\n            await super.activateIbGib({ addr, ibGib });\n\n            if (!this.activeChildInfo) { throw new Error(`(UNEXPECTED) this.activeChildInfo falsy after calling activateIbGib? (E: 7a5845a43e9adf178d822b68336b3825)`); }\n            ibGib ??= this.activeChildInfo.component?.ibGib\n\n            if (ibGib && isProjectIbGib_V1(ibGib)) {\n                // init the agent to listen for context events\n                const space = await this.metaspace.getLocalUserSpace({ lock: false });\n                if (!space) { throw new Error(`(UNEXPECTED) couldn't get default local user space? (E: a524ecb58d65b524618a58dad7b07f25)`); }\n                const projectAgent = await getAgentForDomainIbGib({\n                    ibGib,\n                    metaspace: this.metaspace,\n                    space,\n                });\n                if (!projectAgent) {\n                    throw new Error(`projectAgent not found for project (${addr}) (E: 8e88748121d24c82552387011863e225)`);\n                }\n                await projectAgent.setActiveContext({\n                    contextIbGib: ibGib,\n                });\n                // update the location\n                await simpleIbGibRouterSingleton.updateCurrentURLPathIbGibAddr({\n                    ibGibAddr: this.activeChildInfo.addr,\n                    replace: true,\n                });\n\n                // update breadcrumb\n                await this.setBreadcrumbs();\n\n                // update left panel to ensure we're on the Projects Tab\n                const appShellSvc = getAppShellSvc();\n                appShellSvc.activateLeftPanelTab({ tabName: 'projects' });\n\n                // update right panel - project chronology\n                await appShellSvc.activateRightPanelTab({\n                    tabName: \"chronologys\",\n                    ibGibAddr: this.activeChildInfo.addr,\n                });\n\n                // update footer panel's input\n                while (!appShellSvc.inputComponent) {\n                    await delay(100);\n                    console.log(`${lc} appShellSvc.inputComponent still falsy. probably just page load. will retry... (I: 2628de248d662dc8184ed73c98bb9225)`)\n                }\n                if (!this.activeProjectTabInfo) { throw new Error(`(UNEXPECTED) this.activeProjectTabInfo falsy? (E: 1c50943dcd8f59297f8bbe5635bc8a25)`); }\n                if (!this.activeProjectTabInfo.component?.ibGibProxy) { throw new Error(`(UNEXPECTED) this.activeProjectTabInfo.component?.ibGibProxy falsy? (E: d54f26a14cbb046aa900dea638257f25)`); }\n                await appShellSvc.inputComponent.setContextInfo({\n                    info: {\n                        agent: projectAgent,\n                        placeholderText: CHAT_WITH_AGENT_PLACEHOLDER_PROJECTAGENT,\n                        contextProxyIbGib: this.activeProjectTabInfo.component.ibGibProxy,\n                        // default to default local user space for now\n                        spaceId: undefined,\n                    },\n                });\n            } else {\n                console.error(`${lc} ibGib is falsy or not a project ibGib? this is not necessarily an error, I just don't know about this state of things at this point. this \"error\" is just logged to the console, i.e., wasn't thrown. (E: d5c997bdbf28274ed80b057242768825)`);\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    // /**\n    //  * Loads the ibGib if only addr is provided.\n    //  *\n    //  * Then manages the UI:\n    //  *\n    //  * - If a tab is already created for the project and active, then does nothing.\n    //  * - If it's already created but inactive, then activates tab and loads content\n    //  * - if no tab, then creates it, activates it, loads content.\n    //  *\n    //  * To do this, it creates/hydrates a {@link ProjectTabInfo} and activates\n    //  * it.\n    //  *\n    //  * @see {@link ProjectTabInfo.active}\n    //  * @see {@link activeProjectTabInfo}\n    //  */\n    // private async activateProject({\n    //     projectAddr,\n    //     projectIbGib,\n    // }: {\n    //     projectAddr?: IbGibAddr,\n    //     projectIbGib?: IbGib_V1,\n    // }): Promise<void> {\n    //     const lc = `${this.lc}[${this.activateProject.name}]`;\n    //     try {\n    //         if (logalot) { console.log(`${lc} starting... (I: 2d596a9c36f7e5fac4b8bbc6f0e84d25)`); }\n\n    //         if (!this.elements) { throw new Error(`(UNEXPECTED) this.elements falsy? (E: a574f48ef54d75d0997933fbed55eb25)`); }\n    //         const { contentEl } = this.elements;\n\n    //         // #region init/validate\n    //         if (!this.metaspace) { throw new Error(`(UNEXPECTED) this.metaspace falsy? (E: d647670e3e2a436862719c5b1f324125)`); }\n    //         if (projectIbGib && projectAddr && getIbGibAddr({ ibGib: projectIbGib }) !== projectAddr) { throw new Error(`(UNEXPECTED) addr !== getIbGibAddr({ibGib})? (E: 6d12ed6a578cf3c466a6c7acd645b625)`); }\n    //         projectAddr ??= getIbGibAddr({ ibGib: projectIbGib });\n    //         // #endregion init/validate\n\n    //         // super.activateIbGib({})\n    //         /**\n    //          * the point of this function is to populate this and make it active\n    //          */\n    //         const projectTabInfo = await this.getLoadedChildInfo({\n    //             addr: projectAddr,\n    //             ibGib: projectIbGib,\n    //         });\n\n    //         if (projectTabInfo.active) {\n    //             // already active?\n    //             // debugger; // warning/error...activating an already active tab?\n    //             console.warn(`${lc} tab already active (W: 5fc45570f99f8fde3c5a887ca42e0a25)`);\n    //             return; /* <<<< returns early */\n    //         }\n\n    //         projectIbGib ??= projectTabInfo.component?.ibGib;\n    //         if (!projectIbGib) { throw new Error(`(UNEXPECTED) projectIbGib falsy? the projectTabInfo should be fully loaded at this point, which should include a projectComponent instance. That component should have its ibGib value populated. (E: 73323f5cc6ed3bede337e646322c8e25)`); }\n\n    //         // at this point, we are guaranteed to have a non-active\n    //         // projectTabInfo, so deactivate the old, and activate the new\n    //         const currentlyActive = this.activeProjectTabInfo;\n    //         if (currentlyActive) {\n    //             currentlyActive.childBtnEl.classList.remove('active');\n    //             currentlyActive.active = false;\n    //             contentEl.innerHTML = '';\n    //         }\n\n    //         // init the agent to listen for context events\n    //         const space = await this.metaspace.getLocalUserSpace({ lock: false });\n    //         if (!space) { throw new Error(`(UNEXPECTED) couldn't get default local user space? (E: a524ecb58d65b524618a58dad7b07f25)`); }\n    //         const projectAgent = await getAgentForDomainIbGib({\n    //             ibGib: projectIbGib,\n    //             metaspace: this.metaspace,\n    //             space,\n    //         });\n    //         if (!projectAgent) {\n    //             throw new Error(`projectAgent not found for project (${projectAddr}) (E: 8e88748121d24c82552387011863e225)`);\n    //         }\n    //         await projectAgent.setActiveContext({\n    //             contextIbGib: projectIbGib,\n    //         });\n\n    //         // activate the new tab\n    //         projectTabInfo.childBtnEl.classList.add('active');\n    //         projectTabInfo.childBtnEl.scrollIntoView({ behavior: 'smooth' });\n    //         projectTabInfo.active = true;\n    //         if (!this.childInfos.some(x => x.addr === projectTabInfo.addr)) {\n    //             this.childInfos.push(projectTabInfo);\n    //         }\n    //         if (!projectTabInfo.component) { throw new Error(`(UNEXPECTED) projectTabInfo.component falsy? should be populated by this point in code (E: 5d766308dcb6a30e6c262f4633505125)`); }\n    //         const componentSvc = await getComponentSvc();\n    //         await componentSvc.inject({\n    //             parentEl: contentEl,\n    //             componentToInject: projectTabInfo.component,\n    //         });\n\n    //         // update tab button colors\n    //         // projectTabInfo.component.style.getPropertyValue()\n\n    //         // update the location\n    //         await simpleIbGibRouterSingleton.updateCurrentURLPathIbGibAddr({\n    //             ibGibAddr: projectTabInfo.addr,\n    //             replace: true,\n    //         });\n\n    //         // update breadcrumb\n    //         await this.setBreadcrumbs();\n\n    //         // update left panel to ensure we're on the Projects Tab\n    //         const appShellSvc = getAppShellSvc();\n    //         appShellSvc.activateLeftPanelTab({ tabName: 'projects' });\n\n    //         // update right panel - project chronology\n    //         await appShellSvc.activateRightPanelTab({\n    //             tabName: \"chronologys\",\n    //             ibGibAddr: projectTabInfo.addr,\n    //         });\n\n    //         // update footer panel's input\n    //         while (!appShellSvc.inputComponent) {\n    //             await delay(100);\n    //             console.log(`${lc} appShellSvc.inputComponent still falsy. probably just page load. will retry... (I: 2628de248d662dc8184ed73c98bb9225)`)\n    //         }\n    //         if (!this.activeProjectTabInfo) { throw new Error(`(UNEXPECTED) this.activeProjectTabInfo falsy? (E: 1c50943dcd8f59297f8bbe5635bc8a25)`); }\n    //         if (!this.activeProjectTabInfo.component?.ibGibProxy) { throw new Error(`(UNEXPECTED) this.activeProjectTabInfo.component?.ibGibProxy falsy? (E: d54f26a14cbb046aa900dea638257f25)`); }\n    //         await appShellSvc.inputComponent.setContextInfo({\n    //             info: {\n    //                 agent: projectAgent,\n    //                 placeholderText: CHAT_WITH_AGENT_PLACEHOLDER_PROJECTAGENT,\n    //                 contextProxyIbGib: this.activeProjectTabInfo.component.ibGibProxy,\n    //                 // default to default local user space for now\n    //                 spaceId: undefined,\n    //             },\n    //         });\n    //     } catch (error) {\n    //         console.error(`${lc} ${extractErrorMsg(error)}`);\n    //         throw error;\n    //     } finally {\n    //         if (logalot) { console.log(`${lc} complete.`); }\n    //     }\n    // }\n\n    // protected getLoadedTabInfo({ addr, ibGib, }: { addr: IbGibAddr; ibGib?: IbGib_V1; }): Promise<ProjectTabInfo> {\n    //     throw new Error(\"Method not implemented.\");\n    // }\n\n    /**\n     * @internal\n     * gets the project tab info for the given addr.\n     *\n     * creates and loads the project ibgib component, which itself loads the\n     * ibgib internally (or throws) if not already loaded.\n     *\n     * @returns ProjectTabInfo with fully loaded component and ibgib.\n     *\n     * @see {@link ProjectTabInfo}\n     */\n    protected async getLoadedChildInfo({\n        addr,\n        ibGib,\n    }: {\n        addr: IbGibAddr,\n        ibGib?: IbGib_V1,\n    }): Promise<ProjectTabInfo> {\n        const lc = `${this.lc}[${this.getLoadedChildInfo.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 8bc42ecb105f4ca9dff6590c1a9c2f25)`); }\n            if (!addr) { throw new Error(`(UNEXPECTED) addr falsy? (E: 25e89572d09ae8dd581ba60bde1c9825)`); }\n            const tjpGib = getGibInfo({ ibGibAddr: addr }).tjpGib ?? getIbAndGib({ ibGibAddr: addr }).gib;\n\n            const fnCreateAndLoadProjectComponent = async () => {\n                const componentSvc = await getComponentSvc();\n                const projectComponent = await componentSvc.getComponentInstance({\n                    path: PROJECT_COMPONENT_NAME,\n                    ibGibAddr: addr,\n                    useRegExpPrefilter: true,\n                }) as ProjectComponentInstance | undefined;\n                if (!projectComponent) {\n                    debugger; // error couldn't create component instance for project?\n                    throw new Error(`(UNEXPECTED) projectComponent falsy? couldn't create component instance for project? (E: efeee6b003f5b0af9b0fda679593c725)`);\n                }\n                // await projectComponent.loadIbGib();\n                // await projectComponent.initialized;\n                if (!projectComponent.ibGib) {\n                    debugger; // error couldn't load ibGib for project?\n                    throw new Error(`(UNEXPECTED) ibGib falsy? couldn't load ibGib for project? (E: 352f152063a97e67f769babfadfe1e25)`);\n                }\n                // guaranteed loaded ibGib\n                return projectComponent;\n            }\n\n            /** the point of this function is to populate this */\n            let projectTabInfo: ProjectTabInfo;\n\n            /**\n             * filtered for same timeline of addr via tjpGib\n             */\n            const filtered = this.childInfos.filter(x => {\n                const tabGibInfo = getGibInfo({ ibGibAddr: x.addr });\n                const tabTjpGib = tabGibInfo.tjpGib ?? getIbAndGib({ ibGibAddr: x.addr }).gib;\n                return tabTjpGib === tjpGib;\n            });\n            if (filtered.length > 0) {\n                // already have an existing tab\n                // const filtered = this.childInfos.filter(x => x.addr === addr);\n                if (filtered.length !== 1) { throw new Error(`(UNEXPECTED) filtered.length !== 1? (E: ef126a918a93f1c13d0c4b41d5194b25)`); }\n                projectTabInfo = filtered[0];\n                if (projectTabInfo.component) {\n                    console.log(`${lc} projectTabInfo.component already truthy. (I: f752651269b2ed7151c78668418a7825)`);\n                } else {\n                    projectTabInfo.component = await fnCreateAndLoadProjectComponent();\n                    // ibGib = projectTabInfo.component!.ibGib!;\n                }\n            } else {\n                // no existing tab, so create new project tab info\n                const projectComponent = await fnCreateAndLoadProjectComponent();\n                ibGib = projectComponent.ibGib!; // guaranteed in above fn\n\n                // both addr and ibGib guaranteed now\n                const tabBtnEl = await this.addChild({ addr, ibGib })\n                projectTabInfo = {\n                    addr,\n                    childBtnEl: tabBtnEl,\n                    component: projectComponent,\n                    active: false,\n                };\n            }\n\n            return projectTabInfo;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * creates a new tab element (span atow 03/2025), adds it to the\n     * headerTabsEl and returns the new span element.\n     *\n     * @returns the newly created tab span element\n     */\n    protected override async addChild({\n        addr,\n        ibGib,\n    }: {\n        ibGib: IbGib_V1,\n        addr?: IbGibAddr,\n    }): Promise<HTMLElement> {\n        const lc = `${this.lc}[${this.addChild.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: e6657888d2b42cfdef6df03d89f3e625)`); }\n\n            // #region init/validate\n            if (!this.elements) { throw new Error(`(UNEXPECTED) this.elements falsy? (E: 9f5ad8d5f35ded4496a68ac6b73ac725)`); }\n            const { headerTabsEl } = this.elements;\n\n            addr ??= getIbGibAddr({ ibGib });\n            if (addr !== getIbGibAddr({ ibGib })) {\n                throw new Error(`(UNEXPECTED) addr !== getIbGibAddr({ibGib})? (E: 1981efb1b691c154670376934336d125)`);\n            }\n            const tjpAddr = getTjpAddr({ ibGib, defaultIfNone: 'incomingAddr' });\n            const { gib: tjpGib } = getIbAndGib({ ibGibAddr: tjpAddr });\n            // #endregion init/validate\n\n            // create the tab button element\n            const span = document.createElement('span');\n            span.id = `projects-tab-button-${addr}`;\n            span.classList.add('panel-tab-button');\n            // if (activate) { span.classList.add('active'); }\n            this.updateTabTitleAndText({ span, ibGib });\n            let {\n                punctiliarColor,\n                punctiliarColorTranslucent,\n                tjpColor,\n                tjpColorContrast,\n                tjpColorTranslucent,\n                errorMsg\n            } = getDeterministicColorInfo({ ibGib, translucentAlpha: 70 });\n            if (!errorMsg) {\n                span.style.borderColor = tjpColor ?? punctiliarColor;\n                span.style.backgroundColor = tjpColorTranslucent ?? punctiliarColorTranslucent;\n                span.style.color = tjpColorContrast ?? getColorStrings(90, tjpGib).at(2) ?? 'red'\n\n                // this.style.setProperty('--ibgib-color', punctiliarColor);\n                // this.style.setProperty('--ibgib-color-translucent', punctiliarColor);\n                // this.style.setProperty('--tjp-color', tjpColor ?? punctiliarColor);\n                // this.style.setProperty('--tjp-color-translucent', tjpColorTranslucent ?? punctiliarColorTranslucent);\n            } else {\n                // don't set anything\n                console.error(`${lc} ${errorMsg} (E: f837c92aa2876b444707f0b229fb8e25)`);\n            }\n\n            headerTabsEl.appendChild(span);\n            span.addEventListener('click', async (event) => {\n                // if (logalot) { console.log(`${lc} activating...`); }\n                // await this.activateProject({ projectAddr: addr });\n                await this.activateIbGib({ addr });\n            });\n\n            if (!this.metaspace) { throw new Error(`(UNEXPECTED) this.metaspace falsy? (E: 56ed15004c98e40a95db20144e726825)`); }\n            if (!this.metaspace.latestObs) { throw new Error(`(UNEXPECTED) this.metaspace.latestObs falsy? (E: bab9882340fcdc29242045e8c2d2fe25)`); }\n            await this.metaspace.latestObs?.subscribe(fnObs({\n                next: async (updateInfo: IbGibTimelineUpdateInfo) => {\n                    if (updateInfo.tjpAddr !== tjpAddr) { return; /* <<<< returns early */ }\n                    if (updateInfo.latestIbGib) {\n                        this.updateTabTitleAndText({ span, ibGib: updateInfo.latestIbGib })\n                    } else {\n                        console.error(`{lc}[next] updateInfo.latestIbGib falsy? (E: a8558bdc53889ee07d8d78178328ae25)`);\n                    }\n                },\n                complete: async () => {\n                    console.warn(`${lc}[complete] completed executed? (W: a2df080a4f8ef87df5266888109dfe25)`);\n                },\n                error: async (error) => {\n                    debugger; // error in metaspace.latestObs dispatch?\n                    console.error(`${lc}[error] ${extractErrorMsg(error)}`);\n                },\n            }));\n\n            return span;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    protected removeTabBtn({ tabInfo, }: { tabInfo: ProjectTabInfo; }): Promise<void> {\n        throw new Error(\"Method not implemented.\");\n    }\n\n    private updateTabTitleAndText({\n        span,\n        ibGib,\n    }: {\n        span: HTMLElement,\n        ibGib: IbGib_V1,\n    }): void {\n        const lc = `[${this.updateTabTitleAndText.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: d1c34e159aecc0bf06f57a759b06a625)`); }\n\n            if (!ibGib.data) { throw new Error(`(UNEXPECTED) ibGib.data falsy? (E: a22dd936f38a779c0d61489c7d7c9125)`); }\n            if (!ibGib.data.name) { console.warn(`${lc} ibGib.data.name falsy? (W: genuuid)`); }\n            const title = ibGib.data.name ?? 'untitled'\n            const desc = ibGib.data.description ?? '';\n            span.title = desc ? `${title}\\n${desc}` : title;\n            const MAX_TAB_TEXT_LENGTH = 12;\n            span.textContent = getSaferSubstring({ text: title, length: MAX_TAB_TEXT_LENGTH, });\n            if (title.length > MAX_TAB_TEXT_LENGTH) {\n                span.textContent += '\u2026';\n            }\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    // private async activateTab({\n    //     addr,\n    //     tabSpan,\n    // }: {\n    //     addr: IbGibAddr,\n    //     tabSpan: HTMLSpanElement,\n    // }): Promise<void> {\n    //     const lc = `${this.lc}[${this.activateTab.name}]`;\n    //     try {\n    //         if (logalot) { console.log(`${lc} starting... (I: 3703365ccbfb68df570991962aaf7925)`); }\n    //         // if (!this.elementsheaderEl) { throw new Error(`(UNEXPECTED) this.headerEl falsy? (E: b61066b20aa36f902dbe474577abea25)`); }\n    //     } catch (error) {\n    //         console.error(`${lc} ${extractErrorMsg(error)}`);\n    //         throw error;\n    //     } finally {\n    //         if (logalot) { console.log(`${lc} complete.`); }\n    //     }\n    // }\n\n    async initElements(): Promise<void> {\n        const lc = `${this.lc}[${this.initElements.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 0001223d063c984cd870e9e440725425)`); }\n\n            if (!this.shadowRoot) { throw new Error(`(UNEXPECTED) this.shadowRoot falsy? (E: e2d3077643f8c314fd050706ae64ca25)`); }\n\n            const headerEl = shadowRoot_getElementById<HTMLElement>(this.shadowRoot, 'projects-header');\n\n            // headerTabsEl\n            const headerTabsEl = shadowRoot_getElementById<HTMLElement>(this.shadowRoot, 'projects-header-tabs');\n\n            const contentEl = shadowRoot_getElementById<HTMLElement>(this.shadowRoot, 'projects-content');\n            const pContent = document.createElement('p');\n            pContent.textContent = '[no project loaded...try creating one]';\n            pContent.style.lineHeight = `${contentEl.clientHeight}px`;\n            pContent.style.textAlign = 'center';\n            pContent.style.fontStyle = 'italic';\n            contentEl.appendChild(pContent);\n\n            const footerEl = shadowRoot_getElementById<HTMLElement>(this.shadowRoot, 'projects-footer');\n            footerEl.style.display = 'none';\n\n            // addBtnEl\n            // projects-header-add-btn\n            const addBtnEl = shadowRoot_getElementById<HTMLButtonElement>(this.shadowRoot, 'projects-header-add-btn');\n            addBtnEl.addEventListener('click', async (event) => {\n                await this.newProject({});\n            });\n\n            // ellipsisBtnEl\n            const ellipsisBtnEl = shadowRoot_getElementById<HTMLButtonElement>(this.shadowRoot, 'projects-header-ellipsis-btn');\n            // ellipsisPopoverEl - when user clicks ellipsis, this popover has the options\n            // of what exactly to add\n            const ellipsisPopoverEl = shadowRoot_getElementById<HTMLElement>(this.shadowRoot, 'ellipsis-popover');\n            const ellipsisPopoverOptions = ellipsisPopoverEl.querySelectorAll('.ellipsis-popover-option');\n            ellipsisBtnEl.addEventListener('click', async (event) => {\n                ellipsisPopoverEl.style.position = 'absolute';\n                ellipsisPopoverEl.style.top = `${ellipsisBtnEl.offsetTop + ellipsisBtnEl.clientHeight}px`;\n                ellipsisPopoverEl.style.left = `${ellipsisBtnEl.offsetLeft}px`;\n            });\n            // Event listeners for popover options\n            ellipsisPopoverOptions.forEach(option => {\n                option.addEventListener('click', async (event: Event) => {\n                    try {\n                        const target = event.target as HTMLElement;\n                        const optionType = target.getAttribute('data-option');\n                        if (optionType) {\n                            await this.handleEllipsisPopoverSelected(optionType);\n                        }\n                    } catch (error) {\n                        const emsg = `${lc}[ellipsisPopoverOption] ${extractErrorMsg(error)} (E: 8468587582a85f00f8a71e12282a7825)`;\n                        console.error(emsg);\n                        alertUser({ msg: emsg, title: 'export failed...' }); // spins off\n                    } finally {\n                        // Hide popover after selection\n                        ellipsisPopoverEl.hidePopover();\n                    }\n                });\n            });\n\n            this.elements = {\n                headerEl, headerTabsEl,\n                addBtnEl,\n                ellipsisBtnEl,\n                ellipsisPopoverEl,\n                contentEl,\n                footerEl,\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * exports the current project. If more than one is open, exports the currently active project.\n     *\n     * Should this also include exporting the project's agent? As a flag\n     */\n    private async exportProject({ compress }: { compress: boolean }): Promise<void> {\n        const lc = `${this.lc}[${this.exportProject.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 4912c1a75be42f7cb8cefc88472eea25)`); }\n\n            // if (!this.ibGib) { throw new Error(`(UNEXPECTED) this.ibGib falsy? (E: b50b68bbde884e5928602f77d7579a25)`); }\n            if (!this.activeProjectTabInfo) { throw new Error(`(UNEXPECTED) this.activeProjectTabInfo falsy? (E: 1e99c827600de57928dd3568adebf825)`); }\n            if (!this.activeProjectTabInfo.component) { throw new Error(`(UNEXPECTED) this.activeProjectTabInfo.component falsy? (E: d5c0b80d178860cb484741c808126225)`); }\n            if (!this.activeProjectTabInfo.component.ibGib) { throw new Error(`(UNEXPECTED) this.activeProjectTabInfo.component.ibGib falsy? (E: 64e1c88b22044e63d8d5dea8c3932825)`); }\n            await this.exportIbGib({\n                ibGib: this.activeProjectTabInfo.component.ibGib,\n                compress,\n            });\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private async importProject(): Promise<void> {\n        const lc = `[${this.importProject.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 73e3ca46756816843659c8ae7f438e25)`); }\n            throw new Error(`not implemented (yet!!) ...delayed because of thinking about import as basically being the same thing as a merge, which is non-trivial. work is mostly located in ibgib-dynamic-component-bases.mts importibGib, but need to pull out into a helper. that should actually just call the helper, passing in the components this.ibGib (can be overridden in descending concrete component classes, in case this.ibGib isn't what we want) (E: 6741dd74686156ac8878af58253dd825)`);\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * Handler for when an option is selected from the add popover.\n     */\n    private async handleEllipsisPopoverSelected(optionType: string): Promise<void> {\n        const lc = `${this.lc}[${this.handleEllipsisPopoverSelected.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... optionType: ${optionType} (I: genuuid)`); }\n\n            // const getActiveTabIbGib: () => IbGib_V1 = () => {\n            //     if (!this.activeChildInfo) { throw new Error(`this.activeChildInfo falsy (E: genuuid)`); }\n            //     if (!this.activeChildInfo.component) { throw new Error(`this.activeChildInfo.component falsy. (E: genuuid)`); }\n            //     const ibGib = this.activeChildInfo.component.ibGib;\n            //     if (!ibGib) { throw new Error(`(UNEXPECTED) active tab's component's ibgib falsy? (E: genuuid)`); }\n            //     return ibGib;\n            // }\n            switch (optionType) {\n                case 'copy-active-project-address':\n                    if (this.activeProjectTabInfo) {\n                        copyToClipboard({ data: { text: this.activeProjectTabInfo.addr }, });\n                        highlightElement({ el: this.activeProjectTabInfo.childBtnEl, magicHighlightTimingMs: 1_000 }); // spin off so options disappear\n                    } else {\n                        await alertUser({ title: 'No Project?', msg: `There was no project tab found? This seems like a bug so you should report it please. (E: 249298d98278b3e07fa7261a8d009f25)` });\n                    }\n                    break;\n                case 'export-project':\n                    await this.exportProject({ compress: false });\n                    break;\n                case 'export-project-gzip':\n                    await this.exportProject({ compress: true });\n                    break;\n                case 'import-project':\n                    await this.importProject();\n                    break;\n                default:\n                    throw new Error(`(UNEXPECTED) invalid optionType (${optionType})? (E: genuuid)`);\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    protected override async initAgents(): Promise<void> {\n        const lc = `${this.lc}[${this.initAgents.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 5629caed7bb86623facfde3caf202c25)`); }\n            // if (!this.elements) { throw new Error(`(UNEXPECTED) this.elements falsy? (E: e141c6a515a92f2e68c58b5dcf2eac25)`); }\n            // const {} = this.elements;\n\n            this.metaspace = await getGlobalMetaspace_waitIfNeeded();\n\n            let agent: AgentWitnessAny | undefined = undefined;\n            let agents = await getAgents({\n                metaspace: this.metaspace,\n                type: AGENT_SPECIAL_IBGIB_TYPE_PROJECTSAGENT,\n                spaceId: undefined, // explicitly use default local space just to show this option bc it's early in life\n            });\n            if (agents.length > 0) {\n                agent = agents.at(0)!;\n            } else {\n                const agentsSvc = getAgentsSvc();\n                agent = await agentsSvc.createNewAgent({\n                    metaspace: this.metaspace,\n                    superSpace: undefined, // uses default local user space as the super space\n                    name: `ProjectsAgent-${this.instanceId}`,\n                    api: 'gemini',\n                    model: GEMINI_DEFAULT_MODEL_STR,\n                    availableFunctions: [\n                        ...AGENT_AVAILABLE_FUNCTIONS_PROJECTSAGENT,\n                    ],\n                    initialSystemText: AGENT_INITIAL_SYSTEM_TEXT_PROJECTSAGENT,\n                    initialChatText: AGENT_INITIAL_CHAT_TEXT_PROJECTSAGENT,\n                    fnGetAPIKey: this.getFnGetAPIKey(),\n                    type: AGENT_SPECIAL_IBGIB_TYPE_PROJECTSAGENT,\n                    addToAgentsTag: true,\n                });\n            }\n\n            this.agents = [agent];\n\n            if (!this.agent) { throw new Error(`(UNEXPECTED) agent falsy after createNewAgent? (E: 6ea8e8b7aa551bcf467042dbabab9425)`); }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private getFnGetAPIKey(): () => Promise<string> {\n        const lc = `${this.lc}[${this.getFnGetAPIKey.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 18dc13812e3657d0e2874b72123c6125)`); }\n\n            const fn = async () => {\n                let apiKey = await storageGet({\n                    dbName: BLANK_GIB_DB_NAME, storeName: ARMY_STORE,\n                    key: BEE_KEY,\n                });\n                return apiKey ?? '';\n            };\n            return fn;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private async setBreadcrumbs(): Promise<void> {\n        const lc = `${this.lc}[${this.setBreadcrumbs.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: b18e0977f9213dca453689fa75326b25)`); }\n\n            let appShellSvc = getAppShellSvc();\n            appShellSvc.initialized.then(async () => {\n                try {\n                    const { breadcrumbComponent } = appShellSvc;\n                    if (!breadcrumbComponent) { throw new Error(`(UNEXPECTED) breadcrumbComponent is falsy? (E: 1d5b0148882b0a7f68aab9198ddf7925)`); }\n                    if (!this.meta) { throw new Error(`(UNEXPECTED) this.meta falsy? (E: f85649a6574eb111078faeca6dea5325)`); }\n                    await breadcrumbComponent.addBreadcrumb({\n                        info: {\n                            text: 'projects',\n                            type: 'projects',\n                            // fnClickAction: () => Promise.resolve(), // do nothing\n                        },\n                        clear: true,\n                    });\n\n                    if (this.activeProjectTabInfo) {\n                        const { component: projectComponent } = this.activeProjectTabInfo;\n                        if (!projectComponent) {\n                            console.error(`${lc} (UNEXPECTED) activeProjectTabInfo truthy but its projectComponent falsy? Not throwing here, but returning early. (E: f21843e57044ec11680c078c3d0bdd25)`);\n                            return; /* <<<< returns early */\n                        }\n                        if (!projectComponent.ibGib) {\n                            console.error(`${lc} (UNEXPECTED) activeProjectTabInfo truthy but its projectComponent.ibGib falsy? Not throwing here, but returning early. (E: de3167af997ca496599724198d12ed25)`);\n                            return; /* <<<< returns early */\n                        }\n                        const projectIbGib = projectComponent.ibGib;\n                        if (isProjectIbGib_V1(projectIbGib)) {\n                            await breadcrumbComponent.addBreadcrumb({\n                                info: {\n                                    text: projectIbGib.data!.name,\n                                    type: 'project',\n                                    // in the future this will probably be highlight the project main tab\n                                    // fnClickAction: () => Promise.resolve(), // do nothing\n                                },\n                                clear: false,\n                            });\n                        } else {\n                            // ?\n                            debugger; // want to see how we have an active project component ibgib but it's not a project ibgib\n                        }\n                    }\n                } catch (error) {\n                    console.error(`${lc} couldn't set breadcrumbs for web1 component. (E: 5d255d9c91fdc126a46884cc74fada25)`);\n                }\n            });\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n}\n", "<div id=\"breadcrumb-component\" class=\"\">\n    <!-- breadcrumbs get added here in a row -->\n</div>\n", "/* Basic layout and styling for the project component */\n#breadcrumb-component {\n    display: flex;\n    flex-direction: row;\n    align-items: center;\n    justify-content: flex-start;\n    gap: 3px;\n    width: 100%;\n    height: 100%;\n    box-sizing: border-box;\n    /* Use consistent padding */\n    padding: 1%;\n\n    /* Optional: If using flexbox to control vertical alignment */\n    /* justify-content: center;  Align content vertically */\n\n}\n", "import thisHtml from './breadcrumb.html';\nimport breadcrumbCss from './breadcrumb.css';\nimport stylesCss from '../../../styles.css';\nimport rootCss from '../../../root.css';\n\nimport { extractErrorMsg, } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { IbGib_V1 } from \"@ibgib/ts-gib/dist/V1/types.mjs\";\nimport { IbGibAddr } from \"@ibgib/ts-gib/dist/types.mjs\";\nimport { MetaspaceService } from \"@ibgib/core-gib/dist/witness/space/metaspace/metaspace-types.mjs\";\nimport { IbGibDynamicComponentInstanceBase, IbGibDynamicComponentMetaBase } from \"@ibgib/web-gib/dist/ui/component/ibgib-dynamic-component-bases.mjs\";\nimport { IbGibDynamicComponentInstance, IbGibDynamicComponentInstanceInitOpts, } from \"@ibgib/web-gib/dist/ui/component/component-types.mjs\";\n\nimport {\n    GLOBAL_LOG_A_LOT, ARMY_STORE, BEE_KEY, BLANK_GIB_DB_NAME,\n} from \"../../../constants.mjs\";\nimport { BreadcrumbInfo } from \"./breadcrumb-types.mjs\";\nimport { getComponentCtorArg } from '../../../helpers.web.mjs';\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\nexport const BREADCRUMB_COMPONENT_NAME: string = 'ibgib-breadcrumb';\n\nexport class BreadcrumbComponentMeta extends IbGibDynamicComponentMetaBase {\n    protected override lc: string = `[${BreadcrumbComponentMeta.name}]`;\n\n    /**\n     * temporary regexp path for our initial dev. this component will become\n     * attached to actual ib^gib addrs\n     */\n    routeRegExp?: RegExp = new RegExp(BREADCRUMB_COMPONENT_NAME);\n    // routeRegExp?: RegExp = /apps\\/web1\\/gib\\/contact.html/;\n\n    componentName: string = BREADCRUMB_COMPONENT_NAME;\n\n    constructor() {\n        super(getComponentCtorArg());\n        customElements.define(this.componentName, BreadcrumbComponentInstance);\n    }\n\n    /**\n     * for a breadcrumb, we don't have any additional info in the path.\n     */\n    async createInstance({\n        path,\n        ibGibAddr\n    }: {\n        path: string;\n        ibGibAddr: IbGibAddr;\n    }): Promise<IbGibDynamicComponentInstance> {\n        const lc = `${this.lc}[${this.createInstance.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n            const component = document.createElement(this.componentName) as BreadcrumbComponentInstance;\n            await component.initialize({\n                ibGibAddr,\n                meta: this,\n                html: thisHtml,\n                css: [rootCss, stylesCss, breadcrumbCss],\n            });\n            return component;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n}\n\ninterface BreadcrumbElements {\n    componentEl: HTMLElement;\n    itemEls: HTMLElement[];\n}\n\nexport class BreadcrumbComponentInstance\n    extends IbGibDynamicComponentInstanceBase<IbGib_V1, BreadcrumbElements>\n    implements IbGibDynamicComponentInstance<IbGib_V1, BreadcrumbElements> {\n    protected override lc: string = `[${BreadcrumbComponentInstance.name}]`;\n\n    metaspace: MetaspaceService | undefined;\n\n    breadcrumbs: BreadcrumbInfo[] = [];\n\n    constructor() {\n        super();\n    }\n\n    override async initialize(opts: IbGibDynamicComponentInstanceInitOpts): Promise<void> {\n        const lc = `${this.lc}[${this.initialize.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n            await super.initialize(opts);\n\n            // await this.loadIbGib();\n            // await super.subscribeToIbGibUpdates();\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    override async created(): Promise<void> {\n        const lc = `${this.lc}[${this.created.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n\n            // const { meta, htmlPath, scriptPaths, cssPaths } = opts;\n\n            await this.initUI();\n\n            await this.renderUI();\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private async initUI(): Promise<void> {\n        const lc = `${this.lc}[${this.initUI.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 98c5bd4e6796961b7672cb3258e4da25)`); }\n\n            const shadowRoot = this.shadowRoot;\n\n            if (!shadowRoot) { throw new Error(`(UNEXPECTED) shadowRoot falsy? (E: genuuid)`); }\n\n            const componentEl = shadowRoot.getElementById('breadcrumb-component') as HTMLElement;\n            if (!componentEl) { throw new Error(`(UNEXPECTED) componentEl not found in shadowRoot? (E: genuuid)`); }\n\n\n            this.elements = {\n                componentEl,\n                itemEls: [],\n            };\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * rerender\n     */\n    protected async renderUI(): Promise<void> {\n        const lc = `${this.lc}[${this.renderUI.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 5415ec9be03ca640cb1a3d6a17d22625)`); }\n\n            if (!this.shadowRoot) { throw new Error(`(UNEXPECTED) this.shadowRoot falsy? (E: 48b0f7d56fda65b40a57a11a8557ef25)`); }\n            if (!this.elements) {\n                console.warn(`${lc} (UNEXPECTED) tried to render but haven't initialized elements? (W: genuuid)`);\n                return; /* <<<< returns early */\n            }\n\n            const { componentEl, } = this.elements;\n\n            // render buttons here and hook them up\n            componentEl.innerHTML = '';\n\n            for (let i = 0; i < this.breadcrumbs.length; i++) {\n                const breadcrumb = this.breadcrumbs[i];\n                const delim = document.createElement('span');\n                delim.textContent = '>';\n                componentEl.appendChild(delim);\n\n                // most breadcrumbs are navigable, but the last one is supposed\n                // to be our current location (so we can't nav via the current\n                // breadcrumb)\n                if (i < (this.breadcrumbs.length - 1) && !!breadcrumb.fnClickAction) {\n                    const link = document.createElement('a');\n                    link.textContent = breadcrumb.text;\n                    componentEl.appendChild(link);\n                    link.addEventListener('click', async (e) => {\n                        await this.execNav({ breadcrumb, breadcrumbIndex: i });\n                    });\n                } else {\n                    const text = document.createElement('span');\n                    text.textContent = breadcrumb.text;\n                    componentEl.appendChild(text);\n                }\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    private async execNav({\n        breadcrumb,\n        breadcrumbIndex,\n    }: {\n        breadcrumb: BreadcrumbInfo,\n        breadcrumbIndex: number,\n    }): Promise<void> {\n        const lc = `${this.lc}[${this.execNav.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: f5cb2b0797ed11f0ef21e3ada0b02225)`); }\n\n            if (breadcrumb.fnClickAction) {\n                // clear any downstream breadcrumbs\n                for (let i = breadcrumbIndex + 1; i < this.breadcrumbs.length; i++) {\n                    this.breadcrumbs.pop();\n                }\n\n                // update the breadcrumb UI first because it should be quick and\n                // the action might take awhile\n                await this.renderUI();\n\n                // execute it\n                await breadcrumb.fnClickAction();\n            } else {\n                console.warn(`${lc} executing nav but fnClickAction is falsy? (W: f36c438110be36a11494d5e4d3c56625)`);\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    override async disconnected(): Promise<void> {\n        const lc = `${this.lc}[${this.disconnected.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n            // no action atow\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    // #region public api\n\n    public async addBreadcrumb({\n        info,\n        clear,\n    }: {\n        info: BreadcrumbInfo,\n        clear?: boolean,\n    }): Promise<void> {\n        const lc = `${this.lc}[${this.addBreadcrumb.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 705301d430c4f65b18e005e3020c7825)`); }\n\n            if (clear) { this.breadcrumbs = []; }\n\n            // do the business\n            this.breadcrumbs.push(info);\n\n            await this.renderUI();\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    // #endregion public api\n}\n", "<div id=\"input-component\">\n    <textarea id=\"input-text\" class=\"input-text\" placeholder=\"agent loading...\" readonly></textarea>\n    <button id=\"input-send-btn\" class=\"send-btn\"><b>\u276F</b></button>\n</div>\n", ":host {\n    /* this is used for styling ibgib components for multi-view coordination, so\n     * that ibgib views that are looking at the same ibgib can be visibly shown\n     * as doing so. */\n    --ibgib-color: #ff00dd;\n    --ibgib-color-translucent: #ff00dd10;\n    --tjp-color: #00ffae;\n    --tjp-color-translucent: #00ffae10;\n}\n\n#input-component {\n    display: flex;\n    flex-direction: row;\n    align-items: stretch;\n    gap: 2px;\n    justify-content: stretch;\n    width: 100%;\n    height: 100%;\n    overflow-y: hidden;\n    box-sizing: border-box;\n    padding: 1%;\n\n    textarea {\n        /* height: 100%; */\n        height: auto;\n        width: 100px;\n        background-color: var(--input-background-color);\n        color: var(--input-text-color);\n        /* border: var(--input-border-width) var(--input-border-style) var(--input-border-color); */\n        border-radius: var(--input-border-radius);\n        padding: var(--input-padding);\n        flex-grow: 1;\n\n        /* ibgib styling */\n        border: var(--tjp-color) 1px solid;\n        box-shadow: 0 0 3px var(--tjp-color);\n        /* border-radius: 5px; */\n        background-color: var(--tjp-color-translucent);\n    }\n\n    textarea:focus {\n        outline: none !important;\n        border-radius: calc(var(--input-border-radius) + 1px);\n        /* box-shadow: 0 0 10px var(--highlight-box-shadow-color); */\n        box-shadow: 0 0 10px var(--tjp-color);\n        background-color: var(--background-color-base);\n    }\n\n    button {\n        height: 100%;\n        flex-shrink: 0;\n        align-self: center;\n        margin: 2px;\n        background-color: var(--button-background-color-base);\n        /* color: var(--button-text-color-base); */\n        color: var(--tjp-color);\n        border: var(--button-border-width-base) var(--button-border-style-base) var(--button-border-color-base);\n        border-radius: var(--button-border-radius-base);\n        padding: var(--button-padding-base);\n\n        border: var(--tjp-color) 3px solid;\n        background-color: var(--tjp-color-translucent)\n    }\n\n    button:hover {\n        /* background-color: var(--button-hover-background-color); */\n        background-color: var(--tjp-color);\n        color: var(--button-hover-text-color);\n        /* border-color: var(--button-hover-border-color); */\n        box-shadow: 0 0 10px var(--tjp-color);\n    }\n\n}\n", "import { RCLIArgTypeName, RCLIParamInfo } from \"./rcli-types.mjs\";\n\n/**\n * The keys of this object are the primary prefixes. The values are the arrays\n * of alternate param prefixes.\n *\n * primary-param-prefix -> alt-param-prefix[]\n *\n * this is for making synonyms in a more normalized way.\n */\nexport const PARAM_PREFIXES: { [paramName: string]: string[] } = {\n    'src': ['source', 'from', 'in', 'input'],\n    'dest': ['destination', 'to', 'out', 'output'],\n}\n\n/**\n * builds a parameter with prefix synonyms.\n *\n * helper specifically for rcli params with prefixes.\n */\nexport function getParam_src({\n    paramName,\n    noBare,\n    argTypeName,\n    description,\n}: {\n    paramName: string,\n    /**\n     * set to true if you don't want a synonym that is just {@link paramName}\n     * (without a prefix).\n     *\n     * For example, i differentiate between PARAM_INFO_NAME and\n     * PARAM_INFO_SRC_NAME, so on src_name I don't want the bare \"name\" because\n     * that is in PARAM_INFO_NAME.\n     */\n    noBare?: boolean\n    argTypeName?: RCLIArgTypeName,\n    description?: string,\n}): RCLIParamInfo {\n    const rcliParam: RCLIParamInfo = {\n        name: `src-${paramName}`,\n        argTypeName: argTypeName ?? 'string',\n        synonyms: [...PARAM_PREFIXES['src'].map(x => `${x}-${paramName}`),],\n        description,\n    }\n    if (!noBare) { rcliParam.synonyms!.push(paramName); }\n    return rcliParam;\n}\n\n/**\n * builds a parameter with prefix synonyms.\n *\n * helper specifically for rcli params with prefixes.\n */\nexport function getParam_dest({ paramName, argTypeName = 'string', description }: {\n    paramName: string,\n    argTypeName?: RCLIArgTypeName,\n    description?: string,\n}): RCLIParamInfo {\n    const rcliParam: RCLIParamInfo = {\n        name: `dest-${paramName}`,\n        argTypeName: argTypeName ?? 'string',\n        synonyms: [...PARAM_PREFIXES['dest'].map(x => `${x}-${paramName}`),],\n        description,\n    }\n    return rcliParam;\n}\n\n/**\n * special param that is used as the only param allowed that doesn't have a\n * \"double-dash-specifier=\" form. one \"bare\" arg is allowed atow. if a bare arg\n * is found, it will be mapped to this param info.\n */\nexport const PARAM_INFO_BARE: RCLIParamInfo = {\n    name: 'bare',\n    description: `special param that is used as the only param allowed that doesn't have a \"double-dash-specifier=\" form. one \"bare\" arg is allowed atow. if a bare arg is found, it will be mapped to this param info.`,\n    synonyms: ['bare-arg', 'bare-param', 'no-name', 'manco', 'arg-with-no-name', 'param-with-no-name'],\n    argTypeName: 'string',\n};\n/**\n * the most essential parameter in existence...we all need it.\n */\nexport const PARAM_INFO_HELP: RCLIParamInfo = {\n    name: 'help',\n    description: 'the most essential parameter in existence...we all need it.',\n    synonyms: ['h'],\n    isFlag: true,\n    argTypeName: 'boolean',\n};\n/**\n * flag for dry-run (not producing output but simulating what WOULD be produced)\n */\nexport const PARAM_INFO_DRY_RUN: RCLIParamInfo = {\n    name: 'dry-run',\n    description: 'flag for dry-run (not producing output but simulating what WOULD be produced)',\n    synonyms: ['dry'],\n    isFlag: true,\n    argTypeName: 'boolean',\n};\n/**\n * path pointing to a data resource (file/folder)\n */\nexport const PARAM_INFO_DATA_PATH: RCLIParamInfo = {\n    name: 'data-path',\n    description: 'path pointing to a data resource (file/folder)',\n    synonyms: [],\n    argTypeName: 'string',\n};\n/**\n * for referencing/ingesting file(s)/folder(s) in a fs\n */\nexport const PARAM_INFO_INPUT_PATH: RCLIParamInfo = getParam_src({\n    paramName: 'path',\n    description: 'for referencing/ingesting file(s)/folder(s) in a fs',\n})\n/**\n * for generating file(s)/folder(s)\n */\nexport const PARAM_INFO_OUTPUT_PATH: RCLIParamInfo = getParam_dest({\n    paramName: 'path',\n    description: 'for indicating where to put generated file(s)/folder(s)',\n})\n/**\n * catchall data as a string parameter\n */\nexport const PARAM_INFO_DATA_STRING: RCLIParamInfo = {\n    name: 'data-string',\n    description: 'catchall data as a string parameter',\n    synonyms: ['ds'],\n    argTypeName: 'string',\n};\n/**\n * catchall data as an integer parameter\n */\nexport const PARAM_INFO_DATA_INTEGER: RCLIParamInfo = {\n    name: 'data-integer',\n    description: 'catchall data as an integer parameter',\n    synonyms: ['integer', 'int', 'data-number', 'number', 'num'],\n    argTypeName: 'integer',\n};\n/**\n * catchall data as a boolean parameter\n */\nexport const PARAM_INFO_DATA_BOOLEAN: RCLIParamInfo = {\n    name: 'data-boolean',\n    description: 'catchall data as an integer parameter',\n    synonyms: ['boolean', 'bool', 'data-bool'],\n    argTypeName: 'integer',\n};\n/**\n * used for when you have a name of whatever, based on command/context.\n *\n * i'm adding this for `PARAM_INFO_GENERATE_SOURCE_FILE` (downstream in\n * ibgib/rcli app), but should be reusable.\n */\nexport const PARAM_INFO_NAME: RCLIParamInfo = {\n    name: 'name',\n    description: 'specify the name of something determined by context of the command.',\n    argTypeName: 'string',\n    allowMultiple: false,\n    synonyms: [],\n};\n\n/**\n * Array of common parameters.\n */\nexport const COMMON_PARAM_INFOS: RCLIParamInfo[] = [\n    PARAM_INFO_BARE,\n    PARAM_INFO_HELP,\n    PARAM_INFO_DRY_RUN,\n    PARAM_INFO_DATA_PATH,\n    PARAM_INFO_INPUT_PATH,\n    PARAM_INFO_OUTPUT_PATH,\n    PARAM_INFO_DATA_STRING,\n    PARAM_INFO_DATA_INTEGER,\n    PARAM_INFO_DATA_BOOLEAN,\n    PARAM_INFO_NAME,\n];\n", "import { RCLIParamInfo } from \"@ibgib/helper-gib/dist/rcli/rcli-types.mjs\";\nimport { COMMON_PARAM_INFOS } from \"@ibgib/helper-gib/dist/rcli/rcli-constants.mjs\";\n\nexport const ENCRYPTED_OUTPUT_FILE_EXT = 'encrypt-gib';\n\nexport const PARAM_INFO_ENCRYPT: RCLIParamInfo = {\n    name: 'encrypt',\n    isFlag: true,\n    argTypeName: 'boolean',\n    description: 'flag to indicate a encrypt command'\n};\nexport const PARAM_INFO_DECRYPT: RCLIParamInfo = {\n    name: 'decrypt',\n    isFlag: true,\n    argTypeName: 'boolean',\n    description: 'flag to indicate a decrypt command'\n};\nexport const PARAM_INFO_STRENGTH: RCLIParamInfo = {\n    name: 'strength',\n    argTypeName: 'string',\n    description: 'convenience param. broad strength configuration to determine some default encrypt/decrypt parameters. kind of like an alias of a param set, useful if you don\\'t want to specify all of your individual parameters. i dunno, all of this is use at your own risk.'\n};\nexport const PARAM_INFO_SALT: RCLIParamInfo = {\n    name: 'salt',\n    argTypeName: 'string',\n    description: 'salt to use with each call to hash. used in conjunction with saltStrategy.'\n};\nexport const PARAM_INFO_INDEXING_MODE: RCLIParamInfo = {\n    name: 'indexing-mode',\n    argTypeName: 'string',\n    description: 'mode used when indexing into a jit alphabet per round. can be \"indexOf\" or \"lastIndexOf\". when trying to mitigate against brute forcing, \"lastIndexOf\" should be used so that the entire hash chain is required in order to index into (i think).'\n};\nexport const PARAM_INFO_BLOCKMODE_FLAG: RCLIParamInfo = {\n    name: 'block-mode',\n    argTypeName: 'boolean',\n    isFlag: true,\n    description: 'if true, will execute encrypt/decrypt in a block mode to help mitigate brute force short-circuit attacks.'\n};\nexport const PARAM_INFO_BLOCKMODE_BLOCK_SIZE: RCLIParamInfo = {\n    name: 'block-size',\n    argTypeName: 'integer',\n    description: 'the number of plaintext chars to encipher as a group before proceeding to the next block/group. this can increase processing time and in general act as a memory-hard barrier or significant processing increase.'\n};\nexport const PARAM_INFO_BLOCKMODE_NUM_OF_PASSES: RCLIParamInfo = {\n    name: 'num-of-passes',\n    argTypeName: 'integer',\n    description: 'number of passes per block of plaintext. so if you process data in blocks of 5 and you set this to 10, you will encipher each plaintext char a total of 10 times, but each encipherment happens after the entire previous iteration completes.'\n};\nexport const PARAM_INFO_HASH_ALGORITHM: RCLIParamInfo = {\n    name: 'hash-algorithm',\n    argTypeName: 'string',\n    description: 'specifies the type of hash function to use per round'\n};\nexport const PARAM_INFO_SALT_STRATEGY: RCLIParamInfo = {\n    name: 'salt-strategy',\n    argTypeName: 'string',\n    description: 'the type of salt combining at the initial keystretch phase, as well as per recursive hash inside each round.'\n};\nexport const PARAM_INFO_INITIAL_RECURSIONS: RCLIParamInfo = {\n    name: 'initial-recursions',\n    argTypeName: 'integer',\n    description: 'the initial number of recursive hash functions to execute at the beginning of the encryption (before any round functions are applied on plaintext). this is essentially the key stretching phase.'\n};\nexport const PARAM_INFO_RECURSIONS_PER_HASH: RCLIParamInfo = {\n    name: 'recursions-per-hash',\n    argTypeName: 'integer',\n    description: 'the number of recursive hash functions to execute per round/plaintext character.'\n};\n\n/**\n * Array of all parameters this library's RLI supports.\n */\nexport const PARAM_INFOS: RCLIParamInfo[] = [\n    ...COMMON_PARAM_INFOS,\n    PARAM_INFO_ENCRYPT,\n    PARAM_INFO_DECRYPT,\n    PARAM_INFO_STRENGTH,\n    PARAM_INFO_SALT,\n    PARAM_INFO_INDEXING_MODE,\n    PARAM_INFO_BLOCKMODE_FLAG,\n    PARAM_INFO_BLOCKMODE_BLOCK_SIZE,\n    PARAM_INFO_BLOCKMODE_NUM_OF_PASSES,\n    PARAM_INFO_HASH_ALGORITHM,\n    PARAM_INFO_SALT_STRATEGY,\n    PARAM_INFO_INITIAL_RECURSIONS,\n];\n", "/**\n * @module blank-canvas constants for use with BlankCanvasApp\n *\n * app constants are in this file!\n */\n\n// #region some enum\n// /**\n//  * example enum-like type+const that I use in ibgib. sometimes i put\n//  * these in the types.mts and sometimes in the const.mts, depending\n//  * on context.\n//  */\n// export type SomeEnum =\n//     'ib' | 'gib';\n// export const SomeEnum = {\n//     ib: 'ib' as SomeEnum,\n//     gib: 'gib' as SomeEnum,\n// } satisfies { [key: string]: SomeEnum };\n// export const SOME_TYPE_VALUES: SomeEnum[] = Object.values(SomeEnum);\n// #endregion some enum\n\nexport const BLANK_CANVAS_APP_NAME_REGEXP = /^[a-zA-Z0-9_\\-.]{1,255}$/;\nexport const BLANK_CANVAS_ATOM = 'blank-canvas';\nexport const BLANK_CANVAS_NAME_REGEXP = /^[a-zA-Z0-9_\\-. @~]{1,1024}$/;\n\nexport const CHAT_WITH_AGENT_PLACEHOLDER_SUBMITKEYSTROKE = `Ctrl+ENTER to send`;\nexport const CHAT_WITH_AGENT_PLACEHOLDER_AGENT = `Chat with the agent. Ctrl+ENTER to send`;\n// export const CHAT_WITH_AGENT_PLACEHOLDER_PRIMARYAGENT = `Chat with the primary agent about ibgib and this website.\\nCtrl+ENTER to send`;\nexport const CHAT_WITH_AGENT_PLACEHOLDER_PRIMARYAGENT = [\n    `Chat with the primary AI agent here, like...`,\n    `What's ibgib?`,\n    `What exactly makes ibgib's addressing schema unique?`,\n    `What's this website?`,\n    `Where's the src for ibgib libs & this website?`,\n    CHAT_WITH_AGENT_PLACEHOLDER_SUBMITKEYSTROKE,\n].join('\\n');\nexport const CHAT_WITH_AGENT_PLACEHOLDER_PROJECTSAGENT = `Chat with the projects agent. Ctrl+ENTER to send`;\nexport const CHAT_WITH_AGENT_NEED_API_KEY = `This website currently is BYO-Key, so enter your Gemini API key here. Be aware this will be stored LOCALLY in PLAINTEXT in your browser's IndexedDB.\\n\\nThis will enable not only a website-wide chatbot that you may already be familiar with, but also other UX agents that power some of the advanced, dynamic UX features.\\n\\nDonate! Invest! Help fund us to improve this groundbreaking website and protocol, enabling others to create their own sovereign websites downstream via the protocol. See the funding page for more info.`;\n\nimport { RCLIParamInfo } from \"@ibgib/helper-gib/dist/rcli/rcli-types.mjs\"\nimport { COMMON_PARAM_INFOS, PARAM_PREFIXES, getParam_dest, getParam_src, } from \"@ibgib/helper-gib/dist/rcli/rcli-constants.mjs\";\nimport { clone } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport {\n    PARAM_INFO_DECRYPT, PARAM_INFO_ENCRYPT,\n    PARAM_INFO_INDEXING_MODE, PARAM_INFO_SALT,\n    // PARAM_INFO_STRENGTH, // maybe will use this later?\n    PARAM_INFO_BLOCKMODE_FLAG, PARAM_INFO_BLOCKMODE_BLOCK_SIZE,\n    PARAM_INFO_BLOCKMODE_NUM_OF_PASSES, PARAM_INFO_HASH_ALGORITHM,\n    PARAM_INFO_SALT_STRATEGY, PARAM_INFO_INITIAL_RECURSIONS, PARAM_INFO_RECURSIONS_PER_HASH,\n} from '@ibgib/encrypt-gib/dist/rcli/rcli-constants.mjs';\nimport { TransformOpts_Fork, TransformOpts_Mut8, TransformOpts_Rel8 } from \"@ibgib/ts-gib/dist/types.mjs\";\nimport { ROOT_ADDR } from \"@ibgib/ts-gib/dist/V1/constants.mjs\";\nimport { BOOTSTRAP_IBGIB_ADDR } from \"@ibgib/core-gib/dist/witness/space/bootstrap/bootstrap-constants.mjs\";\n\n// import { FileEncoding } from \"./rcli-types.mjs\";\n\n/**\n * Used in npm test\n */\nexport const RCLI_TEST_PATH = 'test-rcli';\n\n/**\n * the path used for the ibgib subpath if not set by args.\n */\nexport const RCLI_DEFAULT_OUTPUT_PATH = '.ibgib';\n\n/**\n * used when prompting the user.\n */\nexport const DEFAULT_PROMPT_TEMPLATE = `[$id]> `;\n\n/**\n * this is the thing that comes before a command.\n *\n * you can also just use the --[cmd] format (i think).\n */\nexport const DEFAULT_COMMAND_ESCAPE_STRING = ':';\n\n/**\n * the max length of a command escape string.\n */\nexport const RCLI_MAX_ESCAPE_STRING_LENGTH = 8;\n\n/**\n * options that you start with when performing a fork operation.\n *\n * parts of this are what get overridden by parameters.\n */\nexport const DEFAULT_FORK_OPTIONS: TransformOpts_Fork = {\n    type: 'fork',\n    srcAddr: ROOT_ADDR,\n    cloneData: true,\n    cloneRel8ns: true,\n    destIb: undefined,\n    dna: true,\n    linkedRel8ns: undefined,\n    nCounter: true,\n    noTimestamp: false,\n    tjp: {\n        timestamp: true,\n        uuid: true,\n    },\n    uuid: undefined,\n};\n\n/**\n * options that you start with when performing a mut8 operation.\n *\n * parts of this are what get overridden by parameters.\n */\nexport const DEFAULT_MUT8_OPTIONS: TransformOpts_Mut8 = {\n    type: 'mut8',\n    dna: true,\n    linkedRel8ns: undefined,\n    nCounter: true,\n    noTimestamp: false,\n};\n\n/**\n * options that you start with when performing a rel8 operation.\n *\n * parts of this are what get overridden by parameters.\n */\nexport const DEFAULT_REL8_OPTIONS: TransformOpts_Rel8 = {\n    type: 'rel8',\n    dna: true,\n    linkedRel8ns: undefined,\n    nCounter: true,\n    noTimestamp: false,\n};\n\n/**\n * using when reading a file from the command line.\n *\n * ## notes\n *\n * * currently working on handle-reify-file.mts\n */\n// export const DEFAULT_FILE_ENCODING: FileEncoding = 'utf8';\n\n/**\n * maximum number of chars when generating name\n */\nexport const MAX_GENERATE_FILE_NAME_LENGTH = 32;\n\n// #region param info related\n\n// #region command defs\n\n/**\n * command typescript type literal.\n *\n * this is useful (i guess?) in locking down commands.\n *\n * # when creating new commands\n *\n * * Add it to the BlankCanvasCommand type here\n * * add to the constant of the same name\n * * add any synonyms\n */\nexport type BlankCanvasCommand =\n    'help' |\n    'init' |\n    'quit' |\n    'cwd' |\n    'fork' |\n    'mut8' |\n    'rel8' |\n    'version' |\n    'add-comment' | // add-link, add-pic\n    'list-chat' |\n    'secret' |\n    'encryption' |\n    'sync' |\n    'add-stone' |\n    'reify-file' |\n    'generate-source-file' |\n    'info' |\n    'export' |\n    'import' |\n    'space' |\n    'b2tfs-init' |\n    'b2tfs-branch' |\n    'b2tfs-activate-branch' |\n    'b2tfs-info' |\n    'b2tfs-diff' |\n    'b2tfs-sync'\n    ;\nexport const BlankCanvasCommand = {\n    help: 'help' as BlankCanvasCommand,\n    init: 'init' as BlankCanvasCommand,\n    quit: 'quit' as BlankCanvasCommand,\n    cwd: 'cwd' as BlankCanvasCommand,\n    fork: 'fork' as BlankCanvasCommand,\n    mut8: 'mut8' as BlankCanvasCommand,\n    rel8: 'rel8' as BlankCanvasCommand,\n    version: 'version' as BlankCanvasCommand,\n    add_comment: 'add-comment' as BlankCanvasCommand,\n    list_chat: 'list-chat' as BlankCanvasCommand,\n    secret: 'secret' as BlankCanvasCommand,\n    encryption: 'encryption' as BlankCanvasCommand,\n    sync: 'sync' as BlankCanvasCommand,\n    create_stone: 'add-stone' as BlankCanvasCommand,\n    reify_file: 'reify-file' as BlankCanvasCommand,\n    generate_source_file: 'generate-source-file' as BlankCanvasCommand,\n    info: 'info' as BlankCanvasCommand,\n    export: 'export' as BlankCanvasCommand,\n    import: 'import' as BlankCanvasCommand,\n    space: 'space' as BlankCanvasCommand,\n    b2tfs_init: 'b2tfs-init' as BlankCanvasCommand,\n    b2tfs_branch: 'b2tfs-branch' as BlankCanvasCommand,\n    b2tfs_activate_branch: 'b2tfs-activate-branch' as BlankCanvasCommand,\n    b2tfs_info: 'b2tfs-info' as BlankCanvasCommand,\n    b2tfs_diff: 'b2tfs-diff' as BlankCanvasCommand,\n    b2tfs_sync: 'b2tfs-sync' as BlankCanvasCommand,\n} satisfies { [key: string]: BlankCanvasCommand };\nexport const RCLI_COMMANDS: BlankCanvasCommand[] = Object.values(BlankCanvasCommand);\n\n/**\n * B2tFS command synonyms can be built with these instead of the full \"b2tfs\".\n */\nexport const B2TFS_CMD_PREFIXES: string[] = ['b2', 'fs', 'vcs'];\n/**\n * small helper function to generate variants of b2tfs commands. so if you have\n * a cmd \"activate\", this will add `b2tfs-activate`, `b2-activate\n * @param cmdOrSynonymBase is the thing you want to create b2tfs variants for.\n * @returns array of synonyms for given `cmdOrSynonymBase`\n */\nconst fnGetB2PrefixedVariants = (cmdOrSynonymBase: string): string[] => {\n    if (cmdOrSynonymBase.startsWith(\"b2tfs-\")) {\n        // no need to add a b2tfs- variant and strip off the b2tfs from cmd\n        return B2TFS_CMD_PREFIXES.map(prefix => `${prefix}-${cmdOrSynonymBase.substring(\"b2tfs-\".length)}`);\n    } else {\n        // we want the b2tfs variant in there, and we don't need to strip the\n        // b2tfs- from the incoming cmd.\n        return [\n            `b2tfs-${cmdOrSynonymBase}`,\n            ...B2TFS_CMD_PREFIXES.map(prefix => `${prefix}-${cmdOrSynonymBase}`)\n        ];\n    }\n}\nexport const RCLI_COMMAND_SYNONYMS: { [key: string]: string[] } = {\n    [BlankCanvasCommand.help]: ['h', 'huh', 'wat'],\n    [BlankCanvasCommand.init]: ['initialize',],\n    [BlankCanvasCommand.quit]: ['q', 'exit'],\n    [BlankCanvasCommand.fork]: [],\n    [BlankCanvasCommand.mut8]: [],\n    [BlankCanvasCommand.rel8]: [],\n    [BlankCanvasCommand.cwd]: ['pwd'],\n    [BlankCanvasCommand.add_comment]: [],\n    [BlankCanvasCommand.secret]: [],\n    [BlankCanvasCommand.encryption]: [],\n    [BlankCanvasCommand.sync]: [],\n    [BlankCanvasCommand.version]: ['v'],\n    [BlankCanvasCommand.list_chat]: ['view-chat', 'replay', 'ls-chat'],\n    [BlankCanvasCommand.create_stone]: ['new-stone'],\n    [BlankCanvasCommand.reify_file]: ['reify'],\n    [BlankCanvasCommand.generate_source_file]: [\n        'generate-src', 'generate-src-file', 'g-src', 'g-src-file'\n    ],\n    [BlankCanvasCommand.info]: ['status', 'details', 'deets', 'cat'],\n    [BlankCanvasCommand.export]: [],\n    [BlankCanvasCommand.import]: [],\n    [BlankCanvasCommand.space]: ['spaces'], // hmm may be changing this in the future\n    [BlankCanvasCommand.b2tfs_init]: [...fnGetB2PrefixedVariants(BlankCanvasCommand.b2tfs_init)],\n    [BlankCanvasCommand.b2tfs_branch]: [...fnGetB2PrefixedVariants(BlankCanvasCommand.b2tfs_branch)],\n    [BlankCanvasCommand.b2tfs_activate_branch]: [\n        ...fnGetB2PrefixedVariants(BlankCanvasCommand.b2tfs_activate_branch),\n        ...fnGetB2PrefixedVariants('activate'),\n    ],\n    [BlankCanvasCommand.b2tfs_info]: [\n        ...fnGetB2PrefixedVariants(BlankCanvasCommand.b2tfs_info),\n        ...fnGetB2PrefixedVariants('status'), // maybe change later to different cmd? hmm...\n    ],\n    [BlankCanvasCommand.b2tfs_diff]: [\n        ...fnGetB2PrefixedVariants(BlankCanvasCommand.b2tfs_diff),\n    ],\n    [BlankCanvasCommand.b2tfs_sync]: [\n        ...fnGetB2PrefixedVariants(BlankCanvasCommand.b2tfs_sync),\n    ],\n};\nexport const RCLI_COMMAND_IDENTIFIERS: string[] = [\n    ...RCLI_COMMANDS,\n    ...Object.values(RCLI_COMMAND_SYNONYMS).flatMap(x => x),\n];\n// do a quick validation to avoid duplicate command names/synonyms.\nif (RCLI_COMMAND_IDENTIFIERS.length !== new Set(RCLI_COMMAND_IDENTIFIERS).size) {\n    throw new Error(`duplicate rcli command identifier found. (E: 8a962a60050a506e14ff49b81ffd2423)`);\n}\nif (RCLI_COMMAND_IDENTIFIERS.some(x => x === '')) {\n    throw new Error(`empty string rcli command identifier found (E: 6bcff3c0f333544a583a24c47d161823)`);\n}\n\n/**\n * generated constant whose values are param infos for the command in\n * BlankCanvasCommand constant.\n *\n * ATOW all of these are boolean flags, some with synonyms, that do not allow\n * mutiple.\n */\nexport const RCLI_COMMAND_PARAM_INFOS: Record<BlankCanvasCommand, RCLIParamInfo> =\n    Object\n        .values(RCLI_COMMANDS)\n        .reduce((agg: Record<BlankCanvasCommand, RCLIParamInfo>, cmdName: BlankCanvasCommand) => {\n            agg[cmdName] = {\n                name: cmdName,\n                argTypeName: 'boolean',\n                allowMultiple: false,\n                isFlag: true,\n                synonyms: RCLI_COMMAND_SYNONYMS[cmdName],\n            } as RCLIParamInfo;\n            return agg;\n        }, {} as Record<BlankCanvasCommand, RCLIParamInfo>);\n;\n\n// /**\n//  * The keys of this object are the primary prefixes. The values are the arrays\n//  * of alternate param prefixes.\n//  *\n//  * primary-param-prefix -> alt-param-prefix[]\n//  *\n//  * this is for making synonyms in a more normalized way.\n//  */\n// const PARAM_PREFIXES: { [paramName: string]: string[] } = {\n//     'src': ['source', 'from', 'in', 'input'],\n//     'dest': ['destination', 'to', 'out', 'output'],\n// }\n\n// // #endregion command defs\n// function getParam_src({ paramName, noBare }: {\n//     paramName: string,\n//     /**\n//      * set to true if you don't want a synonym that is just {@link paramName}\n//      * (without a prefix).\n//      *\n//      * For example, i differentiate between PARAM_INFO_NAME and\n//      * PARAM_INFO_SRC_NAME, so on src_name I don't want the bare \"name\" because\n//      * that is in PARAM_INFO_NAME.\n//      */\n//     noBare?: boolean\n// }): RCLIParamInfo {\n//     const rcliParam: RCLIParamInfo = {\n//         name: `src-${paramName}`,\n//         argTypeName: 'string',\n//         synonyms: [...PARAM_PREFIXES['src'].map(x => `${x}-${paramName}`),],\n//     }\n//     if (!noBare) { rcliParam.synonyms!.push(paramName); }\n//     return rcliParam;\n// }\n// function getParam_dest({ paramName }: {\n//     paramName: string,\n// }): RCLIParamInfo {\n//     const rcliParam: RCLIParamInfo = {\n//         name: `dest-${paramName}`,\n//         argTypeName: 'string',\n//         synonyms: [...PARAM_PREFIXES['dest'].map(x => `${x}-${paramName}`),],\n//     }\n//     return rcliParam;\n// }\n\n/**\n * name of the src\n */\nexport const PARAM_INFO_SRC_NAME = getParam_src({ paramName: 'name', noBare: true });\n['src', ...PARAM_PREFIXES['src']].forEach(x => { PARAM_INFO_SRC_NAME.synonyms!.push(x) });\nexport const PARAM_INFO_SRC_ALIAS = getParam_src({ paramName: 'alias', noBare: false });\nexport const PARAM_INFO_DEST_ALIAS = getParam_dest({ paramName: 'alias', });\n/**\n * used as a general param in various cases when only a single ibgib addr is\n * expected.\n *\n * when fork, use this for srcAddr of ibGib that you're forking\n *\n * when doing --fs --init (atow in progress/not impl), this will reference\n * an existing fs tag, essentially like doing an import.\n */\nexport const PARAM_INFO_SRC_ADDR = getParam_src({ paramName: 'addr', noBare: false });\n/**\n * used as a general param in various cases when executing operations where you\n * have to provide a source and destination and are referencing via ids (as\n * opposed to say, addrs).\n */\nexport const PARAM_INFO_SRC_ID = getParam_src({ paramName: 'id', noBare: false });\n/**\n * used as a general param in various cases when executing operations where you\n * have to provide a source and destination and are referencing via addrs.\n */\nexport const PARAM_INFO_DEST_ADDR = getParam_dest({ paramName: 'addr', });\n/**\n * used as a general param in various cases when executing operations where you\n * have to provide a source and destination and are referencing via ids.\n */\nexport const PARAM_INFO_DEST_ID = getParam_dest({ paramName: 'id', });\n/**\n * used as a general param in various cases when executing operations where you\n * have to provide a source and destination and are referencing via names.\n *\n * this is a special dest param, in that some of the prefixes can be used by\n * themselves, e.g., '--to=\"some name\"'.\n */\nexport const PARAM_INFO_DEST_NAME: RCLIParamInfo = getParam_dest({ paramName: 'name' });\n['dest', ...PARAM_PREFIXES['dest']].forEach(x => { PARAM_INFO_DEST_NAME.synonyms!.push(x) });\n\n// #region param_info for commands\n\n/**\n * inits/bootstraps a local space\n * should be used in conjunction with data-path, output-path\n * @see {@link PARAM_INFO_DATA_PATH}\n * @see {@link PARAM_INFO_OUTPUT_PATH}\n */\nexport const PARAM_INFO_INIT: RCLIParamInfo = RCLI_COMMAND_PARAM_INFOS[BlankCanvasCommand.init];\n/**\n * execute a fork transform\n *\n * @see {@link TransformOpts_Fork}\n */\nexport const PARAM_INFO_FORK: RCLIParamInfo = RCLI_COMMAND_PARAM_INFOS[BlankCanvasCommand.fork];\n/**\n * execute a mut8 transform\n *\n * @see {@link TransformOpts_Mut8}\n */\nexport const PARAM_INFO_MUT8: RCLIParamInfo = RCLI_COMMAND_PARAM_INFOS[BlankCanvasCommand.mut8];\n/**\n * execute a rel8 transform\n *\n * @see {@link TransformOpts_Rel8}\n */\nexport const PARAM_INFO_REL8: RCLIParamInfo = RCLI_COMMAND_PARAM_INFOS[BlankCanvasCommand.rel8];\nexport const PARAM_INFO_QUIT: RCLIParamInfo = RCLI_COMMAND_PARAM_INFOS[BlankCanvasCommand.quit];\nexport const PARAM_INFO_CWD: RCLIParamInfo = RCLI_COMMAND_PARAM_INFOS[BlankCanvasCommand.cwd];\nexport const PARAM_INFO_ADD_COMMENT: RCLIParamInfo = RCLI_COMMAND_PARAM_INFOS[BlankCanvasCommand.add_comment];\nexport const PARAM_INFO_SECRET: RCLIParamInfo = RCLI_COMMAND_PARAM_INFOS[BlankCanvasCommand.secret];\nexport const PARAM_INFO_ENCRYPTION: RCLIParamInfo = RCLI_COMMAND_PARAM_INFOS[BlankCanvasCommand.encryption];\nexport const PARAM_INFO_SYNC: RCLIParamInfo = RCLI_COMMAND_PARAM_INFOS[BlankCanvasCommand.sync];\nexport const PARAM_INFO_VERSION: RCLIParamInfo = RCLI_COMMAND_PARAM_INFOS[BlankCanvasCommand.version];\nexport const PARAM_INFO_LIST_CHAT: RCLIParamInfo = RCLI_COMMAND_PARAM_INFOS[BlankCanvasCommand.list_chat];\nexport const PARAM_INFO_CREATE_STONE: RCLIParamInfo = RCLI_COMMAND_PARAM_INFOS[BlankCanvasCommand.create_stone];\n/**\n * takes a file in a filesystem that is not an ibgib (with a hash) and reifies\n * it to an ibgib that includes the full ib^gib address with hash.\n *\n * @example if you have a '.ibgibignore' file, then you do not have any kind of\n * metadata/hash associated with that. this will take that file and convert it\n * into an ibgib file.\n */\nexport const PARAM_INFO_REIFY_FILE: RCLIParamInfo = RCLI_COMMAND_PARAM_INFOS[BlankCanvasCommand.reify_file];\nexport const PARAM_INFO_GENERATE_SOURCE_FILE: RCLIParamInfo = RCLI_COMMAND_PARAM_INFOS[BlankCanvasCommand.generate_source_file];\nexport const PARAM_INFO_INFO: RCLIParamInfo = RCLI_COMMAND_PARAM_INFOS[BlankCanvasCommand.info];\n/**\n * export an ibgib graph to a single file (or group of files/compressed file?)\n */\nexport const PARAM_INFO_EXPORT: RCLIParamInfo = RCLI_COMMAND_PARAM_INFOS[BlankCanvasCommand.export];\n/**\n * import an ibgib graph from a single file (or group of files/compressed file?)\n * that was created via an export.\n */\nexport const PARAM_INFO_IMPORT: RCLIParamInfo = RCLI_COMMAND_PARAM_INFOS[BlankCanvasCommand.import];\nexport const PARAM_INFO_SPACE: RCLIParamInfo = RCLI_COMMAND_PARAM_INFOS[BlankCanvasCommand.space];\n\nexport const PARAM_INFO_B2TFS_INIT: RCLIParamInfo = RCLI_COMMAND_PARAM_INFOS[BlankCanvasCommand.b2tfs_init];\nexport const PARAM_INFO_B2TFS_BRANCH: RCLIParamInfo = RCLI_COMMAND_PARAM_INFOS[BlankCanvasCommand.b2tfs_branch];\nexport const PARAM_INFO_B2TFS_ACTIVATE_BRANCH: RCLIParamInfo = RCLI_COMMAND_PARAM_INFOS[BlankCanvasCommand.b2tfs_activate_branch];\nexport const PARAM_INFO_B2TFS_INFO: RCLIParamInfo = RCLI_COMMAND_PARAM_INFOS[BlankCanvasCommand.b2tfs_info];\nexport const PARAM_INFO_B2TFS_DIFF: RCLIParamInfo = RCLI_COMMAND_PARAM_INFOS[BlankCanvasCommand.b2tfs_diff];\nexport const PARAM_INFO_B2TFS_SYNC: RCLIParamInfo = RCLI_COMMAND_PARAM_INFOS[BlankCanvasCommand.b2tfs_sync];\n\n// #endregion param_info for commands\n\n/**\n * we want this just to be a known flag so that we don't throw an error when we\n * see this. rcli will not directly use this, but it will be used for debugging.\n */\nexport const PARAM_INFO_INSPECT: RCLIParamInfo = {\n    name: 'inspect',\n    isFlag: true,\n    synonyms: ['inspect-brk'],\n    argTypeName: 'boolean',\n};\n\n// #region ibgib params\n\n\n/**\n * when fork, use for \"destIb\"\n * when mut8, use for \"mut8Ib\"\n */\nexport const PARAM_INFO_IB: RCLIParamInfo = {\n    name: 'ib',\n    argTypeName: 'string',\n};\n\n/**\n * when rel8, use multiple of these for addrs\n *\n * the value should contain both rel8nName and addr with double vertical bar\n * delimiter.\n *\n * @example --+addr=\"comment||abc^123hash\"\n */\nexport const PARAM_INFO_ADD_ADDR: RCLIParamInfo = {\n    name: 'add-addr',\n    argTypeName: 'string',\n    allowMultiple: true,\n    synonyms: ['+addr', '+@'],\n};\n\n/**\n * when rel8, use multiple of these for addrs to remove (unrel8)\n */\nexport const PARAM_INFO_RM_ADDR: RCLIParamInfo = {\n    name: 'rm-addr',\n    argTypeName: 'string',\n    allowMultiple: true,\n    synonyms: ['-addr', '-@'],\n};\n\n/**\n * tjp defaults to both uuid and timestamp.\n *\n * if one of this param is provided, this will be used **exclusively**. So if\n * you pass ing tjp=\"uuid\", then the timestamp tjp will be falsy.\n *\n * @param {('uuid'|'timestamp'|'none')}\n */\nexport const PARAM_INFO_TJP: RCLIParamInfo = {\n    name: 'tjp',\n    argTypeName: 'string',\n};\n\n/**\n * specifies a \"special\" ibgib (usually an index). if is an empty string, will\n * return the meta special ibgib (index of special ibgibs).\n *\n * used in conjunction with\n * * {@link PARAM_INFO_INFO}\n */\nexport const PARAM_INFO_SPECIAL: RCLIParamInfo = {\n    name: 'special',\n    argTypeName: 'boolean',\n    synonyms: [],\n    allowMultiple: false,\n    description: `specifies a \"special\" ibgib (usually an index).`,\n    isFlag: true,\n};\n\n/**\n * flag that indicates when forking, the parent's data should be cloned.\n */\nexport const PARAM_INFO_CLONE_DATA: RCLIParamInfo = {\n    name: 'clone-data',\n    isFlag: true,\n    argTypeName: 'boolean',\n};\n/**\n * flag that indicates when forking, the parent's rel8ns should be cloned.\n */\nexport const PARAM_INFO_CLONE_REL8NS: RCLIParamInfo = {\n    name: 'clone-rel8ns',\n    isFlag: true,\n    argTypeName: 'boolean',\n};\n\n/**\n * json string for data key(s) to rename\n */\nexport const PARAM_INFO_DATA_TO_RENAME: RCLIParamInfo = {\n    name: 'data-to-rename',\n    argTypeName: 'string',\n    synonyms: ['rename-data'],\n};\n/**\n * json string for data key(s) to remove\n */\nexport const PARAM_INFO_DATA_TO_REMOVE: RCLIParamInfo = {\n    name: 'data-to-remove',\n    argTypeName: 'string',\n    synonyms: ['remove-data'],\n};\n/**\n * json string for data to add/patch when mut8ing\n */\nexport const PARAM_INFO_DATA_TO_ADD_OR_PATCH: RCLIParamInfo = {\n    name: 'data-to-add-or-patch',\n    argTypeName: 'string',\n    synonyms: ['+data', 'add-data', 'patch-data'],\n};\n/**\n * json string for rel8ns to add options object\n */\nexport const PARAM_INFO_REL8NS_TO_ADD: RCLIParamInfo = {\n    name: 'rel8ns-to-add',\n    argTypeName: 'string',\n    synonyms: ['+rel8ns', 'add-rel8ns', 'rel8ns-to-add-by-addr'],\n};\n/**\n * json string for rel8ns to remove options object\n */\nexport const PARAM_INFO_REL8NS_TO_REMOVE: RCLIParamInfo = {\n    name: 'rel8ns-to-remove',\n    argTypeName: 'string',\n    synonyms: ['-rel8ns', 'remove-rel8ns', 'rm-rel8ns', 'rel8ns-to-remove-by-addr'],\n};\n\n/**\n * used when creating comments with comment command\n */\nexport const PARAM_INFO_TEXT: RCLIParamInfo = {\n    name: 'text',\n    synonyms: ['txt', 'message', 'm', 'msg'],\n    argTypeName: 'string',\n};\n\n// #endregion ibgib params\n\n/**\n * @todo\n * path to resolve the bootstrap ibgib.\n *\n * this can be used to use a specific file or a directory to use in\n * conjunction with the default bootstrap filename (bootstrap ibgib addr \"bootstrap^gib\").\n *\n * @see {@link BOOTSTRAP_IBGIB_ADDR}\n */\nexport const PARAM_INFO_BOOTSTRAP_PATH: RCLIParamInfo = {\n    name: 'bootstrap-path',\n    argTypeName: 'string',\n};\n\n/**\n * when using `--init`, this name will be used for the initialized space. if\n * this is not provided, the rcli will prompt the user for a space name.\n *\n * when using `--interactive`, this specifies space by name\n */\nexport const PARAM_INFO_SPACE_NAME: RCLIParamInfo = {\n    name: 'space-name',\n    argTypeName: 'string',\n    allowMultiple: false,\n};\n\n/**\n * when using `--interactive`, this specifies space by id\n * when b2tfs, this can specify the space to act on/look in.\n */\nexport const PARAM_INFO_SPACE_ID: RCLIParamInfo = {\n    name: 'space-id',\n    argTypeName: 'string',\n    allowMultiple: false,\n};\n\n/**\n * space id used to initialize the metaspace's local user space.\n *\n * note that this is not the id of the actual metaspace (which doesn't have an\n * id) but rather points to the local space that the metaspace will use.\n *\n * using this to differentiate from just bare --space-id which is used in\n * various commands.\n */\nexport const PARAM_INFO_LOCAL_SPACE_ID: RCLIParamInfo = {\n    name: 'local-space-id',\n    argTypeName: 'string',\n    synonyms: ['context-space-id'],\n    allowMultiple: false,\n};\n\n/**\n * space name used to initialize the metaspace's local user space.\n *\n * note that this is not the name of the actual metaspace (which doesn't have an\n * name) but rather points to the local space that the metaspace will use.\n *\n * using this to differentiate from just bare --name which is used in\n * various commands.\n */\nexport const PARAM_INFO_LOCAL_SPACE_NAME: RCLIParamInfo = {\n    name: 'local-space-name',\n    argTypeName: 'string',\n    synonyms: ['context-space-name'],\n    allowMultiple: false,\n};\n\n/**\n * space id used to identify an outer space.\n *\n * for now, `allowMultiple` is false. this is because i'm simplifying the\n * process of syncing to artificially restrict to one outer (sync) space. in the\n * future, this should be able to synchronize among more than 2 spaces.\n */\nexport const PARAM_INFO_OUTER_SPACE_ID: RCLIParamInfo = {\n    name: 'outer-space-id',\n    argTypeName: 'string',\n    synonyms: ['sync-space-id', 'remote-id'],\n    allowMultiple: false,\n};\n\n/**\n * space name used to initialize the metaspace's local user space.\n *\n * note that this is not the name of the actual metaspace (which doesn't have an\n * name) but rather points to the local space that the metaspace will use.\n *\n * using this to differentiate from just bare --name which is used in\n * various commands.\n */\nexport const PARAM_INFO_OUTER_SPACE_NAME: RCLIParamInfo = {\n    name: 'outer-space-name',\n    argTypeName: 'string',\n    synonyms: ['sync-space-name', 'remote-name', 'remote'],\n    allowMultiple: false,\n};\n\n/**\n * specify an app id for a cmd\n */\nexport const PARAM_INFO_APP_ID: RCLIParamInfo = {\n    name: 'app-id',\n    argTypeName: 'string',\n    allowMultiple: false,\n};\n\n// commenting this out because I'm just going to put all of this into a \"details\"\n// file with a shape that contains the information. the point is to consume with\n// something like `ibgib --sync --add --input-file=space-details.json`\n// will default to the default local user space\n/**\n * only value atow (02/2024)\n * 'sync'\n *\n * in the future, we may have...\n *\n * * 'push' space\n *   * don't worry about timelines with multiple branching paths, it's\n *     last-one-wins\n *   * similar to a dendrite?\n * * 'connector' space\n *   * acts as a proxy that connects to another outerspace.\n *   * provides a layer of indirection\n *   * similar to an axon?\n * * something else...\n *   * the point is that we're communicating from a local, relatively fast space\n *     to a foreign, relatively latent space.\n */\nexport const PARAM_INFO_SPACE_TYPE: RCLIParamInfo = {\n    name: 'space-type',\n    argTypeName: 'string',\n    synonyms: [],\n    allowMultiple: false,\n    description: 'specifies the broad category of a space, i.e., how it functions. atow this can be \"user\", \"outer\", \"inner\"',\n};\n\n/**\n * arg to specify a space subtype (concrete implementation)\n *\n * atow (02/2024), valid values:\n *\n * 'aws-dynamodb'\n *\n * @see {@link SpaceSubtype}\n *\n * ## intent\n *\n * when we sync with a cloud outerspace (this is similar to a remote node or\n * network drive), this specifies the sync subtype (adapter) to use.\n */\nexport const PARAM_INFO_SPACE_SUBTYPE: RCLIParamInfo = {\n    name: 'space-subtype',\n    argTypeName: 'string',\n    synonyms: [],\n    allowMultiple: false,\n};\n\n/**\n * atow (02/2024) only 'password' is implemented.\n */\nexport const PARAM_INFO_SECRET_TYPE: RCLIParamInfo = {\n    name: 'secret-type',\n    argTypeName: 'string',\n    synonyms: [],\n    allowMultiple: false,\n    description: `Specifies the type of secret. ATOW (02/2024) this is only 'password'.`\n};\n\n/**\n * for selecting a secret via the name. if more than one secret has the same name, this\n * will not be enough\n */\nexport const PARAM_INFO_SECRET_NAME: RCLIParamInfo = {\n    name: 'secret-name',\n    argTypeName: 'string',\n    synonyms: [],\n    allowMultiple: false,\n    description: `Specifies the name of secret.`\n};\n/**\n * for reading a secret from a file instead of prompting the user.\n */\nexport const PARAM_INFO_SECRET_INPUT_PATH: RCLIParamInfo = {\n    name: 'secret-input-path',\n    argTypeName: 'string',\n    synonyms: ['secret-path', 'secret-input', 'secret-file'],\n    allowMultiple: false,\n    description: `Specifies the path to a secret's contents that avoids needing to prompt for the secret.`\n};\n\n/**\n * making this for encryption method, but right now it seems like i can just\n * reuse it for others as well without worrying too much about overlap.\n *\n * atow (02/2024) only 'encrypt-gib' for encryption is implemented.\n */\nexport const PARAM_INFO_METHOD: RCLIParamInfo = {\n    name: 'method',\n    argTypeName: 'string',\n    synonyms: ['encryption-method'],\n    allowMultiple: false,\n    description: `Specifies a method. ATOW (02/2024) this is only for encryption, and specifically one value: 'encrypt-gib'.`\n};\n\n/**\n * name specifier for encryption (configuration) ibgib. use this for specifying\n * an encryption configuration to be associated with an operation.\n */\nexport const PARAM_INFO_ENCRYPTION_NAME: RCLIParamInfo = {\n    name: 'encryption-name',\n    argTypeName: 'string',\n    synonyms: [],\n    allowMultiple: false,\n    description: `name specifier for encryption (configuration) ibgib. use this for specifying an encryption configuration to be associated with an operation.`,\n};\n\n/**\n * flag to indicate if, e.g. when getting an ibgib, we want to get the latest in\n * the timeline.\n */\nexport const PARAM_INFO_LATEST: RCLIParamInfo = {\n    name: 'latest',\n    argTypeName: 'boolean',\n    synonyms: ['latest-only', 'live'],\n    isFlag: true,\n};\n\n/**\n * flag to indicate to use an aws-dynamodb sync space\n */\nexport const PARAM_INFO_AWS_DYNAMODB_SYNC_SPACE: RCLIParamInfo = {\n    name: 'aws-dynamodb',\n    argTypeName: 'boolean',\n    synonyms: ['aws-dynamodb-s3'],\n    isFlag: true,\n    description: 'flag to indicate the aws dynamodb sync space is selected. this also uses s3 for binaries/large ibgibs.',\n};\n\n/**\n * @todo\n * when creating an ibgib, if we want to make it private, i.e. encrypt,\n * use this flag\n *\n * should be used in conjunction with data-path/data-string, output-path\n */\nexport const PARAM_INFO_PRIVATE: RCLIParamInfo = {\n    name: 'private',\n    isFlag: true,\n    argTypeName: 'boolean',\n};\n\n/**\n * create a temporary in-memory space for ibgibs.\n * i.e., don't store anything on disk.\n */\nexport const PARAM_INFO_IN_MEMORY: RCLIParamInfo = {\n    name: 'in-memory',\n    isFlag: true,\n    argTypeName: 'boolean',\n};\n\n/**\n * if true, start a repl.\n */\nexport const PARAM_INFO_INTERACTIVE: RCLIParamInfo = {\n    name: 'interactive',\n    isFlag: true,\n    argTypeName: 'boolean',\n    synonyms: ['repl'],\n};\n\n/**\n * specify encoding for a non-binary file.\n *\n * @see {@link PARAM_INFO_BINARY}\n */\nexport const PARAM_INFO_FILE_ENCODING: RCLIParamInfo = {\n    name: 'file-encoding',\n    argTypeName: 'string',\n    synonyms: ['encoding', 'text-encoding'],\n};\n\n/**\n * flag to indicate if pretty print\n */\nexport const PARAM_INFO_PRETTY: RCLIParamInfo = {\n    name: 'pretty',\n    description: 'flag to indicate if pretty print output',\n    argTypeName: 'boolean',\n    synonyms: ['pretty-print'],\n    isFlag: true,\n};\n\n/**\n * flag to indicate if verbose wordy lots of stuff\n */\nexport const PARAM_INFO_VERBOSE: RCLIParamInfo = {\n    name: 'verbose',\n    description: 'flag to indicate if verbose wordy lots of stuff',\n    argTypeName: 'boolean',\n    synonyms: [],\n    isFlag: true,\n};\n\n/**\n * flag to indicate if eligible confirm(s) are auto-answered as \"yes\".\n */\nexport const PARAM_INFO_YES: RCLIParamInfo = {\n    name: 'yes',\n    description: 'flag to indicate if eligible confirm(s) are auto-answered as \"yes\"',\n    argTypeName: 'boolean',\n    synonyms: ['auto-yes'],\n    isFlag: true,\n};\n\n/**\n * used when creating new ibgibs.\n *\n * ## driving use case\n *\n * creating a new SecretIbGib_V1, but really I should have this is more\n * commands.\n */\nexport const PARAM_INFO_DESCRIPTION: RCLIParamInfo = {\n    name: 'description',\n    synonyms: ['desc'],\n    argTypeName: 'string',\n    description: 'It\\'s a description...self-explanatory really.',\n};\n\n/**\n * used when creating new ibgibs.\n *\n * ## driving use case\n *\n * creating a new SecretIbGib_V1, but really I should have this is more\n * commands.\n */\nexport const PARAM_INFO_HINT: RCLIParamInfo = {\n    name: 'hint',\n    synonyms: [],\n    argTypeName: 'string',\n    description: 'Hints are used in things like secrets, where you want to provide some minor context.',\n};\n\n/**\n * if true, the command should treat a file/whatever as being binary.\n *\n * @see {@link PARAM_INFO_REIFY_FILE}\n */\nexport const PARAM_INFO_BINARY: RCLIParamInfo = {\n    name: 'binary',\n    isFlag: true,\n    argTypeName: 'boolean',\n    synonyms: ['is-binary'],\n};\n\n/**\n * boolean flag to indicate the output/whatever is a witness.\n *\n * i'm making this for * {@link PARAM_INFO_GENERATE_SOURCE_FILE}\n */\nexport const PARAM_INFO_WITNESS: RCLIParamInfo = {\n    name: 'witness',\n    isFlag: true,\n    argTypeName: 'boolean',\n    synonyms: ['is-witness', 'basic-witness'],\n};\n\n/**\n * boolean flag to indicate the output/whatever is specifically an app witness.\n *\n * i'm making this for * {@link PARAM_INFO_GENERATE_SOURCE_FILE}\n */\nexport const PARAM_INFO_APP: RCLIParamInfo = {\n    name: 'app',\n    isFlag: true,\n    argTypeName: 'boolean',\n    synonyms: ['is-app'],\n};\n\n/**\n * boolean flag to indicate the output/whatever is specifically a robbot\n * witness.\n *\n * i'm making this for * {@link PARAM_INFO_GENERATE_SOURCE_FILE}\n */\nexport const PARAM_INFO_ROBBOT: RCLIParamInfo = {\n    name: 'robbot',\n    isFlag: true,\n    argTypeName: 'boolean',\n    synonyms: ['is-robbot'],\n};\n\n/**\n * if true, skip doing respec unit tests\n *\n * ## use case\n *\n * i'm making this for * {@link PARAM_INFO_GENERATE_SOURCE_FILE}\n */\nexport const PARAM_INFO_NO_RESPEC: RCLIParamInfo = {\n    name: 'no-respec',\n    isFlag: true,\n    argTypeName: 'boolean',\n    synonyms: ['no-spec', 'no-specs', 'no-test', 'no-tests'],\n};\n\n/**\n * flag to indicate if we want to apply during some command.\n *\n * kind of the opposite of a dry-run.\n *\n * ## intent\n *\n * I'm making this for B2tFS diff. so when this flag is true, the diff should be\n * applied.\n */\nexport const PARAM_INFO_APPLY: RCLIParamInfo = {\n    name: 'apply',\n    argTypeName: 'boolean',\n    synonyms: ['apply-cmd', 'apply-diff', 'apply-changes'],\n    isFlag: true,\n};\n\n/**\n * flag to indicate if we want to keep output to a minimum.\n *\n * the opposite of verbose.\n *\n * ## intent\n *\n * I'm making this for B2tFS diff. so when this flag is true, the diff should\n * just show files/folders changed.\n */\nexport const PARAM_INFO_BRIEF: RCLIParamInfo = {\n    name: 'brief',\n    argTypeName: 'boolean',\n    synonyms: [],\n    isFlag: true,\n};\n\n/**\n * flag to indicate if we want to add during some command.\n *\n * ## intent\n *\n * I'm making this for B2tFS branch. so when this flag is true, the cmd should\n * be adding a branh.\n */\nexport const PARAM_INFO_ADD: RCLIParamInfo = {\n    name: 'add',\n    description: 'adds something...not necessarily new, yada yada, todo here.',\n    argTypeName: 'boolean',\n    synonyms: [],\n    isFlag: true,\n};\n\n/**\n * flag to indicate if we want to only do the fs (files/folders).\n *\n * ## intent\n *\n * I'm making this for B2tFS branch command similar to an export. so when this\n * flag is true, the cmd should only be snapshotting the files/folders into the\n * target folder and not copying the .ibgib folder.\n */\nexport const PARAM_INFO_FS_ONLY: RCLIParamInfo = {\n    name: 'fs-only',\n    description: 'only do the fs-side of things (not the ibgibs).',\n    argTypeName: 'boolean',\n    synonyms: ['files-only', 'files'],\n    isFlag: true,\n};\n\n/**\n * ## driving intent\n *\n * import - force import even if existing timeline\n */\nexport const PARAM_INFO_FORCE: RCLIParamInfo = {\n    name: 'force',\n    description: 'override some setting',\n    argTypeName: 'boolean',\n    synonyms: [],\n    isFlag: true,\n};\n\n/**\n * ## driving intent\n *\n * add/mut8 secret password\n */\nexport const PARAM_INFO_PROMPT: RCLIParamInfo = {\n    name: 'prompt',\n    description: 'prompt for some data, e.g., if entering a password',\n    argTypeName: 'boolean',\n    synonyms: ['prompt-me', 'ask', 'ask-me'],\n    isFlag: true,\n};\n\nexport const PARAM_INFO_MOVE: RCLIParamInfo = {\n    name: 'move',\n    argTypeName: 'string',\n    synonyms: ['mv'],\n    isFlag: true,\n    description: 'Common use case is to move something. This is being created specifically for moving a branch.',\n};\n\n/**\n * customize the imported common param infos here:\n * * add documentation/description specific to this project's use case\n */\nconst CUSTOMIZED_COMMON_PARAM_INFOS = clone(COMMON_PARAM_INFOS) as RCLIParamInfo[];\nCUSTOMIZED_COMMON_PARAM_INFOS.forEach(x => {\n    // for example, this is the code atow (11/2024) for @ibgib/ibgib rcli init\n    //     if (x.name === PARAM_INFO_NAME.name) {\n    //         const gSrcDesc = `PARAM_INFO_GENERATE_SOURCE_FILE\n    // * name will be used as folder generated, as well as generated files, ibgib/data/rel8n/witness/class types.\n    // * will automatically be converted to various casings\n    //   (camelCase,PascalCase,hyphenated-case,snake_case, etc.) depending on where name is used.\n    //   * e.g. camelCase for params/vars, PascalCase for class names, hyphenated-case for filenames, etc.\n    // `;\n    //         x.description += gSrcDesc;\n    //     }\n});\n\n/**\n * Array of all parameters this library's RCLI supports.\n */\nexport const PARAM_INFOS: RCLIParamInfo[] = [\n    ...CUSTOMIZED_COMMON_PARAM_INFOS,\n    // atow... 11/2023\n    // PARAM_INFO_BARE,\n    // PARAM_INFO_HELP,\n    // PARAM_INFO_DRY_RUN,\n    // PARAM_INFO_DATA_PATH,\n    // PARAM_INFO_INPUT_PATH,\n    // PARAM_INFO_OUTPUT_PATH,\n    // PARAM_INFO_DATA_STRING,\n    // PARAM_INFO_DATA_INTEGER,\n    // PARAM_INFO_DATA_BOOLEAN,\n    // PARAM_INFO_NAME,\n    //  * i'm adding this for {@link PARAM_INFO_GENERATE_SOURCE_FILE}, but should be\n    //  * reusable. used for when you have a name. need to move this into the base lib\n    //  * at some point.\n\n    // ...ENCRYPT_GIB_PARAM_INFOS, // also includes common constants from helper-gib\n    PARAM_INFO_ENCRYPT,\n    PARAM_INFO_DECRYPT,\n    // PARAM_INFO_STRENGTH,\n    PARAM_INFO_SALT,\n    PARAM_INFO_INDEXING_MODE,\n    PARAM_INFO_BLOCKMODE_FLAG,\n    PARAM_INFO_BLOCKMODE_BLOCK_SIZE,\n    PARAM_INFO_BLOCKMODE_NUM_OF_PASSES,\n    PARAM_INFO_HASH_ALGORITHM,\n    PARAM_INFO_SALT_STRATEGY,\n    PARAM_INFO_INITIAL_RECURSIONS,\n    PARAM_INFO_RECURSIONS_PER_HASH,\n\n\n    // command flags\n    PARAM_INFO_INIT,\n    PARAM_INFO_FORK,\n    PARAM_INFO_MUT8,\n    PARAM_INFO_REL8,\n    PARAM_INFO_QUIT,\n    PARAM_INFO_CWD,\n    PARAM_INFO_ADD_COMMENT,\n    PARAM_INFO_SECRET,\n    PARAM_INFO_ENCRYPTION,\n    PARAM_INFO_SYNC,\n    PARAM_INFO_VERSION,\n    PARAM_INFO_LIST_CHAT,\n    PARAM_INFO_CREATE_STONE,\n    PARAM_INFO_REIFY_FILE,\n    PARAM_INFO_GENERATE_SOURCE_FILE,\n    PARAM_INFO_INFO,\n    PARAM_INFO_EXPORT,\n    PARAM_INFO_IMPORT,\n    PARAM_INFO_SPACE,\n\n    // B2tFS\n    PARAM_INFO_B2TFS_INIT, // command\n    PARAM_INFO_B2TFS_BRANCH, // command\n    PARAM_INFO_B2TFS_ACTIVATE_BRANCH, // command\n    PARAM_INFO_B2TFS_INFO, // command\n    PARAM_INFO_B2TFS_DIFF, // command\n    PARAM_INFO_B2TFS_SYNC, // command\n\n    // other flags\n    PARAM_INFO_IN_MEMORY,\n    PARAM_INFO_INTERACTIVE,\n    PARAM_INFO_BINARY,\n    PARAM_INFO_WITNESS,\n    PARAM_INFO_APP,\n    PARAM_INFO_NO_RESPEC,\n    PARAM_INFO_APPLY,\n    PARAM_INFO_BRIEF,\n    PARAM_INFO_ADD,\n    PARAM_INFO_FS_ONLY,\n    PARAM_INFO_FORCE,\n    PARAM_INFO_PROMPT,\n    PARAM_INFO_MOVE,\n\n    // ibgib\n    PARAM_INFO_SRC_NAME,\n    PARAM_INFO_SRC_ADDR,\n    PARAM_INFO_DEST_ADDR,\n    PARAM_INFO_IB,\n    PARAM_INFO_ADD_ADDR,\n    PARAM_INFO_RM_ADDR,\n    PARAM_INFO_TEXT,\n    PARAM_INFO_SPACE_NAME,\n    PARAM_INFO_SPACE_ID,\n    PARAM_INFO_LOCAL_SPACE_NAME,\n    PARAM_INFO_LOCAL_SPACE_ID,\n    PARAM_INFO_OUTER_SPACE_NAME,\n    PARAM_INFO_OUTER_SPACE_ID,\n    PARAM_INFO_APP_ID,\n    PARAM_INFO_SPACE_TYPE,\n    PARAM_INFO_SPACE_SUBTYPE,\n    PARAM_INFO_SECRET_TYPE,\n    PARAM_INFO_SECRET_NAME,\n    PARAM_INFO_SECRET_INPUT_PATH,\n    PARAM_INFO_METHOD,\n    PARAM_INFO_ENCRYPTION_NAME,\n    PARAM_INFO_TJP,\n    PARAM_INFO_SPECIAL,\n\n    // IBGIB FLAGS\n    PARAM_INFO_CLONE_DATA,\n    PARAM_INFO_CLONE_REL8NS,\n    PARAM_INFO_DATA_TO_RENAME,\n    PARAM_INFO_DATA_TO_REMOVE,\n    PARAM_INFO_DATA_TO_ADD_OR_PATCH,\n    PARAM_INFO_REL8NS_TO_ADD,\n    PARAM_INFO_REL8NS_TO_REMOVE,\n    PARAM_INFO_LATEST,\n    PARAM_INFO_AWS_DYNAMODB_SYNC_SPACE,\n\n    // other\n    PARAM_INFO_SRC_ID,\n    PARAM_INFO_DEST_ID,\n    PARAM_INFO_DEST_NAME,\n    PARAM_INFO_BOOTSTRAP_PATH,\n    PARAM_INFO_FILE_ENCODING,\n    PARAM_INFO_PRETTY,\n    PARAM_INFO_VERBOSE,\n    PARAM_INFO_YES,\n    PARAM_INFO_DESCRIPTION,\n    PARAM_INFO_HINT,\n\n    // meta\n    PARAM_INFO_INSPECT,\n];\n\n// #endregion param info related\n\n/**\n * if the user says `spaceId=${DEFAULT_LOCAL_USER_SPACE_VAR}` in a command parameter, then\n * the default local user space will be used.\n */\nexport const DEFAULT_LOCAL_USER_SPACE_VAR = '.';\n", "import thisHtml from './input.html';\nimport thisCss from './input.css';\nimport stylesCss from '../../../styles.css';\nimport rootCss from '../../../root.css';\n\nimport { delay, extractErrorMsg, pretty } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { IbGib_V1 } from \"@ibgib/ts-gib/dist/V1/types.mjs\";\nimport { IbGibAddr, TransformResult } from \"@ibgib/ts-gib/dist/types.mjs\";\nimport { ROOT } from \"@ibgib/ts-gib/dist/V1/constants.mjs\";\nimport { MetaspaceService } from \"@ibgib/core-gib/dist/witness/space/metaspace/metaspace-types.mjs\";\nimport { CommentIbGib_V1 } from \"@ibgib/core-gib/dist/common/comment/comment-types.mjs\";\nimport { createCommentIbGib } from \"@ibgib/core-gib/dist/common/comment/comment-helper.mjs\";\nimport { appendToTimeline } from \"@ibgib/core-gib/dist/timeline/timeline-api.mjs\";\nimport { getDeterministicColorInfo, getGlobalMetaspace_waitIfNeeded, } from \"@ibgib/web-gib/dist/helpers.mjs\";\nimport { IbGibDynamicComponentInstanceBase, IbGibDynamicComponentMetaBase } from \"@ibgib/web-gib/dist/ui/component/ibgib-dynamic-component-bases.mjs\";\nimport { IbGibDynamicComponentInstance, IbGibDynamicComponentInstanceInitOpts, } from \"@ibgib/web-gib/dist/ui/component/component-types.mjs\";\nimport { getAddlMetadataTextForAgentText } from '@ibgib/web-gib/dist/witness/agent/agent-helpers.mjs';\nimport { storageGet, } from \"@ibgib/web-gib/dist/storage/storage-helpers.web.mjs\";\nimport { promptForAPIKey, updateAPIKeyInStorage } from '@ibgib/web-gib/dist/helpers.web.mjs';\n\nimport { GLOBAL_LOG_A_LOT, ARMY_STORE, BEE_KEY, BLANK_GIB_DB_NAME, } from \"../../../constants.mjs\";\nimport { InputInfo } from \"./input-types.mjs\";\nimport { CHAT_WITH_AGENT_NEED_API_KEY } from '../../../witness/app/blank-canvas/blank-canvas-constants.mjs';\nimport { getComponentCtorArg } from '../../../helpers.web.mjs';\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\nexport const INPUT_COMPONENT_NAME: string = 'ibgib-input';\n\nexport class InputComponentMeta extends IbGibDynamicComponentMetaBase {\n    protected override lc: string = `[${InputComponentMeta.name}]`;\n\n    /**\n     * temporary regexp path for our initial dev. this component will become\n     * attached to actual ib^gib addrs\n     */\n    routeRegExp?: RegExp = new RegExp(INPUT_COMPONENT_NAME);\n\n    componentName: string = INPUT_COMPONENT_NAME;\n\n    constructor() {\n        super(getComponentCtorArg());\n        customElements.define(this.componentName, InputComponentInstance);\n    }\n\n    /**\n     * for a input, we don't have any additional info in the path.\n     */\n    async createInstance({\n        path,\n        ibGibAddr\n    }: {\n        path: string;\n        ibGibAddr: IbGibAddr;\n    }): Promise<IbGibDynamicComponentInstance> {\n        const lc = `${this.lc}[${this.createInstance.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n            const component = document.createElement(this.componentName) as InputComponentInstance;\n            await component.initialize({\n                ibGibAddr,\n                meta: this,\n                html: thisHtml,\n                css: [rootCss, stylesCss, thisCss],\n            });\n            return component;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n}\n\ninterface InputElements {\n    componentEl: HTMLElement;\n    inputTextEl: HTMLTextAreaElement;\n    inputSendBtnEl: HTMLButtonElement;\n}\n\nconst DEFAULT_INPUT_INFO: InputInfo = {\n\n}\n\nexport class InputComponentInstance\n    extends IbGibDynamicComponentInstanceBase<IbGib_V1, InputElements>\n    implements IbGibDynamicComponentInstance<IbGib_V1, InputElements> {\n    protected override lc: string = `[${InputComponentInstance.name}]`;\n\n    metaspace: MetaspaceService | undefined;\n\n    inputInfo: InputInfo = DEFAULT_INPUT_INFO;\n\n    private _apiKey: string = '';\n    private _submitting = false;\n    private _queuedSubmitTexts: string[] = [];\n\n    constructor() {\n        super();\n    }\n\n    override async initialize(opts: IbGibDynamicComponentInstanceInitOpts): Promise<void> {\n        const lc = `${this.lc}[${this.initialize.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n            await super.initialize(opts);\n\n            this.metaspace = await getGlobalMetaspace_waitIfNeeded();\n            // await this.loadIbGib();\n            // await super.subscribeToIbGibUpdates();\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    override async created(): Promise<void> {\n        const lc = `${this.lc}[${this.created.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n\n            // const { meta, htmlPath, scriptPaths, cssPaths } = opts;\n\n            await this.initUI();\n\n            await this.renderUI();\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private async initUI(): Promise<void> {\n        const lc = `${this.lc}[${this.initUI.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n\n            const shadowRoot = this.shadowRoot;\n\n            if (!shadowRoot) { throw new Error(`(UNEXPECTED) shadowRoot falsy? (E: genuuid)`); }\n\n            const componentEl = shadowRoot.getElementById('input-component') as HTMLElement;\n            if (!componentEl) { throw new Error(`(UNEXPECTED) componentEl not found in shadowRoot? (E: genuuid)`); }\n\n            const inputTextEl = shadowRoot.getElementById('input-text') as HTMLTextAreaElement;\n            if (!inputTextEl) { throw new Error(`(UNEXPECTED) inputTextEl not found in shadowRoot? (E: genuuid)`); }\n\n            const inputSendBtnEl = shadowRoot.getElementById('input-send-btn') as HTMLButtonElement;\n            if (!inputSendBtnEl) { throw new Error(`(UNEXPECTED) inputSendBtnEl not found in shadowRoot? (E: genuuid)`); }\n\n            this.elements = {\n                componentEl,\n                inputTextEl,\n                inputSendBtnEl,\n            };\n\n            // inputSendBtnEl.addEventListener('click', this.handleSubmit);\n            inputSendBtnEl.addEventListener('click', async () => {\n                await this.handleSubmit();\n            });\n\n            inputTextEl.addEventListener('keydown', async (event) => {\n                if (event.key === 'Enter' && event.ctrlKey === true) {\n                    event.preventDefault(); // Prevent default behavior (new line)\n                    await this.handleSubmit();\n                }\n            });\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private async handleKeydown(event: any): Promise<void> {\n    }\n\n    /**\n     * rerender\n     */\n    protected async renderUI(): Promise<void> {\n        const lc = `${this.lc}[${this.renderUI.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n\n            if (!this.shadowRoot) { throw new Error(`(UNEXPECTED) this.shadowRoot falsy? (E: genuuid)`); }\n            if (!this.elements) {\n                console.warn(`${lc} (UNEXPECTED) tried to render but haven't initialized elements? (W: genuuid)`);\n                return; /* <<<< returns early */\n            }\n\n            // const color = getDeterministicColorInfo({\n            //     ibGib: this.inputInfo.contextProxyIbGib?.ibGib,\n            // });\n            // this.style.setProperty('--ibgib-border-color', color);\n            const {\n                punctiliarColor,\n                punctiliarColorTranslucent,\n                tjpColor,\n                tjpColorTranslucent,\n                errorMsg\n            } = getDeterministicColorInfo({\n                ibGib: this.inputInfo.contextProxyIbGib?.ibGib,\n                translucentAlpha: 10\n            });\n            if (!errorMsg) {\n                this.style.setProperty('--ibgib-color', punctiliarColor);\n                this.style.setProperty('--ibgib-color-translucent', punctiliarColor);\n                this.style.setProperty('--tjp-color', tjpColor ?? punctiliarColor);\n                this.style.setProperty('--tjp-color-translucent', tjpColorTranslucent ?? punctiliarColorTranslucent);\n            } else {\n                // don't set anything\n                console.error(`${lc} ${errorMsg} (E: 65e0d330d029c1fe39f3d6280dda3725)`);\n            }\n\n            const {\n                componentEl,\n                inputSendBtnEl,\n                inputTextEl,\n            } = this.elements;\n\n            const { agent, contextProxyIbGib } = this.inputInfo;\n\n            if (agent || contextProxyIbGib?.ibGib) {\n                inputTextEl.ariaPlaceholder = this.inputInfo.placeholderText ?? '';\n                inputTextEl.placeholder = this.inputInfo.placeholderText ?? '';\n                inputTextEl.removeAttribute('readonly');\n                // inputTextEl.readOnly = false;\n                // inputTextEl.ariaReadOnly = false.toString();\n            } else {\n                inputTextEl.ariaPlaceholder = 'loading...';\n                inputTextEl.placeholder = 'loading...';\n                inputTextEl.textContent = '';\n                inputTextEl.setAttribute('readonly', 'true');\n                // inputTextEl.readOnly = true;\n                // inputTextEl.ariaReadOnly = true.toString();\n            }\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    override async disconnected(): Promise<void> {\n        const lc = `${this.lc}[${this.disconnected.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n            // no action atow\n\n            if (!this.elements) { throw new Error(`(UNEXPECTED) this.elements falsy? (E: 3768c106edf32adc8eedee1b5adc6625)`); }\n\n            // unhook events...necessary?\n            // const { inputSendBtnEl, inputTextEl } = this.elements;\n            // inputSendBtnEl.removeEventListener('click', this.handleSubmit);\n            // inputTextEl.removeEventListener('keydown', this.handleKeydown);\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * adds a comment to the current context ibgib.\n     *\n     * todo: also submit pic(s)\n     */\n    private async handleSubmit(): Promise<void> {\n        const lc = `${this.lc}[${this.handleSubmit.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 6e5d020950ab3c161c3b023772af1a25)`); }\n\n            // #region init & validation\n\n            if (!this.elements) { throw new Error(`(UNEXPECTED) this.elements falsy? (E: genuuid)`); }\n            const { inputTextEl, } = this.elements;\n            // const inputText = inputTextEl.textContent?.trim() ?? '';\n            const inputText = inputTextEl.value?.trim() ?? '';\n            if (!inputText) {\n                console.warn(`${lc} no text to submit. returning early. (W: genuuid)`);\n                return; /* <<<< returns early */\n            }\n            inputTextEl.value = '';\n            const { agent, contextProxyIbGib, spaceId, } = this.inputInfo;\n            if (!contextProxyIbGib && !agent) { throw new Error(`(UNEXPECTED) both contextProxyIbGib AND agent falsy? (E: bb4cb430269b64e07a532e5ae2df5c25)`); }\n            const { metaspace } = this;\n            if (!metaspace) { throw new Error(`(UNEXPECTED) metaspace falsy? (E: 18b602faa9b1a52edef603480fa5ce25)`); }\n\n            // #endregion init & validation\n            if (!this._apiKey) {\n                this._apiKey = await storageGet({\n                    dbName: BLANK_GIB_DB_NAME, storeName: ARMY_STORE,\n                    key: BEE_KEY,\n                }) ?? '';\n            }\n            if (!this._apiKey) {\n                await this.doPromptForAPIKey();\n                // this reloads if they enter the API key. If they don't enter\n                // it, then we just leave it there until they submit again and\n                // are prompted again. so return early. not the best but not the\n                // worst workflow\n                return; /* <<<< returns early */\n            }\n\n            // first determine if we're already submitting.\n            this._queuedSubmitTexts.push(inputText);\n            if (this._submitting) {\n                console.warn(`${lc} already submitting. queueing text. (W: genuuid)`);\n                this._queuedSubmitTexts.push(inputText);\n                return; /* <<<< returns early */\n            }\n\n            const space = await metaspace.getLocalUserSpace({\n                localSpaceId: spaceId, lock: false\n            });\n            if (contextProxyIbGib) {\n                if (!contextProxyIbGib.ibGib) {\n                    throw new Error(`(UNEXPECTED) contextProxyIbGib truthy but contextProxyIbGib.ibGib falsy? (E: c52bdfa29268be0fb968f16940723525)`);\n                }\n                this._submitting = true;\n                do {\n                    const text = this._queuedSubmitTexts.shift();\n                    if (!text) { continue; }\n\n                    // create the comment ibgib\n                    /** atow (04/2025) adds a timestampInTicks and textSrc */\n                    const addlMetadataText = getAddlMetadataTextForAgentText({\n                        textSrc: 'human',\n                    });\n                    const resCreateComment: TransformResult<CommentIbGib_V1> =\n                        await createCommentIbGib({\n                            text,\n                            addlMetadataText,\n                            saveInSpace: true,\n                            space,\n                        });\n                    const commentIbGib = resCreateComment.newIbGib;\n                    await metaspace.registerNewIbGib({ ibGib: commentIbGib, space, });\n\n                    // rel8 to our current context\n                    await appendToTimeline({\n                        timeline: contextProxyIbGib.ibGib,\n                        metaspace,\n                        rel8nInfos: [{ rel8nName: 'comment', ibGibs: [commentIbGib], }],\n                        space,\n                    });\n\n                } while (this._queuedSubmitTexts.length > 0);\n            } else {\n                // submitting to agent\n                if (!agent) { throw new Error(`(UNEXPECTED) agent falsy? at this point should be logically guaranteed? (E: 94b982c0bbeb133a52c2bee537404f25)`); }\n                await this.handleSubmit_toAgent({\n                    texts: this._queuedSubmitTexts.concat(),\n                });\n                this._queuedSubmitTexts = [];\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n            this._submitting = false;\n        }\n    }\n\n    private async handleSubmit_toAgent({\n        texts,\n    }: {\n        texts: string[];\n    }): Promise<void> {\n        const lc = `[${this.handleSubmit_toAgent.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n\n            const { agent, } = this.inputInfo;\n\n            // first ensure our best to see if we have an api key already\n\n            const fnSubmitToAgent = async () => {\n                try {\n                    // Add to the primary agent's chat\n                    if (!agent) { throw new Error(`agent falsy. (E: genuuid)`); }\n                    if (logalot) { console.log(`Adding to agent chat: ${pretty(texts)} (I: genuuid)`); }\n                    await agent.addTexts({\n                        infos: texts.map(text => {\n                            return {\n                                textSrc: 'human',\n                                text,\n                                isSystem: text.startsWith('system: ')\n                            };\n                        }),\n                        // infos: [{\n                        //     textSrc: 'human',\n                        //     text,\n                        //     isSystem: text.startsWith('system: ') }\n                        // ],\n                    });\n                    // for (const text of texts) {\n                    //     await addToChatLogKluge({\n                    //         text,\n                    //         who: 'user',\n                    //         chatLog: undefined, // primary chat log for now...\n                    //         scrollAfter: true,\n                    //     });\n                    // }\n                    const _ = await agent.witness(ROOT);\n                } catch (error) {\n                    console.error(`error adding chat to agent (E: genuuid): ${extractErrorMsg(error)}`);\n                }\n            };\n\n            // if we have an apikey, submit the chat. else we'll have to\n            // do some work to get the user to enter an api key (and\n            // fund us!)\n            if (this._apiKey) {\n                await fnSubmitToAgent();\n            } else {\n                await this.doPromptForAPIKey();\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * ## notes\n     * changed this to \"do\" function name because I'm refactoring to an external\n     * function {@link promptForAPIKey}\n     */\n    private async doPromptForAPIKey(): Promise<void> {\n        const lc = `${this.lc}[${this.doPromptForAPIKey.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: b475d2686686ac016f0ea48ab51ef325)`); }\n\n            let resAPIKey = await promptForAPIKey({\n                msg: CHAT_WITH_AGENT_NEED_API_KEY,\n            });\n            if (resAPIKey === undefined) {\n                console.log(`${lc} user cancelled entering API key. (I: genuuid)`);\n                return; /* <<<< returns early */\n            }\n            this._apiKey = resAPIKey;\n            if (this._apiKey) {\n                await updateAPIKeyInStorage({\n                    dbName: BLANK_GIB_DB_NAME,\n                    storeName: ARMY_STORE,\n                    key: BEE_KEY,\n                    apiKey: this._apiKey,\n                    force: false\n                });\n            } else {\n                // clear it out b/c empty string?\n                // await updateAPIKeyInStorage({ apiKey: this._apiKey, force: true }); // clears it if empty string\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    // #region public api\n\n    public async setContextInfo({\n        info,\n    }: {\n        info: InputInfo,\n    }): Promise<void> {\n        const lc = `${this.lc}[${this.setContextInfo.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n\n            // edge case: don't want to change context in the middle of submitting.\n            while (this._submitting) {\n                if (logalot) { console.log(`${lc} still submitting. don't want to change context in the middle of submitting. (I: d14b2bb9704945be991db24903bf3625)`); }\n                await delay(50);\n            }\n\n            this.inputInfo = info;\n\n            // init agent to subscribe to events in the context?\n\n            await this.renderUI();\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    // #endregion public api\n}\n", "<div id=\"chronologys-component\" class=\"\">\n    <!-- have these both as panel-header just as a kluge to get the tabs to look\n    decent without bigger rewrite/investigation -->\n    <div id=\"chronologys-header\" class=\"chronologys-header panel-header\">\n        <span id=\"chronologys-header-busy-indicator\" class=\"busy-indicator spinning\" style=\"display:none\"\n            title=\"still busy...hold on a sec...\"><b>\u25D0</b></span>\n        <div id=\"chronologys-header-tabs\" class=\"chronologys-header-tabs panel-header\">\n            <!-- looks something like this atow when dynamically added -->\n            <!--\n            <span id=\"chronologys-tab-button-{addr}\" class=\"panel-tab-button active\" title=\"untitled\">\n                untitled\n            </span>\n            -->\n        </div>\n    </div>\n\n    <div id=\"chronologys-content\">\n\n        <!-- todo: insert chronologys-content depending on which tab is active -->\n        <!-- <canvas id=\"ibgib-canvas\" width=\"1000\" height=\"1000\"></canvas> -->\n\n    </div>\n\n    <div id=\"chronologys-footer\" class=\"chronologys-footer\">\n        <!-- <textarea id=\"chronologys-agent-input\" class=\"agent-input\" placeholder=\"loading...\" readonly></textarea>\n        <button id=\"chronologys-agent-input-send-btn\" class=\"send-btn\"><b>\u276F</b></button> -->\n    </div>\n</div>\n", ":host {\n    /* this is used for styling ibgib components for multi-view coordination, so\n     * that ibgib views that are looking at the same ibgib can be visibly shown\n     * as doing so. */\n    --ibgib-color: #ff00dd;\n    --ibgib-color-translucent: #ff00dd10;\n    --tjp-color: #00ffae;\n    --tjp-color-translucent: #00ffae10;\n    --close-tab-button-width: 20px;\n}\n\n#chronologys-component {\n    --footer-panel-background-color: var(--button-background-color);\n    --footer-panel-border-color: var(--button-border-color);\n    --footer-panel-border-radius: 4px;\n\n    /* debug add border style */\n    border-width: 2px;\n    border-color: var(--primary-border-color-dark);\n    border-style: solid;\n    border-radius: 2px;\n    padding: 1%;\n\n    display: flex;\n    flex-direction: column;\n    width: 100%;\n    height: 100%;\n    box-sizing: border-box;\n\n    #chronologys-header {\n        height: 5%;\n        overflow: hidden;\n        /* flex-shrink: initial; */\n\n        #chronologys-header-tabs {\n            overflow-x: auto;\n            width: 90%;\n            /* scrollbar-color: rgba(16, 237, 35, 0.241) rgb(28, 109, 239); */\n            scrollbar-width: thin;\n            scrollbar-gutter: stable;\n            margin-bottom: -1%;\n\n            /* .panel-tab-button.active {\n                border-color: var(--ibgib-border-color) !important;\n            } */\n\n            /* header tab \"button\" (span) that has a child span (close \"X\" button) */\n            span:has(span) {\n                padding-right: calc(var(--close-tab-button-width) * 1.35);\n            }\n        }\n\n        button {\n            width: auto;\n            height: 75%;\n            aspect-ratio: 1/1 !important;\n        }\n\n        button:hover {\n            border-width: 2px;\n            background-color: var(--button-hover-background-color);\n            color: var(--button-hover-text-color);\n            border-color: var(--button-hover-border-color);\n        }\n\n        .close-tab-button {\n            cursor: pointer;\n            box-sizing: border-box;\n            position: absolute;\n            top: 5px;\n            right: 5px;\n            background-color: rgba(255, 0, 0, 0.7);\n            color: white;\n            border: none;\n            border-radius: 50%;\n            width: var(--close-tab-button-width);\n            height: 20px;\n            font-size: 10px;\n            cursor: pointer;\n            display: flex;\n            align-items: center;\n            justify-content: center;\n            z-index: 1;\n            /* Ensure button is above content */\n        }\n\n        .close-tab-button:hover {\n            border-width: 3px;\n            background-color: #ff00cf;\n            color: var(--button-hover-text-color) !important;\n            border-color: var(--button-hover-border-color);\n            border-style: solid;\n        }\n    }\n\n    #chronologys-content {\n        height: 95%;\n        width: 100%;\n    }\n\n    #chronologys-footer {\n        display: none;\n    }\n}\n", "<div id=\"chronology-component\" class=\"\">\n    <!-- have these both as panel-header just as a kluge to get the tabs to look\n    decent without bigger rewrite/investigation -->\n    <div id=\"chronology-header\" class=\"chronology-header panel-header\">\n        <i><p id=\"chronology-text\">loading...</p></i>\n        <p id=\"chronology-description\">chronology description loading...</p>\n        <!-- <div id=\"chronology-header-tabs\" class=\"chronology-header-tabs panel-header\"> -->\n        <!-- looks something like this atow when dynamically added -->\n        <!--\n            <span id=\"chronology-tab-button-{addr}\" class=\"panel-tab-button active\" title=\"untitled\">\n                untitled\n            </span>\n            -->\n        <!-- </div> -->\n        <!-- <button id=\"chronology-header-add-btn\" class=\"tab-btn\">+</button> -->\n    </div>\n\n    <div id=\"chronology-content\">\n       <div id=\"chronology-content-items\">\n           <!-- this is where the individual items will be loaded -->\n       </div>\n    </div>\n\n    <div id=\"chronology-footer\" class=\"chronology-footer\">\n    </div>\n</div>\n", ":host {\n    /* this is used for styling ibgib components for multi-view coordination, so\n     * that ibgib views that are looking at the same ibgib can be visibly shown\n     * as doing so. */\n    --ibgib-color: #ff00dd;\n    --ibgib-color-translucent: #ff00dd10;\n    --tjp-color: #00ffae;\n    --tjp-color-translucent: #00ffae10;\n}\n\n/* Basic layout and styling for the chronology component */\n#chronology-component {\n    display: flex;\n    flex-direction: column;\n    align-items: stretch;\n    width: 100%;\n    height: 100%;\n    box-sizing: border-box;\n    /* Use consistent padding */\n    padding: 1%;\n    overflow-x: hidden;\n    overflow-y: auto;\n\n    /* ibgib styling */\n    border: var(--tjp-color) 5px solid;\n    box-shadow: 0 0 5px var(--tjp-color);\n    border-radius: 5px;\n\n    /* Optional: If using flexbox to control vertical alignment */\n    /* justify-content: center;  Align content vertically */\n\n\n    #chronology-header {\n        display: flex;\n        flex-direction: column;\n        font-size: smaller;\n\n        #chronology-name {\n            font-weight: bold;\n            /* font-size: larger; */\n            /* Use variables for spacing? */\n            /* margin-bottom: 0.5em; */\n        }\n\n        #chronology-description {\n            /* Respect newlines */\n            white-space: pre-wrap;\n            font-style: italic;\n        }\n\n        #chronology-description.collapsed {\n            display: none;\n        }\n    }\n\n    /* Styling for each item/section within the content.\n       make this a flexbox column to arrange the text and timestamp. */\n    #chronology-content {\n\n        section {\n            display: flex;\n            flex-direction: column;\n            /* light gray border */\n            border: 1px solid #cccccc;\n            /* small radius for rounded corners */\n            border-radius: 4px;\n            /* padding inside each section */\n            padding: 10px;\n            /* margin between items */\n            margin-bottom: 10px;\n            position: relative;\n\n            div {\n                /* Allow for scrolling within the text content */\n                max-height: 50dvh;\n                overflow-y: auto;\n            }\n\n            /* Timestamp styling */\n            .timestamp {\n                /* small font size */\n                font-size: x-small;\n                /* italicized */\n                font-style: italic;\n                /* different font family */\n                font-family: monospace;\n                /* Align to the right using flexbox */\n                margin-left: auto;\n                margin-top: 0;\n                margin-bottom: 0;\n                /* Hide timestamp by default with max-height for transition */\n                max-height: 0;\n                overflow: hidden;\n                opacity: 0;\n                transition: max-height 0.3s ease-in-out, opacity 0.3s ease-in-out;\n            }\n\n            /* Copy button styling */\n            .copy-button {\n                /* Hide copy button by default with max-height for transition */\n                max-height: 0;\n                overflow: hidden;\n                opacity: 0;\n                transition: max-height 0.3s ease-in-out, opacity 0.3s ease-in-out;\n\n                /* Remove default button styles */\n                background: none;\n                border: none;\n                /* Small font size */\n                font-size: x-large;\n                /* Positioning in bottom left */\n                position: absolute;\n                bottom: 10px;\n                left: 10px;\n                cursor: pointer;\n                color: var(--button-text-color-base);\n                background-color: transparent;\n                border-radius: 5px;\n            }\n\n\n            /* Hover effect for copy button */\n            .copy-button:hover {\n                color: #555;\n                color: var(--button-hover-text-color);\n                background-color: var(--button-hover-background-color);\n                border: var(--button-hover-text-color) 2px solid;\n                /* Slightly darker text on hover */\n            }\n\n            /* Show timestamp and copy button when show-details class is present */\n            &.show-details .timestamp,\n            &.show-details .copy-button {\n                max-height: 100px;\n                opacity: 1;\n                transition: max-height 0.5s ease-in-out, opacity 0.5s ease-in-out;\n                /* Add some spacing when visible */\n                margin-top: 5px;\n            }\n\n            &.copied-animation {\n                transition: background-color 0.5s ease-in-out, filter 0.5s ease-in-out;\n                background-color: #e8f5e9;\n                filter: blur(2px);\n            }\n\n            /* Styling for the \"Copied!\" feedback message */\n            .copied-feedback {\n                /* Small font size */\n                font-size: small;\n                /* Light background color */\n                background-color: white;\n                /* Dark text color */\n                color: #333;\n                /* Padding and rounded corners */\n                padding: 2px 5px;\n                border-radius: 4px;\n                /* Ensure it's on top */\n                z-index: 10;\n            }\n\n        }\n\n        section.human-message .copy-button {\n            background-color: var(--agent-background-color);\n            color: var(--agent-text-color);\n        }\n\n        section.human-message .copy-button:hover {\n            color: var(--agent-background-color);\n            background-color: var(--agent-text-color);\n            border: var(--agent/un-background-color) 2px solid;\n        }\n\n        section.agent-message .copy-button {\n            background-color: var(--human-background-color);\n            color: var(--human-text-color);\n        }\n\n        section.agent-message .copy-button:hover {\n            color: var(--human-background-color);\n            background-color: var(--human-text-color);\n            border: var(--human-background-color) 2px solid;\n        }\n\n        section.agent-message {\n            background-color: var(--agent-background-color);\n            color: var(--agent-text-color);\n        }\n\n        section.human-message {\n            background-color: var(--human-background-color);\n            color: var(--human-text-color);\n        }\n\n        section.code-message {\n            background-color: var(--code-background-color);\n            color: var(--code-text-color);\n        }\n\n        section.function-message {\n            background-color: var(--function-background-color);\n            color: var(--function-text-color);\n        }\n\n        section.unknown-message {\n            background-color: var(--unknown-background-color);\n            color: var(--unknown-text-color);\n        }\n\n        section.agent-message,\n        section.human-message,\n        section.code-message,\n        section.function-message,\n        section.unknown-message {\n\n            .identity-info {\n                width: 100%;\n                background-color: #00000005;\n                font-weight: bold;\n                line-height: 0;\n                margin: 0;\n                padding: 0;\n                border-radius: 5px;\n                border-color: var(--agent-text-color);\n            }\n\n        }\n    }\n\n\n\n}\n", "import thisHtml from \"./chronology.html\";\nimport thisCss from \"./chronology.css\";\nimport stylesCss from \"../../../styles.css\";\nimport rootCss from \"../../../root.css\";\n\nimport { delay, extractErrorMsg, pretty } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { getTimestampInfo } from \"@ibgib/core-gib/dist/common/other/ibgib-helper.mjs\";\nimport { IbGibAddr, } from \"@ibgib/ts-gib/dist/types.mjs\";\nimport { IbGib_V1 } from \"@ibgib/ts-gib/dist/V1/types.mjs\";\nimport { getIbGibAddr } from \"@ibgib/ts-gib/dist/helper.mjs\";\nimport { MetaspaceService } from \"@ibgib/core-gib/dist/witness/space/metaspace/metaspace-types.mjs\";\nimport { isComment, parseCommentIb } from \"@ibgib/core-gib/dist/common/comment/comment-helper.mjs\";\nimport { tellUserFunctionInfo } from \"@ibgib/web-gib/dist/api/commands/chat/tell-user.mjs\";\nimport { getGlobalMetaspace_waitIfNeeded } from \"@ibgib/web-gib/dist/helpers.mjs\";\nimport { IbGibDynamicComponentInstanceBase, IbGibDynamicComponentMetaBase } from \"@ibgib/web-gib/dist/ui/component/ibgib-dynamic-component-bases.mjs\";\nimport { IbGibDynamicComponentInstance, IbGibDynamicComponentInstanceInitOpts } from \"@ibgib/web-gib/dist/ui/component/component-types.mjs\";\nimport { parseAddlMetadataTextForAgentText, } from \"@ibgib/web-gib/dist/witness/agent/agent-helpers.mjs\";\nimport { AgentWitnessAny, } from \"@ibgib/web-gib/dist/witness/agent/agent-one-file.mjs\";\nimport { TextSource } from \"@ibgib/web-gib/dist/witness/agent/agent-constants.mjs\";\nimport { ProjectIbGib_V1 } from \"@ibgib/web-gib/dist/common/project/project-types.mjs\";\nimport { getAgentsSvc } from \"@ibgib/web-gib/dist/witness/agent/agents-service-v1.mjs\";\nimport { AGENT_SPECIAL_IBGIB_TYPE_PRIMARYAGENT } from '@ibgib/web-gib/dist/witness/agent/agent-constants.mjs';\n\nimport { GLOBAL_LOG_A_LOT, } from \"../../../constants.mjs\";\nimport { getComponentCtorArg, getIbGibGlobalThis_BlankGib, } from \"../../../helpers.web.mjs\";\nimport { ID_PRIMARY_AGENT_CHAT_LOG } from \"../../../ui/shell/shell-constants.mjs\";\nimport {\n    AGENT_GOAL_COMMON, AGENT_INITIAL_CHAT_HI_PLEASEINTRO_YOURSELF,\n    AGENT_SYSTEM_PROMPT_COMMON_INSTRUCTIONS,\n} from \"../../../agent-texts/common-agent-texts.mjs\";\nimport { simpleIbGibRouterSingleton } from \"../../../ui/router/router-one-file.mjs\";\nimport { isMinigameIbGib_V1 } from \"../../../common/minigame/minigame-helper.mjs\";\nimport { MinigameIbGib_V1 } from \"../../../common/minigame/minigame-types.mjs\";\nimport { ProjectComponentInstance } from \"../../projects/project/project-component-one-file.mjs\";\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\nexport const AGENT_SPECIAL_IBGIB_TYPE_CHRONOLOGYAGENT = 'chronologyagent';\nexport const AGENT_GOAL_CHRONOLOGYAGENT = [\n    AGENT_GOAL_COMMON,\n    `You yourself are a \"chronology\" agent. Your job is to help show the chronology of an ibgib.`,\n    `A \"chronology\" is just a synonym for \"timeline\" in our case right now. I use the word \"timeline\" generally when speaking about ibgibs and I wanted a different word in code. But semantically, the \"chronology\" is meant to give some condensed view of an ibgib's evolution.`,\n    `The use case right now is to show the equivalent of what others call \"chats\". A \"chat\" in their sense is a linear sequence of some context that has text, and possibly pics and other artifacts, added to it over time. In ibgib, since we create a hypergraph, the timeline aspect is a little more complicated. The context ibgib itself may add \"child\" items, and so may those child items effectively ad infinitum. This is truly parallel computing.`,\n    `So a chronology is some view on what could be a complicated timeline.`,\n    `Keep in mind though that we're still early dev stage so you may not be able to do much at the moment.`,\n].join('\\n');\n\nexport const AGENT_INITIAL_SYSTEM_TEXT_CHRONOLOGYAGENT = [\n    AGENT_SYSTEM_PROMPT_COMMON_INSTRUCTIONS,\n    AGENT_GOAL_CHRONOLOGYAGENT,\n].join('\\n');\nexport const AGENT_INITIAL_CHAT_TEXT_CHRONOLOGYAGENT = [\n    AGENT_INITIAL_CHAT_HI_PLEASEINTRO_YOURSELF,\n].join('\\n');\nexport const CHAT_WITH_AGENT_PLACEHOLDER_CHRONOLOGYAGENT = '';\nexport const AGENT_AVAILABLE_FUNCTIONS_CHRONOLOGYAGENT = [\n    tellUserFunctionInfo,\n];\n\nexport const CHRONOLOGY_COMPONENT_NAME: string = 'ibgib-chronology';\n\n\nexport class ChronologyComponentMeta extends IbGibDynamicComponentMetaBase {\n    protected override lc: string = `[${ChronologyComponentMeta.name}]`;\n\n    /**\n     * temporary regexp path for our initial dev. this component will become\n     * attached to actual ib^gib addrs\n     */\n    routeRegExp?: RegExp = new RegExp(CHRONOLOGY_COMPONENT_NAME);\n    // routeRegExp?: RegExp = /apps\\/web1\\/gib\\/contact.html/;\n\n    componentName: string = CHRONOLOGY_COMPONENT_NAME;\n\n    constructor() {\n        super(getComponentCtorArg());\n        customElements.define(this.componentName, ChronologyComponentInstance);\n    }\n\n    /**\n     * for a chronology, we don't have any additional info in the path.\n     */\n    async createInstance({\n        path,\n        ibGibAddr\n    }: {\n        path: string;\n        ibGibAddr: IbGibAddr;\n    }): Promise<IbGibDynamicComponentInstance> {\n        const lc = `${this.lc}[${this.createInstance.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 19ed38829f8693c83889ff3d151b4e25)`); }\n            const component = document.createElement(this.componentName) as ChronologyComponentInstance;\n            await component.initialize({\n                ibGibAddr,\n                meta: this,\n                html: thisHtml,\n                css: [rootCss, stylesCss, thisCss],\n            });\n            return component;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n}\n\ninterface ChronologyElements {\n    headerEl: HTMLElement;\n    // headerTabsEl: HTMLElement | undefined;\n    textEl: HTMLHeadingElement;\n    /**\n     *\n     */\n    descEl: HTMLParagraphElement;\n    /**\n     * container element for the chronologys component\n     */\n    contentEl: HTMLElement;\n    footerEl: HTMLElement;\n    // inputEl: HTMLTextAreaElement;\n}\n\nexport class ChronologyComponentInstance\n    extends IbGibDynamicComponentInstanceBase<ProjectIbGib_V1, ChronologyElements>\n    implements IbGibDynamicComponentInstance<IbGib_V1, ChronologyElements> {\n    protected override lc: string = `[${ChronologyComponentInstance.name}]`;\n\n    metaspace: MetaspaceService | undefined;\n\n    constructor() {\n        super();\n    }\n\n    override async initialize(opts: IbGibDynamicComponentInstanceInitOpts): Promise<void> {\n        const lc = `${this.lc}[${this.initialize.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 4764f8b8d8a801a008e85328752f7825)`); }\n            await super.initialize(opts);\n            await this.loadIbGib();\n            this.agentsInitialized = this.initAgents();\n\n            await this.agentsInitialized; // Wait for metaspace to be initialized\n            // await this.eoadChildIbGibs();\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private async loadChildIbGibs(): Promise<void> {\n        const lc = `${this.lc}[${this.loadChildIbGibs.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: beb5c41d17a52fcb53511f97c8301625)`); }\n\n            if (!this.metaspace) { throw new Error(`(UNEXPECTED) metaspace should have been initialized. (E: 3a4c4876a0904b499f09112674b8a925)`) }\n            if (!this.ibGib) { throw new Error(`(UNEXPECTED) this.ibGib falsy? (E: 77428a4a60f81a1a9e9d17d041e39125)`); }\n            if (!this.elements) { throw new Error(`(UNEXPECTED) this.elements falsy? (E: e9802057b36b692985b7e32633e20525)`); }\n            const { contentEl } = this.elements;\n            contentEl.innerHTML = ''; //clear the content\n\n            const excludeRel8nNames: string[] = [\n                'ancestor', 'dna', 'past', 'tjp',\n            ];\n            // const rel8nNames = ['comment', 'pic', 'minigame'];\n            if (!this.ibGib.rel8ns) { throw new Error(`(UNEXPECTED) this.ibGib.rel8ns falsy? (E: 5c530af755a37f89ac51810b61dc2d25)`); }\n            const rel8nNames = Object.keys(this.ibGib.rel8ns).filter(x => !excludeRel8nNames.includes(x));\n            const childAddrs: IbGibAddr[] = [];\n            for (const rel8nName of rel8nNames) {\n                const rel8dAddrs = this.ibGib.rel8ns[rel8nName] ?? [];\n                childAddrs.push(...rel8dAddrs);\n            }\n\n            const childIbGibs: IbGib_V1[] = [];\n            for (const childAddr of childAddrs) {\n                const resGet = await this.metaspace.get({ addr: childAddr });\n                if (resGet.errorMsg) { throw new Error(`Could not retrieve ibGib: ${resGet.errorMsg} (E: 5c77a680328c49e085557e7a7c20b425)`) }\n                if (!resGet.ibGibs || resGet.ibGibs.length === 0) { throw new Error(`Could not retrieve ibGib: No IbGibs returned from metaspace. (E: 4e657a262a784b339873976b3288d125)`); }\n                childIbGibs.push(resGet.ibGibs[0])\n            }\n\n            childIbGibs.sort((a, b) => {\n                const aRes = getTimestampInfo({ ibGib: a });\n                if (!aRes.valid) { throw new Error(`(UNEXPECTED) invalid a timestamp: ${aRes.emsg} (E: 81a4c81e25e65a971922626f0a08a825)`); }\n                const aTicks = Number.parseInt(aRes.ticks);\n                const bRes = getTimestampInfo({ ibGib: b });\n                if (!bRes.valid) { throw new Error(`(UNEXPECTED) invalid b timestamp: ${bRes.emsg} (E: 41813b26a8c92d4c8a293e426d202f25)`); }\n                const bTicks = Number.parseInt(bRes.ticks);\n                if (aTicks < bTicks) {\n                    return -1;\n                } else if (aTicks > bTicks) {\n                    return 1;\n                } else {\n                    return 0;\n                }\n            });\n\n            // childIbGibs.sort((a, b) => {\n            //     const aTicks = getTimestampInfo({ ib: a.ib }).timestampTicks;\n            //     const bTicks = getTimestampInfo({ ib: b.ib }).timestampTicks;\n            //     return aTicks > b.ib ? 1 : -1;\n            // });\n\n            for (const childIbGib of childIbGibs) {\n                let errored = false;\n                try {\n                    const itemElement = await this.renderIbGibItem({ ibGib: childIbGib });\n                    contentEl.appendChild(itemElement)\n                } catch (error) {\n                    console.error(`${lc} Error rendering ibGib: ${extractErrorMsg(error)} (E: b2a7592d1a5743d6b4e7b9241561e325)`);\n                    errored = true;\n                }\n                if (errored) {\n                    try {\n                        const itemElement = await this.renderIbGibItem_fallback({ ibGib: childIbGib });\n                        contentEl.appendChild(itemElement)\n                    } catch (error) {\n                        console.error(`${lc} Error rendering ibGib during fallback?: ${extractErrorMsg(error)} (E: 7d37888dc85e37141877eb786dbaaf25)`);\n                        errored = true;\n                    }\n                }\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    override async created(): Promise<void> {\n        const lc = `${this.lc}[${this.created.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 95d9e84448669a0db81410c810e83b25)`); }\n\n            // const { meta, htmlPath, scriptPaths, cssPaths } = opts;\n\n            // at this point, this.ibGib should be loaded with the latest\n            // project ibgib\n\n            if (!this.ibGib) { throw new Error(`(UNEXPECTED) this.ibGib falsy? It is assumed at this point that we have a valid ibGib to work with. (E: 15af5db05175b88a629e52a335625b25)`); }\n\n            await this.initElements();\n\n            /**\n             * for the moment, we're just re-using the primary agent's chat log...eesh!!\n             *\n             * This is obviously the wrong thing to do in the long run...\n             */\n            const primaryAgentChatLog =\n                document.getElementById(ID_PRIMARY_AGENT_CHAT_LOG) as HTMLDivElement;\n            if (!primaryAgentChatLog) { throw new Error(`(UNEXPECTED) primaryAgentChatLog not found in document? (E: fe663fd60a5820040d5bacb845ed1825)`); }\n\n            await this.agentsInitialized;\n            await this.loadChildIbGibs();\n            await this.renderUI();\n\n            setTimeout(() => {\n                if (!this.elements) { throw new Error(`(UNEXPECTED) this.elements falsy? (E: 3a1c7d612aeadee515218cca2ad0c225)`); }\n                const { contentEl } = this.elements;\n                if (contentEl.lastElementChild) {\n                    contentEl.lastElementChild.scrollIntoView({ behavior: 'smooth' });\n                }\n            }, 1000);\n            // await this.agent!.witness(ROOT); // not the responsibility of the chronology component to initiate prompt\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    override async handleContextUpdated(): Promise<void> {\n        const lc = `${this.lc}[${this.handleContextUpdated.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 1cec5212626b1700aa09c2e3d6966225)`); }\n            console.log(`${lc} this.ibGib: ${pretty(this.ibGib)}`)\n            await super.handleContextUpdated();\n            await this.renderUI();\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * renders a single ibgib into the chronology content element\n     */\n    private async renderIbGibItem({\n        ibGib,\n    }: {\n        ibGib: IbGib_V1;\n    }): Promise<HTMLElement> {\n        const lc = `${this.lc}[${this.renderIbGibItem.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: d59d1e05b804665e8ee9bc28d56ec825)`); }\n\n            let resEl: HTMLElement;\n            if (isComment({ ibGib })) {\n                resEl = await this.renderIbGibItem_comment({ ibGib });\n            } else if (isMinigameIbGib_V1(ibGib)) {\n                resEl = await this.renderIbGibItem_minigame({ ibGib });\n            } else {\n                resEl = await this.renderIbGibItem_fallback({ ibGib });\n            }\n            return resEl;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private async renderIbGibItem_comment({\n        ibGib,\n    }: {\n        ibGib: IbGib_V1;\n    }): Promise<HTMLElement> {\n        const lc = `${this.lc}[${this.renderIbGibItem_comment.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 2948f102f3a6d51d35b26a9339113325)`); }\n            if (!ibGib.data) { throw new Error(`(UNEXPECTED) childIbGib.data falsy? (E: a1c4e1a657f764c98e7f919663058325)`); }\n\n            let text = ibGib.data.text;\n\n            if (!text) { throw new Error(`childIbGib.data.text falsy? what kind of child are we tracking at this point? we only do comments. ${pretty(ibGib)} (E: 0e5e2e1c7b5c692f295979a03c617625)`); }\n\n            const ib = ibGib.ib;\n            // what is the\n\n            const { safeIbCommentMetadataText } = parseCommentIb({ ib });\n            let textSrc: TextSource;\n            try {\n                const resParse = parseAddlMetadataTextForAgentText({\n                    addlMetadataText: safeIbCommentMetadataText ?? '',\n                    ifError: 'ignore',\n                });\n                textSrc = resParse.textSrc;\n            } catch (error) {\n                textSrc = 'unknown';\n            }\n\n            let who: string;\n            switch (textSrc) {\n                case 'ai':\n                    who = 'agent'; break;\n                case 'human':\n                    who = 'user'; break;\n                case 'hardcoded':\n                    who = 'code'; break;\n                case 'function':\n                    who = 'func'; break;\n                default:\n                    who = '[who?]';\n            }\n            const timestampInfo = getTimestampInfo({ ibGib });\n            if (!timestampInfo.valid) {\n                throw new Error(`(UNEXPECTED) invalid timestamp: ${timestampInfo.emsg} (E: 42643858345b58538f09a71287a19f25)`);\n            }\n            const date = timestampInfo.date;\n            const timestampString = date.toLocaleString(); // Use toLocaleString for a more readable format\n            const timestampParagraph = document.createElement('p');\n            timestampParagraph.textContent = timestampString;\n            timestampParagraph.classList.add('timestamp');\n            if (who === 'agent') {\n                who = 'An AI agent (\uD83E\uDD16)';\n            } else {\n                who = 'A human';\n            }\n            timestampParagraph.title = `${who} created this message ${timestampString}`;\n\n            const chatEntry = document.createElement('section');\n            const identityInfoDiv = document.createElement('div');\n            identityInfoDiv.classList.add('identity-info');\n            const identityInfoP = document.createElement('p');\n            if (textSrc === 'ai') {\n                // right now we're encoding it in \"other\" agent text addl\n                // metadata.  see tell-user.mts tellUserImpl and\n                // agent-helpers.mts getAddlMetadataTextForAgentText.\n                const agentName = safeIbCommentMetadataText?.split('_').at(2) ?? 'Agent';\n                identityInfoP.textContent = `\uD83E\uDD16 ${agentName}`;\n                chatEntry.classList.add('agent-message');\n            } else if (textSrc === 'human') {\n                chatEntry.classList.add('human-message');\n                identityInfoP.textContent = `user`;\n            }\n            identityInfoDiv.appendChild(identityInfoP);\n            chatEntry.appendChild(identityInfoDiv)\n\n            const textContentDiv = document.createElement('div');\n            const textParagraphs: string[] = text.split('\\n');\n            textParagraphs.forEach(textParagraph => {\n                const pElement = document.createElement('p');\n                pElement.textContent = textParagraph;\n                textContentDiv.appendChild(pElement);\n            });\n\n            const copyButton = document.createElement('button');\n            copyButton.textContent = '\uD83D\uDDD0';\n            copyButton.classList.add('copy-button');\n            copyButton.addEventListener('click', async (e) => {\n                e.preventDefault();\n                e.stopImmediatePropagation();\n                navigator.clipboard.writeText(text);\n                const feedbackSpan = document.createElement('span');\n                feedbackSpan.textContent = \"Copied!\";\n                feedbackSpan.classList.add('copied-feedback');\n                feedbackSpan.style.position = 'absolute';\n                feedbackSpan.style.bottom = '30px';\n                feedbackSpan.style.left = '20px';\n                chatEntry.appendChild(feedbackSpan);\n                await delay(100);\n                chatEntry.classList.add('copied-animation');\n                chatEntry.classList.add('highlight');\n                await delay(500);\n                chatEntry.classList.remove('copied-animation');\n                await delay(400);\n                chatEntry.classList.remove('highlight');\n                await delay(1000);\n                feedbackSpan.remove();\n            });\n\n            chatEntry.dataset.clicked = \"false\";\n            chatEntry.addEventListener('click', () => {\n                const clicked = chatEntry.dataset.clicked;\n                chatEntry.dataset.clicked = clicked === \"true\" ? \"false\" : \"true\";\n                if (chatEntry.dataset.clicked === \"true\") {\n                    chatEntry.classList.add('show-details');\n                } else {\n                    chatEntry.classList.remove('show-details');\n                }\n            });\n\n            chatEntry.addEventListener('mouseover', () => {\n                if (chatEntry.dataset.clicked !== \"true\") {\n                    chatEntry.classList.add('show-details');\n                }\n            });\n\n            chatEntry.addEventListener('mouseout', () => {\n                if (chatEntry.dataset.clicked !== \"true\") {\n                    chatEntry.classList.remove('show-details');\n                }\n            });\n            chatEntry.appendChild(copyButton);\n\n            chatEntry.appendChild(textContentDiv);\n            chatEntry.appendChild(timestampParagraph);\n\n            return chatEntry;\n\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private async renderIbGibItem_minigame({\n        ibGib,\n    }: {\n        ibGib: MinigameIbGib_V1;\n    }): Promise<HTMLElement> {\n        const lc = `${this.lc}[${this.renderIbGibItem_minigame.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n            if (!ibGib.data) { throw new Error(`(UNEXPECTED) ibGib.data falsy? This is expected to be a minigame ibgib. (E: 5fe49d9c7bd87fb2284fad28f4916925)`); }\n\n            const chatEntry = document.createElement('section');\n\n            // identity\n            // const identityInfoDiv = document.createElement('div');\n            // identityInfoDiv.classList.add('identity-info');\n            // const identityInfoP = document.createElement('p');\n            // chatEntry.classList.add('code-message');\n            // identityInfoP.textContent = `identityhere`;\n            // identityInfoDiv.appendChild(identityInfoP);\n\n            // body\n            const textContentDiv = document.createElement('div');\n            const pElement = document.createElement('p');\n            const name = ibGib.data.name;\n            const iElement = document.createElement('i');\n            iElement.style.fontSize = 'small';\n            iElement.textContent = `${ibGib.data.name || '[no name?]'} minigame added.`;\n            pElement.appendChild(iElement);\n            textContentDiv.appendChild(pElement);\n\n            // timestamp footer\n            const timestampInfo = getTimestampInfo({ ibGib });\n            if (!timestampInfo.valid) {\n                throw new Error(`(UNEXPECTED) invalid timestamp: ${timestampInfo.emsg} (E: genuuid)`);\n            }\n            const date = timestampInfo.date;\n            const timestampString = date.toLocaleString(); // Use toLocaleString for a more readable format\n            const timestampParagraph = document.createElement('p');\n            timestampParagraph.textContent = timestampString;\n            timestampParagraph.classList.add('timestamp');\n            timestampParagraph.title = `This ibgib message was created ${timestampString}`;\n            chatEntry.dataset.clicked = \"false\";\n            chatEntry.addEventListener('click', () => {\n                const clicked = chatEntry.dataset.clicked;\n                chatEntry.dataset.clicked = clicked === \"true\" ? \"false\" : \"true\";\n                if (chatEntry.dataset.clicked === \"true\") {\n                    chatEntry.classList.add('show-details');\n                } else {\n                    chatEntry.classList.remove('show-details');\n                }\n            });\n            chatEntry.addEventListener('mouseover', () => {\n                if (chatEntry.dataset.clicked !== \"true\") {\n                    chatEntry.classList.add('show-details');\n                }\n            });\n            chatEntry.addEventListener('mouseout', () => {\n                if (chatEntry.dataset.clicked !== \"true\") {\n                    chatEntry.classList.remove('show-details');\n                }\n            });\n\n            // compose the chatEntry itself\n            // chatEntry.appendChild(identityInfoDiv)\n            chatEntry.appendChild(textContentDiv);\n            chatEntry.appendChild(timestampParagraph);\n\n            // when clicking the chatEntry, should activate the ibgib on the\n            // projects component\n\n            chatEntry.addEventListener('click', async () => {\n                const globalBlankGib = getIbGibGlobalThis_BlankGib();\n                if (!this.ibGib) { throw new Error(`(UNEXPECTED) this.ibGib falsy? (E: 5c0e3e92ea2dcdb1f1e8eaa828ad5825)`); }\n                const projectsComponent = globalBlankGib.projectsComponent;\n                if (!projectsComponent) { throw new Error(`(UNEXPECTED) globalBlankGib.projectsComponent falsy? (E: 27ec3b3738872869d80064381cebe825)`); }\n                if (!projectsComponent.activeProjectTabInfo) {\n                    throw new Error(`(UNEXPECTED) projectsComponent.activeProjectTabInfo falsy? (E: a9d3de3612f858f818eb1eb85f0c7825)`);\n                }\n                const projectComponent = projectsComponent.activeProjectTabInfo.component as ProjectComponentInstance;\n                if (!projectComponent) { throw new Error(`(UNEXPECTED) projectComponent falsy? projectsComponent.activeProjectTabInfo.component is expected to be truthy at this point. (E: 66cc452486787f8b881a20b35333ac25)`); }\n                await projectComponent.activateIbGib({ ibGib });\n            });\n\n            return chatEntry;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private async renderIbGibItem_fallback({\n        ibGib,\n    }: {\n        ibGib: IbGib_V1;\n    }): Promise<HTMLElement> {\n        const lc = `${this.lc}[${this.renderIbGibItem_fallback.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n\n            const chatEntry = document.createElement('section');\n\n            // identity\n            // const identityInfoDiv = document.createElement('div');\n            // identityInfoDiv.classList.add('identity-info');\n            // const identityInfoP = document.createElement('p');\n            // chatEntry.classList.add('code-message');\n            // identityInfoP.textContent = `identityhere`;\n            // identityInfoDiv.appendChild(identityInfoP);\n\n            // body\n            const textContentDiv = document.createElement('div');\n            const pElement = document.createElement('p');\n            pElement.textContent = getIbGibAddr({ ibGib });\n            textContentDiv.appendChild(pElement);\n\n            // timestamp footer\n            const timestampInfo = getTimestampInfo({ ibGib });\n            if (!timestampInfo.valid) {\n                throw new Error(`(UNEXPECTED) invalid timestamp: ${timestampInfo.emsg} (E: genuuid)`);\n            }\n            const date = timestampInfo.date;\n            const timestampString = date.toLocaleString(); // Use toLocaleString for a more readable format\n            const timestampParagraph = document.createElement('p');\n            timestampParagraph.textContent = timestampString;\n            timestampParagraph.classList.add('timestamp');\n            timestampParagraph.title = `This ibgib message was created ${timestampString}`;\n            chatEntry.dataset.clicked = \"false\";\n            chatEntry.addEventListener('click', () => {\n                const clicked = chatEntry.dataset.clicked;\n                chatEntry.dataset.clicked = clicked === \"true\" ? \"false\" : \"true\";\n                if (chatEntry.dataset.clicked === \"true\") {\n                    chatEntry.classList.add('show-details');\n                } else {\n                    chatEntry.classList.remove('show-details');\n                }\n            });\n            chatEntry.addEventListener('mouseover', () => {\n                if (chatEntry.dataset.clicked !== \"true\") {\n                    chatEntry.classList.add('show-details');\n                }\n            });\n            chatEntry.addEventListener('mouseout', () => {\n                if (chatEntry.dataset.clicked !== \"true\") {\n                    chatEntry.classList.remove('show-details');\n                }\n            });\n\n            // compose the chatEntry itself\n            // chatEntry.appendChild(identityInfoDiv)\n            chatEntry.appendChild(textContentDiv);\n            chatEntry.appendChild(timestampParagraph);\n\n            return chatEntry;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    /**\n     * right now, in witnesswith context base, these children are hard-coded as\n     * pic/comment/link rel8ns. need to change core-gib to make this a property\n     * on the class that drives which rel8nNames to track for new context\n     * children.\n     */\n    protected override async handleNewContextChild({\n        childIbGib\n    }: {\n        childIbGib: IbGib_V1;\n    }): Promise<void> {\n        const lc = `${this.lc}[${this.handleNewContextChild.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 118ee1579105ab6bae507272041e4925)`); }\n\n            // for starters, we'll just add a new item for the child, since it's\n            // just a simple \"chat log\" right now.\n\n            if (!this.elements) { throw new Error(`(UNEXPECTED) this.elements falsy? (E: 3a1c7d612aeadee515218cca2ad0c225)`); }\n            const { contentEl } = this.elements;\n\n            const chatEntry = await this.renderIbGibItem({ ibGib: childIbGib });\n            contentEl.appendChild(chatEntry);\n            chatEntry.scrollIntoView({ behavior: 'smooth' });\n\n            // super.handleNewContextChild\n            // let animation happen. we are not expecting a lot of messages to just come\n            // pouring in. If that becomes the case, then we need to reduce/remove this\n            // delay.\n            await delay(500);\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private async initElements(): Promise<void> {\n        const lc = `${this.lc}[${this.initElements.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 98c5bd4e6796961b7672cb3258e4da25)`); }\n\n            const shadowRoot = this.shadowRoot;\n\n            if (!shadowRoot) { throw new Error(`(UNEXPECTED) shadowRoot falsy? (E: 2669d84403e65a091850a118cc1e8e25)`); }\n\n            // #region header\n\n            const headerEl = shadowRoot.getElementById('chronology-header') as HTMLElement;\n            if (!headerEl) { throw new Error(`(UNEXPECTED) headerEl not found in shadowRoot? (E: 12ba48a30b586c7268577f8a76c0b825)`); }\n\n            const textEl = shadowRoot.getElementById('chronology-text') as HTMLHeadingElement;\n            if (!textEl) { throw new Error(`(UNEXPECTED) textEl not found in shadowRoot? (E: c0c11d642bc26eb224a714740f6c7225)`); }\n            const descEl = shadowRoot.getElementById('chronology-description') as HTMLParagraphElement;\n            if (!descEl) { throw new Error(`(UNEXPECTED) descEl not found in shadowRoot? (E: 8b82a81eb058ee783553b1888c1b3325)`); }\n\n            // #endregion header\n\n            const contentEl = shadowRoot.getElementById('chronology-content') as HTMLElement;\n            if (!contentEl) { throw new Error(`(UNEXPECTED) contentEl not found in shadowRoot? (E: aa90dd17107658d79d8e346f99085a25)`); }\n\n            const footerEl = shadowRoot.getElementById('chronology-footer') as HTMLElement;\n            if (!footerEl) { throw new Error(`(UNEXPECTED) footerEl not found in shadowRoot? (E: 5a4b78703d0e0547f8d8eab86d67d825)`); }\n            footerEl.style.display = 'none';\n            // this.footerEl = footerEl as HTMLElement;\n\n            this.elements = {\n                headerEl,\n                // headerTabsEl,\n                contentEl,\n                footerEl,\n                textEl,\n                descEl,\n            };\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * rerender\n     */\n    protected override async renderUI(): Promise<void> {\n        const lc = `${this.lc}[${this.renderUI.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 5415ec9be03ca640cb1a3d6a17d22625)`); }\n\n            await super.renderUI();\n\n            if (!this.elements) {\n                console.warn(`${lc} (UNEXPECTED) tried to render but haven't initialized elements? (W: 2b9f6893b449d7a72861c148ec428925)`);\n                return; /* <<<< returns early */\n            }\n\n            const {\n                headerEl, contentEl, footerEl,\n                // tabBtnEl,\n                // inputEl,\n                textEl, descEl,\n            } = this.elements;\n\n            if (!this.ibGib) { throw new Error(`(UNEXPECTED) this.ibGib falsy? (E: a2e31a4cfcd763a5c6e5133919aa0725)`); }\n\n\n\n            // if (this.ibGib.ib.startsWith('comment --interactive')) {\n            if (simpleIbGibRouterSingleton.isCurrentPageWeb1) {\n                // the current hack is that we set the chronology's context to\n                // the initial comment ibgib that we hacked to bootstrap the web\n                // app. in the future, we just need a better mechanism for web1\n                // chronology, which may just be an entirely separate app for\n                // web1 and projects/dev\n                if (logalot) { console.warn(`${lc} web1 chronologys tab btn title hack. (W: bc3ed81fdd48f351580c2f7b035e6825)`); }\n                textEl.style.display = 'none';\n                descEl.style.display = 'none';\n            } else {\n                // we are in a regular project/other ibgib\n                textEl.textContent = this.ibGib?.data?.name ?? '[no name?]'\n                textEl.textContent += ` (v${this.ibGib?.data?.n ?? '?'})`\n                const description = this.ibGib?.data?.description;\n                if (description) {\n                    descEl.textContent = description;\n                } else {\n                    descEl.style.display = 'none';\n                }\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    override async disconnected(): Promise<void> {\n        const lc = `${this.lc}[${this.disconnected.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 8e0719f027b8e25dc836b4a8adbf2925)`); }\n            // no action atow\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    protected override async initAgents(): Promise<void> {\n        const lc = `${this.lc}[${this.initAgents.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: a16821cfe4d8dce0483ec60879005425)`); }\n\n            const metaspace = await getGlobalMetaspace_waitIfNeeded();\n            this.metaspace = metaspace;\n            if (!this.ibGib) { throw new Error(`(UNEXPECTED) this.ibGib falsy? (E: f09cc2b636e83410bd7a89ec954e3825)`); }\n\n            // do {\n            if (simpleIbGibRouterSingleton.isCurrentPageWeb1) {\n                let agent: AgentWitnessAny | undefined = undefined;\n                const agentsSvc = getAgentsSvc();\n                do {\n                    let agents = await agentsSvc.getAgents({\n                        metaspace,\n                        type: AGENT_SPECIAL_IBGIB_TYPE_PRIMARYAGENT,\n                        spaceId: undefined, // explicitly use default local space just to show this option bc it's early in life\n                    });\n                    if (agents.length > 0) {\n                        agent = agents.at(0)!;\n                    } else {\n                        await delay(200);\n                    }\n                } while (!agent);\n                this.agents = [agent];\n            } else {\n                await this.loadAgentsCoupledToIbGib();\n            }\n            if (!this.agent) {\n                // do we care\n                console.error(`(UNEXPECTED) this.agent falsy after load agents? (E: 7ab4a8a82c48c3161ab20f3c6f624b25)`);\n                // throw new Error(`(UNEXPECTED) this.agent falsy after load agents? (E: 7ab4a8a82c48c3161ab20f3c6f624b25)`);\n            }\n            //     if (!this.agent) {\n            //         if (logalot) { console.log(`${lc} no agents related to project? delaying and trying again... (I: 1a3acf5c8083b7f23bc665eec8256e25)`); }\n            //         await delay(100)\n            //     }\n            // } while (!this.agent)\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n}\n", "import thisHtml from './chronologys.html';\nimport thisCss from './chronologys.css';\nimport stylesCss from '../../styles.css';\nimport rootCss from '../../root.css';\n\nimport { delay, extractErrorMsg, getSaferSubstring, } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { IbGibAddr } from \"@ibgib/ts-gib/dist/types.mjs\";\nimport { IbGib_V1 } from \"@ibgib/ts-gib/dist/V1/types.mjs\";\nimport { getIbAndGib, getIbGibAddr } from \"@ibgib/ts-gib/dist/helper.mjs\";\nimport { getGibInfo, isPrimitive } from \"@ibgib/ts-gib/dist/V1/transforms/transform-helper.mjs\";\nimport { MetaspaceService } from \"@ibgib/core-gib/dist/witness/space/metaspace/metaspace-types.mjs\";\nimport { fnObs } from \"@ibgib/core-gib/dist/common/pubsub/observer/observer-helper.mjs\";\nimport { IbGibTimelineUpdateInfo } from \"@ibgib/core-gib/dist/common/other/other-types.mjs\";\nimport { getTjpAddr } from \"@ibgib/core-gib/dist/common/other/ibgib-helper.mjs\";\nimport { execInSpaceWithLocking } from \"@ibgib/core-gib/dist/witness/space/space-helper.mjs\";\nimport { mut8Timeline } from \"@ibgib/core-gib/dist/timeline/timeline-api.mjs\";\nimport { getDeterministicColorInfo, } from \"@ibgib/web-gib/dist/helpers.mjs\";\nimport { shadowRoot_getElementById } from '@ibgib/web-gib/dist/helpers.web.mjs';\nimport { tellUserFunctionInfo } from '@ibgib/web-gib/dist/api/commands/chat/tell-user.mjs';\nimport {\n    IbGibDynamicComponentInstanceBase_ParentOfTabs, IbGibDynamicComponentMetaBase\n} from \"@ibgib/web-gib/dist/ui/component/ibgib-dynamic-component-bases.mjs\";\nimport {\n    ElementsBase, IbGibDynamicComponentInstance,\n    IbGibDynamicComponentInstanceInitOpts, ChildInfoBase\n} from \"@ibgib/web-gib/dist/ui/component/component-types.mjs\";\nimport { getComponentSvc } from \"@ibgib/web-gib/dist/ui/component/ibgib-component-service.mjs\";\nimport { getGlobalMetaspace_waitIfNeeded, } from \"@ibgib/web-gib/dist/helpers.mjs\";\nimport { AgentWitnessAny, } from \"@ibgib/web-gib/dist/witness/agent/agent-one-file.mjs\";\nimport { getAgents } from \"@ibgib/web-gib/dist/witness/agent/agent-helpers.mjs\";\nimport { getAgentsSvc } from \"@ibgib/web-gib/dist/witness/agent/agents-service-v1.mjs\";\nimport { GEMINI_DEFAULT_MODEL_STR, } from \"@ibgib/web-gib/dist/witness/agent/gemini/gemini-constants.mjs\";\nimport { isProjectIbGib_V1 } from \"@ibgib/web-gib/dist/common/project/project-helper.mjs\";\nimport { SettingsType } from \"@ibgib/web-gib/dist/common/settings/settings-constants.mjs\";\nimport { getDefaultSettings, getSectionName } from \"@ibgib/web-gib/dist/common/settings/settings-helpers.mjs\";\nimport { Settings_Chronologys } from \"@ibgib/web-gib/dist/common/settings/settings-types.mjs\";\nimport {\n    AGENT_AVAILABLE_FUNCTIONS_PROJECTAGENT,\n    AGENT_AVAILABLE_FUNCTIONS_PROJECTCHILDTEXTAGENT,\n} from \"@ibgib/web-gib/dist/common/project/project-agent-functions.mjs\";\n\nimport { GLOBAL_LOG_A_LOT, } from \"../../constants.mjs\";\nimport { getComponentCtorArg, getDefaultFnGetAPIKey, getIbGibGlobalThis_BlankGib, } from \"../../helpers.web.mjs\";\nimport {\n    AGENT_INITIAL_CHAT_HI_PLEASEINTRO_YOURSELF,\n    AGENT_SYSTEM_PROMPT_COMMON_INSTRUCTIONS,\n} from \"../../agent-texts/common-agent-texts.mjs\";\nimport { CHRONOLOGY_COMPONENT_NAME, ChronologyComponentInstance } from \"../common/chronology/chronology-component-one-file.mjs\";\nimport { simpleIbGibRouterSingleton } from \"../../ui/router/router-one-file.mjs\";\nimport { getAppShellSvc } from \"../../ui/shell/app-shell-service.mjs\";\nimport { CHAT_WITH_AGENT_PLACEHOLDER_AGENT } from \"../../witness/app/blank-canvas/blank-canvas-constants.mjs\";\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\n/**\n * hackish way to store info\n */\n// export const OPEN_CHRONOLOGYS_ADDRS_KEY = 'open-chronology-addrs';\n\nexport const AGENT_SPECIAL_IBGIB_TYPE_CHRONOLOGYSAGENT = 'chronologysagent';\nexport const AGENT_AVAILABLE_FUNCTIONS_CHRONOLOGYSAGENT = [\n    tellUserFunctionInfo,\n    // ...RenderAgentFunctionInfos,\n];\n\nexport const AGENT_GOAL_CHRONOLOGYSAGENT = [\n    `In general, your goal is just to do your best to parse the chat texts and choose the best course of action in terms of one or more functions. Please refer to those available function schemas and descriptions.`,\n    `Usually, you will want to talk with them via the tell user function.`,\n    `As a chronologies agent, your job is mainly to act upon chronology views. These are views that show a linear timeline of an ibgib.`,\n    `An example of a linear timeline is like a chat or a log view. Since ibgibs create a hypergraph, where nodes can link to multiple other nodes even with the same named edge, this can explode. But a linear timeline that selects certain link paths can be very useful.`,\n    `Your job will not be to do that part, rather, your job is to manage other individual chronology view components that do that.`,\n].join('\\n');\n\nexport const AGENT_INITIAL_SYSTEM_TEXT_CHRONOLOGYSAGENT = [\n    AGENT_SYSTEM_PROMPT_COMMON_INSTRUCTIONS,\n    AGENT_GOAL_CHRONOLOGYSAGENT,\n].join('\\n');\n\nexport const CHRONOLOGYS_COMPONENT_NAME: string = 'ibgib-chronologys';\n\nexport class ChronologysComponentMeta extends IbGibDynamicComponentMetaBase {\n    protected override lc: string = `[${ChronologysComponentMeta.name}]`;\n\n    routeRegExp?: RegExp = new RegExp(CHRONOLOGYS_COMPONENT_NAME);\n\n    componentName: string = CHRONOLOGYS_COMPONENT_NAME;\n\n    constructor() {\n        super(getComponentCtorArg());\n        customElements.define(this.componentName, ChronologysComponentInstance);\n    }\n\n    async createInstance({\n        path,\n        ibGibAddr\n    }: {\n        /**\n         * todo: store this in the instance (i think) but will change this when needed\n         */\n        path: string;\n        ibGibAddr: IbGibAddr;\n    }): Promise<IbGibDynamicComponentInstance> {\n        const lc = `${this.lc}[${this.createInstance.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 7ead79dd8262702783917c6972182d25)`); }\n            const component = document.createElement(this.componentName) as ChronologysComponentInstance;\n            await component.initialize({\n                ibGibAddr,\n                meta: this,\n                html: thisHtml,\n                css: [rootCss, stylesCss, thisCss],\n            });\n            return component;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n}\n\ninterface ChronologysElements extends ElementsBase {\n    headerEl: HTMLElement;\n    headerTabsEl: HTMLElement;\n    /**\n     * container element for the projects component\n     */\n    contentEl: HTMLElement;\n    footerEl: HTMLElement;\n    // addProjectBtnEl: HTMLElement | undefined;\n}\n\n/**\n * helper interface for managing tabs and their associated ibgibs\n */\ninterface ChronologyTabInfo extends ChildInfoBase<ChronologyComponentInstance> {\n}\n\nexport class ChronologysComponentInstance\n    extends IbGibDynamicComponentInstanceBase_ParentOfTabs<Settings_Chronologys, IbGib_V1, ChronologysElements, ChronologyTabInfo>\n    implements IbGibDynamicComponentInstance<IbGib_V1, ChronologysElements> {\n    protected override lc: string = `[${ChronologysComponentInstance.name}]`;\n\n    metaspace: MetaspaceService | undefined;\n\n    protected get settingsType(): SettingsType {\n        return SettingsType.chronologys;\n    }\n\n    // private _reloadingTabs = false;\n\n    constructor() {\n        super();\n    }\n\n    override async initialize(opts: IbGibDynamicComponentInstanceInitOpts): Promise<void> {\n        const lc = `${this.lc}[${this.initialize.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: c05cb7a3cb49cf800e23df2f31edb225)`); }\n            // before any initialization, we want to ensure we are bootstrapped\n            // await getIbGibGlobalThis_BlankGib().bootstrapPromise; // this is in the super call now\n\n            if (!this.metaspace) {\n                // wait for the metaspace to be initialized\n                this.metaspace = await getGlobalMetaspace_waitIfNeeded({ delayIntervalMs: 50 });\n            }\n\n            if (isPrimitive({ gib: getIbAndGib({ ibGibAddr: opts.ibGibAddr }).gib })) {\n                const info = await simpleIbGibRouterSingleton.getCurrentPathInfo();\n                opts.ibGibAddr = getIbGibAddr({ ib: info.ib, gib: info.gib });\n            }\n\n            await super.initialize(opts);\n            this.agentsInitialized = this.initAgents(); // spins off\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    override async created(): Promise<void> {\n        const lc = `${this.lc}[${this.created.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 9b8a21e39584a6d78c97005785040d25)`); }\n\n            // const { meta, htmlPath, scriptPaths, cssPaths } = opts;\n            // does nothing atow\n            await this.initElements();\n            if (!this.elements) { throw new Error(`(UNEXPECTED) just initElements but this.elements falsy? (E: 753716ab06183a7787bf3ad649268e25)`); }\n\n            const { } = this.elements;\n\n            await this.agentsInitialized;\n\n            // if we have a primitive ibgib addr\n            const { gib } = getIbAndGib({ ibGibAddr: this.ibGibAddr });\n            if (isPrimitive({ gib })) {\n                if (this.ibGibAddr.includes('.html')) {\n                    // we're on a web1 page\n                    let web1CommentIbGib: IbGib_V1 | undefined = undefined;\n                    let counter = 0;\n                    do {\n                        const { web1CommentIbGibProxy } = getIbGibGlobalThis_BlankGib();\n                        if (web1CommentIbGibProxy) {\n                            web1CommentIbGib = web1CommentIbGibProxy.ibGib;\n                        }\n                        if (web1CommentIbGib) {\n                            break;\n                        } else {\n                            await delay(100);\n                            counter++;\n                            if (counter > 100) {\n                                throw new Error(`(UNEXPECTED) couldn't init chronologys web1 comment after 10 seconds? we're assuming this is just waiting on the global web1 comment to be created/set. (E: fef57e0abdd891783af56f586d200825)`);\n                            }\n                        }\n                    } while (!web1CommentIbGib);\n                    this.ibGibAddr = getIbGibAddr({ ibGib: web1CommentIbGib });\n                } else {\n                    console.warn(`${lc} this.ibGib is primitive, so what are we initializing settings for? (W: 9915089019b81c6935b32ae877095825)`);\n                    return; /* <<<< returns early */\n                }\n            }\n\n            await this.loadIbGib();\n            if (!this.ibGib) { throw new Error(`(UNEXPECTED) this.ibGib falsy after loadIbGib called? (E: ed266a3c51d12a6dedba8ad31c024425)`); }\n            if (isProjectIbGib_V1(this.ibGib)) {\n                // load project\n                this.activateIbGib({ ibGib: this.ibGib }); // spin off because it requires created to finish\n            } else {\n                this.activateIbGib({ ibGib: this.ibGib }); // spin off because it requires created to finish\n            }\n\n            await this.initSettings();\n\n            // spin off because created has to finish\n            // const projectSettings = await this.getCurrentProjectSettings();\n            const chronologysSettings = await this.getSettings<Settings_Chronologys>({\n                settingsType: SettingsType.chronologys,\n                useCase: 'current',\n            });\n            if ((chronologysSettings?.openChildTjpAddrs ?? []).length === 0) {\n                // first run\n                // do nothing\n                // this.showProjectInfoTab();\n            } else {\n                // not first run, so just reopen the old tabs\n                this.reopenOldTabs();\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    protected override async initSettings(): Promise<void> {\n        const lc = `${this.lc}[${this.initSettings.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: c84688efbfd822966623d738f3456825)`); }\n\n            // ensure the settings exists for this ibgib\n            await super.initSettings();\n            let chronologysSettings = await this.getSettings<Settings_Chronologys>({\n                settingsType: SettingsType.chronologys,\n                useCase: 'current',\n            });\n            if (chronologysSettings) {\n                if ((chronologysSettings as any).activeAddr) {\n                    // migrate\n                    const existing = chronologysSettings as any;\n\n                    chronologysSettings = await getDefaultSettings<Settings_Chronologys>({ settingsType: SettingsType.chronologys });\n                    chronologysSettings.activeChildTjpAddr = existing.activeAddr;\n                    chronologysSettings.openChildTjpAddrs = existing.openAddrs;\n                    await this.updateSettings<Settings_Chronologys>({\n                        settingsType: SettingsType.chronologys,\n                        useCase: 'current',\n                        newSectionInfo: chronologysSettings,\n                    });\n                }\n                // reload previously open chronology components\n\n                // this happens after initSettings in created() handler using\n                // reopenOldTabs method\n\n                // setTimeout(async () => {\n                //     if (chronologysSettings) {\n                //         for (const addr of chronologysSettings.openChildTjpAddrs) {\n                //             await this.openIbGibAddr({ ibGibAddr: addr });\n                //         }\n                //     } else {\n                //         debugger; // error?\n                //     }\n                // }, 100);\n            } else {\n                // first run\n                chronologysSettings = await getDefaultSettings<Settings_Chronologys>({ settingsType: SettingsType.chronologys });\n                chronologysSettings.activeChildTjpAddr = this.tjpAddr ?? this.ibGibAddr;\n                // chronologysSettings.openChildTjpAddrs = [this.ibGibAddr];\n                chronologysSettings.openChildTjpAddrs = [this.tjpAddr ?? this.ibGibAddr];\n                await this.updateSettings<Settings_Chronologys>({\n                    settingsType: SettingsType.chronologys,\n                    useCase: 'current',\n                    newSectionInfo: chronologysSettings,\n                });\n\n            }\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    override async disconnected(): Promise<void> {\n        const lc = `${this.lc}[${this.disconnected.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 615c03656d27356cda96ed4f5285d925)`); }\n            // no action atow\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * Loads the ibGib if only addr is provided.\n     *\n     * Then manages the UI:\n     *\n     * - If a tab is already created for the ibgib and active, then does nothing.\n     * - If it's already created but inactive, then activates tab and loads content\n     * - if no tab, then creates it, activates it, loads content.\n     *\n     * To do this, it creates/hydrates a {@link ChronologyTabInfo} and activates\n     * it.\n     *\n     * @see {@link ChildInfoBase.active}\n     * @see {@link activeChildInfo}\n     */\n    public override async activateIbGib({\n        addr,\n        ibGib,\n    }: {\n        addr?: IbGibAddr,\n        ibGib?: IbGib_V1,\n    }): Promise<void> {\n        const lc = `${this.lc}[${this.activateIbGib.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 65b042ad19c214f27189db1f26b60d25)`); }\n            const metaspace = this.metaspace ?? await getGlobalMetaspace_waitIfNeeded();\n            const space = await metaspace.getLocalUserSpace({ lock: false });\n            if (!space) { throw new Error(`(UNEXPECTED) couldnt get default local user space? (E: a6b75f4d02f82916282acc786d65a525)`); }\n            const spaceId = space.data!.uuid!;\n\n            const fn = async () => {\n                await super.activateIbGib({ addr, ibGib });\n\n                addr ??= getIbGibAddr({ ibGib });\n\n                // set the color of the\n\n                // debugger; // what is this value?\n                // terrible fng hack to get the tab to be the same color. I'm so\n                // tired\n                let borderColor: string | undefined = undefined;\n                let interval = setInterval(() => {\n                    borderColor = this.activeChildInfo?.component?.style.getPropertyValue('--tjp-color');\n                    if (borderColor) {\n                        this.activeChildInfo!.childBtnEl.style.borderColor = borderColor;\n                        clearInterval(interval);\n                    }\n                }, 100);\n\n                // set the input to correspond to the\n\n                const childTabInfo = await this.getLoadedChildInfo({ addr, ibGib });\n                if (!childTabInfo.component) { throw new Error(`(UNEXPECTED) childTabInfo.component falsy? (E: 4d0db9333908041bc862fbe84799f825)`); }\n                ibGib ??= childTabInfo.component.ibGib;\n\n                const appShellSvc = getAppShellSvc();\n                await appShellSvc.inputComponent!.setContextInfo({\n                    info: {\n                        agent: childTabInfo.agent,\n                        placeholderText: CHAT_WITH_AGENT_PLACEHOLDER_AGENT,\n                        contextProxyIbGib: childTabInfo.component.ibGibProxy,\n                        // default to default local user space for now\n                        spaceId,\n                    },\n                });\n\n                // update the opened child tab info's agent available functions.\n                // i'm not quite sure where to put this, but in this particular\n                // use case it needs to be here.\n\n                if (childTabInfo.agent) {\n                    if (!ibGib) {\n                        debugger; // chronologys activateIbGib ibGib falsy?\n                        throw new Error(`(UNEXPECTED) ibGib falsy? (E: eca328378f668c41b13f69a3f9250825)`);\n                    }\n                    // available functions\n                    if (isProjectIbGib_V1(ibGib!)) {\n                        await childTabInfo.agent.updateAvailableFunctions({\n                            availableFunctions: AGENT_AVAILABLE_FUNCTIONS_PROJECTAGENT,\n                        });\n                    } else {\n                        // this can't be right but ...\n                        await childTabInfo.agent.updateAvailableFunctions({\n                            availableFunctions: AGENT_AVAILABLE_FUNCTIONS_PROJECTCHILDTEXTAGENT,\n                        });\n                    }\n                } else {\n                    console.error(`${lc} not sure if it's an error, but childTabInfo.agent is falsy? well, we can't update its available functions (E: bb29b8d0271889ba78606828b531e225)`)\n                }\n\n            };\n\n            // instead of locking, i need to just change this to a\n            // most-recent-wins queue\n            await execInSpaceWithLocking({\n                fn,\n                scope: lc,\n                secondsValid: 30,\n                space,\n                callerInstanceId: this.instanceId,\n                maxDelayMs: 30_000,\n                maxLockAttempts: 1_000,\n            });\n\n            if (!ibGib) {\n                const resGet = await this.metaspace?.get({ addrs: [addr!], });\n                if (!resGet || resGet.errorMsg || (resGet.ibGibs ?? []).length !== 1) {\n                    throw new Error(`couldn't get addr (${addr}) from default local user space. wrong space? i need to figure out how I want the project space handled still (atow 06/2025) (E: 35cc487c5009b4628156573d47817425)`);\n                }\n                ibGib = resGet.ibGibs![0];\n            }\n            addr ??= getIbGibAddr({ ibGib });\n            const tjpAddr = getTjpAddr({ ibGib, defaultIfNone: 'incomingAddr' });\n            if (!tjpAddr) { throw new Error(`(UNEXPECTED) tjpAddr falsy? 'incomingAddr' was used as the default option. (E: fb8491546c48bc66f8d55e2a9e891325)`); }\n\n            if (this._reloadingTabs) {\n                // we are loading the current child ibgib tabs and we shouldn't\n                // do any updating tothe settings\n                console.log(`${lc} just loading ibgib, so nothing further to do here. returning early (I: 3e02683a9f19bc7fddb53068f1a79825)`)\n                return; /* <<<< returns early */\n            } else {\n                const chronologysSettings = await this.getSettings<Settings_Chronologys>({\n                    settingsType: SettingsType.chronologys,\n                    useCase: 'current',\n                });\n                if (!chronologysSettings) { throw new Error(`(UNEXPECTED) chronologysSettings falsy? (E: b66b0893bf4481d16bc4787573f36825)`); }\n\n                // we are NOT loading and we should persist this change to\n                // settings\n                let modified = false;\n                if (!chronologysSettings.openChildTjpAddrs.includes(tjpAddr)) {\n                    chronologysSettings.openChildTjpAddrs.push(tjpAddr);\n                    modified = true;\n                }\n                if (chronologysSettings.activeChildTjpAddr !== tjpAddr) {\n                    chronologysSettings.activeChildTjpAddr = tjpAddr;\n                    modified = true;\n                }\n                if (modified) {\n                    const sectionName_current = await getSectionName({\n                        settingsType: SettingsType.chronologys,\n                        useCase: 'current',\n                    });\n                    const _newSettings = await mut8Timeline({\n                        timeline: this.settings!.ibGib!,\n                        metaspace: this.metaspace!,\n                        mut8Opts: {\n                            dataToAddOrPatch: {\n                                sections: {\n                                    [sectionName_current]: chronologysSettings,\n                                }\n                            },\n                        },\n                    });\n                } else {\n                    console.warn(`${lc} already activated? should this get this far if we're clicking a tab that's already activated? (W: 4c6d98e8809813a4f8a2075b113cb325)`)\n                }\n\n\n            }\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    public async openIbGibAddr({ ibGibAddr }): Promise<void> {\n        const lc = `${this.lc}[${this.openIbGibAddr.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 2dc7ba5e8e3f9b6326d61dff666eec25)`); }\n            if (isPrimitive({ gib: getIbAndGib({ ibGibAddr }).gib })) {\n                await this.activateIbGib({\n                    addr: ibGibAddr,\n                });\n            } else {\n                await this.activateIbGib({\n                    addr: ibGibAddr,\n                });\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * @internal\n     * gets the project tab info for the given addr.\n     *\n     * creates and loads the project ibgib component, which itself loads the\n     * ibgib internally (or throws) if not already loaded.\n     *\n     * @returns ChronologyTabInfo with fully loaded component and ibgib.\n     *\n     * @see {@link ChronologyTabInfo}\n     */\n    protected override async getLoadedChildInfo({\n        addr,\n        ibGib,\n    }: {\n        addr: IbGibAddr,\n        ibGib?: IbGib_V1,\n    }): Promise<ChronologyTabInfo> {\n        const lc = `${this.lc}[${this.getLoadedChildInfo.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: a41937087adf2b3b132f48aa94326b25)`); }\n            if (!addr) { throw new Error(`(UNEXPECTED) addr falsy? (E: 9ce2130c766a09771678c59a3e4b0425)`); }\n\n            const fnCreateAndLoadChronologyComponent = async () => {\n                try {\n                    const componentSvc = await getComponentSvc();\n                    const component = await componentSvc.getComponentInstance({\n                        path: CHRONOLOGY_COMPONENT_NAME,\n                        ibGibAddr: addr,\n                        useRegExpPrefilter: true,\n                    }) as ChronologyComponentInstance | undefined;\n                    if (!component) {\n                        debugger; // error couldn't create component instance for project?\n                        throw new Error(`(UNEXPECTED) component falsy? couldn't create component instance for project? (E: abb22a24dc5cb5463ee3e454e69d3825)`);\n                    }\n                    await component.loadIbGib();\n                    if (!component.ibGib) {\n                        debugger; // error couldn't load ibGib for project?\n                        throw new Error(`(UNEXPECTED) ibGib falsy? couldn't load ibGib for project? (E: 6e6aea01eaa7b18b0fcec9cdc74ab825)`);\n                    }\n                    // guaranteed loaded ibGib\n                    return component;\n                } catch (error) {\n                    // debugger; // error in creating chronology component\n                    console.error(`${lc}[fnCreateAndLoadChronologyComponent] ${extractErrorMsg(error)}`);\n                    throw error;\n                }\n            }\n\n            /** the point of this function is to populate this */\n            let tabInfo: ChronologyTabInfo;\n\n            // first check to see if an existing tab matches by tjp\n            let gib = getIbAndGib({ ibGibAddr: addr }).gib;\n            let gibInfo = getGibInfo({ gib });\n            let tjpGib = gibInfo.tjpGib ?? gib;\n\n            function tabInfoSharesTjpGib(tabInfo: ChronologyTabInfo): boolean {\n                let tabGib = getIbAndGib({ ibGibAddr: tabInfo.addr }).gib;\n                let tabGibInfo = getGibInfo({ gib: tabGib });\n                let tabTjpGib = tabGibInfo.tjpGib ?? tabGib;\n                return tabTjpGib === tjpGib;\n            }\n\n            if (this.childInfos.some(x => tabInfoSharesTjpGib(x))) {\n                const filtered = this.childInfos.filter(x => tabInfoSharesTjpGib(x));\n                if (filtered.length !== 1) { throw new Error(`(UNEXPECTED) filtered.length !== 1? (E: d856b4526718cd20ff6037426694d325)`); }\n                tabInfo = filtered[0];\n                if (tabInfo.component) {\n                    // ? component is already created, do we need to do anything else?\n                } else {\n                    tabInfo.component = await fnCreateAndLoadChronologyComponent();\n                    // ibGib = tabInfo.component!.ibGib!;\n                }\n            } else {\n                // tab info does not exist, so create new tab info (requires new\n                // component and tab els)\n                const component = await fnCreateAndLoadChronologyComponent();\n                ibGib = component.ibGib!; // guaranteed in above fn\n\n                // both addr and ibGib guaranteed now\n                const childBtnEl = await this.addChild({ addr, ibGib })\n                tabInfo = {\n                    agent: component.agent,\n                    addr,\n                    childBtnEl,\n                    component,\n                    active: false,\n                };\n                this.childInfos.push(tabInfo);\n            }\n\n            return tabInfo;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * creates a new tab element (span atow 03/2025), adds it to the\n     * headerTabsEl and returns the new span element.\n     *\n     * @returns the newly created tab span element\n     */\n    protected override async addChild({\n        addr,\n        ibGib,\n    }: {\n        ibGib: IbGib_V1,\n        addr?: IbGibAddr,\n    }): Promise<HTMLElement> {\n        const lc = `${this.lc}[${this.addChild.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 4f1d5f010a59239ceeb2f2af255a9125)`); }\n\n            // #region init/validate\n            if (!this.elements) { throw new Error(`(UNEXPECTED) this.elements falsy? (E: 35fe84a0edbfef2ff12f886602006725)`); }\n            const { headerTabsEl } = this.elements;\n\n            addr ??= getIbGibAddr({ ibGib });\n            if (addr !== getIbGibAddr({ ibGib })) {\n                const addr_tjpGib =\n                    getGibInfo({ ibGibAddr: addr }).tjpGib ??\n                    getIbAndGib({ ibGibAddr: addr }).gib;\n                const ibGib_addr = getIbGibAddr({ ibGib });\n                const ibGib_tjpGib =\n                    getGibInfo({ ibGibAddr: ibGib_addr }).tjpGib ??\n                    getIbAndGib({ ibGibAddr: ibGib_addr }).gib;\n                if (addr_tjpGib === ibGib_tjpGib) {\n                    // same timeline, so ignore it\n                    addr = ibGib_addr;\n                } else {\n                    throw new Error(`(UNEXPECTED) addr !== getIbGibAddr({ibGib})? (${addr}) (${ibGib_addr}) (E: 4702e8b8e79292315b22574c9d063925)`);\n                }\n            }\n            const tjpAddr = getTjpAddr({ ibGib });\n            // #endregion init/validate\n\n            // create the tab button element\n            const childBtnEl = document.createElement('span');\n            childBtnEl.id = `chronologys-tab-button-${addr}`;\n            childBtnEl.classList.add('panel-tab-button');\n            // if (activate) { span.classList.add('active'); }\n            this.updateTabTitleAndText({ span: childBtnEl, ibGib });\n            const {\n                punctiliarColor,\n                punctiliarColorTranslucent,\n                tjpColor,\n                tjpColorTranslucent,\n                tjpColorContrast,\n                errorMsg\n            } = getDeterministicColorInfo({ ibGib, translucentAlpha: 10 });\n            if (!errorMsg) {\n\n                // let borderColor: string | undefined = undefined;\n                // let interval = setInterval(() => {\n                //     borderColor = this.activeChildInfo?.component?.style.getPropertyValue('--tjp-color');\n                //     if (borderColor) {\n                //         this.activeChildInfo!.childBtnEl.style.borderColor = borderColor;\n                //         clearInterval(interval);\n                //     }\n                // }, 100);\n\n                // happy birthday to me! (ty kelli). May the fifth be wifth you.\n\n                childBtnEl.style.borderColor =\n                    tjpColor ?? punctiliarColor;\n                childBtnEl.style.backgroundColor =\n                    tjpColor ?? punctiliarColor;\n                // debugger; // contrast color?\n                childBtnEl.style.color =\n                    tjpColorContrast ?? tjpColorTranslucent ?? punctiliarColorTranslucent;\n\n                // this.style.setProperty('--ibgib-color', punctiliarColor);\n                // this.style.setProperty('--ibgib-color-translucent', punctiliarColor);\n                // this.style.setProperty('--tjp-color', tjpColor ?? punctiliarColor);\n                // this.style.setProperty('--tjp-color-translucent', tjpColorTranslucent ?? punctiliarColorTranslucent);\n            } else {\n                // don't set anything\n                console.error(`${lc} ${errorMsg} (E: 05fb07200acd505238e35669d19cf225)`);\n            }\n\n            // add a close button to the tab button proper, if the tab is not\n            // our project tab Project tab is always open atow (06/2025) but\n            // this is just because I want to always have a tab open right now,\n            // as it simplifies early dev\n            if (tjpAddr !== this.tjpAddr) {\n                const closeBtnEl = document.createElement('span');\n                closeBtnEl.classList.add('close-tab-button');\n                closeBtnEl.textContent = '\u274C'; // or a Font Awesome icon\n                childBtnEl.appendChild(closeBtnEl);\n                closeBtnEl.addEventListener('click', async (event) => {\n                    event.stopPropagation(); // Prevent activating the tab\n                    await this.closeTab({ ibGib });\n                });\n            }\n\n            childBtnEl.addEventListener('click', async () => {\n                await this.openIbGibAddr({ ibGibAddr: addr, });\n            });\n\n            headerTabsEl.appendChild(childBtnEl);\n\n            if (!this.metaspace) { throw new Error(`(UNEXPECTED) this.metaspace falsy? (E: e9f0bfecb8880b9fb84b4dd95aafd825)`); }\n            if (!this.metaspace.latestObs) { throw new Error(`(UNEXPECTED) this.metaspace.latestObs falsy? (E: 71d7e8f0ee5c4b400811f0192a319825)`); }\n            await this.metaspace.latestObs?.subscribe(fnObs({\n                next: async (updateInfo: IbGibTimelineUpdateInfo) => {\n                    if (updateInfo.tjpAddr !== tjpAddr) { return; /* <<<< returns early */ }\n                    if (updateInfo.latestIbGib) {\n                        this.updateTabTitleAndText({ span: childBtnEl, ibGib: updateInfo.latestIbGib })\n                    } else {\n                        console.error(`{lc}[next] updateInfo.latestIbGib falsy? (E: a8558bdc53889ee07d8d78178328ae25)`);\n                    }\n                },\n                complete: async () => {\n                    console.warn(`${lc}[complete] completed executed? (W: a2df080a4f8ef87df5266888109dfe25)`);\n                },\n                error: async (error) => {\n                    debugger; // error in metaspace.latestObs dispatch?\n                    console.error(`${lc}[error] ${extractErrorMsg(error)}`);\n                },\n            }));\n\n            return childBtnEl;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    protected async removeTabBtn({ tabInfo, }: { tabInfo: ChronologyTabInfo; }): Promise<void> {\n        this.elements!.headerTabsEl!.removeChild(tabInfo.childBtnEl);\n    }\n\n    private updateTabTitleAndText({\n        span,\n        ibGib,\n    }: {\n        span: HTMLElement,\n        ibGib: IbGib_V1,\n    }): void {\n        const lc = `[${this.updateTabTitleAndText.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 2ceddea7093d27938127cb1fe2c3b225)`); }\n            const ibGibAddr = getIbGibAddr({ ibGib });\n\n            if (!ibGib.data) { throw new Error(`(UNEXPECTED) ibGib.data falsy? (E: a64e99f222f2ba84c8852ac8c263fa25)`); }\n            if (!ibGib.data.name) { console.warn(`${lc} ibGib.data.name falsy? (W: ab854c8f802179d84463f674e43fec25)`); }\n            let title: string;\n            if (!ibGib.data.name) {\n                // if (ibGib.ib.startsWith('comment --interactive')) {\n                if (simpleIbGibRouterSingleton.isCurrentPageWeb1) {\n                    // needs to change to look at router\n                    console.warn(`${lc} web1 chronologys tab btn title hack. (W: 292af18fc411b6176d8e23e49201ef25)`);\n                    title = 'Web1';\n                } else {\n                    title = 'untitled';\n                }\n            } else {\n                title = ibGib.data.name;\n            }\n            const desc = ibGib.data.description ?? '';\n            span.title = desc ? `${title}\\n${desc}` : title;\n            const MAX_TAB_TEXT_LENGTH = 12;\n            span.textContent = getSaferSubstring({ text: title, length: MAX_TAB_TEXT_LENGTH, });\n            if (title.length > MAX_TAB_TEXT_LENGTH) {\n                span.textContent += '\u2026';\n            }\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private async activateTab({\n        addr,\n        tabSpan,\n    }: {\n        addr: IbGibAddr,\n        tabSpan: HTMLSpanElement,\n    }): Promise<void> {\n        const lc = `${this.lc}[${this.activateTab.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: e6d0420eb8e31a486859edbf02f97625)`); }\n            // if (!this.elementsheaderEl) { throw new Error(`(UNEXPECTED) this.headerEl falsy? (E: cbba6780bb44f801233a7bcf19e4bf25)`); }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    async initElements(): Promise<void> {\n        const lc = `${this.lc}[${this.initElements.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 305745140004d907e7174bf10ea1bc25)`); }\n\n            if (!this.shadowRoot) { throw new Error(`(UNEXPECTED) this.shadowRoot falsy? (E: ddbff9ccd2ddb1b281ec9797786cf825)`); }\n\n            const headerEl = shadowRoot_getElementById(this.shadowRoot, 'chronologys-header');\n\n            const busyEl = shadowRoot_getElementById(this.shadowRoot, 'chronologys-header-busy-indicator')\n\n            // headerTabsEl\n            const headerTabsEl = this.shadowRoot.getElementById('chronologys-header-tabs') as HTMLElement;\n            if (!headerTabsEl) { throw new Error(`(UNEXPECTED) headerTabsEl not found in this.shadowRoot? (E: d5b7651c724d017532777f5dc096da25)`); }\n\n            const contentEl = this.shadowRoot.getElementById('chronologys-content') as HTMLElement;\n            if (!contentEl) { throw new Error(`(UNEXPECTED) contentEl not found in this.shadowRoot? (E: 5acf36fbd068fd00ae1a7a1abad5c825)`); }\n            const pContent = document.createElement('p');\n            pContent.textContent = '[no project loaded...try creating one]';\n            // pContent.style.lineHeight = `${contentEl.clientHeight}px`;\n            pContent.style.textAlign = 'center';\n            pContent.style.fontStyle = 'italic';\n            contentEl.appendChild(pContent);\n\n            const footerEl = this.shadowRoot.getElementById('chronologys-footer') as HTMLElement;\n            if (!footerEl) { throw new Error(`(UNEXPECTED) footerEl not found in this.shadowRoot? (E: dd2f3f2e1ce805c3f69a4abebc710425)`); }\n            footerEl.style.display = 'none';\n\n            this.elements = {\n                headerEl, headerTabsEl,\n                contentEl,\n                footerEl,\n                busyEl,\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    protected override async initAgents(): Promise<void> {\n        const lc = `${this.lc}[${this.initAgents.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 2f680c5b3bc502d816b2e13d964d5125)`); }\n            // if (!this.elements) { throw new Error(`(UNEXPECTED) this.elements falsy? (E: 9fca9ad8cb57caeb495f872b58232625)`); }\n            // const {} = this.elements;\n\n            this.metaspace = await getGlobalMetaspace_waitIfNeeded();\n\n            let agent: AgentWitnessAny | undefined = undefined;\n            let agents = await getAgents({\n                metaspace: this.metaspace,\n                type: AGENT_SPECIAL_IBGIB_TYPE_CHRONOLOGYSAGENT,\n                spaceId: undefined, // explicitly use default local space just to show this option bc it's early in life\n            });\n            if (agents.length > 0) {\n                agent = agents.at(0)!;\n            } else {\n                const agentsSvc = getAgentsSvc();\n                agent = await agentsSvc.createNewAgent({\n                    metaspace: this.metaspace,\n                    superSpace: undefined, // uses default local user space as the super space\n                    name: `ChronologysAgent-${this.instanceId}`,\n                    api: 'gemini',\n                    model: GEMINI_DEFAULT_MODEL_STR,\n                    availableFunctions: [\n                        ...AGENT_AVAILABLE_FUNCTIONS_CHRONOLOGYSAGENT,\n                    ],\n                    initialSystemText: [\n                        AGENT_INITIAL_SYSTEM_TEXT_CHRONOLOGYSAGENT,\n                    ].join('\\n'),\n                    initialChatText: [\n                        AGENT_INITIAL_CHAT_HI_PLEASEINTRO_YOURSELF,\n                    ].join('\\n'),\n                    // fnGetAPIKey: this.getFnGetAPIKey(),\n                    fnGetAPIKey: getDefaultFnGetAPIKey(),\n                    type: AGENT_SPECIAL_IBGIB_TYPE_CHRONOLOGYSAGENT,\n                    addToAgentsTag: true,\n                });\n            }\n\n            this.agents = [agent];\n\n            if (!this.agent) {\n                debugger; // do we care?\n                console.error(`(UNEXPECTED) agent falsy after createNewAgent? just logging error, no throw. (E: b6954a552e23ed83421c45f9ed781c25)`);\n                // throw new Error(`(UNEXPECTED) agent falsy after createNewAgent? (E: b6954a552e23ed83421c45f9ed781c25)`);\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    protected override async renderUI_busy(): Promise<void> {\n        const lc = `${this.lc}[${this.renderUI_busy.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 8a23e88fc1d4294f98d1cf0552d41825)`); }\n            if (!this.elements) { throw new Error(`(UNEXPECTED) this.elements falsy? (E: 7d67d87197b8f38548670b48a4c4f525)`); }\n            const { busyEl } = this.elements;\n            if (!busyEl) { throw new Error(`(UNEXPECTED) busyEl falsy? (E: 48c488350a588ecbe8309c05df8b7825)`); }\n            if (this.isBusy) {\n                busyEl.style.display = 'flex';\n            } else {\n                busyEl.style.display = 'none';\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n}\n", "<div id=\"projects-explorer-component\" class=\"\">\n    <!-- have these both as panel-header just as a kluge to get the tabs to look\n    decent without bigger rewrite/investigation -->\n    <div id=\"projects-explorer-header\" class=\"projects-explorer-header panel-header\">\n        <h3>\uD83D\uDEA7WIP\uD83D\uDEA7</h3>\n    </div>\n\n    <div id=\"projects-explorer-content\">\n        <ul>\n            <li><a href=\"#/apps/web1/gib/about-projects.html\">\u24D8 About Projects</a></li>\n            <li><a href=\"#/apps/projects/gib/projects\">new \"project\"</a></li>\n        </ul>\n        <input id=\"project-list-filter\" placeholder=\"\uD83D\uDD0D...\" />\n        <ul id=\"project-list\" class=\"project-list\">\n            <!-- This is just a stub of a content for a project list -->\n            <!-- Project/Agent list items -->\n            <!-- <li><a href=\"#/apps/web1/gib/about-projects.html\">\u24D8 About Projects</a></li>\n              <li><a href=\"#/apps/projects/gib/projects\">new \"project\"</a></li> -->\n            <!-- <li><a href=\"#/apps/projects/gib/canvas\">ai canvas playground</a></li> -->\n        </ul>\n\n        <!-- todo: insert projects-explorer-content depending on which tab is active -->\n        <!-- <canvas id=\"ibgib-canvas\" width=\"1000\" height=\"1000\"></canvas> -->\n\n    </div>\n\n    <div id=\"projects-explorer-footer\">\n    </div>\n</div>\n", "/* :host { */\n/* this is used for styling ibgib components for multi-view coordination, so\n     * that ibgib views that are looking at the same ibgib can be visibly shown\n     * as doing so. */\n/* --ibgib-border-color: #00ccff; */\n/* } */\n\n#projects-explorer-component {\n    --footer-panel-background-color: var(--button-background-color);\n    --footer-panel-border-color: var(--button-border-color);\n    --footer-panel-border-radius: 4px;\n\n    /* debug add border style */\n    border-width: 2px;\n    border-color: var(--primary-border-color-dark);\n    border-style: solid;\n    border-radius: 2px;\n    padding: 1%;\n\n    display: flex;\n    flex-direction: column;\n    width: 100%;\n    height: 100%;\n    box-sizing: border-box;\n\n    #projects-explorer-header {\n        height: 5%;\n        overflow: hidden;\n        /* flex-shrink: initial; */\n\n        button {\n            width: auto;\n            height: 75%;\n            aspect-ratio: 1/1 !important;\n\n        }\n\n        button:hover {\n            /* cursor: pointer; */\n            /* border-color: var(--button-hover-border-color); */\n            border-width: 2px;\n        }\n\n\n        /* Add back the relative container for the button and popover */\n        .add-button-container,\n        .ellipsis-button-container {\n            background-color: transparent;\n            /* position: relative;\n                display: inline-block; */\n        }\n\n        /* Keep the styles for the popover options */\n        .add-popover-option,\n        .ellipsis-popover-option {\n            padding: 8px 15px;\n            margin-bottom: 2px;\n            cursor: pointer;\n            transition: background-color 0.2s ease;\n            background-color: var(--tab-background-color);\n            color: var(--tab-text-color);\n        }\n\n        /* Keep the styles for the popover options */\n        .add-popover-option:hover,\n        .ellipsis-popover-option:hover {\n            /* color: var(--tjp-color-contrast, #f0f0f0); */\n            color: contrast-color(var(--tjp-color, #f0f0f0));\n            background-color: var(--tjp-color, #f0f0f0);\n        }\n\n        /* Use anchor() for positioning */\n        .add-popover,\n        .ellipsis-popover {\n            /* bottom: anchor(top); */\n            /* Position the bottom of the popover at the top of the anchor */\n            /* left: anchor(left); */\n            /* Align the left of the popover with the left of the anchor */\n            flex-direction: column;\n            margin: 0px;\n            /* padding: 5px 0; */\n            border-radius: var(--border-radius, 4px);\n            background-color: var(--background-color, #fff);\n            border: 1px solid var(--border-color, #ccc);\n            box-shadow: var(--box-shadow, 0 2px 5px rgba(0, 0, 0, 0.2));\n            z-index: 10;\n            /* Ensure it appears above other content */\n        }\n    }\n\n    #projects-explorer-content {\n        display: flex;\n        flex-direction: column;\n        height: 95%;\n        width: 100%;\n        align-items: stretch;\n        overflow: auto;\n\n\n        #project-list-filter {\n            width: 90%;\n            align-self: center;\n        }\n\n        /* overflow-y: auto; */\n        #project-list {\n            display: flex;\n            flex-direction: column;\n\n            padding: 2px 2px 2px 5px;\n\n            li:not(:first-child) {\n                margin-top: 3px;\n            }\n\n        }\n    }\n\n    #projects-explorer-footer {\n        display: none;\n    }\n}\n", "<div id=\"explorer-item-component\" class=\"\">\n    <!-- have these both as panel-header just as a kluge to get the tabs to look\n    decent without bigger rewrite/investigation -->\n    <div id=\"explorer-item-header\" class=\"explorer-item-header panel-header\" style=\"display: none\">\n    </div>\n\n    <div id=\"explorer-item-content\">\n        <p id=\"explorer-item-name\">[loading...]</p>\n    </div>\n\n    <div id=\"explorer-item-footer\" class=\"explorer-item-footer\" style=\"display: none\">\n    </div>\n</div>\n", ":host {\n    /* this is used for styling ibgib components for multi-view coordination, so\n     * that ibgib views that are looking at the same ibgib can be visibly shown\n     * as doing so. */\n    --ibgib-color: #ff00dd;\n    --ibgib-color-translucent: #ff00dd10;\n    --tjp-color: #00ffae;\n    --tjp-color-translucent: #00ffae10;\n    /* hardcoded tmp */\n    border-radius: 25px;\n    cursor: pointer;\n}\n\n/* Basic layout and styling for the explorer-item component */\n#explorer-item-component {\n    display: flex;\n    flex-direction: column;\n    align-items: stretch;\n    width: 100%;\n    height: 100%;\n    overflow: auto;\n    box-sizing: border-box;\n    /* Use consistent padding */\n    padding: 1%;\n\n    /* ibgib styling */\n    border: var(--tjp-color) 5px solid;\n    box-shadow: 0 0 10px var(--tjp-color);\n    border-radius: 5px;\n\n    /* Optional: If using flexbox to control vertical alignment */\n    /* justify-content: center;  Align content vertically */\n\n    #explorer-item-header {\n        display: flex;\n        flex-direction: column;\n\n\n    }\n\n    #explorer-item-content {\n\n        #explorer-item-name {\n            font-weight: bold;\n            margin: 0;\n            /* font-size: larger; */\n            /* Use variables for spacing? */\n            /* margin-bottom: 0.5em; */\n        }\n\n    }\n\n\n}\n", "import thisHtml from './explorer-item.html';\nimport thisCss from './explorer-item.css';\nimport stylesCss from '../../../styles.css';\nimport rootCss from '../../../root.css';\n\nimport { extractErrorMsg, } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { IbGib_V1 } from \"@ibgib/ts-gib/dist/V1/types.mjs\";\nimport { IbGibAddr, } from \"@ibgib/ts-gib/dist/types.mjs\";\nimport { MetaspaceService } from \"@ibgib/core-gib/dist/witness/space/metaspace/metaspace-types.mjs\";\nimport { tellUserFunctionInfo } from '@ibgib/web-gib/dist/api/commands/chat/tell-user.mjs';\nimport { helloWorldFunctionInfo } from '@ibgib/web-gib/dist/api/commands/chat/hello-world.mjs';\nimport { alertUser, highlightElement, promptForConfirm, promptForText, shadowRoot_getElementById, } from \"@ibgib/web-gib/dist/helpers.web.mjs\";\nimport { getGlobalMetaspace_waitIfNeeded, } from \"@ibgib/web-gib/dist/helpers.mjs\";\nimport { IbGibDynamicComponentInstanceBase, IbGibDynamicComponentMetaBase } from \"@ibgib/web-gib/dist/ui/component/ibgib-dynamic-component-bases.mjs\";\nimport { ElementsBase, IbGibDynamicComponentInstance, IbGibDynamicComponentInstanceInitOpts, } from \"@ibgib/web-gib/dist/ui/component/component-types.mjs\";\n\nimport {\n    GLOBAL_LOG_A_LOT,\n    // ARMY_STORE, BEE_KEY, BLANK_GIB_DB_NAME,\n} from \"../../../constants.mjs\";\nimport { getPath } from \"../../../ui/router/router-one-file.mjs\";\nimport { getComponentCtorArg } from '../../../helpers.web.mjs';\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\nexport const AGENT_SPECIAL_IBGIB_TYPE_EXPLORERITEMAGENT = 'exploreritemagent';\nexport const CHAT_WITH_AGENT_PLACEHOLDER_EXPLORERITEMAGENT = '';\nexport const AGENT_AVAILABLE_FUNCTIONS_EXPLORERITEMAGENT = [\n    helloWorldFunctionInfo,\n    tellUserFunctionInfo,\n];\n\nexport const EXPLORERITEM_COMPONENT_NAME: string = 'ibgib-explorer-item';\n\nexport class ExplorerItemComponentMeta extends IbGibDynamicComponentMetaBase {\n    protected override lc: string = `[${ExplorerItemComponentMeta.name}]`;\n\n    /**\n     * temporary regexp path for our initial dev. this component will become\n     * attached to actual ib^gib addrs\n     */\n    routeRegExp?: RegExp = new RegExp(EXPLORERITEM_COMPONENT_NAME);\n    // routeRegExp?: RegExp = /apps\\/web1\\/gib\\/contact.html/;\n\n    componentName: string = EXPLORERITEM_COMPONENT_NAME;\n\n    constructor() {\n        super(getComponentCtorArg());\n        customElements.define(this.componentName, ExplorerItemComponentInstance);\n    }\n\n    async createInstance({\n        path,\n        ibGibAddr\n    }: {\n        path: string;\n        ibGibAddr: IbGibAddr;\n    }): Promise<IbGibDynamicComponentInstance> {\n        const lc = `${this.lc}[${this.createInstance.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n            const component = document.createElement(this.componentName) as ExplorerItemComponentInstance;\n            await component.initialize({\n                ibGibAddr,\n                meta: this,\n                html: thisHtml,\n                css: [rootCss, stylesCss, thisCss],\n            });\n            return component;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n}\n\ninterface ExplorerItemElements {\n    headerEl: HTMLElement;\n    // headerTabsEl: HTMLElement | undefined;\n    nameEl: HTMLElement;\n    /**\n     * container element for the component\n     */\n    contentEl: HTMLElement;\n    footerEl: HTMLElement;\n}\n\n\nexport class ExplorerItemComponentInstance\n    extends IbGibDynamicComponentInstanceBase<IbGib_V1, ExplorerItemElements>\n    implements IbGibDynamicComponentInstance<IbGib_V1, ExplorerItemElements> {\n    protected override lc: string = `[${ExplorerItemComponentInstance.name}]`;\n\n    metaspace: MetaspaceService | undefined;\n\n    linkEl: HTMLElement | undefined;\n\n    constructor() {\n        super();\n    }\n\n    override async initialize(opts: IbGibDynamicComponentInstanceInitOpts): Promise<void> {\n        const lc = `${this.lc}[${this.initialize.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n            await super.initialize(opts);\n            await this.loadIbGib({ getLatest: true });\n            this.metaspace = await getGlobalMetaspace_waitIfNeeded();\n            this.agentsInitialized = this.initAgents();\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    override async created(): Promise<void> {\n        const lc = `${this.lc}[${this.created.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n\n            // const { meta, htmlPath, scriptPaths, cssPaths } = opts;\n\n            // at this point, this.ibGib should be loaded with the latest ibgib\n            if (!this.ibGib) { throw new Error(`(UNEXPECTED) this.ibGib falsy? It is assumed at this point that we have a valid ibGib to work with. (E: genuuid)`); }\n\n            await this.initElements();\n            await this.agentsInitialized;\n            await this.renderUI();\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    override async handleContextUpdated(): Promise<void> {\n        const lc = `${this.lc}[${this.handleContextUpdated.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n            await super.handleContextUpdated();\n            await this.renderUI();\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private async initElements(): Promise<void> {\n        const lc = `${this.lc}[${this.initElements.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n\n            const shadowRoot = this.shadowRoot;\n\n            if (!shadowRoot) { throw new Error(`(UNEXPECTED) shadowRoot falsy? (E: genuuid)`); }\n\n            // #region header\n\n            const headerEl = shadowRoot_getElementById(shadowRoot, 'explorer-item-header') as HTMLElement;\n\n            // #endregion header\n\n            const contentEl = shadowRoot_getElementById(shadowRoot, 'explorer-item-content');\n            const nameEl = shadowRoot_getElementById<HTMLHeadingElement>(shadowRoot, 'explorer-item-name');\n\n            const footerEl = shadowRoot_getElementById(shadowRoot, 'explorer-item-footer');\n            footerEl.style.display = 'none';\n\n            this.elements = {\n                headerEl,\n                contentEl,\n                footerEl,\n                nameEl,\n            };\n\n            // click anywhere on this component should go to the link (atow anyway 07/2025)\n            shadowRoot.addEventListener('click', async (e: Event) => {\n                if (e.target && !(e.target instanceof HTMLAnchorElement)) {\n                    e.preventDefault();\n                    e.stopImmediatePropagation();\n                    e.stopPropagation();\n                    if (this.linkEl) { this.linkEl.click(); }\n                }\n            });\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * rerender\n     */\n    protected override async renderUI(): Promise<void> {\n        const lc = `${this.lc}[${this.renderUI.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n\n            await super.renderUI();\n\n            if (!this.ibGib) {\n                console.error(`${lc} this.ibGib falsy? (E: genuuid)`)\n                return; /* <<<< returns early */\n            }\n            if (!this.ibGib.data) {\n                console.error(`${lc} this.ibGib.data falsy? (E: genuuid)`)\n                return; /* <<<< returns early */\n            }\n            const { ibGib } = this;\n            const { ib, gib, data } = this.ibGib;\n            if (!gib) { throw new Error(`(UNEXPECTED) gib falsy? (E: fc04c25e0f59a98fb8b7832c92b1fc25)`); }\n\n            if (!this.elements) {\n                console.warn(`${lc} (UNEXPECTED) tried to render but haven't initialized elements? (W: genuuid)`);\n                return; /* <<<< returns early */\n            }\n\n            const {\n                headerEl,\n                contentEl,\n                footerEl,\n                nameEl,\n            } = this.elements;\n\n            // prepare the name element (container)\n            nameEl.innerHTML = '';\n\n            // build up the data for the name\n            const name = data.name ?? ibGib.ib;\n            const maxLength = 16;\n            const shortenedName = name.length > maxLength ?\n                name.substring(0, maxLength).concat('\u2026') :\n                name;\n            const labelText = `${shortenedName} (v${data.n ?? '?'})`;\n            const title = [\n                name,\n                `version: ${data.n ?? '?'}`,\n                data.description ?? '[no description]',\n                `id: ${data.uuid ?? '[no uuid]'}`\n            ].join('\\n');\n\n            // build a link to the item...this is hard-coding\n            const link = document.createElement('a');\n            this.linkEl = link;\n            link.href = getPath({\n                ibGibRouteInfo: {\n                    base: 'apps',\n                    appName: 'projects',\n                    ib,\n                    gib,\n                }\n            });\n            link.textContent = labelText;\n            link.title = title;\n\n            // add the link to the name container\n            nameEl.appendChild(link);\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    override async disconnected(): Promise<void> {\n        const lc = `${this.lc}[${this.disconnected.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n            // no action atow\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    protected override async initAgents(): Promise<void> {\n        const lc = `${this.lc}[${this.initAgents.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n\n            // do nothing\n\n            await this.loadAgentsCoupledToIbGib({ dontThrowIfNone: true });\n\n            // if (!this.agent) { throw new Error(`(UNEXPECTED) agent falsy after createNewAgent? (E: genuuid)`); }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n}\n", "import thisHtml from './projects-explorer.html';\nimport thisCss from './projects-explorer.css';\nimport stylesCss from '../../../styles.css';\nimport rootCss from '../../../root.css';\n\nimport { extractErrorMsg, getSaferSubstring, } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { IbGibAddr } from \"@ibgib/ts-gib/dist/types.mjs\";\nimport { IbGib_V1 } from \"@ibgib/ts-gib/dist/V1/types.mjs\";\nimport { getIbAndGib, getIbGibAddr } from \"@ibgib/ts-gib/dist/helper.mjs\";\nimport { getGibInfo, } from \"@ibgib/ts-gib/dist/V1/transforms/transform-helper.mjs\";\nimport { MetaspaceService } from \"@ibgib/core-gib/dist/witness/space/metaspace/metaspace-types.mjs\";\nimport { fnObs } from \"@ibgib/core-gib/dist/common/pubsub/observer/observer-helper.mjs\";\nimport { IbGibTimelineUpdateInfo } from \"@ibgib/core-gib/dist/common/other/other-types.mjs\";\nimport { getTjpAddr } from \"@ibgib/core-gib/dist/common/other/ibgib-helper.mjs\";\nimport { AgentWitnessAny, } from \"@ibgib/web-gib/dist/witness/agent/agent-one-file.mjs\";\nimport {\n    getDeterministicColorInfo,\n    getColorStrings,\n} from \"@ibgib/web-gib/dist/helpers.mjs\";\nimport {\n    alertUser, copyToClipboard,\n    highlightElement,\n    shadowRoot_getElementById,\n} from \"@ibgib/web-gib/dist/helpers.web.mjs\";\nimport { GEMINI_DEFAULT_MODEL_STR, } from \"@ibgib/web-gib/dist/witness/agent/gemini/gemini-constants.mjs\";\nimport { tellUserFunctionInfo } from \"@ibgib/web-gib/dist/api/commands/chat/tell-user.mjs\";\nimport { getProjects, parseProjectIb, } from \"@ibgib/web-gib/dist/common/project/project-helper.mjs\";\nimport { getAgentsSvc } from \"@ibgib/web-gib/dist/witness/agent/agents-service-v1.mjs\";\nimport {\n    IbGibDynamicComponentInstanceBase_ParentOfTabs,\n    IbGibDynamicComponentMetaBase,\n} from \"@ibgib/web-gib/dist/ui/component/ibgib-dynamic-component-bases.mjs\";\nimport {\n    ElementsBase, IbGibDynamicComponentInstance,\n    IbGibDynamicComponentInstanceInitOpts, ChildInfoBase,\n} from \"@ibgib/web-gib/dist/ui/component/component-types.mjs\";\nimport { getComponentSvc } from \"@ibgib/web-gib/dist/ui/component/ibgib-component-service.mjs\";\nimport { getAgents } from \"@ibgib/web-gib/dist/witness/agent/agent-helpers.mjs\";\nimport { debounce, getGlobalMetaspace_waitIfNeeded } from \"@ibgib/web-gib/dist/helpers.mjs\";\nimport { IbGibSettings, SettingsWithTabs } from \"@ibgib/web-gib/dist/common/settings/settings-types.mjs\";\nimport { SettingsType } from \"@ibgib/web-gib/dist/common/settings/settings-constants.mjs\";\n\nimport { GLOBAL_LOG_A_LOT, } from \"../../../constants.mjs\";\nimport {\n    AGENT_INITIAL_CHAT_TEXT_PROJECTSAGENT,\n    AGENT_INITIAL_SYSTEM_TEXT_PROJECTSAGENT\n} from \"../../../agent-texts/projects-agent-texts.mjs\";\nimport { EXPLORERITEM_COMPONENT_NAME, ExplorerItemComponentInstance } from \"../../common/explorer-item/explorer-item-component-one-file.mjs\";\nimport { getComponentCtorArg, getDefaultFnGetAPIKey, getIbGibGlobalThis_BlankGib } from '../../../helpers.web.mjs';\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\nexport const AGENT_SPECIAL_IBGIB_TYPE_PROJECTSAGENT = 'projectsagent';\nexport const AGENT_AVAILABLE_FUNCTIONS_PROJECTSAGENT = [\n    tellUserFunctionInfo,\n    // ...RenderAgentFunctionInfos,\n];\n\nexport const PROJECTS_EXPLORER_COMPONENT_NAME: string = 'ibgib-projects-explorer';\n\nexport class ProjectsExplorerComponentMeta extends IbGibDynamicComponentMetaBase {\n    protected override lc: string = `[${ProjectsExplorerComponentMeta.name}]`;\n\n    /**\n     * temporary regexp path for our initial dev. this component will become\n     * attached to actual ib^gib addrs\n     *\n     *\n     * either the path is\n     *   * /apps/projects/gib/projects\n     *   * /apps/projects/ABC123.456DEF/project%20my-project%201744553032000\n     *\n     * The point is that it's either a bland projects^gib to indicate create a\n     * new project or it's a valid gib and a valid project ib. lazy regexp here\n     */\n    // routeRegExp?: RegExp = /apps\\/projects\\/(gib|.*)\\/(projects|project \\/.*\\/.*)?/;\n    routeRegExp?: RegExp = new RegExp(`^${PROJECTS_EXPLORER_COMPONENT_NAME}$`);\n\n    componentName: string = PROJECTS_EXPLORER_COMPONENT_NAME;\n\n    constructor() {\n        super(getComponentCtorArg());\n        customElements.define(this.componentName, ProjectsExplorerComponentInstance);\n    }\n\n    async createInstance({\n        path,\n        ibGibAddr\n    }: {\n        /**\n         * todo: store this in the instance (i think) but will change this when needed\n         */\n        path: string;\n        ibGibAddr: IbGibAddr;\n    }): Promise<IbGibDynamicComponentInstance> {\n        const lc = `${this.lc}[${this.createInstance.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 75ddd5c933420026d8129cf5dfb5e825)`); }\n            const component = document.createElement(this.componentName) as ProjectsExplorerComponentInstance;\n            await component.initialize({\n                ibGibAddr,\n                meta: this,\n                html: thisHtml,\n                css: [rootCss, stylesCss, thisCss],\n            });\n            return component;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n}\n\n/**\n * helper interface for managing tabs and their associated ibgibs\n */\ninterface ProjectChildInfo extends ChildInfoBase<ExplorerItemComponentInstance> {\n    // tabBtnEl: HTMLElement;\n    // addr: IbGibAddr;\n    /**\n     * access the ibGib via this component.\n     *\n     * This component wraps an ibgib proxy that automatically stays up-to-date\n     * when new ibgib frames are added to the ibgib's timeline and published to\n     * the metaspace. (via metaspace.registerNewIbGib)\n     */\n    // projectComponent?: ExplorerItemComponentInstance;\n    // agent?: AgentWitnessAny;\n    // active: boolean;\n}\n\ninterface ProjectsExplorerElements extends ElementsBase {\n    headerEl: HTMLElement;\n    // headerTabsEl: HTMLElement;\n    projectListEl: HTMLElement;\n    projectListFilterEl: HTMLInputElement;\n    footerEl: HTMLElement;\n    // addBtnEl: HTMLButtonElement;\n    // ellipsisBtnEl: HTMLElement;\n    // ellipsisPopoverEl: HTMLElement;\n}\n\nexport class ProjectsExplorerComponentInstance\n    extends IbGibDynamicComponentInstanceBase_ParentOfTabs<IbGibSettings & SettingsWithTabs, IbGib_V1, ProjectsExplorerElements, ProjectChildInfo>\n    implements IbGibDynamicComponentInstance<IbGib_V1, ProjectsExplorerElements> {\n\n    protected override lc: string = `[${ProjectsExplorerComponentInstance.name}]`;\n    private projectListFilterText: string = '';\n\n    // projectTabInfos: ProjectChildInfo[] = [];\n    get activeProjectTabInfo(): ProjectChildInfo | undefined {\n        return this.childInfos.find(x => x.active);\n    }\n\n    metaspace: MetaspaceService | undefined;\n\n    protected get settingsType(): SettingsType {\n        return SettingsType.projectsExplorer;\n    }\n\n    constructor() {\n        super();\n    }\n\n    override async initialize(opts: IbGibDynamicComponentInstanceInitOpts): Promise<void> {\n        const lc = `${this.lc}[${this.initialize.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: efee75e15accb11b99113dd84aa91e25)`); }\n            // before any initialization, we want to ensure we are bootstrapped\n            // await getIbGibGlobalThis_BlankGib().bootstrapPromise; // this is in the super call now\n\n            if (!this.metaspace) {\n                // wait for the metaspace to be initialized\n                this.metaspace = await getGlobalMetaspace_waitIfNeeded({ delayIntervalMs: 50 });\n            }\n\n            // opts.ibGibAddr = await this.metaspace.getLatestAddr({ addr: opts.ibGibAddr }) ?? opts.ibGibAddr;\n\n            await super.initialize(opts);\n            this.agentsInitialized = this.initAgents(); // spins off\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    override async created(): Promise<void> {\n        const lc = `${this.lc}[${this.created.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: dbda48643e911488a96ccbc803111825)`); }\n\n            // const { meta, htmlPath, scriptPaths, cssPaths } = opts;\n            // does nothing atow\n            await this.initElements();\n            if (!this.elements) { throw new Error(`(UNEXPECTED) just initElements but this.elements falsy? (E: 322ce753a848fce61bef88f8bf724825)`); }\n\n            const { } = this.elements;\n\n\n            await this.agentsInitialized;\n\n            const globalBlankGib = getIbGibGlobalThis_BlankGib();\n            globalBlankGib.projectsExplorerComponent = this;\n\n            // setTimeout(() => { });\n            await this.renderUI();\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    override async disconnected(): Promise<void> {\n        const lc = `${this.lc}[${this.disconnected.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 4aa68862ac656ae6b540ed98e824e325)`); }\n            // no action atow\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n\n    protected override async renderUI(): Promise<void> {\n        const lc = `${this.lc}[${this.renderUI.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 8371d8c58d883becd8cacbd88ae07c25)`); }\n\n            await this.renderUI_projectList();\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n\n    protected async renderUI_projectList(): Promise<void> {\n        const lc = `${this.lc}[${this.renderUI_projectList.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n\n            if (!this.shadowRoot) { throw new Error(`(UNEXPECTED) this.shadowRoot falsy? (E: genuuid)`); }\n            const { shadowRoot } = this;\n            if (!this.metaspace) { throw new Error(`(UNEXPECTED) this.metaspace falsy? (E: genuuid)`); }\n\n\n            const projectList = shadowRoot_getElementById(shadowRoot, 'project-list');\n            projectList.innerHTML = '';\n\n            const addedGibs: string[] = [];\n\n            const projectIbGibs = await getProjects({ metaspace: this.metaspace });\n            for (const projectIbGib of projectIbGibs) {\n                const projectAddr = getIbGibAddr({ ibGib: projectIbGib });\n                const { ib: projectIb, gib: projectGib } =\n                    getIbAndGib({ ibGibAddr: projectAddr });\n                let projectName = parseProjectIb({ ib: projectIb }).safeName;\n                if (!projectName) {\n                    console.warn(`${lc} projectName falsy? changed project ib format? (W: genuuid)`)\n                    projectName = projectIb;\n                }\n\n                // skip adding this project if it's filtered out\n                let filterOut =\n                    (!!this.projectListFilterText &&\n                        !projectName.toLowerCase().includes(this.projectListFilterText.toLowerCase()))\n                    || addedGibs.includes(projectGib)\n                    ;\n\n                if (!filterOut) {\n                    addedGibs.push(projectGib);\n                    const liProject = document.createElement('li');\n                    const componentSvc = await getComponentSvc();\n                    const itemComponent = await componentSvc.getComponentInstance({\n                        useRegExpPrefilter: true,\n                        path: EXPLORERITEM_COMPONENT_NAME,\n                        ibGibAddr: projectAddr,\n                    }) as ExplorerItemComponentInstance;\n\n                    await componentSvc.inject({\n                        parentEl: liProject,\n                        componentToInject: itemComponent,\n                    });\n                    projectList.appendChild(liProject);\n                } else {\n                    if (logalot) { console.log(`${lc} case-insensitive filtered out ${projectName} with filter ${this.projectListFilterText} (I: genuuid)`); }\n                }\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n\n    }\n\n    public override async activateIbGib({ addr, ibGib, }: { addr?: IbGibAddr; ibGib?: IbGib_V1; }): Promise<void> {\n        const lc = `${this.lc}[${this.activateIbGib.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 4a03e843bf98c3fa382e6a8598dec825)`); }\n            if (!this.metaspace) { debugger; throw new Error(`(UNEXPECTED) this.metaspace falsy? (E: 1a72d80af929b77c0fa3a1f80a973825)`); }\n            await super.activateIbGib({ addr, ibGib });\n\n            // removed a bunch of stuff taken from projects-component\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * @internal\n     * gets the project tab info for the given addr.\n     *\n     * creates and loads the project ibgib component, which itself loads the\n     * ibgib internally (or throws) if not already loaded.\n     *\n     * @returns ProjectChildInfo with fully loaded component and ibgib.\n     *\n     * @see {@link ProjectChildInfo}\n     */\n    protected async getLoadedChildInfo({\n        addr,\n        ibGib,\n    }: {\n        addr: IbGibAddr,\n        ibGib?: IbGib_V1,\n    }): Promise<ProjectChildInfo> {\n        const lc = `${this.lc}[${this.getLoadedChildInfo.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: ecaad8b7c0d5a3289edcacc8d5830825)`); }\n            if (!addr) { throw new Error(`(UNEXPECTED) addr falsy? (E: c00d98024143d46ac885f0d9fc098c25)`); }\n            const tjpGib = getGibInfo({ ibGibAddr: addr }).tjpGib ?? getIbAndGib({ ibGibAddr: addr }).gib;\n\n            const fnCreateAndLoadProjectComponent = async () => {\n                const componentSvc = await getComponentSvc();\n                const childComponent = await componentSvc.getComponentInstance({\n                    path: EXPLORERITEM_COMPONENT_NAME,\n                    ibGibAddr: addr,\n                    useRegExpPrefilter: true,\n                }) as ExplorerItemComponentInstance | undefined;\n                if (!childComponent) {\n                    debugger; // error couldn't create component instance for project?\n                    throw new Error(`(UNEXPECTED) projectComponent falsy? couldn't create component instance for project? (E: c6b248bc481f21dc74eb6b993692d825)`);\n                }\n                // await projectComponent.loadIbGib();\n                // await projectComponent.initialized;\n                if (!childComponent.ibGib) {\n                    debugger; // error couldn't load ibGib for project?\n                    throw new Error(`(UNEXPECTED) ibGib falsy? couldn't load ibGib for project? (E: 2b1558512458ec70497f1d58a7b00825)`);\n                }\n                // guaranteed loaded ibGib\n                return childComponent;\n            }\n\n            /** the point of this function is to populate this */\n            let childInfo: ProjectChildInfo;\n\n            /**\n             * filtered for same timeline of addr via tjpGib\n             */\n            const filtered = this.childInfos.filter(x => {\n                const tabGibInfo = getGibInfo({ ibGibAddr: x.addr });\n                const tabTjpGib = tabGibInfo.tjpGib ?? getIbAndGib({ ibGibAddr: x.addr }).gib;\n                return tabTjpGib === tjpGib;\n            });\n            if (filtered.length > 0) {\n                // already have an existing tab\n                // const filtered = this.childInfos.filter(x => x.addr === addr);\n                if (filtered.length !== 1) { throw new Error(`(UNEXPECTED) filtered.length !== 1? (E: ebcc484b751821619a3985bfd194b825)`); }\n                childInfo = filtered[0];\n                if (childInfo.component) {\n                    console.log(`${lc} childInfo.component already truthy. (I: 3639381951e8478068cd7688fb954f25)`);\n                } else {\n                    childInfo.component = await fnCreateAndLoadProjectComponent();\n                    // ibGib = childInfo.component!.ibGib!;\n                }\n            } else {\n                // no existing tab, so create new project tab info\n                const projectComponent = await fnCreateAndLoadProjectComponent();\n                ibGib = projectComponent.ibGib!; // guaranteed in above fn\n\n                // both addr and ibGib guaranteed now\n                const tabBtnEl = await this.addChild({ addr, ibGib })\n                childInfo = {\n                    addr,\n                    childBtnEl: tabBtnEl,\n                    component: projectComponent,\n                    active: false,\n                };\n            }\n\n            return childInfo;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * creates a new tab element (span atow 03/2025), adds it to the\n     * headerTabsEl and returns the new span element.\n     *\n     * @returns the newly created tab span element\n     */\n    protected override async addChild({\n        addr,\n        ibGib,\n    }: {\n        ibGib: IbGib_V1,\n        addr?: IbGibAddr,\n    }): Promise<HTMLElement> {\n        const lc = `${this.lc}[${this.addChild.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: d5a6d80fb9e8df427f5bc293143ab825)`); }\n\n            // #region init/validate\n            if (!this.elements) { throw new Error(`(UNEXPECTED) this.elements falsy? (E: b937c8169f5840a5e878ac58d013e725)`); }\n            // const { headerTabsEl } = this.elements;\n\n            addr ??= getIbGibAddr({ ibGib });\n            if (addr !== getIbGibAddr({ ibGib })) {\n                throw new Error(`(UNEXPECTED) addr !== getIbGibAddr({ibGib})? (E: a349d8d20ca86cac682c87f8898be125)`);\n            }\n            const tjpAddr = getTjpAddr({ ibGib, defaultIfNone: 'incomingAddr' });\n            const { gib: tjpGib } = getIbAndGib({ ibGibAddr: tjpAddr });\n            // #endregion init/validate\n\n            // create the tab button element\n            const span = document.createElement('span');\n            span.id = `projects-tab-button-${addr}`;\n            span.classList.add('panel-tab-button');\n            // if (activate) { span.classList.add('active'); }\n            this.updateTabTitleAndText({ span, ibGib });\n            let {\n                punctiliarColor,\n                punctiliarColorTranslucent,\n                tjpColor,\n                tjpColorContrast,\n                tjpColorTranslucent,\n                errorMsg\n            } = getDeterministicColorInfo({ ibGib, translucentAlpha: 70 });\n            if (!errorMsg) {\n                span.style.borderColor = tjpColor ?? punctiliarColor;\n                span.style.backgroundColor = tjpColorTranslucent ?? punctiliarColorTranslucent;\n                span.style.color = tjpColorContrast ?? getColorStrings(90, tjpGib).at(2) ?? 'red'\n\n                // this.style.setProperty('--ibgib-color', punctiliarColor);\n                // this.style.setProperty('--ibgib-color-translucent', punctiliarColor);\n                // this.style.setProperty('--tjp-color', tjpColor ?? punctiliarColor);\n                // this.style.setProperty('--tjp-color-translucent', tjpColorTranslucent ?? punctiliarColorTranslucent);\n            } else {\n                // don't set anything\n                console.error(`${lc} ${errorMsg} (E: b855d82bb8af0a2468aef54d983b6825)`);\n            }\n\n            // headerTabsEl.appendChild(span);\n            span.addEventListener('click', async (event) => {\n                // if (logalot) { console.log(`${lc} activating...`); }\n                // await this.activateProject({ projectAddr: addr });\n                await this.activateIbGib({ addr });\n            });\n\n            if (!this.metaspace) { throw new Error(`(UNEXPECTED) this.metaspace falsy? (E: 692f4e402551f41beba2bca88ad6c125)`); }\n            if (!this.metaspace.latestObs) { throw new Error(`(UNEXPECTED) this.metaspace.latestObs falsy? (E: a1423ef1c978672ad9a72ae9188ac825)`); }\n            await this.metaspace.latestObs?.subscribe(fnObs({\n                next: async (updateInfo: IbGibTimelineUpdateInfo) => {\n                    if (updateInfo.tjpAddr !== tjpAddr) { return; /* <<<< returns early */ }\n                    if (updateInfo.latestIbGib) {\n                        this.updateTabTitleAndText({ span, ibGib: updateInfo.latestIbGib })\n                    } else {\n                        console.error(`{lc}[next] updateInfo.latestIbGib falsy? (E: 3df9efd911e8d84ddd9f3fafa45a8825)`);\n                    }\n                },\n                complete: async () => {\n                    console.warn(`${lc}[complete] completed executed? (W: 8bf2c8723158050e5861bf885fbe4925)`);\n                },\n                error: async (error) => {\n                    debugger; // error in metaspace.latestObs dispatch?\n                    console.error(`${lc}[error] ${extractErrorMsg(error)}`);\n                },\n            }));\n\n            return span;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    protected removeTabBtn({ tabInfo, }: { tabInfo: ProjectChildInfo; }): Promise<void> {\n        throw new Error(\"Method not implemented.\");\n    }\n\n    private updateTabTitleAndText({\n        span,\n        ibGib,\n    }: {\n        span: HTMLElement,\n        ibGib: IbGib_V1,\n    }): void {\n        const lc = `[${this.updateTabTitleAndText.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: bf99b7f4991876f96986d1814b6ad825)`); }\n\n            if (!ibGib.data) { throw new Error(`(UNEXPECTED) ibGib.data falsy? (E: 4b4a1aef1f362a411811d733b18f6825)`); }\n            if (!ibGib.data.name) { console.warn(`${lc} ibGib.data.name falsy? (W: 07c1e8963bad9e12cda272a237c42d25)`); }\n            const title = ibGib.data.name ?? 'untitled'\n            const desc = ibGib.data.description ?? '';\n            span.title = desc ? `${title}\\n${desc}` : title;\n            const MAX_TAB_TEXT_LENGTH = 12;\n            span.textContent = getSaferSubstring({ text: title, length: MAX_TAB_TEXT_LENGTH, });\n            if (title.length > MAX_TAB_TEXT_LENGTH) {\n                span.textContent += '\u2026';\n            }\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    async initElements(): Promise<void> {\n        const lc = `${this.lc}[${this.initElements.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 757cf5efc3e99ffca3dbad4ec11d4825)`); }\n\n            if (!this.shadowRoot) { throw new Error(`(UNEXPECTED) this.shadowRoot falsy? (E: 292b82f80698b67e9ec9d44dd2f13825)`); }\n            const { shadowRoot } = this;\n\n            const headerEl = shadowRoot_getElementById(shadowRoot, 'projects-explorer-header');\n\n            // headerTabsEl\n            // const headerTabsEl = shadowRoot_getElementById(shadowRoot, 'projects-explorer-header-tabs');\n\n            const contentEl = shadowRoot_getElementById(shadowRoot, 'projects-explorer-content');\n\n            const projectListFilterEl = shadowRoot_getElementById<HTMLInputElement>(shadowRoot, 'project-list-filter');\n            const fnApplyFilter = async (text: string) => {\n                this.projectListFilterText = text;\n                await this.renderUI_projectList();\n            }\n            const fnApplyFilter_debounced = debounce(fnApplyFilter, 1_000);\n            // Add an event listener to the textarea\n            projectListFilterEl.addEventListener('input', async (event) => {\n                const target = event.target as HTMLInputElement;\n                fnApplyFilter_debounced(target.value);\n            });\n\n            const projectListEl = shadowRoot_getElementById(shadowRoot, 'project-list');\n            const pContent = document.createElement('p');\n            pContent.textContent = '[loading...]';\n            pContent.style.textAlign = 'center';\n            pContent.style.fontStyle = 'italic';\n            projectListEl.appendChild(pContent);\n\n            const footerEl = shadowRoot_getElementById(shadowRoot, 'projects-explorer-footer');\n            footerEl.style.display = 'none';\n\n            // ellipsisBtnEl\n            // const ellipsisBtnEl = shadowRoot_getElementById(shadowRoot, 'projects-explorer-header-ellipsis-btn');\n            // // ellipsisPopoverEl - when user clicks ellipsis\n            // const ellipsisPopoverEl = shadowRoot_getElementById(shadowRoot, 'ellipsis-popover');\n            // const ellipsisPopoverOptions = ellipsisPopoverEl.querySelectorAll('.ellipsis-popover-option');\n            // ellipsisBtnEl.addEventListener('click', async (event) => {\n            //     ellipsisPopoverEl.style.position = 'absolute';\n            //     ellipsisPopoverEl.style.top = `${ellipsisBtnEl.offsetTop + ellipsisBtnEl.clientHeight}px`;\n            //     ellipsisPopoverEl.style.left = `${ellipsisBtnEl.offsetLeft}px`;\n            // });\n            // // Event listeners for popover options\n            // ellipsisPopoverOptions.forEach(option => {\n            //     option.addEventListener('click', async (event: Event) => {\n            //         try {\n            //             const target = event.target as HTMLElement;\n            //             const optionType = target.getAttribute('data-option');\n            //             if (optionType) {\n            //                 await this.handleEllipsisPopoverSelected(optionType);\n            //             }\n            //         } catch (error) {\n            //             const emsg = `${lc}[ellipsisPopoverOption] ${extractErrorMsg(error)} (E: f0d1c840dfc809d39f2b8cd83ddb3225)`;\n            //             console.error(emsg);\n            //             alertUser({ msg: emsg, title: 'export failed...' }); // spins off\n            //         } finally {\n            //             // Hide popover after selection\n            //             ellipsisPopoverEl.hidePopover();\n            //         }\n            //     });\n            // });\n\n            this.elements = {\n                headerEl,\n                // headerTabsEl,\n                // addBtnEl,\n                // ellipsisBtnEl,\n                // ellipsisPopoverEl,\n                contentEl,\n                projectListEl,\n                projectListFilterEl,\n                footerEl,\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * exports the current project. If more than one is open, exports the currently active project.\n     *\n     * Should this also include exporting the project's agent? As a flag\n     */\n    private async exportProject({ compress }: { compress: boolean }): Promise<void> {\n        const lc = `${this.lc}[${this.exportProject.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 7b8ac4cbe6382312b8b3416318fc0425)`); }\n\n            // if (!this.ibGib) { throw new Error(`(UNEXPECTED) this.ibGib falsy? (E: ec92b82f7708e9bbe89ff8e8ddfca825)`); }\n            if (!this.activeProjectTabInfo) { throw new Error(`(UNEXPECTED) this.activeProjectTabInfo falsy? (E: ebee7ed1a098abcb38cf0258270e7825)`); }\n            if (!this.activeProjectTabInfo.component) { throw new Error(`(UNEXPECTED) this.activeProjectTabInfo.component falsy? (E: 57a2d854006843f9781bef68b3e49d25)`); }\n            if (!this.activeProjectTabInfo.component.ibGib) { throw new Error(`(UNEXPECTED) this.activeProjectTabInfo.component.ibGib falsy? (E: 71b8d460d4c8e4b0fd62894f4c3a0825)`); }\n            await this.exportIbGib({\n                ibGib: this.activeProjectTabInfo.component.ibGib,\n                compress,\n            });\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private async importProject(): Promise<void> {\n        const lc = `[${this.importProject.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 232821cbc758065f8d8be84a4728f225)`); }\n            throw new Error(`not implemented (yet!!) ...delayed because of thinking about import as basically being the same thing as a merge, which is non-trivial. work is mostly located in ibgib-dynamic-component-bases.mts importibGib, but need to pull out into a helper. that should actually just call the helper, passing in the components this.ibGib (can be overridden in descending concrete component classes, in case this.ibGib isn't what we want) (E: 6ae10a989a46095ad867a5a83368f325)`);\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * Handler for when an option is selected from the add popover.\n     */\n    private async handleEllipsisPopoverSelected(optionType: string): Promise<void> {\n        const lc = `${this.lc}[${this.handleEllipsisPopoverSelected.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... optionType: ${optionType} (I: 4ee4d8f38618d34151b4d28853bdaa25)`); }\n\n            switch (optionType) {\n                case 'copy-active-project-address':\n                    if (this.activeProjectTabInfo) {\n                        copyToClipboard({ data: { text: this.activeProjectTabInfo.addr }, });\n                        highlightElement({ el: this.activeProjectTabInfo.childBtnEl, magicHighlightTimingMs: 1_000 }); // spin off so options disappear\n                    } else {\n                        await alertUser({ title: 'No Project?', msg: `There was no project tab found? This seems like a bug so you should report it please. (E: 3c82e358dd89822a9f7b4bc89b372925)` });\n                    }\n                    break;\n                case 'export-project':\n                    await this.exportProject({ compress: false });\n                    break;\n                case 'export-project-gzip':\n                    await this.exportProject({ compress: true });\n                    break;\n                case 'import-project':\n                    await this.importProject();\n                    break;\n                default:\n                    throw new Error(`(UNEXPECTED) invalid optionType (${optionType})? (E: 4c175e5f7ad48f9f9320c51b157c2825)`);\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    protected override async initAgents(): Promise<void> {\n        const lc = `${this.lc}[${this.initAgents.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: ef8d186a78582cd22f17d7a8eb887a25)`); }\n\n            this.metaspace = await getGlobalMetaspace_waitIfNeeded();\n\n            let agent: AgentWitnessAny | undefined = undefined;\n            let agents = await getAgents({\n                metaspace: this.metaspace,\n                type: AGENT_SPECIAL_IBGIB_TYPE_PROJECTSAGENT,\n                spaceId: undefined, // explicitly use default local space just to show this option bc it's early in life\n            });\n            if (agents.length > 0) {\n                agent = agents.at(0)!;\n            } else {\n                const agentsSvc = getAgentsSvc();\n                agent = await agentsSvc.createNewAgent({\n                    metaspace: this.metaspace,\n                    superSpace: undefined, // uses default local user space as the super space\n                    name: `ProjectsAgent-${this.instanceId}`,\n                    api: 'gemini',\n                    model: GEMINI_DEFAULT_MODEL_STR,\n                    availableFunctions: [\n                        ...AGENT_AVAILABLE_FUNCTIONS_PROJECTSAGENT,\n                    ],\n                    initialSystemText: AGENT_INITIAL_SYSTEM_TEXT_PROJECTSAGENT,\n                    initialChatText: AGENT_INITIAL_CHAT_TEXT_PROJECTSAGENT,\n                    fnGetAPIKey: getDefaultFnGetAPIKey(),\n                    type: AGENT_SPECIAL_IBGIB_TYPE_PROJECTSAGENT,\n                    addToAgentsTag: true,\n                });\n            }\n\n            this.agents = [agent];\n\n            if (!this.agent) { throw new Error(`(UNEXPECTED) agent falsy after createNewAgent? (E: 8e7ef1336958e674934288ac1078cb25)`); }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n}\n", "<div id=\"web1-page-about\" class=\"web1-page\">\n\n    <article>\n        <section>\n\n            <h2>About IbGib Protocol...</h2>\n\n            <aside>\n\n                The ibgib protocol is the culmination of a lifetime of work.\n\n            </aside>\n\n            <p>\n\n                Originally inspired by SuperMemo, automatons and\n                information-centric ontology like memes, ibgib has evolved as a <b>unique</b> DLT approach:\n\n            </p>\n\n            <ul>\n                <li><b>unique</b> content addressing mechanism</li>\n                <li><b>unique</b> first-class citizens of timelines, i.e., spacetime</li>\n                <li><b>unique</b> distributed computation identity (planned)</li>\n            </ul>\n\n        </section>\n\n        <section>\n\n            <h2>About Me, William Raiford</h2>\n\n            <aside>\n\n                <b>Lifelong</b> obsession of distributed computation and its relationship to lifelong learning.\n\n            </aside>\n\n            <p>\n\n                I live in San Antonio, TX, with my wife of 26 years, two dogs,\n                three + two cats, two chickens, and numerous plants and trees.\n                After surmounting burnout, induced by programming 16+ hours a day\n                both as an Air Force contractor and an ibgib creator, I have\n                been unable to do anything other than focus on ibgib for the\n                past decade. All other approaches are inherently limited and\n                short-sighted.\n\n            </p>\n\n        </section>\n\n    </article>\n</div>\n", ".web1-page {\n    display: flex;\n    flex-direction: column;\n    align-items: center;\n    justify-self: center;\n\n    height: 100%;\n    /* why didn't I have this before? I thought I took it out for something. */\n    width: 100%;\n    max-width: 800px;\n    padding: 10px;\n\n    overflow-y: auto;\n\n    aside {\n        width: 40%;\n        padding: 5px;\n        padding-left: 0.5rem;\n        margin-left: 0.5rem;\n        float: right;\n        /* box-shadow: inset 5px 0 5px -5px #29627e; */\n        /* box-shadow: inset 5px 0 5px -5px var(--primary-border-color-dark); */\n        box-shadow: inset 5px 0 5px -5px var(--tab-border-color-active);\n        font-style: italic;\n        font-size: larger;\n        color: var(--tab-text-color-active);\n        /* background-color: var(--dialog-backdrop-color); */\n        background-color: var(--tab-background-color-active);\n        border-radius: 5px;\n\n        /* NEW: Blur and fade-in animation */\n        filter: blur(10px);\n        /* Initial blur */\n        opacity: 0.5;\n        /* Initial opacity (slightly transparent) */\n        transition: filter 2s ease-out, opacity 1s ease-out, border-color 2s ease-in-out;\n        /* Smooth transitions */\n        border: 1px solid transparent;\n        /* Initial transparent border */\n\n        /* small screens have text go off screen*/\n        overflow-wrap: break-word;\n        overflow: hidden;\n        min-width: 10ch;\n\n        iframe {\n            max-width: 100%;\n        }\n    }\n\n    aside.unblurred {\n        /* Class to trigger unblur and border animation */\n        filter: blur(0px);\n        /* Remove blur */\n        opacity: 1;\n        /* Fully opaque */\n        border-color: rgba(0, 255, 0, 0.35);\n        /* Start radiating green border */\n        box-shadow: inset 5px 0 5px -5px var(--primary-border-color-dark), 0 0 20px rgba(0, 255, 0, 0.5);\n        /* Add subtle box-shadow glow */\n    }\n\n    aside>p {\n        margin: 0.5rem;\n    }\n\n    article {\n        width: 100%;\n        display: flex;\n        flex-direction: column;\n        gap: 5vh;\n    }\n\n    section {\n        border-width: 1px;\n        border-color: var(--primary-border-color);\n        border-style: solid;\n        border-radius: 5px;\n        background-color: var(--very-light-background-color);\n        padding: 13px;\n        /* transition: border-width var(--highlight-transition-time) ease-in-out, border-color var(--highlight-transition-time) ease-in-out, background-color var(--highlight-transition-time) ease-in-out, padding var(--highlight-transition-time) ease-in-out; */\n        /* transition: border-width var(--highlight-transition-time) ease-in-out,\n            border-color var(--highlight-transition-time) ease-in-out,\n            border-radius var(--highlight-transition-time) ease-in-out,\n            background-color var(--highlight-transition-time) ease-in-out,\n            padding var(--highlight-transition-time) ease-in-out; */\n\n        h2 {\n            margin-top: 0;\n        }\n    }\n}\n\n.thumbnail {\n    max-height: 50% !important;\n    max-width: 100% !important;\n    aspect-ratio: 1/1;\n}\n\ntable {\n    border-width: 3px;\n    border-color: var(--primary-border-color-dark);\n    border-style: solid;\n    border-radius: 5px;\n\n    width: 100%;\n\n    background-color: rgba(0, 255, 0, 0.163);\n\n    thead {\n        border-bottom-color: var(--primary-border-color-dark);\n    }\n\n    tr th {\n        border-width: 0px;\n        border-color: var(--primary-border-color);\n        border-style: solid;\n        margin: 0px;\n    }\n\n    th,\n    td {\n        border-width: 1px;\n        border-color: var(--primary-border-color);\n        border-style: solid;\n        border-collapse: collapse;\n    }\n\n    td:nth-child(2n),\n    tr th:nth-child(2n) {\n        background-color: rgba(51, 236, 30, 0.24);\n    }\n}\n\nbutton {\n    border-width: 2px;\n    border-color: var(--primary-border-color-dark);\n    border-style: solid;\n    border-radius: 5px;\n    background-color: var(--light-background-color);\n}\n", "/* #web1-page-about { */\n\n    /* just debugging */\n    /* aside {\n        background-color: rgb(255, 218, 8) !important;\n    } */\n\n/* } */\n", "import { APIFunctionInfo } from \"../../api-types.mjs\";\nimport { updateCSSVariablesFunctionInfo } from './update-css-variables.mjs';\n\nexport const UIAgentFunctionInfos: APIFunctionInfo<any>[] = [\n    updateCSSVariablesFunctionInfo,\n];\n", "import { ChatAPIFunctionInfos } from \"../../api/commands/chat/chat-index.mjs\";\nimport { UIAgentFunctionInfos } from \"../../api/commands/ui/ui-index.mjs\";\n\nexport const AGENT_AVAILABLE_FUNCTIONS_PRIMARYAGENT = [\n    ...ChatAPIFunctionInfos,\n    // fetchWeb1PageFunctionInfo, // need to customize this in blank-gib\n    ...UIAgentFunctionInfos,\n];\n", "import { delay, extractErrorMsg } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { IbGibAddr, } from \"@ibgib/ts-gib/dist/types.mjs\";\nimport { getIbGibAddr } from \"@ibgib/ts-gib/dist/helper.mjs\";\nimport { IbGib_V1 } from \"@ibgib/ts-gib/dist/V1/types.mjs\";\nimport { createCommentIbGib } from \"@ibgib/core-gib/dist/common/comment/comment-helper.mjs\";\nimport { getTjpAddr, toDto } from \"@ibgib/core-gib/dist/common/other/ibgib-helper.mjs\";\nimport { appendToTimeline } from \"@ibgib/core-gib/dist/timeline/timeline-api.mjs\";\nimport { getAddlMetadataTextForAgentText, taggifyForPrompt, } from \"@ibgib/web-gib/dist/witness/agent/agent-helpers.mjs\";\nimport { AgentWitnessAny, } from \"@ibgib/web-gib/dist/witness/agent/agent-one-file.mjs\";\nimport { getGlobalMetaspace_waitIfNeeded, } from \"@ibgib/web-gib/dist/helpers.mjs\";\nimport { highlightElement, unhighlightElement } from \"@ibgib/web-gib/dist/helpers.web.mjs\";\nimport { AGENT_SPECIAL_IBGIB_TYPE_PRIMARYAGENT, TextSource } from \"@ibgib/web-gib/dist/witness/agent/agent-constants.mjs\";\nimport { LiveProxyIbGib } from \"@ibgib/web-gib/dist/witness/live-proxy-ibgib/live-proxy-ibgib-one-file.mjs\";\nimport { getAgentsSvc } from \"@ibgib/web-gib/dist/witness/agent/agents-service-v1.mjs\";\nimport {\n    IbGibDynamicComponentInstanceBase, IbGibDynamicComponentMetaBase\n} from \"@ibgib/web-gib/dist/ui/component/ibgib-dynamic-component-bases.mjs\";\nimport {\n    FnHandleRouteType, IbGibDynamicComponentInstance,\n    IbGibDynamicComponentInstanceInitOpts\n} from \"@ibgib/web-gib/dist/ui/component/component-types.mjs\";\nimport { AGENT_AVAILABLE_FUNCTIONS_PRIMARYAGENT } from \"@ibgib/web-gib/dist/witness/agent/agent-one-file.app.mjs\";\n\nimport { GLOBAL_LOG_A_LOT, HARDCODED_PROMPT_TAG_TEXT } from \"../../constants.mjs\";\nimport { getAppShellSvc } from \"../../ui/shell/app-shell-service.mjs\";\nimport { CHAT_WITH_AGENT_PLACEHOLDER_PRIMARYAGENT } from \"../../witness/app/blank-canvas/blank-canvas-constants.mjs\";\nimport { getComponentCtorArg, getIbGibGlobalThis_BlankGib } from \"../../helpers.web.mjs\";\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\n\nexport abstract class Web1ComponentMetaBase\n    extends IbGibDynamicComponentMetaBase {\n    protected override lc: string = `[${Web1ComponentMetaBase.name}]`;\n\n    /**\n     * @see {@link IbGibDynamicComponentMeta.componentName}\n     */\n    componentName: string = this.getComponentName();\n\n    /**\n     * @see {@link IbGibDynamicComponentMeta.routeRegExp}\n     */\n    routeRegExp?: RegExp = undefined;\n\n    /**\n     * @see {@link IbGibDynamicComponentMeta.fnHandleRoute}\n     */\n    fnHandleRoute?: FnHandleRouteType = undefined;\n\n    /**\n     * @see {@link IbGibDynamicComponentMeta.componentName}\n     */\n    protected abstract getComponentName(): string;\n    protected abstract getHtml(): string;\n    protected abstract getCss(): string[] | undefined;\n\n\n    /**\n     * override this with the `customElements.define` call that will register\n     * the web component.\n     *\n     * @example\n     *\n     * customElements.define(this.componentName, Web1ComponentInstance_Funding);\n     */\n    protected abstract registerCustomElements(): void;\n\n    /**\n     *\n     */\n    constructor() {\n        super(getComponentCtorArg());\n        this.registerCustomElements();\n    }\n\n\n    /**\n     * creates the instance of a web1 funding.html component.\n     *\n     * note that since this is web 1.0, this doesn't really use the incoming\n     * args, but that other more ibgib-related components may do so.\n     */\n    async createInstance({\n        path,\n        ibGibAddr,\n    }: {\n        path: string;\n        ibGibAddr: IbGibAddr;\n    }): Promise<IbGibDynamicComponentInstance> {\n        const lc = `${this.lc}[${this.createInstance.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: baf75543b6da9f117ae76fc76703fd25)`); }\n            const component = document.createElement(this.componentName) as IbGibDynamicComponentInstance;\n            await component.initialize({\n                ibGibAddr,\n                meta: this,\n                html: this.getHtml(),\n                css: this.getCss(),\n            });\n            return component;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n}\n\nexport abstract class Web1ComponentInstanceBase\n    extends IbGibDynamicComponentInstanceBase\n    implements IbGibDynamicComponentInstance<IbGib_V1, any> {\n    protected override lc: string = `[${Web1ComponentInstanceBase.name}]`;\n\n    // protected abstract _getName(): string;\n\n    // get name(): string { return this._getName(); }\n\n    constructor() {\n        super();\n    }\n\n    override async initialize(opts: IbGibDynamicComponentInstanceInitOpts): Promise<void> {\n        const lc = `${this.lc}[${this.initialize.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: b3964c3b9f3f5100870f1106226eb325)`); }\n            await super.initialize(opts);\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n\n    }\n\n    override async created(): Promise<void> {\n        const lc = `${this.lc}[${this.created.name}]`;\n        console.log(`${lc} created (I: 3a2fe4eea594c46f8f84374461e12f25)`);\n        delay(4000).then(async () => { await this.unblurAsides(); });\n        await this.setBreadcrumbs();\n        while (!getIbGibGlobalThis_BlankGib().bootstrapPromise) {\n            await delay(30);\n            console.log(`${lc} waiting for bootstrapPromise to be truthy, let alone complete.`);\n        }\n        await getIbGibGlobalThis_BlankGib().bootstrapPromise;\n        this.agentsInitialized = this.initAgents(); // spins off but we await\n        // we are awaiting because this was screwing up local space special\n        // ibgib indexes because it was running in parallel with bootstrap\n        await this.agentsInitialized;\n    }\n\n    private async initInput(): Promise<void> {\n        const lc = `${this.lc}[${this.initInput.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 478954ef685613d2217601dfa2deae25)`); }\n\n            const appShellSvc = getAppShellSvc();\n            await appShellSvc.initialized;\n            while (!appShellSvc.inputComponent) {\n                console.log(`${lc} appShellSvc.inputComponent falsy. waiting until it's created. (I: b045c1f5ba4a94a66178ecbeec70c725)`);\n                await delay(100);\n            }\n\n            // make the call to update the input component\n            await appShellSvc.inputComponent!.setContextInfo({\n                info: {\n                    agent: this.agent,\n                    placeholderText: CHAT_WITH_AGENT_PLACEHOLDER_PRIMARYAGENT,\n                    // default to default local user space for now\n                    spaceId: undefined,\n                    contextProxyIbGib: this.ibGibProxy,\n                },\n            });\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * inits the chronology in the right panel for web1 components\n     */\n    private async initChronology(): Promise<void> {\n        const lc = `${this.lc}[${this.initChronology.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n\n            const globalIbGib = getIbGibGlobalThis_BlankGib();\n            let chronologysComponent = globalIbGib.chronologysComponent;\n\n            let count = 0;\n            while (!chronologysComponent) {\n                console.warn(`${lc} global chronologysComponent is expected to be truthy by now. delaying (W: genuuid)`)\n                count++;\n                if (count > 100) {\n                    debugger; // error in web1 component expectation\n                    throw new Error(`(UNEXPECTED) global chronologysComponent is falsy? (E: 3d68459066ee7ef9fbdfea4ea3904825)`);\n                }\n                await delay(100);\n            }\n\n            if (!this.ibGibProxy) { throw new Error(`(UNEXPECTED) this.ibGibProxy falsy? (E: 4e91911bf6ce45d398c04a256fceb825)`); }\n            // ibGibProxy.ibGib is a comment ibgib that is data.n=2. the 2 is\n            // because it is already related to an agent.\n\n            await chronologysComponent.openIbGibAddr({\n                ibGibAddr: getIbGibAddr({ ibGib: this.ibGibProxy.ibGib }),\n            });\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    /**\n     * web1 components use the primary agent\n     */\n    protected override async initAgents(): Promise<void> {\n        const lc = `${this.lc}[${this.initAgents.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: bb6228de92a7552ff389cec83f9a0825)`); }\n\n            getGlobalMetaspace_waitIfNeeded().then(async (metaspace) => {\n                let agent: AgentWitnessAny | undefined = undefined;\n                const agentsSvc = getAgentsSvc();\n                do {\n                    let agents = await agentsSvc.getAgents({\n                        metaspace,\n                        type: AGENT_SPECIAL_IBGIB_TYPE_PRIMARYAGENT,\n                        spaceId: undefined, // explicitly use default local space just to show this option bc it's early in life\n                    });\n                    if (agents.length > 0) {\n                        agent = agents.at(0)!;\n                    } else {\n                        await delay(200);\n                    }\n                } while (!agent);\n\n                this.agents = [agent];\n                if (!this.agent) { throw new Error(`(UNEXPECTED) this.agent falsy just after loading? (E: cc4f770e59d771a13411d32aa42ccd25)`); }\n\n                await this.initProxyIbGib();\n                await this.initInput(); // footer\n                await this.initChronology(); // right panel\n                if (!this.ibGib) { throw new Error(`(UNEXPECTED) this.ibGib falsy even though we just initialized proxy ibgib? (E: f2b1093291e30d420c3f5909b9d0d125)`); }\n                await agent.updateAvailableFunctions({\n                    availableFunctions: AGENT_AVAILABLE_FUNCTIONS_PRIMARYAGENT,\n                });\n                await agent.setActiveContext({\n                    contextIbGib: this.ibGib,\n                });\n                const contextTjpAddr = getTjpAddr({ ibGib: this.ibGib });\n                await this.agent.addTexts({\n                    infos: [\n                        {\n                            textSrc: TextSource.HARDCODED,\n                            text: taggifyForPrompt({\n                                contentText: `Current URL path: \"${window.location.href.substring((window.location.protocol + '//' + window.location.host).length) || \"/\"}\".\\nCurrent web 1.0 context ibgib tjp address: ${contextTjpAddr}`,\n                                tagText: HARDCODED_PROMPT_TAG_TEXT,\n                            }),\n                        }\n                    ]\n                });\n                // await this.agent.doPrompt(); // this will not await any subsequent function calls made by the agent.\n            }); // spin off\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    /**\n     * at this point, this.agent is set\n     */\n    protected async initProxyIbGib(): Promise<void> {\n        const lc = `${this.lc}[${this.initProxyIbGib.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 8e7885645d473e564c524657644e9425)`); }\n            if (!this.agent) { throw new Error(`(UNEXPECTED) this.agent falsy? this is assumed to be populated at this point. (E: dbe35604778c4049f5f8ef6a0f660f25)`); }\n\n            const ibgibGlobalThis = getIbGibGlobalThis_BlankGib();\n            if (!ibgibGlobalThis.web1CommentIbGibProxy) {\n                // initialize a new comment as the ibgib context for all web1 interactions\n                const metaspace = await getGlobalMetaspace_waitIfNeeded();\n                const space = await metaspace.getLocalUserSpace({ lock: false }); // default space\n\n                // need to create/load an agent for the comment\n\n                // let agent: AgentWitnessAny;\n                // const agentsSvc = getAgentsSvc();\n                // const agents = await agentsSvc.getAgents({\n                //     metaspace,\n                //     type: AGENT_SPECIAL_IBGIB_TYPE_PRIMARYAGENT,\n                //     space,\n                // });\n                // if (agents.length === 0) {\n                //     // no agents so create one\n\n                //     agent = await agentsSvc.createNewAgent({\n                //         metaspace,\n                //         superSpace: space, // uses default local user space as the super space\n                //         name: `PrimaryAgent-${this.instanceId}`,\n                //         api: 'gemini',\n                //         model: GEMINI_DEFAULT_MODEL_STR,\n                //         availableFunctions: clone(AGENT_AVAILABLE_FUNCTIONS_PRIMARYAGENT),\n                //         initialSystemText: [\n                //             AGENT_INITIAL_SYSTEM_TEXT_PRIMARYAGENT,\n                //         ].join('\\n'),\n                //         initialChatText: [\n                //             AGENT_INITIAL_CHAT_TEXT_PRIMARYAGENT\n                //         ].join('\\n'),\n                //         fnGetAPIKey: getIbGibGlobalThis_BlankGib().fnDefaultGetAPIKey,\n                //         type: AGENT_SPECIAL_IBGIB_TYPE_PRIMARYAGENT,\n                //         addToAgentsTag: true,\n                //     });\n                // } else {\n                //     agent = agents[0];\n                // }\n                const agentAddr = getIbGibAddr({ ibGib: this.agent });\n\n                // create the new comment\n                const resCommentIbGib = await createCommentIbGib({\n                    text: 'This is a web 1 context.',\n                    addlMetadataText: getAddlMetadataTextForAgentText({\n                        textSrc: 'hardcoded',\n                    }),\n                    saveInSpace: true,\n                    space,\n                });\n                const commentIbGib = resCommentIbGib.newIbGib;\n                await metaspace.registerNewIbGib({ ibGib: commentIbGib, space });\n\n                // associate to the comment\n                const latestCommentIbGib = await appendToTimeline({\n                    timeline: toDto({ ibGib: commentIbGib }),\n                    metaspace,\n                    rel8nInfos: [{ rel8nName: 'comment', ibGibs: [commentIbGib], }],\n                    space,\n                });\n                // const resRel8 = await rel8({\n                //     type: 'rel8',\n                //     src: toDto({ ibGib: commentIbGib }),\n                //     rel8nsToAddByAddr: {\n                //         [AGENT_REL8N_NAME]: [agentAddr],\n                //     },\n                //     dna: true,\n                //     nCounter: true,\n                // }) as TransformResult<CommentIbGib_V1>;\n                // const newCommentIbGib = resRel8.newIbGib;\n                // await metaspace.persistTransformResult({\n                //     resTransform: resRel8,\n                //     space,\n                // });\n                // await metaspace.registerNewIbGib({\n                //     ibGib: newCommentIbGib,\n                //     space,\n                // });\n                // latestCommentIbGib = newCommentIbGib;\n\n                // create the proxy\n                const proxy = new LiveProxyIbGib();\n                await proxy.initialized;\n                await proxy.setWrappedIbGib({ ibGib: latestCommentIbGib });\n\n                // set the global comment proxy\n                ibgibGlobalThis.web1CommentIbGibProxy = proxy;\n            }\n            if (!ibgibGlobalThis.web1CommentIbGibProxy) {\n                throw new Error(`(UNEXPECTED) ibgibGlobalThis.web1CommentIbGibProxy falsy? we just should have initialized it (E: 596f92ead59186c374e36e1356924925)`);\n            }\n            const proxy = ibgibGlobalThis.web1CommentIbGibProxy;\n            this.ibGibProxy = proxy;\n            this.ibGibAddr = getIbGibAddr({ ibGib: proxy.ibGib });\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private async setBreadcrumbs(): Promise<void> {\n        const lc = `${this.lc}[${this.setBreadcrumbs.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: b18e0977f9213dca453689fa75326b25)`); }\n\n            let appShellSvc = getAppShellSvc();\n            appShellSvc.initialized.then(async () => {\n                try {\n                    const { breadcrumbComponent } = appShellSvc;\n                    if (!breadcrumbComponent) { throw new Error(`(UNEXPECTED) breadcrumbComponent is falsy? (E: 1d5b0148882b0a7f68aab9198ddf7925)`); }\n                    if (!this.meta) { throw new Error(`(UNEXPECTED) this.meta falsy? (E: f85649a6574eb111078faeca6dea5325)`); }\n                    await breadcrumbComponent.addBreadcrumb({\n                        info: {\n                            text: this.meta.componentName.replace('web1-', '').replace('-component', ''),\n                            type: 'web1',\n                            fnClickAction: () => Promise.resolve(), // do nothing\n                        },\n                        clear: true,\n                    });\n                } catch (error) {\n                    console.error(`${lc} couldn't set breadcrumbs for web1 component. (E: 5d255d9c91fdc126a46884cc74fada25)`);\n                }\n            });\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    override async disconnected(): Promise<void> {\n        const lc = `${this.lc}[${this.disconnected.name}]`;\n        console.log(`${lc} destroyed (I: 385596be521e5e859317324c9703e725)`);\n    }\n\n    async unblurAsides(): Promise<void> {\n        const lc = `[${this.unblurAsides.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: b7a52438e3a3b656d2b75a71bf94ac25)`); }\n\n            if (!this.shadowRoot) { throw new Error(`(UNEXPECTED) shadowRoot is falsy? (E: 1d5b0148882b0a7f68aab9198ddf7925)`); }\n            const asideElements = this.shadowRoot.querySelectorAll('.web1-page aside'); // Get aside element\n\n            console.log(`${lc} asideElements.length: ${asideElements.length} (I: d04f31d8cff89078ebec56f8994c5f25)`);\n\n            /**\n             * we want to focus one element at a time and have a delay in\n             * between them. So if two asides are on the screen at the same\n             * time, we want to stagger unblurring. So this is like a lock to do\n             * that.\n             */\n            let focusOneAtATime_focusing = false;\n            let focusQueue: HTMLElement[] = [];\n            /**\n             * indirect helper fn needed to get focusOneAtATime_focusing working\n             * right.\n             */\n            async function changeFocus({\n                el,\n                toUnblur,\n                delayMs = 1000,\n            }: {\n                el: HTMLElement,\n                toUnblur: boolean,\n                delayMs?: number,\n            }): Promise<void> {\n                delayMs ??= 1000;\n                while (focusOneAtATime_focusing) { await delay(delayMs); }\n                if (toUnblur) {\n                    if (el.classList.contains('unblurred')) {\n                        return; /* <<<< returns early */\n                    }\n                    focusOneAtATime_focusing = true;\n                    await delay(1000);\n                    el.classList.add('unblurred');\n                    await highlightElement({ el });\n                    focusOneAtATime_focusing = false;\n                } else {\n                    el.classList.remove('unblurred'); // blur the entry\n                    await unhighlightElement({ el });\n                }\n            }\n            // no iterator on NodeListOf<Element> so regular for statement.\n            // can't forEach for async and ensure order is correct (i think).\n            for (let i = 0; i < asideElements.length; i++) {\n                const el = asideElements[i] as HTMLElement;\n                const observer = new IntersectionObserver(async (entries) => {\n                    for (let entry of entries) {\n                        await changeFocus({ el, toUnblur: entry.isIntersecting, delayMs: 1000 });\n                    }\n                }, { threshold: 0.5 });\n                observer.observe(el);\n            }\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n}\n", "import thisHtml from './about.html';\nimport commonCss from '../web1-common.css';\nimport thisCss from './about.css';\nimport stylesCss from '../../../styles.css';\nimport rootCss from '../../../root.css';\n\nimport { extractErrorMsg } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { IbGibAddr } from \"@ibgib/ts-gib/dist/types.mjs\";\n\nimport { GLOBAL_LOG_A_LOT } from \"../../../constants.mjs\";\nimport { Web1ComponentInstanceBase, Web1ComponentMetaBase } from \"../web1-component-base-one-file.mjs\";\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\n\nconst WEB1_COMPONENT_NAME: string = 'web1-about-component';\nconst WEB1_HTML_PATH: string = '/components/web1/about/about.html';\n/**\n * script paths don't really work atow. I mean they are \"loaded\", but there is\n * no way that I can tell to get access to the shadow root of the web component.\n * any scripting I need done that requires this reference I am putting in these\n * component instances' code.\n */\nconst WEB1_SCRIPT_PATHS: string[] = [\n    // '/components/web1/web1-common.mjs',\n    // '/components/web1/about/about.mjs',\n];\nconst WEB1_CSS_PATHS: string[] = [\n    '/styles.css',\n    '/components/web1/web1-common.css',\n    '/components/web1/about/about.css',\n];\n\nexport const ComponentInfoWeb1_About = {\n    componentName: WEB1_COMPONENT_NAME,\n    htmlPath: WEB1_HTML_PATH,\n    scriptPaths: WEB1_SCRIPT_PATHS,\n    cssPaths: WEB1_CSS_PATHS,\n}\n\n/**\n * This is the root component for any web1 component. this will take in the\n * given path, see if it's web 1.0 path, and then delegate to the appropriate\n * web1 sub component (home, funding, etc.);\n */\nexport class Web1ComponentMeta_About\n    extends Web1ComponentMetaBase {\n    protected override lc: string = `[${Web1ComponentMeta_About.name}]`;\n\n    protected getComponentName(): string { return WEB1_COMPONENT_NAME; }\n    protected getHtml(): string { return thisHtml; }\n    protected getCss(): string[] | undefined {\n        return [\n            rootCss,\n            stylesCss,\n            commonCss,\n            thisCss,\n        ];\n    }\n\n    componentName: string = this.getComponentName();\n\n    routeRegExp?: RegExp = /apps\\/web1\\/gib\\/about.html/;\n\n    fnHandleRoute = async (arg: {\n        path: string;\n        ibGibAddr?: IbGibAddr | undefined;\n    }) => {\n        if (logalot) { console.log(`Web1Component fnHandleRoute: path: ${arg.path}, ibGibAddr: ${arg.ibGibAddr}`); }\n        return true;\n    }\n\n    constructor() {\n        super();\n    }\n    protected registerCustomElements(): void {\n        customElements.define(this.componentName, Web1ComponentInstance_About);\n    }\n\n}\n\nexport class Web1ComponentInstance_About\n    extends Web1ComponentInstanceBase {\n    protected override lc: string = `[${Web1ComponentInstance_About.name}]`;\n\n    /**\n     *\n     */\n    constructor() {\n        super();\n    }\n\n}\n", "<div id=\"web1-page-blog\" class=\"web1-page\">\n\n    <article>\n\n        <h1>ibgib blog </h1>\n\n        <section>\n\n            <aside><time class=\"blog-date\" datetime=\"2025-06-26\">June 26, 2025</time></aside>\n\n            <h2>AI-Theming and Ibgib Projects are LIVE <i>(...in early alpha)</i></h2>\n            <h3>brief recap</h3>\n            <p>For those of you not yet familiar with ibgib, it's a protocol for truly distributed computation. It\n                resembles more git than blockchain under the hood, and it perfectly dovetails with the Agentic Era. </p>\n            <p>This innovative website in an early alpha stage, utilizing the ibgib protocol throughout its design. In\n                short, everything is an ibgib. The agents are ibgibs, the \"projects\" which we'll get to, the parts of\n                the projects, even the \"chat\" that you see on the right of the screen and even each message within the\n                chat...each and every one of these is an ibgib.</p>\n            <p>And just as git revolutionized code collaboration, the ibgib protocol completely revolutionizes\n                human-agentic collaboration.</p>\n            <h3>ibgib.com Update #1: AI-Theming beyond Light/Dark Themes</h3>\n            <p>First, the shiny: You can now theme the entire website with natural language via the website's primary\n                agent. This isn't just a chatbot and this isn't just a dark theme. We've hooked up the agent with the\n                ability to change so many of the website's colors, and we're among the first to do so.</p>\n            <p>But that's just a fun thing that others can emulate. The new \"projects\" capability is our first step to\n                ibgib awesomeness. </p>\n            <h3>ibgib.com Update #2: Projects have officially begun</h3>\n            <p>On the ibgib.com website, we can now create and interact with Agent-backed projects. Now, \"project\" is\n                just a word - a word to help us understand what an ibgib is. Let me explain.</p>\n            <p>Every serious project is a complex endeavor that breaks down into sub-projects, with individual\n                components that ultimately evolve independently. This trend is especially evident in decoupled hardware\n                and software systems, which rely on intricate supply chain networks. So as project scale increases, so\n                inevitably does this \"sub-project\" sprawl. Git's solution to this (and thus almost everyone's solution)\n                is either a single monorepo or repo sprawl, each with their pros and cons.\n                <button id=\"monorepo-vs-repo-sprawl-btn\" popovertarget=\"monorepo-vs-repo-sprawl\"\n                    class=\"info-popover-btn\" aria-label=\"Show Git Monorepo vs Repo Sprawl Information\">\uD83D\uDEC8</button>\n            </p>\n\n            <div id=\"monorepo-vs-repo-sprawl\" class=\"info-popover\" popover>\n                <button popovertarget=\"monorepo-vs-repo-sprawl\">\u274C</button>\n\n                <h3>\uD83D\uDEC8</h3>\n                <h4>git <b>Monorepo</b></h4>\n                <p>Pros:</p>\n                <ul>\n                    <li>Code sharing and reuse are simplified.</li>\n                    <li>Dependency management is easier to handle.</li>\n                    <li>Atomic changes across multiple components are possible.</li>\n                    <li>Code is easier to discover and navigate.</li>\n                </ul>\n                <p>Cons:</p>\n                <ul>\n                    <li>Can be slow for large projects due to the size of the repository.</li>\n                    <li>Access control can be more complex to manage.</li>\n                    <li>Build and test times increase.</li>\n                </ul>\n                <h4>git <b>Repo Sprawl</b></h4>\n                <p>Pros:</p>\n                <ul>\n                    <li>Faster build and test times due to smaller repository sizes.</li>\n                    <li>Simpler access control.</li>\n                    <li>Easier to understand the codebase for individual components.</li>\n                </ul>\n                <p>Cons:</p>\n                <ul>\n                    <li>Code sharing and reuse are more difficult.</li>\n                    <li>Dependency management is more complex.</li>\n                    <li>Atomic changes across multiple components are not possible.</li>\n                    <li>Code can be harder to discover and navigate.</li>\n                </ul>\n\n            </div>\n\n            <h4>Another Way?</h4>\n            <aside>\n                <p><b>But what if we didn't use git?</b></p>\n            </aside>\n            <p>What git does NOT allow for is sub-file granularity or cross-repo content-addressing. You can't version a\n                function and you can't get a commit hash that points even to a file. So we get tons of small repos with\n                a bunch of unnecessary overhead. This is because git's object database (the thing that has the commit\n                hashes) does not include repo metadata. This is why you have a .git folder with things like refs, hooks,\n                repo description and the config settings proper. None of these are in the object database, so none of\n                these can leverage the git push/pull mechanism that makes the source code versioning so useful across\n                remotes.</p>\n            <p>This is where ibgib and ibgib projects come in.</p>\n            <p>A \"project\" (and a \"sub-project\") is a friendly wrapper term for an \"ibgib\". And an ibgib is like a git\n                repo but at the semantic level. What does this mean? Git works at the file level of granularity (a\n                folder is just a collection of files). But a file is an OS construct and many OS files have tremendous\n                semantic structure, i.e., there can be many \"things\" inside a single file. This is the level that ibgib\n                tracks. Each \"thing\" has a timeline, that looks similar to an entire repo's timeline. Each and every\n                piece of semantic data has its own \"commit hash\" so to speak. When you \"change\" an ibgib, you actually\n                create a new frame on its timeline and link back to the previous address - just like a repo (and a\n                blockchain). </p>\n            <p>This gives us what I call \"supersymmetry\". Each piece of data is individually addressed and thus can be\n                \"imported\" into any arbitrary space. This includes metadata and derivative data. So as complexity grows,\n                we still use the same timeline dynamics as our foundation. There is no separate code required for a\n                package repository. </p>\n            <p>Don't get me wrong, there is still inherent complexity as the projects and subprojects grow. But we\n                minimize this complexity with a uniform foundation upon which to build and version our software\n                artifacts. </p>\n            <p>This approach unlocks an entirely new collaboration paradigm just in time for the explosion that is\n                accompanying the AI-based agent revolution.</p>\n            <h4>check out projects</h4>\n            <p>You can explore the beginnings of our project ibgib implementation by navigating to the Projects Tab in\n                the left panel and selecting 'New Project'. Then hit the plus sign and you'll be off and going.\n                Introduce yourself to your project agent (every ibgib has its own backing agent), and see where it takes\n                you.</p>\n        </section>\n\n        <section>\n\n            <aside><time class=\"blog-date\" datetime=\"2025-03-21\">March 21, 2025</time></aside>\n\n            <h2>First Funding!</h2>\n\n            <p>\n\n                A momentous day, with the first\n                <a href=\"#/apps/web1/gib/funding.html\">funding</a>\n                received from a generous individual: $100 !\n\n            </p>\n\n            <p>\n\n                This may or may not have been prompted by the Google workshop I participated in called <a\n                    href=\"https://rsvp.withgoogle.com/events/build-with-ai-aus\">Build with AI</a>. It was a fun event\n                with a lot of smart, smiling people.\n\n            </p>\n\n            <img src=\"/images/2025-build-with-ai/early_slide.jpg\"\n                alt=\"Shows early on in the workshop with a slide on a projector and some of the other people in the room.\" />\n            <img src=\"/images/2025-build-with-ai/the_view_1.jpg\"\n                alt=\"Shows the view outside of the window, looking out over the river in Austin, TX.\" />\n            <img src=\"/images/2025-build-with-ai/the_view_2.jpg\"\n                alt=\"Shows the view outside of the window, looking down over the sail building adjacent to Google's building where the workshop was held in Austin, TX.\" />\n\n        </section>\n\n\n    </article>\n\n\n\n</div>\n", "#web1-page-blog {\n\n    /* just debugging */\n    aside {\n        background-color: rgba(235, 88, 240, 0.77) !important;\n    }\n\n    img {\n        width: 100%;\n        aspect-ratio: 1/1;\n    }\n}\n", "import thisHtml from './blog.html';\nimport commonCss from '../web1-common.css';\nimport thisCss from './blog.css';\nimport stylesCss from '../../../styles.css';\nimport rootCss from '../../../root.css';\n\nimport { extractErrorMsg } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { IbGibAddr } from \"@ibgib/ts-gib/dist/types.mjs\";\n\nimport { GLOBAL_LOG_A_LOT } from \"../../../constants.mjs\";\nimport { Web1ComponentInstanceBase, Web1ComponentMetaBase } from \"../web1-component-base-one-file.mjs\";\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\n\n\nconst WEB1_COMPONENT_NAME: string = 'web1-blog-component';\nconst WEB1_HTML_PATH: string = '/components/web1/blog/blog.html';\n/**\n * script paths don't really work atow. I mean they are \"loaded\", but there is\n * no way that I can tell to get access to the shadow root of the web component.\n * any scripting I need done that requires this reference I am putting in these\n * component instances' code.\n */\nconst WEB1_SCRIPT_PATHS: string[] = [\n    // '/components/web1/web1-common.mjs',\n    // '/components/web1/blog/blog.mjs',\n];\nconst WEB1_CSS_PATHS: string[] = [\n    '/styles.css',\n    '/components/web1/web1-common.css',\n    '/components/web1/blog/blog.css',\n];\n\nexport const ComponentInfoWeb1_Blog = {\n    componentName: WEB1_COMPONENT_NAME,\n    htmlPath: WEB1_HTML_PATH,\n    scriptPaths: WEB1_SCRIPT_PATHS,\n    cssPaths: WEB1_CSS_PATHS,\n}\n\n/**\n * This is the root component for any web1 component. this will take in the\n * given path, see if it's web 1.0 path, and then delegate to the appropriate\n * web1 sub component (home, funding, etc.);\n */\nexport class Web1ComponentMeta_Blog\n    extends Web1ComponentMetaBase {\n    protected override lc: string = `[${Web1ComponentMeta_Blog.name}]`;\n\n    protected getComponentName(): string { return WEB1_COMPONENT_NAME; }\n    protected getHtml(): string { return thisHtml; }\n    protected getCss(): string[] | undefined {\n        return [\n            rootCss,\n            stylesCss,\n            commonCss,\n            thisCss,\n        ];\n    }\n\n    componentName: string = this.getComponentName();\n\n    routeRegExp?: RegExp = /apps\\/web1\\/gib\\/blog.html/;\n\n    fnHandleRoute = async (arg: {\n        path: string;\n        ibGibAddr?: IbGibAddr | undefined;\n    }) => {\n        if (logalot) { console.log(`Web1Component fnHandleRoute: path: ${arg.path}, ibGibAddr: ${arg.ibGibAddr}`); }\n        return true;\n    }\n\n    constructor() {\n        super();\n    }\n\n    protected registerCustomElements(): void {\n        customElements.define(this.componentName, Web1ComponentInstance_Blog);\n    }\n\n}\n\nexport class Web1ComponentInstance_Blog\n    extends Web1ComponentInstanceBase {\n    protected override lc: string = `[${Web1ComponentInstance_Blog.name}]`;\n\n    /**\n     *\n     */\n    constructor() {\n        super();\n    }\n\n}\n", "<div id=\"web1-page-contact\" class=\"web1-page\">\n\n    <article>\n\n        <section>\n\n            <p>\n                <a href=\"mailto:ibgib.info@gmail.com?subject=ibgib%2Elink%20contact\">\n                    email me\n                </a>\n            </p>\n            <p>Bill Raiford</p>\n\n        </section>\n\n    </article>\n\n</div>\n", "#web1-page-contact {\n\n    /* just debugging */\n    aside {\n        background-color: yellow !important;\n    }\n\n}\n", "import thisHtml from './contact.html';\nimport commonCss from '../web1-common.css';\nimport thisCss from './contact.css';\nimport stylesCss from '../../../styles.css';\nimport rootCss from '../../../root.css';\n\nimport { extractErrorMsg } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { IbGibAddr } from \"@ibgib/ts-gib/dist/types.mjs\";\n\nimport { GLOBAL_LOG_A_LOT } from \"../../../constants.mjs\";\nimport { Web1ComponentInstanceBase, Web1ComponentMetaBase } from \"../web1-component-base-one-file.mjs\";\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\n\nconst WEB1_COMPONENT_NAME: string = 'web1-contact-component';\nconst WEB1_HTML_PATH: string = '/components/web1/contact/contact.html';\n/**\n * script paths don't really work atow. I mean they are \"loaded\", but there is\n * no way that I can tell to get access to the shadow root of the web component.\n * any scripting I need done that requires this reference I am putting in these\n * component instances' code.\n */\nconst WEB1_SCRIPT_PATHS: string[] = [\n    // '/components/web1/web1-common.mjs',\n    // '/components/web1/contact/contact.mjs',\n];\nconst WEB1_CSS_PATHS: string[] = [\n    '/styles.css',\n    '/components/web1/web1-common.css',\n    '/components/web1/contact/contact.css',\n];\n\nexport const ComponentInfoWeb1_Contact = {\n    componentName: WEB1_COMPONENT_NAME,\n    htmlPath: WEB1_HTML_PATH,\n    scriptPaths: WEB1_SCRIPT_PATHS,\n    cssPaths: WEB1_CSS_PATHS,\n}\n\n/**\n * This is the root component for any web1 component. this will take in the\n * given path, see if it's web 1.0 path, and then delegate to the appropriate\n * web1 sub component (home, funding, etc.);\n */\nexport class Web1ComponentMeta_Contact\n    extends Web1ComponentMetaBase {\n    protected override lc: string = `[${Web1ComponentMeta_Contact.name}]`;\n\n    protected getComponentName(): string { return WEB1_COMPONENT_NAME; }\n    protected getHtml(): string { return thisHtml; }\n    protected getCss(): string[] | undefined {\n        return [\n            rootCss,\n            stylesCss,\n            commonCss,\n            thisCss,\n        ];\n    }\n\n    componentName: string = this.getComponentName();\n\n    routeRegExp?: RegExp = /apps\\/web1\\/gib\\/contact.html/;\n\n    fnHandleRoute = async (arg: {\n        path: string;\n        ibGibAddr?: IbGibAddr | undefined;\n    }) => {\n        if (logalot) { console.log(`Web1Component fnHandleRoute: path: ${arg.path}, ibGibAddr: ${arg.ibGibAddr}`); }\n        return true;\n    }\n\n    constructor() {\n        super();\n    }\n    protected registerCustomElements(): void {\n        customElements.define(this.componentName, Web1ComponentInstance_Contact);\n    }\n\n}\n\nexport class Web1ComponentInstance_Contact\n    extends Web1ComponentInstanceBase {\n    protected override lc: string = `[${Web1ComponentInstance_Contact.name}]`;\n\n    /**\n     *\n     */\n    constructor() {\n        super();\n    }\n\n}\n", "<div id=\"web1-page-faq\" class=\"web1-page\">\n\n    <article>\n\n        <h1>FAQ - Frequently Asked Queries</h1>\n\n        <section>\n\n            <h2>q's on ibgib...</h2>\n\n            <aside>why not...?</aside>\n\n            <section class=\"qa\">\n\n                <div class=\"question\">\n                    <p>Why not use GitHub/GitLab/etc?</p>\n                </div>\n                <div class=\"answer\">\n\n                    <p>\n\n                        As I've said elsewhere, git is the greatest monopoly\n                        ever, and arguably the greatest piece of software\n                        written to date. Like all GOAT questions, this can never\n                        be resolved, but it is at the very least \"in the\n                        conversation\".\n\n                    </p>\n\n                    <p>\n\n                        It will also be obselete by 2030.\n\n                    </p>\n                    <p>\n\n                        This does not mean it will\n                        no longer exist of course, rather, it will be recognized as\n                        relatively inefficient for the AI era. There is too much\n                        overhead for too many informational branches and \"remotes\"\n                        with the explosion of agents.\n\n                    </p>\n\n                    <p>\n\n                        Also GitHub is the arguably the greatest SAAS to date,\n                        giving birth to gitops. And gitops is a nightmare of\n                        complexity, as is other out-of-band, non-versioned\n                        metadata and derivatives such as issues and discussions.\n\n                    </p>\n\n                    <aside><b>all in the same graph</b></aside>\n\n                    <p>\n\n                        In ibgib, **EVERYTHING** uses the same semi-structure -\n                        something I call supersymmetry. It is kind of like\n                        adding version control at the file level (though it's\n                        even finer grained than this at the semantic level).\n                        <b>As such, we can include things like commit messages,\n                            issue tracking, discussions, pull requests, etc. ALL IN\n                            THE SAME GRAPH projection as the code that it\n                            describes</b>. This also applies to specs, packages,\n                        \"and much much more\u2122\"! These are all things that in one\n                        way or another get shoehorned into git. And in\n                        programming, we have a term for this: \"code smell\". But\n                        for some unfathomable reason, normally <i>extremely</i>\n                        intelligent (i.e. the smartest humans on the planet)\n                        people have lost their noses.\n\n                    </p>\n\n            </section>\n\n            <section class=\"qa\">\n\n                <div class=\"question\">\n                    <p>Why not use GoFundMe or Kickstarter?</p>\n                </div>\n                <div class=\"answer\">\n                    <p>\n\n                        Ibgib's protocol seeks to provide \"granular\" version\n                        control-like capabilities, but also granular\n                        compensation/financial support. This will address not\n                        only \"open source\" remuneration (a problem simply\n                        unsolvable with today's infrastructure), but service\n                        remuneration in general. This would place it in\n                        competition with the services like GoFundMe and\n                        Kickstarter, which similar to the case of git,\n                        ultimately will not be granular enough for the explosion\n                        we are about to experience.\n\n                    </p>\n\n                </div>\n\n\n            </section>\n\n            <section class=\"qa\">\n\n                <div class=\"question\">\n                    <p>Why not use existing web3 tech...don't they do what ibgib does?</p>\n                </div>\n                <div class=\"answer\">\n\n                    <aside>As soon as you version control in git, you've lost.</aside>\n\n                    <p>\n\n                        Yes. But the question is at what cost? Most people think\n                        of \"efficient\" in terms of time. But there are also\n                        costs in terms of complexity. And not only that,\n                        complexity at what <i>scale</i>?\n\n                    </p>\n                    <p>\n\n                        Ibgib has an upfront complexity cost of incorporating\n                        time with data. This makes it <i>entirely</i> unsuitable\n                        for small scales. But the long-term simplicity gains\n                        will outweigh that initial cost, whereas existing\n                        technologies explode in complexity and cannot meet the\n                        scale without an exponential growth of surface area.\n                        This means less interoperability, fewer features, and\n                        necessarily less security <i>even possible</i>.\n\n                    </p>\n\n                    <aside>supply chain complexity explosion</aside>\n\n                    <p>\n\n                        For example, say you are building a web3 \"dapp\"\n                        (decentralized application). You will write src that\n                        goes in a repo. Already now, you have <i>at least</i>\n                        two separate Merkle-based buckets for data: 1) src data\n                        goes in git (a Merkle DAG), and 2) your dapp's\n                        infrastructure which hooks up to (most likely) a\n                        blockchain (a Merkle-linked list). You most likely also\n                        have intermediate artifacts like packages hosted on,\n                        e.g., npm (like ibgib does). While not strictly a Merkle\n                        DAG/blockchain, package managers still ad hoc do\n                        essentially the same thing: version control (tar) files\n                        via content addressing and provide integrity guarantees\n                        via a hashing mechanism to prevent tampering. Now not\n                        only do they have to maintain the security of their own\n                        infrastructure, but you have to maintain your\n                        credentials and infrastructure for connecting to their\n                        infrastructure. And this is only for package derivates.\n                        What about issue tracking, not only with the issues but\n                        with identity? Commit messages? Code conversations?\n                        <b>And this explodes for each participant in the supply\n                            chain.</b>\n\n                    </p>\n\n                </div>\n\n\n            </section>\n\n            <section>\n\n                <div class=\"question\">\n                    todo: ... more questions...\n                </div>\n                <div class=\"answer\">\n                    todo: ... more answers...\n                </div>\n\n\n            </section>\n\n        </section>\n\n        <!-- <section>\n\n            <h2>q's on this website...</h2>\n\n            <aside></aside>\n\n        </section> -->\n\n\n    </article>\n\n\n\n</div>\n", "#web1-page-faq {\n\n    /* just debugging */\n    aside {\n        background-color: rgb(255, 247, 0) !important;\n    }\n\n    .qa {\n        margin-bottom: 10px;\n    }\n\n    .question {\n        font-weight: bold;\n\n        ::first-letter {\n            font-size: x-large;\n        }\n    }\n\n    .answer {\n        margin-top: 10px;\n    }\n}\n", "import thisHtml from './faq.html';\nimport commonCss from '../web1-common.css';\nimport thisCss from './faq.css';\nimport stylesCss from '../../../styles.css';\nimport rootCss from '../../../root.css';\n\nimport { extractErrorMsg } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { IbGibAddr } from \"@ibgib/ts-gib/dist/types.mjs\";\n\nimport { GLOBAL_LOG_A_LOT } from \"../../../constants.mjs\";\nimport { Web1ComponentInstanceBase, Web1ComponentMetaBase } from \"../web1-component-base-one-file.mjs\";\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\n\n\nconst WEB1_COMPONENT_NAME: string = 'web1-faq-component';\nconst WEB1_HTML_PATH: string = '/components/web1/faq/faq.html';\n/**\n * script paths don't really work atow. I mean they are \"loaded\", but there is\n * no way that I can tell to get access to the shadow root of the web component.\n * any scripting I need done that requires this reference I am putting in these\n * component instances' code.\n */\nconst WEB1_SCRIPT_PATHS: string[] = [\n    // '/components/web1/web1-common.mjs',\n    // '/components/web1/faq/faq.mjs',\n];\nconst WEB1_CSS_PATHS: string[] = [\n    '/styles.css',\n    '/components/web1/web1-common.css',\n    '/components/web1/faq/faq.css',\n];\n\nexport const ComponentInfoWeb1_Faq = {\n    componentName: WEB1_COMPONENT_NAME,\n    htmlPath: WEB1_HTML_PATH,\n    scriptPaths: WEB1_SCRIPT_PATHS,\n    cssPaths: WEB1_CSS_PATHS,\n}\n\n/**\n * This is the root component for any web1 component. this will take in the\n * given path, see if it's web 1.0 path, and then delegate to the appropriate\n * web1 sub component (home, funding, etc.);\n */\nexport class Web1ComponentMeta_Faq\n    extends Web1ComponentMetaBase {\n    protected override lc: string = `[${Web1ComponentMeta_Faq.name}]`;\n\n    protected getComponentName(): string { return WEB1_COMPONENT_NAME; }\n    protected getHtml(): string { return thisHtml; }\n    protected getCss(): string[] | undefined {\n        return [\n            rootCss,\n            stylesCss,\n            commonCss,\n            thisCss,\n        ];\n    }\n\n    componentName: string = this.getComponentName();\n\n    routeRegExp?: RegExp = /apps\\/web1\\/gib\\/faq.html/;\n\n    fnHandleRoute = async (arg: {\n        path: string;\n        ibGibAddr?: IbGibAddr | undefined;\n    }) => {\n        if (logalot) { console.log(`Web1Component fnHandleRoute: path: ${arg.path}, ibGibAddr: ${arg.ibGibAddr}`); }\n        return true;\n    }\n\n    constructor() {\n        super();\n    }\n    protected registerCustomElements(): void {\n        customElements.define(this.componentName, Web1ComponentInstance_Faq);\n    }\n\n}\n\nexport class Web1ComponentInstance_Faq\n    extends Web1ComponentInstanceBase {\n    protected override lc: string = `[${Web1ComponentInstance_Faq.name}]`;\n\n    /**\n     *\n     */\n    constructor() {\n        super();\n    }\n\n}\n", "<div id=\"web1-page-funding\" class=\"web1-page\">\n    <button id=\"funding-jump-to-how-btn\">jump to how to fund ibgib...</button>\n    <article>\n\n        <section>\n\n            <aside>\n                Tick. Tock. Tick. Tock.\n            </aside>\n\n            <p>\n\n                Currently \"ibgib\" is an assumed name, here in San Antonio, TX,\n                with next to zero funding, all the while being a ridiculously\n                ENORMOUS opportunity. Fortunately, git's monopoly is so\n                ABSOLUTE, we are still in no danger of being beaten to the punch\n                of genuinely effective AI tools. But the clock is ticking.\n\n            </p>\n\n\n        </section>\n\n        <section>\n            <h2>funding received so far</h2>\n\n            <aside>\n\n                <p>\n                    total: <span id=\"funding-received-so-far\">100</span>\n                </p>\n\n            </aside>\n\n            <p>As of <time datetime=\"2025-03-21\">2025/03/21</time>), ONE charitable soul has funded us!\uD83D\uDE2E\uD83D\uDE2E\uD83D\uDE2E</p>\n            <p>\n\n                Be the SECOND to fund a lifelong project from a certified,\n                <i>slightly</i> mad genius.\n\n            </p>\n\n        </section>\n\n        <section class=\"financial-section\">\n            <h2>funding breakdown, aka supporters</h2>\n\n            <table>\n                <thead>\n                    <tr>\n                        <th>When</th>\n                        <th>Who</th>\n                        <th>What</th>\n                        <th>Comments</th>\n                    </tr>\n                </thead>\n                <tbody id=\"funding-supporters-table-body\">\n                    <tr>\n                        <td><time datetime=\"2025-03-21\">2025/03/21</time></td>\n                        <td>AG</td>\n                        <td>$100</td>\n                        <td>The Very First!! Thank you AG!</td>\n                    </tr>\n                </tbody>\n            </table>\n\n        </section>\n\n        <section class=\"financial-section\">\n            <h2>other funding, expenditures</h2>\n\n            <table>\n                <thead>\n                    <tr>\n                        <th>When</th>\n                        <th>Who</th>\n                        <th>What</th>\n                        <th>Comments</th>\n                    </tr>\n                </thead>\n                <tbody id=\"funding-supporters-table-body\">\n                    <tr>\n                        <td><time datetime=\"2025-03-11\">2025/03/11</time></td>\n                        <td>KA</td>\n                        <td>$5</td>\n                        <td>Test</td>\n                    </tr>\n                    <tr>\n                        <td><time datetime=\"2025-03-11\">2025/03/11</time></td>\n                        <td>KA</td>\n                        <td>$20</td>\n                        <td>Assumed name</td>\n                    </tr>\n                    <tr>\n                        <td><time datetime=\"2025-03-14\">2025/03/14</time></td>\n                        <td>COUNTY OF BEXAR COUNTY</td>\n                        <td>-$21</td>\n                        <td>Assumed name</td>\n                    </tr>\n                    <tr>\n                        <td><time datetime=\"2025-03-14\">2025/03/14</time></td>\n                        <td>MUNICIPAL SERVICE FEE</td>\n                        <td>-$0.54</td>\n                        <td>Assumed name</td>\n                    </tr>\n                    <tr>\n                        <td><time datetime=\"2025-03-14\">2025/03/14</time></td>\n                        <td>MUNICIPAL SERVICE FEE</td>\n                        <td>-$0.54</td>\n                        <td>Assumed name</td>\n                    </tr>\n                    <tr>\n                        <td><time datetime=\"2025-03-20\">2025/03/20</time></td>\n                        <td>KA</td>\n                        <td>$125</td>\n                        <td>Austin trip for Google Cloud's Build with AI event</td>\n                    </tr>\n                    <tr>\n                        <td><time datetime=\"2025-03-21\">2025/03/21</time></td>\n                        <td>HEB Gas</td>\n                        <td>-$32.12</td>\n                        <td>Gas</td>\n                    </tr>\n                    <tr>\n                        <td><time datetime=\"2025-03-21\">2025/03/21</time></td>\n                        <td>500 W 2ND ST GARAG</td>\n                        <td>-$36</td>\n                        <td>Parking for Google Cloud's Build with AI event</td>\n                    </tr>\n                    <tr>\n                        <td><time datetime=\"2025-04-08\">2025/04/08</time></td>\n                        <td>NAME-CHEAP.COM</td>\n                        <td>-$68.64</td>\n                        <td>Renew domains ibgib.com, .app, .link, .dev</td>\n                    </tr>\n                    <tr>\n                        <td><time datetime=\"2025-04-09\">2025/04/09</time></td>\n                        <td>HEB Gas</td>\n                        <td>-$40</td>\n                        <td>Gas</td>\n                    </tr>\n                    <tr>\n                        <td><time datetime=\"2025-04-15\">2025/04/15</time></td>\n                        <td>KA</td>\n                        <td>$5</td>\n                        <td>GFiber</td>\n                    </tr>\n                    <tr>\n                        <td><time datetime=\"2025-04-15\">2025/04/15</time></td>\n                        <td>GOOGLE *FIBER</td>\n                        <td>$5</td>\n                        <td>GFiber</td>\n                    </tr>\n                </tbody>\n            </table>\n\n        </section>\n\n        <section id=\"how-to-fund\">\n\n            <h2>how to fund ibgib?</h2>\n            <aside>\n                web1 links are only temporary \uD83D\uDE09\n            </aside>\n            <p>\n\n                Your personal support would be GREATLY appreciated. Please let\n                me know if you'd like recognition (initials, full name) or not.\n                I will default to anonymous.\n\n            </p>\n            <ul>\n                <li><a href=\"https://paypal.me/ibgib\">paypal.me/ibgib</a></li>\n            </ul>\n\n        </section>\n\n        <section>\n\n            <aside>Would you rather be the King of England or an American Executive?</aside>\n\n            <h2>how to <i><b>invest</b></i> in ibgib?</h2>\n            <p>\n\n                I am actively looking for larger, more formal early stage\n                funding with the following requirements:\n\n            </p>\n            <ul>\n                <li>The ibgib protocol itself requires a non-profit company that...\n                    <ul>\n                        <li>protects the interests of the protocol ecosystem</li>\n                        <li>is 100% open source</li>\n                        <li>is 100% open data with transparent finances</li>\n                        <li>has me, William Raiford, as the CEO.</li>\n                    </ul>\n                </li>\n                <li>Use case, for-profit companies that I personally am involved in must...\n                    <ul>\n                        <li>dogfood the protocol for...\n                            <ul>\n                                <li>version control for src, hardware specs\n                                    (e.g. cads), models, and other aspects.</li>\n                                <li>learning (e.g., company/project onboarding)</li>\n                                <li>inter-company communications</li>\n                                <li>dev sec ops to the greatest extent possible</li>\n                            </ul>\n                        </li>\n                        <li>employ me at the lowest employee's base salary rate</li>\n                        <li>be incentive- and performance-based</li>\n                        <li>provide transparent salary/bonus information (again\n                            dogfooding the protocol)</li>\n                        <li>provide a tenuring mechanism guaranteeing the lowest\n                            salary rate for life (as an actually viable alternative\n                            to UBI)</li>\n                    </ul>\n                </li>\n                <li><i><b>Genuinely innovative</b></i> use case companies in\n                    which I am personally interested include...\n                    <ul>\n                        <li>solving distributed remuneration</li>\n                        <li>ai-based code creation</li>\n                        <li>lifelong learning across all domains</li>\n                        <li>autonomous iot agents</li>\n                    </ul>\n                </li>\n            </ul>\n\n            <p>\n\n                Essentially, we are going for the sovereign-side of the DAO\n                approach. If you are interested, our best path forward is to\n                <a href=\"#/apps/web1/gib/contact.html\">contact me</a> to discuss\n                how we can best meet your - hopefully excessive - financial\n                goals while adhering to the above requirements.\n\n            </p>\n\n        </section>\n\n    </article>\n</div>\n", "#web1-page-funding {\n\n    #funding-received-so-far::before {\n        content: \"$\";\n    }\n\n    #funding-received-so-far {\n        font-weight: bold;\n        color: #042407;\n        text-align: right;\n    }\n\n    /* just debugging */\n    aside {\n        background-color: gold !important;\n    }\n\n    button {\n        color: var(--text-color-base);\n        font-size: xx-large;\n        margin-bottom: 5vh;\n    }\n\n    .financial-section {\n        overflow: auto;\n        max-height: 67vh;\n    }\n}\n", "import thisHtml from './funding.html';\nimport commonCss from '../web1-common.css';\nimport thisCss from './funding.css';\nimport stylesCss from '../../../styles.css';\nimport rootCss from '../../../root.css';\n\nimport { delay, extractErrorMsg } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { IbGibAddr } from \"@ibgib/ts-gib/dist/types.mjs\";\nimport { alertUser, highlightElement } from \"@ibgib/web-gib/dist/helpers.web.mjs\";\n\nimport { GLOBAL_LOG_A_LOT } from \"../../../constants.mjs\";\nimport { Web1ComponentInstanceBase, Web1ComponentMetaBase } from \"../web1-component-base-one-file.mjs\";\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\n\nconst WEB1_COMPONENT_NAME: string = 'web1-funding-component';\nconst WEB1_HTML_PATH: string = '/components/web1/funding/funding.html';\n/**\n * script paths don't really work atow. I mean they are \"loaded\", but there is\n * no way that I can tell to get access to the shadow root of the web component.\n * any scripting I need done that requires this reference I am putting in these\n * component instances' code.\n */\nconst WEB1_SCRIPT_PATHS: string[] = [\n    // '/components/web1/web1-common.mjs',\n    // '/components/web1/funding/funding.mjs',\n];\nconst WEB1_CSS_PATHS: string[] = [\n    '/styles.css',\n    '/components/web1/web1-common.css',\n    '/components/web1/funding/funding.css',\n];\n\nexport const ComponentInfoWeb1_Funding = {\n    componentName: WEB1_COMPONENT_NAME,\n    htmlPath: WEB1_HTML_PATH,\n    scriptPaths: WEB1_SCRIPT_PATHS,\n    cssPaths: WEB1_CSS_PATHS,\n}\n\n/**\n * This is the root component for any web1 component. this will take in the\n * given path, see if it's web 1.0 path, and then delegate to the appropriate\n * web1 sub component (home, funding, etc.);\n */\nexport class Web1ComponentMeta_Funding\n    extends Web1ComponentMetaBase {\n    protected override lc: string = `[${Web1ComponentMeta_Funding.name}]`;\n\n    protected getComponentName(): string { return WEB1_COMPONENT_NAME; }\n    protected getHtml(): string { return thisHtml; }\n    protected getCss(): string[] | undefined {\n        return [\n            rootCss,\n            stylesCss,\n            commonCss,\n            thisCss,\n        ];\n    }\n\n    componentName: string = this.getComponentName();\n\n    routeRegExp?: RegExp = /apps\\/web1\\/gib\\/funding.html/;\n\n    fnHandleRoute = async (arg: {\n        path: string;\n        ibGibAddr?: IbGibAddr | undefined;\n    }) => {\n        if (logalot) { console.log(`Web1Component fnHandleRoute: path: ${arg.path}, ibGibAddr: ${arg.ibGibAddr}`); }\n        return true;\n    }\n\n    constructor() {\n        super();\n    }\n    protected registerCustomElements(): void {\n        customElements.define(this.componentName, Web1ComponentInstance_Funding);\n    }\n\n}\n\nexport class Web1ComponentInstance_Funding\n    extends Web1ComponentInstanceBase {\n    protected override lc: string = `[${Web1ComponentInstance_Funding.name}]`;\n\n    /**\n     *\n     */\n    constructor() {\n        super();\n    }\n\n\n    override async created(): Promise<void> {\n        const lc = `${this.lc}[${this.created.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 2088bd2d46691df394f9f392934dd325)`); }\n            await super.created();\n\n            // init jumpBtn\n            const jumpBtn = this.shadowRoot?.getElementById('funding-jump-to-how-btn') as HTMLButtonElement;\n            if (jumpBtn) {\n                highlightElement({\n                    el: jumpBtn,\n                    magicHighlightTimingMs: 2000,\n                }); // spin off\n                const howToFund = this.shadowRoot!.getElementById('how-to-fund') as HTMLElement;\n                if (howToFund) {\n                    jumpBtn.addEventListener('click', async () => {\n                        await highlightElement({\n                            el: howToFund,\n                            magicHighlightTimingMs: 1000,\n                            scrollIntoView: true,\n                        });\n                    });\n                } else {\n                    // console.error(`${lc} (unexpected) howToFund falsy? (E: 922a43a96fa58a7268c24e555d11ec25)`);\n                    alertUser({ title: 'eek', msg: `how embarassing... can't find the how to fund section? contact me to let me know please... (E: 922a43a96fa58a7268c24e555d11ec25)` });\n                }\n            } else {\n                console.error(`(UNEXPECTED) ? (E: 7eb4b6b49eb4aee6bfd833687d25cf25)`);\n            }\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n\n    }\n}\n", "<div id=\"web1-page-home\" class=\"web1-page\">\n\n    <article>\n\n        <h1><b>NEW, AI-FIRST Version Control Paradigm</b></h1>\n\n        <section>\n\n            <h2>ibgib is...</h2>\n\n            <aside>All previous coding paradigms will be dwarfed by AI-first <b>version control</b>.</aside>\n\n            <p>\n\n                a new and unique DLT protocol to enable new and unique\n                distributed computing in the age of AI. This means a <i>genuinely</i>\n                new and innovative collaboration paradigm among humans and AI,\n                and <i>that</i> will create an exponential growth of src +\n                derivates + metadata, both by humans and AI <b>together</b>.\n\n            </p>\n        </section>\n\n        <section>\n\n            <h2>git was...</h2>\n\n            <aside>all git-based solutions will be obselete by 2030</aside>\n\n            <p>\n\n                the greatest piece of software over the last 20 years by market\n                and mindshare. <b>No one even thinks about not using it.</b> But\n                git simply is not granular enough for the AI era without serious\n                kluging.\n\n            </p>\n\n        </section>\n\n        <section>\n\n            <h2>You must focus...</h2>\n            <aside>\n\n                <iframe src=\"https://www.youtube.com/embed/Ev80GGP5VNc?si=XMu9tnENL7tb5EDF&amp;start=390\"\n                    title=\"Excellent video by Hanno Embregts showing version control systems on timeline depicting mobile phone style at the time. git is at 2005 and NOTHING is after this. That's 20 years!\"\n                    frameborder=\"0\"\n                    allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\"\n                    referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen></iframe>\n\n            </aside>\n\n            <p>\n\n                on an AI-FIRST <b>Version Control\n                    Paradigm</b> - even if it's not ibgib. Watch <b>JUST 20\n                    seconds</b> of this video - the only VCS\n                being built since 2005. <b>THAT'S 20+ YEARS AGO!!</b>\n\n            </p>\n\n        </section>\n\n        <section>\n\n            <h2>AI coding is...</h2>\n\n            <aside><b>Every</b> AI tool falls short on non-trivial solutions.</aside>\n\n            <p>\n\n                speculative at best. A ground-up rewrite of version control\n                with AI as a first-class citizen is today's missing ingredient\n                to truly effective agentic systems. And thanks to git's\n                overpowering success as literally (literally!) the world's\n                greatest software ever written and consequently the greatest\n                software monopoly, this is an <b>ENORMOUSLY UNDERRATED</b>\n                opportunity.\n\n            </p>\n\n            <p>\n\n                So click on the Projects tab and get started.\n\n            </p>\n\n        </section>\n\n\n    </article>\n\n\n\n</div>\n", "/* #web1-page-home {\n\n    aside {\n        background-color: orange !important;\n    }\n\n} */\n", "import thisHtml from './home.html';\nimport commonCss from '../web1-common.css';\nimport thisCss from './home.css';\nimport stylesCss from '../../../styles.css';\nimport rootCss from '../../../root.css';\n\nimport { extractErrorMsg } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { IbGibAddr } from \"@ibgib/ts-gib/dist/types.mjs\";\n\nimport { GLOBAL_LOG_A_LOT } from \"../../../constants.mjs\";\nimport { Web1ComponentInstanceBase, Web1ComponentMetaBase } from \"../web1-component-base-one-file.mjs\";\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\n\n\nconst WEB1_COMPONENT_NAME: string = 'web1-home-component';\n\n/**\n * This is the root component for any web1 component. this will take in the\n * given path, see if it's web 1.0 path, and then delegate to the appropriate\n * web1 sub component (home, funding, etc.);\n */\nexport class Web1ComponentMeta_Home\n    extends Web1ComponentMetaBase {\n    protected override lc: string = `[${Web1ComponentMeta_Home.name}]`;\n\n    protected getComponentName(): string { return WEB1_COMPONENT_NAME; }\n    protected getHtml(): string { return thisHtml; }\n    protected getCss(): string[] | undefined {\n        return [\n            rootCss,\n            stylesCss,\n            commonCss,\n            thisCss\n        ];\n    }\n\n    componentName: string = this.getComponentName();\n\n    routeRegExp?: RegExp = /apps\\/web1\\/gib\\/home.html/;\n\n    fnHandleRoute = async (arg: {\n        path: string;\n        ibGibAddr?: IbGibAddr | undefined;\n    }) => {\n        if (logalot) { console.log(`Web1Component fnHandleRoute: path: ${arg.path}, ibGibAddr: ${arg.ibGibAddr}`); }\n        return true;\n    }\n\n    constructor() {\n        super();\n    }\n    protected registerCustomElements(): void {\n        customElements.define(this.componentName, Web1ComponentInstance_Home);\n    }\n\n}\n\nexport class Web1ComponentInstance_Home\n    extends Web1ComponentInstanceBase {\n    protected override lc: string = `[${Web1ComponentInstance_Home.name}]`;\n\n    /**\n     *\n     */\n    constructor() {\n        super();\n    }\n\n}\n", "<!-- <div id=\"web1-page-links\" class=\"web1-page\"> -->\n<!-- <iframe part=\"links-page\" src=\"/apps/web1/gib/link-gib/dist/index.html\"></iframe> -->\n<div id=\"links-container\"></div>\n<!-- </div> -->\n", "/* #web1-page-links {\n\n    border-color: pink;\n    border-width: 15px;\n    border-style: solid;\n\n    aside {\n        background-color: blue !important;\n    }\n\n} */\n\n#links-container {\n    display: flex;\n    flex-direction: column;\n    gap: 2rem;\n    padding: 1rem;\n    max-width: 800px;\n    margin: 0 auto;\n}\n\n.link-group {\n    display: flex;\n    flex-direction: column;\n    gap: 1rem;\n}\n\n.link-group h2 {\n    color: var(--chronology-agent-text-color);\n    border-bottom: 2px solid var(--primary-border-color);\n    padding-bottom: 0.5rem;\n    margin-bottom: 0.5rem;\n    text-transform: capitalize;\n}\n\n.link-entry {\n    background-color: var(--very-light-background-color);\n    border: 1px solid var(--primary-border-color);\n    border-radius: 8px;\n    padding: 1.5rem;\n    display: flex;\n    flex-direction: column;\n    gap: 0.75rem;\n    transition: all 0.3s ease;\n    max-height: 50dvh;\n    overflow-y: auto;\n    position: relative;\n    cursor: pointer;\n}\n\n.link-entry.expanded {\n    max-height: none;\n}\n\n.link-entry:hover {\n    transform: translateY(-2px);\n    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);\n    border-color: var(--primary-border-color-dark);\n}\n\n.link-header {\n    display: flex;\n    justify-content: space-between;\n    align-items: center;\n    gap: 1rem;\n}\n\n.link-name {\n    font-weight: bold;\n    font-size: 1.1rem;\n    color: var(--text-color-base);\n}\n\n.link-actions {\n    display: flex;\n    gap: 0.5rem;\n}\n\n.copy-button {\n    background-color: var(--button-background-color-base);\n    color: var(--button-text-color-base);\n    border: 1px solid var(--button-border-color-base);\n    border-radius: var(--button-border-radius-base);\n    padding: 4px 10px;\n    cursor: pointer;\n    font-size: 0.8rem;\n    transition: all 0.2s ease;\n}\n\n.copy-button:hover {\n    background-color: var(--button-hover-background-color);\n    border-color: var(--button-hover-border-color);\n}\n\n.link-description {\n    font-size: 0.95rem;\n    line-height: 1.5;\n    color: var(--text-color-base);\n}\n\n.link-url-container {\n    word-break: break-all;\n    font-size: 0.85rem;\n}\n\n.link-url {\n    color: var(--link-color);\n    text-decoration: var(--link-text-decoration);\n}\n\n.link-url:hover {\n    color: var(--link-hover-color);\n    text-decoration: var(--link-hover-text-decoration);\n}\n\n.video-container {\n    position: relative;\n    padding-bottom: 56.25%; /* 16:9 aspect ratio */\n    height: 0;\n    overflow: hidden;\n    max-width: 100%;\n    background: #000;\n    border-radius: 4px;\n    margin-bottom: 0.75rem;\n}\n\n.video-container iframe {\n    position: absolute;\n    top: 0;\n    left: 0;\n    width: 100%;\n    height: 100%;\n}", "import thisHtml from './links.html';\nimport commonCss from '../web1-common.css';\nimport thisCss from './links.css';\nimport stylesCss from '../../../styles.css';\nimport rootCss from '../../../root.css';\n\nimport { extractErrorMsg } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { IbGibAddr } from \"@ibgib/ts-gib/dist/types.mjs\";\n\nimport { GLOBAL_LOG_A_LOT } from \"../../../constants.mjs\";\nimport { Web1ComponentInstanceBase, Web1ComponentMetaBase } from \"../web1-component-base-one-file.mjs\";\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\nconst WEB1_COMPONENT_NAME: string = 'web1-links-component';\nconst WEB1_HTML_PATH: string = '/components/web1/links/links.html';\n\nconst WEB1_SCRIPT_PATHS: string[] = [];\nconst WEB1_CSS_PATHS: string[] = [\n    '/styles.css',\n    '/components/web1/web1-common.css',\n    '/components/web1/links/links.css',\n];\n\nexport const ComponentInfoWeb1_Links = {\n    componentName: WEB1_COMPONENT_NAME,\n    htmlPath: WEB1_HTML_PATH,\n    scriptPaths: WEB1_SCRIPT_PATHS,\n    cssPaths: WEB1_CSS_PATHS,\n}\n\nconst LINK_DATA = [\n    {\n        group: 'motivation',\n        links: [\n            {\n                name: 'graph of version control systems by cellphone technology',\n                description: `A profound, surprisingly hard-hitting video by a git instructor who made an absolutely striking graphic, depicting version control systems next to each's cellphone of the day. He looked into git alternatives once a student asked why nothing happened after 2005. <b>A must-watch video, also highlighting Pijul's move into non-source code domain</b> (but still text only).`,\n                url: 'https://youtu.be/Ev80GGP5VNc?t=390',\n                embedUrl: 'https://www.youtube.com/embed/Ev80GGP5VNc?start=390',\n            },\n            {\n                name: 'git technical debt, or: How do I delete a Git branch locally and remotely?',\n                description: `<p>git is one of the greatest, most successful pieces of software. it's also a <a href=\"https://www.investopedia.com/terms/n/natural_monopoly.asp\" target=\"_blank\">natural monopoly</a>.</p>\n                    <p>check out these <em>incredible</em> stats as both a measure of git's success, <b>but also its two decades of technical debt</b>. (all atow)\n                    <ul>\n                      <li>over 11 million views</li>\n                      <li>Asked over 14 years, 4 months ago...</li>\n                      <li>...and <em>modified 3 months ago</em></li>\n                      <li>20,377 upvotes on the question</li>\n                      <li>25,884 upvotes on the top answer, <b>which requires an executive summary, two major revisions with the original answer being completely supplanted, and 45 total revisions by 32 users</b></li>\n                      <li>Two <em>pages</em> of answers (41 in all and counting atow), composed of...\n                        <ul>\n                          <li>dozens of less-upvoted questions with 1000s of votes</li>\n                          <li>five answers with graphical aides (unheard of)</li>\n                        </ul>\n                      </li>\n                      <li>a whopping 59,933 upvotes in toto</li>\n                      <li><b>And the cherry on the gr\u00E2ce, 1 absolutely-unheard-of OP question comment by a 46k-rep member to completely circumvent SO's voting mechanism to jump straight to the \"best\" answer</b></li>\n                    </ul>\n                    <p>all of this to do one of the most common actions with the application <em>and it still is a terrible syntax</em>.</p>`,\n                url: 'https://stackoverflow.com/questions/2003505/how-do-i-delete-a-git-branch-locally-and-remotely?page=1',\n            },\n            {\n                name: 'Version Control for Data Scientists',\n                description: `An interesting talk about how practicing data scientists are actually kluging git as a workaround for versioning data models. Definite code smell.`,\n                url: 'https://youtu.be/pah3xJ0tPqI',\n                embedUrl: 'https://www.youtube.com/embed/pah3xJ0tPqI',\n            },\n        ]\n    },\n    {\n        group: 'NPM packages',\n        links: [\n            {\n                name: '@ibgib/web-gib',\n                description: 'Framework for creating agentic ibGib web apps. Contains plumbing for ibgib components, agentic framework (currently only Gemini implemented), web-based IndexedDB storage substrate, and more.',\n                url: 'https://www.npmjs.com/package/@ibgib/web-gib',\n            },\n            {\n                name: '@ibgib/node-gib',\n                description: \"Node and server-specific ibGib code, i.e., things that don't run in the browser.\",\n                url: 'https://www.npmjs.com/package/@ibgib/node-gib',\n            },\n            {\n                name: '@ibgib/encrypt-gib',\n                description: `Custom encryption library that uses an ibgib-friendly, custom (unproven and assumed weak) NOVEL hash-based encryption algorithm. AFAICT it should be post quantum secure, but it has not been thoroughly tested/vetted. I like it though, because I can understand all parts, assuming the magic of the underlying hash function.`,\n                url: 'https://www.npmjs.com/package/@ibgib/encrypt-gib',\n            },\n            {\n                name: '@ibgib/core-gib',\n                description: 'Core functionality like abstract class architecture for witnesses, spaces, etc. Works for both node and the web.',\n                url: 'https://www.npmjs.com/package/@ibgib/core-gib',\n            },\n            {\n                name: '@ibgib/ts-gib',\n                description: 'Graphing substrate for low-level ibgib protocol DAG.',\n                url: 'https://www.npmjs.com/package/@ibgib/ts-gib',\n            },\n            {\n                name: '@ibgib/helper-gib',\n                description: 'Utilities used throughout ibgib libs and apps, but not necessarily ibgib-specific. ATOW includes the custom respec-gib testing framework (for more polite developers).',\n                url: 'https://www.npmjs.com/package/@ibgib/helper-gib',\n            },\n        ]\n    },\n    {\n        group: 'social',\n        links: [\n            {\n                name: 'X (Twitter)',\n                description: 'Rarely used, but present.',\n                url: 'https://x.com/ibgibDOTcom',\n            },\n            {\n                name: 'GitHub',\n                description: `NOTE: OUT-OF-DATE --> Dwindling presence because of onset of dogfooding ibgib's B2tFS. The current repo paradigm is too restrictive. The future is in much more robust and powerful \"version control\" across multiple domains, source code only being one of them.`,\n                url: 'https://github.com/wraiford',\n            },\n            {\n                name: 'GitLab',\n                description: `NOTE: OUT-OF-DATE --> Dwindling presence because of onset of dogfooding ibgib's B2tFS. The current repo paradigm is too restrictive. The future is in much more robust and powerful \"version control\" across multiple domains, source code only being one of them.`,\n                url: 'https://gitlab.com/ibgib',\n            },\n        ]\n    }\n];\n\nexport class Web1ComponentMeta_Links\n    extends Web1ComponentMetaBase {\n    protected override lc: string = `[${Web1ComponentMeta_Links.name}]`;\n\n    protected getComponentName(): string { return WEB1_COMPONENT_NAME; }\n    protected getHtml(): string { return thisHtml; }\n    protected getCss(): string[] | undefined {\n        return [\n            rootCss,\n            stylesCss,\n            commonCss,\n            thisCss,\n        ];\n    }\n\n    componentName: string = this.getComponentName();\n\n    routeRegExp?: RegExp = /apps\\/web1\\/gib\\/links.html/;\n\n    fnHandleRoute = async (arg: {\n        path: string;\n        ibGibAddr?: IbGibAddr | undefined;\n    }) => {\n        if (logalot) { console.log(`Web1Component fnHandleRoute: path: ${arg.path}, ibGibAddr: ${arg.ibGibAddr}`); }\n        return true;\n    }\n\n    constructor() {\n        super();\n    }\n    protected registerCustomElements(): void {\n        customElements.define(this.componentName, Web1ComponentInstance_Links);\n    }\n\n}\n\nconst COPY_ICON_SVG = `\n<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\">\n  <rect x=\"9\" y=\"9\" width=\"13\" height=\"13\" rx=\"2\" ry=\"2\"></rect>\n  <path d=\"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1\"></path>\n</svg>\n`;\n\nexport class Web1ComponentInstance_Links\n    extends Web1ComponentInstanceBase {\n    protected override lc: string = `[${Web1ComponentInstance_Links.name}]`;\n\n    constructor() {\n        super();\n    }\n\n    override async created(): Promise<void> {\n        const lc = `${this.lc}[${this.created.name}]`;\n        try {\n            await super.created();\n            if (logalot) { console.log(`${lc} starting...`); }\n\n            const container = this.shadowRoot?.querySelector('#links-container');\n            if (container) {\n                this.renderLinks(container);\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n        }\n    }\n\n    private renderLinks(container: Element): void {\n        container.innerHTML = '';\n        LINK_DATA.forEach(group => {\n            const groupEl = document.createElement('div');\n            groupEl.className = 'link-group';\n\n            const h2 = document.createElement('h2');\n            h2.textContent = group.group;\n            groupEl.appendChild(h2);\n\n            group.links.forEach(link => {\n                const entryEl = document.createElement('div');\n                entryEl.className = 'link-entry';\n                entryEl.onclick = (e) => {\n                    // Don't toggle if clicking a button or link\n                    if ((e.target as HTMLElement).closest('.copy-button') ||\n                        (e.target as HTMLElement).closest('a')) {\n                        return;\n                    }\n                    entryEl.classList.toggle('expanded');\n                };\n\n                if ((link as any).embedUrl) {\n                    const videoContainer = document.createElement('div');\n                    videoContainer.className = 'video-container';\n                    const iframe = document.createElement('iframe');\n                    iframe.src = (link as any).embedUrl;\n                    iframe.setAttribute('frameborder', '0');\n                    iframe.setAttribute('allow', 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share');\n                    iframe.setAttribute('allowfullscreen', 'true');\n                    videoContainer.appendChild(iframe);\n                    entryEl.appendChild(videoContainer);\n                }\n\n                const headerEl = document.createElement('div');\n                headerEl.className = 'link-header';\n\n                const nameEl = document.createElement('span');\n                nameEl.className = 'link-name';\n                nameEl.textContent = link.name;\n                headerEl.appendChild(nameEl);\n\n                const actionsEl = document.createElement('div');\n                actionsEl.className = 'link-actions';\n\n                const copyBtn = document.createElement('button');\n                copyBtn.className = 'copy-button';\n                copyBtn.innerHTML = COPY_ICON_SVG;\n                copyBtn.title = 'Copy Link';\n                copyBtn.onclick = (e) => {\n                    e.stopPropagation();\n                    this.copyToClipboard(link.url, copyBtn);\n                };\n                actionsEl.appendChild(copyBtn);\n\n                headerEl.appendChild(actionsEl);\n                entryEl.appendChild(headerEl);\n\n                const urlContainer = document.createElement('div');\n                urlContainer.className = 'link-url-container';\n                const a = document.createElement('a');\n                a.className = 'link-url';\n                a.href = link.url;\n                a.target = '_blank';\n                a.textContent = link.url;\n                a.onclick = (e) => e.stopPropagation();\n                urlContainer.appendChild(a);\n                entryEl.appendChild(urlContainer);\n\n                const descEl = document.createElement('div');\n                descEl.className = 'link-description';\n                descEl.innerHTML = link.description;\n                entryEl.appendChild(descEl);\n\n                groupEl.appendChild(entryEl);\n            });\n\n            container.appendChild(groupEl);\n        });\n    }\n\n    private async copyToClipboard(text: string, button: HTMLButtonElement): Promise<void> {\n        try {\n            await navigator.clipboard.writeText(text);\n            const originalContent = button.innerHTML;\n            button.textContent = 'copied!';\n            setTimeout(() => {\n                button.innerHTML = originalContent;\n            }, 2000);\n        } catch (err) {\n            console.error('Failed to copy: ', err);\n        }\n    }\n}\n", "<div id=\"web1-page-challenges\" class=\"web1-page\">\n\n    <article>\n\n        <h1>Challenges</h1>\n\n        <section>\n\n            <h3><i>technical challenges</i></h3>\n\n            <section>\n\n                <aside>identity</aside>\n\n                <p>\n\n                    \n                </p>\n\n            </section>\n\n        </section>\n\n        <section>\n\n            <h3>non-technical challenges \uD83D\uDE44</h3>\n\n            <section>\n\n                <aside>resource allocation</aside>\n\n                <p>\n\n                    I first started with ibgib's unique content addressing schema\n                    over a decade ago. Even the first iteration had...\n\n                </p>\n\n                <ul>\n                    <li>per-use-case `ib` metadata</li>\n                    <li>^ delimiter</li>\n                    <li>`gib` cryptographic hash</li>\n                </ul>\n\n                <p>\n\n                    What it did NOT have was the Temporal Junction Point - an\n                    absolutely crucial aspect that enables time as the first-class\n                    citizen (something that no other DLT protocol has). Since I was\n                    isolated with no help or users, the downsides of solitude came\n                    with the upside of agility.\n\n                </p>\n\n                <p>\n\n                    But now, after several more years, the protocol is quite stable\n                    for v1, and there is no more upside to this process. When I troubleshoot css for this website, I\n                    which\n                    could easily be\n                    handed off to a regular developer, especially even with today's\n                    AI tools.\n\n                </p>\n\n                <p>\n\n                    But there are architectural challenges that still require my\n                    active attention.\n\n                </p>\n            </section>\n        </section>\n\n    </article>\n\n\n\n</div>\n", "#web1-page-challenges {\n\n    /* just debugging */\n    aside {\n        background-color: rgba(136, 255, 0, 0.736) !important;\n    }\n\n}\n", "import thisHtml from './challenges.html';\nimport commonCss from '../web1-common.css';\nimport thisCss from './challenges.css';\nimport stylesCss from '../../../styles.css';\nimport rootCss from '../../../root.css';\n\nimport { IbGibAddr } from \"@ibgib/ts-gib/dist/types.mjs\";\n\nimport { GLOBAL_LOG_A_LOT } from \"../../../constants.mjs\";\nimport { Web1ComponentInstanceBase, Web1ComponentMetaBase } from \"../web1-component-base-one-file.mjs\";\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\n\n\nconst WEB1_COMPONENT_NAME: string = 'web1-challenges-component';\nconst WEB1_HTML_PATH: string = '/components/web1/challenges/challenges.html';\n/**\n * script paths don't really work atow. I mean they are \"loaded\", but there is\n * no way that I can tell to get access to the shadow root of the web component.\n * any scripting I need done that requires this reference I am putting in these\n * component instances' code.\n */\nconst WEB1_SCRIPT_PATHS: string[] = [\n    // '/components/web1/web1-common.mjs',\n    // '/components/web1/challenges/challenges.mjs',\n];\nconst WEB1_CSS_PATHS: string[] = [\n    '/styles.css',\n    '/components/web1/web1-common.css',\n    '/components/web1/challenges/challenges.css',\n];\n\nexport const ComponentInfoWeb1_Challenges = {\n    componentName: WEB1_COMPONENT_NAME,\n    htmlPath: WEB1_HTML_PATH,\n    scriptPaths: WEB1_SCRIPT_PATHS,\n    cssPaths: WEB1_CSS_PATHS,\n}\n\n/**\n * This is the root component for any web1 component. this will take in the\n * given path, see if it's web 1.0 path, and then delegate to the appropriate\n * web1 sub component (home, funding, etc.);\n */\nexport class Web1ComponentMeta_Challenges\n    extends Web1ComponentMetaBase {\n    protected override lc: string = `[${Web1ComponentMeta_Challenges.name}]`;\n\n    protected getComponentName(): string { return WEB1_COMPONENT_NAME; }\n    protected getHtml(): string { return thisHtml; }\n    protected getCss(): string[] | undefined {\n        return [\n            rootCss,\n            stylesCss,\n            commonCss,\n            thisCss,\n        ];\n    }\n\n    componentName: string = this.getComponentName();\n\n    routeRegExp?: RegExp = /apps\\/web1\\/gib\\/challenges.html/;\n\n    fnHandleRoute = async (arg: {\n        path: string;\n        ibGibAddr?: IbGibAddr | undefined;\n    }) => {\n        if (logalot) { console.log(`Web1Component fnHandleRoute: path: ${arg.path}, ibGibAddr: ${arg.ibGibAddr}`); }\n        return true;\n    }\n\n    constructor() {\n        super();\n    }\n    protected registerCustomElements(): void {\n        customElements.define(this.componentName, Web1ComponentInstance_Challenges);\n    }\n\n}\n\nexport class Web1ComponentInstance_Challenges\n    extends Web1ComponentInstanceBase {\n    protected override lc: string = `[${Web1ComponentInstance_Challenges.name}]`;\n\n    /**\n     *\n     */\n    constructor() {\n        super();\n    }\n\n}\n", "<div id=\"web1-page-about-projects\" class=\"web1-page\">\n\n    <article>\n\n        <h1><b>Projects are Chats</b></h1>\n\n        <section>\n\n            <h2>tl;dr</h2>\n\n            <aside>create, chunk, knuch projects by treating chats like repos</aside>\n\n            <p>\n\n                Create a \"new\" project (fork from your brainspace) which creates\n                a \"chat\". But think about each chat item with respect to\n                <i><b>time</b></i>. Some chat items you want the latest one,\n                like a \"file\" in a repo at HEAD. But each \"file\" is like its own\n                repo. Some chat items you want to spawn an \"issue\" which is\n                itself a metadata chat. Some \"issues\" you may want a tag, which\n                you will make design decisions on. <b>This \"tag\" on this \"issue\"\n                    on this \"file\" is a \"chat\"</b>.\n\n            </p>\n            <p>\n\n                The \"Project Explorer\" on the left is a view on this **chat**.\n                The \"breadcrumb\" control in the header is a view on this chat.\n                The \"log\" is a view on it. The contents of a single file is a\n                view on it. Rebase your brain to understand each and every piece\n                of each and every project is its own project, with its own\n                timeline, and you want to CRUD those pieces - **but natively in\n                time**.\n\n            </p>\n\n\n        </section>\n\n\n        <section>\n\n            <h2>Bass...</h2>\n\n            <aside>WORDS come first.</aside>\n\n            <p>\n\n                ackwards. That's how people do software right now. They write\n                code and THEN tack on things like commit messages, issue\n                tracking, discussions, code reviews, etc., having\n                <b>forgotten</b> that there were words in the first place. To\n                unify production, we must understand that WORDS come FIRST and\n                code, apps, libs, docker images, cloud architectures come\n                after-the-fact.\n\n            </p>\n\n        </section>\n\n        <section>\n\n            <h2>Projects are...</h2>\n\n            <aside>Projects are chats.</aside>\n\n            <p>\n\n                chats. This is the third time on this page that this is stated -\n                and for good reason. It's <i>vitally</i> important to grasp this\n                key fundamental. \"Vibe coding\" is words. Ibgib \"projects\" are\n                how we manage vibe coding in real-world situations, beyond silly\n                trivial demos.\n\n            </p>\n\n        </section>\n\n    </article>\n\n</div>\n", "/* #web1-page-about-projects {\n\n    aside {\n        background-color: orange !important;\n    }\n\n} */\n", "import thisHtml from './about-projects.html';\nimport commonCss from '../web1-common.css';\nimport thisCss from './about-projects.css';\nimport stylesCss from '../../../styles.css';\nimport rootCss from '../../../root.css';\n\n// import { extractErrorMsg } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { IbGibAddr } from \"@ibgib/ts-gib/dist/types.mjs\";\n\nimport { GLOBAL_LOG_A_LOT } from \"../../../constants.mjs\";\nimport { Web1ComponentInstanceBase, Web1ComponentMetaBase } from \"../web1-component-base-one-file.mjs\";\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\n\n\nconst WEB1_COMPONENT_NAME: string = 'web1-about-projects-component';\nconst WEB1_HTML_PATH: string = '/components/web1/about-projects/about-projects.html';\n/**\n * script paths don't really work atow. I mean they are \"loaded\", but there is\n * no way that I can tell to get access to the shadow root of the web component.\n * any scripting I need done that requires this reference I am putting in these\n * component instances' code.\n */\nconst WEB1_SCRIPT_PATHS: string[] = [\n    // '/components/web1/web1-common.mjs',\n    // '/components/web1/about-projects/about-projects.mjs',\n];\nconst WEB1_CSS_PATHS: string[] = [\n    '/styles.css',\n    '/components/web1/web1-common.css',\n    '/components/web1/about-projects/about-projects.css',\n];\n\nexport const ComponentInfoWeb1_AboutProjects = {\n    componentName: WEB1_COMPONENT_NAME,\n    htmlPath: WEB1_HTML_PATH,\n    scriptPaths: WEB1_SCRIPT_PATHS,\n    cssPaths: WEB1_CSS_PATHS,\n}\n\n/**\n * This is the root component for any web1 component. this will take in the\n * given path, see if it's web 1.0 path, and then delegate to the appropriate\n * web1 sub component (home, funding, etc.);\n */\nexport class Web1ComponentMeta_AboutProjects\n    extends Web1ComponentMetaBase {\n    protected override lc: string = `[${Web1ComponentMeta_AboutProjects.name}]`;\n\n    protected getComponentName(): string { return WEB1_COMPONENT_NAME; }\n    protected getHtml(): string { return thisHtml; }\n    protected getCss(): string[] | undefined {\n        return [\n            rootCss,\n            stylesCss,\n            commonCss,\n            thisCss,\n        ];\n    }\n\n    componentName: string = this.getComponentName();\n\n    routeRegExp?: RegExp = /apps\\/web1\\/gib\\/about-projects.html/;\n\n    fnHandleRoute = async (arg: {\n        path: string;\n        ibGibAddr?: IbGibAddr | undefined;\n    }) => {\n        if (logalot) { console.log(`Web1Component fnHandleRoute: path: ${arg.path}, ibGibAddr: ${arg.ibGibAddr}`); }\n        return true;\n    }\n\n    constructor() {\n        super();\n    }\n    protected registerCustomElements(): void {\n        customElements.define(this.componentName, Web1ComponentInstance_AboutProjects);\n    }\n\n}\n\nexport class Web1ComponentInstance_AboutProjects\n    extends Web1ComponentInstanceBase {\n    protected override lc: string = `[${Web1ComponentInstance_AboutProjects.name}]`;\n\n    /**\n     *\n     */\n    constructor() {\n        super();\n    }\n\n}\n", "import { IbGibDynamicComponentMeta } from \"@ibgib/web-gib/dist/ui/component/component-types.mjs\";\n\nimport { Web1ComponentMeta_About } from \"./about/web1-about-component-one-file.mjs\";\nimport { Web1ComponentMeta_Blog } from \"./blog/web1-blog-component-one-file.mjs\";\nimport { Web1ComponentMeta_Contact } from \"./contact/web1-contact-component-one-file.mjs\";\nimport { Web1ComponentMeta_Faq } from \"./faq/web1-faq-component-one-file.mjs\";\nimport { Web1ComponentMeta_Funding } from \"./funding/web1-funding-component-one-file.mjs\";\nimport { Web1ComponentMeta_Home } from \"./home/web1-home-component-one-file.mjs\";\nimport { Web1ComponentMeta_Links } from \"./links/web1-links-component-one-file.mjs\";\nimport { Web1ComponentMeta_Challenges } from \"./challenges/web1-challenges-component-one-file.mjs\";\nimport { Web1ComponentMeta_AboutProjects } from \"./about-projects/web1-about-projects-component-one-file.mjs\";\n\nexport const componentsMeta_Web1: IbGibDynamicComponentMeta[] = [\n    new Web1ComponentMeta_Home(),\n    new Web1ComponentMeta_Funding(),\n    new Web1ComponentMeta_About(),\n    new Web1ComponentMeta_Links(),\n    new Web1ComponentMeta_Contact(),\n    new Web1ComponentMeta_Blog(),\n    new Web1ComponentMeta_Challenges(),\n    new Web1ComponentMeta_Faq(),\n    new Web1ComponentMeta_AboutProjects(),\n];\n\nexport const WEB1_PAGES: string[] = [\n    'home',\n    'funding',\n    'about',\n    'links',\n    'contact',\n    'blog',\n    'challenges',\n    'faq',\n    'about-projects',\n]\n\nexport const GEMINI_SCHEMA_WEB1_PAGE = {\n    type: 'string',\n    enum: WEB1_PAGES.concat(),\n    description: `kebab-cased string corresponding to a web 1.0 page on the website.`\n}\n", "import { delay, extractErrorMsg, pretty } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { ROOT_ADDR } from \"@ibgib/ts-gib/dist/V1/constants.mjs\";\nimport { IbGibAddr } from \"@ibgib/ts-gib/dist/types.mjs\";\nimport {\n    alertUser, document_getElementById,\n    highlightElement, isExecutingInBlankGibWebAppProper, promptForAPIKey,\n    promptForConfirm, updateAPIKeyInStorage,\n} from \"@ibgib/web-gib/dist/helpers.web.mjs\";\nimport { storageGet, storagePut } from \"@ibgib/web-gib/dist/storage/storage-helpers.web.mjs\";\nimport { getExistingUIInfo } from \"@ibgib/web-gib/dist/ui/ui-helpers.mjs\";\nimport { getComponentSvc, IbGibComponentService } from \"@ibgib/web-gib/dist/ui/component/ibgib-component-service.mjs\";\nimport { IbGibDynamicComponentMeta } from \"@ibgib/web-gib/dist/ui/component/component-types.mjs\";\nimport { getGlobalMetaspace_waitIfNeeded, getMaskedSecret } from \"@ibgib/web-gib/dist/helpers.mjs\";\nimport { IbGibAppShell } from \"@ibgib/web-gib/dist/app-bootstrap/types.mjs\";\n\nimport {\n    APP_CONFIG,\n    ARMY_STORE, BEE_KEY, BLANK_GIB_DB_NAME, CONFIG_OPTION_GEMINI_API_KEY_LOCATION_HELP, GLOBAL_LOG_A_LOT,\n    HTML_META_APP_ID_CONTENT,\n    HTML_META_APP_ID_NAME,\n    KEY_TUTORIAL_PANELS_EXPAND_ANIMATION_COUNT,\n    TUTORIAL_PANELS_EXPAND_ANIMATION_COUNT_ENOUGH_ALREADY,\n} from \"../../constants.mjs\";\nimport {\n    handleLocalSPAAnchorClick,\n    simpleIbGibRouterSingleton as router,\n} from \"../router/router-one-file.mjs\";\nimport { RouterAppName } from \"../../common/app-constants.mjs\";\nimport {\n    ID_APP_SHELL, ID_HEADER_PANEL, ID_PANEL_CONTAINER, ID_LEFT_PANEL,\n    ID_LEFT_PANEL_CONTENT, ID_LEFT_PANEL_FOOTER, ID_LEFT_PANEL_HEADER,\n    ID_LEFT_PANEL_MAXIMIZE_HANDLE, ID_PROJECT_EXPLORER_TAB_BUTTON,\n    ID_PROJECT_EXPLORER_TAB_CONTENT, ID_RIGHT_PANEL, ID_RIGHT_PANEL_CONTENT,\n    ID_RIGHT_PANEL_FOOTER, ID_RIGHT_PANEL_HEADER,\n    ID_RIGHT_PANEL_MAXIMIZE_HANDLE, ID_FOOTER_PANEL, ID_FOOTER_INPUT_CONTAINER,\n    ID_WEB10_TAB_BUTTON, ID_WEB10_TAB_CONTENT, ID_TAG_NAV,\n    ID_LEFT_PANEL_COLLAPSE_HANDLE, ID_LEFT_PANEL_EXPAND_HANDLE,\n    ID_RIGHT_PANEL_COLLAPSE_HANDLE, ID_RIGHT_PANEL_EXPAND_HANDLE,\n    ID_FOOTER_PANEL_COLLAPSE_HANDLE, ID_FOOTER_PANEL_EXPAND_HANDLE,\n    ID_FOOTER_PANEL_MAXIMIZE_HANDLE, ID_CENTER_PANEL_CONTENT, ID_WEB_1_NAV,\n    ID_TAB_BUTTON_CHRONOLOGYS, ID_HEADER_PANEL_CONTENT, ID_IBGIB_COM_TITLE_LINK,\n    ID_CHRONOLOGYS_CONTENT, ID_LEFT_PANEL_PROJECT_LIST,\n} from './shell-constants.mjs';\nimport { CanvasComponentMeta } from \"../../components/canvas/canvas-component-one-file.mjs\";\nimport { ProjectsComponentMeta } from \"../../components/projects/projects-component-one-file.mjs\";\nimport { ProjectComponentMeta } from \"../../components/projects/project/project-component-one-file.mjs\";\nimport { BREADCRUMB_COMPONENT_NAME, BreadcrumbComponentInstance, BreadcrumbComponentMeta } from \"../../components/common/breadcrumb/breadcrumb-component-one-file.mjs\";\nimport { INPUT_COMPONENT_NAME, InputComponentInstance, InputComponentMeta } from \"../../components/common/input/input-component-one-file.mjs\";\nimport { CHRONOLOGYS_COMPONENT_NAME, ChronologysComponentInstance, ChronologysComponentMeta } from \"../../components/chronologys/chronologys-component-one-file.mjs\";\nimport { ChronologyComponentMeta } from \"../../components/common/chronology/chronology-component-one-file.mjs\";\nimport { RawComponentMeta } from \"../../components/common/raw/raw-component-one-file.mjs\";\nimport { TextEditorComponentMeta } from \"../../components/common/text-editor/text-editor-component-one-file.mjs\";\n// import { getExistingUIInfo } from \"../ui-helpers.mjs\";\nimport { MinigameComponentMeta } from \"../../components/minigame/minigame-component-one-file.mjs\";\nimport { TypingComponentMeta } from \"../../components/minigame/typing/typing-component-one-file.mjs\";\nimport { PROJECTS_EXPLORER_COMPONENT_NAME, ProjectsExplorerComponentInstance, ProjectsExplorerComponentMeta } from \"../../components/projects/projects-explorer/projects-explorer-component-one-file.mjs\";\nimport { componentsMeta_Web1 } from \"../../components/web1/web1-constants.mjs\";\nimport { ExplorerItemComponentMeta } from \"../../components/common/explorer-item/explorer-item-component-one-file.mjs\";\nimport { getDefaultFnGetAPIKey, getIbGibGlobalThis_BlankGib } from \"../../helpers.web.mjs\";\nimport { CHAT_WITH_AGENT_NEED_API_KEY } from \"../../witness/app/blank-canvas/blank-canvas-constants.mjs\";\n\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\ntype PanelType = 'leftPanel' | 'rightPanel' | 'footerPanel' | 'headerPanel' | 'centerPanel';\n\ntype PanelStatus = 'collapsed' | 'expanded' | 'maximized' | 'default';\n\ninterface PanelState {\n    status: PanelStatus; // Use the new PanelState type here\n    width?: string | null;\n    height?: string | null;\n}\n/**\n * For use with maximizing center panel. We want to capture the panel states so\n * that if the center panel is restored (either \"expanded\" or \"collapsed\"), then\n * we restore the exact state.\n */\ninterface PanelStates {\n    headerPanel: PanelState;\n    leftPanel: PanelState;\n    rightPanel: PanelState;\n    footerPanel: PanelState;\n}\n\nexport class AppShellService implements IbGibAppShell {\n    /** log context */\n    private lc: string = `[${AppShellService.name}]`;\n\n    // #region elements\n\n    private appShell: HTMLElement | null = null;\n    private headerPanel: HTMLElement | null = null;\n    private headerPanelContent: HTMLElement | null = null;\n    private ibGibComTitleLink: HTMLElement | null = null;\n    /**\n     * this contains the left, center, and right panels.\n     */\n    private panelContainer: HTMLElement | null = null;\n    private leftPanel: HTMLElement | null = null;\n    private leftPanelHeader: HTMLElement | null = null;\n    private leftPanelContent: HTMLElement | null = null;\n    // private projectList: HTMLElement | null = null;\n    private leftPanelFooter: HTMLElement | null = null;\n    private leftPanelCollapseHandle: HTMLElement | null = null;\n    private leftPanelExpandHandle: HTMLElement | null = null;\n    private leftPanelMaximizeHandle: HTMLElement | null = null;\n    private leftPanelHamburgerBtn: HTMLButtonElement | null = null;\n    private leftPanelCloseBtn: HTMLButtonElement | null = null;\n\n    private rightPanel: HTMLElement | null = null;\n    private rightPanelHeader: HTMLElement | null = null;\n    private rightPanelContent: HTMLElement | null = null;\n    private chronologysContent: HTMLElement | null = null;\n    private rightPanelFooter: HTMLElement | null = null;\n    private rightPanelCollapseHandle: HTMLElement | null = null;\n    private rightPanelExpandHandle: HTMLElement | null = null;\n    private rightPanelMaximizeHandle: HTMLElement | null = null;\n    private footerPanel: HTMLElement | null = null;\n    private footerInputContainer: HTMLElement | null = null;\n    private footerPanelCollapseHandle: HTMLElement | null = null;\n    private footerPanelExpandHandle: HTMLElement | null = null;\n    private footerPanelMaximizeHandle: HTMLElement | null = null;\n    private centerPanelContent: HTMLElement | null = null;\n\n    private leftHandles: HTMLElement[] = [];\n    private leftPanels: HTMLElement[] = [];\n    private leftAll: HTMLElement[] = [];\n    private rightHandles: HTMLElement[] = [];\n    private rightPanels: HTMLElement[] = [];\n    private rightAll: HTMLElement[] = [];\n    private footerHandles: HTMLElement[] = [];\n    private footerPanels: HTMLElement[] = [];\n    private footerAll: HTMLElement[] = [];\n\n    // #endregion elements\n\n    /**\n     * When true, the app is in a mobile-first view (i.e., small screen).\n     */\n    private isMobileView: boolean = false;\n    private mobileMediaQuery: MediaQueryList | null = null;\n\n    /**\n     * if scroll down, then this number will be negative. if scroll up this will be\n     * positive.\n     *\n     * ## driving intent\n     *\n     * hide the header as we scroll center panel content\n     */\n    private centerPanelScrollOffset = 0;\n    private lastCenterPanelScrollTop = 0;\n    private initialHeaderPanelHeight = 0;\n    private initialHeaderPanelHeightPctOfAppShell = 0;\n\n    /**\n     * ## driving use case\n     *\n     * for use when maximizing/expanding/collapsing center panel\n     */\n    private lastPanelStates: PanelStates | undefined = undefined;\n\n    /**\n     * flag to track center panel maximized state\n     */\n    private isCenterPanelMaximized = false;\n    /**\n     * publicly exposed so consumers can just manually change this as needed\n     * from anywhere (since this service is a singleton)\n     */\n    breadcrumbComponent: BreadcrumbComponentInstance | undefined;\n\n    inputComponent: InputComponentInstance | undefined;\n\n    componentSvc: IbGibComponentService | undefined;\n\n    initialized: Promise<void>;\n\n    constructor() {\n        this.initialized = this.initialize();\n    }\n\n    // #region private init methods\n\n    /**\n     * does the initializing of all of the elements based on getting elements\n     * from the current HTML document.\n     */\n    private initElements(): void {\n        const lc = `[${this.initElements.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 5a7c48a369f95589c5d2b1867549cf25)`); }\n\n            this.appShell = document_getElementById<HTMLElement>(ID_APP_SHELL);\n            this.headerPanel = document_getElementById<HTMLElement>(ID_HEADER_PANEL);\n            this.headerPanelContent = document_getElementById<HTMLElement>(ID_HEADER_PANEL_CONTENT);\n            this.ibGibComTitleLink = document_getElementById<HTMLElement>(ID_IBGIB_COM_TITLE_LINK);\n            this.panelContainer = document_getElementById<HTMLElement>(ID_PANEL_CONTAINER);\n            this.leftPanel = document_getElementById<HTMLElement>(ID_LEFT_PANEL);\n            this.leftPanelHeader = document_getElementById<HTMLElement>(ID_LEFT_PANEL_HEADER);\n            this.leftPanelContent = document_getElementById<HTMLElement>(ID_LEFT_PANEL_CONTENT);\n            // this.projectList = document_getElementById<HTMLElement>(ID_LEFT_PANEL_PROJECT_LIST);\n            this.leftPanelFooter = document_getElementById<HTMLElement>(ID_LEFT_PANEL_FOOTER);\n            this.leftPanelCollapseHandle = document_getElementById<HTMLElement>(ID_LEFT_PANEL_COLLAPSE_HANDLE);\n            this.leftPanelExpandHandle = document_getElementById<HTMLElement>(ID_LEFT_PANEL_EXPAND_HANDLE);\n            this.leftPanelMaximizeHandle = document_getElementById<HTMLElement>(ID_LEFT_PANEL_MAXIMIZE_HANDLE);\n            this.leftPanelHamburgerBtn = document_getElementById<HTMLButtonElement>('left-panel-hamburger-btn');\n            this.leftPanelCloseBtn = document_getElementById<HTMLButtonElement>('left-panel-close-btn');\n\n\n            this.rightPanel = document_getElementById<HTMLElement>(ID_RIGHT_PANEL);\n            this.rightPanelContent = document_getElementById<HTMLElement>(ID_RIGHT_PANEL_CONTENT);\n            this.chronologysContent = document_getElementById<HTMLElement>(ID_CHRONOLOGYS_CONTENT);\n            this.rightPanelHeader = document_getElementById<HTMLElement>(ID_RIGHT_PANEL_HEADER);\n            this.rightPanelFooter = document_getElementById<HTMLElement>(ID_RIGHT_PANEL_FOOTER);\n            this.rightPanelCollapseHandle = document_getElementById<HTMLElement>(ID_RIGHT_PANEL_COLLAPSE_HANDLE);\n            this.rightPanelExpandHandle = document_getElementById<HTMLElement>(ID_RIGHT_PANEL_EXPAND_HANDLE);\n            this.rightPanelMaximizeHandle = document_getElementById<HTMLElement>(ID_RIGHT_PANEL_MAXIMIZE_HANDLE);\n\n            this.footerPanel = document_getElementById<HTMLElement>(ID_FOOTER_PANEL);\n            this.footerInputContainer = document_getElementById<HTMLElement>(ID_FOOTER_INPUT_CONTAINER);\n            this.footerPanelCollapseHandle = document_getElementById<HTMLElement>(ID_FOOTER_PANEL_COLLAPSE_HANDLE);\n            this.footerPanelExpandHandle = document_getElementById<HTMLElement>(ID_FOOTER_PANEL_EXPAND_HANDLE);\n            this.footerPanelMaximizeHandle = document_getElementById<HTMLElement>(ID_FOOTER_PANEL_MAXIMIZE_HANDLE);\n\n            this.centerPanelContent = document_getElementById<HTMLElement>(ID_CENTER_PANEL_CONTENT) as HTMLElement;\n\n            // if (!this.appShell) { throw new Error(`(UNEXPECTED) app shell falsy? (E: 51c5045e4b84c4f92647d61430370c25)`); }\n            // if (!this.headerPanel) { throw new Error(`(UNEXPECTED) Header panel not found? (E: d00a3c546396bac9edb9b7cb38be1a25)`); }\n            // if (!this.ibGibComTitleLink) { throw new Error(`(UNEXPECTED) ibgib.com title link not found? (E: 3a28eb148a9db4752ef7b06da4dfbf25)`); }\n            // if (!this.headerPanelContent) { throw new Error(`(UNEXPECTED) Header panel content not found? (E: 5e4e7aaaa6cd68cdf994da75f0192a25)`); }\n\n            // if (!this.panelContainer) { throw new Error(`(UNEXPECTED) Panel container not found? (E: 6efcd4bbe32653a40cd7af2ed7a84825)`); }\n            // if (!this.leftPanel) { throw new Error(`(UNEXPECTED) Left panel not found? (E: 5507ecca9fb6d3a90dcff6f577d78225)`); }\n            // if (!this.rightPanel) { throw new Error(`(UNEXPECTED) Right panel not found? (E: d9373f83bd7f021ab2c478467c576f25)`) };\n            // if (!this.leftPanelCollapseHandle) { throw new Error(`(UNEXPECTED) Left panel collapse handle not found? (E: 53f3c27a8443c13cdf08c612a744ea25)`); }\n            // if (!this.rightPanelCollapseHandle) { throw new Error(`(UNEXPECTED) Right panel collapse handle not found? (E: 60c56dc2e54ea0d34abcda7ac6b98325)`); }\n            // if (!this.leftPanelExpandHandle) { throw new Error(`(UNEXPECTED) Left panel expand handle not found? (E: 1da50cae5fee165954c2830a8f538225)`); }\n            // if (!this.rightPanelExpandHandle) { throw new Error(`(UNEXPECTED) Right panel expand handle not found? (E: b578747f8da1ed7c8c663309ed3c9625)`); }\n            // if (!this.leftPanelMaximizeHandle) { throw new Error(`(UNEXPECTED) Left panel maximize handle not found? (E: 6969dc4cd84df10b3bc73f75e6a1a225)`); }\n            // if (!this.rightPanelMaximizeHandle) { throw new Error(`(UNEXPECTED) Right panel maximize handle not found? (E: aea0bd86f7c4e9c41b326d83dbdddf25)`); }\n            // if (!this.leftPanelFooter) { throw new Error(`(UNEXPECTED) Left panel footer not found? (E: 62d11cbe41943b1ef736a002fdca1c25)`); }\n            // if (!this.leftPanelContent) { throw new Error(`(UNEXPECTED) left panel content falsy? (E: f59fbaabff0a14f88b5fad9803bb1125)`); }\n            // if (!this.projectList) { throw new Error(`(UNEXPECTED) left panel project list falsy? (E: 5e79d62788a6c2625fa2d32c17e88325)`); }\n            // if (!this.leftPanelHeader) { throw new Error(`(UNEXPECTED) left panel header falsy? (E: 96e2cf5bbc92de30fc4af8baf4c3c925)`); }\n            // if (!this.rightPanelFooter) { throw new Error(`(UNEXPECTED) Right panel footer not found? (E: 5e15a334ba68394e41ce5fae1c35dd25)`); }\n            // if (!this.rightPanelContent) { throw new Error(`(UNEXPECTED) right panel content falsy? (E: e97e4bca7edbfb4a965487fb30f47225)`); }\n            // if (!this.rightPanelHeader) { throw new Error(`(UNEXPECTED) right panel header falsy? (E: df42a4074a6f005bcf6f3c827cdf3325)`); }\n\n            // footer panel\n            // if (!this.footerPanel) { throw new Error(`(UNEXPECTED) Footer panel not found? (E: c5e4ce4d48f59ffe0b724df1aa664c25)`); }\n            // if (!this.footerInputContainer) { throw new Error(`(UNEXPECTED) Primary agent input (footer-input-container) not found? (E: b8119a25544681d2695d0e0360fbd425)`); }\n            // if (!this.footerPanelCollapseHandle) { throw new Error(`(UNEXPECTED) Footer panel collapse handle not found? (E: f06e9874c54c2a029ea7b59307348725)`); }\n            // if (!this.footerPanelExpandHandle) { throw new Error(`(UNEXPECTED) footerPanelExpandHandle not found? (E: b9429cf155d87f4f2277df2a20c2af25)`); }\n            // if (!this.footerPanelMaximizeHandle) { throw new Error(`(UNEXPECTED) footerPanelMaximizeHandle not found? (E: 2eab4faf2592f9482241f37533765725)`); }\n\n            // if (!this.centerPanelContent) { throw new Error(`(UNEXPECTED) Center panel content not found? (E: a1367b39ec61ca44b879ec389e9f6f25)`); }\n\n            this.leftHandles = [\n                this.leftPanelCollapseHandle, this.leftPanelExpandHandle,\n                this.leftPanelMaximizeHandle\n            ];\n            this.leftPanels = [\n                this.leftPanel, this.leftPanelFooter, this.leftPanelContent,\n                this.leftPanelHeader\n            ];\n            this.leftAll = [...this.leftPanels, ...this.leftHandles];\n            this.rightHandles = [\n                this.rightPanelCollapseHandle, this.rightPanelExpandHandle,\n                this.rightPanelMaximizeHandle\n            ];\n            this.rightPanels = [\n                this.rightPanel, this.rightPanelFooter, this.rightPanelContent,\n                this.rightPanelHeader\n            ];\n            this.rightAll = [...this.rightPanels, ...this.rightHandles];\n            this.footerPanels = [this.footerPanel, this.footerInputContainer];\n            this.footerHandles = [\n                this.footerPanelCollapseHandle, this.footerPanelExpandHandle,\n                this.footerPanelMaximizeHandle\n            ];\n            this.footerAll = [...this.footerPanels, ...this.footerHandles];\n\n            this.initPanelEventHandlers();\n            this.initPanelState();\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    private initHideHeaderOnScroll(): void {\n        const lc = `[${this.initHideHeaderOnScroll.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: f57dd8b3a8ff88958b35f07c3a341e25)`); }\n            if (!this.appShell) { throw new Error(`(UNEXPECTED) appShell not found? (E: fa55d5cac07ede4bfd7f3bace7026d25)`); }\n            if (!this.headerPanel) { throw new Error(`(UNEXPECTED) Header panel not found? (E: 4ce8f134611b8781a5a82a32e20ccf25)`); }\n            if (!this.centerPanelContent) { throw new Error(`(UNEXPECTED) centerPanelContent falsy? (E: 86daea2e4c676990a3287cb79d00a825)`); }\n\n            const updateCenterPanelScrollHidesHeader = (headerPanelHeight: number) => {\n                if (!this.centerPanelContent) { throw new Error(`(UNEXPECTED) centerPanelContent falsy? (E: d593fee7525b3c9308ba0df32c9d0625)`); }\n                if (!this.headerPanel) { throw new Error(`(UNEXPECTED) Header panel not found? this was originally truthy but in this scroll handler, it's falsy? (E: e22be78e20522e61ea245c7ec87b7325)`); }\n\n                const oldScroll = this.lastCenterPanelScrollTop;\n                const newScroll = this.centerPanelContent.scrollTop;\n                /**\n                 * scrolling down => positive delta\n                 * scrolling up => negative delta\n                 *\n                 * we want to hide the header as we scroll down, so we take the height\n                 * of the header panel and subtract the delta up until the height is 1.\n                 *\n                 * when we scroll back up, we want to slowly reshow the header.\n                 */\n                this.centerPanelScrollOffset += newScroll - oldScroll;\n\n                if (this.centerPanelScrollOffset > headerPanelHeight) {\n                    this.centerPanelScrollOffset = headerPanelHeight;\n                } else if (this.centerPanelScrollOffset < 0) {\n                    this.centerPanelScrollOffset = 0;\n                }\n                if (this.centerPanelScrollOffset > 0) {\n                    // don't just transform but actually change the height.\n                    // otherwise, our overall layout has problems\n                    const scale = (headerPanelHeight - this.centerPanelScrollOffset) / headerPanelHeight;\n                    const scaledHeight = scale * headerPanelHeight;\n                    this.headerPanel.style.height = `${scaledHeight}px`;\n                    /** document.documentElement corresponds to :root css selector */\n                    document.documentElement.style.setProperty('--header-calculated-height-loss', (headerPanelHeight - scaledHeight) + \"px\");\n\n                } else {\n                    // restore the original height\n                    this.headerPanel.style.height = `${headerPanelHeight}px`;\n                    /** document.documentElement corresponds to :root css selector */\n                    document.documentElement.style.setProperty('--header-calculated-height-loss', \"0px\");\n                }\n\n                // set for next time\n                this.lastCenterPanelScrollTop = this.centerPanelContent.scrollTop;\n            }\n\n            this.initialHeaderPanelHeight = this.headerPanel.clientHeight;\n            this.initialHeaderPanelHeightPctOfAppShell = this.initialHeaderPanelHeight / this.appShell.clientHeight;\n            let appShellResizeObserver = new ResizeObserver((_entries) => {\n                if (!this.headerPanel) { throw new Error(`(UNEXPECTED) headerPanel falsy in resize handler? (E: 69327376be54c87da86361a7c3156925)`); }\n                if (!this.appShell) { throw new Error(`(UNEXPECTED) appShell falsy? (E: 8141efedd3f1c9aaa8b94316b0423125)`); }\n                this.lastCenterPanelScrollTop = 0;\n                this.centerPanelScrollOffset = 0;\n                this.initialHeaderPanelHeight = this.appShell?.clientHeight * this.initialHeaderPanelHeightPctOfAppShell;\n                // updateCenterPanelScrollHidesHeader(this.initialHeaderPanelHeight);\n                this.headerPanel.style.height = `${this.initialHeaderPanelHeight}px`;\n                /** document.documentElement corresponds to :root css selector */\n                document.documentElement.style.setProperty('--header-calculated-height-loss', \"0px\");\n\n            });\n            appShellResizeObserver.observe(this.appShell);\n\n            this.centerPanelContent.addEventListener('scroll', (ev: Event) => {\n                updateCenterPanelScrollHidesHeader(this.initialHeaderPanelHeight);\n            });\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private initPanelEventHandlers() {\n        const lc = `[${this.initPanelEventHandlers.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: b02f038bc4fdc8a39ecc0eba2687c325)`); }\n\n            if (!this.leftPanelCollapseHandle || !this.leftPanelExpandHandle || !this.leftPanelMaximizeHandle ||\n                !this.rightPanelCollapseHandle || !this.rightPanelExpandHandle || !this.rightPanelMaximizeHandle ||\n                !this.footerPanelCollapseHandle || !this.footerPanelExpandHandle || !this.footerPanelMaximizeHandle) {\n                throw new Error(`(UNEXPECTED) Panel handles are not initialized. (E: 7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d)`);\n            }\n            if (!this.leftPanel || !this.leftPanelContent || !this.leftPanelFooter || !this.leftPanelHeader ||\n                !this.rightPanel || !this.rightPanelContent || !this.rightPanelFooter || !this.rightPanelHeader ||\n                !this.footerPanel || !this.footerInputContainer || !this.panelContainer) {\n                throw new Error(`(UNEXPECTED) Panels are not initialized. (E: 8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e)`);\n            }\n\n            // wire up click handlers for all buttons (handles)\n            this.leftPanelCollapseHandle.addEventListener('click', () => {\n                this.collapse({ panelNames: ['leftPanel'] });\n            });\n            this.leftPanelExpandHandle.addEventListener('click', () => {\n                this.expand({ panelNames: ['leftPanel'] });\n            });\n            this.leftPanelMaximizeHandle.addEventListener('click', () => {\n                this.maximize({ panelNames: ['leftPanel'] });\n\n            });\n\n            this.rightPanelCollapseHandle.addEventListener('click', () => {\n                this.collapse({ panelNames: ['rightPanel'] });\n            });\n            this.rightPanelExpandHandle.addEventListener('click', () => {\n                this.expand({ panelNames: ['rightPanel'] });\n            });\n            this.rightPanelMaximizeHandle.addEventListener('click', () => {\n                this.maximize({ panelNames: ['rightPanel'] });\n            });\n\n            // footer panel\n            this.footerPanelCollapseHandle.addEventListener('click', () => {\n                this.collapse({ panelNames: ['footerPanel'] });\n            });\n            this.footerPanelExpandHandle.addEventListener('click', () => {\n                this.expand({ panelNames: ['footerPanel'] });\n            });\n            this.footerPanelMaximizeHandle.addEventListener('click', () => {\n                this.maximize({ panelNames: ['footerPanel'] });\n            });\n\n            // hamburger and close button setup\n            if (!this.leftPanelHamburgerBtn) { throw new Error(`(UNEXPECTED) leftPanelHamburgerBtn not found? (E: 1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d)`); }\n            this.leftPanelHamburgerBtn.addEventListener('click', (event) => {\n                event.stopPropagation(); // prevent the global click listener from immediately closing the menu\n                if (this.isMobileView) {\n                    if (!this.leftPanel) { throw new Error(`(UNEXPECTED) leftPanel not found? (E: 2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e)`); }\n                    this.leftPanel.classList.toggle('mobile-visible');\n                    if (this.leftPanel.classList.contains('mobile-visible')) {\n                        this.maximize({ panelNames: ['leftPanel'] });\n                    }\n                }\n            });\n\n            if (!this.leftPanelCloseBtn) { throw new Error(`(UNEXPECTED) leftPanelCloseBtn not found? (E: 3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f)`); }\n            this.leftPanelCloseBtn.addEventListener('click', () => {\n                if (this.isMobileView) {\n                    if (!this.leftPanel) { throw new Error(`(UNEXPECTED) leftPanel not found? (E: 4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a)`); }\n                    this.leftPanel.classList.remove('mobile-visible');\n                }\n            });\n\n            // Add a global click listener to close the mobile menu when clicking outside of it\n            document.addEventListener('click', (event) => {\n                if (this.isMobileView) {\n                    if (!this.leftPanel) { throw new Error(`(UNEXPECTED) leftPanel not found? (E: 5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b)`); }\n                    const isClickInside = this.leftPanel.contains(event.target as Node);\n                    if (this.leftPanel.classList.contains('mobile-visible') && !isClickInside) {\n                        this.leftPanel.classList.remove('mobile-visible');\n                    }\n                }\n            });\n\n\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * helper to update a variable to hack the left/right panel height when\n     * they are collapsed. Basically when we collapse either one, we update css\n     * variables which drive the width.\n     *\n     * The problem stems from the fact that we are rotating the panel headers\n     * 90/270 degrees, and I can't figure out how to get the panel itself to\n     * conform to this rotated height.\n     */\n    private updateCollapsedPanelWidthOverride() {\n        const lc = `${this.lc}[${this.updateCollapsedPanelWidthOverride.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: c495c20291c39eea19020a1c28627125)`); }\n\n\n\n            // kluge ah well\n            // [100, 200, 300, 400, 500].forEach(ms => {\n            [100, 500].forEach(ms => {\n                setTimeout(() => {\n                    if (!this.leftPanelHeader) { throw new Error(`(UNEXPECTED) this.leftPanelHeader falsy? (E: 5a23c55f2938ac218fb5fd73ad828e25)`); }\n                    const leftMagicNumberTweak = 2;\n                    document.documentElement.style.setProperty('--left-panel-header-calculated-height', `${this.leftPanelHeader.clientHeight + leftMagicNumberTweak}px`);\n\n                    if (!this.rightPanelHeader) { throw new Error(`(UNEXPECTED) this.rightPanelHeader falsy? (E: b7eb697acb3a72f64afa587a6b5f2b25)`); }\n                    const rightMagicNumberTweak = 3;\n                    document.documentElement.style.setProperty('--right-panel-header-calculated-height', `${this.rightPanelHeader!.clientHeight + rightMagicNumberTweak}px`);\n                }, ms)\n            });\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private initPanelState() {\n        const lc = `[${this.initPanelState.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: b4e1fa3e7be418452ade0a43ea0fb625)`); }\n\n            if (!this.leftPanel || !this.leftPanelContent || !this.leftPanelFooter || !this.leftPanelHeader ||\n                !this.rightPanel || !this.rightPanelContent || !this.rightPanelFooter || !this.rightPanelHeader ||\n                !this.footerPanel || !this.footerInputContainer) {\n                throw new Error(`(UNEXPECTED) Panels are not initialized. (E: 9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4)`);\n            }\n            if (!this.leftPanelExpandHandle || !this.rightPanelExpandHandle || !this.footerPanelExpandHandle) {\n                throw new Error(`(UNEXPECTED) Expand handles are not initialized. (E: a0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f)`);\n            }\n\n            const leftPanels = [this.leftPanel, this.leftPanelFooter, this.leftPanelContent, this.leftPanelHeader];\n            const rightPanels = [this.rightPanel, this.rightPanelFooter, this.rightPanelHeader];\n            const footerPanels = [this.footerPanel, this.footerInputContainer];\n\n            const fnClearAllClasses = ({ footerAlso }: { footerAlso: boolean }) => {\n                this.clearClasses([this.panelContainer, this.leftPanel, this.rightPanel]);\n                if (footerAlso) { this.clearClasses([this.footerPanel]); }\n            };\n\n            fnClearAllClasses({ footerAlso: true });\n            this.expandElements([\n                ...leftPanels,\n                ...rightPanels,\n                ...footerPanels,\n            ]);\n            this.collapseElements([\n                this.leftPanelExpandHandle,\n                this.rightPanelExpandHandle,\n                this.footerPanelExpandHandle,\n            ]);\n\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    private initMobileView(): void {\n        const lc = `${this.lc}[${this.initMobileView.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 9c2a7e7d6b3a4e9b8a8e3d6b3a4e9b8a)`); }\n\n            // Using a media query to detect screen size for mobile view\n            this.mobileMediaQuery = window.matchMedia('(max-width: 768px)');\n\n            // Set the initial state by calling the handler\n            this.handleScreenSizeChange(this.mobileMediaQuery);\n\n            // Add a listener for when the screen size crosses the 768px threshold\n            this.mobileMediaQuery.addEventListener('change', this.handleScreenSizeChange.bind(this));\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    private initTabButtonsLeftPanel() {\n        const lc = `[${this.initTabButtonsLeftPanel.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 564a084b92a4e90b7560248afcfc2425)`); }\n\n            const { web10TabButton, projectExplorerTabButton } = this.getLeftPanelTabButtons();\n\n            web10TabButton.addEventListener('click', () => this.activateLeftPanelTab({ tabName: RouterAppName.web1 }));\n            projectExplorerTabButton.addEventListener('click', () => this.activateLeftPanelTab({ tabName: RouterAppName.projects }));\n            // tagExplorerTabButton.addEventListener('click', () => this.activateLeftPanelTab({ tabName: RouterAppName.tags }));\n\n            // default to web 1.0 nav tab on load\n            this.activateLeftPanelTab({ tabName: RouterAppName.web1 });\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    private initTabButtonsRightPanel() {\n        const lc = `[${this.initTabButtonsRightPanel.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: e2c3667f4aa97480138f9a469614fc25)`); }\n\n            const { chronologysTabButton } = this.getRightPanelTabButtons();\n\n            chronologysTabButton.addEventListener('click', () => this.activateRightPanelTab({ tabName: 'chronologys' }));\n\n            // default to web 1.0 nav tab on load\n            // this.activateRightPanelTab({ tabName: 'chronologys' });\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    private initNav() {\n        const lc = `[${this.initNav.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: f4efbf831b16e293af5b83c13487cc25)`); }\n\n            const headerPanel = document.getElementById(ID_HEADER_PANEL);\n            if (!headerPanel) { throw new Error(`(UNEXPECTED) #header-panel not found (E: 7f35a780801e3bfa056fb9f6d55e6825)`); }\n            headerPanel.addEventListener('click', async (event) => {\n                if ((event.target as HTMLElement).tagName === 'A') {\n                    await handleLocalSPAAnchorClick({ event });\n                }\n            });\n\n            const web10Nav = document.getElementById(ID_WEB_1_NAV);\n            if (!web10Nav) { throw new Error(`(UNEXPECTED) #web1-nav not found (E: 7843992b049b7a2a77e12b2b3b032a25)`); }\n            web10Nav.addEventListener('click', async (event) => {\n                if ((event.target as HTMLElement).tagName === 'A') {\n                    await handleLocalSPAAnchorClick({ event });\n                }\n            });\n\n            const tagNav = document.getElementById(ID_TAG_NAV);\n            if (!tagNav) { throw new Error(`(UNEXPECTED) #tag-nav not found (E: bc672beb0f2f266ced0d240c5445ac25)`); }\n            tagNav.addEventListener('click', async (event) => {\n                if ((event.target as HTMLElement).tagName === 'A') {\n                    await handleLocalSPAAnchorClick({ event });\n                }\n            });\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    /**\n     * When the browser popstate happens (back button is pressed), we want to load the URL.\n     */\n    private initPopstateListener(): void {\n        const lc = `[${this.initPopstateListener.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 1f987e79acef11b9c54eab811a2eb425)`); }\n\n            window.addEventListener('popstate', () => {\n                if (logalot) { console.log(`${lc} popstate event triggered. (I: 89b959b770a50e241f3e6afb4364ce25)`); }\n\n                const lcPopstate = `${lc}[popstate]`;\n\n                const isInWebAppProper = isExecutingInBlankGibWebAppProper({\n                    metaName_appId: HTML_META_APP_ID_NAME,\n                    metaContent_appId: HTML_META_APP_ID_CONTENT,\n                });\n\n                if (!isInWebAppProper) {\n                    if (logalot) { console.log(`${lcPopstate} executing in iframe so returning early (I: b84172ceedb5fea0c5d0c1cfbd911b25)`); }\n                    return; /* <<<< returns early */\n                }\n\n                router.loadCurrentURLPath();\n            });\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private async initHeader({ componentSvc }: { componentSvc: IbGibComponentService }): Promise<void> {\n        const lc = `${this.lc}[${this.initHeader.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 3717bfd6a9ae8a8c7a8b88f29b947b25)`); }\n            const breadcrumbComponent =\n                await componentSvc.getComponentInstance({\n                    path: BREADCRUMB_COMPONENT_NAME,\n                    ibGibAddr: ROOT_ADDR,\n                    useRegExpPrefilter: true,\n                }) as BreadcrumbComponentInstance;\n\n            if (!this.headerPanelContent) { throw new Error(`(UNEXPECTED) this.headerPanelContent falsy? (E: f96ed2a402b891d72d56c73ffcb17625)`); }\n            if (!breadcrumbComponent) { throw new Error(`(UNEXPECTED) breadcrumbComponent falsy? (E: fb26e6efe94f3e49de6e93910b479e25)`); }\n            await componentSvc.inject({\n                parentEl: this.headerPanelContent,\n                componentToInject: breadcrumbComponent,\n            });\n            this.breadcrumbComponent = breadcrumbComponent;\n\n            // configBtnEl\n            const configBtnEl = document_getElementById<HTMLButtonElement>('header-panel-config-btn');\n            // configPopoverEl - when user clicks config, this popover has the options\n            // of what exactly to config\n            const configPopoverEl = document_getElementById('config-popover');\n            const configPopoverOptions = configPopoverEl.querySelectorAll('.config-popover-option');\n            configBtnEl.addEventListener('click', async (event) => {\n                // debugger; // walkthru config btn click, is stlye.right right?\n                configPopoverEl.style.position = 'absolute';\n                configPopoverEl.style.top = `${configBtnEl.offsetTop + configBtnEl.clientHeight + 5}px`;\n                let widestWidth = 0;\n                for (let i = 0; i < configPopoverOptions.length; i++) {\n                    const optionEl = configPopoverOptions[i];\n                    // calculate once browser has actually rendered the options (width starts as 0)\n                    while (optionEl.clientWidth === 0) { await delay(8); }\n                    if (optionEl.clientWidth > widestWidth) { widestWidth = optionEl.clientWidth; }\n                    configPopoverEl.style.left = `${document.body.clientWidth - widestWidth - 10}px`;\n                }\n            });\n            // Event listeners for popover options\n            configPopoverOptions.forEach(option => {\n                option.addEventListener('click', async (event: Event) => {\n                    const target = event.target as HTMLElement;\n                    const optionType = target.getAttribute('data-option');\n                    if (optionType) { await this.handleConfigPopoverSelected(optionType); }\n                    configPopoverEl.hidePopover(); // idempotent\n                });\n            });\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private async handleConfigPopoverSelected(optionType: string): Promise<void> {\n        const lc = `${this.lc}[${this.handleConfigPopoverSelected.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: db1ef866696819b6110dbf0dc574a825)`); }\n            switch (optionType) {\n                case 'gemini-api-key':\n                    await this.handleConfigPopoverSelected_geminiApiKey();\n                    break;\n                default:\n                    debugger; // error unknown config type\n                    throw new Error(`(UNEXPECTED) unknown config optionType (${optionType})? (E: 19b9eb257e58e1fe384f58b8ab58d825)`);\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    private async handleConfigPopoverSelected_geminiApiKey(): Promise<void> {\n        const lc = `${this.lc}[${this.handleConfigPopoverSelected_geminiApiKey.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 586cd8d6c5f8b1bb08076b387bf34325)`); }\n            // 1. prompt user for gemini api key, populating the field\n            // with the existing one, if any. be sure to mention how\n            // this is stored locally and in plaintext\n            // 2. update stored API key...right now we just delete it and reload\n            // though, so there ya go.\n            const existingApiKey = await getDefaultFnGetAPIKey()() ?? '';\n            if (existingApiKey) {\n                // user wants to read/update existing API key\n                /**\n                 * atow (07/2025) google's ai studio shows this exact same mask\n                 * of the last 4 characters\n                 */\n                const existingApiKeyMasked = getMaskedSecret({ secret: existingApiKey, countToShow: 4 });\n                // const existingApiKeyMasked = `****${existingApiKey.substring(existingApiKey.length - 4)}`;\n                const clearAPIKey = await promptForConfirm({\n                    msg: `Your existing (masked) Gemini API key is ${existingApiKeyMasked}.\\n\\nWould you like to CLEAR/DELETE this now?\\n\\nNote: This will prevent you from any further interaction with any Gemini agents on this site, but your data won't be deleted.\\n\\nTo re-enable agents, you will have to enter an API key again with ${CONFIG_OPTION_GEMINI_API_KEY_LOCATION_HELP}.\\n\\n(apologies for the crappy workflow, but this would be a great time for funding or contribution!)`\n                });\n                if (clearAPIKey) {\n                    await updateAPIKeyInStorage({\n                        dbName: BLANK_GIB_DB_NAME,\n                        storeName: ARMY_STORE,\n                        key: BEE_KEY,\n                        apiKey: '',\n                        force: true\n                    }); // \"deletes\" the API key\n                } else {\n                    await alertUser({ title: 'cancelled...', msg: 'Clear API key cancelled' });\n                }\n            } else {\n                // user wants to enter API key anew\n                const apiKey = await promptForAPIKey({\n                    msg: CHAT_WITH_AGENT_NEED_API_KEY,\n                });\n                if (apiKey) {\n                    await updateAPIKeyInStorage({\n                        dbName: BLANK_GIB_DB_NAME,\n                        storeName: ARMY_STORE,\n                        key: BEE_KEY,\n                        apiKey,\n                        force: false,\n                    });\n                } else {\n                    console.log(`${lc} user cancelled (I: 4705481d1a7f629066737658ec455e25)`);\n                }\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private handleScreenSizeChange(event: MediaQueryList | MediaQueryListEvent): void {\n        const lc = `${this.lc}[${this.handleScreenSizeChange.name}]`;\n        this.isMobileView = event.matches;\n\n        if (!this.leftPanelHamburgerBtn || !this.leftPanelCloseBtn || !this.leftPanel) {\n            console.error(`${lc} hamburger button or left panel not initialized. (E: a9b8c7d6e5f4a3b2a1a9b8c7d6e5f4a3)`);\n            return;\n        }\n\n        if (this.isMobileView) {\n            // We are on a small screen (mobile view)\n            if (logalot) { console.log(`${lc} Entering mobile view. (I: 8b7c6d5e4f3a2b1a9b8c7d6e5f4a3b2a)`); }\n            this.leftPanelHamburgerBtn.classList.remove('collapsed');\n            this.leftPanelCloseBtn.classList.remove('collapsed');\n            // Ensure the mobile overlay is hidden by default when switching to mobile\n            this.leftPanel.classList.remove('mobile-visible');\n            // this.maximize({panelNames: ['leftPanel']});\n        } else {\n            // We are on a larger screen (desktop view)\n            if (logalot) { console.log(`${lc} Exiting mobile view. (I: 7a6b5c4d3e2f1a9b8c7d6e5f4a3b2a1a)`); }\n            this.leftPanelHamburgerBtn.classList.add('collapsed');\n            this.leftPanelCloseBtn.classList.add('collapsed');\n            // Make sure the mobile overlay is hidden when switching back to desktop\n            this.leftPanel.classList.remove('mobile-visible');\n        }\n    }\n\n    /**\n     * The left panel has web1 and projects atow (05/2025).\n     *\n     * I'm making this so this init the left panel's projects explorer\n     * component. atow (05/2025), this is just manually getting all projects\n     */\n    private async initLeftPanel({ componentSvc }: { componentSvc: IbGibComponentService }) {\n        const lc = `${this.lc}[${this.initLeftPanel.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: genuuid)`); }\n\n            // #region projects explorer\n            const projectsExplorerTabContent = document_getElementById(ID_PROJECT_EXPLORER_TAB_CONTENT);\n            const explorerComponent =\n                await componentSvc.getComponentInstance({\n                    path: PROJECTS_EXPLORER_COMPONENT_NAME,\n                    ibGibAddr: ROOT_ADDR,\n                    useRegExpPrefilter: true,\n                }) as ProjectsExplorerComponentInstance;\n\n            await componentSvc.inject({\n                componentToInject: explorerComponent,\n                parentEl: projectsExplorerTabContent,\n            });\n            // #endregion projects explorer\n\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * right now, there are only \"chats\" (chronologys). so this init\n     * automatically creates the chronologys component and injects it into the\n     * right panel content.\n     */\n    private async initRightPanel({ componentSvc }: { componentSvc: IbGibComponentService }) {\n        const lc = `${this.lc}[${this.initRightPanel.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: c0eabc24bd4902f53a539ae1d99c7425)`); }\n\n            if (!this.chronologysContent) { throw new Error(`(UNEXPECTED) this.chronologysContent falsy? (E: 2d93b3fe28d2cccec79b4419c1e09625)`); }\n            const chronologysComponent =\n                await componentSvc.getComponentInstance({\n                    path: CHRONOLOGYS_COMPONENT_NAME,\n                    ibGibAddr: ROOT_ADDR,\n                    useRegExpPrefilter: true,\n                }) as ChronologysComponentInstance;\n\n            if (!chronologysComponent) { throw new Error(`(UNEXPECTED) chronologysComponent falsy? (E: 950d479e6dc3e9b559e883328b8f6a25)`); }\n            await componentSvc.inject({\n                parentEl: this.chronologysContent,\n                componentToInject: chronologysComponent,\n            });\n            const globalIbGib = getIbGibGlobalThis_BlankGib();\n            globalIbGib.chronologysComponent = chronologysComponent;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private async initFooter({ componentSvc }: { componentSvc: IbGibComponentService }): Promise<void> {\n        const lc = `[${this.initFooter.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: c0eabc24bd4902f53a539ae1d99c7425)`); }\n\n            if (!this.footerInputContainer) { throw new Error(`(UNEXPECTED) this.footerInputContainer falsy? (E: bbbe3960c3876337c2676a0f26777825)`); }\n            const inputComponent =\n                await componentSvc.getComponentInstance({\n                    path: INPUT_COMPONENT_NAME,\n                    ibGibAddr: ROOT_ADDR,\n                    useRegExpPrefilter: true,\n                }) as InputComponentInstance;\n\n            if (!inputComponent) { throw new Error(`(UNEXPECTED) inputComponent falsy? (E: 0e539c1fc7ddecc737741c33d61a2625)`); }\n            await componentSvc.inject({\n                parentEl: this.footerInputContainer,\n                componentToInject: inputComponent,\n            });\n            this.inputComponent = inputComponent;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    // #endregion private init methods\n\n    // #region private element methods\n\n    private clearAllClasses({ footerAlso }: { footerAlso: boolean; }): void {\n        this.clearClasses([this.panelContainer, ...this.leftAll, ...this.rightAll,]);\n        if (footerAlso) { this.clearClasses([...this.footerAll]); }\n    };\n    private clearResize = (els: (HTMLElement | null)[]) => {\n        els.forEach(el => {\n            if (!el) { throw new Error(`(UNEXPECTED) el is falsy? (E: 67b2eeb874a2090f8763edb62d9a7325)`); }\n            // el.style.setProperty('resize', 'none');\n            el.style.removeProperty('width');\n            el.style.removeProperty('height');\n        })\n    }\n    private clearClasses = (els: (HTMLElement | null)[]) => {\n        els.forEach(el => {\n            if (!el) { throw new Error(`(UNEXPECTED) el is falsy? (E: 344bb8c7602e551327ab9a0ff8fe0325)`); }\n            el.classList.remove('collapsed');\n            el.classList.remove('expanded');\n            el.classList.remove('maximized');\n        })\n    };\n    private collapseElements = (els: (HTMLElement | null)[]) => {\n        this.clearClasses(els);\n        els.forEach(el => {\n            if (!el) { throw new Error(`(UNEXPECTED) el falsy? (E: a5d739f683aa91d8eeb1ab8955f00c25)`); }\n            el.classList.add('collapsed');\n        });\n    };\n    private expandElements = (els: (HTMLElement | null)[]) => {\n        this.clearClasses(els);\n        els.forEach(el => {\n            if (!el) { throw new Error(`(UNEXPECTED) el falsy? (E: 57b021c90bb8d1738307146b79c39125)`); }\n            el.classList.add('expanded');\n        })\n    };\n    private maximizeElements = (els: (HTMLElement | null)[]) => {\n        this.clearClasses(els);\n        els.forEach(el => {\n            if (!el) { throw new Error(`(UNEXPECTED) el falsy? (E: aa2dab40b7cbce96448756ededf82725)`); }\n            el.classList.add('maximized');\n        })\n    };\n\n    // #endregion private element methods\n\n    // #region private state methods\n\n    private getPanelVisualState(el: HTMLElement): PanelStatus {\n        if (el.classList.contains('maximized')) return 'maximized';\n        if (el.classList.contains('expanded')) return 'expanded';\n        if (el.classList.contains('collapsed')) return 'collapsed';\n        return 'default'; // or perhaps 'expanded' as default? depends on initial state.\n    }\n    private restorePanelStates(): void {\n        const lc = `${this.lc}[${this.restorePanelStates.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 8debefde7d44e8b371f7ca1f1e16cd25)`); }\n\n            const states = this.lastPanelStates;\n            if (!states) {\n                if (logalot) { console.log(`${lc} lastPanelStates falsy. returning early. (I: acc5b2640bc40b9271c9adb597ced425)`); }\n                return; /* <<<< returns early */\n            }\n\n            if (logalot) { console.log(`[${this.restorePanelStates.name}] restoring state:`, states); }\n            if (!this.leftPanel) { throw new Error(`(UNEXPECTED) leftPanel falsy? (E: 80997e37f2fcb1787caa51a3ead1b225)`); }\n            if (!this.rightPanel) { throw new Error(`(UNEXPECTED) rightPanel falsy? (E: c2e889af5d9f3a9138a1f3b280b52c25)`); }\n            if (!this.footerPanel) { throw new Error(`(UNEXPECTED) footerPanel falsy? (E: 84e21a9393dab76d530cdc0fe7ea2a25)`); }\n\n            this.setPanelVisualState('leftPanel', states.leftPanel.status);\n            if (states.leftPanel.width) { this.leftPanel.style.width = states.leftPanel.width; }\n            if (states.leftPanel.height) { this.leftPanel.style.height = states.leftPanel.height; }\n            this.setPanelVisualState('rightPanel', states.rightPanel.status);\n            if (states.rightPanel.width) { this.rightPanel.style.width = states.rightPanel.width; }\n            if (states.rightPanel.height) { this.rightPanel.style.height = states.rightPanel.height; }\n            this.setPanelVisualState('footerPanel', states.footerPanel.status);\n            if (states.footerPanel.width) { this.footerPanel.style.width = states.footerPanel.width; }\n            if (states.footerPanel.height) { this.footerPanel.style.height = states.footerPanel.height; }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    /**\n     * @internal helper that collapses/expands/maximizes UI based on passed in {@link status}\n     * @param panelName - which panel we're working on\n     * @param status - determines what action to perform on the panel\n     */\n    private setPanelVisualState(panelName: PanelType, status: PanelStatus): void {\n        const lc = `${this.lc}[${this.setPanelVisualState.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: c60c1af7149d32ff06414e483334e125)`); }\n\n            switch (status) {\n                case 'collapsed': this.collapse({ panelNames: [panelName] }); break;\n                case 'expanded': this.expand({ panelNames: [panelName] }); break;\n                case 'maximized': this.maximize({ panelNames: [panelName] }); break;\n                case 'default': this.expand({ panelNames: [panelName] }); break;\n                case undefined:\n                    this.expand({ panelNames: [panelName] }); break;\n                default: throw new Error(`(UNEXPECTED) hit default in switch? (E: a8045655f5f3a61c360907457c2d2a25)`);\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    // #endregion private state methods\n\n    // #region private other methods\n\n    private getLeftPanelTabButtons(): {\n        web10TabButton: HTMLElement;\n        projectExplorerTabButton: HTMLElement;\n        // tagExplorerTabButton: HTMLElement;\n    } {\n        const lc = `[${this.getLeftPanelTabButtons.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 8675bae85fab6164daa088d8e5bd9925)`); }\n\n            const web10TabButton = document_getElementById(ID_WEB10_TAB_BUTTON);\n            const projectExplorerTabButton = document_getElementById(ID_PROJECT_EXPLORER_TAB_BUTTON);\n            // const tagExplorerTabButton = document_getElementById(ID_TAG_EXPLORER_TAB_BUTTON);\n\n\n            // return { web10TabButton, projectExplorerTabButton, tagExplorerTabButton };\n            return { web10TabButton, projectExplorerTabButton, };\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n    private getRightPanelTabButtons(): {\n        chronologysTabButton: HTMLElement;\n    } {\n        const lc = `[${this.getRightPanelTabButtons.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 8675bae85fab6164daa088d8e5bd9925)`); }\n\n            const chronologysTabButton = document.getElementById(ID_TAB_BUTTON_CHRONOLOGYS)\n\n            if (!chronologysTabButton) { throw new Error(`(UNEXPECTED) chronologysTabButton not found? (E: fef8517cc1af60197219fc81c9721925)`); }\n\n            return { chronologysTabButton };\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private async registerComponents(): Promise<void> {\n        const lc = `[${this.registerComponents.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: c4635960bdd3fd41dc03b7bbfb236f25)`); }\n\n            const componentsMeta: IbGibDynamicComponentMeta[] = [\n                // add components here (we don't have any modules or anything like that at this time)\n                ...componentsMeta_Web1,\n                new CanvasComponentMeta(),\n                new ProjectsComponentMeta(),\n                new ProjectComponentMeta(),\n                new ChronologysComponentMeta(),\n                new ChronologyComponentMeta(),\n                new BreadcrumbComponentMeta(),\n                new InputComponentMeta(),\n                new RawComponentMeta(),\n                new TextEditorComponentMeta(),\n                new MinigameComponentMeta(),\n                new TypingComponentMeta(),\n                new ProjectsExplorerComponentMeta(),\n                new ExplorerItemComponentMeta(),\n            ];\n            const componentSvc = await getComponentSvc();\n            for (let componentMeta of componentsMeta) {\n                componentSvc.registerComponentMeta(componentMeta);\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    async sillyDrawEyeToElements(): Promise<void> {\n        const lc = `[${this.sillyDrawEyeToElements.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: b63771f8769a5a41016e1cbb6fac6725)`); }\n\n            const tutorial_panelsExpandAnimationCount = Number.parseInt(await storageGet({\n                dbName: BLANK_GIB_DB_NAME,\n                storeName: ARMY_STORE,\n                key: KEY_TUTORIAL_PANELS_EXPAND_ANIMATION_COUNT,\n            }) || \"0\");\n\n            // if we've already done the animation a couple times, we don't need to\n            // keep doing it. in the future, we should have a better tutorial\n            // mechanism.\n            if (tutorial_panelsExpandAnimationCount < TUTORIAL_PANELS_EXPAND_ANIMATION_COUNT_ENOUGH_ALREADY) {\n\n                await delay(1000);\n                this.maximize({ panelNames: ['centerPanel'] });\n                await delay(1000);\n                this.expand({ panelNames: ['centerPanel'] });\n\n                await delay(1000);\n                this.collapse({ panelNames: ['leftPanel'] });\n                await delay(600);\n                this.collapse({ panelNames: ['footerPanel'] });\n                await delay(600);\n                this.collapse({ panelNames: ['rightPanel'] });\n\n                await delay(1000);\n                this.expand({ panelNames: ['footerPanel', 'leftPanel', 'rightPanel'] });\n\n                storagePut({\n                    dbName: BLANK_GIB_DB_NAME,\n                    storeName: ARMY_STORE,\n                    key: KEY_TUTORIAL_PANELS_EXPAND_ANIMATION_COUNT,\n                    value: (tutorial_panelsExpandAnimationCount + 1).toString(),\n                }); // spin off/no await, don't care about multithreadedness here\n                await delay(200);\n\n                await highlightElement({\n                    el: this.ibGibComTitleLink!,\n                    magicHighlightTimingMs: 1000,\n                    scrollIntoView: false,\n                });\n            } else {\n                await delay(200);\n                this.maximize({ panelNames: ['centerPanel'] });\n                await delay(200);\n                this.expand({ panelNames: ['centerPanel'] });\n                await delay(200);\n                this.expand({ panelNames: ['footerPanel', 'rightPanel'] });\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            // don't rethrow in this silly function. just log the error\n            // throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    // #endregion private other methods\n\n    // #region public api\n\n    public async initialize(): Promise<void> {\n        const lc = `[${this.initialize.name}]`;\n        console.time(lc);\n        return new Promise(async (resolve, reject) => {\n            try {\n                const isInWebAppProper = isExecutingInBlankGibWebAppProper({\n                    metaName_appId: HTML_META_APP_ID_NAME,\n                    metaContent_appId: HTML_META_APP_ID_CONTENT,\n                });\n\n                if (!isInWebAppProper) {\n                    if (logalot) { console.log(`${lc} executing in iframe so returning early (I: 7118fb26f44e791f46bb0301172bbd25)`); }\n                    return; /* <<<< returns early */\n                }\n                this.registerComponents();\n                console.timeLog(lc, 'registerComponents complete');\n                this.initElements();\n                console.timeLog(lc, 'initElements complete');\n                this.initMobileView(); // <-- Add this line\n                console.timeLog(lc, 'initMobileView complete');\n                // this is waaaay early. but this is only acceptable because\n                // we're just setting css variables. if this changes, we may\n                // need to reorder this.\n                await this.initTheme();\n                console.timeLog(lc, 'initTheme complete');\n                this.initTabButtonsLeftPanel();\n                console.timeLog(lc, 'initTabButtonsLeftPanel complete');\n                this.initTabButtonsRightPanel();\n                console.timeLog(lc, 'initTabButtonsRightPanel complete');\n                this.sillyDrawEyeToElements().then(() => {\n                    console.timeLog(lc, 'sillyDrawEyeToElements complete');\n                }); // spin off\n                this.initHideHeaderOnScroll();\n                console.timeLog(lc, 'initHideHeaderOnScroll complete');\n                // this.initLeftPanelWidthTweak();\n                // console.timeLog(lc, 'initLeftPanelWidthTweak complete');\n                this.initNav();\n                console.timeLog(lc, 'initNav complete');\n                this.initPopstateListener();\n                console.timeLog(lc, 'initPopstateListener complete');\n\n                getGlobalMetaspace_waitIfNeeded().then(async () => {\n                    // at this point, we have initialized the metaspace, because\n                    // these require the metaspace to be initialized and the\n                    // component architecture to be up\n                    this.componentSvc ??= await getComponentSvc();\n                    const { componentSvc } = this;\n                    await this.initHeader({ componentSvc });\n                    console.timeLog(lc, 'initHeader complete');\n                    await this.initRightPanel({ componentSvc });\n                    await this.initLeftPanel({ componentSvc });\n                    await this.initFooter({ componentSvc });\n                    console.timeLog(lc, 'initFooter complete');\n                    console.timeEnd(lc);\n                    resolve();\n                }); // spin off. can't await because metaspace happens after this shell layout finishes\n\n            } catch (error) {\n                console.error(`${lc} ${extractErrorMsg(error)}`);\n                reject(error);\n            } finally {\n                //\n            }\n        });\n    }\n    private async initTheme(): Promise<void> {\n        const lc = `${this.lc}[${this.initTheme.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 7ff768702108c6f7495f6e4eae06a825)`); }\n            // restore the theme if it exists\n            const existingUIInfo = await getExistingUIInfo({\n                dbName: BLANK_GIB_DB_NAME,\n                storeName: ARMY_STORE,\n            });\n            if (existingUIInfo) {\n                for (const [variableName, value] of Object.entries(existingUIInfo.cssVariableOverrides)) {\n                    document.documentElement.style.setProperty(variableName, value);\n                }\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    public expand({ panelNames }: { panelNames: PanelType[] }): void {\n        const lc = `${this.lc}[${this.expand.name}]`;\n        for (const panelName of panelNames) {\n            switch (panelName) {\n                case 'centerPanel':\n                    if (this.isCenterPanelMaximized) {\n                        // Restore state if coming from maximized center\n                        this.restorePanelStates();\n                        this.isCenterPanelMaximized = false;\n                    } else {\n                        // no-op since it's not maximized right now.\n                        console.log(`${lc} centerPanel not maximized. (I: d8bd34a3adcd4afb0ac3954e9afea925)`);\n                        // // if not maximized, just expand left/right/footer in case they were collapsed independently?\n                        // if (this.leftPanel && this.leftPanelContent && this.leftPanelFooter && this.leftPanelHeader) {\n                        //     els.push(this.leftPanel, this.leftPanelContent, this.leftPanelFooter, this.leftPanelHeader);\n                        // }\n                        // if (this.rightPanel && this.rightPanelContent && this.rightPanelFooter && this.rightPanelHeader) {\n                        //     els.push(this.rightPanel, this.rightPanelContent, this.rightPanelFooter, this.rightPanelHeader);\n                        // }\n                        // if (this.footerPanel && this.footerInputContainer) {\n                        //     els.push(this.footerPanel, this.footerInputContainer);\n                        // }\n                    }\n                    break;\n                case 'leftPanel':\n                    this.clearResize([this.leftPanel]);\n                    this.clearClasses(this.leftAll);\n                    this.expandElements(this.leftPanels);\n                    this.collapseElements([this.leftPanelExpandHandle]);\n                    break;\n                case 'rightPanel':\n                    this.clearResize([this.rightPanel]);\n                    this.clearClasses(this.rightAll);\n                    this.expandElements(this.rightPanels);\n                    this.collapseElements([this.rightPanelExpandHandle]);\n                    break;\n                case 'footerPanel':\n                    this.clearResize([this.rightPanel]);\n                    this.clearClasses([this.panelContainer, ...this.footerAll]);\n                    this.expandElements(this.footerPanels);\n                    this.collapseElements([this.footerPanelExpandHandle]);\n                    break;\n                case 'headerPanel':\n                    break;\n                default:\n                    throw new Error(`(UNEXPECTED) Unknown panel name: ${panelName} (E: b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6)`);\n            }\n        }\n    }\n\n    public collapse({ panelNames }: { panelNames: PanelType[] }): void {\n        const lc = `${this.lc}[${this.collapse.name}]`;\n        for (const panelName of panelNames) {\n            switch (panelName) {\n                case 'centerPanel':\n                    console.warn(`${lc} 'centerPanel' collapse is a no-op for now. (W: 16e79f41e5442eba7141bb8af2907125)`);\n                    return;\n                case 'leftPanel':\n                    this.clearResize([this.leftPanel]);\n                    this.clearClasses(this.leftAll!);\n                    this.collapseElements([...this.leftPanels, this.leftPanelCollapseHandle]);\n                    this.updateCollapsedPanelWidthOverride();\n                    break;\n                case 'rightPanel':\n                    this.clearResize([this.rightPanel]);\n                    this.clearClasses(this.rightAll);\n                    this.collapseElements([...this.rightPanels, this.rightPanelCollapseHandle]);\n                    this.updateCollapsedPanelWidthOverride();\n                    break;\n                case 'footerPanel':\n                    this.clearResize([this.rightPanel]);\n                    this.clearClasses([this.panelContainer, ...this.footerAll]);\n                    this.collapseElements([...this.footerPanels, this.footerPanelCollapseHandle]);\n                    break;\n                case 'headerPanel':\n                    break;\n                default:\n                    throw new Error(`(UNEXPECTED) Unknown panel name: ${panelName} (E: c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7)`);\n            }\n        }\n    }\n\n    public maximize({ panelNames }: { panelNames: PanelType[] }): void {\n        const lc = `${this.lc}[${this.maximize.name}]`;\n        for (const panelName of panelNames) {\n            switch (panelName) {\n                case 'centerPanel':\n                    if (!this.isCenterPanelMaximized) {\n                        // Capture current state before maximizing center\n                        this.lastPanelStates = this.getPanelStates();\n                        if (logalot) { console.log(`${lc} captured state: ${pretty(this.lastPanelStates)} (I: c02e17707fcacc7e16ecb73e2dbf2925)`); }\n                        this.isCenterPanelMaximized = true;\n                        this.collapse({ panelNames: ['leftPanel', 'rightPanel', 'footerPanel'] });\n                    } else {\n                        console.log(`${lc} already maximized (I: 6dc6ae73f11442a14129bb42438d0e25)`)\n                    }\n                    break;\n                case 'leftPanel':\n                    this.clearResize([this.leftPanel]);\n                    this.clearAllClasses({ footerAlso: false });\n                    this.collapseElements([\n                        ...this.leftPanels,\n                        ...this.rightPanels, this.rightPanelCollapseHandle,\n                        // ...footerPanels, this.footerPanelCollapseHandle\n                    ]);\n                    this.maximizeElements(this.leftPanels);\n                    this.collapseElements([this.leftPanelMaximizeHandle]);\n                    break;\n                case 'rightPanel':\n                    this.clearResize([this.rightPanel]);\n                    this.clearAllClasses({ footerAlso: false });\n                    this.collapseElements([\n                        ...this.rightPanels,\n                        ...this.leftPanels, this.leftPanelCollapseHandle,\n                        // ...footerPanels, this.footerPanelCollapseHandle\n                    ]);\n                    this.maximizeElements(this.rightPanels);\n                    this.collapseElements([this.rightPanelMaximizeHandle]);\n                    break;\n                case 'footerPanel':\n                    this.clearResize([this.rightPanel]);\n                    this.clearAllClasses({ footerAlso: true });\n                    this.collapseElements([\n                        ...this.rightPanels, this.rightPanelCollapseHandle,\n                        ...this.leftPanels, this.leftPanelCollapseHandle,\n                        this.panelContainer,\n                    ]);\n                    this.maximizeElements(this.footerPanels);\n                    this.collapseElements([this.rightPanelMaximizeHandle]);\n                    break;\n                case 'headerPanel':\n                    console.log(`${lc} no op? (I: d6dda6aa1455cd37622a46541683df25)`)\n                    break;\n                default:\n                    throw new Error(`(UNEXPECTED) Unknown panel name: ${panelName} (E: d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8)`);\n            }\n        }\n    }\n\n    public getPanelStates(): PanelStates {\n        const lc = `${this.lc}[${this.getPanelStates.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 501341aed7f205240a024f26e0889c25)`); }\n\n            let states: PanelStates | undefined = undefined;\n            if (!this.headerPanel) { throw new Error(`(UNEXPECTED) this.headerPanel falsy? (E: c56ae78f8395764d234add5fca025425)`); }\n            if (!this.leftPanel) { throw new Error(`(UNEXPECTED) this.leftPanel falsy? (E: a0fba68516d2c7cd1fa0df92fc777725)`); }\n            if (!this.rightPanel) { throw new Error(`(UNEXPECTED) this.rightPanel falsy? (E: 764bbf40a9186fb3fb7afe3c8c369a25)`); }\n            if (!this.footerPanel) { throw new Error(`(UNEXPECTED) this.footerPanel falsy? (E: 807a9baf4afbe6471d0708840595b625)`); }\n            states = {\n                headerPanel: {\n                    status: this.getPanelVisualState(this.headerPanel),\n                },\n                leftPanel: {\n                    status: this.getPanelVisualState(this.leftPanel),\n                    width: this.leftPanel.style.width || null,\n                    height: this.leftPanel.style.height || null,\n                },\n                rightPanel: {\n                    status: this.getPanelVisualState(this.rightPanel),\n                    width: this.rightPanel.style.width || null,\n                    height: this.rightPanel.style.height || null,\n                },\n                footerPanel: {\n                    status: this.getPanelVisualState(this.footerPanel),\n                    width: this.footerPanel.style.width || null,\n                    height: this.footerPanel.style.height || null,\n                },\n            }\n            if (logalot) { console.log(`${lc} states: ${pretty(states)} (I: cfcdfa42b285e81154073abe87532525)`); }\n            return states;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    public getPanelStatus({ panelName }: { panelName: PanelType }): PanelStatus {\n        const lc = `${this.lc}[${this.getPanelStatus.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: eb49bf7425ff05460be38f59ebda7e25)`); }\n            const states = this.getPanelStates();\n            let panelStateInfo = states[panelName] as PanelState;\n            return panelStateInfo.status;\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    /**\n     * helper function that activates one of the left panel's tabs, based on the\n     * given {@link tabName}\n     */\n    public activateLeftPanelTab({\n        tabName,\n    }: {\n        tabName: RouterAppName,\n    }): void {\n        const lc = `[${this.activateLeftPanelTab.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 5bada68f957da3cf7520a2c2ed249125)`); }\n\n            // first show the left panel if it's not already shown\n            const status = this.getPanelStatus({ panelName: 'leftPanel' });\n            if (status === 'collapsed') {\n                this.expand({ panelNames: ['leftPanel'] });\n            }\n\n            // now do the highlighting of the element\n\n            const { web10TabButton, projectExplorerTabButton, } = this.getLeftPanelTabButtons();\n            // const { web10TabButton, projectExplorerTabButton, tagExplorerTabButton } = this.getLeftPanelTabButtons();\n\n            const web10TabContent = document.getElementById(ID_WEB10_TAB_CONTENT);\n            const projectExplorerTabContent = document_getElementById(ID_PROJECT_EXPLORER_TAB_CONTENT);\n            // const tagExplorerTabContent = document.getElementById(ID_TAG_EXPLORER_TAB_CONTENT);\n\n            if (!web10TabContent) { throw new Error(`(UNEXPECTED) web10TabContent not found? (E: 25a8907b3b7c11e434057c939d322725)`); }\n            if (!projectExplorerTabContent) { throw new Error(`(UNEXPECTED) projectExplorerTabContent not found? (E: 664b2e2b0990950a4280d2c1a1a19325)`); }\n            // if (!tagExplorerTabContent) { throw new Error(`(UNEXPECTED) tagExplorerTabContent not found? (E: 468cc54110fa840edd89256a519cd125)`); }\n\n            const tabButtons = [web10TabButton, projectExplorerTabButton];\n            const tabContents = [web10TabContent, projectExplorerTabContent];\n\n            let tabButtonToShow: HTMLElement;\n            switch (tabName) {\n                case RouterAppName.web1:\n                    tabButtonToShow = web10TabButton;\n                    break;\n                case RouterAppName.projects:\n                    tabButtonToShow = projectExplorerTabButton;\n                    break;\n                // case RouterAppName.tags:\n                //     tabButtonToShow = tagExplorerTabButton;\n                //     break;\n                default:\n                    throw new Error(`(UNEXPECTED) unknown tabName: ${tabName}? (E: fc075a2f1c8daf80c29e3c114ccb4d25)`);\n            }\n\n            tabButtons.forEach(btn => btn.classList.remove('active'));\n            tabButtonToShow.classList.add('active');\n            let contentToShow: HTMLElement | null;\n            if (tabButtonToShow === web10TabButton) {\n                contentToShow = web10TabContent;\n            } else if (tabButtonToShow === projectExplorerTabButton) {\n                contentToShow = projectExplorerTabContent;\n                // } else if (tabButtonToShow === tagExplorerTabButton) {\n                //     contentToShow = tagExplorerTabContent;\n            } else {\n                throw new Error(`(UNEXPECTED) unknown tab button: ${tabButtonToShow.id} (E: 36a601b1c90f8656024b2b34e9831525)`);\n            }\n            tabContents.forEach(content => content.classList.add('collapsed'));\n            contentToShow.classList.remove('collapsed');\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    private chronologysActiveIbGibAddr: IbGibAddr = ROOT_ADDR;\n\n    public async activateRightPanelTab({\n        tabName,\n        ibGibAddr,\n    }: {\n        tabName: 'chronologys',\n        ibGibAddr?: IbGibAddr,\n    }): Promise<void> {\n        const lc = `[${this.activateRightPanelTab.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 08c97c33eddef98c9983d95150763b25)`); }\n\n            if (tabName === 'chronologys') {\n                this.chronologysActiveIbGibAddr = ibGibAddr ?? ROOT_ADDR;\n            }\n\n            // first show the right panel if it's not already shown\n            const status = this.getPanelStatus({ panelName: 'rightPanel' });\n            if (status === 'collapsed') {\n                this.expand({ panelNames: ['rightPanel'] });\n            }\n\n            // now do the highlighting of the tab btn element\n            if (!this.chronologysContent) { throw new Error(`(UNEXPECTED) this.chronologysContent falsy? (E: d89e3fa5aa2202926276a19ace872a25)`); }\n\n            const { chronologysTabButton } = this.getRightPanelTabButtons();\n\n            const tabButtons = [chronologysTabButton];\n            const tabContents = [this.chronologysContent];\n\n            let tabButtonToShow: HTMLElement;\n            switch (tabName) {\n                case 'chronologys':\n                    tabButtonToShow = chronologysTabButton;\n                    break;\n                default:\n                    throw new Error(`(UNEXPECTED) unknown tabName: ${tabName}? (E: fb06833f125858bc8e6f5ce68f5cc925)`);\n            }\n\n            tabButtons.forEach(btn => btn.classList.remove('active'));\n            tabButtonToShow.classList.add('active');\n            let contentToShow: HTMLElement | null;\n            if (tabButtonToShow === chronologysTabButton) {\n                contentToShow = this.chronologysContent;\n            } else {\n                throw new Error(`(UNEXPECTED) unknown tab button: ${tabButtonToShow.id} (E: c850c5511b2b1e0218fdc729ab228625)`);\n            }\n            tabContents.forEach(content => content.classList.add('collapsed'));\n            contentToShow.classList.remove('collapsed');\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    // #endregion public api\n\n    /**\n     * Called by the bootstrap engine when the ibGib engine and metaspace\n     * are fully initialized and ready for interaction.\n     */\n    public onEngineReady(): void {\n        const lc = `${this.lc}[${this.onEngineReady.name}]`;\n        if (logalot) { console.log(`${lc} Engine ready. (I: 231be7a1fcadb7f0659e491411f34f25)`); }\n        // satisfying IbGibAppShell interface\n    }\n}\n\n/**\n * Returns the singleton {@link AppShellService} instance, stored on the\n * globalThis.ibgib.blankgib.shell slot.\n */\nexport function getAppShellSvc(): AppShellService {\n    const lc = `[getAppShellSvc]`;\n    const ibGibGlobalThis = getIbGibGlobalThis_BlankGib(APP_CONFIG);\n    if (!ibGibGlobalThis.shell) {\n        if (logalot) { console.log(`${lc} initializing AppShellService singleton on globalThis... (I: 279ef6e902c2e0e470126938f32a2c25)`); }\n        ibGibGlobalThis.shell = new AppShellService();\n    }\n    return ibGibGlobalThis.shell as AppShellService;\n}\n\n// fnObs\n", "import { delay, extractErrorMsg, pretty } from \"@ibgib/helper-gib/dist/helpers/utils-helper.mjs\";\nimport { GIB, ROOT_ADDR } from \"@ibgib/ts-gib/dist/V1/constants.mjs\";\nimport { Gib, Ib, IbGibAddr } from \"@ibgib/ts-gib/dist/types.mjs\";\nimport { getIbAndGib, getIbGibAddr } from \"@ibgib/ts-gib/dist/helper.mjs\";\nimport { validateGib, validateIb } from \"@ibgib/ts-gib/dist/V1/validate-helper.mjs\";\nimport { isPrimitive } from \"@ibgib/ts-gib/dist/V1/index.mjs\";\nimport { isExecutingInBlankGibWebAppProper, } from \"@ibgib/web-gib/dist/helpers.web.mjs\";\nimport { document_getElementById } from \"@ibgib/web-gib/dist/helpers.web.mjs\";\nimport { getComponentSvc } from \"@ibgib/web-gib/dist/ui/component/ibgib-component-service.mjs\";\n\nimport {\n    GLOBAL_LOG_A_LOT, HTML_META_APP_ID_CONTENT, HTML_META_APP_ID_NAME\n} from \"../../constants.mjs\";\nimport {\n    ROUTER_APP_NAME_WEB1, RouterAppName, VALID_ROUTER_APP_NAMES,\n    WEB1_FILENAME_HOME, isValidRouterAppName,\n} from \"../../common/app-constants.mjs\";\nimport { ID_CENTER_PANEL_CONTENT } from \"../shell/shell-constants.mjs\";\nimport { AppShellService, getAppShellSvc } from \"../shell/app-shell-service.mjs\";\n\nconst logalot = GLOBAL_LOG_A_LOT;\n\n// #region constants\n\nexport const DEFAULT_PATH_APPS_WEB1 = `/apps/${ROUTER_APP_NAME_WEB1}/gib/${WEB1_FILENAME_HOME}`;\n\n// #endregion constants\n\n// #region types\n\nexport interface IbGibRouteInfo {\n    base: 'apps' | string,\n    appName: RouterAppName,\n    gib: Gib,\n    ib: Ib,\n}\n\n// #endregion types\n\n// #region helpers\n\n\nexport function getPath({\n    ibGibRouteInfo,\n}: {\n    ibGibRouteInfo: IbGibRouteInfo,\n}): string {\n    const lc = `[${getPath.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 9c9f46b8cdf54d0b1e7284b5f73b6725)`); }\n\n        // const EXPECTED_PATH_SCHEMA = '/#/apps/[appName]/[gib]/[ib/filename], e.g., /#/apps/web1/gib/home.html';\n\n        const { base, appName, gib, ib } = ibGibRouteInfo;\n\n        const path = `/#/${base}/${appName}/${encodeURI(gib)}/${encodeURI(ib)}`;\n        if (logalot) { console.log(`${lc} path: ${path} (I: 7fe027b8872c57389fd980eb8ddb0d25)`); }\n        return path;\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nexport async function parseRoute({\n    path,\n}: {\n    path: string,\n}): Promise<IbGibRouteInfo> {\n    const lc = `[${parseRoute.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: 68ac065368c70f81cc3f7c6b9a720225)`); }\n\n        path ||= DEFAULT_PATH_APPS_WEB1;\n\n        let pathPieces = path.split('/');\n        if (path.startsWith('/')) { pathPieces = pathPieces.slice(1); }\n        if (path.startsWith('#')) { pathPieces = pathPieces.slice(1); }\n        if (pathPieces.some(x => !x)) { throw new Error(`(UNEXPECTED) empty route path piece? path: ${path} (E: 3727076b99b54328095c4d1862b2fe25)`); }\n\n        const EXPECTED_PATH_SCHEMA = '/#/apps/[appName]/[gib]/[ib/filename], e.g., /#/apps/web1/gib/home.html';\n\n        if (pathPieces.length !== 4) {\n            throw new Error(`${lc} (UNEXPECTED) pathPieces.length !== 3? Right now we're just doing a simple router that expects route in form of ${EXPECTED_PATH_SCHEMA} (E: 82838aff61c4a68ec6ba273a0ed07e25)`)\n        }\n\n        let [base_shouldbeappsrightnow, appName, gib, ib] = pathPieces;\n        ib = decodeURI(ib);\n        gib = decodeURI(gib);\n\n        if (base_shouldbeappsrightnow !== \"apps\") { throw new Error(`(UNEXPECTED) _apps path piece isn't \"apps\" literal? Right now we're just expecting \"apps\" as this path piece? ${EXPECTED_PATH_SCHEMA} (E: 0232cb52674ab47f3a26fd572283c125)`); }\n        const ibValidationErrors = validateIb({ ib }) ?? [];\n        if (ibValidationErrors.length > 0) {\n            throw new Error(`invalid ib in path (${path}). ibValidationErrors: ${pretty(ibValidationErrors)} (E: 3df241dc41963cdfcde541b3b289b225)`);\n        }\n        if (gib !== GIB) {\n            const gibValidationErrors = validateGib({ gib }) ?? [];\n            if (gibValidationErrors.length > 0) {\n                throw new Error(`invalid gib in path (${path}). gibValidationErrors: ${pretty(gibValidationErrors)} (E: 7a4a73f2bd85bfe69ce98d1b9ca54325)`);\n            }\n            // throw new Error(`(UNEXPECTED) gib path piece isn't \"gib\" literal? Right now we're just expecting \"gib\" as this path piece? ${EXPECTED_PATH_SCHEMA} (E: 18a003dd692675787f02a7c113029d25)`);\n        }\n        if (!isValidRouterAppName(appName)) { throw new Error(`invalid appName (${appName}) in path (${path}). valid app names: ${VALID_ROUTER_APP_NAMES} (E: bc407d787dbe6ff66cf4ea6892157f25)`); }\n\n        return { base: base_shouldbeappsrightnow, appName, gib, ib };\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * when html has an anchor tag but we just want to route to something, use this.\n */\nexport async function handleLocalSPAAnchorClick({ event }: { event: any }): Promise<void> {\n    const lc = `[${handleLocalSPAAnchorClick.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: a94f18a96df6cb3e46a3cddeb777df25)`); }\n        // Prevent default link navigation\n        event.preventDefault();\n\n        // modify the browser history quietly (without triggering a page\n        // reload)\n        const href = (event.target as HTMLAnchorElement).getAttribute('href')!;\n        window.history.pushState({}, '', href);\n\n        // update the document title to reflect the new location for\n        // accurate browser history and tab name\n        const { appName, ib } = await parseRoute({\n            path: href.startsWith('#') ? href.substring(1) : href\n        });\n        document.title = `${ib} - ibgib ${appName}`;\n\n        // we have now set the new URL and we need to trigger the actual\n        // load via the router\n        simpleIbGibRouterSingleton.loadCurrentURLPath();\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n// #endregion helpers\n\nasync function route(path: string): Promise<void> {\n    const lc = `[${route.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: a1b2c3d4e5f67890)`); }\n\n        const isInWebAppProper = isExecutingInBlankGibWebAppProper({\n            metaName_appId: HTML_META_APP_ID_NAME,\n            metaContent_appId: HTML_META_APP_ID_CONTENT,\n        });\n\n        if (!isInWebAppProper) {\n            if (logalot) { console.log(`${lc} executing in iframe so returning early without routing (I: b84172ceedb5fea0c5d0c1cfbd911b25)`); }\n            return; /* <<<< returns early */\n        }\n\n        if (path === '' || path === '/') { path = DEFAULT_PATH_APPS_WEB1; }\n\n        let info = await parseRoute({ path });\n\n        const { appName, ib, gib } = info;\n        const ibGibAddr = getIbGibAddr({ ib, gib });\n\n        const appShellSvc = getAppShellSvc();\n\n        await route_centerPanel({ path, ibGibAddr });\n        await route_leftPanel({ path, appName, ib, gib, ibGibAddr, appShellSvc });\n\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        // Display a generic error message in the center pane if routing fails\n        document.getElementById('center-canvas-area')!.innerHTML = `<p class=\"error\">Error loading page.</p><p>${extractErrorMsg(error)}</p>`;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nasync function route_centerPanel({\n    path,\n    ibGibAddr,\n}: {\n    path: string,\n    ibGibAddr: IbGibAddr,\n}): Promise<void> {\n    const lc = `[${route_centerPanel.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: c4c0c83822783d0fc8cdefda75391c25)`); }\n\n        const centerPanelContent = document_getElementById(ID_CENTER_PANEL_CONTENT);\n\n        const componentSvc = await getComponentSvc();\n        const componentToInject = await componentSvc.getComponentInstance({\n            useRegExpPrefilter: true,\n            path,\n            ibGibAddr,\n        });\n\n        if (componentToInject) {\n            await componentSvc.inject({\n                parentEl: centerPanelContent,\n                componentToInject,\n            });\n            // since this is a route-level injection, we will style it as a page.\n            componentToInject.classList.add('ibgib-page');\n        } else {\n            console.warn(`${lc} No component found to handle route: ${path} (W: db04f7fdfbd32caf817d0122a292ae25)`);\n            centerPanelContent.innerHTML = `<p class=\"error\">No component found for route: ${path}</p>`;\n        }\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nasync function route_leftPanel({\n    path,\n    appName,\n    ib, gib,\n    ibGibAddr,\n    appShellSvc,\n}: {\n    path: string,\n    appName: string,\n    ib: Ib, gib: Gib,\n    ibGibAddr: IbGibAddr,\n    appShellSvc: AppShellService,\n}): Promise<void> {\n    const lc = `[${route_leftPanel.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: c4c0c83822783d0fc8cdefda75391c25)`); }\n\n        if (isPrimitive({ gib })) {\n            appShellSvc.activateLeftPanelTab({ tabName: 'web1' })\n        } else if (appName === 'projects') {\n            appShellSvc.activateLeftPanelTab({ tabName: 'projects' })\n        } else {\n            appShellSvc.activateLeftPanelTab({ tabName: 'web1' })\n        }\n\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\nasync function route_rightPanel({\n    path,\n    appName,\n    ib, gib,\n    ibGibAddr,\n    appShellSvc,\n}: {\n    path: string,\n    appName: string,\n    ib: Ib, gib: Gib,\n    ibGibAddr: IbGibAddr,\n    appShellSvc: AppShellService,\n}): Promise<void> {\n    const lc = `[${route_rightPanel.name}]`;\n    try {\n        if (logalot) { console.log(`${lc} starting... (I: c4c0c83822783d0fc8cdefda75391c25)`); }\n\n        if (isPrimitive({ gib })) {\n            // don't need to do anything?...\n            // appShellSvc.chronolo;\n        } else if (appName === 'projects') {\n            // should this be done some other way...expose current ibgib addr?\n            appShellSvc.activateLeftPanelTab({ tabName: 'projects' })\n        } else {\n            appShellSvc.activateLeftPanelTab({ tabName: 'web1' })\n        }\n\n    } catch (error) {\n        console.error(`${lc} ${extractErrorMsg(error)}`);\n        throw error;\n    } finally {\n        if (logalot) { console.log(`${lc} complete.`); }\n    }\n}\n\n/**\n * simplistic SPA-like router, but focused on routing ibgib addresses.\n */\nexport class SimpleIbGibRouter {\n    protected lc: string = `[${SimpleIbGibRouter.name}]`;\n\n    get currentURLPath(): string {\n        const path = window.location.hash.substring(1); // Remove the leading '#'\n        return path;\n    }\n\n    /**\n     *\n     */\n    constructor() {\n\n    }\n\n    getCurrentPathInfo(): Promise<IbGibRouteInfo> {\n        return parseRoute({ path: this.currentURLPath });\n    }\n\n\n    async loadCurrentURLPath(): Promise<void> {\n        const lc = `${this.lc}[${this.loadCurrentURLPath.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 2301ec8af3d848230826f3799a462725)`); }\n            await route(this.currentURLPath);\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            await route('/');\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n\n    get isCurrentPageWeb1(): boolean {\n        const path = window.location.hash.substring(1); // Remove the leading '#'\n        const isWeb1 = path.startsWith('/apps/web1') || path === \"\";\n        return isWeb1;\n    }\n\n    /**\n     * updates the current URL with the given {@link ibGibAddr}. If that is\n     * falsy, then will remove any existing ibGibAddr from the URL, if\n     * there is one.\n     */\n    async updateCurrentURLPathIbGibAddr({\n        ibGibAddr,\n        replace,\n    }: {\n        ibGibAddr?: IbGibAddr,\n        replace?: boolean,\n    }): Promise<void> {\n        const lc = `${this.lc}[${this.updateCurrentURLPathIbGibAddr.name}]`;\n        try {\n            if (logalot) { console.log(`${lc} starting... (I: 6adcf3cf5e489c2d036f8391dc858825)`); }\n\n            let currentPath = window.location.hash.substring(1); // Remove the leading '#'\n            let currentPathInfo = await parseRoute({ path: currentPath });\n            let { ib, gib } = getIbAndGib({ ibGibAddr: ibGibAddr ?? ROOT_ADDR });\n            if (currentPathInfo.ib === ib && currentPathInfo.gib === gib) {\n                if (logalot) { console.log(`${lc} current path ibGibAddr === incoming ibGibAddr so no need to update. returning early. (I: 0f67662a76f96ec5c60ff08bced73c25)`); }\n                return; /* <<<< returns early */\n            }\n            let fullPath = getPath({\n                ibGibRouteInfo: {\n                    appName: currentPathInfo.appName,\n                    base: currentPathInfo.base,\n                    ib,\n                    gib,\n                }\n            });\n            if (replace) {\n                // replace current browser nav stack entry\n                window.history.replaceState({}, '', fullPath);\n            } else {\n                // add to browser nav stack\n                window.history.pushState({}, '', fullPath);\n            }\n        } catch (error) {\n            console.error(`${lc} ${extractErrorMsg(error)}`);\n            throw error;\n        } finally {\n            if (logalot) { console.log(`${lc} complete.`); }\n        }\n    }\n}\n\n/**\n * maybe YAGNI, but we're doing this for now.\n */\nexport const simpleIbGibRouterSingleton = new SimpleIbGibRouter();\n"],
  "mappings": "iFAQO,IAAMA,GAAc,2BAOdC,GAAmB,wBAMnBC,GAA0C,mHAC1CC,GAAiC,eAKjCC,GAAoC,oBAIpCC,GAAoC,oBA8B1C,IAAMC,GAA8B,IAK9BC,GAA6B,qBChE1C,IAAMC,GAA8B,GAEhCC,GAAc,WAAW,OACzB,CAAE,OAAAC,EAAM,EAAKD,GAGJE,GAAkD,CAC3D,QAAW,UACX,QAAW,WAGT,SAAUC,EAAMC,EAAQ,CAC1B,OAAO,KAAK,MAAM,KAAK,UAAUA,CAAG,CAAC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_CAPTURE_GROUPS_REGEXP", "ERROR_MSG_LOCATION_ONLY_REGEXP", "HEXADECIMAL_HASH_STRING_REGEXP_32", "HEXADECIMAL_HASH_STRING_REGEXP_64", "DEFAULT_DATA_PATH_DELIMITER", "ONLY_HAS_NON_ALPHANUMERICS", "logalot", "crypto", "subtle", "HashAlgorithm", "clone", "obj", "__name", "getTimestamp", "date", "hash", "s", "algorithm", "validAlgorithms", "msgUint8", "buffer", "b", "error", "extractErrorMsg", "getUUID", "seedSize", "uuid", "values", "pretty", "delay", "ms", "resolve", "groupBy", "items", "keyFn", "lc", "result", "i", "item", "key", "getRegExp", "min", "max", "chars", "noSpaces", "getTimestampInTicks", "timestamp", "getExpirationUTCString", "startDate", "years", "months", "days", "hours", "seconds", "addTimeToDate", "intervalToAdd", "newDateTicks", "isExpired", "expirationTimestampUTC", "expirationDate", "unique", "arr", "patchObject", "value", "path", "pathDelimiter", "DEFAULT_DATA_PATH_DELIMITER", "targetObj", "pathPieces", "x", "piece", "currentValue", "getIdPool", "n", "id", "getSaferSubstring", "text", "length", "keepLiterals", "replaceMap", "saferText", "tokenToKeepMap", "keep", "tmpToken", "pickRandom_Letters", "toReplace", "replaceWith", "tokens", "token", "ONLY_HAS_NON_ALPHANUMERICS", "pickRandom", "randomIndex", "count", "getIbGibAddr", "ib", "gib", "ibGib", "delimiter", "__name", "getIbAndGib", "ibGibAddr", "lc", "pieces", "crypto", "subtle", "sha256v1", "ibGib", "salt", "hashToHex", "__name", "message", "msgUint8", "buffer", "subtle", "b", "hashToHex_Uint8Array", "tohashUint8Array", "msgUint8_salt", "hashAsBuffer", "toNormalizedForHashing", "value", "element", "normalizedObject", "sortedKeys", "key", "propertyValue", "hashFields", "ib", "data", "rel8ns", "hasRel8ns", "k", "hasData", "ibHash", "rel8nsHash", "dataHash", "Rel8n", "IB", "GIB", "ROOT", "IBGIB_DELIMITER", "GIB_DELIMITER", "ROOT_ADDR", "FORBIDDEN_ADD_RENAME_REMOVE_REL8N_NAMES", "IB_MAX_LENGTH_DEFAULT", "IB_REGEXP_DEFAULT", "buildDna", "opts", "transformData", "clone", "lc", "result", "IBGIB_DELIMITER", "GIB", "sha256v1", "__name", "isDna", "ibGib", "knownTransformPrimitiveAddrs", "x", "error", "extractErrorMsg", "isPrimitive", "gib", "getGib", "hasTjp", "tjpAddr", "gibDelimiter", "hashAlgorithm", "ibGibHash", "rel8ns", "data", "GIB_DELIMITER", "tjpAddrGib", "getIbGibAddr", "getIbAndGib", "getGibInfo", "ibGibAddr", "pieces", "p", "piecesCount", "fork", "opts", "noTimestamp", "dna", "linkedRel8ns", "destIb", "uuid", "tjp", "cloneRel8ns", "cloneData", "type", "src", "lc", "IBGIB_DELIMITER", "dto", "srcAddr", "getIbGibAddr", "rel8ns", "clone", "data", "ancestor", "Rel8n", "newIbGib", "date", "getTimestamp", "getUUID", "ROOT_ADDR", "transformDna", "buildDna", "dnaAddr", "sha256v1", "result", "__name", "mut8", "opts", "noTimestamp", "dna", "linkedRel8ns", "dataToRename", "dataToRemove", "dataToAddOrPatch", "mut8Ib", "type", "src", "lc", "IBGIB_DELIMITER", "srcAddr", "getIbGibAddr", "isPrimitive", "dto", "newIbGib", "clone", "srcRel8ns", "rel8ns", "Rel8n", "data", "renameOrRemove", "patch", "date", "getTimestamp", "tjpRel8n", "transformDna", "buildDna", "dnaAddr", "hasTjp", "getGib", "result", "__name", "obj", "info", "which", "FORBIDDEN_RENAME_REMOVE_KEYS", "key", "infoVal", "patchInfo", "patchKey", "patchVal", "objVal", "rel8", "opts", "noTimestamp", "dna", "linkedRel8ns", "rel8nsToAddByAddr", "rel8nsToRemoveByAddr", "type", "src", "lc", "IBGIB_DELIMITER", "isPrimitive", "isAdding", "isRemoving", "srcAddr", "getIbGibAddr", "fnValidIbGibAddr", "__name", "s", "x", "rel8ds", "rel8d", "dto", "newIbGib", "clone", "data", "date", "getTimestamp", "rel8ns", "rel8nName", "FORBIDDEN_ADD_RENAME_REMOVE_REL8N_NAMES", "existingRel8d", "newRel8d", "toRemoveRel8d", "prunedRel8d", "linkedRel8nName", "initialLength", "tjpRel8n", "hasTjp", "transformDna", "buildDna", "dnaAddr", "Rel8n", "getGib", "result", "hasTjp", "ibGib", "lc", "dnaPrimitives", "x", "GIB_DELIMITER", "GIB", "getGibInfo", "getIbGibAddr", "__name", "toDto", "dtoIbGib", "clone", "logalot", "validateIbGibIntrinsically", "ibGib", "lc", "errors", "addr", "getIbGibAddr", "validateIbGibAddr", "isPrimitive", "gottenGib", "getGib", "toDto", "hasTjp", "error", "extractErrorMsg", "__name", "delimiter", "version", "IBGIB_DELIMITER", "ib", "gib", "getIbAndGib", "resValidateIb", "validateIb", "resValidateGib", "validateGib", "ibGibAddrDelimiter", "IB", "gibDelimiter", "INVALID_GIB_CHARS", "invalidCharsFound", "invalidChar", "punctiliarHash", "tjpGib", "getGibInfo", "GIB_DELIMITER", "punctiliarHashIs_32", "HEXADECIMAL_HASH_STRING_REGEXP_32", "punctiliarHashIs_64", "HEXADECIMAL_HASH_STRING_REGEXP_64", "tjpGibValidationErrors", "validateRel8nsIntrinsically", "rel8ns", "rel8nNames", "i", "rel8nName", "addrs", "j", "addrErrors", "logalot", "Factory_V1", "_Factory_V1", "__name", "IB", "ib", "GIB", "ibs", "parentIbGib", "data", "rel8ns", "dna", "tjp", "linkedRel8ns", "noTimestamp", "nCounter", "squash", "lc", "interimResults", "src", "ROOT", "resFork", "fork", "resMut8", "mut8", "resRel8", "rel8", "newIbGib", "resultWithIntermediates", "x", "dnas", "res", "getGib", "error", "extractErrorMsg", "parentPrimitiveIb", "ibRegExpPattern", "uuid", "validateIb", "regExp", "IB_REGEXP_DEFAULT", "incomingRel8nNames", "forbiddenRel8nNames", "FORBIDDEN_ADD_RENAME_REMOVE_REL8N_NAMES", "stoneIbGib", "getUUID", "GLOBAL_TIMER_NAME", "SAFE_SPECIAL_CHARS", "IB_REGEXP_DEFAULT", "ROBBOT_NAME_REGEXP", "ROBBOT_PREFIX_SUFFIX_REGEXP", "SpecialIbGibType", "ROBBOT_REL8N_NAME", "ZERO_SPACE_ID", "IBGIB_SPACE_NAME_DEFAULT", "PERSIST_OPTS_AND_RESULTS_IBGIBS_DEFAULT", "DEFAULT_LOCAL_SPACE_DESCRIPTION", "SPACE_NAME_REGEXP", "SYNC_SPACE_REL8N_NAME", "DEFAULT_LOCAL_SPACE_POLLING_INTERVAL_MS", "SPACE_ATOM", "SPACE_LOCK_IB_TERM", "DEFAULT_MAX_DELAY_MS_RETRY_LOCK_ACQUIRE", "DEFAULT_MAX_DELAY_RETRY_LOCK_ACQUIRE_ATTEMPTS", "MAX_LOCK_SECONDS_VALID", "DEFAULT_SECONDS_VALID_LOCAL", "ROOT_REL8N_NAME", "DEFAULT_ROOT_REL8N_NAME", "DEFAULT_ROOT_TEXT", "DEFAULT_ROOT_ICON", "DEFAULT_ROOT_DESCRIPTION", "TAG_REL8N_NAME", "TAG_TARGET_REL8N_NAME", "DEFAULT_TAG_ICON", "DEFAULT_TAG_DESCRIPTION", "AUTOSYNC_ALWAYS_REL8N_NAME", "ARCHIVE_REL8N_NAME", "TRASH_REL8N_NAME", "SPECIAL_IBGIB_TYPE_REGEXP", "INVALID_DATE_STRING", "TRUE_GIB", "GIB", "FALSE_GIB", "GIB", "CONFIG_KEY_ATOM", "APP_NAME_REGEXP", "APP_REL8N_NAME", "BOOTSTRAP_IBGIB_ADDR", "GIB", "BOOTSTRAP_DATA_DEFAULT_SPACE_ID_KEY", "BOOTSTRAP_DATA_KNOWN_SPACE_IDS_KEY", "SaltStrategy", "SALT_STRATEGIES", "HashAlgorithm", "HASH_ALGORITHMS", "AlphabetIndexingMode", "ALPHABET_INDEXING_MODES", "encodeStringToHexString", "s", "lc", "resolve", "reject", "bytes", "stringToUTF8Bytes", "hexString", "bytesToHexString", "error", "extractErrorMsg", "__name", "byte", "decodeHexStringToString", "hexStringToBytes", "utf8BytesToString", "numBytes", "i", "DEFAULT_SALT_STRATEGY", "SaltStrategy", "DEFAULT_HASH_ALGORITHM", "DEFAULT_GETUUID_SEEDSIZE", "DEFAULT_INITIAL_RECURSIONS", "DEFAULT_RECURSIONS_PER_HASH", "DEFAULT_ALPHABET_INDEXING_MODE_LEGACY", "DEFAULT_ALPHABET_INDEXING_MODE_BLOCKMODE", "DEFAULT_MAX_BLOCK_SIZE", "DEFAULT_NUM_OF_PASSES", "DEFAULT_ENCRYPTED_DATA_DELIMITER", "getPreHash", "secret", "prevHash", "salt", "saltStrategy", "SaltStrategy", "__name", "execRound_getNextHash", "count", "hashAlgorithm", "lc", "hash", "i", "preHash", "error", "extractErrorMsg", "doInitialRecursions_keystretch", "initialRecursions", "encryptFromHex_stream", "hexEncodedData", "initialRecursions", "recursionsPerHash", "salt", "saltStrategy", "secret", "hashAlgorithm", "encryptedDataDelimiter", "indexingMode", "lc", "prevHash", "doInitialRecursions_keystretch", "getIndex", "alphabet", "hexChar", "encryptedDataIndexes", "i", "hexCharFromData", "hash", "execRound_getNextHash", "charIndex", "error", "extractErrorMsg", "__name", "decryptToHex_stream", "encryptedData", "initialRecursions", "recursionsPerHash", "salt", "saltStrategy", "secret", "hashAlgorithm", "encryptedDataDelimiter", "lc", "prevHash", "doInitialRecursions_keystretch", "encryptedDataIndexes", "nString", "decryptedDataArray", "i", "charIndex", "alphabet", "hash", "execRound_getNextHash", "hexChar", "error", "extractErrorMsg", "__name", "decryptImpl_stream", "encryptedData", "initialRecursions", "recursionsPerHash", "salt", "saltStrategy", "secret", "hashAlgorithm", "encryptedDataDelimiter", "lc", "errors", "warnings", "DEFAULT_INITIAL_RECURSIONS", "DEFAULT_RECURSIONS_PER_HASH", "DEFAULT_SALT_STRATEGY", "DEFAULT_HASH_ALGORITHM", "getUUID", "DEFAULT_GETUUID_SEEDSIZE", "DEFAULT_ENCRYPTED_DATA_DELIMITER", "lcv", "e", "HashAlgorithm", "SALT_STRATEGIES", "hexEncodedData", "decryptToHex_stream", "decodeHexStringToString", "__name", "encryptImpl_stream", "dataToEncrypt", "initialRecursions", "recursionsPerHash", "salt", "saltStrategy", "secret", "hashAlgorithm", "encryptedDataDelimiter", "confirm", "indexingMode", "lc", "errors", "warnings", "DEFAULT_INITIAL_RECURSIONS", "DEFAULT_RECURSIONS_PER_HASH", "DEFAULT_SALT_STRATEGY", "DEFAULT_HASH_ALGORITHM", "getUUID", "DEFAULT_GETUUID_SEEDSIZE", "DEFAULT_ENCRYPTED_DATA_DELIMITER", "DEFAULT_ALPHABET_INDEXING_MODE_LEGACY", "lcv", "e", "ALPHABET_INDEXING_MODES", "HashAlgorithm", "SALT_STRATEGIES", "hexEncodedData", "encodeStringToHexString", "decodeHexStringToString", "encryptedData", "encryptFromHex_stream", "resDecrypt", "decryptImpl_stream", "__name", "encryptFromHex_blockMode", "hexEncodedData", "initialRecursions", "recursionsPerHash", "salt", "saltStrategy", "secret", "hashAlgorithm", "encryptedDataDelimiter", "indexingMode", "maxBlockSize", "numOfPasses", "lc", "prevHash", "doInitialRecursions_keystretch", "getIndexOfCharInAlphabet", "alphabet", "hexChar", "encryptedDataIndexes", "totalLength", "blockSize", "blockSections", "finalBlockSize", "indexHexEncodedDataAtStartOfPass", "indexOfBlock", "resGetAlphabets", "getAlphabetsThisBlock", "alphabetsThisBlock", "encryptedIndexesThisBlock", "getEncryptedIndexesThisBlock", "error", "extractErrorMsg", "__name", "indexHexEncodedData", "hash", "passNum", "indexIntoBlock", "execRound_getNextHash", "hexCharFromData", "resIndexes", "encryptedIndexIntoAlphabet", "decryptToHex_blockMode", "encryptedData", "initialRecursions", "recursionsPerHash", "salt", "saltStrategy", "secret", "hashAlgorithm", "encryptedDataDelimiter", "maxBlockSize", "numOfPasses", "lc", "prevHash", "doInitialRecursions_keystretch", "encryptedDataIndexes", "nString", "decryptedDataArray", "totalLength", "blockSize", "blockSections", "finalBlockSize", "indexEncryptedDataIndexesAtStartOfPass", "indexOfBlock", "resGetAlphabets", "getAlphabetsThisBlock", "alphabetsThisBlock", "decryptedDataArrayThisBlock", "getDecryptedDataArrayThisBlock", "error", "extractErrorMsg", "__name", "indexEncryptedDataIndexes", "hash", "passNum", "indexIntoBlock", "alphabet", "execRound_getNextHash", "encryptedIndex", "resDataArray", "decryptedCharString", "decryptImpl_blockMode", "args", "lc", "encryptedData", "initialRecursions", "recursionsPerHash", "salt", "saltStrategy", "secret", "hashAlgorithm", "encryptedDataDelimiter", "indexingMode", "blockMode", "multipass", "errors", "warnings", "DEFAULT_INITIAL_RECURSIONS", "DEFAULT_RECURSIONS_PER_HASH", "DEFAULT_SALT_STRATEGY", "DEFAULT_HASH_ALGORITHM", "getUUID", "DEFAULT_GETUUID_SEEDSIZE", "DEFAULT_ENCRYPTED_DATA_DELIMITER", "DEFAULT_ALPHABET_INDEXING_MODE_BLOCKMODE", "maxBlockSize", "maxPassSectionLength", "numOfPasses", "DEFAULT_MAX_BLOCK_SIZE", "DEFAULT_NUM_OF_PASSES", "lcv", "e", "ALPHABET_INDEXING_MODES", "HashAlgorithm", "SALT_STRATEGIES", "result", "hexEncodedData", "decryptToHex_blockMode", "decryptedData", "decodeHexStringToString", "__name", "encryptImpl_blockMode", "args", "lc", "dataToEncrypt", "initialRecursions", "recursionsPerHash", "salt", "saltStrategy", "secret", "hashAlgorithm", "encryptedDataDelimiter", "confirm", "indexingMode", "blockMode", "multipass", "errors", "warnings", "DEFAULT_INITIAL_RECURSIONS", "DEFAULT_ENCRYPTED_DATA_DELIMITER", "DEFAULT_ALPHABET_INDEXING_MODE_BLOCKMODE", "maxBlockSize", "maxPassSectionLength", "numOfPasses", "DEFAULT_MAX_BLOCK_SIZE", "DEFAULT_NUM_OF_PASSES", "lcv", "e", "ALPHABET_INDEXING_MODES", "HashAlgorithm", "SALT_STRATEGIES", "result", "hexEncodedData", "encodeStringToHexString", "decodeHexStringToString", "encryptedData", "encryptFromHex_blockMode", "resDecrypt", "decryptImpl_blockMode", "error", "extractErrorMsg", "__name", "encrypt", "args", "lc", "getUUID", "DEFAULT_GETUUID_SEEDSIZE", "DEFAULT_SALT_STRATEGY", "DEFAULT_HASH_ALGORITHM", "DEFAULT_RECURSIONS_PER_HASH", "result", "encryptImpl_blockMode", "encryptImpl_stream", "e", "w", "error", "__name", "decrypt", "decryptImpl_blockMode", "decryptImpl_stream", "DEFAULT_ENCRYPTION_INITIAL_RECURSIONS", "DEFAULT_ENCRYPTION_SALT_STRATEGY", "SaltStrategy", "DEFAULT_ENCRYPTION_RECURSIONS_PER_HASH", "DEFAULT_ENCRYPTION_HASH_ALGORITHM", "ENCRYPTION_REL8N_NAME", "CIPHERTEXT_ATOM", "SpaceLocation", "VALID_SPACE_LOCATIONS", "SpaceType", "VALID_SPACE_TYPES", "UserSpaceSubtype", "SyncSpaceSubtype", "SpaceSubtype", "VALID_SPACE_SUBTYPES", "IbGibSpaceOptionsCmd", "IbGibSpaceOptionsCmdModifier", "logalot", "DynamicFormBuilder", "_DynamicFormBuilder", "__name", "lc", "resultArray", "chars", "charLength", "i", "charIndex", "id", "what", "item", "idPool", "value", "required", "defaultValue", "getRegExp", "SAFE_SPECIAL_CHARS", "of", "label", "UUID_REGEXP", "formName", "WitnessFormBuilder", "_WitnessFormBuilder", "DynamicFormBuilder", "__name", "of", "required", "data", "allowPrimitiveArgs", "catchAllErrors", "persistOptsAndResultIbGibs", "trace", "version", "logalot", "validateCommonAppData", "appData", "lc", "logalot", "errors", "name", "uuid", "classname", "APP_NAME_REGEXP", "UUID_REGEXP", "error", "__name", "getAppIb", "validationErrors", "getInfoFromAppIb", "appIb", "pieces", "createNewApp", "fnPromptApp", "ibgibs", "space", "lc", "logalot", "resApp", "newApp", "allIbGibs", "x", "i", "ibGib", "validationErrors", "validateIbGibIntrinsically", "pretty", "persistTransformResult", "zeroSpace", "fnBroadcast", "fnUpdateBootstrap", "registerNewIbGib", "__name", "rel8ToSpecialIbGib", "APP_REL8N_NAME", "error", "DEFAULT_UUID_CHAT_APP", "DEFAULT_NAME_CHAT_APP", "DEFAULT_DESCRIPTION_CHAT_APP", "DEFAULT_CHAT_APP_DATA_V1", "DEFAULT_CHAT_APP_REL8NS_V1", "DEFAULT_UUID_RAW_APP", "DEFAULT_NAME_RAW_APP", "DEFAULT_DESCRIPTION_RAW_APP", "DEFAULT_RAW_APP_DATA_V1", "DEFAULT_RAW_APP_REL8NS_V1", "DEFAULT_UUID_TODO_APP", "DEFAULT_NAME_TODO_APP", "DEFAULT_DESCRIPTION_TODO_APP", "DEFAULT_TODO_APP_DATA_V1", "DEFAULT_TODO_APP_REL8NS_V1", "validateBootstrapIbGib", "bootstrapSpace", "lc", "errors", "getIbGibAddr", "BOOTSTRAP_IBGIB_ADDR", "intrinsicErrors", "validateIbGibIntrinsically", "e", "data", "rel8ns", "spaceId", "BOOTSTRAP_DATA_DEFAULT_SPACE_ID_KEY", "error", "__name", "META_STONE_ATOM", "DEFAULT_META_STONE_TIMESTAMP", "META_STONE_TARGET_REL8N_NAME", "META_STONE_TARGET_TJP_REL8N_NAME", "logalot", "validateCommonMetaStoneIb", "ib", "lc", "errors", "pieces", "META_STONE_ATOM", "tjpGib", "tjpGibValidationErrors", "validateGib", "nAsString", "parsedN", "timestampInTicks", "timestampInfo", "getTimestampInfo", "error", "extractErrorMsg", "__name", "validateCommonMetaStoneData", "data", "targetData", "timestamp", "targetTjpGib", "targetN", "targetTimestamp", "targetTimestampInfo", "timestampDate", "validateCommonMetaStoneRel8ns", "rel8ns", "intrinsicErrors", "validateRel8nsIntrinsically", "targetAddrs", "META_STONE_TARGET_REL8N_NAME", "targetTjpAddrs", "META_STONE_TARGET_TJP_REL8N_NAME", "validateCommonMetaStoneIbGib", "ibGib", "validateIbGibIntrinsically", "ibErrors", "atom", "n", "parseMetaStoneIb", "dataErrors", "rel8nsErrors", "result", "getMetaStoneIb", "classname", "validationErrors", "targetTimestampInTicks", "getTimestampInTicks", "DEFAULT_META_STONE_TIMESTAMP", "isMetaStone", "addr", "getIbGibAddr", "newUpMetaStone", "targetIbGib", "targetAddr", "targetTjpAddr", "getTjpAddr", "metaStoneData", "metaStoneRel8ns", "getGibInfo", "GIB", "metaStoneTimestampDate", "metaStoneTimestamp", "getTimestamp", "metaStoneTimestampMs", "isBinary", "metaStoneIb", "metaStoneIbGib", "constantIbGib", "WITNESS_ATOM", "WITNESS_ARG_METADATA_STRING", "WITNESS_RESULT_METADATA_STRING", "WITNESS_CONTEXT_REL8N_NAME", "logalot", "getFromSpace", "addr", "addrs", "isDna", "space", "force", "lc", "logalot", "argGet", "getSpaceArgMetadata", "result", "error", "__name", "putInSpace", "ibGib", "ibGibs", "x", "argPutIbGibs", "getIbGibAddr", "resPutIbGibs", "warning", "errorMsg", "deleteFromSpace", "argDel", "persistTransformResult", "resTransform", "newIbGib", "intermediateIbGibs", "dnas", "argPutDnas", "resPutDnas", "getSpecialRel8dIbGibs", "type", "rel8nName", "special", "getSpecialIbGib", "rel8dAddrs", "rel8dIbgibs", "i", "resGet", "initialize", "zeroSpace", "fnUpdateBootstrap", "fnBroadcast", "fnGetInitializing", "fnSetInitializing", "dontWarnIfNotExist", "key", "getSpecialConfigKey", "getConfigAddr", "createSpecial", "resSpecial", "specialIbGib", "resLatest", "getLatestAddrs", "specialAddr", "latestAddr", "emsg", "dontWarn", "setConfigAddr", "rel8nsToAddByAddr", "resNewSpace", "rel8", "newSpace", "getCurrentRoot", "roots", "currentRootAddr", "resCurrentRoot", "setCurrentRoot", "root", "rootAddr", "resNewRoots", "configKey", "newRoots", "newRootsAddr", "registerNewIbGib", "rel8ToCurrentRoot", "linked", "currentRoot", "tjpAddr", "getTjpAddr", "ibGibAddr", "DEFAULT_ROOT_REL8N_NAME", "resNewRoot", "newRoot", "newRootAddr", "createAndSaveNewMetaStone", "targetIbGib", "metaStone", "newUpMetaStone", "resPutMetaStone", "extractErrorMsg", "initialLogalot", "getGibInfo", "tjp", "getTjpIbGib", "replaceLatest", "success", "latestAddrsMap", "errors", "pretty", "keysLatestAddrsMap", "existingLatestAddr", "resExistingLatest", "existingLatestIbGib", "n_ibGib", "n_existingLatest", "getLatestAddr_Brute", "rel8ToSpecialIbGib", "ibGibsToRel8", "ibGibsToUnRel8", "addrsToUnRel8", "severPast", "deletePreviousSpecialIbGib", "addrsToRel8", "resGetSpecial", "oldSpecialIbGib", "resNewSpecial", "Rel8n", "newSpecialIbGib", "getGib", "newSpecialAddr", "specialTjpAddr", "naive", "gib", "getIbAndGib", "GIB", "isTjp_Naive", "firstTjpAddr", "resGetTjpIbGib", "resErrorMsg", "past", "pastIbGibAddr", "resGetPastIbGib", "pastIbGib", "createSpecial_Roots", "createSpecial_Tags", "createSpecial_Secrets", "createSpecial_Encryptions", "createSpecial_OuterSpaces", "createSpecial_Autosyncs", "createSpecial_Robbots", "createSpecial_Apps", "createSpecial_Default", "createSpecialIbGib", "skipRel8ToRoot", "specialIb", "getSpecialIbGibIb", "src", "Factory_V1", "fork", "initialTagDatas", "data", "createTagIbGibAndSundry", "text", "icon", "description", "DEFAULT_TAG_ICON", "DEFAULT_TAG_DESCRIPTION", "tagIb", "tagTextToIb", "tagPrimitive", "resNewTag", "newTag", "newTagsAddr", "rel8TagToTagsIbGib", "rootsIbGib", "rootsAddr", "initialDatas", "n", "DEFAULT_ROOT_ICON", "DEFAULT_ROOT_DESCRIPTION", "firstRoot", "resCreate", "createRootIbGib", "DEFAULT_ROOT_TEXT", "ib", "getRootIb", "parentIbGib", "resNewIbGib", "ROOT_REL8N_NAME", "secretsAddr", "secretsIbgib", "encryptionsIbgib", "outerSpacesAddr", "outerSpacesIbGib", "autosyncsAddr", "autosyncsIbGib", "robbotsAddr", "robbotsIbGib", "appsAddr", "appsIbGib", "createApp", "DEFAULT_CHAT_APP_DATA_V1", "DEFAULT_CHAT_APP_REL8NS_V1", "DEFAULT_RAW_APP_DATA_V1", "DEFAULT_RAW_APP_REL8NS_V1", "DEFAULT_TODO_APP_DATA_V1", "DEFAULT_TODO_APP_REL8NS_V1", "defaultAppData", "defaultAppRel8ns", "clone", "rel8ns", "DEFAULT_UUID_TODO_APP", "getUUID", "classname", "getAppIb", "resNewApp", "APP_REL8N_NAME", "existingLatest", "ibGibPast", "existingLatestPast", "newerAddr", "firstIterationCount", "getPastCount", "otherAddr", "xPast", "newCount", "resNextX", "ibGibPastCount", "existingPastCount", "tagIbGib", "TAG_REL8N_NAME", "getSpaceLockAddr", "space", "scope", "lc", "logalot", "IBGIB_DELIMITER", "spaceId", "ib", "SPACE_LOCK_IB_TERM", "getIbGibAddr", "GIB", "error", "__name", "execInSpaceWithLocking", "secondsValid", "maxDelayMs", "fn", "callerInstanceId", "maxLockAttempts", "resultFn", "lockIbGib", "DEFAULT_MAX_DELAY_MS_RETRY_LOCK_ACQUIRE", "attempts", "DEFAULT_MAX_DELAY_RETRY_LOCK_ACQUIRE_ATTEMPTS", "lockSpace", "delayMs", "delay", "lc2", "unlockSpace", "getValidatedBootstrapIbGib", "zeroSpace", "bootstrapAddr", "BOOTSTRAP_IBGIB_ADDR", "argGet", "getSpaceArgMetadata", "resGetBootstrapIbGib", "bootstrapIbGib", "pretty", "validateBootstrapIbGib", "getLocalSpace", "localSpaceId", "lock", "fnDtoToSpace", "localSpaceCacheSvc", "validatedBootstrapIbGib", "DEFAULT_SECONDS_VALID_LOCAL", "BOOTSTRAP_DATA_DEFAULT_SPACE_ID_KEY", "localSpaceAddr", "fnGet", "resLocalSpace", "localSpaceDto", "localSpace", "instanceId", "resLockIbGib", "spaceLockAddr", "existingLock", "getLock", "getFromSpace", "isExpired", "clone", "gib", "getIbAndGib", "getExpirationUTCString", "argPut", "resPut", "getLockRace", "existingLockRace", "emsg", "resDelete", "deleteFromSpace", "updateBootstrapIbGib", "setSpaceAsDefault", "createIfNotFound", "newSpaceAddr", "existingSpaceAddr", "bootstrapIb", "Factory_V1", "BOOTSTRAP_DATA_KNOWN_SPACE_IDS_KEY", "argPutBootstrap", "resPutBootstrap", "getTimestampInTicks", "getSpaceResultMetadata", "getSpaceIb", "spaceData", "classname", "name", "IBGIB_SPACE_NAME_DEFAULT", "id", "spaceType", "spaceSubtype", "WITNESS_ATOM", "SPACE_ATOM", "isSpaceIb", "parseSpaceIb", "spaceIb", "witnessAtom", "spaceAtom", "spaceClassname", "spaceName", "spaceType_string", "spaceSubtype_string", "VALID_SPACE_TYPES", "VALID_SPACE_SUBTYPES", "getLatestAddrs", "ibGibs", "addrs", "tjps", "tjpAddrs", "space", "lc", "logalot", "addrsToQuery", "ibGib", "getIbGibAddr", "tjpGibs", "x", "getIbAndGib", "ibGibAddr", "gib", "tjpGib", "argGet", "getSpaceArgMetadata", "error", "__name", "throwIfContextIsSpecial", "ibGib_Context", "isSpecial", "trash", "rel8nName_Context", "addr", "zeroSpace", "fnUpdateBootstrap", "fnBroadcast", "contextIsSpecialIbGib", "resNewContext", "rel8", "TRASH_REL8N_NAME", "persistTransformResult", "newSpecialAddr", "specialType", "getSpecialTypeFromIb", "configKey", "getSpecialConfigKey", "setConfigAddr", "registerNewIbGib", "archive", "ARCHIVE_REL8N_NAME", "spaceNameIsValid", "name", "regexOnlyIncluded", "matchOnlyIncluded", "regexStart", "logalot", "constantIbGib", "parentPrimitiveIb", "ib", "ibRegExpPattern", "data", "rel8ns", "lc", "validateIb", "regExp", "IB_REGEXP_DEFAULT", "incomingRel8nNames", "forbiddenRel8nNames", "FORBIDDEN_ADD_RENAME_REMOVE_REL8N_NAMES", "x", "Factory_V1", "getGib", "error", "__name", "getBinHashAndExt", "addr", "parseBinIb", "__name", "lc", "isBinary", "ib", "getIbAndGib", "ibPieces", "error", "ibGib", "getIbGibAddr", "gib", "UUID_REGEXP", "getSpecialIbGibIb", "type", "SPECIAL_IBGIB_TYPE_REGEXP", "__name", "getSpecialTypeFromIb", "ib", "lc", "logalot", "isSpecial", "pieces", "specialType", "SpecialIbGibType", "x", "error", "getSpecialIbGibAddr", "GIB", "getSpecialConfigKey", "CONFIG_KEY_ATOM", "ibGib", "getRootIb", "rootText", "tagTextToIb", "tagText", "splitPerTjpAndOrDna", "ibGibs", "filterPrimitives", "mapWithTjp_YesDna", "mapWithTjp_NoDna", "mapWithoutTjps", "hasTjp", "getTimelinesGroupedByTjp", "mapIbGibsWithTjp", "ibGibsWithTjp", "mapTjpTimelines_Ascending", "groupBy", "getIbGibAddr", "pretty", "_tjpAddr", "timeline", "a", "b", "dnaPrimitives", "GIB_DELIMITER", "getGibInfo", "getTjpAddr", "ibGib", "defaultIfNone", "lc", "tjpMap", "getTjpAddrs", "error", "__name", "ibGibs", "resultMap", "ibGibAddr", "getIbGibAddr", "tjpAddr", "isTjp_Naive", "naive", "logalot", "toDto", "dtoIbGib", "isBinary", "clone", "isIbGib", "obj", "getTimestampInfo", "data", "timestamp", "ms", "emsg", "parsedTimestamp", "date", "INVALID_DATE_STRING", "extractErrorMsg", "GLOBAL_LOG_A_LOT", "BLANK_GIB_DB_NAME", "ARMY_STORE", "BEE_KEY", "BLANK_GIB_INDEXEDDB_LOCAL_SPACE_NAME_PREFIX", "APP_CONFIG", "BLANK_GIB_DB_NAME", "ARMY_STORE", "BEE_KEY", "ZERO_SPACE_ID", "CONFIG_OPTION_GEMINI_API_KEY_LOCATION_HELP", "KEY_TUTORIAL_PANELS_EXPAND_ANIMATION_COUNT", "TUTORIAL_PANELS_EXPAND_ANIMATION_COUNT_ENOUGH_ALREADY", "HTML_META_APP_ID_NAME", "HTML_META_APP_ID_CONTENT", "TAG_AGENT_TEXT", "TAG_AGENT_ICON", "TAG_AGENT_DESCRIPTION", "TAG_AGENT_IB", "tagTextToIb", "HARDCODED_PROMPT_TAG_TEXT", "logalot", "uint8ArrayToBase64", "uint8Array", "resolve", "reject", "blob", "reader", "base64String", "error", "__name", "base64ToUint8Array", "dataUrl", "buffer", "serializeGraphToString", "graph", "lc", "serializableGraph", "key", "jsonString", "extractErrorMsg", "deserializeStringToGraph", "parsedGraph", "value", "data", "compressIbGibToBlob", "dataToCompress", "compressedStream", "decompressIbGibFromBlob", "compressedBlob", "decompressedStream", "compressIbGibGraphToString", "decompressIbGibGraphFromString", "compressedBase64", "compressedUint8Array", "RAW_EXPORT_ATOM", "logalot", "getRawExportIb", "data", "lc", "graphSize", "dependencyGraphAsString", "timestamp", "graphStringLength", "timestampInTicks", "getTimestampInTicks", "compressDescription", "date", "ib", "gib", "getIbAndGib", "tjpGib", "getGibInfo", "dateString", "RAW_EXPORT_ATOM", "error", "extractErrorMsg", "__name", "getRawExportIbGib", "ibGib", "metaspace", "space", "compress", "live", "ignoreErrors", "lc", "logalot", "ibGibAddr", "getIbGibAddr", "errorInfos", "validationErrors", "validateIbGibIntrinsically", "errorMsg", "resGraph", "dependencyGraphAsString", "compressIbGibGraphToString", "serializeGraphToString", "tjpAddr", "getTjpAddr", "now", "exportData", "getTimestamp", "exportIbGib", "getRawExportIb", "exportGib", "getGib", "error", "extractErrorMsg", "__name", "GLOBAL_LOG_A_LOT", "GLOBAL_TIMER_NAME", "GLOBAL_THIS_IBGIB_KEY", "GEMINI_API_KEY_REGEXP", "CONFIG_OPTION_GEMINI_API_KEY_LOCATION_HELP", "TAG_AGENT_TEXT", "TAG_AGENT_ICON", "TAG_AGENT_DESCRIPTION", "TAG_AGENT_IB", "tagTextToIb", "DEFAULT_IBGIB_COLOR", "DEFAULT_IBGIB_TRANSLUCENT", "DEFAULT_IBGIB_COLOR_CONTRAST", "HARDCODED_PROMPT_TAG_TEXT", "logalot", "GLOBAL_LOG_A_LOT", "initRequestCount", "askForPersistStorage", "lc", "_unusedtesting", "persisted", "error", "extractErrorMsg", "__name", "initializeStorage", "dbName", "storeName", "version", "uuid", "db", "resolve", "reject", "openDBRequest", "storeAlreadyExisted", "event", "ev", "storageGetDBInfo", "x", "storageCreateStoreIfNotExist", "storeExists", "dbInfo", "newVersion", "storagePut", "key", "value", "store", "data", "storageGet", "getRequest", "uint8ArrayToString", "storageDBExists", "storageRmRF", "pathToRm", "logalotInitDebug", "objectStore", "range", "openCursorRequest", "rmCount", "cursor", "deleteRequest", "storageReaddir", "dirPath", "withFileTypes", "normalizedDirPath", "entries", "dirents", "relativePath", "childSegment", "isDirectory", "VALID_CSS_VARIABLES", "UI_THEME_INFO_KEY", "logalot", "GLOBAL_LOG_A_LOT", "showFullscreenDialog", "opts", "lc", "dialog", "dialogBody", "titleElement", "messageElement", "promptInput", "okButton", "cancelButton", "child", "line", "pLine", "onKeypress", "__name", "ev", "resolve", "removeEventListeners", "onOK", "onCancel", "onClose", "result", "delay", "error", "extractErrorMsg", "getExistingUIInfo", "dbName", "storeName", "key", "UI_THEME_INFO_KEY", "existingUIInfo", "existingUIInfoAsString", "storageGet", "logalot", "GLOBAL_LOG_A_LOT", "getTagsIbGib", "metaspace", "space", "lc", "tagsIbGib", "SpecialIbGibType", "error", "extractErrorMsg", "__name", "getIndexNameFromIbGib", "scope", "ibGib", "ibGibAddr", "defaultNameIfError", "primitiveAncestorIb", "atom", "ancestorIbOrAtom", "getIbGibAddr", "primitiveAncestorAddrs", "x", "isPrimitive", "getIbAndGib", "primitiveAncestorAddr", "ib", "indexName", "getLocalCoupledIbGibForDomainIbGib", "skipGetLatest", "indexSpecialIbGibType", "domainTjpAddr", "getTjpAddr", "fn", "specialIndex", "coupledAddr", "addrToGet", "resGet", "execInSpaceWithLocking", "getTimestampInTicks", "coupleDomainIbGibWithLocalIbGibViaIndex", "domainIbGib", "localIbGib", "localAddr", "agentSpecialIndex", "map", "coupleMap", "clone", "existingMappedAgentAddr", "resNewSpecial", "mut8", "Rel8n", "newSpecialIbGib", "persistTransformResult", "configKey", "getSpecialConfigKey", "debounce", "func", "wait", "immediate", "timeout", "args", "context", "later", "callNow", "getMaskedSecret", "secret", "countToShow", "insertAt", "newItems", "index", "targetArray", "arrayCopy", "deleteAt", "getShortenedStringWithEllipsis", "str", "maxChars", "getIbGibGlobalThis_IbGib", "lc", "logalot", "result", "GLOBAL_THIS_IBGIB_KEY", "error", "extractErrorMsg", "__name", "getGlobalMetaspace_waitIfNeeded", "delayIntervalMs", "metaspace", "delay", "getDeterministicColorInfo", "ibGibAddr", "gib", "ibGib", "translucentAlpha", "GIB", "getIbAndGib", "gibInfo", "getGibInfo", "drivingHash", "DEFAULT_IBGIB_COLOR", "DEFAULT_IBGIB_TRANSLUCENT", "DEFAULT_IBGIB_COLOR_CONTRAST", "punctiliarColor", "punctiliarColorTranslucent", "punctiliarColorContrast", "getColorStrings", "tjpColor", "tjpColorTranslucent", "tjpColorContrast", "errorMsg", "getContrastColor", "hexcolor", "c", "r", "g", "b", "yiq", "alphaStr", "color", "colorTranslucent", "colorContrast", "logalot", "GLOBAL_LOG_A_LOT", "uint8ArrayToString", "array", "__name", "PathUtilsHelper", "_PathUtilsHelper", "path", "paths", "lc", "joined", "i", "ext", "copyToClipboard", "data", "logalot", "title", "text", "url", "textToCopy", "error", "extractErrorMsg", "isExecutingInBlankGibWebAppProper", "metaName_appId", "metaContent_appId", "metaElement", "__name", "promptForText", "msg", "title", "confirm", "noNewLine", "rl", "defaultValue", "dontCloseRl", "cancelable", "lc", "result", "attempts", "maxAttempts", "delay", "showFullscreenDialog", "error", "extractErrorMsg", "promptForSecret", "logalot", "firstTry", "result2", "promptForConfirm", "yesLabel", "noLabel", "alertUser", "skipHitEnterToContinue", "getUserPreferredColorScheme", "highlightElement", "el", "magicHighlightTimingMs", "scrollIntoView", "lc", "logalot", "delay", "error", "extractErrorMsg", "__name", "unhighlightElement", "getRawExportIbGibAndGraphFromJsonString", "exportIbGibJsonString", "metaspace", "parsedIbGib_notYetValidated", "parsedExportIbGib_dependenciesNotValidated", "emsg", "errorHack", "validationErrors", "validateIbGibIntrinsically", "payloadGraph", "decompressIbGibGraphFromString", "deserializeStringToGraph", "validationErrorMap", "addr", "payloadIbGib", "pretty", "exportIbGib", "ibGib", "compress", "space", "isPrimitive", "resGetExport", "getRawExportIbGib", "exportErrors", "exportIbGibAsString", "dataStr", "filename", "getIbGibAddr", "downloadAnchorEl", "div", "promptForAPIKey", "msg", "resAPIKey", "tryAgain", "attempts", "maxAttempts", "promptForSecret", "GEMINI_API_KEY_REGEXP", "alertUser", "updateAPIKeyInStorage", "dbName", "storeName", "key", "apiKey", "force", "storagePut", "CONFIG_OPTION_GEMINI_API_KEY_LOCATION_HELP", "getElementById_throwsIfFalsy", "id", "shadowRoot", "resElement", "document_getElementById", "shadowRoot_getElementById", "getGlobalStoreName", "hackGlobal", "getIbGibGlobalThis_IbGib", "getGlobalDbName", "getGlobalIndexedDbKey_APIKey", "initAppStorage", "infos", "info", "storeNames", "storageDBExists", "initializeStorage", "storageCreateStoreIfNotExist", "logalot", "GLOBAL_LOG_A_LOT", "IbGibComponentService", "_IbGibComponentService", "__name", "lc", "error", "extractErrorMsg", "componentMeta", "c", "useRegExpPrefilter", "path", "ibGibAddr", "componentToInject", "registeredComponents", "componentSvc", "possibleComponentsMeta", "component", "componentMatchesPath", "parentEl", "getComponentSvc", "ROUTER_APP_NAME_WEB1", "ROUTER_APP_NAME_PROJECTS", "ROUTER_APP_NAME_TAGS", "RouterAppName", "VALID_ROUTER_APP_NAMES", "isValidRouterAppName", "str", "__name", "WEB1_FILENAME_HOME", "WEB1_FILENAME_ABOUT", "WEB1_FILENAME_FUNDING", "WEB1_FILENAME_LINKS", "WEB1_FILENAMES", "VALID_WEB1_FILENAMES", "ID_APP_SHELL", "ID_HEADER_PANEL", "ID_HEADER_PANEL_CONTENT", "ID_IBGIB_COM_TITLE_LINK", "ID_PANEL_CONTAINER", "ID_LEFT_PANEL", "ID_LEFT_PANEL_HEADER", "ID_LEFT_PANEL_CONTENT", "ID_LEFT_PANEL_FOOTER", "ID_LEFT_PANEL_COLLAPSE_HANDLE", "ID_LEFT_PANEL_EXPAND_HANDLE", "ID_LEFT_PANEL_MAXIMIZE_HANDLE", "ID_WEB10_TAB_CONTENT", "ID_WEB10_TAB_BUTTON", "ID_WEB_1_NAV", "ID_TAG_NAV", "ID_PROJECT_EXPLORER_TAB_CONTENT", "ID_PROJECT_EXPLORER_TAB_BUTTON", "ID_CENTER_PANEL_CONTENT", "ID_RIGHT_PANEL", "ID_RIGHT_PANEL_HEADER", "ID_RIGHT_PANEL_CONTENT", "ID_RIGHT_PANEL_FOOTER", "ID_RIGHT_PANEL_COLLAPSE_HANDLE", "ID_RIGHT_PANEL_EXPAND_HANDLE", "ID_RIGHT_PANEL_MAXIMIZE_HANDLE", "ID_TAB_BUTTON_CHRONOLOGYS", "ID_CHRONOLOGYS_CONTENT", "ID_FOOTER_PANEL", "ID_FOOTER_INPUT_CONTAINER", "ID_FOOTER_PANEL_COLLAPSE_HANDLE", "ID_FOOTER_PANEL_EXPAND_HANDLE", "ID_FOOTER_PANEL_MAXIMIZE_HANDLE", "ID_PRIMARY_AGENT_CHAT_LOG", "canvas_default", "canvas_default", "styles_default", "root_default", "logalot", "getDependencyGraph", "ibGib", "ibGibs", "ibGibAddr", "ibGibAddrs", "live", "gotten", "tjpAddrsAlreadyAnalyzed", "skipAddrs", "skipRel8nNames", "onlyRel8nNames", "maxRetries", "msBetweenRetries", "space", "timeLogName", "mapTjpAddrToLatestAddrsInSpace", "lc", "graph", "getGraphProjection", "ibs", "unique", "ib", "error", "__name", "getGraphProjection_initializeOpts", "x", "isPrimitive", "getIbAndGib", "getIbGibAddr", "getGraphProjection_getIbGibsInIbGibAddrs", "resIbGibs", "addrsToGetFromSpace", "gottenAddrs", "incomingIbGibAddrs", "i", "addr", "addrsToGet", "retryCount", "delay", "resGetThese", "getFromSpace", "gottenIbGibs", "opts", "supplementalIbGibs", "commentIbs", "getGraphProjection_Live", "getGraphProjection_NonLive", "getGraphProjection_Live", "ibGibs", "ibGibAddrs", "gotten", "tjpAddrsAlreadyAnalyzed", "mapTjpAddrToLatestAddrsInSpace", "skipAddrs", "skipRel8nNames", "onlyRel8nNames", "maxRetries", "msBetweenRetries", "space", "timeLogName", "lc", "allIbGibsSoFar", "x", "getIbGibAddr", "allKnownTimelinesAtThisPoint", "getTimelinesGroupedByTjp", "logalot", "timelinesNotAnalyzed", "tjpAddr", "pretty", "mapTjpAddrToLatestIbGibInTimelineThatWeHaventAlreadyAnalyzed", "mapLatestAddrAlreadyGottenToTjpAddr", "timeline", "latestIbGibAlreadyGotten", "latestAddrAlreadyGotten", "countOfTimelinesNotYetGotten", "latestAddrsMap", "latestIbGibCorrespondingToTjpAddr", "latestAddrCorrespondingToTjpAddr", "ibGibsToQueryLatestAddrs", "queriedLatestAddrsMap", "resLatestAddrsMapInEntireSpace", "getLatestAddrs", "newerAddrsFound", "newerAddrFoundToTjpAddrMap", "latestAddrInSpace", "rel8dAddrsNotYetGotten", "i", "rel8ns", "rel8nName", "rel8dAddr", "unique", "getGraphProjection", "addr", "y", "error", "emsg", "__name", "getGraphProjection_NonLive", "addrsWeDontHaveAlready_Rel8dAddrs", "ibGib", "ibGibAddr", "gib", "getIbAndGib", "GIB", "invalidAddrs", "rel8nNames", "gottenKeys", "rel8dAddrs", "falsyAddrs", "IBGIB_DELIMITER", "validationErrors", "validateIbGibAddr", "resGet", "getFromSpace", "result", "logalot", "getLockScope", "timeline", "lc", "isPrimitive", "getIbGibAddr", "gibInfo", "getGibInfo", "tjpGib", "error", "extractErrorMsg", "__name", "appendToTimeline", "timeline", "rel8nInfos", "rel8nRemovalInfos", "timelineIndexInfo", "metaspace", "space", "skipLock", "noDna", "lc", "logalot", "lockScope", "getLockScope", "fn", "__name", "timelineAddr", "getIbGibAddr", "latestTimelineIbGibAddr", "latestTimelineIbGibDto", "toDto", "resGetLatest", "rel8nsToRemoveByAddr", "rel8nRemovalInfo", "rel8nName", "ibGibAddrs", "rel8nsToAddByAddr", "rel8nInfo", "ibGibs", "ibGib", "resRel8", "rel8", "newTimelineIbGib", "updateSpecialIndex", "execInSpaceWithLocking", "getTimestampInTicks", "error", "extractErrorMsg", "type", "dataToAddOrPatch", "fnGetSpecialIndex", "specialIndex", "existingSpecialIndexRel8ns", "addrsToUnRel8", "existingAddrsThisRel8nName", "toUnrel8ThisRel8nName_Set", "addr", "pastAddrs", "x", "resNewSpecial", "mut8", "Rel8n", "newSpecialIbGib", "persistTransformResult", "configKey", "getSpecialConfigKey", "getLatestTimelineIbGibDto_nonLocking", "mut8Timeline", "mut8Opts", "resGet", "resMut8", "COMMENT_IB_WHITESPACE_ONLY_TEXT", "logalot", "getCommentIb", "commentText", "addlMetadataText", "lc", "ibCommentText", "getSaferSubstring", "ibCommentMetadata", "error", "__name", "parseCommentIb", "ib", "_", "safeIbCommentText", "safeIbCommentMetadataText", "createCommentIbGib", "text", "saveInSpace", "space", "dontTrimText", "data", "getTimestamp", "opts", "Factory_V1", "COMMENT_IB_WHITESPACE_ONLY_TEXT", "pretty", "resCommentIbGib", "persistTransformResult", "isComment", "ibGib", "rel8ns", "ancestors", "AGENT_ATOM", "AGENT_NAME_REGEXP", "AGENT_DESC_REGEXP", "DEFAULT_UUID_AGENT", "DEFAULT_NAME_AGENT", "DEFAULT_DESCRIPTION_AGENT", "FUNCTION_CALL_REQUEST_COMMENT_TAG", "AGENT_REL8N_NAME", "GEMINI_SCHEMA_AGENT_ID", "GEMINI_SCHEMA_AGENT_TYPE", "TEXT_SOURCE_HARDCODED", "TEXT_SOURCE_HUMAN", "TEXT_SOURCE_AI", "TEXT_SOURCE_FUNCTION", "TEXT_SOURCE_UNKNOWN", "TextSource", "TEXT_SOURCE_VALUES", "isTextSource", "str", "__name", "GEMINI_SCHEMA_AGENTS_SELF_IDENTIFIED_NAME", "AGENT_NAME_REGEXP", "AGENT_SPECIAL_IBGIB_TYPE_PRIMARYAGENT", "COMMAND_BASE_SCHEMA_PROPERTIES", "GEMINI_SCHEMA_AGENT_ID", "GEMINI_SCHEMA_AGENTS_SELF_IDENTIFIED_NAME", "logalot", "GLOBAL_LOG_A_LOT", "AllFunctionInfos", "DeprecatedFunctionInfoNames", "getAllFunctionInfos", "lc", "error", "extractErrorMsg", "__name", "getDeprecatedFunctionInfoNames", "registerDeprecatedFunctionInfoName", "nameOrId", "registerFunctionInfos", "functionInfos", "functionInfo", "CommandService_V1", "_CommandService_V1", "__name", "enqueuedCommand", "lc", "result", "error", "cmdData", "anonApiFn", "functionInfo", "getAllFunctionInfos", "x", "info", "modifier", "pretty", "args", "errorMsg", "extractErrorMsg", "globalCommandService", "getCommandService", "FUNCTION_CALL_EXAMPLES_HEADER", "logalot", "rel8ToTag", "ibGib", "addr", "tagIbGib", "metaspace", "space", "lc", "getIbGibAddr", "latestTagAddr", "resGetLatestTag", "rel8nsToAddByAddr", "TAG_TARGET_REL8N_NAME", "resRel8ToTag", "rel8", "newTagIbGib", "error", "extractErrorMsg", "__name", "logalot", "GLOBAL_LOG_A_LOT", "AgentsService_V1", "_AgentsService_V1", "__name", "opts", "lc", "agentId", "agentType", "spaceId", "agent", "metaspace", "getGlobalMetaspace_waitIfNeeded", "getAgents", "x", "pretty", "error", "extractErrorMsg", "throwIfNewerFound", "existing", "toDto", "msg", "id", "classname", "fnDtoToAgentWitness", "dto", "fn", "res", "fnClassnames", "fnClassname", "agentAddr", "agentIb", "getIbAndGib", "parseAgentIb", "resAgent", "space", "resGet", "agentIbGib", "agentWitness", "arg", "superSpace", "name", "availableFunctions", "initialSystemText", "initialChatText", "fnGetAPIKey", "addToAgentsTag", "type", "agentFactory", "getConcreteAgentFactory", "data", "newSubSpace", "rel8ns", "resFirstGen", "Factory_V1", "getAgentIb", "AGENT_ATOM", "agentsTagIbGib", "getTag_Agents", "_newAgentsTagIbGib", "rel8ToTag", "updateSpecialIndex", "AGENT_REL8N_NAME", "textsToAdd", "taggifyForPrompt", "HARDCODED_PROMPT_TAG_TEXT", "_agentsSvcInstance", "getAgentsSvc", "GEMINI_MODEL_GEMINI_3_1_PRO_PREVIEW", "GEMINI_MODEL_GEMINI_3_FLASH_PREVIEW", "GEMINI_MODEL_GEMINI_3_1_FLASH_LITE_PREVIEW", "GEMINI_MODEL_GEMINI_3_1_FLASH_LIVE_PREVIEW", "GEMINI_MODEL_GEMINI_2_5_PRO", "GEMINI_MODEL_GEMINI_2_5_FLASH", "GEMINI_MODEL_GEMINI_2_5_FLASH_LITE", "GEMINI_MODEL_GEMINI_2_5_FLASH_PREVIEW_TTS", "GEMINI_MODEL_GEMINI_2_0_FLASH", "GEMINI_MODEL_GEMINI_2_0_FLASH_LITE", "GeminiModel", "GEMINI_MODEL_VALUES", "GEMINI_DEFAULT_MODEL_STR", "GeminiModel", "GEMINI_BACKUP_MODEL_STR", "GEMINI_MAX_TRY_COUNT", "DEFAULT_AGENT_DATA_V1", "DEFAULT_UUID_AGENT", "DEFAULT_NAME_AGENT", "DEFAULT_DESCRIPTION_AGENT", "GEMINI_DEFAULT_MODEL_STR", "AGENT_SPECIAL_IBGIB_TYPE_PRIMARYAGENT", "ROOT_ADDR", "DEFAULT_AGENT_REL8NS_V1", "_defaultBaseGeminiUrl", "_defaultBaseVertexUrl", "getDefaultBaseUrls", "_defaultBaseGeminiUrl", "_defaultBaseVertexUrl", "__name", "getBaseUrl", "httpOptions", "vertexai", "vertexBaseUrlFromEnv", "geminiBaseUrlFromEnv", "defaultBaseUrls", "_a", "_b", "BaseModule", "formatMap", "templateString", "valueMap", "regex", "match", "key", "value", "setValueByPath", "data", "keys", "keyName", "arrayData", "j", "entry", "d", "keyToSet", "existingData", "getValueByPath", "defaultValue", "i", "error", "moveValueByPath", "paths", "sourcePath", "destPath", "sourceKeys", "destKeys", "excludeKeys", "wildcardIdx", "_moveValueRecursive", "keyIdx", "dataRecord", "item", "keysToMove", "k", "valuesToMove", "v", "newDestKeys", "dk", "tBytes", "fromBytes", "fetchPredictOperationParametersToVertex", "fromObject", "toObject", "fromOperationName", "common.getValueByPath", "common.setValueByPath", "fromResourceName", "generateVideosOperationFromMldev", "fromName", "fromMetadata", "fromDone", "fromError", "fromResponse", "generateVideosResponseFromMldev", "generateVideosOperationFromVertex", "generateVideosResponseFromVertex", "fromGeneratedVideos", "transformedList", "generatedVideoFromMldev", "fromRaiMediaFilteredCount", "fromRaiMediaFilteredReasons", "generatedVideoFromVertex", "fromVideo", "videoFromMldev", "videoFromVertex", "getOperationParametersToMldev", "getOperationParametersToVertex", "importFileOperationFromMldev", "importFileResponseFromMldev", "fromSdkHttpResponse", "fromParent", "fromDocumentName", "uploadToFileSearchStoreOperationFromMldev", "uploadToFileSearchStoreResponseFromMldev", "fromUri", "fromVideoBytes", "t.tBytes", "fromMimeType", "Outcome", "Language", "FunctionResponseScheduling", "Type", "Mode", "ApiSpec", "AuthType", "HttpElementLocation", "PhishBlockThreshold", "ThinkingLevel", "HarmCategory", "HarmBlockMethod", "HarmBlockThreshold", "FinishReason", "HarmProbability", "HarmSeverity", "UrlRetrievalStatus", "BlockedReason", "TrafficType", "Modality", "MediaResolution", "TuningMode", "AdapterSize", "JobState", "TuningTask", "PartMediaResolutionLevel", "FeatureSelectionPreference", "Behavior", "DynamicRetrievalConfigMode", "Environment", "FunctionCallingConfigMode", "SafetyFilterLevel", "PersonGeneration", "ImagePromptLanguage", "MaskReferenceMode", "ControlReferenceType", "SubjectReferenceType", "EditMode", "SegmentMode", "VideoGenerationReferenceType", "VideoGenerationMaskMode", "VideoCompressionQuality", "TuningMethod", "DocumentState", "FileState", "FileSource", "TurnCompleteReason", "MediaModality", "VadSignalType", "StartSensitivity", "EndSensitivity", "ActivityHandling", "TurnCoverage", "Scale", "MusicGenerationMode", "LiveMusicPlaybackControl", "HttpResponse", "__name", "response", "headers", "pair", "GenerateContentResponse", "__name", "_d", "_c", "_b", "_a", "text", "anyTextPartText", "nonTextParts", "part", "_h", "_g", "_f", "_e", "fieldName", "fieldValue", "data", "nonDataParts", "functionCalls", "functionCall", "executableCode", "_j", "codeExecutionResult", "EmbedContentResponse", "GenerateImagesResponse", "EditImageResponse", "UpscaleImageResponse", "RecontextImageResponse", "SegmentImageResponse", "ListModelsResponse", "DeleteModelResponse", "CountTokensResponse", "ComputeTokensResponse", "GenerateVideosOperation", "_GenerateVideosOperation", "__name", "apiResponse", "_isVertexAI", "operation", "response", "op", "generateVideosOperationFromVertex", "generateVideosOperationFromMldev", "ListTuningJobsResponse", "CancelTuningJobResponse", "DeleteCachedContentResponse", "ListCachedContentsResponse", "ListDocumentsResponse", "ListFileSearchStoresResponse", "UploadToFileSearchStoreResumableResponse", "ImportFileOperation", "_ImportFileOperation", "__name", "apiResponse", "_isVertexAI", "operation", "response", "importFileOperationFromMldev", "ListFilesResponse", "CreateFileResponse", "DeleteFileResponse", "ListBatchJobsResponse", "__name", "LiveServerMessage", "__name", "text", "anyTextPartFound", "nonTextParts", "part", "_c", "_b", "_a", "fieldName", "fieldValue", "data", "nonDataParts", "LiveMusicServerMessage", "__name", "UploadToFileSearchStoreOperation", "_UploadToFileSearchStoreOperation", "__name", "apiResponse", "_isVertexAI", "operation", "response", "uploadToFileSearchStoreOperationFromMldev", "tModel", "apiClient", "model", "parts", "tCachesModel", "transformedModel", "tBlobs", "blobs", "blob", "tBlob", "tImageBlob", "transformedBlob", "tAudioBlob", "tPart", "origin", "tParts", "item", "_isContent", "_isFunctionCallPart", "_isFunctionResponsePart", "tContent", "tContentsForEmbed", "content", "tContents", "result", "accumulatedParts", "isContentArray", "isContent", "flattenTypeArrayToAnyOf", "typeList", "resultingSchema", "listWithoutNull", "type", "types.Type", "i", "processJsonSchema", "_jsonSchema", "genAISchema", "schemaFieldNames", "listSchemaFieldNames", "dictSchemaFieldNames", "incomingAnyOf", "fieldName", "fieldValue", "listSchemaFieldValue", "dictSchemaFieldValue", "key", "value", "tSchema", "schema", "tSpeechConfig", "speechConfig", "tLiveSpeechConfig", "tTool", "tool", "functionDeclaration", "tTools", "tools", "resourceName", "client", "resourcePrefix", "splitsAfterPrefix", "shouldAppendPrefix", "tCachedContentName", "name", "tTuningJobStatus", "status", "tBytes", "fromImageBytes", "baseTransformers.tBytes", "_isFile", "isGeneratedVideo", "isVideo", "tFileName", "fromName", "_a", "match", "tModelsUrl", "baseModels", "res", "tExtractModels", "hasField", "data", "mcpToGeminiTool", "mcpTool", "config", "mcpToolSchema", "mcpToolsToGeminiTool", "mcpTools", "functionDeclarations", "toolNames", "mcpToolName", "geminiTool", "tBatchJobSource", "src", "sourceObj", "vertexSourcesCount", "mldevSourcesCount", "tBatchJobDestination", "dest", "destString", "tRecvBatchJobDestination", "obj", "inlineResponsesVal", "responsesArray", "hasEmbedding", "responseItem", "responseVal", "tBatchJobName", "nameString", "tJobState", "state", "stateString", "batchJobDestinationFromMldev", "fromObject", "toObject", "fromFileName", "common.getValueByPath", "common.setValueByPath", "fromInlinedResponses", "transformedList", "inlinedResponseFromMldev", "fromInlinedEmbedContentResponses", "batchJobDestinationFromVertex", "fromFormat", "fromGcsUri", "fromBigqueryUri", "batchJobDestinationToVertex", "batchJobFromMldev", "fromDisplayName", "fromState", "t.tJobState", "fromCreateTime", "fromEndTime", "fromUpdateTime", "fromModel", "fromDest", "t.tRecvBatchJobDestination", "batchJobFromVertex", "fromError", "fromStartTime", "fromSrc", "batchJobSourceFromVertex", "fromCompletionStats", "batchJobSourceToMldev", "fromInlinedRequests", "inlinedRequestToMldev", "batchJobSourceToVertex", "blobToMldev", "fromData", "fromMimeType", "cancelBatchJobParametersToMldev", "t.tBatchJobName", "cancelBatchJobParametersToVertex", "candidateFromMldev", "fromContent", "fromCitationMetadata", "citationMetadataFromMldev", "fromTokenCount", "fromFinishReason", "fromAvgLogprobs", "fromGroundingMetadata", "fromIndex", "fromLogprobsResult", "fromSafetyRatings", "fromUrlContextMetadata", "fromCitations", "contentToMldev", "fromParts", "partToMldev", "fromRole", "createBatchJobConfigToMldev", "parentObject", "createBatchJobConfigToVertex", "t.tBatchJobDestination", "createBatchJobParametersToMldev", "t.tModel", "t.tBatchJobSource", "fromConfig", "createBatchJobParametersToVertex", "createEmbeddingsBatchJobConfigToMldev", "createEmbeddingsBatchJobParametersToMldev", "embeddingsBatchJobSourceToMldev", "deleteBatchJobParametersToMldev", "deleteBatchJobParametersToVertex", "deleteResourceJobFromMldev", "fromSdkHttpResponse", "fromDone", "deleteResourceJobFromVertex", "embedContentBatchToMldev", "fromContents", "t.tContentsForEmbed", "embedContentConfigToMldev", "common.moveValueByPath", "fromTaskType", "fromTitle", "fromOutputDimensionality", "fileDataToMldev", "fromFileUri", "functionCallToMldev", "fromId", "fromArgs", "functionCallingConfigToMldev", "fromMode", "fromAllowedFunctionNames", "generateContentConfigToMldev", "fromSystemInstruction", "t.tContent", "fromTemperature", "fromTopP", "fromTopK", "fromCandidateCount", "fromMaxOutputTokens", "fromStopSequences", "fromResponseLogprobs", "fromLogprobs", "fromPresencePenalty", "fromFrequencyPenalty", "fromSeed", "fromResponseMimeType", "fromResponseSchema", "t.tSchema", "fromResponseJsonSchema", "fromSafetySettings", "safetySettingToMldev", "fromTools", "t.tTools", "toolToMldev", "t.tTool", "fromToolConfig", "toolConfigToMldev", "fromCachedContent", "t.tCachedContentName", "fromResponseModalities", "fromMediaResolution", "fromSpeechConfig", "t.tSpeechConfig", "fromThinkingConfig", "fromImageConfig", "imageConfigToMldev", "fromEnableEnhancedCivicAnswers", "generateContentResponseFromMldev", "fromCandidates", "fromModelVersion", "fromPromptFeedback", "fromResponseId", "fromUsageMetadata", "getBatchJobParametersToMldev", "getBatchJobParametersToVertex", "googleMapsToMldev", "fromEnableWidget", "googleSearchToMldev", "fromTimeRangeFilter", "fromAspectRatio", "fromImageSize", "t.tContents", "fromMetadata", "fromResponse", "listBatchJobsConfigToMldev", "fromPageSize", "fromPageToken", "listBatchJobsConfigToVertex", "fromFilter", "listBatchJobsParametersToMldev", "listBatchJobsParametersToVertex", "listBatchJobsResponseFromMldev", "fromNextPageToken", "fromBatchJobs", "listBatchJobsResponseFromVertex", "fromCodeExecutionResult", "fromExecutableCode", "fromFileData", "fromFunctionCall", "fromFunctionResponse", "fromInlineData", "fromText", "fromThought", "fromThoughtSignature", "fromVideoMetadata", "fromCategory", "fromThreshold", "fromFunctionCallingConfig", "fromRetrievalConfig", "fromFunctionDeclarations", "fromGoogleSearchRetrieval", "fromComputerUse", "fromFileSearch", "fromCodeExecution", "fromGoogleMaps", "fromGoogleSearch", "fromUrlContext", "PagedItem", "Pager", "request", "params", "requestParams", "_b", "index", "Batches", "BaseModule", "x", "body", "converters.createBatchJobParametersToMldev", "urlParams", "path", "common.formatMap", "requestsWrapper", "requests", "newRequests", "requestDict", "systemInstructionValue", "requestContent", "newConfig", "timestampStr", "gcsUri", "bigqueryUri", "queryParams", "converters.createBatchJobParametersToVertex", "httpResponse", "converters.batchJobFromVertex", "_c", "_d", "converters.batchJobFromMldev", "converters.createEmbeddingsBatchJobParametersToMldev", "converters.getBatchJobParametersToVertex", "converters.getBatchJobParametersToMldev", "converters.cancelBatchJobParametersToVertex", "converters.cancelBatchJobParametersToMldev", "converters.listBatchJobsParametersToVertex", "jsonResponse", "resp", "converters.listBatchJobsResponseFromVertex", "typedResp", "types.ListBatchJobsResponse", "converters.listBatchJobsParametersToMldev", "converters.listBatchJobsResponseFromMldev", "converters.deleteBatchJobParametersToVertex", "converters.deleteResourceJobFromVertex", "converters.deleteBatchJobParametersToMldev", "converters.deleteResourceJobFromMldev", "createCachedContentConfigToMldev", "fromTtl", "fromExpireTime", "createCachedContentConfigToVertex", "toolToVertex", "fromKmsKeyName", "createCachedContentParametersToMldev", "t.tCachesModel", "createCachedContentParametersToVertex", "deleteCachedContentParametersToMldev", "deleteCachedContentParametersToVertex", "deleteCachedContentResponseFromMldev", "deleteCachedContentResponseFromVertex", "functionDeclarationToVertex", "fromDescription", "fromParameters", "fromParametersJsonSchema", "getCachedContentParametersToMldev", "getCachedContentParametersToVertex", "listCachedContentsConfigToMldev", "listCachedContentsConfigToVertex", "listCachedContentsParametersToMldev", "listCachedContentsParametersToVertex", "listCachedContentsResponseFromMldev", "fromCachedContents", "listCachedContentsResponseFromVertex", "fromRetrieval", "fromEnterpriseWebSearch", "updateCachedContentConfigToMldev", "updateCachedContentConfigToVertex", "updateCachedContentParametersToMldev", "updateCachedContentParametersToVertex", "Caches", "converters.createCachedContentParametersToVertex", "converters.createCachedContentParametersToMldev", "converters.getCachedContentParametersToVertex", "converters.getCachedContentParametersToMldev", "converters.deleteCachedContentParametersToVertex", "converters.deleteCachedContentResponseFromVertex", "types.DeleteCachedContentResponse", "converters.deleteCachedContentParametersToMldev", "converters.deleteCachedContentResponseFromMldev", "converters.updateCachedContentParametersToVertex", "converters.updateCachedContentParametersToMldev", "converters.listCachedContentsParametersToVertex", "converters.listCachedContentsResponseFromVertex", "types.ListCachedContentsResponse", "converters.listCachedContentsParametersToMldev", "converters.listCachedContentsResponseFromMldev", "isValidResponse", "response", "content", "_a", "isValidContent", "__name", "part", "validateHistory", "history", "extractCuratedHistory", "comprehensiveHistory", "curatedHistory", "length", "i", "modelOutput", "isValid", "Chats", "modelsModule", "apiClient", "params", "Chat", "model", "config", "inputContent", "t.tContent", "responsePromise", "outputContent", "_b", "fullAutomaticFunctionCallingHistory", "index", "automaticFunctionCallingHistory", "_c", "streamResponse", "curated", "_f", "streamResponse_1", "__asyncValues", "streamResponse_1_1", "__await", "chunk", "_e", "_d", "userInput", "outputContents", "ApiError", "_ApiError", "options", "createFileParametersToMldev", "fromObject", "toObject", "fromFile", "common.getValueByPath", "common.setValueByPath", "createFileResponseFromMldev", "fromSdkHttpResponse", "deleteFileParametersToMldev", "fromName", "t.tFileName", "deleteFileResponseFromMldev", "getFileParametersToMldev", "listFilesConfigToMldev", "parentObject", "fromPageSize", "fromPageToken", "listFilesParametersToMldev", "fromConfig", "listFilesResponseFromMldev", "fromNextPageToken", "fromFiles", "transformedList", "item", "Files", "BaseModule", "Pager", "PagedItem", "x", "resp", "path", "queryParams", "body", "converters.listFilesParametersToMldev", "common.formatMap", "httpResponse", "jsonResponse", "apiResponse", "converters.listFilesResponseFromMldev", "typedResp", "types.ListFilesResponse", "converters.createFileParametersToMldev", "converters.createFileResponseFromMldev", "types.CreateFileResponse", "converters.getFileParametersToMldev", "converters.deleteFileParametersToMldev", "converters.deleteFileResponseFromMldev", "types.DeleteFileResponse", "blobToMldev", "fromData", "fromMimeType", "contentToMldev", "fromParts", "partToMldev", "fromRole", "fileDataToMldev", "fromFileUri", "functionCallToMldev", "fromId", "fromArgs", "functionDeclarationToVertex", "fromDescription", "fromParameters", "fromParametersJsonSchema", "fromResponse", "fromResponseJsonSchema", "generationConfigToVertex", "fromModelSelectionConfig", "fromAudioTimestamp", "fromCandidateCount", "fromEnableAffectiveDialog", "fromFrequencyPenalty", "fromLogprobs", "fromMaxOutputTokens", "fromMediaResolution", "fromPresencePenalty", "fromResponseLogprobs", "fromResponseMimeType", "fromResponseModalities", "fromResponseSchema", "fromRoutingConfig", "fromSeed", "fromSpeechConfig", "speechConfigToVertex", "fromStopSequences", "fromTemperature", "fromThinkingConfig", "fromTopK", "fromTopP", "googleMapsToMldev", "fromEnableWidget", "googleSearchToMldev", "fromTimeRangeFilter", "liveConnectConfigToMldev", "fromGenerationConfig", "t.tLiveSpeechConfig", "fromSystemInstruction", "fromTools", "t.tTools", "toolToMldev", "t.tTool", "fromSessionResumption", "sessionResumptionConfigToMldev", "fromInputAudioTranscription", "fromOutputAudioTranscription", "fromRealtimeInputConfig", "fromContextWindowCompression", "fromProactivity", "liveConnectConfigToVertex", "toolToVertex", "fromExplicitVadSignal", "liveConnectParametersToMldev", "fromModel", "t.tModel", "liveConnectParametersToVertex", "liveMusicSetConfigParametersToMldev", "fromMusicGenerationConfig", "liveMusicSetWeightedPromptsParametersToMldev", "fromWeightedPrompts", "liveSendRealtimeInputParametersToMldev", "fromMedia", "t.tBlobs", "fromAudio", "t.tAudioBlob", "fromAudioStreamEnd", "fromVideo", "t.tImageBlob", "fromText", "fromActivityStart", "fromActivityEnd", "liveSendRealtimeInputParametersToVertex", "liveServerMessageFromVertex", "fromSetupComplete", "fromServerContent", "fromToolCall", "fromToolCallCancellation", "fromUsageMetadata", "usageMetadataFromVertex", "fromGoAway", "fromSessionResumptionUpdate", "fromVoiceActivityDetectionSignal", "fromCodeExecutionResult", "fromExecutableCode", "fromFileData", "fromFunctionCall", "fromFunctionResponse", "fromInlineData", "fromThought", "fromThoughtSignature", "fromVideoMetadata", "fromHandle", "fromVoiceConfig", "fromLanguageCode", "fromFunctionDeclarations", "fromGoogleSearchRetrieval", "fromComputerUse", "fromFileSearch", "fromCodeExecution", "fromGoogleMaps", "fromGoogleSearch", "fromUrlContext", "fromRetrieval", "fromEnterpriseWebSearch", "fromPromptTokenCount", "fromCachedContentTokenCount", "fromResponseTokenCount", "fromToolUsePromptTokenCount", "fromThoughtsTokenCount", "fromTotalTokenCount", "fromPromptTokensDetails", "fromCacheTokensDetails", "fromResponseTokensDetails", "fromToolUsePromptTokensDetails", "fromTrafficType", "candidateFromMldev", "fromContent", "fromCitationMetadata", "citationMetadataFromMldev", "fromTokenCount", "fromFinishReason", "fromAvgLogprobs", "fromGroundingMetadata", "fromIndex", "fromLogprobsResult", "fromSafetyRatings", "fromUrlContextMetadata", "fromCitations", "computeTokensParametersToVertex", "fromContents", "t.tContents", "computeTokensResponseFromVertex", "fromTokensInfo", "contentEmbeddingFromVertex", "fromValues", "fromStatistics", "contentEmbeddingStatisticsFromVertex", "fromTruncated", "controlReferenceConfigToVertex", "fromControlType", "fromEnableControlImageComputation", "countTokensConfigToMldev", "countTokensConfigToVertex", "countTokensParametersToMldev", "countTokensParametersToVertex", "countTokensResponseFromMldev", "fromTotalTokens", "countTokensResponseFromVertex", "deleteModelParametersToMldev", "deleteModelParametersToVertex", "deleteModelResponseFromMldev", "deleteModelResponseFromVertex", "editImageConfigToVertex", "fromOutputGcsUri", "fromNegativePrompt", "fromNumberOfImages", "fromAspectRatio", "fromGuidanceScale", "fromSafetyFilterLevel", "fromPersonGeneration", "fromIncludeSafetyAttributes", "fromIncludeRaiReason", "fromLanguage", "fromOutputMimeType", "fromOutputCompressionQuality", "fromAddWatermark", "fromLabels", "fromEditMode", "fromBaseSteps", "editImageParametersInternalToVertex", "fromPrompt", "fromReferenceImages", "referenceImageAPIInternalToVertex", "editImageResponseFromVertex", "fromGeneratedImages", "generatedImageFromVertex", "embedContentConfigToMldev", "fromTaskType", "fromTitle", "fromOutputDimensionality", "embedContentConfigToVertex", "fromAutoTruncate", "embedContentParametersToMldev", "t.tContentsForEmbed", "fromModelForEmbedContent", "embedContentParametersToVertex", "embedContentResponseFromMldev", "fromEmbeddings", "fromMetadata", "embedContentResponseFromVertex", "endpointFromVertex", "fromDeployedModelId", "functionCallingConfigToMldev", "fromMode", "fromAllowedFunctionNames", "generateContentConfigToMldev", "t.tSchema", "fromSafetySettings", "safetySettingToMldev", "fromToolConfig", "toolConfigToMldev", "fromCachedContent", "t.tCachedContentName", "t.tSpeechConfig", "fromImageConfig", "imageConfigToMldev", "fromEnableEnhancedCivicAnswers", "generateContentConfigToVertex", "imageConfigToVertex", "generateContentParametersToMldev", "generateContentParametersToVertex", "generateContentResponseFromMldev", "fromCandidates", "fromModelVersion", "fromPromptFeedback", "fromResponseId", "generateContentResponseFromVertex", "fromCreateTime", "generateImagesConfigToMldev", "fromImageSize", "generateImagesConfigToVertex", "fromEnhancePrompt", "generateImagesParametersToMldev", "generateImagesParametersToVertex", "generateImagesResponseFromMldev", "generatedImageFromMldev", "fromPositivePromptSafetyAttributes", "safetyAttributesFromMldev", "generateImagesResponseFromVertex", "safetyAttributesFromVertex", "generateVideosConfigToMldev", "fromNumberOfVideos", "fromDurationSeconds", "fromResolution", "fromLastFrame", "imageToMldev", "videoGenerationReferenceImageToMldev", "generateVideosConfigToVertex", "fromFps", "fromPubsubTopic", "fromGenerateAudio", "imageToVertex", "videoGenerationReferenceImageToVertex", "fromMask", "videoGenerationMaskToVertex", "fromCompressionQuality", "generateVideosOperationFromMldev", "fromDone", "fromError", "generateVideosResponseFromMldev", "generateVideosOperationFromVertex", "generateVideosResponseFromVertex", "generateVideosParametersToMldev", "fromImage", "videoToMldev", "fromSource", "generateVideosSourceToMldev", "generateVideosParametersToVertex", "videoToVertex", "generateVideosSourceToVertex", "fromGeneratedVideos", "generatedVideoFromMldev", "fromRaiMediaFilteredCount", "fromRaiMediaFilteredReasons", "generatedVideoFromVertex", "imageFromMldev", "fromRaiFilteredReason", "fromSafetyAttributes", "imageFromVertex", "fromEnhancedPrompt", "generatedImageMaskFromVertex", "videoFromMldev", "videoFromVertex", "getModelParametersToMldev", "getModelParametersToVertex", "fromImageBytes", "t.tBytes", "fromGcsUri", "listModelsConfigToMldev", "fromFilter", "fromQueryBase", "t.tModelsUrl", "listModelsConfigToVertex", "listModelsParametersToMldev", "listModelsParametersToVertex", "listModelsResponseFromMldev", "fromModels", "t.tExtractModels", "modelFromMldev", "listModelsResponseFromVertex", "modelFromVertex", "maskReferenceConfigToVertex", "fromMaskMode", "fromSegmentationClasses", "fromMaskDilation", "fromDisplayName", "fromVersion", "fromTunedModelInfo", "tunedModelInfoFromMldev", "fromInputTokenLimit", "fromOutputTokenLimit", "fromSupportedActions", "fromMaxTemperature", "fromThinking", "fromEndpoints", "tunedModelInfoFromVertex", "fromDefaultCheckpointId", "fromCheckpoints", "productImageToVertex", "fromProductImage", "recontextImageConfigToVertex", "recontextImageParametersToVertex", "recontextImageSourceToVertex", "recontextImageResponseFromVertex", "fromPersonImage", "fromProductImages", "fromReferenceImage", "fromReferenceId", "fromReferenceType", "fromMaskImageConfig", "fromControlImageConfig", "fromStyleImageConfig", "fromSubjectImageConfig", "fromCategories", "fromScores", "fromContentType", "fromCategory", "fromThreshold", "scribbleImageToVertex", "segmentImageConfigToVertex", "fromMaxPredictions", "fromConfidenceThreshold", "fromBinaryColorThreshold", "segmentImageParametersToVertex", "segmentImageSourceToVertex", "segmentImageResponseFromVertex", "fromGeneratedMasks", "fromScribbleImage", "fromFunctionCallingConfig", "fromRetrievalConfig", "fromBaseModel", "fromUpdateTime", "updateModelConfigToMldev", "updateModelConfigToVertex", "updateModelParametersToMldev", "updateModelParametersToVertex", "upscaleImageAPIConfigInternalToVertex", "fromEnhanceInputImage", "fromImagePreservationFactor", "upscaleImageAPIParametersInternalToVertex", "fromUpscaleFactor", "upscaleImageResponseFromVertex", "fromUri", "fromVideoBytes", "createFileSearchStoreConfigToMldev", "createFileSearchStoreParametersToMldev", "deleteFileSearchStoreConfigToMldev", "fromForce", "deleteFileSearchStoreParametersToMldev", "getFileSearchStoreParametersToMldev", "importFileConfigToMldev", "fromCustomMetadata", "fromChunkingConfig", "importFileOperationFromMldev", "importFileResponseFromMldev", "importFileParametersToMldev", "fromFileSearchStoreName", "fromFileName", "fromParent", "fromDocumentName", "listFileSearchStoresConfigToMldev", "listFileSearchStoresParametersToMldev", "listFileSearchStoresResponseFromMldev", "fromFileSearchStores", "uploadToFileSearchStoreConfigToMldev", "uploadToFileSearchStoreParametersToMldev", "uploadToFileSearchStoreResumableResponseFromMldev", "CONTENT_TYPE_HEADER", "SERVER_TIMEOUT_HEADER", "USER_AGENT_HEADER", "GOOGLE_API_CLIENT_HEADER", "SDK_VERSION", "LIBRARY_LABEL", "VERTEX_AI_API_DEFAULT_VERSION", "GOOGLE_AI_API_DEFAULT_VERSION", "ApiClient", "opts", "initHttpOptions", "httpOptions", "urlElement", "baseUrl", "urlParts", "url", "prependProjectLocation", "request", "patchedHttpOptions", "key", "value", "requestInit", "baseHttpOptions", "requestHttpOptions", "abortSignal", "abortController", "signal", "timeoutHandle", "includeExtraBodyToRequestInit", "httpMethod", "throwErrorIfNotOK", "types.HttpResponse", "e", "reader", "decoder", "buffer", "dataPrefix", "delimiters", "done", "chunkString", "chunkJson", "errorJson", "status", "code", "errorMessage", "delimiterIndex", "delimiterLength", "delimiter", "eventString", "trimmedEvent", "processedChunkString", "partialResponse", "headers", "versionHeaderValue", "file", "fileName", "fileToUpload", "uploader", "fileStat", "mimeType", "uploadUrl", "fileSearchStoreName", "sizeBytes", "configHttpOptions", "errorBody", "extraBody", "currentBodyObject", "parsedBody", "deepMerge", "target", "source", "output", "sourceValue", "targetValue", "mergedBody", "MCP_LABEL", "hasMcpToolUsageFromMcpToTool", "hasMcpToolUsage", "tools", "tool", "isMcpCallableTool", "setMcpUsageHeader", "existingHeader", "object", "McpCallableTool", "listAllTools", "mcpClient_1", "mcpClient", "maxTools", "cursor", "numTools", "t", "_McpCallableTool", "mcpClients", "functionMap", "mcpTools", "e_1", "mcpTool", "mcpToolName", "mcpToolsToGeminiTool", "functionCalls", "functionCallResponseParts", "functionCall", "requestOptions", "callToolResponse", "handleWebSocketMessage", "apiClient", "onmessage", "event", "serverMessage", "types.LiveMusicServerMessage", "data", "LiveMusic", "__name", "auth", "webSocketFactory", "params", "websocketBaseUrl", "apiVersion", "headers", "mapToHeaders", "apiKey", "url", "onopenResolve", "onopenPromise", "resolve", "callbacks", "onopenAwaitedCallback", "websocketCallbacks", "_a", "e", "_b", "conn", "headersToMap", "clientMessage", "t.tModel", "LiveMusicSession", "clientContent", "converters.liveMusicSetWeightedPromptsParametersToMldev", "setConfigParameters", "converters.liveMusicSetConfigParametersToMldev", "playbackControl", "types.LiveMusicPlaybackControl", "headerMap", "value", "key", "map", "FUNCTION_RESPONSE_REQUIRES_ID", "types.LiveServerMessage", "jsonData", "resp", "converters.liveServerMessageFromVertex", "Live", "clientHeaders", "hasMcpToolUsage", "setMcpUsageHeader", "method", "keyName", "transformedModel", "project", "location", "_c", "types.Modality", "_d", "inputTools", "_f", "_e", "convertedTools", "tool", "callableTool", "liveConnectParameters", "converters.liveConnectParametersToVertex", "converters.liveConnectParametersToMldev", "Session", "defaultLiveSendClientContentParamerters", "contents", "t.tContents", "item", "contentToMldev", "functionResponses", "functionResponse", "converters.liveSendRealtimeInputParametersToVertex", "converters.liveSendRealtimeInputParametersToMldev", "DEFAULT_MAX_REMOTE_CALLS", "shouldDisableAfc", "config", "callableToolsPresent", "isCallableTool", "maxCalls", "hasCallableTools", "findAfcIncompatibleToolIndexes", "afcIncompatibleToolIndexes", "index", "geminiTool", "shouldAppendAfcHistory", "Models", "BaseModule", "transformedParams", "afc.hasCallableTools", "afc.shouldDisableAfc", "incompatibleToolIndexes", "afc.findAfcIncompatibleToolIndexes", "formattedIndexes", "response", "functionResponseContent", "automaticFunctionCallingHistory", "tContents", "maxRemoteCalls", "afc.DEFAULT_MAX_REMOTE_CALLS", "remoteCalls", "responseContent", "functionResponseParts", "afc.isCallableTool", "parts", "afc.shouldAppendAfcHistory", "streamFunctionCall", "disableAfc", "apiResponse", "positivePromptSafetyAttributes", "generatedImages", "generatedImage", "actualParams", "Pager", "PagedItem", "x", "paramsInternal", "img", "apiConfig", "apiParams", "tools", "transformedTools", "newParams", "mcp.hasMcpToolUsage", "newHeaders", "mcp.setMcpUsageHeader", "afcTools", "toolDeclaration", "declaration", "wereFunctionsCalled", "remoteCallCount", "afcToolsMap", "models", "__await", "responseContents", "response_1", "e_1", "__asyncValues", "response_1_1", "chunk", "part", "responseParts", "typedResponseChunk", "types.GenerateContentResponse", "newContents", "updatedContents", "path", "queryParams", "body", "converters.generateContentParametersToVertex", "common.formatMap", "httpResponse", "jsonResponse", "converters.generateContentResponseFromVertex", "typedResp", "converters.generateContentParametersToMldev", "converters.generateContentResponseFromMldev", "apiResponse_1", "apiResponse_1_1", "apiResponse_2", "apiResponse_2_1", "converters.embedContentParametersToVertex", "converters.embedContentResponseFromVertex", "types.EmbedContentResponse", "converters.embedContentParametersToMldev", "converters.embedContentResponseFromMldev", "converters.generateImagesParametersToVertex", "converters.generateImagesResponseFromVertex", "types.GenerateImagesResponse", "converters.generateImagesParametersToMldev", "converters.generateImagesResponseFromMldev", "converters.editImageParametersInternalToVertex", "converters.editImageResponseFromVertex", "types.EditImageResponse", "converters.upscaleImageAPIParametersInternalToVertex", "converters.upscaleImageResponseFromVertex", "types.UpscaleImageResponse", "converters.recontextImageParametersToVertex", "converters.recontextImageResponseFromVertex", "types.RecontextImageResponse", "converters.segmentImageParametersToVertex", "converters.segmentImageResponseFromVertex", "types.SegmentImageResponse", "converters.getModelParametersToVertex", "converters.modelFromVertex", "converters.getModelParametersToMldev", "converters.modelFromMldev", "converters.listModelsParametersToVertex", "converters.listModelsResponseFromVertex", "types.ListModelsResponse", "converters.listModelsParametersToMldev", "converters.listModelsResponseFromMldev", "converters.updateModelParametersToVertex", "converters.updateModelParametersToMldev", "converters.deleteModelParametersToVertex", "converters.deleteModelResponseFromVertex", "types.DeleteModelResponse", "converters.deleteModelParametersToMldev", "converters.deleteModelResponseFromMldev", "converters.countTokensParametersToVertex", "converters.countTokensResponseFromVertex", "types.CountTokensResponse", "converters.countTokensParametersToMldev", "converters.countTokensResponseFromMldev", "converters.computeTokensParametersToVertex", "converters.computeTokensResponseFromVertex", "types.ComputeTokensResponse", "converters.generateVideosParametersToVertex", "converters.generateVideosOperationFromVertex", "types.GenerateVideosOperation", "converters.generateVideosParametersToMldev", "converters.generateVideosOperationFromMldev", "Operations", "parameters", "operation", "resourceName", "httpOptions", "rawOperation", "converters.getOperationParametersToVertex", "converters.getOperationParametersToMldev", "converters.fetchPredictOperationParametersToVertex", "blobToMldev", "fromObject", "toObject", "fromData", "common.getValueByPath", "common.setValueByPath", "fromMimeType", "fromParts", "transformedList", "partToMldev", "fromRole", "createAuthTokenConfigToMldev", "parentObject", "fromExpireTime", "fromNewSessionExpireTime", "fromUses", "fromLiveConnectConstraints", "liveConnectConstraintsToMldev", "fromLockAdditionalFields", "createAuthTokenParametersToMldev", "fromConfig", "fileDataToMldev", "fromFileUri", "functionCallToMldev", "fromId", "fromArgs", "fromName", "googleMapsToMldev", "fromEnableWidget", "googleSearchToMldev", "fromTimeRangeFilter", "liveConnectConfigToMldev", "fromGenerationConfig", "fromResponseModalities", "fromTemperature", "fromTopP", "fromTopK", "fromMaxOutputTokens", "fromMediaResolution", "fromSeed", "fromSpeechConfig", "t.tLiveSpeechConfig", "fromThinkingConfig", "fromEnableAffectiveDialog", "fromSystemInstruction", "t.tContent", "fromTools", "t.tTools", "toolToMldev", "t.tTool", "fromSessionResumption", "sessionResumptionConfigToMldev", "fromInputAudioTranscription", "fromOutputAudioTranscription", "fromRealtimeInputConfig", "fromContextWindowCompression", "fromProactivity", "fromModel", "fromCodeExecutionResult", "fromExecutableCode", "fromFileData", "fromFunctionCall", "fromFunctionResponse", "fromInlineData", "fromText", "fromThought", "fromThoughtSignature", "fromVideoMetadata", "fromHandle", "fromFunctionDeclarations", "fromGoogleSearchRetrieval", "fromComputerUse", "fromFileSearch", "fromCodeExecution", "fromGoogleMaps", "fromGoogleSearch", "fromUrlContext", "getFieldMasks", "setup", "fields", "field", "kk", "convertBidiSetupToTokenSetup", "requestDict", "setupForMaskGeneration", "bidiGenerateContentSetupValue", "innerSetup", "preExistingFieldMask", "generatedMaskFromBidi", "generationConfigFields", "mappedFieldsFromPreExisting", "finalMaskParts", "Tokens", "converters.createAuthTokenParametersToMldev", "transformedBody", "deleteDocumentConfigToMldev", "fromForce", "deleteDocumentParametersToMldev", "getDocumentParametersToMldev", "listDocumentsConfigToMldev", "fromPageSize", "fromPageToken", "listDocumentsParametersToMldev", "fromParent", "listDocumentsResponseFromMldev", "fromSdkHttpResponse", "fromNextPageToken", "fromDocuments", "Documents", "converters.getDocumentParametersToMldev", "converters.deleteDocumentParametersToMldev", "converters.listDocumentsParametersToMldev", "converters.listDocumentsResponseFromMldev", "types.ListDocumentsResponse", "FileSearchStores", "documents", "converters.createFileSearchStoreParametersToMldev", "converters.getFileSearchStoreParametersToMldev", "converters.deleteFileSearchStoreParametersToMldev", "converters.listFileSearchStoresParametersToMldev", "converters.listFileSearchStoresResponseFromMldev", "types.ListFileSearchStoresResponse", "converters.uploadToFileSearchStoreParametersToMldev", "converters.uploadToFileSearchStoreResumableResponseFromMldev", "types.UploadToFileSearchStoreResumableResponse", "converters.importFileParametersToMldev", "converters.importFileOperationFromMldev", "types.ImportFileOperation", "uuid4Internal", "crypto", "u8", "randomByte", "c", "uuid4", "isAbortError", "err", "castToError", "error", "GeminiNextGenAPIClientError", "APIError", "_APIError", "status", "message", "msg", "errorResponse", "APIConnectionError", "BadRequestError", "AuthenticationError", "PermissionDeniedError", "NotFoundError", "ConflictError", "UnprocessableEntityError", "RateLimitError", "InternalServerError", "APIUserAbortError", "cause", "APIConnectionTimeoutError", "startsWithSchemeRegexp", "isAbsoluteURL", "isArrayInternal", "val", "isArray", "isReadonlyArrayInternal", "isReadonlyArray", "isEmptyObj", "obj", "_k", "hasOwn", "validatePositiveInteger", "name", "n", "safeJSON", "text", "sleep", "ms", "VERSION", "getDetectedPlatform", "getPlatformProperties", "detectedPlatform", "normalizePlatform", "normalizeArch", "browserInfo", "getBrowserInfo", "browserPatterns", "pattern", "match", "major", "minor", "patch", "arch", "platform", "_platformHeaders", "getPlatformHeaders", "getDefaultFetch", "makeReadableStream", "args", "ReadableStream", "ReadableStreamFrom", "iterable", "iter", "controller", "done", "ReadableStreamToAsyncIterable", "stream", "reader", "result", "cancelPromise", "CancelReadableStream", "FallbackEncoder", "checkFileSupport", "process", "isOldNode", "makeFile", "fileBits", "fileName", "options", "getName", "isAsyncIterable", "isBlobLike", "isFileLike", "isResponseLike", "toFile", "blob", "getBytes", "type", "value_1", "value_1_1", "constructor", "propsForError", "p", "APIResource", "client", "encodeURIPath", "str", "EMPTY", "createPathTagFunction", "pathEncoder", "statics", "postPath", "invalidSegments", "previousValue", "currentValue", "encoded", "pathOnly", "invalidSegmentPattern", "a", "b", "lastEnd", "underline", "acc", "segment", "spaces", "arrows", "BaseInteractions", "api_version", "__rest", "Errors.GeminiNextGenAPIClientError", "id", "query", "Interactions", "concatBytes", "buffers", "length", "buffer", "output", "encodeUTF8_", "encodeUTF8", "encoder", "decodeUTF8_", "decodeUTF8", "bytes", "decoder", "LineDecoder", "binaryChunk", "lines", "patternIndex", "findNewlineIndex", "endIndex", "line", "startIndex", "i", "findDoubleNewlineIndex", "levelNumbers", "parseLogLevel", "maybeLevel", "sourceName", "loggerFor", "noop", "makeLogFn", "fnLevel", "logger", "logLevel", "noopLogger", "cachedLoggers", "cachedLogger", "levelLogger", "formatRequestDetails", "details", "Stream", "_Stream", "iterator", "consumed", "_iterSSEMessages", "sse", "readableStream", "iterLines", "lineDecoder", "iter_1", "iter_1_1", "left", "right", "teeIterator", "queue", "self", "ctrl", "sseDecoder", "SSEDecoder", "iterSSEChunks", "sseChunk", "iterator_3", "iterator_3_1", "newData", "fieldname", "_", "partition", "delimiter", "defaultParseResponse", "props", "requestLogID", "retryOfRequestLogID", "startTime", "contentType", "mediaType", "APIPromise", "_APIPromise", "responsePromise", "parseResponse", "transform", "onfulfilled", "onrejected", "onfinally", "brand_privateNullableHeaders", "iterateHeaders", "values", "nulls", "shouldClear", "row", "didClear", "buildHeaders", "targetHeaders", "nullHeaders", "seenHeaders", "lowerName", "readEnv", "env", "BaseGeminiNextGenAPIClient", "_BaseGeminiNextGenAPIClient", "baseURL", "opts", "defaultLogLevel", "_g", "_h", "_j", "Shims.getDefaultFetch", "Opts.FallbackEncoder", "Errors.APIError", "defaultBaseURL", "defaultQuery", "request", "remainingRetries", "optionsInput", "retriesRemaining", "maxRetries", "req", "timeout", "retryLogStr", "Errors.APIUserAbortError", "headersTime", "retryMessage", "isTimeout", "Errors.APIConnectionTimeoutError", "Errors.APIConnectionError", "responseInfo", "shouldRetry", "Shims.CancelReadableStream", "errText", "errJSON", "errMessage", "init", "signal", "isReadableBody", "fetchOptions", "shouldRetryHeader", "responseHeaders", "timeoutMillis", "retryAfterMillisHeader", "timeoutMs", "retryAfterHeader", "timeoutSeconds", "numRetries", "sleepSeconds", "jitter", "inputOptions", "retryCount", "bodyHeaders", "reqHeaders", "idempotencyHeaders", "rawHeaders", "Shims.ReadableStreamFrom", "GeminiNextGenAPIClient", "API.Interactions", "Errors.NotFoundError", "Errors.ConflictError", "Errors.RateLimitError", "Errors.BadRequestError", "Errors.AuthenticationError", "Errors.InternalServerError", "Errors.PermissionDeniedError", "Errors.UnprocessableEntityError", "Uploads.toFile", "cancelTuningJobParametersToMldev", "_rootObject", "cancelTuningJobParametersToVertex", "cancelTuningJobResponseFromMldev", "cancelTuningJobResponseFromVertex", "createTuningJobConfigToMldev", "fromTunedModelDisplayName", "fromEpochCount", "fromLearningRateMultiplier", "fromBatchSize", "fromLearningRate", "createTuningJobConfigToVertex", "rootObject", "discriminatorValidationDataset", "fromValidationDataset", "tuningValidationDatasetToVertex", "fromDescription", "discriminatorEpochCount", "discriminatorLearningRateMultiplier", "discriminatorExportLastCheckpointOnly", "fromExportLastCheckpointOnly", "discriminatorAdapterSize", "fromAdapterSize", "fromLabels", "fromBeta", "createTuningJobParametersPrivateToMldev", "fromBaseModel", "fromPreTunedModel", "fromTrainingDataset", "tuningDatasetToMldev", "createTuningJobParametersPrivateToVertex", "tuningDatasetToVertex", "getTuningJobParametersToMldev", "getTuningJobParametersToVertex", "listTuningJobsConfigToMldev", "fromFilter", "listTuningJobsConfigToVertex", "listTuningJobsParametersToMldev", "listTuningJobsParametersToVertex", "listTuningJobsResponseFromMldev", "fromTuningJobs", "tuningJobFromMldev", "listTuningJobsResponseFromVertex", "tuningJobFromVertex", "tunedModelFromMldev", "fromEndpoint", "fromExamples", "discriminatorGcsUri", "fromGcsUri", "discriminatorVertexDatasetResource", "fromVertexDatasetResource", "fromState", "t.tTuningJobStatus", "fromCreateTime", "fromStartTime", "fromEndTime", "fromUpdateTime", "fromTunedModel", "fromError", "fromSupervisedTuningSpec", "fromPreferenceOptimizationSpec", "fromTuningDataStats", "fromEncryptionSpec", "fromPartnerModelTuningSpec", "fromCustomBaseModel", "fromExperiment", "fromOutputUri", "fromPipelineJob", "fromServiceAccount", "fromVeoTuningSpec", "tuningOperationFromMldev", "fromMetadata", "fromDone", "Tunings", "preTunedModel", "paramsPrivate", "tunedModelName", "types.JobState", "converters.getTuningJobParametersToVertex", "converters.tuningJobFromVertex", "converters.getTuningJobParametersToMldev", "converters.tuningJobFromMldev", "converters.listTuningJobsParametersToVertex", "converters.listTuningJobsResponseFromVertex", "types.ListTuningJobsResponse", "converters.listTuningJobsParametersToMldev", "converters.listTuningJobsResponseFromMldev", "converters.cancelTuningJobParametersToVertex", "converters.cancelTuningJobResponseFromVertex", "types.CancelTuningJobResponse", "converters.cancelTuningJobParametersToMldev", "converters.cancelTuningJobResponseFromMldev", "converters.createTuningJobParametersPrivateToVertex", "converters.createTuningJobParametersPrivateToMldev", "converters.tuningOperationFromMldev", "BrowserDownloader", "_params", "_apiClient", "MAX_CHUNK_SIZE", "MAX_RETRY_COUNT", "INITIAL_RETRY_DELAY_MS", "DELAY_MULTIPLIER", "X_GOOG_UPLOAD_STATUS_HEADER_FIELD", "uploadBlob", "file", "uploadUrl", "uploadBlobInternal", "responseJson", "uploadBlobToFileSearchStore", "_converters.uploadToFileSearchStoreOperationFromMldev", "UploadToFileSearchStoreOperation", "fileSize", "offset", "HttpResponse", "uploadCommand", "chunkSize", "currentDelayMs", "getBlobStat", "resolvePromise", "BrowserUploader", "BrowserWebSocketFactory", "BrowserWebSocket", "GOOGLE_API_KEY_HEADER", "WebAuth", "LANGUAGE_LABEL_PREFIX", "GoogleGenAI", "httpOpts", "nextGenClient", "GeminiNextGenAPI", "baseUrl", "getBaseUrl", "ApiClient", "Batches", "Chats", "Caches", "Files", "logalot", "GLOBAL_LOG_A_LOT", "textSourceToGeminiRole", "src", "TextSource", "__name", "isPromptInfoGemini", "info", "systemPromptEntriesToSystemInstructionContent", "systemPromptEntries", "lc", "logalot", "entry", "TextSource", "sysInstructionContent", "pretty", "error", "extractErrorMsg", "__name", "isFunctionCallRequestComment", "ibGib", "isComment", "text", "FUNCTION_CALL_REQUEST_COMMENT_TAG", "getFunctionCallAndResponseParts", "functionInfoIbGib", "fnName", "fnArgs", "fnResult", "logalot", "GLOBAL_LOG_A_LOT", "FUNCTION_INFO_REL8N_NAME", "FUNCTION_INFO_ATOM", "getFunctionInfoIb", "data", "lc", "model", "api", "agentId", "timestamp", "timestampInTicks", "getTimestampInTicks", "x", "__name", "createFunctionInfoIbGib", "arg", "lc", "logalot", "fnRawRequest", "api", "model", "agentId", "fnName", "fnArgs", "fnResult", "fnComplete", "parseErrorMsg", "execErrorMsg", "repromptWithResult", "saveInSpace", "metaspace", "space", "date", "data", "getTimestamp", "ib", "getFunctionInfoIb", "resFunctionInfo", "Factory_V1", "FUNCTION_INFO_ATOM", "getIbGibAddr", "error", "extractErrorMsg", "__name", "logalot", "LightWitnessBase_V1", "_LightWitnessBase_V1", "__name", "initialData", "initialRel8ns", "getUUID", "getGib", "toDto", "dto", "lc", "clone", "error", "errors", "ERROR_IB_REGEXP", "logalot", "getErrorIb", "rawMsg", "lc", "parsed", "parseRawErrorMsg", "saferText", "msgSlice", "error", "__name", "data", "regexResult", "ERROR_MSG_WITH_ID_CAPTURE_GROUPS_REGEXP", "_", "location", "unexpectedAtStart", "body", "idSection", "unexpectedAtEnd", "regexResultLocation", "ERROR_MSG_LOCATION_ONLY_REGEXP", "getErrorIbGib", "constantIbGib", "ERROR_IB_REGEXP", "isError", "ibGib", "ANONYMOUS_FN_ATOM", "DEFAULT_ANONYMOUS_FN_DATA_V1", "logalot", "getAnonymousFnIb", "data", "lc", "ANONYMOUS_FN_ATOM", "error", "__name", "AnonymousFnWitness_V1", "__name", "ANONYMOUS_FN_ATOM", "GIB", "clone", "DEFAULT_ANONYMOUS_FN_DATA_V1", "fn", "arg", "hash", "getAnonymousFnIb", "getGib", "logalot", "extractObsErrMsg", "err", "lc", "isIbGib", "ibGib", "isError", "extractErrorMsg", "error", "__name", "fnObs", "observerOrFn", "observer", "fnNext", "ROOT", "fnWitness", "nextAnonFnWitness", "AnonymousFnWitness_V1", "witnessAnonFnWitness", "observerWitness", "x", "fnError", "errorMsg", "errorAnonFnWitness", "getErrorIbGib", "fnComplete", "completeAnonFnWitness", "_", "logalot", "WitnessBase_V1", "_WitnessBase_V1", "__name", "value", "lc", "result", "initialData", "initialRel8ns", "toDto", "dto", "clone", "error", "arg", "sha256v1", "validationErrors_this", "validationErrors_arg", "getIbGibAddr", "errors", "ibErrors", "validateIb", "gibErrors", "validateGib", "intrinsicErrors", "validateIbGibIntrinsically", "getGibInfo", "logalot", "WitnessWithContextBase_V1", "_WitnessWithContextBase_V1", "WitnessBase_V1", "__name", "initialData", "initialRel8ns", "lc", "error", "extractErrorMsg", "thisAddr", "getIbGibAddr", "latestAddr", "resGet", "validationErrors", "pretty", "ibGibs", "rel8nName", "linked", "metaspace", "thisValidationErrors", "alreadyRel8dTjpGibs", "x", "getGibInfo", "ibGibsNotYetRel8dByTjp", "tjpGib", "addrs", "resNewThis", "rel8", "newThisIbGib", "newThisValidationErrors", "validateIbGibIntrinsically", "ibGibToRel8", "ibGibAddrToRel8", "contextIbGib", "rel8nNames", "rel8nsToAddByAddr", "resRel8ToContext", "newContext", "text", "space", "resComment", "createCommentIbGib", "commentIbGib", "getSaferSubstring", "atom", "classnameIsh", "nameIsh", "idIsh", "addlMetadataText", "arg", "addr", "latest", "resLatestAddr", "incomingContext_NotLatest", "currentTjpAddr", "getTjpAddr", "incomingTjpAddr", "updatePriorChildren", "contextTjpAddr", "fnObs", "update", "lcNext", "currentAddr", "latestN_Supposedly", "currentN", "err", "lcErr", "extractObsErrMsg", "tries", "maxTries", "delay", "newChildrenIbGibs", "newChild", "newChildrenAddrs", "resLatestAddrs", "getLatestAddrs", "latestAddrs", "SUBJECT_ATOM", "SUBJECT_NAME_REGEXP", "DEFAULT_NAME_SUBJECT", "DEFAULT_UUID_SUBJECT", "DEFAULT_DESCRIPTION_SUBJECT", "OBSERVABLE_ATOM", "ObservableCmd", "OBSERVABLE_CMD_VALUES", "ObserverCmd", "SubjectCmd", "ObservableCmd", "ObserverCmd", "DEFAULT_SUBJECT_DATA_V1", "DEFAULT_UUID_SUBJECT", "DEFAULT_NAME_SUBJECT", "DEFAULT_DESCRIPTION_SUBJECT", "DEFAULT_SUBJECT_REL8NS_V1", "logalot", "getArgIb", "ibMetadata", "lc", "ib", "WITNESS_ARG_METADATA_STRING", "error", "__name", "isArg", "ibGib", "getResultIb", "WITNESS_RESULT_METADATA_STRING", "argy_", "argData", "ibMetadata", "noTimestamp", "lc", "resArgIbGib", "Factory_V1", "getArgIb", "WITNESS_ARG_METADATA_STRING", "resultIbGib", "sha256v1", "error", "__name", "resulty_", "resultData", "resResultIbGib", "getResultIb", "WITNESS_RESULT_METADATA_STRING", "isCommand", "ibGib", "lc", "logalot", "cmdData", "error", "__name", "isWitness", "ibGib", "lc", "logalot", "error", "__name", "WitnessFactoryBase", "_WitnessFactoryBase", "__name", "logalot", "DynamicFormFactoryBase", "_DynamicFormFactoryBase", "WitnessFactoryBase", "__name", "data", "contextPath", "items", "pathDelimiter", "lc", "i", "item", "path", "patchObject", "error", "SUBSCRIPTION_ATOM", "SUBSCRIPTION_NAME_REGEXP", "DEFAULT_UUID_SUBSCRIPTION", "DEFAULT_NAME_SUBSCRIPTION", "DEFAULT_DESCRIPTION_SUBSCRIPTION", "SubscriptionCmd", "DEFAULT_SUBSCRIPTION_DATA_V1", "DEFAULT_UUID_SUBSCRIPTION", "DEFAULT_NAME_SUBSCRIPTION", "DEFAULT_DESCRIPTION_SUBSCRIPTION", "DEFAULT_SUBSCRIPTION_REL8NS_V1", "logalot", "isObservable", "ibGib", "lc", "logalot", "ib", "OBSERVABLE_ATOM", "SUBJECT_ATOM", "atom", "error", "__name", "logalot", "Subscription_V1", "_Subscription_V1", "LightWitnessBase_V1", "__name", "initialData", "initialRel8ns", "lc", "getSubscriptionIb", "getGib", "error", "arg", "ib", "SubscriptionCmd", "isObservable", "extractErrorMsg", "ROOT", "ibGib", "result", "TRUE_GIB", "FALSE_GIB", "pretty", "Factory_V1", "isError", "errorIbGib", "resRaw", "resUnsubscribed", "argData", "ibMetadata", "noTimestamp", "ibGibs", "argy_", "resultData", "resulty_", "Subscription_V1_Factory", "_Subscription_V1_Factory", "DynamicFormFactoryBase", "data", "rel8ns", "clone", "DEFAULT_SUBSCRIPTION_DATA_V1", "DEFAULT_SUBSCRIPTION_REL8NS_V1", "getUUID", "classname", "subscriptionIbGibDto", "constantIbGib", "witnessIbGib", "witness", "idPool", "getIdPool", "form", "SubscriptionFormBuilder", "DEFAULT_DESCRIPTION_SUBSCRIPTION", "DEFAULT_DATA_PATH_DELIMITER", "logalot", "validateCommonSubscriptionData", "data", "lc", "errors", "name", "uuid", "classname", "SUBSCRIPTION_NAME_REGEXP", "UUID_REGEXP", "CLASSNAME_REGEXP", "error", "extractErrorMsg", "__name", "getSubscriptionIb", "data", "classname", "lc", "validationErrors", "validateCommonSubscriptionData", "uuid", "SUBSCRIPTION_ATOM", "error", "extractErrorMsg", "__name", "SubscriptionFormBuilder", "_SubscriptionFormBuilder", "WitnessFormBuilder", "__name", "isSubscription", "ibGib", "lc", "logalot", "sub", "error", "newupSubscription", "Subscription_V1_Factory", "OBSERVABLE_EVENT_ATOM", "logalot", "getObservableEventIbGib", "eventType", "srcObservable", "payload", "lc", "UUID_REGEXP", "data", "getUUID", "getIbGibAddr", "constantIbGib", "OBSERVABLE_EVENT_ATOM", "getObservableEventIb", "error", "__name", "classname", "extractErrorMsg", "logalot", "ObservableBase_V1", "_ObservableBase_V1", "LightWitnessBase_V1", "__name", "initialData", "initialRel8ns", "arg", "lc", "ib", "isCommand", "isWitness", "error", "extractErrorMsg", "ObservableCmd", "OBSERVABLE_CMD_VALUES", "isSubscription", "key", "subscription", "_observer", "ROOT", "observer", "subscriberKey", "fnStillSubscribed", "i", "keepGoing", "payload", "ibGib", "newupSubscription", "resSubscription", "isObserver", "getIbGibAddr", "fnForObserver", "observableEventType", "subscriberTuples", "observerOrWitness", "observableEventWrapper", "getObservableEventIbGib", "argData", "ibMetadata", "noTimestamp", "ibGibs", "argy_", "resultData", "result", "resulty_", "logalot", "Subject_V1", "_Subject_V1", "ObservableBase_V1", "__name", "initialData", "initialRel8ns", "observer", "lc", "arg", "SubjectCmd", "getIbGibAddr", "error", "ibGib", "errorIbGib", "getErrorIbGib", "extractErrorMsg", "isError", "cmd", "ROOT", "payloadIbGib", "subscriberTuples", "subscription", "errIbGib", "observerOrWitness", "isObserver", "i", "argData", "ibMetadata", "noTimestamp", "ibGibs", "ObservableCmd", "argy_", "resultData", "result", "resulty_", "Subject_V1_Factory", "_Subject_V1_Factory", "DynamicFormFactoryBase", "data", "rel8ns", "clone", "DEFAULT_SUBJECT_DATA_V1", "DEFAULT_SUBJECT_REL8NS_V1", "getUUID", "classname", "ib", "getSubjectIb", "subscriptionIbGibDto", "constantIbGib", "witnessIbGib", "pretty", "witness", "idPool", "getIdPool", "form", "SubjectFormBuilder", "DEFAULT_DESCRIPTION_SUBJECT", "DEFAULT_DATA_PATH_DELIMITER", "logalot", "validateCommonSubjectData", "data", "lc", "errors", "name", "uuid", "classname", "SUBJECT_NAME_REGEXP", "UUID_REGEXP", "CLASSNAME_REGEXP", "error", "extractErrorMsg", "__name", "getSubjectIb", "data", "classname", "lc", "validationErrors", "validateCommonSubjectData", "name", "uuid", "SUBJECT_ATOM", "error", "extractErrorMsg", "__name", "SubjectFormBuilder", "_SubjectFormBuilder", "WitnessFormBuilder", "__name", "isObserver", "ibGib", "lc", "logalot", "error", "newupSubject", "data", "replay", "subjectFactory", "Subject_V1_Factory", "clone", "DEFAULT_SUBJECT_DATA_V1", "logalot", "GLOBAL_LOG_A_LOT", "LiveProxyIbGib", "WitnessWithContextBase_V1", "__name", "IB", "GIB", "lc", "error", "extractErrorMsg", "dto", "initialData", "initialRel8ns", "newupSubject", "ib", "arg", "isSpaceIb", "spaceId", "Factory_V1", "space", "ROOT", "update", "ibGib", "ibGibAddr", "getGlobalMetaspace_waitIfNeeded", "resGet", "newChild", "logalot", "GLOBAL_LOG_A_LOT", "AgentWitness_V1", "_AgentWitness_V1", "LightWitnessBase_V1", "__name", "tr", "initialData", "initialRel8ns", "pickRandom_Letters", "lc", "errors", "UUID_REGEXP", "AGENT_NAME_REGEXP", "AGENT_DESC_REGEXP", "error", "extractErrorMsg", "getGlobalMetaspace_waitIfNeeded", "ibGibProxy", "LiveProxyIbGib", "fnObs", "nextIbGib", "lcNext", "pretty", "e", "dto", "space", "getIbGibAddr", "nProxy", "nThis", "delay", "metaspace", "validationErrors", "opts", "contextIbGib", "loggingInfo", "contextIbGibAddr", "contextTjpAddr", "getTjpAddr", "proxy", "lcContextUpdated", "lcNewContextChild", "newChild", "isComment", "alreadyDoneCommentTjpAddrs", "x", "newChildTjpAddr", "safeIbCommentMetadataText", "parseCommentIb", "textSrc", "parseAddlMetadataTextForAgentText", "isSystem", "TextSource", "name", "availableFunctions", "functionsToAdd", "incomingFn", "functionInfo", "getAllFunctionInfos", "dataToAddOrPatch", "superSpace", "tjpGib", "getGibInfo", "execInSpaceWithLocking", "agentsSvc", "getAgentsSvc", "resMut8", "mut8", "newAgentIbGib", "updateAgentIndex", "functionInfos", "promptTextInfo", "apiResult", "functionCalls", "text", "functionInfoIbGibs", "transientDecompressionPromptText", "functionCallStr", "functionInfoIbGib", "functionCallParsedObj", "parseErrorMsg", "functionArgs", "functionName", "fnResult", "fnComplete", "execErrorMsg", "createFunctionInfoIbGib", "fcrText", "taggifyForPrompt", "FUNCTION_CALL_REQUEST_COMMENT_TAG", "addlMetadataText", "getAddlMetadataTextForAgentText", "resComment", "createCommentIbGib", "resRel8FunctionInfosToFCR", "rel8", "FUNCTION_INFO_REL8N_NAME", "functionCallRequestComment", "contentTexts", "functionInfoAddr", "fnRawRequest", "contentText", "arg", "IB", "GIB", "ROOT", "logalot", "GLOBAL_LOG_A_LOT", "AgentWitnessGemini_V1", "_AgentWitnessGemini_V1", "AgentWitness_V1", "__name", "lc", "errors", "error", "extractErrorMsg", "ib", "opts", "agentsSvc", "getAgentsSvc", "metaspace", "orderedCommentIbGibs_all", "orderedCommentIbGibs_system", "orderedCommentIbGibs_chat", "superSpace", "info", "textSrc", "isSystem", "text", "commentIbGib", "addlMetadataText", "getAddlMetadataTextForAgentText", "createCommentIbGib", "validationErrors", "validateAgentWitnessCommentIbGib", "rel8nInfosToAppend", "newAgentIbGib", "appendToTimeline", "AGENT_REL8N_NAME", "systemPromptEntries", "entry", "currentContextTjpAddr", "ROOT_ADDR", "TextSource", "textSourceToGeminiRole", "getTextPartForCurrentContextTjpAddr", "chatPromptHistoryParts", "chatCommentIbGibs_history", "chatPromptCurrent", "chatCommentIbGib_current", "chatPromptCurrent_rawarray", "resPromptInfo", "pretty", "isPromptInfoGemini", "api", "model", "apiKey", "GoogleGenAI", "functionDeclarations", "x", "chatPromptCurrent_final", "clone", "result", "fnGoModel", "modelStr", "historyContents", "chatConfig", "systemPromptEntriesToSystemInstructionContent", "FunctionCallingConfigMode", "chat", "messageParams", "tryCount", "errorMessage", "status", "GEMINI_BACKUP_MODEL_STR", "delay", "GEMINI_MAX_TRY_COUNT", "response", "functionCalls", "parts", "part", "parseCommentIb", "timestampInTicks", "errorMsg", "other", "parseAddlMetadataTextForAgentText", "isFunctionCallRequestComment", "functionInfoIbGibs", "functionCallParts", "functionResponseParts", "functionInfoIbGib", "call", "getFunctionCallAndResponseParts", "functionCallEntry", "functionResponseEntry", "systemInstructions", "modelsToTry", "modelIndex", "retryDelayInSeconds", "nextModelStr", "fcrCommentIbGib", "resFunctionInfoIbGibs", "functionInfoAddrs", "FUNCTION_INFO_REL8N_NAME", "resGetFunctionInfos", "getIbGibAddr", "dto", "fn", "nameOrId", "getAllFunctionInfos", "getDeprecatedFunctionInfoNames", "rel8dAddrs_system", "resGet_systemComments", "rel8dAddrs_chat", "resGet_chatComments", "execInSpaceWithLocking", "getTimestampInTicks", "agentIbGibDtoToWitness", "getGibInfo", "logalot", "GLOBAL_LOG_A_LOT", "CreateConcreteAgentWitnessFactory_Gemini", "_CreateConcreteAgentWitnessFactory_Gemini", "__name", "arg", "superSpace", "lc", "name", "api", "model", "type", "availableFunctions", "data", "clone", "DEFAULT_AGENT_DATA_V1", "getUUID", "x", "AgentWitnessGemini_V1", "error", "extractErrorMsg", "DEFAULT_AGENT_REL8NS_V1", "witness", "agentIbGibDtoToWitness", "agentIbGib", "agentWitness", "storageGet", "getGlobalDbName", "getGlobalStoreName", "getGlobalIndexedDbKey_APIKey", "logalot", "GLOBAL_LOG_A_LOT", "getTag_Agents", "metaspace", "space", "createIfNone", "lc", "tagsIbGib", "getTagsIbGib", "agentTagAddrs", "TAG_REL8N_NAME", "x", "ib", "getIbAndGib", "TAG_AGENT_IB", "agentTagAddr", "agentTagIbGib", "newTagIbGib", "TAG_AGENT_TEXT", "TAG_AGENT_ICON", "TAG_AGENT_DESCRIPTION", "resGet", "error", "extractErrorMsg", "__name", "getAgents", "type", "spaceId", "agentIbGibs", "AGENT_REL8N_NAME", "resAgentWitnessesProper", "agentIbGib", "agentsSvc", "getAgentsSvc", "actualWitness", "updateAgentIndex", "newAgentIbGib", "latestAgentInMemory", "newAgentAddr", "getIbGibAddr", "updateSpecialIndex", "toDto", "registerDomainIbGibWithAgentIndex", "domainIbGib", "agentIbGib", "metaspace", "space", "lc", "logalot", "coupleDomainIbGibWithLocalIbGibViaIndex", "error", "extractErrorMsg", "__name", "getAgentForDomainIbGib", "ibGib", "getLocalCoupledIbGibForDomainIbGib", "domainTjpAddr", "getTjpAddr", "agentAddr", "getIbGibAddr", "agentWitness", "getAgentsSvc", "getConcreteAgentFactory", "arg", "api", "CreateConcreteAgentWitnessFactory_Gemini", "taggifyForPrompt", "tagText", "contentText", "randomIdLength", "fullTagText", "pickRandom_Letters", "getAddlMetadataTextForAgentText", "textSrc", "other", "getTimestampInTicks", "parseAddlMetadataTextForAgentText", "addlMetadataText", "ifError", "timestampInTicksStr", "isTextSource", "TEXT_SOURCE_VALUES", "timestampInTicks", "errorMsg", "TextSource", "getAgentIb", "data", "name", "uuid", "type", "x", "AGENT_ATOM", "parseAgentIb", "ib", "atom", "validateAgentWitnessCommentIbGib", "errors", "validateIbGibIntrinsically", "isComment", "parseCommentIb", "addlMetaInfo", "logalot", "GLOBAL_LOG_A_LOT", "FUNCTION_NAME", "CMD_CATEGORY", "CMD_MODIFIERS", "EXAMPLE_INPUT_TELLUSER", "EXAMPLES", "FUNCTION_CALL_EXAMPLES_HEADER", "pretty", "FUNCTION_DESCRIPTION", "tellUserViaCmd", "opts", "lc", "commandService", "getCommandService", "command", "resolve", "reject", "error", "extractErrorMsg", "__name", "tellUserImpl", "metaspace", "getGlobalMetaspace_waitIfNeeded", "contextAddr", "addrErrors", "validateIbGibAddr", "isPrimitive", "getIbAndGib", "space", "commentIbGib", "createCommentIbGib", "getAddlMetadataTextForAgentText", "TextSource", "latestContextIbGib", "latestContextAddr", "resGetLatest", "appendToTimeline", "GEMINI_SCHEMA_TELL_USER_TEXT", "GEMINI_SCHEMA_TELL_USER_CONTEXT_ADDR", "tellUserFunctionInfo", "COMMAND_BASE_SCHEMA_PROPERTIES", "GEMINI_SCHEMA_AGENTS_SELF_IDENTIFIED_NAME", "SETTINGS_ATOM", "SETTINGS_TYPE_GENERAL", "SETTINGS_TYPE_TEXTEDITOR", "SETTINGS_TYPE_PROJECTS", "SETTINGS_TYPE_PROJECTSEXPLORER", "SETTINGS_TYPE_PROJECTSDROPDOWN", "SETTINGS_TYPE_PROJECT", "SETTINGS_TYPE_MINIGAME", "SETTINGS_TYPE_CHRONOLOGYS", "SettingsType", "SETTINGS_TYPE_VALID_VALUES", "DEFAULT_SETTINGS_GENERAL", "SettingsType", "DEFAULT_SETTINGS_TEXTEDITOR", "DEFAULT_SETTINGS_PROJECT", "DEFAULT_SETTINGS_MINIGAME", "DEFAULT_SETTINGS_CHRONOLOGYS", "DEFAULT_SETTINGS_DATA_V1", "logalot", "GLOBAL_LOG_A_LOT", "getSettingsScope", "ibGib", "lc", "ib", "getIbAndGib", "atom", "SETTINGS_ATOM", "error", "extractErrorMsg", "__name", "getSectionName", "settingsType", "useCase", "getDefaultSettings", "settingsType", "lc", "logalot", "SettingsType", "clone", "DEFAULT_SETTINGS_GENERAL", "DEFAULT_SETTINGS_TEXTEDITOR", "DEFAULT_SETTINGS_PROJECT", "DEFAULT_SETTINGS_MINIGAME", "DEFAULT_SETTINGS_CHRONOLOGYS", "SETTINGS_TYPE_VALID_VALUES", "error", "extractErrorMsg", "__name", "getSettingsSection", "sectionName", "settingsIbGib", "getSettingsIb", "scope", "SETTINGS_ATOM", "createSettings", "scope", "metaspace", "space", "saveInSpace", "lc", "ib", "getSettingsIb", "data", "getDefaultSettingsData", "resSettings", "Factory_V1", "SETTINGS_ATOM", "error", "extractErrorMsg", "__name", "logalot", "clone", "DEFAULT_SETTINGS_DATA_V1", "sectionName_generalDefault", "getSectionName", "sectionName_generalCurrent", "DEFAULT_SETTINGS_GENERAL", "sectionName_textEditorDefault", "sectionName_textEditorCurrent", "DEFAULT_SETTINGS_TEXTEDITOR", "logalot", "GLOBAL_LOG_A_LOT", "IbGibDynamicComponentMetaBase", "_IbGibDynamicComponentMetaBase", "__name", "fnGetMetaspace", "bootstrapPromise", "IbGibDynamicComponentInstanceBase", "_IbGibDynamicComponentInstanceBase", "ib", "getIbAndGib", "ROOT_ADDR", "gib", "ibGibAddr", "isPrimitive", "Factory_V1", "getTjpAddr", "lc", "error", "extractErrorMsg", "pickRandom_Letters", "opts", "meta", "html", "css", "template", "name", "oldValue", "newValue", "getLatest", "metaspace", "space", "latestAddr", "resGet", "ibGib", "ibGibProxy", "LiveProxyIbGib", "fnObs", "nextIbGib", "lcNext", "pretty", "e", "childIbGib", "_ignoredSpace", "_ignored", "getIbGibAddr", "punctiliarColor", "punctiliarColorTranslucent", "punctiliarColorContrast", "tjpColor", "tjpColorTranslucent", "tjpColorContrast", "errorMsg", "getDeterministicColorInfo", "dontThrowIfNone", "agent", "getAgentForDomainIbGib", "initialN", "delay", "afterN", "toDto", "settingsType", "useCase", "settingsSection", "getSettingsSection", "getSectionName", "newSectionInfo", "sectionName_current", "_newSettings", "mut8Timeline", "sectionName", "scope", "getSettingsScope", "settingsIbGib", "getLocalCoupledIbGibForDomainIbGib", "createSettings", "coupleDomainIbGibWithLocalIbGibViaIndex", "settingsProxy", "SettingsType", "compress", "exportIbGib", "exportIbGibJsonString", "rel8nName", "force", "skipRegisterTimelines", "divergentTimelineStrategy", "rawExportIbGib", "ibGibGraph", "getRawExportIbGibAndGraphFromJsonString", "exportRootAddr", "skipImportGraphIntoSpace", "resGetExisting", "splitPerTjpAndOrDna", "graphIbGibs_dna", "graphIbGibs_nondna", "x", "isDna", "resPutDna", "mapWithTjp_YesDna", "mapWithTjp_NoDna", "mapWithoutTjps", "resPutNonDnaStones", "timelineIbGibsMap", "timelineIbGibs", "resPutTimelines", "timelineMap_groupdByTjp", "getTimelinesGroupedByTjp", "timelines", "timeline", "latestIbGibInTimeline", "IbGibDynamicComponentInstanceBase_Parent", "addr", "tabInfoSharesTjpGib", "tabInfo", "tabGib", "getGibInfo", "tjpGib", "contentEl", "componentSvc", "getComponentSvc", "childInfo", "currentlyActive", "IbGibDynamicComponentInstanceBase_ParentOfTabs", "_IbGibDynamicComponentInstanceBase_ParentOfTabs", "value", "valueIsDifferent", "addrToClose", "tjpAddrToClose", "tabInfoToClose", "settings_current", "newOpenChildTjpAddrs", "newActiveChildTjpAddr", "newIndex", "newSectionSettings", "settings", "currentChildTjpAddr", "childTjpAddr", "RENDERABLE_HANDLE_TYPE", "CANVAS_HANDLE_TYPE", "RENDERABLE_SHAPE_RECTANGLE", "RENDERABLE_SHAPE_CIRCLE", "RENDERABLE_SHAPE_PATH", "RENDERABLE_SHAPE_TEXT", "RENDERABLE_SHAPE_GROUP", "RenderableShape", "logalot", "GLOBAL_LOG_A_LOT", "RenderService_V1", "_RenderService_V1", "__name", "opts", "renderSvcId", "canvasEl", "parentContainerEl", "renderFrame", "count", "ids", "getIdPool", "lc", "uuid", "handle", "RENDERABLE_HANDLE_TYPE", "CANVAS_HANDLE_TYPE", "type", "parameters", "RenderableShape", "paramsRect", "paramsText", "paramsPath", "targetInfo", "rawHandle", "stateMapEntry", "currentState", "currentGeometryGroupParameters", "updatedStateKeys", "updatedMembers", "memberHandle", "recursive", "stateInfo", "paramsGroup", "pretty", "resMap", "state", "geometry", "position", "scale", "color", "width", "height", "text", "fontFamily", "fontSize", "ctx", "commands", "fnCheapValidateCmd", "command", "cmd", "initialWidth", "error", "extractErrorMsg", "globalRenderService", "getRenderService", "forceNew", "renderSvc", "PathCommandType", "PATH_COMMAND_TYPE_VALUES", "GEMINI_SCHEMA_RENDERABLE_SVC_ID", "GEMINI_SCHEMA_RENDERABLE_HANDLE", "GEMINI_SCHEMA_RENDERABLE_HANDLES", "GEMINI_SCHEMA_RENDERABLE_COLOR", "GEMINI_SCHEMA_RENDERABLE_POSITION", "GEMINI_SCHEMA_RENDERABLE_SCALE", "GEMINI_SCHEMA_RENDERABLE_ISVISIBLE", "GEMINI_SCHEMA_RENDERABLE_RECURSIVE", "GEMINI_SCHEMA_RENDERABLE_TEXT_TEXT", "GEMINI_SCHEMA_RENDERABLE_TEXT_FONTFAMILY", "GEMINI_SCHEMA_RENDERABLE_TEXT_FONTSIZE", "GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_TEXT", "GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_GROUP", "GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_RECT", "XY_COORD_IF_TRUTHY_NOTE", "GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_PATH_COMMANDTYPE", "PATH_COMMAND_TYPE_VALUES", "GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_PATH_BEGINPATH", "GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_PATH_LINE", "GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_PATH_ARC", "GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_PATH_BEZIERCURVE", "GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_PATH_QUADRATICBEZIERCURVE", "GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_PATH_MOVETO", "GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_PATH_CLOSEPATH", "GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_PATH_STROKE", "GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_PATH_FILL", "GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_PATH_ITEM", "GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_PATH_COMMANDS", "GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PARAMS_PATH", "GEMINI_SCHEMA_RENDERABLE_GEOMETRY_RECT", "GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PATH", "GEMINI_SCHEMA_RENDERABLE_GEOMETRY_TEXT", "GEMINI_SCHEMA_RENDERABLE_GEOMETRY_GROUP", "EXAMPLE_INPUT_RENDERABLE_CREATERECTS", "RenderableShape", "EXAMPLE_INPUT_RENDERABLE_CREATEPATHS", "EXAMPLE_INPUT_RENDERABLE_CREATETEXTS", "EXAMPLE_INPUT_RENDERABLE_CREATEGROUP", "RENDERABLE_HANDLE_TYPE", "EXAMPLES_RECT", "FUNCTION_CALL_EXAMPLES_HEADER", "pretty", "EXAMPLES_PATH", "EXAMPLES_TEXT", "EXAMPLES_GROUP", "renderableCreateViaCmd", "opts", "commandService", "getCommandService", "command", "resolve", "reject", "__name", "renderableCreateImpl", "renderService", "getRenderService", "handles", "initialState", "handle", "x", "renderableCreateRectsFunctionInfo", "COMMAND_BASE_SCHEMA_PROPERTIES", "GEMINI_SCHEMA_RENDERABLE_SVC_ID", "GEMINI_SCHEMA_RENDERABLE_ISVISIBLE", "GEMINI_SCHEMA_RENDERABLE_COLOR", "GEMINI_SCHEMA_RENDERABLE_POSITION", "GEMINI_SCHEMA_RENDERABLE_SCALE", "GEMINI_SCHEMA_RENDERABLE_GEOMETRY_RECT", "renderableCreatePathsFunctionInfo", "GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PATH", "renderableCreateTextsFunctionInfo", "GEMINI_SCHEMA_RENDERABLE_GEOMETRY_TEXT", "renderableCreateGroupsFunctionInfo", "GEMINI_SCHEMA_RENDERABLE_GEOMETRY_GROUP", "tweakGeminiSchema", "baseSchema", "addlDescription", "resSchema", "clone", "__name", "EXAMPLE_INPUT_RENDERABLE_DESTROY_SINGLE", "EXAMPLE_INPUT_RENDERABLE_DESTROY_MULTIPLE", "EXAMPLES", "FUNCTION_CALL_EXAMPLES_HEADER", "pretty", "renderableDestroyViaCmd", "opts", "commandService", "getCommandService", "command", "resolve", "reject", "__name", "renderableDestroyImpl", "getRenderService", "renderableDestroyFunctionInfo", "COMMAND_BASE_SCHEMA_PROPERTIES", "GEMINI_SCHEMA_RENDERABLE_SVC_ID", "GEMINI_SCHEMA_RENDERABLE_HANDLES", "tweakGeminiSchema", "GEMINI_SCHEMA_RENDERABLE_RECURSIVE", "renderableGetAllViaCmd", "opts", "commandService", "getCommandService", "command", "resolve", "reject", "__name", "renderableGetAllImpl", "statesMap", "getRenderService", "handles", "renderableGetAllFunctionInfo", "COMMAND_BASE_SCHEMA_PROPERTIES", "GEMINI_SCHEMA_RENDERABLE_SVC_ID", "logalot", "GLOBAL_LOG_A_LOT", "EXAMPLE_INPUT_RENDERABLE_GET", "EXAMPLES", "FUNCTION_CALL_EXAMPLES_HEADER", "pretty", "renderableGetViaCmd", "opts", "commandService", "getCommandService", "command", "resolve", "reject", "__name", "renderableGetImpl", "lc", "getRenderService", "error", "extractErrorMsg", "renderableGetFunctionInfo", "COMMAND_BASE_SCHEMA_PROPERTIES", "GEMINI_SCHEMA_RENDERABLE_SVC_ID", "GEMINI_SCHEMA_RENDERABLE_HANDLES", "EXAMPLE_INPUT_UPDATEREDBOX_UNUSUAL_COLOR", "EXAMPLE_INPUT_UPDATEREDBOX_ALL_PROPS", "RenderableShape", "EXAMPLE_INPUT_UPDATEREDBOX_POSITION", "EXAMPLES", "FUNCTION_CALL_EXAMPLES_HEADER", "pretty", "EXAMPLES_COLOR_ONLY", "EXAMPLES_POSITION", "renderableUpdateViaCmd", "opts", "commandService", "getCommandService", "command", "resolve", "reject", "__name", "renderableUpdateImpl", "getRenderService", "getRenderableUpdateFunctionInfo", "nameOrId", "geometrySchema", "updatedStatePropertyNames", "examples", "updatedStateProperties", "requiredList", "schemas", "GEMINI_SCHEMA_RENDERABLE_ISVISIBLE", "GEMINI_SCHEMA_RENDERABLE_COLOR", "GEMINI_SCHEMA_RENDERABLE_POSITION", "GEMINI_SCHEMA_RENDERABLE_SCALE", "tweakGeminiSchema", "GEMINI_SCHEMA_RENDERABLE_RECURSIVE", "validNames", "x", "propName", "COMMAND_BASE_SCHEMA_PROPERTIES", "GEMINI_SCHEMA_RENDERABLE_SVC_ID", "GEMINI_SCHEMA_RENDERABLE_HANDLE", "renderableUpdateRectFunctionInfo", "GEMINI_SCHEMA_RENDERABLE_GEOMETRY_RECT", "renderableUpdatePathFunctionInfo", "GEMINI_SCHEMA_RENDERABLE_GEOMETRY_PATH", "renderableUpdateTextFunctionInfo", "GEMINI_SCHEMA_RENDERABLE_GEOMETRY_TEXT", "renderableUpdateColorFunctionInfo", "RenderAgentFunctionInfos", "renderableCreateRectsFunctionInfo", "renderableCreatePathsFunctionInfo", "renderableCreateTextsFunctionInfo", "renderableCreateGroupsFunctionInfo", "renderableDestroyFunctionInfo", "renderableGetFunctionInfo", "renderableGetAllFunctionInfo", "renderableUpdateRectFunctionInfo", "renderableUpdateTextFunctionInfo", "AGENT_INITIAL_CHAT_GIVESELFNAME", "AGENT_INITIAL_CHAT_HELLOWORLD", "AGENT_INSTRUCTIONS_INIT_HELLOWORLD_GETCONTEXT", "AGENT_INSTRUCTIONS_PROMPTS_ARE_COMMENT_IBGIBS", "AGENT_INSTRUCTIONS_IBGIB_DEFINITION", "AGENT_INSTRUCTIONS_MULTI_TURN_FUNCTIONS", "AGENT_SYSTEM_PROMPT_COMMON_INSTRUCTIONS", "AGENT_INITIAL_SYSTEM_SUPER_COOL", "AGENT_INITIAL_CHAT_HI_PLEASEINTRO_YOURSELF", "AGENT_EARLY_DAYS_DEV_CAVEAT", "AGENT_GOAL_COMMON", "AGENT_SYSTEM_PROMPT_COMMON_INSTRUCTIONS", "AGENT_INSTRUCTIONS_PROMPTS_ARE_COMMENT_IBGIBS", "AGENT_INSTRUCTIONS_IBGIB_DEFINITION", "AGENT_INSTRUCTIONS_MULTI_TURN_FUNCTIONS", "AGENT_INSTRUCTIONS_INIT_HELLOWORLD_GETCONTEXT", "CURRENT_WEB1_LINKS", "AGENT_WEBSITE_DESCRIPTION_CENTERPANEL", "AGENT_WEBSITE_DESCRIPTION_LEFTPANEL", "AGENT_WEBSITE_DESCRIPTION_HEADERPANEL", "AGENT_WEBSITE_DESCRIPTION_RIGHTPANEL", "AGENT_WEBSITE_DESCRIPTION_FOOTERPANEL", "AGENT_WEBSITE_DESCRIPTION", "AGENT_GOAL_CANVASAGENT", "AGENT_INITIAL_SYSTEM_TEXT_CANVASAGENT", "AGENT_SYSTEM_PROMPT_COMMON_INSTRUCTIONS", "initIbGibStorage", "config", "lc", "initAppStorage", "error", "extractErrorMsg", "__name", "initIbGibGlobalThis", "globalThisKey", "version", "storageGet", "getIbGibGlobalThis_IbGibApp", "globalThisKey", "config", "version", "initIbGibGlobalThis", "__name", "getDefaultFnGetAPIKey", "gb", "storageGet", "dynamicallyLoadBootstrapScript", "path", "bootstrapFnName", "lc", "module", "fn", "error", "extractErrorMsg", "getComponentCtorArg", "fnGetMetaspace", "getGlobalMetaspace_waitIfNeeded", "bootstrapPromiseWrapper", "resolve", "reject", "maxTries", "counter", "bootstrapPromise", "delay", "AUTO_GENERATED_VERSION", "logalot", "GLOBAL_LOG_A_LOT", "GLOBALTHIS_KEY", "initBlankGibStorage", "initIbGibStorage", "APP_CONFIG", "__name", "dynamicallyLoadBootstrapScript", "path", "bootstrapFnName", "getComponentCtorArg", "getDefaultFnGetAPIKey", "initIbGibGlobalThis", "config", "AUTO_GENERATED_VERSION", "getIbGibGlobalThis_BlankGib", "getIbGibGlobalThis_Common", "lc", "g", "getCurrentActiveProjectComponent", "ibGibGlobalThis", "error", "extractErrorMsg", "logalot", "GLOBAL_LOG_A_LOT", "AGENT_SPECIAL_IBGIB_TYPE_CANVASAGENT", "CHAT_WITH_AGENT_PLACEHOLDER_CANVASAGENT", "AGENT_AVAILABLE_FUNCTIONS_CANVASAGENT", "tellUserFunctionInfo", "RenderAgentFunctionInfos", "CANVAS_COMPONENT_NAME", "CanvasComponentMeta", "_CanvasComponentMeta", "IbGibDynamicComponentMetaBase", "__name", "getComponentCtorArg", "CanvasComponentInstance", "path", "ibGibAddr", "lc", "component", "canvas_default", "root_default", "styles_default", "error", "extractErrorMsg", "_CanvasComponentInstance", "IbGibDynamicComponentInstanceBase", "opts", "canvasEl", "getUUID", "getRenderService", "ROOT", "getGlobalMetaspace_waitIfNeeded", "agent", "agents", "getAgents", "getAgentsSvc", "GEMINI_DEFAULT_MODEL_STR", "clone", "AGENT_INITIAL_SYSTEM_TEXT_CANVASAGENT", "appShellSvc", "getAppShellSvc", "delay", "storageGet", "BLANK_GIB_DB_NAME", "ARMY_STORE", "BEE_KEY", "projects_default", "projects_default", "PROJECT_ATOM", "PROJECT_NAME_REGEXP", "PROJECT_DESC_REGEXP", "PROJECT_SETTINGS_SCOPE", "SETTINGS_ATOM", "PROJECT_ATOM", "DEFAULT_PROJECT_SAFE_NAME_LENGTH", "DEFAULT_PROJECT_ADDL_METADATA_LENGTH", "PROJECT_CHILD_TEXT_REL8N_NAME", "AGENT_SPECIAL_IBGIB_TYPE_PROJECTAGENT", "logalot", "GLOBAL_LOG_A_LOT", "getProjectSafeName", "name", "lc", "safeName", "getSaferSubstring", "DEFAULT_PROJECT_SAFE_NAME_LENGTH", "error", "extractErrorMsg", "__name", "getProjectIb", "data", "validationErrors", "validateProjectData_V1", "timestampInfo", "getTimestampInfo", "addlMetadataFields", "addlMetadataText", "DEFAULT_PROJECT_ADDL_METADATA_LENGTH", "PROJECT_ATOM", "parseProjectIb", "ib", "lc", "logalot", "pieces", "atom", "safeName", "addlMetadataText", "PROJECT_ATOM", "metadataPieces", "timestampInTicksStr", "timestampInTicks", "result", "pretty", "error", "__name", "validateProjectData_V1", "data", "errors", "PROJECT_NAME_REGEXP", "PROJECT_DESC_REGEXP", "resValid", "getTimestampInfo", "extractErrorMsg", "isProjectData_V1", "data", "lc", "logalot", "validateProjectData_V1", "error", "extractErrorMsg", "__name", "isProjectIbGib_V1", "ibGib", "PROJECT_ATOM", "createProjectIbGib", "name", "srcCommentIbGib", "description", "saveInSpace", "space", "resSrcCommentIbGib", "createCommentIbGib", "safeName", "getSaferSubstring", "DEFAULT_PROJECT_SAFE_NAME_LENGTH", "resNewProjectFork", "fork", "now", "timestamp", "getTimestamp", "timestampMs", "fullNewDataSortOf", "newIb", "getProjectIb", "dataToAddOrPatch", "pretty", "resNewProjectMut8", "mut8", "resNewProject", "persistTransformResult", "getProjects", "metaspace", "space", "lc", "logalot", "spaceId", "parseSpaceIb", "projectAgents", "getAgentsSvc", "AGENT_SPECIAL_IBGIB_TYPE_PROJECTAGENT", "projectTjpAddrs", "projectAgent", "projectTjpAddr", "getIbGibAddr", "uniqueTjpAddrs", "unique", "resLatestIbGib", "getLatestAddrs", "latestAddrsMap", "latestAddrs", "addr", "latestAddr", "resGet", "latestProjectIbGibs", "ibGibsUnknownType", "ibGibUnknownType", "isProjectIbGib_V1", "error", "extractErrorMsg", "__name", "DEFAULT_PROJECT_DESCRIPTION", "LENS_MODE_RAW", "LENS_MODE_TEXT", "LENS_MODE_MINIGAME", "LensMode", "logalot", "GLOBAL_LOG_A_LOT", "EXAMPLE_INPUT_GETCONTEXTINFO", "EXAMPLES", "FUNCTION_CALL_EXAMPLES_HEADER", "pretty", "getContextInfoViaCmd", "opts", "commandService", "getCommandService", "command", "resolve", "reject", "__name", "getContextInfoImpl", "lc", "agentId", "agentType", "agent", "getAgentsSvc", "metaspace", "getGlobalMetaspace_waitIfNeeded", "contextAddr", "superSpaceId", "superSpace", "resGetContext", "contextIbGib", "latestContextIbGib", "latestContextAddr", "resGetLatest", "error", "errorMsg", "extractErrorMsg", "getContextInfoFunctionInfo", "COMMAND_BASE_SCHEMA_PROPERTIES", "GEMINI_SCHEMA_AGENT_ID", "GEMINI_SCHEMA_AGENT_TYPE", "logalot", "GLOBAL_LOG_A_LOT", "FUNCTION_NAME", "CMD_CATEGORY", "CMD_MODIFIERS", "EXAMPLE_INPUT_HELLOWORLD", "EXAMPLES", "FUNCTION_CALL_EXAMPLES_HEADER", "pretty", "FUNCTION_DESCRIPTION", "GEMINI_SCHEMA_AGENT_ID", "GEMINI_SCHEMA_AGENT_TYPE", "helloWorldViaCmd", "opts", "commandService", "getCommandService", "command", "resolve", "reject", "__name", "helloWorldImpl", "lc", "agentId", "agentType", "agentsSelfIdentifiedName", "agent", "getAgentsSvc", "error", "errorMsg", "extractErrorMsg", "helloWorldFunctionInfo", "COMMAND_BASE_SCHEMA_PROPERTIES", "GEMINI_SCHEMA_AGENTS_SELF_IDENTIFIED_NAME", "ChatAPIFunctionInfos", "tellUserFunctionInfo", "helloWorldFunctionInfo", "getContextInfoFunctionInfo", "logalot", "GLOBAL_LOG_A_LOT", "FUNCTION_NAME", "CMD_CATEGORY", "CMD_MODIFIERS", "EXAMPLE_INPUT_GETIBGIBS_SINGLE", "EXAMPLE_INPUT_GETIBGIBS_MULTIPLE", "EXAMPLES", "FUNCTION_CALL_EXAMPLES_HEADER", "pretty", "FUNCTION_DESCRIPTION", "GEMINI_SCHEMA_IBGIB_ADDRS", "GET_IBGIBS_SCHEMA", "COMMAND_BASE_SCHEMA_PROPERTIES", "getIbGibsViaCmd", "opts", "commandService", "getCommandService", "command", "resolve", "reject", "__name", "getIbGibsImpl", "lc", "spaceId", "ibGibAddrs", "getLatest", "metaspace", "getGlobalMetaspace_waitIfNeeded", "space", "addrToLatestAddrMap", "resLatestAddrs", "getLatestAddrs", "addr", "latestAddr", "addrsToGet", "resGet", "extractErrorMsg", "resMap", "ibGib", "ibGibAddr", "getIbGibAddr", "x", "error", "getIbGibsFunctionInfo", "logalot", "GLOBAL_LOG_A_LOT", "FUNCTION_NAME", "CMD_CATEGORY", "CMD_MODIFIERS", "DISALLOWED_DATA_KEYS", "EXAMPLE_INPUT_MUT8IBGIB_MUT8PROJECTNAME", "EXAMPLE_INPUT_MUT8IBGIB_MUT8DESCRIPTION", "EXAMPLE_INPUT_MUT8IBGIB_REMOVEKEY", "EXAMPLE_INPUT_MUT8IBGIB_RENAMEKEY", "EXAMPLE_INPUT_MUT8IBGIB_MUT8IB", "EXAMPLES", "FUNCTION_CALL_EXAMPLES_HEADER", "pretty", "FUNCTION_DESCRIPTION", "JSON_CAVEAT", "DISALLOWED_CAVEAT", "MUT8_IBGIB_SCHEMA", "COMMAND_BASE_SCHEMA_PROPERTIES", "mut8IbGibViaCmd", "opts", "commandService", "getCommandService", "command", "resolve", "reject", "__name", "mut8IbGibImpl", "lc", "spaceId", "ibGibAddr", "dataToRenameJSONString", "dataToRemoveJSONString", "dataToAddOrPatchJSONString", "mut8Ib", "newName", "newDescription", "metaspace", "getGlobalMetaspace_waitIfNeeded", "space", "newSafeName", "getProjectSafeName", "latestIbGibAddr", "projectIb", "getIbAndGib", "addlMetadataText", "atom", "parseProjectIb", "dataToRename", "dataToRemove", "dataToAddOrPatch", "fnValidateMap", "map", "paramName", "key", "invalidChars", "x", "newTimelineIbGib", "mut8Timeline", "error", "extractErrorMsg", "mut8IbGibFunctionInfo", "FUNCTION_NAME", "mut8IbGibViaCmd", "mut8IbGibImpl", "CMD_CATEGORY", "CMD_MODIFIERS", "MUT8_IBGIB_SCHEMA", "IbGibAPIFunctionInfos", "getIbGibsFunctionInfo", "mut8IbGibFunctionInfo", "logalot", "GLOBAL_LOG_A_LOT", "FUNCTION_NAME", "CMD_CATEGORY", "CMD_MODIFIERS", "EXAMPLE_INPUT_EDIT_TEXT", "EXAMPLES", "FUNCTION_CALL_EXAMPLES_HEADER", "pretty", "FUNCTION_DESCRIPTION", "FUNCTION_SCHEMA", "COMMAND_BASE_SCHEMA_PROPERTIES", "viaCmd", "opts", "commandService", "getCommandService", "command", "resolve", "reject", "__name", "fnImpl", "lc", "spaceId", "ibGibAddr", "newText", "metaspace", "getGlobalMetaspace_waitIfNeeded", "space", "newIb", "getCommentIb", "getTimestampInTicks", "newTimelineIbGib", "mut8Timeline", "getTimestamp", "error", "extractErrorMsg", "editTextFunctionInfo", "TextAPIFunctionInfos", "editTextFunctionInfo", "logalot", "GLOBAL_LOG_A_LOT", "FUNCTION_NAME", "CMD_CATEGORY", "CMD_MODIFIERS", "EXAMPLE_INPUT_UPDATECSS", "EXAMPLES", "FUNCTION_CALL_EXAMPLES_HEADER", "pretty", "FUNCTION_DESCRIPTION", "updateCSSVariablesViaCmd", "opts", "commandService", "getCommandService", "command", "resolve", "reject", "__name", "updateCSSVariablesImpl", "lc", "variableName", "value", "dbName", "getGlobalDbName", "storeName", "getGlobalStoreName", "existingUIInfo", "getExistingUIInfo", "newUIInfo", "storagePut", "UI_THEME_INFO_KEY", "error", "extractErrorMsg", "updateCSSVariablesFunctionInfo", "COMMAND_BASE_SCHEMA_PROPERTIES", "VALID_CSS_VARIABLES", "varName", "ProjectFunctionInfos", "AGENT_AVAILABLE_FUNCTIONS_PROJECTAGENT", "updateCSSVariablesFunctionInfo", "ChatAPIFunctionInfos", "TextAPIFunctionInfos", "IbGibAPIFunctionInfos", "ProjectFunctionInfos", "AGENT_AVAILABLE_FUNCTIONS_PROJECTCHILDTEXTAGENT", "AGENT_WEBSITE_DESCRIPTION_PROJECTCAVEAT", "AGENT_GOAL_PROJECTAGENT_LANGUAGELEARNING", "AGENT_GOAL_PROJECTAGENT", "AGENT_GOAL_COMMON", "AGENT_INITIAL_SYSTEM_TEXT_PROJECTAGENT", "AGENT_SYSTEM_PROMPT_COMMON_INSTRUCTIONS", "AGENT_WEBSITE_DESCRIPTION", "AGENT_INITIAL_CHAT_HI_PLEASEINTRO_YOURSELF_PROJECTAGENT", "AGENT_INITIAL_CHAT_TEXT_PROJECTAGENT", "CHAT_WITH_AGENT_PLACEHOLDER_PROJECTAGENT", "project_default", "project_default", "raw_default", "raw_default", "logalot", "GLOBAL_LOG_A_LOT", "RAW_COMPONENT_NAME", "RawComponentMeta", "_RawComponentMeta", "IbGibDynamicComponentMetaBase", "__name", "getComponentCtorArg", "RawComponentInstance", "path", "ibGibAddr", "lc", "logalot", "component", "raw_default", "root_default", "styles_default", "project_default", "error", "extractErrorMsg", "_RawComponentInstance", "IbGibDynamicComponentInstanceBase", "opts", "getGlobalMetaspace_waitIfNeeded", "shadowRoot", "headerEl", "shadowRoot_getElementById", "nameEl", "descEl", "contentEl", "summaryContentEl", "summaryHeaderEl", "ibContentEl", "ibHeaderEl", "gibContentEl", "gibHeaderEl", "dataContentEl", "dataHeaderEl", "rel8nsContentEl", "rel8nsHeaderEl", "rawJsonEl", "rawJsonHeaderEl", "entry", "_event", "footerEl", "description", "summaryUlEl", "fnAddLi", "label", "value", "liLabelEl", "liValueEl", "getTjpAddr", "data", "pretty", "rel8nsSubAccordion", "rel8nName", "rel8nNameSection", "ulRel8dsEl", "rel8dAddr", "liRel8dEl", "isPrimitive", "getIbAndGib", "addrEl", "getIbGibGlobalThis_BlankGib", "chronologysComponent", "count", "delay", "getIbGibAddr", "storageGet", "BLANK_GIB_DB_NAME", "ARMY_STORE", "BEE_KEY", "text_editor_default", "text_editor_default", "logalot", "GLOBAL_LOG_A_LOT", "TEXTEDITOR_COMPONENT_NAME", "TextEditorComponentMeta", "_TextEditorComponentMeta", "IbGibDynamicComponentMetaBase", "__name", "getComponentCtorArg", "TextEditorComponentInstance", "path", "ibGibAddr", "lc", "logalot", "component", "text_editor_default", "root_default", "styles_default", "error", "extractErrorMsg", "_TextEditorComponentInstance", "IbGibDynamicComponentInstanceBase", "opts", "getGlobalMetaspace_waitIfNeeded", "shadowRoot", "headerEl", "nameEl", "versionEl", "descEl", "contentEl", "editorEl", "footerEl", "saving", "debouncedSave", "debounce", "text", "delay", "getTimestampInTicks", "mut8Timeline", "getTimestamp", "event", "target", "description", "chronologysComponent", "getIbGibGlobalThis_BlankGib", "count", "getIbGibAddr", "storageGet", "BLANK_GIB_DB_NAME", "ARMY_STORE", "BEE_KEY", "AGENT_SPECIAL_IBGIB_TYPE_PROJECTCHILDTEXTAGENT", "AGENT_GOAL_PROJECTCHILDTEXTAGENT", "AGENT_GOAL_COMMON", "AGENT_INITIAL_SYSTEM_TEXT_PROJECTCHILDTEXTAGENT", "AGENT_SYSTEM_PROMPT_COMMON_INSTRUCTIONS", "AGENT_WEBSITE_DESCRIPTION", "AGENT_WEBSITE_DESCRIPTION_PROJECTCAVEAT", "AGENT_INITIAL_CHAT_HI_PLEASEINTRO_YOURSELF_PROJECTCHILDTEXTAGENT", "AGENT_INITIAL_CHAT_GIVESELFNAME", "AGENT_INITIAL_CHAT_HELLOWORLD", "AGENT_INITIAL_CHAT_TEXT_PROJECTCHILDTEXTAGENT", "TYPING_ATOM", "TYPING_SETTINGS_SCOPE", "SETTINGS_ATOM", "TYPING_ATOM", "DEFAULT_TYPING_GAMEMETA", "DEFAULT_TYPING_GAMESTATE", "TypingFunctionInfos", "getContextInfoFunctionInfo", "getIbGibsFunctionInfo", "AGENT_AVAILABLE_FUNCTIONS_TYPINGAGENT", "MINIGAME_GAMEVARIANT_TYPING_PARROT", "MINIGAME_GAMEVARIANT_TYPING_ANTIPHONY", "MINIGAME_GAMEVARIANT_TYPING_FITB", "MINIGAME_GAMEVARIANT_TYPING_TRANSLATE", "MinigameGameVariant_Typing", "MINIGAME_GAME_VARIANT_TYPING_VALUES", "MINIGAME_FOCUS_INFO", "MINIGAME_STIMULTI_TO_ADD_INFO", "EXPECTED_RESPONSE_TYPE_EXACT", "EXPECTED_RESPONSE_TYPE_EQUIVALENT", "EXPECTED_RESPONSE_TYPE_FITB", "EXPECTED_RESPONSE_TYPE_ANSWER", "ExpectedResponseType", "EXPECTED_RESPONSE_TYPE_VALID_VALUES", "DEFAULT_ISO_639_LANGUAGE_CODES", "MINIGAME_ATOM", "MINIGAME_NAME_REGEXP", "MINIGAME_DESC_REGEXP", "MINIGAME_SETTINGS_SCOPE", "SETTINGS_ATOM", "DEFAULT_MINIGAME_SAFE_NAME_LENGTH", "DEFAULT_MINIGAME_ADDL_METADATA_LENGTH", "MINIGAME_PROTOTYPE_REL8N_NAME", "MINIGAME_REL8N_NAME", "AGENT_AVAILABLE_FUNCTIONS_MINIGAMEAGENT", "ChatAPIFunctionInfos", "TextAPIFunctionInfos", "IbGibAPIFunctionInfos", "MINIGAME_GAMETYPE_TYPING", "MinigameGameType", "MINIGAME_GAME_TYPE_VALUES", "MINIGAME_GAMEVARIANT_COMMON_DEFAULT", "MINIGAME_GAMEVARIANT_COMMON_MULTI", "MinigameGameVariant_Common", "MINIGAME_GAME_VARIANT_COMMON_VALUES", "MinigameGameVariant", "MinigameGameVariant_Typing", "MINIGAME_GAME_VARIANT_VALUES", "GEMINI_SCHEMA_MINIGAME_GAMETYPE", "GEMINI_SCHEMA_MINIGAME_GAMEVARIANT_COMMON_DESCRIPTION", "GEMINI_SCHEMA_MINIGAME_GAMEVARIANT_TYPING_DESCRIPTION", "GEMINI_SCHEMA_MINIGAME_NAME", "GEMINI_SCHEMA_MINIGAME_DESCRIPTION", "GEMINI_SCHEMA_MINIGAME_INSTRUCTIONS", "GEMINI_SCHEMA_MINIGAME_KEYWORDS", "GEMINI_SCHEMA_MINIGAME_CONTEXT_ADDR", "GEMINI_SCHEMA_MINIGAME_MINIGAME_ADDR", "MINIGAME_GAMEPHASE_INIT", "MINIGAME_GAMEPHASE_READY", "MINIGAME_GAMEPHASE_PLAYING", "MINIGAME_GAMEPHASE_PAUSED", "MINIGAME_GAMEPHASE_ABORTED", "MINIGAME_GAMEPHASE_COMPLETE", "MinigameGamePhase", "MINIGAME_GAME_PHASE_VALUES", "DEFAULT_MINIGAME_TEXT", "DEFAULT_MINIGAME_NAME", "DEFAULT_MINIGAME_DESCRIPTION", "DEFAULT_MINIGAME_INSTRUCTIONS", "DEFAULT_MINIGAME_GAMETYPE", "MinigameGameType", "DEFAULT_MINIGAME_GAMEVARIANT", "MinigameGameVariant", "DEFAULT_MINIGAME_GAMEPHASE", "MinigameGamePhase", "DEFAULT_MINIGAME_KEYWORDS", "DEFAULT_MINIGAME_DATA_V1", "DEFAULT_MINIGAME_NAME", "DEFAULT_MINIGAME_TEXT", "DEFAULT_MINIGAME_DESCRIPTION", "DEFAULT_MINIGAME_INSTRUCTIONS", "DEFAULT_MINIGAME_GAMETYPE", "DEFAULT_MINIGAME_GAMEVARIANT", "DEFAULT_MINIGAME_GAMEPHASE", "DEFAULT_MINIGAME_KEYWORDS", "DEFAULT_TOKEN_CONSTRUCT_RULE", "logalot", "GLOBAL_LOG_A_LOT", "DEFAULT_ENGINE_CONSTRUCT_RULES", "DEFAULT_TOKEN_CONSTRUCT_RULE", "AnalysisEngine", "_AnalysisEngine", "__name", "rules", "lc", "r", "error", "extractErrorMsg", "name", "visited", "rule", "pattern", "flagsSet", "match", "regexBody", "regexFlags", "flag", "subName", "childInfo", "captureMatch", "result", "text", "constructs", "compiledInfo", "finalFlags", "finalRegex", "matches", "term", "normalizedTerm", "tokenFrequencyMap", "tokenCount", "sum", "count", "uniqueTokenCount", "logalot", "GLOBAL_LOG_A_LOT", "CorpusAnalyzer", "_CorpusAnalyzer", "__name", "engine", "id", "result", "lc", "error", "extractErrorMsg", "text", "docId", "topN", "constructsToReport", "AnalysisEngine", "analysis", "keywordsByConstruct", "constructName", "termFreqMap", "totalTermsInConstruct", "s", "c", "idfMap", "keywords", "term", "count", "tf", "idf", "a", "b", "sourceDocId", "targetDocId", "sourceReport", "targetReport", "sourceKeywords", "targetKeywords", "sourceTerms", "k", "targetTerms", "sharedKeywords", "sourceUniqueKeywords", "targetUniqueKeywords", "errorPrefix", "foundErrors", "terms", "docFrequencies", "totalDocs", "constructDocFreq", "termCounts", "logalot", "GLOBAL_LOG_A_LOT", "DEFAULT_LANGUAGE_FINGERPRINTS", "detectLanguage", "text", "fingerprints", "lc", "lang", "scores", "char", "maxScore", "key", "score", "error", "extractErrorMsg", "__name", "sentenceSplitter", "regex", "sentences", "s", "spanishText", "greekText", "germanText", "logalot", "GLOBAL_LOG_A_LOT", "editStimuli_typing", "stimuliEditInfos", "minigameIbGib", "minigameAddr", "lc", "metaspace", "getGlobalMetaspace_waitIfNeeded", "space", "getIbGibAddr", "latestMinigameIbGib", "getLatestTimelineIbGibDto_nonLocking", "allStimuli_new", "info", "existingIndex", "pretty", "insertAt", "x", "deleteAt", "mut8Timeline", "newMinigameIbGib", "error", "extractErrorMsg", "__name", "validateMinigameIsReady_typing", "data", "MinigameGameType", "errors", "gameMeta", "getElapsedInfo", "a", "b", "startTimestampString", "result", "startTimestampInTicksInt", "end_stimulusInTicksInt", "end_responseInTicksInt", "now_timestampInTicks", "getTimestampInTicks", "now_timestampInTicksInt", "emsg", "getWpm", "responsesAnalysis", "elapsedMs", "elapsedMinutes", "wpmRaw", "toHoursMinutesSeconds", "totalSeconds", "hours", "minutes", "seconds", "getUniqueTokens", "text", "tokensToIgnore", "lc", "logalot", "docId", "pickRandom_Letters", "topN", "engine", "AnalysisEngine", "DEFAULT_TOKEN_CONSTRUCT_RULE", "analyzer", "CorpusAnalyzer", "analysis", "report", "tokenFreqMap", "tokenFreqMapEntriesSortedByCount", "a", "b", "uniqueTokens", "x", "error", "extractErrorMsg", "__name", "getAnotherFocusText", "focusLevel", "existingFocuses", "randomize", "alertUser", "allFocuses", "focusPool", "uniqueCharacters", "unique", "allFocusesChars", "existingFocuses_lower", "sentenceSplitter", "resFocusText", "pickRandom", "getGoogleTranslateLink", "getStimulusEntryEl", "shadowRoot", "stimulusEntry", "entryTemplateContentNode", "shadowRoot_getElementById", "entryEl", "entryTemplateDiv", "entryTextEl", "deleteBtnEl", "editBtnEl", "detailsEl", "variantEl", "focusTextEl", "languageEl", "srcLanguageEl", "expectedTypeEl", "ExpectedResponseType", "expectedTypeSelectEl", "expectedTextEl", "delay", "highlightElement", "getTextTargetMappingString", "fromText", "toText", "maxChars", "getShortenedStringWithEllipsis", "askAgentTranslateOneOff", "agent", "contextSrcText", "getFocusAndElementsInfo", "dialogSrcText", "language", "fnHandleStimuliGenerated", "focusTemplateContentNode", "focusTemplateDiv", "focusTextTranslateEl", "detailsParrotEl", "detailsFitbEl", "detailsTranslateEl", "detailsEls", "fnOutroEl", "el", "slideRightAndFade", "detailsParrot_expectedResponse", "getNewTypingEntryId", "getTimestampInTicks", "detailsFitbNumBlanksEl", "fnGetBlankedText", "str", "numBlanks", "blank", "blankedText", "answerMap", "availableTokens", "i", "token", "blankIndex", "answers", "index", "detailsFitb_blankedTextEl", "detailsFitb_expectedResponseEl", "fnUpdateFitbInfo", "resBlank", "debounce", "detailsTranslateTranslatedFocusTextEl", "fnUpdateTranslationLabels", "translation", "detailsTranslate_stimulusGenTargetNative", "detailsTranslate_stimulusGenNativeTarget", "rawAgentTranslation", "languageOptionsCheckboxEl", "detailsTranslateTargetNativeCheckboxEl", "detailsTranslateNativeTargetCheckboxEl", "translatedText", "getUUID", "durationMs", "width", "resolve", "unfadeEl", "logalot", "GLOBAL_LOG_A_LOT", "getMinigameSafeName", "name", "lc", "safeName", "getSaferSubstring", "DEFAULT_MINIGAME_SAFE_NAME_LENGTH", "error", "extractErrorMsg", "__name", "getMinigameIb", "data", "validationErrors", "validateMinigameData_V1", "timestampInfo", "getTimestampInfo", "addlMetadataFields", "addlMetadataText", "DEFAULT_MINIGAME_ADDL_METADATA_LENGTH", "MINIGAME_ATOM", "validateMinigameData_V1", "data", "lc", "errors", "logalot", "MINIGAME_NAME_REGEXP", "MINIGAME_DESC_REGEXP", "resValid", "getTimestampInfo", "error", "extractErrorMsg", "__name", "isMinigameData_V1", "data", "lc", "logalot", "validateMinigameData_V1", "error", "extractErrorMsg", "__name", "isMinigameIbGib_V1", "ibGib", "MINIGAME_ATOM", "createMinigameIbGib", "srcMinigameIbGib", "saveInSpace", "space", "registerNewIbGib", "name", "description", "instructions", "gameType", "gameVariants", "gameState", "keywords", "startingData", "DEFAULT_MINIGAME_DATA_V1", "now", "timestamp", "getTimestamp", "timestampMs", "src", "Factory_V1", "MINIGAME_PROTOTYPE_REL8N_NAME", "getIbGibAddr", "resNewMinigameFork", "fork", "getMinigameIb", "newMinigameIbGib", "newMinigameAddr", "persistTransformResult", "pretty", "getGlobalMetaspace_waitIfNeeded", "validateMinigameIsReady", "minigameIbGib", "MinigameGameType", "validateMinigameIsReady_typing", "minigame_default", "minigame_default", "typing_default", "typing_default", "logalot", "GLOBAL_LOG_A_LOT", "FUNCTION_NAME", "CMD_CATEGORY", "CMD_MODIFIERS", "EXAMPLE_INPUT_MINIGAMEBUILDER_VALIDATE_AND_READY", "EXAMPLES", "FUNCTION_CALL_EXAMPLES_HEADER", "pretty", "FUNCTION_DESCRIPTION", "minigameBuilderValidateAndReadyViaCmd", "opts", "lc", "commandService", "getCommandService", "command", "resolve", "reject", "error", "extractErrorMsg", "__name", "minigameBuilderValidateAndReadyImpl", "metaspace", "getGlobalMetaspace_waitIfNeeded", "minigameAddr", "addrErrors", "validateIbGibAddr", "isPrimitive", "getIbAndGib", "space", "latestAddr", "resGet", "minigameIbGib", "isReadyErrors", "validateMinigameIsReady", "MinigameGamePhase", "mut8Timeline", "ibGibGlobalThis", "getIbGibGlobalThis_BlankGib", "minigameBuilderValidateAndReadyFunctionInfo", "COMMAND_BASE_SCHEMA_PROPERTIES", "GEMINI_SCHEMA_MINIGAME_MINIGAME_ADDR", "logalot", "GLOBAL_LOG_A_LOT", "FUNCTION_NAME", "CMD_CATEGORY", "CMD_MODIFIERS", "EXAMPLE_INPUT_MINIGAMEBUILDER_EDIT_STIMULI", "EXAMPLE_INPUT_MINIGAMEBUILDER_EDIT_STIMULI_ANTIPHONY", "ExpectedResponseType", "EXAMPLE_INPUT_MINIGAMEBUILDER_EDIT_STIMULI_FITB", "EXAMPLES", "FUNCTION_CALL_EXAMPLES_HEADER", "pretty", "FUNCTION_DESCRIPTION", "minigameBuilderEditStimuliViaCmd", "opts", "lc", "commandService", "getCommandService", "command", "resolve", "reject", "error", "extractErrorMsg", "__name", "minigameBuilderEditStimuliImpl", "metaspace", "getGlobalMetaspace_waitIfNeeded", "minigameAddr", "addrErrors", "validateIbGibAddr", "isPrimitive", "getIbAndGib", "info", "getNewTypingEntryId", "_newMinigameIbGib", "editStimuli_typing", "GEMINI_SCHEMA_MINIGAME_TYPING_STIMULUS", "EXPECTED_RESPONSE_TYPE_VALID_VALUES", "GEMINI_SCHEMA_MINIGAME_TYPING_STIMULUS_EDIT_INFO", "GEMINI_SCHEMA_MINIGAME_TYPING_STIMULUS_EDIT_INFOS", "minigameBuilderEditStimuliFunctionInfo", "COMMAND_BASE_SCHEMA_PROPERTIES", "GEMINI_SCHEMA_MINIGAME_CONTEXT_ADDR", "logalot", "GLOBAL_LOG_A_LOT", "TYPING_COMPONENT_NAME", "TypingComponentMeta", "_TypingComponentMeta", "IbGibDynamicComponentMetaBase", "__name", "getComponentCtorArg", "TypingComponentInstance", "path", "ibGibAddr", "lc", "logalot", "component", "typing_default", "root_default", "styles_default", "error", "extractErrorMsg", "_TypingComponentInstance", "IbGibDynamicComponentInstanceBase", "gamePhase", "MinigameGamePhase", "newIbGib", "mut8Timeline", "delay", "firstStimulus", "getTimestampInTicks", "interactions", "topN", "responses_string", "x", "responses_docId", "getUUID", "stimuli_string", "stimuli_docId", "engine", "AnalysisEngine", "DEFAULT_TOKEN_CONSTRUCT_RULE", "analyzer", "CorpusAnalyzer", "responses_analysis", "responses_report", "stimuli_analysis", "stimuli_report", "comparison", "elapsedMs_toLastInteractionResponse", "elapsedMs_toLastInteractionStimulus", "elapsedMs_toNow", "elapsedErrors", "getElapsedInfo", "elapsedMs", "wpm", "getWpm", "numberCorrect", "fnGetAgentsOpinion", "agentsOpinion", "asNumber", "interaction", "stats", "toHoursMinutesSeconds", "screenCompleteEl", "summaryStatsEl", "pre", "pretty", "opts", "getGlobalMetaspace_waitIfNeeded", "shadowRoot", "headerEl", "nameEl", "descEl", "commandBarEl", "contentEl", "shadowRoot_getElementById", "screenInitEl", "initAllStimuliEl", "initAddStimulusBtnEl", "initTranslateLinkEl", "initPlayableEl", "initGameTypeEl", "screenReadyEl", "readyCountdownEl", "screenPlayingEl", "screenAbortedEl", "stimulusEl", "footerEl", "inputEl", "inputSendBtnEl", "event", "newStimulusText", "newStimuli", "newLines", "line", "newStimulus", "getNewTypingEntryId", "minigameBuilderEditStimuliFunctionInfo", "resReady", "minigameBuilderValidateAndReadyFunctionInfo", "alertUser", "inputText", "nextStimulus", "ibGib", "data", "typingMeta", "DEFAULT_TYPING_GAMEMETA", "typingGameState", "DEFAULT_TYPING_GAMESTATE", "allStimuli", "allStimuliText", "unique", "getGoogleTranslateLink", "stimulusEntry", "entryEl", "deleteBtnEl", "editBtnEl", "getStimulusEntryEl", "noEntriesEl", "currentStimulus", "variant", "MinigameGameVariant_Typing", "templateId", "templateRootDiv", "stimulusTextDiv", "lineEl", "stimTextEl", "diffEl", "lastLength", "pTagEls", "pCurrent", "fnRevealDiff", "debounce", "expectedResponse", "inputSoFarLength", "durationMs", "highlightElement", "slideRightAndFade", "unfadeEl", "inputAsChars", "expectedResponseAsChars", "expectedChar", "inputChar", "charSpan", "i", "elements", "gameState", "promptForText", "clone", "screenMap", "screen", "dialogErrors", "srcTextTextArea", "srcTextChanged", "newText", "fnSrcIbGibIsInvalid", "errorMsg", "fnSrcIbGibIsValid", "fnGetSrc_latest", "addr", "lcGetSrc", "space", "latestAddr", "resGet", "emsg", "srcAddrInput", "fnSrcAddrChanged", "srcAddr", "srcAddrErrors", "validateIbGibAddr", "srcIbGibOrEmsg", "srcIbGib_latest", "promptForConfirm", "getIbAndGib", "getIbGibAddr", "MINIGAME_FOCUS_INFO", "languageDetailsDiv", "languageOptionsCheckboxEl", "srcLanguageEl", "targetLanguageEl", "fnUpdateSrcAndTargetLanguage", "languageCode", "checkboxing", "fnHandleAutoTranslateCheckboxInput", "srcLanguage", "DEFAULT_ISO_639_LANGUAGE_CODES", "MINIGAME_STIMULTI_TO_ADD_INFO", "fnAddStimuliToMinigame", "focusInfo", "containerEl", "info", "focusLevelEl", "focusNumberEl", "existingStimuli", "focusRandomize", "focusNumberToAdd", "someFocusText", "getAnotherFocusText", "dialogFocus", "getFocusAndElementsInfo", "stimuli", "focusesDivEl", "inputParrot", "inputFitb", "tokenInfo", "uniqueTokens", "availableVariants", "pickRandom", "stimulusText", "expectedResponseType", "ExpectedResponseType", "blankedText", "regex", "resolve", "_reject", "dialog", "dialogBody", "okButton", "cancelButton", "dialogSrcAddrEl", "dialogSrcTextEl", "focusesDiv", "stimuliDiv", "fnResetDialog", "removeEventListeners", "onOK", "onCancel", "onClose", "contextAddr", "manualInputEvent", "logalot", "GLOBAL_LOG_A_LOT", "Metronome", "_Metronome", "info", "bpm", "frequency", "duration", "volume", "audioCtx", "__name", "#isTicking", "lc", "delay", "error", "extractErrorMsg", "oscillator", "gainNode", "logalot", "GLOBAL_LOG_A_LOT", "MINIGAME_COMPONENT_NAME", "MinigameComponentMeta", "_MinigameComponentMeta", "IbGibDynamicComponentMetaBase", "__name", "getComponentCtorArg", "MinigameComponentInstance", "path", "ibGibAddr", "lc", "component", "minigame_default", "root_default", "styles_default", "error", "extractErrorMsg", "_MinigameComponentInstance", "IbGibDynamicComponentInstanceBase", "addr", "ibGib", "getIbGibAddr", "getTjpAddr", "isMinigameIbGib_V1", "data", "componentSvc", "getComponentSvc", "typingComponent", "TYPING_COMPONENT_NAME", "minigameComponentDivEl", "opts", "getGlobalMetaspace_waitIfNeeded", "minigameSettings", "shadowRoot", "headerEl", "shadowRoot_getElementById", "timerEl", "contentEl", "nameEl", "minigameInstructionsBtnEl", "event", "alertUser", "maximizeBtnEl", "getAppShellSvc", "pauseScreenEl", "footerEl", "metronomeBpmEl", "metronomeBtnEl", "pauseBtnEl", "playBtnEl", "abortBtnEl", "nextGameBtnEl", "restartBtnEl", "Metronome", "bpmStr", "bpm", "MinigameGamePhase", "promptForConfirm", "currentProjectComponent", "getCurrentActiveProjectComponent", "projectIbGib", "nextIndex", "minigameAddrs", "MINIGAME_REL8N_NAME", "currentMinigameIndex", "gib", "getIbAndGib", "tjpGib", "GIB_DELIMITER", "nextMinigameAddr", "sectionName_default", "getSectionName", "SettingsType", "sectionName_current", "_newSettings", "mut8Timeline", "getSettingsSection", "elements", "gamePhase", "#timerInterval", "#timerValueInSeconds", "runningTotalSeconds", "hours", "minutes", "seconds", "formattedTime", "AGENT_AVAILABLE_FUNCTIONS_MINIGAMEAGENT", "AGENT_SPECIAL_IBGIB_TYPE_MINIGAMEAGENT", "AGENT_GOAL_MINIGAMEAGENT", "AGENT_GOAL_COMMON", "AGENT_INITIAL_SYSTEM_TEXT_MINIGAMEAGENT", "AGENT_INITIAL_SYSTEM_SUPER_COOL", "AGENT_SYSTEM_PROMPT_COMMON_INSTRUCTIONS", "AGENT_WEBSITE_DESCRIPTION", "AGENT_INITIAL_CHAT_HI_PLEASEINTRO_YOURSELF_MINIGAMEAGENT", "AGENT_INITIAL_CHAT_GIVESELFNAME", "AGENT_INITIAL_CHAT_TEXT_MINIGAMEAGENT", "logalot", "GLOBAL_LOG_A_LOT", "FUNCTION_NAME", "CMD_CATEGORY", "CMD_MODIFIERS", "EXAMPLE_INPUT_MINIGAMEBUILDER_START", "MinigameGameType", "EXAMPLE_INPUT_MINIGAMEBUILDER_START_ANTIPHONY", "EXAMPLE_INPUT_MINIGAMEBUILDER_START_FITB", "EXAMPLES", "FUNCTION_CALL_EXAMPLES_HEADER", "pretty", "FUNCTION_DESCRIPTION", "minigameBuilderStartViaCmd", "opts", "lc", "commandService", "getCommandService", "command", "resolve", "reject", "error", "extractErrorMsg", "__name", "minigameBuilderStartImpl", "metaspace", "getGlobalMetaspace_waitIfNeeded", "contextAddr", "addrErrors", "validateIbGibAddr", "isPrimitive", "getIbAndGib", "space", "name", "description", "instructions", "gameType", "gameVariant", "keywords", "minigameIbGib", "createMinigameIbGib", "DEFAULT_MINIGAME_DATA_V1", "getTjpAddr", "minigameTjpGib", "newAgentIbGib", "getAgentsSvc", "GEMINI_DEFAULT_MODEL_STR", "clone", "AGENT_AVAILABLE_FUNCTIONS_MINIGAMEAGENT", "AGENT_INITIAL_SYSTEM_TEXT_MINIGAMEAGENT", "AGENT_INITIAL_CHAT_TEXT_MINIGAMEAGENT", "getDefaultFnGetAPIKey", "AGENT_SPECIAL_IBGIB_TYPE_MINIGAMEAGENT", "registerDomainIbGibWithAgentIndex", "latestContextIbGib", "latestContextAddr", "resGetLatest", "newContextIbGib", "appendToTimeline", "MINIGAME_REL8N_NAME", "minigameAddr", "minigameBuilderStartFunctionInfo", "COMMAND_BASE_SCHEMA_PROPERTIES", "GEMINI_SCHEMA_MINIGAME_CONTEXT_ADDR", "GEMINI_SCHEMA_MINIGAME_NAME", "GEMINI_SCHEMA_MINIGAME_DESCRIPTION", "GEMINI_SCHEMA_MINIGAME_INSTRUCTIONS", "GEMINI_SCHEMA_MINIGAME_GAMETYPE", "GEMINI_SCHEMA_MINIGAME_KEYWORDS", "logalot", "GLOBAL_LOG_A_LOT", "PROJECT_COMPONENT_NAME", "ProjectComponentMeta", "_ProjectComponentMeta", "IbGibDynamicComponentMetaBase", "__name", "getComponentCtorArg", "ProjectComponentInstance", "path", "ibGibAddr", "lc", "component", "project_default", "root_default", "styles_default", "error", "extractErrorMsg", "_ProjectComponentInstance", "IbGibDynamicComponentInstanceBase_ParentOfTabs", "SettingsType", "LensMode", "addr", "ibGib", "getIbGibAddr", "settings_current", "metaspace", "getGlobalMetaspace_waitIfNeeded", "resGet", "tjpAddr", "getTjpAddr", "modified", "sectionName_current", "getSectionName", "_newSettings", "mut8Timeline", "componentSvc", "getComponentSvc", "componentPath", "RAW_COMPONENT_NAME", "TEXTEDITOR_COMPONENT_NAME", "MINIGAME_COMPONENT_NAME", "tjpGib", "getGibInfo", "getIbAndGib", "tabInfo", "filtered", "x", "tabBtnEl", "span", "title", "desc", "MAX_TAB_TEXT_LENGTH", "titleText", "getSaferSubstring", "textNode", "headerTabsEl", "childBtnEl", "punctiliarColor", "punctiliarColorTranslucent", "tjpColor", "tjpColorTranslucent", "tjpColorContrast", "errorMsg", "getDeterministicColorInfo", "getColorStrings", "closeBtnEl", "event", "fnObs", "updateInfo", "opts", "askForPersistStorage", "settings", "childIbGib", "isMinigameIbGib_V1", "shadowRoot", "headerEl", "shadowRoot_getElementById", "addBtnEl", "addPopoverEl", "addPopoverOptions", "option", "optionType", "ellipsisBtnEl", "ellipsisPopoverEl", "ellipsisPopoverOptions", "emsg", "alertUser", "contentEl", "footerEl", "lensBarEl", "rawLensBtnEl", "textLensBtnEl", "minigameLensBtnEl", "projectSettings", "sectionName_default", "lensBtn", "lensMode", "btn", "skipInject", "name", "promptForText", "space", "activeTabIbGib", "activeTjpAddr", "resNewMinigame", "minigameBuilderStartFunctionInfo", "latestMinigameAddr", "commentIbGib", "createCommentIbGib", "getTimestampInTicks", "newAgentIbGib", "getAgentsSvc", "GEMINI_DEFAULT_MODEL_STR", "clone", "AGENT_AVAILABLE_FUNCTIONS_PROJECTCHILDTEXTAGENT", "AGENT_INITIAL_SYSTEM_TEXT_PROJECTCHILDTEXTAGENT", "AGENT_INITIAL_CHAT_TEXT_PROJECTCHILDTEXTAGENT", "getDefaultFnGetAPIKey", "AGENT_SPECIAL_IBGIB_TYPE_PROJECTCHILDTEXTAGENT", "registerDomainIbGibWithAgentIndex", "isProjectIbGib_V1", "appendToTimeline", "PROJECT_CHILD_TEXT_REL8N_NAME", "chronologysComponent", "getIbGibGlobalThis_Common", "count", "delay", "copyToClipboard", "highlightElement", "compress", "AGENT_AVAILABLE_FUNCTIONS_PROJECTAGENT", "getIbGibGlobalThis_BlankGib", "AGENT_GOAL_PROJECTSAGENT", "AGENT_INITIAL_SYSTEM_TEXT_PROJECTSAGENT", "AGENT_SYSTEM_PROMPT_COMMON_INSTRUCTIONS", "AGENT_INITIAL_CHAT_TEXT_PROJECTSAGENT", "AGENT_INITIAL_CHAT_HI_PLEASEINTRO_YOURSELF", "logalot", "GLOBAL_LOG_A_LOT", "AGENT_SPECIAL_IBGIB_TYPE_PROJECTSAGENT", "AGENT_AVAILABLE_FUNCTIONS_PROJECTSAGENT", "tellUserFunctionInfo", "PROJECTS_COMPONENT_NAME", "ProjectsComponentMeta", "_ProjectsComponentMeta", "IbGibDynamicComponentMetaBase", "__name", "getComponentCtorArg", "ProjectsComponentInstance", "path", "ibGibAddr", "lc", "component", "projects_default", "root_default", "styles_default", "error", "extractErrorMsg", "_ProjectsComponentInstance", "IbGibDynamicComponentInstanceBase_ParentOfTabs", "x", "SettingsType", "opts", "getGlobalMetaspace_waitIfNeeded", "gib", "getIbAndGib", "isPrimitive", "globalBlankGib", "getIbGibGlobalThis_BlankGib", "projectSpaceId", "initialCommentText", "srcIbGibAddr", "space", "srcCommentIbGib", "resGetSrc", "isComment", "name", "promptForText", "PROJECT_NAME_REGEXP", "alertUser", "pickRandom_Letters", "projectIbGib", "createProjectIbGib", "DEFAULT_PROJECT_DESCRIPTION", "projectAddr", "getIbGibAddr", "newAgentIbGib", "getAgentsSvc", "GEMINI_DEFAULT_MODEL_STR", "clone", "AGENT_AVAILABLE_FUNCTIONS_PROJECTAGENT", "AGENT_INITIAL_SYSTEM_TEXT_PROJECTAGENT", "AGENT_INITIAL_CHAT_TEXT_PROJECTAGENT", "AGENT_SPECIAL_IBGIB_TYPE_PROJECTAGENT", "registerDomainIbGibWithAgentIndex", "ibGib", "tjpGib", "getGibInfo", "filtered", "xTjpGib", "addBtnEl", "addr", "isProjectIbGib_V1", "projectAgent", "getAgentForDomainIbGib", "simpleIbGibRouterSingleton", "appShellSvc", "getAppShellSvc", "delay", "CHAT_WITH_AGENT_PLACEHOLDER_PROJECTAGENT", "fnCreateAndLoadProjectComponent", "projectComponent", "getComponentSvc", "PROJECT_COMPONENT_NAME", "projectTabInfo", "tabBtnEl", "headerTabsEl", "tjpAddr", "getTjpAddr", "span", "punctiliarColor", "punctiliarColorTranslucent", "tjpColor", "tjpColorContrast", "tjpColorTranslucent", "errorMsg", "getDeterministicColorInfo", "getColorStrings", "event", "fnObs", "updateInfo", "tabInfo", "title", "desc", "MAX_TAB_TEXT_LENGTH", "getSaferSubstring", "headerEl", "shadowRoot_getElementById", "contentEl", "pContent", "footerEl", "ellipsisBtnEl", "ellipsisPopoverEl", "ellipsisPopoverOptions", "option", "optionType", "emsg", "compress", "copyToClipboard", "highlightElement", "agent", "agents", "getAgents", "AGENT_INITIAL_SYSTEM_TEXT_PROJECTSAGENT", "AGENT_INITIAL_CHAT_TEXT_PROJECTSAGENT", "storageGet", "BLANK_GIB_DB_NAME", "ARMY_STORE", "BEE_KEY", "breadcrumbComponent", "breadcrumb_default", "breadcrumb_default", "logalot", "GLOBAL_LOG_A_LOT", "BREADCRUMB_COMPONENT_NAME", "BreadcrumbComponentMeta", "_BreadcrumbComponentMeta", "IbGibDynamicComponentMetaBase", "__name", "getComponentCtorArg", "BreadcrumbComponentInstance", "path", "ibGibAddr", "lc", "component", "breadcrumb_default", "root_default", "styles_default", "error", "extractErrorMsg", "_BreadcrumbComponentInstance", "IbGibDynamicComponentInstanceBase", "opts", "shadowRoot", "componentEl", "i", "breadcrumb", "delim", "link", "e", "text", "breadcrumbIndex", "info", "clear", "input_default", "input_default", "PARAM_PREFIXES", "getParam_src", "paramName", "noBare", "argTypeName", "description", "rcliParam", "x", "__name", "getParam_dest", "PARAM_INFO_BARE", "PARAM_INFO_HELP", "PARAM_INFO_DRY_RUN", "PARAM_INFO_DATA_PATH", "PARAM_INFO_INPUT_PATH", "PARAM_INFO_OUTPUT_PATH", "PARAM_INFO_DATA_STRING", "PARAM_INFO_DATA_INTEGER", "PARAM_INFO_DATA_BOOLEAN", "PARAM_INFO_NAME", "COMMON_PARAM_INFOS", "PARAM_INFO_ENCRYPT", "PARAM_INFO_DECRYPT", "PARAM_INFO_STRENGTH", "PARAM_INFO_SALT", "PARAM_INFO_INDEXING_MODE", "PARAM_INFO_BLOCKMODE_FLAG", "PARAM_INFO_BLOCKMODE_BLOCK_SIZE", "PARAM_INFO_BLOCKMODE_NUM_OF_PASSES", "PARAM_INFO_HASH_ALGORITHM", "PARAM_INFO_SALT_STRATEGY", "PARAM_INFO_INITIAL_RECURSIONS", "PARAM_INFO_RECURSIONS_PER_HASH", "PARAM_INFOS", "COMMON_PARAM_INFOS", "CHAT_WITH_AGENT_PLACEHOLDER_SUBMITKEYSTROKE", "CHAT_WITH_AGENT_PLACEHOLDER_AGENT", "CHAT_WITH_AGENT_PLACEHOLDER_PRIMARYAGENT", "CHAT_WITH_AGENT_NEED_API_KEY", "DEFAULT_PROMPT_TEMPLATE", "DEFAULT_COMMAND_ESCAPE_STRING", "BlankCanvasCommand", "RCLI_COMMANDS", "B2TFS_CMD_PREFIXES", "fnGetB2PrefixedVariants", "__name", "cmdOrSynonymBase", "prefix", "RCLI_COMMAND_SYNONYMS", "RCLI_COMMAND_IDENTIFIERS", "x", "RCLI_COMMAND_PARAM_INFOS", "agg", "cmdName", "PARAM_INFO_SRC_NAME", "getParam_src", "PARAM_PREFIXES", "PARAM_INFO_SRC_ALIAS", "PARAM_INFO_DEST_ALIAS", "getParam_dest", "PARAM_INFO_SRC_ADDR", "PARAM_INFO_SRC_ID", "PARAM_INFO_DEST_ADDR", "PARAM_INFO_DEST_ID", "PARAM_INFO_DEST_NAME", "PARAM_INFO_INIT", "PARAM_INFO_FORK", "PARAM_INFO_MUT8", "PARAM_INFO_REL8", "PARAM_INFO_QUIT", "PARAM_INFO_CWD", "PARAM_INFO_ADD_COMMENT", "PARAM_INFO_SECRET", "PARAM_INFO_ENCRYPTION", "PARAM_INFO_SYNC", "PARAM_INFO_VERSION", "PARAM_INFO_LIST_CHAT", "PARAM_INFO_CREATE_STONE", "PARAM_INFO_REIFY_FILE", "PARAM_INFO_GENERATE_SOURCE_FILE", "PARAM_INFO_INFO", "PARAM_INFO_EXPORT", "PARAM_INFO_IMPORT", "PARAM_INFO_SPACE", "PARAM_INFO_B2TFS_INIT", "PARAM_INFO_B2TFS_BRANCH", "PARAM_INFO_B2TFS_ACTIVATE_BRANCH", "PARAM_INFO_B2TFS_INFO", "PARAM_INFO_B2TFS_DIFF", "PARAM_INFO_B2TFS_SYNC", "PARAM_INFO_INSPECT", "PARAM_INFO_IB", "PARAM_INFO_ADD_ADDR", "PARAM_INFO_RM_ADDR", "PARAM_INFO_TJP", "PARAM_INFO_SPECIAL", "PARAM_INFO_CLONE_DATA", "PARAM_INFO_CLONE_REL8NS", "PARAM_INFO_DATA_TO_RENAME", "PARAM_INFO_DATA_TO_REMOVE", "PARAM_INFO_DATA_TO_ADD_OR_PATCH", "PARAM_INFO_REL8NS_TO_ADD", "PARAM_INFO_REL8NS_TO_REMOVE", "PARAM_INFO_TEXT", "PARAM_INFO_BOOTSTRAP_PATH", "PARAM_INFO_SPACE_NAME", "PARAM_INFO_SPACE_ID", "PARAM_INFO_LOCAL_SPACE_ID", "PARAM_INFO_LOCAL_SPACE_NAME", "PARAM_INFO_OUTER_SPACE_ID", "PARAM_INFO_OUTER_SPACE_NAME", "PARAM_INFO_APP_ID", "PARAM_INFO_SPACE_TYPE", "PARAM_INFO_SPACE_SUBTYPE", "PARAM_INFO_SECRET_TYPE", "PARAM_INFO_SECRET_NAME", "PARAM_INFO_SECRET_INPUT_PATH", "PARAM_INFO_METHOD", "PARAM_INFO_ENCRYPTION_NAME", "PARAM_INFO_LATEST", "PARAM_INFO_AWS_DYNAMODB_SYNC_SPACE", "PARAM_INFO_IN_MEMORY", "PARAM_INFO_INTERACTIVE", "PARAM_INFO_FILE_ENCODING", "PARAM_INFO_PRETTY", "PARAM_INFO_VERBOSE", "PARAM_INFO_YES", "PARAM_INFO_DESCRIPTION", "PARAM_INFO_HINT", "PARAM_INFO_BINARY", "PARAM_INFO_WITNESS", "PARAM_INFO_APP", "PARAM_INFO_NO_RESPEC", "PARAM_INFO_APPLY", "PARAM_INFO_BRIEF", "PARAM_INFO_ADD", "PARAM_INFO_FS_ONLY", "PARAM_INFO_FORCE", "PARAM_INFO_PROMPT", "PARAM_INFO_MOVE", "CUSTOMIZED_COMMON_PARAM_INFOS", "clone", "COMMON_PARAM_INFOS", "x", "PARAM_INFOS", "PARAM_INFO_ENCRYPT", "PARAM_INFO_DECRYPT", "PARAM_INFO_SALT", "PARAM_INFO_INDEXING_MODE", "PARAM_INFO_BLOCKMODE_FLAG", "PARAM_INFO_BLOCKMODE_BLOCK_SIZE", "PARAM_INFO_BLOCKMODE_NUM_OF_PASSES", "PARAM_INFO_HASH_ALGORITHM", "PARAM_INFO_SALT_STRATEGY", "PARAM_INFO_INITIAL_RECURSIONS", "PARAM_INFO_RECURSIONS_PER_HASH", "PARAM_INFO_INIT", "PARAM_INFO_FORK", "PARAM_INFO_MUT8", "PARAM_INFO_REL8", "PARAM_INFO_QUIT", "PARAM_INFO_CWD", "PARAM_INFO_ADD_COMMENT", "PARAM_INFO_SECRET", "PARAM_INFO_ENCRYPTION", "PARAM_INFO_SYNC", "PARAM_INFO_VERSION", "PARAM_INFO_LIST_CHAT", "PARAM_INFO_CREATE_STONE", "PARAM_INFO_REIFY_FILE", "PARAM_INFO_GENERATE_SOURCE_FILE", "PARAM_INFO_INFO", "PARAM_INFO_EXPORT", "PARAM_INFO_IMPORT", "PARAM_INFO_SPACE", "PARAM_INFO_B2TFS_INIT", "PARAM_INFO_B2TFS_BRANCH", "PARAM_INFO_B2TFS_ACTIVATE_BRANCH", "PARAM_INFO_B2TFS_INFO", "PARAM_INFO_B2TFS_DIFF", "PARAM_INFO_B2TFS_SYNC", "PARAM_INFO_IN_MEMORY", "PARAM_INFO_INTERACTIVE", "PARAM_INFO_BINARY", "PARAM_INFO_WITNESS", "PARAM_INFO_APP", "PARAM_INFO_SRC_NAME", "PARAM_INFO_SRC_ADDR", "PARAM_INFO_DEST_ADDR", "PARAM_INFO_IB", "PARAM_INFO_ADD_ADDR", "PARAM_INFO_RM_ADDR", "PARAM_INFO_TEXT", "PARAM_INFO_SPACE_NAME", "PARAM_INFO_SPACE_ID", "PARAM_INFO_LOCAL_SPACE_NAME", "PARAM_INFO_LOCAL_SPACE_ID", "PARAM_INFO_OUTER_SPACE_NAME", "PARAM_INFO_OUTER_SPACE_ID", "PARAM_INFO_APP_ID", "PARAM_INFO_SPACE_TYPE", "PARAM_INFO_SPACE_SUBTYPE", "PARAM_INFO_SECRET_TYPE", "PARAM_INFO_SECRET_NAME", "PARAM_INFO_SECRET_INPUT_PATH", "PARAM_INFO_METHOD", "PARAM_INFO_ENCRYPTION_NAME", "PARAM_INFO_TJP", "PARAM_INFO_SPECIAL", "PARAM_INFO_CLONE_DATA", "PARAM_INFO_CLONE_REL8NS", "PARAM_INFO_DATA_TO_RENAME", "PARAM_INFO_DATA_TO_REMOVE", "PARAM_INFO_DATA_TO_ADD_OR_PATCH", "PARAM_INFO_REL8NS_TO_ADD", "PARAM_INFO_REL8NS_TO_REMOVE", "PARAM_INFO_LATEST", "PARAM_INFO_AWS_DYNAMODB_SYNC_SPACE", "PARAM_INFO_SRC_ID", "PARAM_INFO_DEST_ID", "PARAM_INFO_DEST_NAME", "PARAM_INFO_BOOTSTRAP_PATH", "PARAM_INFO_FILE_ENCODING", "PARAM_INFO_PRETTY", "PARAM_INFO_VERBOSE", "PARAM_INFO_YES", "PARAM_INFO_DESCRIPTION", "PARAM_INFO_HINT", "PARAM_INFO_INSPECT", "logalot", "GLOBAL_LOG_A_LOT", "INPUT_COMPONENT_NAME", "InputComponentMeta", "_InputComponentMeta", "IbGibDynamicComponentMetaBase", "__name", "getComponentCtorArg", "InputComponentInstance", "path", "ibGibAddr", "lc", "component", "input_default", "root_default", "styles_default", "error", "extractErrorMsg", "DEFAULT_INPUT_INFO", "_InputComponentInstance", "IbGibDynamicComponentInstanceBase", "opts", "getGlobalMetaspace_waitIfNeeded", "shadowRoot", "componentEl", "inputTextEl", "inputSendBtnEl", "event", "punctiliarColor", "punctiliarColorTranslucent", "tjpColor", "tjpColorTranslucent", "errorMsg", "getDeterministicColorInfo", "agent", "contextProxyIbGib", "inputText", "spaceId", "metaspace", "storageGet", "BLANK_GIB_DB_NAME", "ARMY_STORE", "BEE_KEY", "space", "text", "addlMetadataText", "getAddlMetadataTextForAgentText", "commentIbGib", "createCommentIbGib", "appendToTimeline", "texts", "fnSubmitToAgent", "pretty", "_", "ROOT", "resAPIKey", "promptForAPIKey", "CHAT_WITH_AGENT_NEED_API_KEY", "updateAPIKeyInStorage", "info", "delay", "chronologys_default", "chronologys_default", "chronology_default", "chronology_default", "logalot", "GLOBAL_LOG_A_LOT", "AGENT_GOAL_CHRONOLOGYAGENT", "AGENT_GOAL_COMMON", "AGENT_INITIAL_SYSTEM_TEXT_CHRONOLOGYAGENT", "AGENT_SYSTEM_PROMPT_COMMON_INSTRUCTIONS", "AGENT_INITIAL_CHAT_TEXT_CHRONOLOGYAGENT", "AGENT_INITIAL_CHAT_HI_PLEASEINTRO_YOURSELF", "CHRONOLOGY_COMPONENT_NAME", "ChronologyComponentMeta", "_ChronologyComponentMeta", "IbGibDynamicComponentMetaBase", "__name", "getComponentCtorArg", "ChronologyComponentInstance", "path", "ibGibAddr", "lc", "logalot", "component", "chronology_default", "root_default", "styles_default", "error", "extractErrorMsg", "_ChronologyComponentInstance", "IbGibDynamicComponentInstanceBase", "opts", "contentEl", "excludeRel8nNames", "rel8nNames", "x", "childAddrs", "rel8nName", "rel8dAddrs", "childIbGibs", "childAddr", "resGet", "a", "b", "aRes", "getTimestampInfo", "aTicks", "bRes", "bTicks", "childIbGib", "errored", "itemElement", "ID_PRIMARY_AGENT_CHAT_LOG", "pretty", "ibGib", "resEl", "isComment", "isMinigameIbGib_V1", "text", "ib", "safeIbCommentMetadataText", "parseCommentIb", "textSrc", "parseAddlMetadataTextForAgentText", "who", "timestampInfo", "timestampString", "timestampParagraph", "chatEntry", "identityInfoDiv", "identityInfoP", "agentName", "textContentDiv", "textParagraph", "pElement", "copyButton", "e", "feedbackSpan", "delay", "clicked", "name", "iElement", "globalBlankGib", "getIbGibGlobalThis_BlankGib", "projectsComponent", "projectComponent", "getIbGibAddr", "shadowRoot", "headerEl", "textEl", "descEl", "footerEl", "simpleIbGibRouterSingleton", "description", "metaspace", "getGlobalMetaspace_waitIfNeeded", "agent", "agentsSvc", "getAgentsSvc", "agents", "AGENT_SPECIAL_IBGIB_TYPE_PRIMARYAGENT", "logalot", "GLOBAL_LOG_A_LOT", "AGENT_SPECIAL_IBGIB_TYPE_CHRONOLOGYSAGENT", "AGENT_AVAILABLE_FUNCTIONS_CHRONOLOGYSAGENT", "tellUserFunctionInfo", "AGENT_GOAL_CHRONOLOGYSAGENT", "AGENT_INITIAL_SYSTEM_TEXT_CHRONOLOGYSAGENT", "AGENT_SYSTEM_PROMPT_COMMON_INSTRUCTIONS", "CHRONOLOGYS_COMPONENT_NAME", "ChronologysComponentMeta", "_ChronologysComponentMeta", "IbGibDynamicComponentMetaBase", "__name", "getComponentCtorArg", "ChronologysComponentInstance", "path", "ibGibAddr", "lc", "component", "chronologys_default", "root_default", "styles_default", "error", "extractErrorMsg", "_ChronologysComponentInstance", "IbGibDynamicComponentInstanceBase_ParentOfTabs", "SettingsType", "opts", "getGlobalMetaspace_waitIfNeeded", "isPrimitive", "getIbAndGib", "info", "simpleIbGibRouterSingleton", "getIbGibAddr", "gib", "web1CommentIbGib", "counter", "web1CommentIbGibProxy", "getIbGibGlobalThis_BlankGib", "delay", "isProjectIbGib_V1", "chronologysSettings", "existing", "getDefaultSettings", "addr", "ibGib", "space", "spaceId", "execInSpaceWithLocking", "borderColor", "interval", "childTabInfo", "getAppShellSvc", "CHAT_WITH_AGENT_PLACEHOLDER_AGENT", "AGENT_AVAILABLE_FUNCTIONS_PROJECTAGENT", "AGENT_AVAILABLE_FUNCTIONS_PROJECTCHILDTEXTAGENT", "resGet", "tjpAddr", "getTjpAddr", "modified", "sectionName_current", "getSectionName", "_newSettings", "mut8Timeline", "tabInfoSharesTjpGib", "tabInfo", "tabGib", "getGibInfo", "tjpGib", "fnCreateAndLoadChronologyComponent", "getComponentSvc", "CHRONOLOGY_COMPONENT_NAME", "x", "filtered", "childBtnEl", "headerTabsEl", "addr_tjpGib", "ibGib_addr", "ibGib_tjpGib", "punctiliarColor", "punctiliarColorTranslucent", "tjpColor", "tjpColorTranslucent", "tjpColorContrast", "errorMsg", "getDeterministicColorInfo", "closeBtnEl", "event", "fnObs", "updateInfo", "span", "title", "desc", "MAX_TAB_TEXT_LENGTH", "getSaferSubstring", "tabSpan", "headerEl", "shadowRoot_getElementById", "busyEl", "contentEl", "pContent", "footerEl", "agent", "agents", "getAgents", "getAgentsSvc", "GEMINI_DEFAULT_MODEL_STR", "AGENT_INITIAL_CHAT_HI_PLEASEINTRO_YOURSELF", "getDefaultFnGetAPIKey", "projects_explorer_default", "projects_explorer_default", "explorer_item_default", "explorer_item_default", "logalot", "GLOBAL_LOG_A_LOT", "EXPLORERITEM_COMPONENT_NAME", "ExplorerItemComponentMeta", "_ExplorerItemComponentMeta", "IbGibDynamicComponentMetaBase", "__name", "getComponentCtorArg", "ExplorerItemComponentInstance", "path", "ibGibAddr", "lc", "logalot", "component", "explorer_item_default", "root_default", "styles_default", "error", "extractErrorMsg", "_ExplorerItemComponentInstance", "IbGibDynamicComponentInstanceBase", "opts", "getGlobalMetaspace_waitIfNeeded", "shadowRoot", "headerEl", "shadowRoot_getElementById", "contentEl", "nameEl", "footerEl", "e", "ibGib", "ib", "gib", "data", "name", "maxLength", "labelText", "title", "link", "getPath", "logalot", "GLOBAL_LOG_A_LOT", "AGENT_SPECIAL_IBGIB_TYPE_PROJECTSAGENT", "AGENT_AVAILABLE_FUNCTIONS_PROJECTSAGENT", "tellUserFunctionInfo", "PROJECTS_EXPLORER_COMPONENT_NAME", "ProjectsExplorerComponentMeta", "_ProjectsExplorerComponentMeta", "IbGibDynamicComponentMetaBase", "__name", "getComponentCtorArg", "ProjectsExplorerComponentInstance", "path", "ibGibAddr", "lc", "component", "projects_explorer_default", "root_default", "styles_default", "error", "extractErrorMsg", "_ProjectsExplorerComponentInstance", "IbGibDynamicComponentInstanceBase_ParentOfTabs", "x", "SettingsType", "opts", "getGlobalMetaspace_waitIfNeeded", "globalBlankGib", "getIbGibGlobalThis_BlankGib", "shadowRoot", "projectList", "shadowRoot_getElementById", "addedGibs", "projectIbGibs", "getProjects", "projectIbGib", "projectAddr", "getIbGibAddr", "projectIb", "projectGib", "getIbAndGib", "projectName", "parseProjectIb", "liProject", "componentSvc", "getComponentSvc", "itemComponent", "EXPLORERITEM_COMPONENT_NAME", "addr", "ibGib", "tjpGib", "getGibInfo", "fnCreateAndLoadProjectComponent", "childComponent", "childInfo", "filtered", "projectComponent", "tabBtnEl", "tjpAddr", "getTjpAddr", "span", "punctiliarColor", "punctiliarColorTranslucent", "tjpColor", "tjpColorContrast", "tjpColorTranslucent", "errorMsg", "getDeterministicColorInfo", "getColorStrings", "event", "fnObs", "updateInfo", "tabInfo", "title", "desc", "MAX_TAB_TEXT_LENGTH", "getSaferSubstring", "headerEl", "contentEl", "projectListFilterEl", "fnApplyFilter_debounced", "debounce", "text", "target", "projectListEl", "pContent", "footerEl", "compress", "optionType", "copyToClipboard", "highlightElement", "alertUser", "agent", "agents", "getAgents", "getAgentsSvc", "GEMINI_DEFAULT_MODEL_STR", "AGENT_INITIAL_SYSTEM_TEXT_PROJECTSAGENT", "AGENT_INITIAL_CHAT_TEXT_PROJECTSAGENT", "getDefaultFnGetAPIKey", "about_default", "web1_common_default", "about_default", "UIAgentFunctionInfos", "updateCSSVariablesFunctionInfo", "AGENT_AVAILABLE_FUNCTIONS_PRIMARYAGENT", "ChatAPIFunctionInfos", "UIAgentFunctionInfos", "logalot", "GLOBAL_LOG_A_LOT", "Web1ComponentMetaBase", "_Web1ComponentMetaBase", "IbGibDynamicComponentMetaBase", "__name", "getComponentCtorArg", "path", "ibGibAddr", "lc", "component", "error", "extractErrorMsg", "Web1ComponentInstanceBase", "_Web1ComponentInstanceBase", "IbGibDynamicComponentInstanceBase", "opts", "delay", "getIbGibGlobalThis_BlankGib", "appShellSvc", "getAppShellSvc", "CHAT_WITH_AGENT_PLACEHOLDER_PRIMARYAGENT", "chronologysComponent", "count", "getIbGibAddr", "getGlobalMetaspace_waitIfNeeded", "metaspace", "agent", "agentsSvc", "getAgentsSvc", "agents", "AGENT_SPECIAL_IBGIB_TYPE_PRIMARYAGENT", "AGENT_AVAILABLE_FUNCTIONS_PRIMARYAGENT", "contextTjpAddr", "getTjpAddr", "TextSource", "taggifyForPrompt", "HARDCODED_PROMPT_TAG_TEXT", "ibgibGlobalThis", "space", "agentAddr", "commentIbGib", "createCommentIbGib", "getAddlMetadataTextForAgentText", "latestCommentIbGib", "appendToTimeline", "toDto", "proxy", "LiveProxyIbGib", "breadcrumbComponent", "asideElements", "focusOneAtATime_focusing", "focusQueue", "changeFocus", "el", "toUnblur", "delayMs", "highlightElement", "unhighlightElement", "i", "entries", "entry", "logalot", "GLOBAL_LOG_A_LOT", "WEB1_COMPONENT_NAME", "Web1ComponentMeta_About", "_Web1ComponentMeta_About", "Web1ComponentMetaBase", "__name", "WEB1_COMPONENT_NAME", "about_default", "root_default", "styles_default", "web1_common_default", "arg", "logalot", "Web1ComponentInstance_About", "_Web1ComponentInstance_About", "Web1ComponentInstanceBase", "blog_default", "blog_default", "logalot", "GLOBAL_LOG_A_LOT", "WEB1_COMPONENT_NAME", "Web1ComponentMeta_Blog", "_Web1ComponentMeta_Blog", "Web1ComponentMetaBase", "__name", "WEB1_COMPONENT_NAME", "blog_default", "root_default", "styles_default", "web1_common_default", "arg", "logalot", "Web1ComponentInstance_Blog", "_Web1ComponentInstance_Blog", "Web1ComponentInstanceBase", "contact_default", "contact_default", "logalot", "GLOBAL_LOG_A_LOT", "WEB1_COMPONENT_NAME", "Web1ComponentMeta_Contact", "_Web1ComponentMeta_Contact", "Web1ComponentMetaBase", "__name", "WEB1_COMPONENT_NAME", "contact_default", "root_default", "styles_default", "web1_common_default", "arg", "logalot", "Web1ComponentInstance_Contact", "_Web1ComponentInstance_Contact", "Web1ComponentInstanceBase", "faq_default", "faq_default", "logalot", "GLOBAL_LOG_A_LOT", "WEB1_COMPONENT_NAME", "Web1ComponentMeta_Faq", "_Web1ComponentMeta_Faq", "Web1ComponentMetaBase", "__name", "WEB1_COMPONENT_NAME", "faq_default", "root_default", "styles_default", "web1_common_default", "arg", "logalot", "Web1ComponentInstance_Faq", "_Web1ComponentInstance_Faq", "Web1ComponentInstanceBase", "funding_default", "funding_default", "logalot", "GLOBAL_LOG_A_LOT", "WEB1_COMPONENT_NAME", "Web1ComponentMeta_Funding", "_Web1ComponentMeta_Funding", "Web1ComponentMetaBase", "__name", "WEB1_COMPONENT_NAME", "funding_default", "root_default", "styles_default", "web1_common_default", "arg", "logalot", "Web1ComponentInstance_Funding", "_Web1ComponentInstance_Funding", "Web1ComponentInstanceBase", "lc", "jumpBtn", "highlightElement", "howToFund", "alertUser", "error", "extractErrorMsg", "home_default", "home_default", "logalot", "GLOBAL_LOG_A_LOT", "WEB1_COMPONENT_NAME", "Web1ComponentMeta_Home", "_Web1ComponentMeta_Home", "Web1ComponentMetaBase", "__name", "home_default", "root_default", "styles_default", "web1_common_default", "arg", "Web1ComponentInstance_Home", "_Web1ComponentInstance_Home", "Web1ComponentInstanceBase", "links_default", "links_default", "logalot", "GLOBAL_LOG_A_LOT", "WEB1_COMPONENT_NAME", "LINK_DATA", "Web1ComponentMeta_Links", "_Web1ComponentMeta_Links", "Web1ComponentMetaBase", "__name", "WEB1_COMPONENT_NAME", "links_default", "root_default", "styles_default", "web1_common_default", "arg", "logalot", "Web1ComponentInstance_Links", "COPY_ICON_SVG", "_Web1ComponentInstance_Links", "Web1ComponentInstanceBase", "lc", "container", "error", "extractErrorMsg", "group", "groupEl", "h2", "link", "entryEl", "e", "videoContainer", "iframe", "headerEl", "nameEl", "actionsEl", "copyBtn", "urlContainer", "a", "descEl", "text", "button", "originalContent", "err", "challenges_default", "challenges_default", "logalot", "GLOBAL_LOG_A_LOT", "WEB1_COMPONENT_NAME", "Web1ComponentMeta_Challenges", "_Web1ComponentMeta_Challenges", "Web1ComponentMetaBase", "__name", "WEB1_COMPONENT_NAME", "challenges_default", "root_default", "styles_default", "web1_common_default", "arg", "logalot", "Web1ComponentInstance_Challenges", "_Web1ComponentInstance_Challenges", "Web1ComponentInstanceBase", "about_projects_default", "about_projects_default", "logalot", "GLOBAL_LOG_A_LOT", "WEB1_COMPONENT_NAME", "Web1ComponentMeta_AboutProjects", "_Web1ComponentMeta_AboutProjects", "Web1ComponentMetaBase", "__name", "WEB1_COMPONENT_NAME", "about_projects_default", "root_default", "styles_default", "web1_common_default", "arg", "logalot", "Web1ComponentInstance_AboutProjects", "_Web1ComponentInstance_AboutProjects", "Web1ComponentInstanceBase", "componentsMeta_Web1", "Web1ComponentMeta_Home", "Web1ComponentMeta_Funding", "Web1ComponentMeta_About", "Web1ComponentMeta_Links", "Web1ComponentMeta_Contact", "Web1ComponentMeta_Blog", "Web1ComponentMeta_Challenges", "Web1ComponentMeta_Faq", "Web1ComponentMeta_AboutProjects", "WEB1_PAGES", "GEMINI_SCHEMA_WEB1_PAGE", "logalot", "GLOBAL_LOG_A_LOT", "AppShellService", "_AppShellService", "__name", "lc", "document_getElementById", "ID_APP_SHELL", "ID_HEADER_PANEL", "ID_HEADER_PANEL_CONTENT", "ID_IBGIB_COM_TITLE_LINK", "ID_PANEL_CONTAINER", "ID_LEFT_PANEL", "ID_LEFT_PANEL_HEADER", "ID_LEFT_PANEL_CONTENT", "ID_LEFT_PANEL_FOOTER", "ID_LEFT_PANEL_COLLAPSE_HANDLE", "ID_LEFT_PANEL_EXPAND_HANDLE", "ID_LEFT_PANEL_MAXIMIZE_HANDLE", "ID_RIGHT_PANEL", "ID_RIGHT_PANEL_CONTENT", "ID_CHRONOLOGYS_CONTENT", "ID_RIGHT_PANEL_HEADER", "ID_RIGHT_PANEL_FOOTER", "ID_RIGHT_PANEL_COLLAPSE_HANDLE", "ID_RIGHT_PANEL_EXPAND_HANDLE", "ID_RIGHT_PANEL_MAXIMIZE_HANDLE", "ID_FOOTER_PANEL", "ID_FOOTER_INPUT_CONTAINER", "ID_FOOTER_PANEL_COLLAPSE_HANDLE", "ID_FOOTER_PANEL_EXPAND_HANDLE", "ID_FOOTER_PANEL_MAXIMIZE_HANDLE", "ID_CENTER_PANEL_CONTENT", "error", "extractErrorMsg", "updateCenterPanelScrollHidesHeader", "headerPanelHeight", "oldScroll", "newScroll", "scaledHeight", "_entries", "ev", "event", "isClickInside", "ms", "leftPanels", "rightPanels", "footerPanels", "footerAlso", "web10TabButton", "projectExplorerTabButton", "RouterAppName", "chronologysTabButton", "headerPanel", "handleLocalSPAAnchorClick", "web10Nav", "ID_WEB_1_NAV", "tagNav", "ID_TAG_NAV", "lcPopstate", "isExecutingInBlankGibWebAppProper", "HTML_META_APP_ID_NAME", "HTML_META_APP_ID_CONTENT", "simpleIbGibRouterSingleton", "componentSvc", "breadcrumbComponent", "BREADCRUMB_COMPONENT_NAME", "ROOT_ADDR", "configBtnEl", "configPopoverEl", "configPopoverOptions", "widestWidth", "i", "optionEl", "delay", "option", "optionType", "existingApiKey", "getDefaultFnGetAPIKey", "existingApiKeyMasked", "getMaskedSecret", "promptForConfirm", "CONFIG_OPTION_GEMINI_API_KEY_LOCATION_HELP", "updateAPIKeyInStorage", "BLANK_GIB_DB_NAME", "ARMY_STORE", "BEE_KEY", "alertUser", "apiKey", "promptForAPIKey", "CHAT_WITH_AGENT_NEED_API_KEY", "projectsExplorerTabContent", "ID_PROJECT_EXPLORER_TAB_CONTENT", "explorerComponent", "PROJECTS_EXPLORER_COMPONENT_NAME", "chronologysComponent", "CHRONOLOGYS_COMPONENT_NAME", "globalIbGib", "getIbGibGlobalThis_BlankGib", "inputComponent", "INPUT_COMPONENT_NAME", "els", "el", "states", "panelName", "status", "ID_WEB10_TAB_BUTTON", "ID_PROJECT_EXPLORER_TAB_BUTTON", "ID_TAB_BUTTON_CHRONOLOGYS", "componentsMeta", "componentsMeta_Web1", "CanvasComponentMeta", "ProjectsComponentMeta", "ProjectComponentMeta", "ChronologysComponentMeta", "ChronologyComponentMeta", "BreadcrumbComponentMeta", "InputComponentMeta", "RawComponentMeta", "TextEditorComponentMeta", "MinigameComponentMeta", "TypingComponentMeta", "ProjectsExplorerComponentMeta", "ExplorerItemComponentMeta", "getComponentSvc", "componentMeta", "tutorial_panelsExpandAnimationCount", "storageGet", "KEY_TUTORIAL_PANELS_EXPAND_ANIMATION_COUNT", "TUTORIAL_PANELS_EXPAND_ANIMATION_COUNT_ENOUGH_ALREADY", "storagePut", "highlightElement", "resolve", "reject", "getGlobalMetaspace_waitIfNeeded", "existingUIInfo", "getExistingUIInfo", "variableName", "value", "panelNames", "pretty", "tabName", "web10TabContent", "ID_WEB10_TAB_CONTENT", "projectExplorerTabContent", "tabButtons", "tabContents", "tabButtonToShow", "btn", "contentToShow", "content", "ibGibAddr", "getAppShellSvc", "ibGibGlobalThis", "APP_CONFIG", "logalot", "GLOBAL_LOG_A_LOT", "DEFAULT_PATH_APPS_WEB1", "ROUTER_APP_NAME_WEB1", "WEB1_FILENAME_HOME", "getPath", "ibGibRouteInfo", "lc", "base", "appName", "gib", "ib", "path", "error", "extractErrorMsg", "__name", "parseRoute", "pathPieces", "x", "EXPECTED_PATH_SCHEMA", "base_shouldbeappsrightnow", "ibValidationErrors", "validateIb", "pretty", "GIB", "gibValidationErrors", "validateGib", "isValidRouterAppName", "VALID_ROUTER_APP_NAMES", "handleLocalSPAAnchorClick", "event", "href", "simpleIbGibRouterSingleton", "route", "isExecutingInBlankGibWebAppProper", "HTML_META_APP_ID_NAME", "HTML_META_APP_ID_CONTENT", "info", "ibGibAddr", "getIbGibAddr", "appShellSvc", "getAppShellSvc", "route_centerPanel", "route_leftPanel", "centerPanelContent", "document_getElementById", "ID_CENTER_PANEL_CONTENT", "componentSvc", "getComponentSvc", "componentToInject", "isPrimitive", "SimpleIbGibRouter", "_SimpleIbGibRouter", "__name", "parseRoute", "lc", "logalot", "route", "error", "extractErrorMsg", "path", "ibGibAddr", "replace", "currentPath", "currentPathInfo", "ib", "gib", "getIbAndGib", "ROOT_ADDR", "fullPath", "getPath", "simpleIbGibRouterSingleton"]
}
