@humain/humain-code 0.8.0 → 0.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +21 -0
- package/dist/bundle/chunks/{anthropic-messages-UZB5HJE3.js → anthropic-messages-XFCDMGD6.js} +4 -4
- package/dist/bundle/chunks/{azure-openai-responses-J3LCMWPQ.js → azure-openai-responses-F4KQM3NK.js} +3 -3
- package/dist/bundle/chunks/{chunk-7EONJCBE.js → chunk-2JNJJ6SZ.js} +1 -1
- package/dist/bundle/chunks/{chunk-WRYGY5XG.js → chunk-4MKATHT2.js} +1 -1
- package/dist/bundle/chunks/{chunk-ATFZAFMS.js → chunk-65FLSKDA.js} +1 -1
- package/dist/bundle/chunks/{chunk-CET2MXXN.js → chunk-6P6MMQUH.js} +1 -1
- package/dist/bundle/chunks/{chunk-CU6KU7JK.js → chunk-6TTMNQXI.js} +13 -13
- package/dist/bundle/chunks/{chunk-KQXXBQ57.js → chunk-6YVORXTX.js} +155 -125
- package/dist/bundle/chunks/{chunk-SQ7NTRLJ.js → chunk-7X6DNT45.js} +17 -16
- package/dist/bundle/chunks/{chunk-PGVDL4KB.js → chunk-CQ2CE3RB.js} +1 -1
- package/dist/bundle/chunks/{chunk-QRYDGY5I.js → chunk-DJG2WUNM.js} +1 -1
- package/dist/bundle/chunks/{chunk-R3VDXQW2.js → chunk-E7OBH44W.js} +5 -5
- package/dist/bundle/chunks/{chunk-4EV7CK26.js → chunk-F2H47FRF.js} +1 -1
- package/dist/bundle/chunks/chunk-FQ4KS5S4.js +23 -0
- package/dist/bundle/chunks/{chunk-TYN46EVI.js → chunk-GPLWWO5Q.js} +1 -1
- package/dist/bundle/chunks/{chunk-EMBIUIQ2.js → chunk-IMUFBWEK.js} +4 -4
- package/dist/bundle/chunks/{chunk-Z5UFSRO4.js → chunk-KI7CHPWC.js} +1 -1
- package/dist/bundle/chunks/{chunk-VKQNYZUA.js → chunk-KRBELWQH.js} +1 -1
- package/dist/bundle/chunks/{chunk-AI7EHDAX.js → chunk-LSRXA7OS.js} +1 -1
- package/dist/bundle/chunks/{chunk-XVIQYONJ.js → chunk-MIAXMK5F.js} +1 -1
- package/dist/bundle/chunks/{chunk-NNWNIBLG.js → chunk-NICPFMOP.js} +1 -1
- package/dist/bundle/chunks/{chunk-4SFWYKL5.js → chunk-P42E6YY6.js} +441 -415
- package/dist/bundle/chunks/{chunk-WGXMYMPE.js → chunk-PFBAIRCY.js} +2 -2
- package/dist/bundle/chunks/{chunk-OVDMYBIT.js → chunk-PWFM6AQQ.js} +1 -1
- package/dist/bundle/chunks/{chunk-JV7VHOAY.js → chunk-QRRVZYTG.js} +1 -1
- package/dist/bundle/chunks/{chunk-IOLLZXQN.js → chunk-ROFZVEFN.js} +125 -114
- package/dist/bundle/chunks/{chunk-C4DHVDYT.js → chunk-SXOIQWNX.js} +1 -1
- package/dist/bundle/chunks/{chunk-IXQYPQRQ.js → chunk-XZ7FTBXS.js} +1446 -1423
- package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-ETKC6B2S.js → cloudflare-workers-ai-system-one-JEZVYITT.js} +1 -1
- package/dist/bundle/chunks/{compat-HS4ARZK3.js → compat-SRCNS6OQ.js} +6 -6
- package/dist/bundle/chunks/{curator-server-TC7RVVN2.js → curator-server-QB4GITGS.js} +1 -1
- package/dist/bundle/chunks/{dist-5AQPJ2TI.js → dist-4OMLHRJE.js} +1 -1
- package/dist/bundle/chunks/{dist-NMEXYUP3.js → dist-CBODG4CA.js} +5 -5
- package/dist/bundle/chunks/{dist-DYB3AR7C.js → dist-TRAK7EXI.js} +7 -7
- package/dist/bundle/chunks/{extract-QHZTEVJP.js → extract-L373D6O7.js} +2 -2
- package/dist/bundle/chunks/{flow-implementer-QMN3HKE2.js → flow-implementer-4KO3Q4B5.js} +4 -4
- package/dist/bundle/chunks/github-copilot.js +53 -56
- package/dist/bundle/chunks/{google-generative-ai-ZND73WDQ.js → google-generative-ai-WIASMWS3.js} +2 -2
- package/dist/bundle/chunks/{google-vertex-YAH62YRM.js → google-vertex-WSPHRZIZ.js} +3 -3
- package/dist/bundle/chunks/{host-Q565BCXB.js → host-WOLZCWQQ.js} +1 -1
- package/dist/bundle/chunks/{inprocess-453SLFL5.js → inprocess-TOBRVK4C.js} +5 -5
- package/dist/bundle/chunks/{interactive-mode-MVZOJ5OU.js → interactive-mode-BJJKPBXD.js} +3 -3
- package/dist/bundle/chunks/{llama-cpp-classify-Z4GZY4GC.js → llama-cpp-classify-KYZT532X.js} +1 -1
- package/dist/bundle/chunks/{mistral-conversations-7I5JURDP.js → mistral-conversations-7JYDDRUT.js} +2 -2
- package/dist/bundle/chunks/{node-IMSYVRPL.js → node-N7TPBUJB.js} +1 -1
- package/dist/bundle/chunks/{openai-codex-responses-LTHOMN37.js → openai-codex-responses-7PAML4NF.js} +3 -3
- package/dist/bundle/chunks/{openai-completions-W2X635EE.js → openai-completions-UJDAIGTK.js} +3 -3
- package/dist/bundle/chunks/{openai-decisions-TN2GNOYI.js → openai-decisions-JMSDGR7K.js} +1 -1
- package/dist/bundle/chunks/{openai-responses-DVY4QXOG.js → openai-responses-2WNCE6AY.js} +3 -3
- package/dist/bundle/chunks/{openrouter-images-SE2JMS44.js → openrouter-images-V3UCCO6X.js} +1 -1
- package/dist/bundle/chunks/{pi-messages-WAS6Z5L5.js → pi-messages-TQ7LJUNQ.js} +2 -2
- package/dist/bundle/chunks/{session-picker-XNVLSJ22.js → session-picker-4JQEGLDD.js} +1 -1
- package/dist/bundle/chunks/{startup-ui-3TCT465D.js → startup-ui-AKTA4NDP.js} +1 -1
- package/dist/bundle/chunks/{typesafe-system-one-AAZH6S3I.js → typesafe-system-one-YP7GGN4C.js} +1 -1
- package/dist/bundle/chunks/{virtual-modules-CIVXCEAN.js → virtual-modules-3CT5BMBA.js} +8 -8
- package/dist/bundle/cli-runtime.js +5 -5
- package/dist/bundle/index.js +8 -8
- package/dist/bundle/rpc-entry.js +4 -4
- package/dist/cli/args.js +1 -1
- package/dist/cli/args.js.map +1 -1
- package/dist/cli/list-models.d.ts.map +1 -1
- package/dist/cli/list-models.js +16 -1
- package/dist/cli/list-models.js.map +1 -1
- package/dist/cli/setup.d.ts +1 -1
- package/dist/cli/setup.d.ts.map +1 -1
- package/dist/cli/setup.js +3 -2
- package/dist/cli/setup.js.map +1 -1
- package/dist/cli.js.map +1 -1
- package/dist/core/agent-session-runtime.d.ts +3 -0
- package/dist/core/agent-session-runtime.d.ts.map +1 -1
- package/dist/core/agent-session-runtime.js +11 -2
- package/dist/core/agent-session-runtime.js.map +1 -1
- package/dist/core/keybindings.d.ts +24 -0
- package/dist/core/keybindings.d.ts.map +1 -1
- package/dist/core/keybindings.js +3 -0
- package/dist/core/keybindings.js.map +1 -1
- package/dist/core/model-registry.d.ts.map +1 -1
- package/dist/core/model-registry.js +12 -1
- package/dist/core/model-registry.js.map +1 -1
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/model-resolver.js +11 -7
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/model-runtime.d.ts +11 -2
- package/dist/core/model-runtime.d.ts.map +1 -1
- package/dist/core/model-runtime.js +23 -6
- package/dist/core/model-runtime.js.map +1 -1
- package/dist/core/oauth-account-pool.d.ts +4 -0
- package/dist/core/oauth-account-pool.d.ts.map +1 -1
- package/dist/core/oauth-account-pool.js +104 -20
- package/dist/core/oauth-account-pool.js.map +1 -1
- package/dist/core/sdk.js +2 -2
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/slash-commands.d.ts.map +1 -1
- package/dist/core/slash-commands.js +1 -0
- package/dist/core/slash-commands.js.map +1 -1
- package/dist/extensions/usage/confirmation.d.ts.map +1 -1
- package/dist/extensions/usage/confirmation.js +1 -1
- package/dist/extensions/usage/confirmation.js.map +1 -1
- package/dist/extensions/usage/index.js +1 -1
- package/dist/extensions/usage/index.js.map +1 -1
- package/dist/extensions/usage/panes.d.ts +5 -0
- package/dist/extensions/usage/panes.d.ts.map +1 -0
- package/dist/extensions/usage/panes.js +10 -0
- package/dist/extensions/usage/panes.js.map +1 -0
- package/dist/extensions/usage/popup.d.ts.map +1 -1
- package/dist/extensions/usage/popup.js +9 -18
- package/dist/extensions/usage/popup.js.map +1 -1
- package/dist/humain/hcode/contracts.d.ts +15 -0
- package/dist/humain/hcode/contracts.d.ts.map +1 -1
- package/dist/humain/hcode/contracts.js +85 -10
- package/dist/humain/hcode/contracts.js.map +1 -1
- package/dist/humain/hcode/environment.d.ts.map +1 -1
- package/dist/humain/hcode/environment.js +4 -2
- package/dist/humain/hcode/environment.js.map +1 -1
- package/dist/humain/hcode/images.d.ts.map +1 -1
- package/dist/humain/hcode/images.js +4 -2
- package/dist/humain/hcode/images.js.map +1 -1
- package/dist/humain/hcode/login-copy.js +1 -1
- package/dist/humain/hcode/login-copy.js.map +1 -1
- package/dist/humain/hcode/notices.d.ts +22 -1
- package/dist/humain/hcode/notices.d.ts.map +1 -1
- package/dist/humain/hcode/notices.js +34 -3
- package/dist/humain/hcode/notices.js.map +1 -1
- package/dist/humain/hcode/provider.d.ts +3 -1
- package/dist/humain/hcode/provider.d.ts.map +1 -1
- package/dist/humain/hcode/provider.js +126 -46
- package/dist/humain/hcode/provider.js.map +1 -1
- package/dist/humain/hcode/run-credential.d.ts +21 -0
- package/dist/humain/hcode/run-credential.d.ts.map +1 -0
- package/dist/humain/hcode/run-credential.js +140 -0
- package/dist/humain/hcode/run-credential.js.map +1 -0
- package/dist/humain/hcode/sandbox.d.ts +6 -0
- package/dist/humain/hcode/sandbox.d.ts.map +1 -0
- package/dist/humain/hcode/sandbox.js +139 -0
- package/dist/humain/hcode/sandbox.js.map +1 -0
- package/dist/humain/hcode/selection.d.ts +7 -2
- package/dist/humain/hcode/selection.d.ts.map +1 -1
- package/dist/humain/hcode/selection.js +29 -5
- package/dist/humain/hcode/selection.js.map +1 -1
- package/dist/humain/hcode/transport.d.ts +3 -2
- package/dist/humain/hcode/transport.d.ts.map +1 -1
- package/dist/humain/hcode/transport.js +22 -7
- package/dist/humain/hcode/transport.js.map +1 -1
- package/dist/humain/remote/broker.d.ts +84 -0
- package/dist/humain/remote/broker.d.ts.map +1 -0
- package/dist/humain/remote/broker.js +427 -0
- package/dist/humain/remote/broker.js.map +1 -0
- package/dist/humain/remote/deny-store.d.ts +12 -0
- package/dist/humain/remote/deny-store.d.ts.map +1 -0
- package/dist/humain/remote/deny-store.js +164 -0
- package/dist/humain/remote/deny-store.js.map +1 -0
- package/dist/humain/remote/enablement.d.ts +5 -0
- package/dist/humain/remote/enablement.d.ts.map +1 -0
- package/dist/humain/remote/enablement.js +8 -0
- package/dist/humain/remote/enablement.js.map +1 -0
- package/dist/humain/remote/environment.d.ts +11 -0
- package/dist/humain/remote/environment.d.ts.map +1 -0
- package/dist/humain/remote/environment.js +19 -0
- package/dist/humain/remote/environment.js.map +1 -0
- package/dist/humain/remote/host-watch.d.ts +21 -0
- package/dist/humain/remote/host-watch.d.ts.map +1 -0
- package/dist/humain/remote/host-watch.js +186 -0
- package/dist/humain/remote/host-watch.js.map +1 -0
- package/dist/humain/remote/ipc-posix.d.ts +5 -0
- package/dist/humain/remote/ipc-posix.d.ts.map +1 -0
- package/dist/humain/remote/ipc-posix.js +29 -0
- package/dist/humain/remote/ipc-posix.js.map +1 -0
- package/dist/humain/remote/ipc-windows.d.ts +3 -0
- package/dist/humain/remote/ipc-windows.d.ts.map +1 -0
- package/dist/humain/remote/ipc-windows.js +5 -0
- package/dist/humain/remote/ipc-windows.js.map +1 -0
- package/dist/humain/remote/ipc.d.ts +10 -0
- package/dist/humain/remote/ipc.d.ts.map +1 -0
- package/dist/humain/remote/ipc.js +19 -0
- package/dist/humain/remote/ipc.js.map +1 -0
- package/dist/humain/remote/protocol.d.ts +43 -0
- package/dist/humain/remote/protocol.d.ts.map +1 -0
- package/dist/humain/remote/protocol.js +76 -0
- package/dist/humain/remote/protocol.js.map +1 -0
- package/dist/humain/remote/relay-socket.d.ts +30 -0
- package/dist/humain/remote/relay-socket.d.ts.map +1 -0
- package/dist/humain/remote/relay-socket.js +137 -0
- package/dist/humain/remote/relay-socket.js.map +1 -0
- package/dist/humain/remote/secure-channel.d.ts +10 -0
- package/dist/humain/remote/secure-channel.d.ts.map +1 -0
- package/dist/humain/remote/secure-channel.js +5 -0
- package/dist/humain/remote/secure-channel.js.map +1 -0
- package/dist/humain/remote/terminal.d.ts +48 -0
- package/dist/humain/remote/terminal.d.ts.map +1 -0
- package/dist/humain/remote/terminal.js +119 -0
- package/dist/humain/remote/terminal.js.map +1 -0
- package/dist/humain/remote/tickets.d.ts +35 -0
- package/dist/humain/remote/tickets.d.ts.map +1 -0
- package/dist/humain/remote/tickets.js +132 -0
- package/dist/humain/remote/tickets.js.map +1 -0
- package/dist/main.d.ts +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +13 -1
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/account-picker.d.ts +31 -0
- package/dist/modes/interactive/components/account-picker.d.ts.map +1 -0
- package/dist/modes/interactive/components/account-picker.js +150 -0
- package/dist/modes/interactive/components/account-picker.js.map +1 -0
- package/dist/modes/interactive/interactive-mode.d.ts +15 -2
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +225 -36
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/oauth-account-format.d.ts +9 -0
- package/dist/modes/interactive/oauth-account-format.d.ts.map +1 -1
- package/dist/modes/interactive/oauth-account-format.js +31 -22
- package/dist/modes/interactive/oauth-account-format.js.map +1 -1
- package/docs/cli.md +1 -1
- package/docs/forge-run-bootstrap.md +46 -0
- package/docs/humain-code.md +2 -2
- package/docs/index.md +2 -1
- package/docs/keybindings.md +10 -0
- package/docs/providers.md +2 -2
- package/docs/quickstart.md +16 -2
- package/docs/slash-commands.md +4 -2
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/schemas/keybindings.schema.json +12 -0
- package/dist/bundle/chunks/chunk-J5TSAJGC.js +0 -22
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"environment.js","sourceRoot":"","sources":["../../../src/humain/hcode/environment.ts"],"names":[],"mappings":"AAQA,MAAM,YAAY,GAA6D,MAAM,CAAC,MAAM,CAAC;IAC5F,GAAG,EAAE,MAAM,CAAC,MAAM,CAAC;QAClB,EAAE,EAAE,KAAK;QACT,MAAM,EAAE,6BAA6B;QACrC,gBAAgB,EAAE,2CAA2C;KAC7D,CAAC;IACF,OAAO,EAAE,MAAM,CAAC,MAAM,CAAC;QACtB,EAAE,EAAE,SAAS;QACb,MAAM,EAAE,6BAA6B;QACrC,gBAAgB,EAAE,2CAA2C;KAC7D,CAAC;IACF,UAAU,EAAE,MAAM,CAAC,MAAM,CAAC;QACzB,EAAE,EAAE,YAAY;QAChB,MAAM,EAAE,yBAAyB;QACjC,gBAAgB,EAAE,uCAAuC;KACzD,CAAC;CACF,CAAC,CAAC;AAEH,qGAAqG;AACrG,MAAM,UAAU,uBAAuB,CAAC,KAAK,GAAW,YAAY;IACnE,IAAI,KAAK,KAAK,KAAK;QAAE,OAAO,YAAY,CAAC,OAAO,CAAC;IACjD,IAAI,KAAK,KAAK,KAAK,IAAI,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,YAAY;QACnE,MAAM,IAAI,KAAK,CAAC,oDAAoD,CAAC,CAAC;IACvE,OAAO,YAAY,CAAC,KAAK,CAAC,CAAC;AAC5B,CAAC;AAED,kFAAkF;AAClF,MAAM,UAAU,gBAAgB,CAAC,aAAqB;IACrD,IAAI,aAAa,KAAK,KAAK;QAAE,OAAO,mBAAmB,CAAC;IACxD,IAAI,aAAa,KAAK,SAAS;QAAE,OAAO,
|
|
1
|
+
{"version":3,"file":"environment.js","sourceRoot":"","sources":["../../../src/humain/hcode/environment.ts"],"names":[],"mappings":"AAQA,MAAM,YAAY,GAA6D,MAAM,CAAC,MAAM,CAAC;IAC5F,GAAG,EAAE,MAAM,CAAC,MAAM,CAAC;QAClB,EAAE,EAAE,KAAK;QACT,MAAM,EAAE,6BAA6B;QACrC,gBAAgB,EAAE,2CAA2C;KAC7D,CAAC;IACF,OAAO,EAAE,MAAM,CAAC,MAAM,CAAC;QACtB,EAAE,EAAE,SAAS;QACb,MAAM,EAAE,6BAA6B;QACrC,gBAAgB,EAAE,2CAA2C;KAC7D,CAAC;IACF,UAAU,EAAE,MAAM,CAAC,MAAM,CAAC;QACzB,EAAE,EAAE,YAAY;QAChB,MAAM,EAAE,yBAAyB;QACjC,gBAAgB,EAAE,uCAAuC;KACzD,CAAC;CACF,CAAC,CAAC;AAEH,qGAAqG;AACrG,MAAM,UAAU,uBAAuB,CAAC,KAAK,GAAW,YAAY;IACnE,IAAI,KAAK,KAAK,KAAK;QAAE,OAAO,YAAY,CAAC,OAAO,CAAC;IACjD,IAAI,KAAK,KAAK,MAAM;QAAE,OAAO,YAAY,CAAC,UAAU,CAAC;IACrD,IAAI,KAAK,KAAK,KAAK,IAAI,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,YAAY;QACnE,MAAM,IAAI,KAAK,CAAC,oDAAoD,CAAC,CAAC;IACvE,OAAO,YAAY,CAAC,KAAK,CAAC,CAAC;AAC5B,CAAC;AAED,kFAAkF;AAClF,MAAM,UAAU,gBAAgB,CAAC,aAAqB;IACrD,IAAI,aAAa,KAAK,KAAK;QAAE,OAAO,mBAAmB,CAAC;IACxD,IAAI,aAAa,KAAK,SAAS;QAAE,OAAO,uBAAuB,CAAC;IAChE,OAAO,aAAa,CAAC;AACtB,CAAC","sourcesContent":["// Immutable built-in HUMAIN Code destinations; independent providers retain their own origins.\nexport type HcodeEnvironmentName = \"dev\" | \"staging\" | \"production\";\nexport interface HcodeEnvironment {\n\treadonly id: HcodeEnvironmentName;\n\treadonly origin: string;\n\treadonly inferenceBaseUrl: string;\n}\n\nconst ENVIRONMENTS: Readonly<Record<HcodeEnvironmentName, HcodeEnvironment>> = Object.freeze({\n\tdev: Object.freeze({\n\t\tid: \"dev\",\n\t\torigin: \"https://code.dev.humain.com\",\n\t\tinferenceBaseUrl: \"https://code.dev.humain.com/api/inference\",\n\t}),\n\tstaging: Object.freeze({\n\t\tid: \"staging\",\n\t\torigin: \"https://code.stg.humain.com\",\n\t\tinferenceBaseUrl: \"https://code.stg.humain.com/api/inference\",\n\t}),\n\tproduction: Object.freeze({\n\t\tid: \"production\",\n\t\torigin: \"https://code.humain.com\",\n\t\tinferenceBaseUrl: \"https://code.humain.com/api/inference\",\n\t}),\n});\n\n/** Resolves only built-in destinations, defaulting to production without I/O or ambient settings. */\nexport function resolveHcodeEnvironment(value: string = \"production\"): HcodeEnvironment {\n\tif (value === \"stg\") return ENVIRONMENTS.staging;\n\tif (value === \"prod\") return ENVIRONMENTS.production;\n\tif (value !== \"dev\" && value !== \"staging\" && value !== \"production\")\n\t\tthrow new Error(\"Invalid --env. Choose dev, staging, or production.\");\n\treturn ENVIRONMENTS[value];\n}\n\n/** Product label for the selected environment, without a suffix in production. */\nexport function hcodeDisplayName(environmentId: string): string {\n\tif (environmentId === \"dev\") return \"HUMAIN Code (Dev)\";\n\tif (environmentId === \"staging\") return \"HUMAIN Code (Staging)\";\n\treturn \"HUMAIN Code\";\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"images.d.ts","sourceRoot":"","sources":["../../../src/humain/hcode/images.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,KAAK,EAAE,GAAG,EAAgB,KAAK,EAAe,MAAM,uBAAuB,CAAC;AAanF,4DAA4D;AAC5D,MAAM,MAAM,gBAAgB,GACzB,SAAS,GACT,aAAa,GACb,YAAY,GACZ,YAAY,GACZ,gBAAgB,GAChB,cAAc,GACd,MAAM,GACN,SAAS,CAAC;AAGb,eAAO,MAAM,kBAAkB,6BAAoC,CAAC;AASpE,+GAA+G;AAC/G,wBAAgB,0BAA0B,CAAC,CAAC,EAC3C,OAAO,EAAE,CA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<= limit && nonImageBytes <= HCODE_REQUEST_MAX_NON_IMAGE_BYTES;
|
|
196
|
-
// Text-only
|
|
197
|
-
if (
|
|
196
|
+
// Text-only overflows cannot be fitted; classify them as size refusals, not schema failures.
|
|
197
|
+
if (fits())
|
|
198
198
|
return { body, omitted: 0 };
|
|
199
|
+
if (!hasImageContent)
|
|
200
|
+
return;
|
|
199
201
|
const projected = messages.slice();
|
|
200
202
|
const optional = [];
|
|
201
203
|
const historical = [];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"images.js","sourceRoot":"","sources":["../../../src/humain/hcode/images.ts"],"names":[],"mappings":"AAAA,uGAAuG;AACvG,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAGrD,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAC5D,OAAO,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAC5D,OAAO,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AACnD,OAAO,EACN,6BAA6B,EAC7B,iCAAiC,EAGjC,sBAAsB,EACtB,yBAAyB,GACzB,MAAM,gBAAgB,CAAC;AAaxB,iGAAiG;AACjG,MAAM,CAAC,MAAM,kBAAkB,GAAG,IAAI,OAAO,EAAsB,CAAC;AACpE,MAAM,iBAAiB,GAAG,IAAI,OAAO,EAAe,CAAC;AAErD,MAAM,qBAAqB,GAAG,IAAI,iBAAiB,EAI/C,CAAC;AAEL,+GAA+G;AAC/G,MAAM,UAAU,0BAA0B,CACzC,OAAkC,EAClC,GAAY,EACZ,EACC,gBAAgB,GAAG,IAAI,EACvB,kBAAkB,GAClB,GAAoE,EAAE;IAEvE,OAAO,qBAAqB,CAAC,GAAG,CAAC,EAAE,OAAO,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,EAAE,GAAG,CAAC,CAAC;AAC1F,CAAC;AAED,iHAAiH;AACjH,MAAM,UAAU,2BAA2B;IAC1C,qBAAqB,CAAC,QAAQ,EAAE,E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AC,IAAI,MAAM,GAAG,IAAI,CAAC,MAAM,GAAG,MAAM;gBAAE,OAAO,KAAK,CAAC;YAC9D,MAAM,IAAI,MAAM,CAAC;QAClB,CAAC;IACF,CAAC;IACD,OAAO,KAAK,CAAC;AACd,CAAC","sourcesContent":["// Fits HUMAIN Code request images to the selected model's catalog limits and names each refusal cause.\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { Api, ImageContent, Model, TextContent } from \"@earendil-works/pi-ai\";\nimport { getImageDimensions } from \"@earendil-works/pi-tui\";\nimport { processImage } from \"../../utils/image-process.ts\";\nimport { loadPhoton } from \"../../utils/photon.ts\";\nimport {\n\tHCODE_REQUEST_MAX_IMAGE_BYTES,\n\tHCODE_REQUEST_MAX_NON_IMAGE_BYTES,\n\ttype HcodeModel,\n\ttype HcodeText,\n\thcodeDecodedImageBytes,\n\tparseHcodeMessagesRequest,\n} from \"./contracts.ts\";\n\n/** Why an image cannot be part of a HUMAIN Code request. */\nexport type HcodeImageReason =\n\t| \"blocked\"\n\t| \"unsupported\"\n\t| \"perMessage\"\n\t| \"perRequest\"\n\t| \"aggregateBytes\"\n\t| \"requestBytes\"\n\t| \"size\"\n\t| \"invalid\";\n\n// Content array identity survives custom-message conversion without adding metadata to the wire.\nexport const hcodeActivePrompts = new WeakSet<readonly unknown[]>();\nconst optionalImageText = new WeakSet<TextContent>();\n\nconst imageOmissionObserver = new AsyncLocalStorage<{\n\tobserve: (message: string) => void;\n\tautoResizeImages: boolean;\n\tonImageSizeRefusal?: () => void;\n}>();\n\n/** Observe serialized image omissions for this session's requests, not other sessions sharing the provider. */\nexport function observeHcodeImageOmissions<T>(\n\tobserve: (message: string) => void,\n\trun: () => T,\n\t{\n\t\tautoResizeImages = true,\n\t\tonImageSizeRefusal,\n\t}: { autoResizeImages?: boolean; onImageSizeRefusal?: () => void } = {},\n): T {\n\treturn imageOmissionObserver.run({ observe, autoResizeImages, onImageSizeRefusal }, run);\n}\n\n/** Record fresh attachments refused before dispatch so the session can omit them from subsequent projections. */\nexport function reportHcodeImageSizeRefusal(): void {\n\timageOmissionObserver.getStore()?.onImageSizeRefusal?.();\n}\n\n/** Report wire-level omissions after the final transport dispatches the request. */\nexport function reportHcodeImageOmissions(count: number, model: Model<Api>): void {\n\ttry {\n\t\timageOmissionObserver.getStore()?.observe(hcodeImageOmissionNotice(count, \"requestBytes\", model));\n\t} catch {\n\t\t// A notice listener cannot turn a submitted request into a reported transport failure.\n\t}\n}\n\n/** Format the notice presented to the caller for projected or serialized omissions. */\nexport function hcodeImageOmissionNotice(count: number, reason: HcodeImageReason, model: Model<Api>): string {\n\treturn `${count === 1 ? \"1 image was\" : `${count} images were`} left out of this HUMAIN Code request. ${hcodeImageMessage(reason, model)}`;\n}\n\n/** Request messages with every image fitted, and the images that had to be left out (by message index). */\nexport interface FittedHcodeImages {\n\tmessages: AgentMessage[];\n\tomitted: { index: number; reason: HcodeImageReason }[];\n}\n\ntype ImageLimits = HcodeModel[\"inputLimits\"][\"images\"] & {};\n\n/** The model accepts only these inline image types; anything else is converted to PNG first. */\nconst HCODE_IMAGE_MIME_TYPES = [\"image/png\", \"image/jpeg\", \"image/webp\"] as const;\n\n/**\n * Downscale or recompress every image to the model's catalog limits. Newer messages keep their images\n * first; images over the count limits or that cannot fit become a text note, so one bad image never\n * blocks later requests. Original messages are not changed.\n */\nexport async function fitHcodeImages(\n\tmodel: Model<Api>,\n\tmessages: AgentMessage[],\n\t{ autoResizeImages, blockImages }: { autoResizeImages: boolean; blockImages: boolean },\n\tfresh: ReadonlySet<AgentMessage>,\n\trejected?: ReadonlySet<AgentMessage>,\n): Promise<FittedHcodeImages> {\n\tconst limits = imageLimits(model);\n\tconst fitted = messages.slice();\n\tconst omitted: FittedHcodeImages[\"omitted\"] = [];\n\tconst shared =\n\t\tlimits &&\n\t\tautoResizeImages &&\n\t\t!blockImages &&\n\t\tlimits.maxPerRequest * limits.resize.maxBytes * 0.75 > HCODE_REQUEST_MAX_IMAGE_BYTES\n\t\t\t? await fitFreshAggregate(fresh, limits)\n\t\t\t: undefined;\n\tlet count = 0;\n\tlet remainingBytes = HCODE_REQUEST_MAX_IMAGE_BYTES;\n\tconst order = messages.map((_, index) => index).reverse();\n\tfor (const index of [\n\t\t...order.filter((i) => fresh.has(messages[i]!)),\n\t\t...order.filter((i) => !fresh.has(messages[i]!)),\n\t]) {\n\t\tconst message = messages[index]!;\n\t\tif (!(\"content\" in message) || !Array.isArray(message.content)) continue;\n\t\tif (!message.content.some((block) => block.type === \"image\")) continue;\n\t\tconst content: (TextContent | ImageContent)[] = [];\n\t\tlet perMessage = 0;\n\t\tfor (const block of message.content as (TextContent | ImageContent)[]) {\n\t\t\tif (block.type !== \"image\") {\n\t\t\t\tcontent.push(block);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst result = rejected?.has(message)\n\t\t\t\t? \"requestBytes\"\n\t\t\t\t: blockImages\n\t\t\t\t\t? \"blocked\"\n\t\t\t\t\t: !limits\n\t\t\t\t\t\t? \"unsupported\"\n\t\t\t\t\t\t: perMessage >= limits.maxPerMessage\n\t\t\t\t\t\t\t? \"perMessage\"\n\t\t\t\t\t\t\t: count >= limits.maxPerRequest\n\t\t\t\t\t\t\t\t? \"perRequest\"\n\t\t\t\t\t\t\t\t: ((fresh.has(message) ? shared?.get(block) : undefined) ??\n\t\t\t\t\t\t\t\t\t(await fitImage(block, limits, autoResizeImages)));\n\t\t\tlet reason: HcodeImageReason;\n\t\t\tif (typeof result === \"string\") reason = result;\n\t\t\telse {\n\t\t\t\tconst reduced =\n\t\t\t\t\thcodeDecodedImageBytes(result.image.data) > remainingBytes && fresh.has(message) && limits\n\t\t\t\t\t\t? await fitImage(block, limits, autoResizeImages, Math.floor(remainingBytes / 3) * 4)\n\t\t\t\t\t\t: result;\n\t\t\t\tconst bytes = typeof reduced === \"string\" ? Infinity : hcodeDecodedImageBytes(reduced.image.data);\n\t\t\t\tif (typeof reduced !== \"string\" && bytes <= remainingBytes) {\n\t\t\t\t\tremainingBytes -= bytes;\n\t\t\t\t\tcount++;\n\t\t\t\t\tperMessage++;\n\t\t\t\t\tcontent.push(reduced.image);\n\t\t\t\t\tif (reduced.hints.length) content.push(imageText(reduced.hints.join(\"\\n\")));\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\treason = \"aggregateBytes\";\n\t\t\t}\n\t\t\tomitted.push({ index, reason });\n\t\t\tcontent.push(imageOmissionBlock(reason, model));\n\t\t}\n\t\tfitted[index] = { ...message, content } as AgentMessage;\n\t}\n\treturn { messages: fitted, omitted };\n}\n\n// A fresh batch must fit as a whole. Don't spend the aggregate budget in transcript order.\nasync function fitFreshAggregate(fresh: ReadonlySet<AgentMessage>, limits: ImageLimits) {\n\tconst images = [...fresh].flatMap((message) =>\n\t\t\"content\" in message && Array.isArray(message.content)\n\t\t\t? message.content.filter((block): block is ImageContent => block.type === \"image\")\n\t\t\t: [],\n\t);\n\tif (\n\t\timages.length > limits.maxPerRequest ||\n\t\timages.length * limits.resize.maxBytes * 0.75 <= HCODE_REQUEST_MAX_IMAGE_BYTES\n\t)\n\t\treturn;\n\tlet total = 0;\n\tfor (const block of images) {\n\t\tconst result = await fitImage(block, limits, true);\n\t\tif (typeof result === \"string\") return;\n\t\ttotal += hcodeDecodedImageBytes(result.image.data);\n\t}\n\tif (total <= HCODE_REQUEST_MAX_IMAGE_BYTES) return;\n\tconst maxBytes = Math.floor(HCODE_REQUEST_MAX_IMAGE_BYTES / images.length / 3) * 4;\n\tconst reduced = new Map<ImageContent, FitResult>();\n\tfor (const block of images) {\n\t\tif (!reduced.has(block)) reduced.set(block, await fitImage(block, limits, true, maxBytes));\n\t}\n\treturn reduced;\n}\n\nfunction imageText(text: string): HcodeText {\n\tconst block = { type: \"text\" as const, text };\n\toptionalImageText.add(block);\n\treturn block;\n}\n\nfunction imageOmissionBlock(reason: HcodeImageReason, model: Model<Api>): HcodeText {\n\treturn imageText(`[Image omitted from this HUMAIN Code request: ${hcodeImageMessage(reason, model)}]`);\n}\n\ntype PayloadMessage = { content: string | readonly { type: string }[] };\n\n/** Isolate the transcript from payload hooks and retain image provenance across reordering or cloning. */\nexport function hcodeImagePayloadDraft<T extends { context: { messages: PayloadMessage[] } }>(\n\tpayload: T,\n\tactive: ReadonlySet<number>,\n): { draft: T; protectedMessages: (messages: PayloadMessage[]) => Set<number> } {\n\tconst draft = JSON.parse(JSON.stringify(payload)) as T;\n\tconst fresh: ImageContent[] = [];\n\tconst history: ImageContent[] = [];\n\tfor (const [index, message] of payload.context.messages.entries()) {\n\t\tif (typeof message.content === \"string\") continue;\n\t\tconst copy = draft.context.messages[index]!.content as readonly { type: string }[];\n\t\tfor (const [i, block] of message.content.entries()) {\n\t\t\tif (block.type === \"image\") (active.has(index) ? fresh : history).push(block as ImageContent);\n\t\t\tif (block.type === \"text\" && optionalImageText.has(block as TextContent))\n\t\t\t\toptionalImageText.add(copy[i] as TextContent);\n\t\t}\n\t}\n\treturn {\n\t\tdraft,\n\t\tprotectedMessages(messages) {\n\t\t\treturn new Set(\n\t\t\t\tmessages.flatMap((message, index) => {\n\t\t\t\t\tif (typeof message.content === \"string\") return [];\n\t\t\t\t\tconst protectedImage = message.content.some((block) => {\n\t\t\t\t\t\tif (block.type !== \"image\") return false;\n\t\t\t\t\t\tconst { data, mimeType } = block as ImageContent;\n\t\t\t\t\t\tconst matches = (image: ImageContent) => image.data === data && image.mimeType === mimeType;\n\t\t\t\t\t\t// Added or changed images are not eligible for silent eviction. Fresh wins on identical copies.\n\t\t\t\t\t\treturn Object.keys(block).length !== 3 || fresh.some(matches) || !history.some(matches);\n\t\t\t\t\t});\n\t\t\t\t\treturn protectedImage ? [index] : [];\n\t\t\t\t}),\n\t\t\t);\n\t\t},\n\t};\n}\n\n/** The catalog and hard wire limits apply to the exact JSON, including image metadata and options. */\nexport async function fitHcodeRequestSize<T extends { role: string; content: string | readonly { type: string }[] }>(\n\tmodel: Model<Api>,\n\tmessages: T[],\n\tactive: ReadonlySet<number>,\n\tserialize: (messages: T[]) => string,\n): Promise<{ body: string; omitted: number } | undefined> {\n\tconst limit = Math.min(12582912, model.inputLimits?.maxRequestBytes ?? 12582912);\n\tconst imageData = (block: { type: string }): block is ImageContent => block.type === \"image\";\n\tconst byteLength = (value: string) => Buffer.byteLength(value, \"utf8\");\n\tlet body = serialize(messages);\n\tlet bytes = byteLength(body);\n\tlet nonImageBytes = bytes;\n\tlet hasImageContent = false;\n\tfor (const message of messages) {\n\t\tif (typeof message.content === \"string\") continue;\n\t\tfor (const block of message.content) {\n\t\t\tif (imageData(block)) {\n\t\t\t\tnonImageBytes -= block.data.length;\n\t\t\t\thasImageContent = true;\n\t\t\t} else if (block.type === \"text\" && optionalImageText.has(block as TextContent)) hasImageContent = true;\n\t\t}\n\t}\n\tconst fits = () => bytes <= limit && nonImageBytes <= HCODE_REQUEST_MAX_NON_IMAGE_BYTES;\n\t// Text-only requests retain their existing strict parse and final-send size checks.\n\tif (!hasImageContent || fits()) return { body, omitted: 0 };\n\n\tconst projected = messages.slice();\n\tconst optional: { put: (block: TextContent | undefined) => void; note: TextContent }[] = [];\n\tconst historical: ((block: TextContent | undefined) => void)[] = [];\n\tconst fresh: { put: (block: ImageContent) => void; image: ImageContent }[] = [];\n\tfor (const [index, message] of messages.entries()) {\n\t\tif (typeof message.content === \"string\" || (message.role !== \"user\" && message.role !== \"toolResult\")) continue;\n\t\tconst slots: ({ type: string } | undefined)[] = [...message.content];\n\t\tlet length = slots.length;\n\t\tfor (const [i, block] of message.content.entries()) {\n\t\t\tconst put = (value: (typeof slots)[number]) => {\n\t\t\t\tconst previous = slots[i];\n\t\t\t\tconst delta = (b: typeof previous) => (b ? byteLength(JSON.stringify(b)) : 0);\n\t\t\t\tconst data = (b: typeof previous) => (b && imageData(b) ? b.data.length : 0);\n\t\t\t\tconst separator = !previous && value && length > 0 ? 1 : previous && !value && length > 1 ? -1 : 0;\n\t\t\t\tlength += Number(value !== undefined) - Number(previous !== undefined);\n\t\t\t\tconst change = delta(value) - delta(previous) + separator;\n\t\t\t\tbytes += change;\n\t\t\t\tnonImageBytes += change + data(previous) - data(value);\n\t\t\t\tslots[i] = value;\n\t\t\t\tprojected[index] = { ...message, content: slots.filter((entry) => entry !== undefined) };\n\t\t\t};\n\t\t\tif (block.type === \"text\" && optionalImageText.has(block as TextContent))\n\t\t\t\toptional.push({ put, note: block as TextContent });\n\t\t\telse if (imageData(block)) {\n\t\t\t\tif (active.has(index)) fresh.push({ put, image: block });\n\t\t\t\telse historical.push(put);\n\t\t\t}\n\t\t}\n\t}\n\tfor (const { put } of optional) put(undefined);\n\tlet omitted = 0;\n\tfor (const put of historical) {\n\t\tif (fits()) break;\n\t\tput(undefined);\n\t\tomitted++;\n\t\toptional.push({ put, note: imageText(\"[Image omitted: request size limit.]\") });\n\t}\n\tif (!fits() && nonImageBytes <= HCODE_REQUEST_MAX_NON_IMAGE_BYTES) {\n\t\tconst limits = imageLimits(model);\n\t\tconst autoResize = imageOmissionObserver.getStore()?.autoResizeImages ?? true;\n\t\tif (limits && autoResize) {\n\t\t\t// Reserve wire metadata for every attachment; smaller images keep their bytes first.\n\t\t\tfresh.sort((a, b) => a.image.data.length - b.image.data.length);\n\t\t\tlet remaining = limit - bytes + fresh.reduce((sum, { image }) => sum + image.data.length, 0);\n\t\t\tfor (const [i, { put, image }] of fresh.entries()) {\n\t\t\t\tconst share = Math.floor(remaining / (fresh.length - i));\n\t\t\t\tconst result = await fitImage(image, limits, true, share);\n\t\t\t\tif (typeof result === \"string\") return;\n\t\t\t\tput(result.image);\n\t\t\t\tremaining -= result.image.data.length + result.image.mimeType.length - image.mimeType.length;\n\t\t\t}\n\t\t}\n\t}\n\tif (!fits()) return;\n\tfor (const { put, note } of optional) {\n\t\tput(note);\n\t\tif (!fits()) put(undefined);\n\t}\n\tbody = serialize(projected);\n\treturn { body, omitted };\n}\n\nfunction imageLimits(model: Model<Api>): ImageLimits | undefined {\n\t// The provider supplies only its X1-validated, immutable canonical model; pi's generic limits are optional.\n\treturn model.input.includes(\"image\") ? (model.inputLimits?.images as ImageLimits | undefined) : undefined;\n}\n\ntype FitResult = { image: ImageContent; hints: string[] } | HcodeImageReason;\n\n// History blocks are stable objects, so each image is decoded and resized once per limits profile.\nconst fitCache = new WeakMap<ImageContent, { limits: ImageLimits; autoResizeImages: boolean; result: FitResult }>();\n\nasync function fitImage(\n\tblock: ImageContent,\n\tlimits: ImageLimits,\n\tautoResizeImages: boolean,\n\tbyteBudget = limits.resize.maxBytes,\n): Promise<FitResult> {\n\tconst maxBytes = Math.min(byteBudget, limits.resize.maxBytes);\n\tif (maxBytes < 4) return \"size\";\n\tconst cacheable = maxBytes === limits.resize.maxBytes;\n\tconst cached = cacheable ? fitCache.get(block) : undefined;\n\tif (cached?.limits === limits && cached.autoResizeImages === autoResizeImages) return cached.result;\n\tconst effective = cacheable ? limits : { ...limits, resize: { ...limits.resize, maxBytes } };\n\tconst processed = await processImage(Buffer.from(block.data, \"base64\"), block.mimeType, {\n\t\tautoResizeImages,\n\t\tresizeOptions: effective.resize,\n\t\tmimeTypes: HCODE_IMAGE_MIME_TYPES,\n\t});\n\tlet result: FitResult;\n\tif (!processed.ok) result = (await checkHcodeImage(block, effective)) ?? \"size\";\n\telse {\n\t\tconst unchanged = processed.data === block.data && processed.mimeType === block.mimeType;\n\t\tconst image: ImageContent = unchanged\n\t\t\t? block\n\t\t\t: { type: \"image\", data: processed.data, mimeType: processed.mimeType };\n\t\tresult = (await checkHcodeImage(image, effective)) ?? { image, hints: processed.hints };\n\t}\n\tif (cacheable) fitCache.set(block, { limits, autoResizeImages, result });\n\treturn result;\n}\n\n/** One plain message per refusal cause, naming the catalog limit that applies. */\nexport function hcodeImageMessage(reason: HcodeImageReason, model: Model<Api>): string {\n\tconst limits = imageLimits(model);\n\tswitch (reason) {\n\t\tcase \"blocked\":\n\t\t\treturn \"HUMAIN Code image attachments are blocked. Remove them or change /settings before sending.\";\n\t\tcase \"requestBytes\":\n\t\t\treturn \"Earlier images exceeded the HUMAIN Code request size limit.\";\n\t\tcase \"unsupported\":\n\t\t\treturn \"This HUMAIN Code model doesn't support images. Remove the image or choose an image-capable model with /model.\";\n\t\tcase \"perMessage\":\n\t\t\treturn `HUMAIN Code accepts at most ${images(limits?.maxPerMessage)} per message. Remove some images and try again.`;\n\t\tcase \"perRequest\":\n\t\t\treturn `HUMAIN Code accepts at most ${images(limits?.maxPerRequest)} per request, including earlier messages. Remove some images and try again.`;\n\t\tcase \"aggregateBytes\":\n\t\t\treturn \"This HUMAIN Code request exceeds the combined image size limit of 8 MiB. Attach fewer or smaller images.\";\n\t\tcase \"size\":\n\t\t\treturn `This image couldn't be reduced to the HUMAIN Code limits (${limits?.resize.maxWidth}x${limits?.resize.maxHeight} px, ${limits?.resize.maxBytes} bytes). Attach a smaller image.`;\n\t\tcase \"invalid\":\n\t\t\treturn \"This image isn't a readable single-frame PNG, JPEG or WebP image. Attach a different image.\";\n\t}\n}\n\nfunction images(count: number | undefined): string {\n\treturn count === 1 ? \"1 image\" : `${count} images`;\n}\n\n/** Refuse a request whose images do not meet the model's limits; the final guard before the wire. */\nexport async function validateHcodeImages(\n\tmodel: Model<Api>,\n\tmessages: readonly { content: string | readonly { type: string }[] }[],\n): Promise<void> {\n\tconst groups = messages.flatMap((message) => {\n\t\tif (typeof message.content === \"string\") return [];\n\t\tconst content = message.content.filter((block): block is ImageContent => block.type === \"image\");\n\t\treturn content.length ? [content] : [];\n\t});\n\tif (!groups.length) return;\n\tconst limits = imageLimits(model);\n\tconst refuse = (reason: HcodeImageReason) => {\n\t\tthrow new Error(hcodeImageMessage(reason, model));\n\t};\n\tif (!limits) return refuse(\"unsupported\");\n\tif (groups.some((group) => group.length > limits.maxPerMessage)) return refuse(\"perMessage\");\n\tconst blocks = groups.flat();\n\tif (blocks.length > limits.maxPerRequest) return refuse(\"perRequest\");\n\tlet bytes = 0;\n\tfor (const block of blocks) {\n\t\tconst reason = await checkHcodeImage(block, limits);\n\t\tif (reason) return refuse(reason);\n\t\tbytes += hcodeDecodedImageBytes(block.data);\n\t}\n\tif (bytes > HCODE_REQUEST_MAX_IMAGE_BYTES) return refuse(\"aggregateBytes\");\n\ttry {\n\t\t// Reuse X1's canonical base64, MIME, count and aggregate byte bounds for the whole request.\n\t\tparseHcodeMessagesRequest({\n\t\t\tmodel: model.id,\n\t\t\tcontext: { messages: groups.map((content) => ({ role: \"user\", content, timestamp: 0 })) },\n\t\t});\n\t} catch {\n\t\trefuse(\"size\");\n\t}\n}\n\n/** Check one image against the limits without changing it; undefined when it can be sent as is. */\nasync function checkHcodeImage(block: ImageContent, limits: ImageLimits): Promise<HcodeImageReason | undefined> {\n\tif (block.data.length > limits.resize.maxBytes) return \"size\";\n\ttry {\n\t\tparseHcodeMessagesRequest({\n\t\t\tmodel: \"image\",\n\t\t\tcontext: { messages: [{ role: \"user\", content: [block], timestamp: 0 }] },\n\t\t});\n\t} catch {\n\t\treturn \"invalid\";\n\t}\n\tconst dimensions = getImageDimensions(block.data, block.mimeType);\n\tif (!dimensions || dimensions.widthPx < 1 || dimensions.heightPx < 1) return \"invalid\";\n\tif (dimensions.widthPx > limits.resize.maxWidth || dimensions.heightPx > limits.resize.maxHeight) return \"size\";\n\tconst data = Buffer.from(block.data, \"base64\");\n\t// Image bytes are wire input: reject animation, incomplete containers and hidden trailing frames before decoding.\n\tif (!isStaticImageContainer(data, block.mimeType)) return \"invalid\";\n\tconst photon = await loadPhoton();\n\tif (!photon) return \"invalid\";\n\ttry {\n\t\tconst image = photon.PhotonImage.new_from_byteslice(data);\n\t\ttry {\n\t\t\tif (image.get_width() !== dimensions.widthPx || image.get_height() !== dimensions.heightPx) return \"invalid\";\n\t\t} finally {\n\t\t\timage.free();\n\t\t}\n\t} catch {\n\t\treturn \"invalid\";\n\t}\n\treturn undefined;\n}\n\nfunction isStaticImageContainer(data: Buffer, mime: string): boolean {\n\tif (mime === \"image/png\") {\n\t\tlet offset = 8,\n\t\t\tpixels = false;\n\t\twhile (offset + 12 <= data.length) {\n\t\t\tconst length = data.readUInt32BE(offset),\n\t\t\t\tname = data.toString(\"ascii\", offset + 4, offset + 8);\n\t\t\tif (length > data.length - offset - 12 || name === \"acTL\" || name === \"fcTL\" || name === \"fdAT\") return false;\n\t\t\tif (name === \"IDAT\") pixels = true;\n\t\t\toffset += length + 12;\n\t\t\tif (name === \"IEND\") return !length && pixels && offset === data.length;\n\t\t}\n\t} else if (mime === \"image/webp\") {\n\t\tif (data.length < 12 || data.readUInt32LE(4) !== data.length - 8) return false;\n\t\tlet offset = 12,\n\t\t\tframes = 0;\n\t\twhile (offset + 8 <= data.length) {\n\t\t\tconst name = data.toString(\"ascii\", offset, offset + 4),\n\t\t\t\tlength = data.readUInt32LE(offset + 4);\n\t\t\tif (\n\t\t\t\tlength > data.length - offset - 8 ||\n\t\t\t\tname === \"ANIM\" ||\n\t\t\t\tname === \"ANMF\" ||\n\t\t\t\t(name === \"VP8X\" && data[offset + 8]! & 2)\n\t\t\t)\n\t\t\t\treturn false;\n\t\t\tif (name === \"VP8 \" || name === \"VP8L\") frames++;\n\t\t\toffset += 8 + length + (length % 2);\n\t\t}\n\t\treturn offset === data.length && frames === 1;\n\t} else if (mime === \"image/jpeg\") {\n\t\tlet offset = 2;\n\t\twhile (offset < data.length) {\n\t\t\tif (data[offset++] !== 255) continue;\n\t\t\twhile (data[offset] === 255) offset++;\n\t\t\tconst marker = data[offset++];\n\t\t\tif (marker === 217) return offset === data.length;\n\t\t\tif (marker === 216) return false;\n\t\t\tif (marker === 0 || marker === 1 || (marker !== undefined && marker >= 208 && marker <= 215)) continue;\n\t\t\tif (offset + 2 > data.length) return false;\n\t\t\tconst length = data.readUInt16BE(offset);\n\t\t\tif (length < 2 || length > data.length - offset) return false;\n\t\t\toffset += length;\n\t\t}\n\t}\n\treturn false;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"images.js","sourceRoot":"","sources":["../../../src/humain/hcode/images.ts"],"names":[],"mappings":"AAAA,uGAAu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C,MAAM,IAAI,MAAM,KAAK,CAAC,CAAC;IAC/C,CAAC;SAAM,IAAI,IAAI,KAAK,YAAY,EAAE,CAAC;QAClC,IAAI,MAAM,GAAG,CAAC,CAAC;QACf,OAAO,MAAM,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC;YAC7B,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC,KAAK,GAAG;gBAAE,SAAS;YACrC,OAAO,IAAI,CAAC,MAAM,CAAC,KAAK,GAAG;gBAAE,MAAM,EAAE,CAAC;YACtC,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC;YAC9B,IAAI,MAAM,KAAK,GAAG;gBAAE,OAAO,MAAM,KAAK,IAAI,CAAC,MAAM,CAAC;YAClD,IAAI,MAAM,KAAK,GAAG;gBAAE,OAAO,KAAK,CAAC;YACjC,IAAI,MAAM,KAAK,CAAC,IAAI,MAAM,KAAK,CAAC,IAAI,CAAC,MAAM,KAAK,SAAS,IAAI,MAAM,IAAI,GAAG,IAAI,MAAM,IAAI,GAAG,CAAC;gBAAE,SAAS;YACvG,IAAI,MAAM,GAAG,CAAC,GAAG,IAAI,CAAC,MAAM;gBAAE,OAAO,KAAK,CAAC;YAC3C,MAAM,MAAM,GAAG,IAAI,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC;YACzC,IAAI,MAAM,GAAG,CAAC,IAAI,MAAM,GAAG,IAAI,CAAC,MAAM,GAAG,MAAM;gBAAE,OAAO,KAAK,CAAC;YAC9D,MAAM,IAAI,MAAM,CAAC;QAClB,CAAC;IACF,CAAC;IACD,OAAO,KAAK,CAAC;AACd,CAAC","sourcesContent":["// Fits HUMAIN Code request images to the selected model's catalog limits and names each refusal cause.\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { Api, ImageContent, Model, TextContent } from \"@earendil-works/pi-ai\";\nimport { getImageDimensions } from \"@earendil-works/pi-tui\";\nimport { processImage } from \"../../utils/image-process.ts\";\nimport { loadPhoton } from \"../../utils/photon.ts\";\nimport {\n\tHCODE_REQUEST_MAX_IMAGE_BYTES,\n\tHCODE_REQUEST_MAX_NON_IMAGE_BYTES,\n\ttype HcodeModel,\n\ttype HcodeText,\n\thcodeDecodedImageBytes,\n\tparseHcodeMessagesRequest,\n} from \"./contracts.ts\";\n\n/** Why an image cannot be part of a HUMAIN Code request. */\nexport type HcodeImageReason =\n\t| \"blocked\"\n\t| \"unsupported\"\n\t| \"perMessage\"\n\t| \"perRequest\"\n\t| \"aggregateBytes\"\n\t| \"requestBytes\"\n\t| \"size\"\n\t| \"invalid\";\n\n// Content array identity survives custom-message conversion without adding metadata to the wire.\nexport const hcodeActivePrompts = new WeakSet<readonly unknown[]>();\nconst optionalImageText = new WeakSet<TextContent>();\n\nconst imageOmissionObserver = new AsyncLocalStorage<{\n\tobserve: (message: string) => void;\n\tautoResizeImages: boolean;\n\tonImageSizeRefusal?: () => void;\n}>();\n\n/** Observe serialized image omissions for this session's requests, not other sessions sharing the provider. */\nexport function observeHcodeImageOmissions<T>(\n\tobserve: (message: string) => void,\n\trun: () => T,\n\t{\n\t\tautoResizeImages = true,\n\t\tonImageSizeRefusal,\n\t}: { autoResizeImages?: boolean; onImageSizeRefusal?: () => void } = {},\n): T {\n\treturn imageOmissionObserver.run({ observe, autoResizeImages, onImageSizeRefusal }, run);\n}\n\n/** Record fresh attachments refused before dispatch so the session can omit them from subsequent projections. */\nexport function reportHcodeImageSizeRefusal(): void {\n\timageOmissionObserver.getStore()?.onImageSizeRefusal?.();\n}\n\n/** Report wire-level omissions after the final transport dispatches the request. */\nexport function reportHcodeImageOmissions(count: number, model: Model<Api>): void {\n\ttry {\n\t\timageOmissionObserver.getStore()?.observe(hcodeImageOmissionNotice(count, \"requestBytes\", model));\n\t} catch {\n\t\t// A notice listener cannot turn a submitted request into a reported transport failure.\n\t}\n}\n\n/** Format the notice presented to the caller for projected or serialized omissions. */\nexport function hcodeImageOmissionNotice(count: number, reason: HcodeImageReason, model: Model<Api>): string {\n\treturn `${count === 1 ? \"1 image was\" : `${count} images were`} left out of this HUMAIN Code request. ${hcodeImageMessage(reason, model)}`;\n}\n\n/** Request messages with every image fitted, and the images that had to be left out (by message index). */\nexport interface FittedHcodeImages {\n\tmessages: AgentMessage[];\n\tomitted: { index: number; reason: HcodeImageReason }[];\n}\n\ntype ImageLimits = HcodeModel[\"inputLimits\"][\"images\"] & {};\n\n/** The model accepts only these inline image types; anything else is converted to PNG first. */\nconst HCODE_IMAGE_MIME_TYPES = [\"image/png\", \"image/jpeg\", \"image/webp\"] as const;\n\n/**\n * Downscale or recompress every image to the model's catalog limits. Newer messages keep their images\n * first; images over the count limits or that cannot fit become a text note, so one bad image never\n * blocks later requests. Original messages are not changed.\n */\nexport async function fitHcodeImages(\n\tmodel: Model<Api>,\n\tmessages: AgentMessage[],\n\t{ autoResizeImages, blockImages }: { autoResizeImages: boolean; blockImages: boolean },\n\tfresh: ReadonlySet<AgentMessage>,\n\trejected?: ReadonlySet<AgentMessage>,\n): Promise<FittedHcodeImages> {\n\tconst limits = imageLimits(model);\n\tconst fitted = messages.slice();\n\tconst omitted: FittedHcodeImages[\"omitted\"] = [];\n\tconst shared =\n\t\tlimits &&\n\t\tautoResizeImages &&\n\t\t!blockImages &&\n\t\tlimits.maxPerRequest * limits.resize.maxBytes * 0.75 > HCODE_REQUEST_MAX_IMAGE_BYTES\n\t\t\t? await fitFreshAggregate(fresh, limits)\n\t\t\t: undefined;\n\tlet count = 0;\n\tlet remainingBytes = HCODE_REQUEST_MAX_IMAGE_BYTES;\n\tconst order = messages.map((_, index) => index).reverse();\n\tfor (const index of [\n\t\t...order.filter((i) => fresh.has(messages[i]!)),\n\t\t...order.filter((i) => !fresh.has(messages[i]!)),\n\t]) {\n\t\tconst message = messages[index]!;\n\t\tif (!(\"content\" in message) || !Array.isArray(message.content)) continue;\n\t\tif (!message.content.some((block) => block.type === \"image\")) continue;\n\t\tconst content: (TextContent | ImageContent)[] = [];\n\t\tlet perMessage = 0;\n\t\tfor (const block of message.content as (TextContent | ImageContent)[]) {\n\t\t\tif (block.type !== \"image\") {\n\t\t\t\tcontent.push(block);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst result = rejected?.has(message)\n\t\t\t\t? \"requestBytes\"\n\t\t\t\t: blockImages\n\t\t\t\t\t? \"blocked\"\n\t\t\t\t\t: !limits\n\t\t\t\t\t\t? \"unsupported\"\n\t\t\t\t\t\t: perMessage >= limits.maxPerMessage\n\t\t\t\t\t\t\t? \"perMessage\"\n\t\t\t\t\t\t\t: count >= limits.maxPerRequest\n\t\t\t\t\t\t\t\t? \"perRequest\"\n\t\t\t\t\t\t\t\t: ((fresh.has(message) ? shared?.get(block) : undefined) ??\n\t\t\t\t\t\t\t\t\t(await fitImage(block, limits, autoResizeImages)));\n\t\t\tlet reason: HcodeImageReason;\n\t\t\tif (typeof result === \"string\") reason = result;\n\t\t\telse {\n\t\t\t\tconst reduced =\n\t\t\t\t\thcodeDecodedImageBytes(result.image.data) > remainingBytes && fresh.has(message) && limits\n\t\t\t\t\t\t? await fitImage(block, limits, autoResizeImages, Math.floor(remainingBytes / 3) * 4)\n\t\t\t\t\t\t: result;\n\t\t\t\tconst bytes = typeof reduced === \"string\" ? Infinity : hcodeDecodedImageBytes(reduced.image.data);\n\t\t\t\tif (typeof reduced !== \"string\" && bytes <= remainingBytes) {\n\t\t\t\t\tremainingBytes -= bytes;\n\t\t\t\t\tcount++;\n\t\t\t\t\tperMessage++;\n\t\t\t\t\tcontent.push(reduced.image);\n\t\t\t\t\tif (reduced.hints.length) content.push(imageText(reduced.hints.join(\"\\n\")));\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\treason = \"aggregateBytes\";\n\t\t\t}\n\t\t\tomitted.push({ index, reason });\n\t\t\tcontent.push(imageOmissionBlock(reason, model));\n\t\t}\n\t\tfitted[index] = { ...message, content } as AgentMessage;\n\t}\n\treturn { messages: fitted, omitted };\n}\n\n// A fresh batch must fit as a whole. Don't spend the aggregate budget in transcript order.\nasync function fitFreshAggregate(fresh: ReadonlySet<AgentMessage>, limits: ImageLimits) {\n\tconst images = [...fresh].flatMap((message) =>\n\t\t\"content\" in message && Array.isArray(message.content)\n\t\t\t? message.content.filter((block): block is ImageContent => block.type === \"image\")\n\t\t\t: [],\n\t);\n\tif (\n\t\timages.length > limits.maxPerRequest ||\n\t\timages.length * limits.resize.maxBytes * 0.75 <= HCODE_REQUEST_MAX_IMAGE_BYTES\n\t)\n\t\treturn;\n\tlet total = 0;\n\tfor (const block of images) {\n\t\tconst result = await fitImage(block, limits, true);\n\t\tif (typeof result === \"string\") return;\n\t\ttotal += hcodeDecodedImageBytes(result.image.data);\n\t}\n\tif (total <= HCODE_REQUEST_MAX_IMAGE_BYTES) return;\n\tconst maxBytes = Math.floor(HCODE_REQUEST_MAX_IMAGE_BYTES / images.length / 3) * 4;\n\tconst reduced = new Map<ImageContent, FitResult>();\n\tfor (const block of images) {\n\t\tif (!reduced.has(block)) reduced.set(block, await fitImage(block, limits, true, maxBytes));\n\t}\n\treturn reduced;\n}\n\nfunction imageText(text: string): HcodeText {\n\tconst block = { type: \"text\" as const, text };\n\toptionalImageText.add(block);\n\treturn block;\n}\n\nfunction imageOmissionBlock(reason: HcodeImageReason, model: Model<Api>): HcodeText {\n\treturn imageText(`[Image omitted from this HUMAIN Code request: ${hcodeImageMessage(reason, model)}]`);\n}\n\ntype PayloadMessage = { content: string | readonly { type: string }[] };\n\n/** Isolate the transcript from payload hooks and retain image provenance across reordering or cloning. */\nexport function hcodeImagePayloadDraft<T extends { context: { messages: PayloadMessage[] } }>(\n\tpayload: T,\n\tactive: ReadonlySet<number>,\n): { draft: T; protectedMessages: (messages: PayloadMessage[]) => Set<number> } {\n\tconst draft = JSON.parse(JSON.stringify(payload)) as T;\n\tconst fresh: ImageContent[] = [];\n\tconst history: ImageContent[] = [];\n\tfor (const [index, message] of payload.context.messages.entries()) {\n\t\tif (typeof message.content === \"string\") continue;\n\t\tconst copy = draft.context.messages[index]!.content as readonly { type: string }[];\n\t\tfor (const [i, block] of message.content.entries()) {\n\t\t\tif (block.type === \"image\") (active.has(index) ? fresh : history).push(block as ImageContent);\n\t\t\tif (block.type === \"text\" && optionalImageText.has(block as TextContent))\n\t\t\t\toptionalImageText.add(copy[i] as TextContent);\n\t\t}\n\t}\n\treturn {\n\t\tdraft,\n\t\tprotectedMessages(messages) {\n\t\t\treturn new Set(\n\t\t\t\tmessages.flatMap((message, index) => {\n\t\t\t\t\tif (typeof message.content === \"string\") return [];\n\t\t\t\t\tconst protectedImage = message.content.some((block) => {\n\t\t\t\t\t\tif (block.type !== \"image\") return false;\n\t\t\t\t\t\tconst { data, mimeType } = block as ImageContent;\n\t\t\t\t\t\tconst matches = (image: ImageContent) => image.data === data && image.mimeType === mimeType;\n\t\t\t\t\t\t// Added or changed images are not eligible for silent eviction. Fresh wins on identical copies.\n\t\t\t\t\t\treturn Object.keys(block).length !== 3 || fresh.some(matches) || !history.some(matches);\n\t\t\t\t\t});\n\t\t\t\t\treturn protectedImage ? [index] : [];\n\t\t\t\t}),\n\t\t\t);\n\t\t},\n\t};\n}\n\n/** The catalog and hard wire limits apply to the exact JSON, including image metadata and options. */\nexport async function fitHcodeRequestSize<T extends { role: string; content: string | readonly { type: string }[] }>(\n\tmodel: Model<Api>,\n\tmessages: T[],\n\tactive: ReadonlySet<number>,\n\tserialize: (messages: T[]) => string,\n): Promise<{ body: string; omitted: number } | undefined> {\n\tconst limit = Math.min(12582912, model.inputLimits?.maxRequestBytes ?? 12582912);\n\tconst imageData = (block: { type: string }): block is ImageContent => block.type === \"image\";\n\tconst byteLength = (value: string) => Buffer.byteLength(value, \"utf8\");\n\tlet body = serialize(messages);\n\tlet bytes = byteLength(body);\n\tlet nonImageBytes = bytes;\n\tlet hasImageContent = false;\n\tfor (const message of messages) {\n\t\tif (typeof message.content === \"string\") continue;\n\t\tfor (const block of message.content) {\n\t\t\tif (imageData(block)) {\n\t\t\t\tnonImageBytes -= block.data.length;\n\t\t\t\thasImageContent = true;\n\t\t\t} else if (block.type === \"text\" && optionalImageText.has(block as TextContent)) hasImageContent = true;\n\t\t}\n\t}\n\tconst fits = () => bytes <= limit && nonImageBytes <= HCODE_REQUEST_MAX_NON_IMAGE_BYTES;\n\t// Text-only overflows cannot be fitted; classify them as size refusals, not schema failures.\n\tif (fits()) return { body, omitted: 0 };\n\tif (!hasImageContent) return;\n\n\tconst projected = messages.slice();\n\tconst optional: { put: (block: TextContent | undefined) => void; note: TextContent }[] = [];\n\tconst historical: ((block: TextContent | undefined) => void)[] = [];\n\tconst fresh: { put: (block: ImageContent) => void; image: ImageContent }[] = [];\n\tfor (const [index, message] of messages.entries()) {\n\t\tif (typeof message.content === \"string\" || (message.role !== \"user\" && message.role !== \"toolResult\")) continue;\n\t\tconst slots: ({ type: string } | undefined)[] = [...message.content];\n\t\tlet length = slots.length;\n\t\tfor (const [i, block] of message.content.entries()) {\n\t\t\tconst put = (value: (typeof slots)[number]) => {\n\t\t\t\tconst previous = slots[i];\n\t\t\t\tconst delta = (b: typeof previous) => (b ? byteLength(JSON.stringify(b)) : 0);\n\t\t\t\tconst data = (b: typeof previous) => (b && imageData(b) ? b.data.length : 0);\n\t\t\t\tconst separator = !previous && value && length > 0 ? 1 : previous && !value && length > 1 ? -1 : 0;\n\t\t\t\tlength += Number(value !== undefined) - Number(previous !== undefined);\n\t\t\t\tconst change = delta(value) - delta(previous) + separator;\n\t\t\t\tbytes += change;\n\t\t\t\tnonImageBytes += change + data(previous) - data(value);\n\t\t\t\tslots[i] = value;\n\t\t\t\tprojected[index] = { ...message, content: slots.filter((entry) => entry !== undefined) };\n\t\t\t};\n\t\t\tif (block.type === \"text\" && optionalImageText.has(block as TextContent))\n\t\t\t\toptional.push({ put, note: block as TextContent });\n\t\t\telse if (imageData(block)) {\n\t\t\t\tif (active.has(index)) fresh.push({ put, image: block });\n\t\t\t\telse historical.push(put);\n\t\t\t}\n\t\t}\n\t}\n\tfor (const { put } of optional) put(undefined);\n\tlet omitted = 0;\n\tfor (const put of historical) {\n\t\tif (fits()) break;\n\t\tput(undefined);\n\t\tomitted++;\n\t\toptional.push({ put, note: imageText(\"[Image omitted: request size limit.]\") });\n\t}\n\tif (!fits() && nonImageBytes <= HCODE_REQUEST_MAX_NON_IMAGE_BYTES) {\n\t\tconst limits = imageLimits(model);\n\t\tconst autoResize = imageOmissionObserver.getStore()?.autoResizeImages ?? true;\n\t\tif (limits && autoResize) {\n\t\t\t// Reserve wire metadata for every attachment; smaller images keep their bytes first.\n\t\t\tfresh.sort((a, b) => a.image.data.length - b.image.data.length);\n\t\t\tlet remaining = limit - bytes + fresh.reduce((sum, { image }) => sum + image.data.length, 0);\n\t\t\tfor (const [i, { put, image }] of fresh.entries()) {\n\t\t\t\tconst share = Math.floor(remaining / (fresh.length - i));\n\t\t\t\tconst result = await fitImage(image, limits, true, share);\n\t\t\t\tif (typeof result === \"string\") return;\n\t\t\t\tput(result.image);\n\t\t\t\tremaining -= result.image.data.length + result.image.mimeType.length - image.mimeType.length;\n\t\t\t}\n\t\t}\n\t}\n\tif (!fits()) return;\n\tfor (const { put, note } of optional) {\n\t\tput(note);\n\t\tif (!fits()) put(undefined);\n\t}\n\tbody = serialize(projected);\n\treturn { body, omitted };\n}\n\nfunction imageLimits(model: Model<Api>): ImageLimits | undefined {\n\t// The provider supplies only its X1-validated, immutable canonical model; pi's generic limits are optional.\n\treturn model.input.includes(\"image\") ? (model.inputLimits?.images as ImageLimits | undefined) : undefined;\n}\n\ntype FitResult = { image: ImageContent; hints: string[] } | HcodeImageReason;\n\n// History blocks are stable objects, so each image is decoded and resized once per limits profile.\nconst fitCache = new WeakMap<ImageContent, { limits: ImageLimits; autoResizeImages: boolean; result: FitResult }>();\n\nasync function fitImage(\n\tblock: ImageContent,\n\tlimits: ImageLimits,\n\tautoResizeImages: boolean,\n\tbyteBudget = limits.resize.maxBytes,\n): Promise<FitResult> {\n\tconst maxBytes = Math.min(byteBudget, limits.resize.maxBytes);\n\tif (maxBytes < 4) return \"size\";\n\tconst cacheable = maxBytes === limits.resize.maxBytes;\n\tconst cached = cacheable ? fitCache.get(block) : undefined;\n\tif (cached?.limits === limits && cached.autoResizeImages === autoResizeImages) return cached.result;\n\tconst effective = cacheable ? limits : { ...limits, resize: { ...limits.resize, maxBytes } };\n\tconst processed = await processImage(Buffer.from(block.data, \"base64\"), block.mimeType, {\n\t\tautoResizeImages,\n\t\tresizeOptions: effective.resize,\n\t\tmimeTypes: HCODE_IMAGE_MIME_TYPES,\n\t});\n\tlet result: FitResult;\n\tif (!processed.ok) result = (await checkHcodeImage(block, effective)) ?? \"size\";\n\telse {\n\t\tconst unchanged = processed.data === block.data && processed.mimeType === block.mimeType;\n\t\tconst image: ImageContent = unchanged\n\t\t\t? block\n\t\t\t: { type: \"image\", data: processed.data, mimeType: processed.mimeType };\n\t\tresult = (await checkHcodeImage(image, effective)) ?? { image, hints: processed.hints };\n\t}\n\tif (cacheable) fitCache.set(block, { limits, autoResizeImages, result });\n\treturn result;\n}\n\n/** One plain message per refusal cause, naming the catalog limit that applies. */\nexport function hcodeImageMessage(reason: HcodeImageReason, model: Model<Api>): string {\n\tconst limits = imageLimits(model);\n\tswitch (reason) {\n\t\tcase \"blocked\":\n\t\t\treturn \"HUMAIN Code image attachments are blocked. Remove them or change /settings before sending.\";\n\t\tcase \"requestBytes\":\n\t\t\treturn \"Earlier images exceeded the HUMAIN Code request size limit.\";\n\t\tcase \"unsupported\":\n\t\t\treturn \"This HUMAIN Code model doesn't support images. Remove the image or choose an image-capable model with /model.\";\n\t\tcase \"perMessage\":\n\t\t\treturn `HUMAIN Code accepts at most ${images(limits?.maxPerMessage)} per message. Remove some images and try again.`;\n\t\tcase \"perRequest\":\n\t\t\treturn `HUMAIN Code accepts at most ${images(limits?.maxPerRequest)} per request, including earlier messages. Remove some images and try again.`;\n\t\tcase \"aggregateBytes\":\n\t\t\treturn \"This HUMAIN Code request exceeds the combined image size limit of 8 MiB. Attach fewer or smaller images.\";\n\t\tcase \"size\":\n\t\t\treturn `This image couldn't be reduced to the HUMAIN Code limits (${limits?.resize.maxWidth}x${limits?.resize.maxHeight} px, ${limits?.resize.maxBytes} bytes). Attach a smaller image.`;\n\t\tcase \"invalid\":\n\t\t\treturn \"This image isn't a readable single-frame PNG, JPEG or WebP image. Attach a different image.\";\n\t}\n}\n\nfunction images(count: number | undefined): string {\n\treturn count === 1 ? \"1 image\" : `${count} images`;\n}\n\n/** Refuse a request whose images do not meet the model's limits; the final guard before the wire. */\nexport async function validateHcodeImages(\n\tmodel: Model<Api>,\n\tmessages: readonly { content: string | readonly { type: string }[] }[],\n): Promise<void> {\n\tconst groups = messages.flatMap((message) => {\n\t\tif (typeof message.content === \"string\") return [];\n\t\tconst content = message.content.filter((block): block is ImageContent => block.type === \"image\");\n\t\treturn content.length ? [content] : [];\n\t});\n\tif (!groups.length) return;\n\tconst limits = imageLimits(model);\n\tconst refuse = (reason: HcodeImageReason) => {\n\t\tthrow new Error(hcodeImageMessage(reason, model));\n\t};\n\tif (!limits) return refuse(\"unsupported\");\n\tif (groups.some((group) => group.length > limits.maxPerMessage)) return refuse(\"perMessage\");\n\tconst blocks = groups.flat();\n\tif (blocks.length > limits.maxPerRequest) return refuse(\"perRequest\");\n\tlet bytes = 0;\n\tfor (const block of blocks) {\n\t\tconst reason = await checkHcodeImage(block, limits);\n\t\tif (reason) return refuse(reason);\n\t\tbytes += hcodeDecodedImageBytes(block.data);\n\t}\n\tif (bytes > HCODE_REQUEST_MAX_IMAGE_BYTES) return refuse(\"aggregateBytes\");\n\ttry {\n\t\t// Reuse X1's canonical base64, MIME, count and aggregate byte bounds for the whole request.\n\t\tparseHcodeMessagesRequest({\n\t\t\tmodel: model.id,\n\t\t\tcontext: { messages: groups.map((content) => ({ role: \"user\", content, timestamp: 0 })) },\n\t\t});\n\t} catch {\n\t\trefuse(\"size\");\n\t}\n}\n\n/** Check one image against the limits without changing it; undefined when it can be sent as is. */\nasync function checkHcodeImage(block: ImageContent, limits: ImageLimits): Promise<HcodeImageReason | undefined> {\n\tif (block.data.length > limits.resize.maxBytes) return \"size\";\n\ttry {\n\t\tparseHcodeMessagesRequest({\n\t\t\tmodel: \"image\",\n\t\t\tcontext: { messages: [{ role: \"user\", content: [block], timestamp: 0 }] },\n\t\t});\n\t} catch {\n\t\treturn \"invalid\";\n\t}\n\tconst dimensions = getImageDimensions(block.data, block.mimeType);\n\tif (!dimensions || dimensions.widthPx < 1 || dimensions.heightPx < 1) return \"invalid\";\n\tif (dimensions.widthPx > limits.resize.maxWidth || dimensions.heightPx > limits.resize.maxHeight) return \"size\";\n\tconst data = Buffer.from(block.data, \"base64\");\n\t// Image bytes are wire input: reject animation, incomplete containers and hidden trailing frames before decoding.\n\tif (!isStaticImageContainer(data, block.mimeType)) return \"invalid\";\n\tconst photon = await loadPhoton();\n\tif (!photon) return \"invalid\";\n\ttry {\n\t\tconst image = photon.PhotonImage.new_from_byteslice(data);\n\t\ttry {\n\t\t\tif (image.get_width() !== dimensions.widthPx || image.get_height() !== dimensions.heightPx) return \"invalid\";\n\t\t} finally {\n\t\t\timage.free();\n\t\t}\n\t} catch {\n\t\treturn \"invalid\";\n\t}\n\treturn undefined;\n}\n\nfunction isStaticImageContainer(data: Buffer, mime: string): boolean {\n\tif (mime === \"image/png\") {\n\t\tlet offset = 8,\n\t\t\tpixels = false;\n\t\twhile (offset + 12 <= data.length) {\n\t\t\tconst length = data.readUInt32BE(offset),\n\t\t\t\tname = data.toString(\"ascii\", offset + 4, offset + 8);\n\t\t\tif (length > data.length - offset - 12 || name === \"acTL\" || name === \"fcTL\" || name === \"fdAT\") return false;\n\t\t\tif (name === \"IDAT\") pixels = true;\n\t\t\toffset += length + 12;\n\t\t\tif (name === \"IEND\") return !length && pixels && offset === data.length;\n\t\t}\n\t} else if (mime === \"image/webp\") {\n\t\tif (data.length < 12 || data.readUInt32LE(4) !== data.length - 8) return false;\n\t\tlet offset = 12,\n\t\t\tframes = 0;\n\t\twhile (offset + 8 <= data.length) {\n\t\t\tconst name = data.toString(\"ascii\", offset, offset + 4),\n\t\t\t\tlength = data.readUInt32LE(offset + 4);\n\t\t\tif (\n\t\t\t\tlength > data.length - offset - 8 ||\n\t\t\t\tname === \"ANIM\" ||\n\t\t\t\tname === \"ANMF\" ||\n\t\t\t\t(name === \"VP8X\" && data[offset + 8]! & 2)\n\t\t\t)\n\t\t\t\treturn false;\n\t\t\tif (name === \"VP8 \" || name === \"VP8L\") frames++;\n\t\t\toffset += 8 + length + (length % 2);\n\t\t}\n\t\treturn offset === data.length && frames === 1;\n\t} else if (mime === \"image/jpeg\") {\n\t\tlet offset = 2;\n\t\twhile (offset < data.length) {\n\t\t\tif (data[offset++] !== 255) continue;\n\t\t\twhile (data[offset] === 255) offset++;\n\t\t\tconst marker = data[offset++];\n\t\t\tif (marker === 217) return offset === data.length;\n\t\t\tif (marker === 216) return false;\n\t\t\tif (marker === 0 || marker === 1 || (marker !== undefined && marker >= 208 && marker <= 215)) continue;\n\t\t\tif (offset + 2 > data.length) return false;\n\t\t\tconst length = data.readUInt16BE(offset);\n\t\t\tif (length < 2 || length > data.length - offset) return false;\n\t\t\toffset += length;\n\t\t}\n\t}\n\treturn false;\n}\n"]}
|
|
@@ -69,6 +69,6 @@ export function hcodeSignedInElsewhereNotice(environmentId, elsewhere) {
|
|
|
69
69
|
const other = elsewhere[0];
|
|
70
70
|
if (!other)
|
|
71
71
|
return undefined;
|
|
72
|
-
return `${hcodeDisplayName(environmentId)}: not signed in. Your saved sign-in is for ${hcodeDisplayName(other)}: start humain-code with --env ${other} to use it, or /login to sign in here.`;
|
|
72
|
+
return `${hcodeDisplayName(environmentId)}: not signed in. HUMAIN Code now defaults to production. Your saved sign-in is for ${hcodeDisplayName(other)} and was not moved: start humain-code with --env ${other} to use it, or /login to sign in here.`;
|
|
73
73
|
}
|
|
74
74
|
//# sourceMappingURL=login-copy.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,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C3B,IAAI,CAAC,KAAK;QAAE,OAAO,SAAS,CAAC;IAC7B,OAAO,GAAG,gBAAgB,CAAC,aAAa,CAAC,sFAAsF,gBAAgB,CAAC,KAAK,CAAC,oDAAoD,KAAK,wCAAwC,CAAC;AACzP,CAAC","sourcesContent":["// Plain-language copy for HUMAIN Code sign-in readiness and an empty model list; fixed text only, never server text.\nimport type { HcodeCatalogEmptyReason } from \"./contracts.ts\";\nimport { hcodeDisplayName } from \"./environment.ts\";\nimport type { HcodeLoginReadiness } from \"./facade.ts\";\n\n/** Why a signed-in account has no models: Forge's reason (if it sent one), or the list couldn't be loaded. */\nexport type HcodeEmptyCatalogCause = { kind: \"empty\"; reason?: HcodeCatalogEmptyReason } | { kind: \"failed\" };\n\n/** Guidance for a direct login when the server's sign-in settings don't match this CLI. */\nexport const HCODE_LOGIN_MISMATCH_DETAILS =\n\t\"HUMAIN Code's sign-in settings (/api/cli/config or issuer discovery) don't match what this CLI version accepts. Update the CLI with `humain-code update`, or ask the HUMAIN Code platform team to check the server's CLI sign-in configuration.\";\n\nconst EMPTY_REASONS: Readonly<Record<HcodeCatalogEmptyReason, { reason: string; fix: string }>> = {\n\tno_cli_models_approved: {\n\t\treason: \"no model is approved for CLI\",\n\t\tfix: \"Ask an admin to set a model to Web + CLI or CLI only in Settings > Model Access.\",\n\t},\n\tprovider_key_not_cli_enabled: {\n\t\treason: \"the provider key isn't enabled for CLI\",\n\t\tfix: \"Ask an admin to enable CLI on the key in Settings > Provider Keys.\",\n\t},\n\tcli_capacity_unconfigured: {\n\t\treason: \"CLI capacity hasn't been configured\",\n\t\tfix: \"Ask the HUMAIN Code platform team to check the deployment's CLI capacity limits.\",\n\t},\n\tprovider_key_not_dedicated: {\n\t\treason: \"the provider key is shared or isn't approved for CLI use\",\n\t\tfix: \"Ask an admin to configure a dedicated key for HUMAIN Code CLI.\",\n\t},\n\tmodels_not_qualified: {\n\t\treason: \"this server hasn't finished CLI setup for the approved models\",\n\t\tfix: \"Ask an admin to report it to the HUMAIN Code platform team.\",\n\t},\n};\n\n/** Say why the account's catalog is empty and what to do; servers without a reason keep the generic text. */\nexport function hcodeEmptyCatalogMessage(reason: HcodeCatalogEmptyReason | undefined): string {\n\tif (!reason) return \"Your admin hasn't enabled CLI models yet.\";\n\tconst { reason: why, fix } = EMPTY_REASONS[reason];\n\treturn `No models are available in the CLI: ${why}. ${fix}`;\n}\n\n/** The short reason and who can fix it: an admin, the server's configuration or the network. */\nexport function hcodeEmptyCatalogReason(cause: HcodeEmptyCatalogCause): { reason: string; fix: string } {\n\tif (cause.kind === \"failed\")\n\t\treturn { reason: \"the model list couldn't be loaded\", fix: \"Check your network, VPN or Zscaler.\" };\n\treturn cause.reason\n\t\t? EMPTY_REASONS[cause.reason]\n\t\t: { reason: \"your admin hasn't enabled CLI models yet\", fix: \"Ask an admin to enable a model for CLI.\" };\n}\n\n/** Non-blocking notice after a sign-in that produced no models. */\nexport function hcodeEmptyCatalogNotice(\n\tenvironmentId: string,\n\temail: string | undefined,\n\tcause: HcodeEmptyCatalogCause,\n): string {\n\tconst { reason, fix } = hcodeEmptyCatalogReason(cause);\n\treturn [\n\t\t`✓ Signed in to ${hcodeDisplayName(environmentId)}${email ? ` as ${email}` : \"\"}`,\n\t\t` No models available in the CLI yet: ${reason}.`,\n\t\t` ${fix}`,\n\t\t\" You can keep using your other providers. I'll check again automatically.\",\n\t\t\" /model to retry · /login status for details\",\n\t].join(\"\\n\");\n}\n\n/** `/login` row state for a readiness check; `undefined` means the check is still running. */\nexport function hcodeLoginAvailability(readiness: HcodeLoginReadiness | undefined): {\n\tstate: \"pending\" | \"ready\" | \"failed\";\n\ttext: string;\n} {\n\tif (!readiness) return { state: \"pending\", text: \"checking connection…\" };\n\tswitch (readiness.kind) {\n\t\tcase \"ready\":\n\t\t\treturn { state: \"ready\", text: \"connected\" };\n\t\tcase \"unreachable\":\n\t\t\treturn { state: \"failed\", text: `Can't reach ${readiness.host}: check VPN/Zscaler [Retry]` };\n\t\tcase \"mismatch\":\n\t\t\treturn { state: \"failed\", text: \"Server sign-in settings don't match this CLI version [Details]\" };\n\t\tcase \"unavailable\":\n\t\t\treturn { state: \"failed\", text: \"Sign-in is not available in this environment [Retry]\" };\n\t}\n}\n\n/** Says that the saved sign-in belongs to another environment and how to use it, e.g. after starting without --env. */\nexport function hcodeSignedInElsewhereNotice(environmentId: string, elsewhere: readonly string[]): string | undefined {\n\tconst other = elsewhere[0];\n\tif (!other) return undefined;\n\treturn `${hcodeDisplayName(environmentId)}: not signed in. HUMAIN Code now defaults to production. Your saved sign-in is for ${hcodeDisplayName(other)} and was not moved: start humain-code with --env ${other} to use it, or /login to sign in here.`;\n}\n"]}
|
|
@@ -2,7 +2,9 @@ import type { AssistantMessage } from "@earendil-works/pi-ai";
|
|
|
2
2
|
import { type HcodeInferenceError } from "./contracts.ts";
|
|
3
3
|
export declare const HCODE_PENDING_EXPLANATION = "Pending usage is awaiting provider confirmation. It remains reserved until confirmed or reviewed by an admin. It is not a final charge and is not free usage.";
|
|
4
4
|
export declare const HCODE_AMBIGUOUS_NOTICE = "HUMAIN Code couldn't confirm this request's outcome. It may still be charged. No automatic retry was sent. Check /usage before trying again.";
|
|
5
|
+
export declare const BUILD_SESSION_ENDED = "Build session ended. Start a new Build run.";
|
|
5
6
|
declare const localReasons: {
|
|
7
|
+
readonly buildSessionEnded: "Build session ended. Start a new Build run.";
|
|
6
8
|
readonly account: "The selected HUMAIN Code account or model is no longer current.";
|
|
7
9
|
readonly transport: "HUMAIN Code only supports SSE for this request.";
|
|
8
10
|
readonly envelope: "The CLI could not build a valid HUMAIN Code request envelope.";
|
|
@@ -17,13 +19,32 @@ declare const localReasons: {
|
|
|
17
19
|
readonly cancelled: "The HUMAIN Code request was cancelled before submission.";
|
|
18
20
|
};
|
|
19
21
|
export type HcodeLocalReason = keyof typeof localReasons;
|
|
22
|
+
declare const localDetails: {
|
|
23
|
+
readonly messageLimit: readonly ["context.messages", "History exceeds 512 messages; compact the session before retrying."];
|
|
24
|
+
readonly schema: readonly ["$", "Request structure failed local schema validation."];
|
|
25
|
+
readonly "message.schema": readonly ["context.messages", "History failed local schema validation."];
|
|
26
|
+
readonly "system.schema": readonly ["context.messages[*]", "A system message failed local schema validation."];
|
|
27
|
+
readonly "user.schema": readonly ["context.messages[*]", "A user message failed local schema validation."];
|
|
28
|
+
readonly "assistant.schema": readonly ["context.messages[*]", "An assistant message failed local schema validation."];
|
|
29
|
+
readonly "assistant.deferred": readonly ["context.messages[*]", "Assistant history contains a deferred response."];
|
|
30
|
+
readonly "toolCall.schema": readonly ["context.messages[*].content[*]", "A tool call failed local schema validation."];
|
|
31
|
+
readonly "toolCall.orphan": readonly ["context.messages[*].content[*]", "Tool-call history is missing a matching result."];
|
|
32
|
+
readonly "toolCall.unknownTool": readonly ["context.messages[*].content[*].name", "Tool-call history references an unavailable tool."];
|
|
33
|
+
readonly "toolCall.argumentsError": readonly ["context.messages[*].content[*].argumentsError", "Tool-call history contains invalid arguments."];
|
|
34
|
+
readonly "toolCall.duplicate": readonly ["context.messages[*].content[*].id", "Tool-call history contains a repeated call."];
|
|
35
|
+
readonly "toolResult.schema": readonly ["context.messages[*]", "A tool result failed local schema validation."];
|
|
36
|
+
readonly "toolResult.orphan": readonly ["context.messages[*]", "Tool-result history has no matching call."];
|
|
37
|
+
readonly "options.schema": readonly ["options", "Request options failed local schema validation."];
|
|
38
|
+
readonly "toolChoice.unknownTool": readonly ["options.toolChoice", "The current tool choice is unavailable."];
|
|
39
|
+
};
|
|
40
|
+
export type HcodeLocalDetail = keyof typeof localDetails;
|
|
20
41
|
/** Header names and closed reason values Forge sends with deterministic refusals. */
|
|
21
42
|
export declare const HCODE_REFUSAL_REASON_HEADERS: {
|
|
22
43
|
readonly model_unavailable: readonly ["x-hcode-model-unavailable-reason", string[]];
|
|
23
44
|
readonly unsupported_capability: readonly ["x-hcode-unsupported-capability-reason", string[]];
|
|
24
45
|
};
|
|
25
46
|
/** Render a closed, non-reflecting reason for an inference that never reached the send boundary. */
|
|
26
|
-
export declare function formatHcodeLocalRefusal(reason: unknown): string | undefined;
|
|
47
|
+
export declare function formatHcodeLocalRefusal(reason: unknown, detail?: unknown): string | undefined;
|
|
27
48
|
/** Format the server's reset instant in UTC, independently of the host timezone. */
|
|
28
49
|
export declare function formatHcodeReset(resetAt: string): string;
|
|
29
50
|
/** Render schema-validated service facts without reading raw diagnostics or granting automatic retry. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"notices.d.ts","sourceRoot":"","sources":["../../../src/humain/hcode/notices.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAC9D,OAAO,EAAE,KAAK,mBAAmB,EAA6C,MAAM,gBAAgB,CAAC;AAGrG,eAAO,MAAM,yBAAyB,kKAC0H,CAAC;AAEjK,eAAO,MAAM,sBAAsB,iJAC4G,CAAC;AAEhJ,QAAA,MAAM,YAAY;aACjB,OAAO,EAAE,iEAAiE;aAC1E,SAAS,EAAE,iDAAiD;aAC5D,QAAQ,EAAE,+DAA+D;aACzE,IAAI,EAAE,iEAAiE;aACvE,KAAK,EAAE,kEAAkE;aACzE,SAAS,EAAE,mGAAmG;aAC9G,MAAM,EAAE,yEAAyE;aACjF,KAAK,EAAE,sDAAsD;aAC7D,KAAK,EAAE,wDAAwD;aAC/D,WAAW,EAAE,6DAA6D;aAC1E,MAAM,EAAE,6EAA6E;aACrF,SAAS,EAAE,0DAA0D;CAC5D,CAAC;AAEX,MAAM,MAAM,gBAAgB,GAAG,MAAM,OAAO,YAAY,CAAC;AA8BzD,qFAAqF;AACrF,eAAO,MAAM,4BAA4B;;;CAGuE,CAAC;AA0BjH,oGAAoG;AACpG,wBAAgB,uBAAuB,CAAC,MAAM,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,
|
|
1
|
+
{"version":3,"file":"notices.d.ts","sourceRoot":"","sources":["../../../src/humain/hcode/notices.ts"],"names":[],"mappings":"AACA,OAAO,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AAqB,EAAE,+CAA+C;aAC5F,mBAAmB,YAAG,qBAAqB,EAAE,2CAA2C;aACxF,gBAAgB,YAAG,SAAS,EAAE,iDAAiD;aAC/E,wBAAwB,YAAG,oBAAoB,EAAE,yCAAyC;CACjF,CAAC;AAEX,MAAM,MAAM,gBAAgB,GAAG,MAAM,OAAO,YAAY,CAAC;AA8BzD,qFAAqF;AACrF,eAAO,MAAM,4BAA4B;;;CAGuE,CAAC;AA0BjH,oGAAoG;AACpG,wBAAgB,uBAAuB,CAAC,MAAM,EAAE,OAAO,EAAE,MAAM,CAAC,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CAU7F;AAED,oFAAoF;AACpF,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAExD;AAED,yGAAyG;AACzG,wBAAgB,iBAAiB,CAChC,OAAO,EAAE,mBAAmB,EAC5B,UAAU,EAAE,MAAM,EAClB,MAAM,CAAC,EAAE,OAAO,GACd;IACF,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,SAAS,MAAM,EAAE,CAAC;IACzB,YAAY,CAAC,EAAE,MAAM,CAAC;CACtB,CAkDA;AAED,wGAAwG;AACxG,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,gBAAgB,GAAG,MAAM,GAAG,SAAS,CAyBtF"}
|
|
@@ -2,7 +2,9 @@ import { parseHcodeInferenceError } from "./contracts.js";
|
|
|
2
2
|
import { HCODE_PROVIDER } from "./http.js";
|
|
3
3
|
export const HCODE_PENDING_EXPLANATION = "Pending usage is awaiting provider confirmation. It remains reserved until confirmed or reviewed by an admin. It is not a final charge and is not free usage.";
|
|
4
4
|
export const HCODE_AMBIGUOUS_NOTICE = "HUMAIN Code couldn't confirm this request's outcome. It may still be charged. No automatic retry was sent. Check /usage before trying again.";
|
|
5
|
+
export const BUILD_SESSION_ENDED = "Build session ended. Start a new Build run.";
|
|
5
6
|
const localReasons = {
|
|
7
|
+
buildSessionEnded: BUILD_SESSION_ENDED,
|
|
6
8
|
account: "The selected HUMAIN Code account or model is no longer current.",
|
|
7
9
|
transport: "HUMAIN Code only supports SSE for this request.",
|
|
8
10
|
envelope: "The CLI could not build a valid HUMAIN Code request envelope.",
|
|
@@ -16,6 +18,27 @@ const localReasons = {
|
|
|
16
18
|
images: "An image is unsupported or exceeds the selected HUMAIN Code model's limits.",
|
|
17
19
|
cancelled: "The HUMAIN Code request was cancelled before submission.",
|
|
18
20
|
};
|
|
21
|
+
const localDetails = {
|
|
22
|
+
messageLimit: ["context.messages", "History exceeds 512 messages; compact the session before retrying."],
|
|
23
|
+
schema: ["$", "Request structure failed local schema validation."],
|
|
24
|
+
"message.schema": ["context.messages", "History failed local schema validation."],
|
|
25
|
+
"system.schema": ["context.messages[*]", "A system message failed local schema validation."],
|
|
26
|
+
"user.schema": ["context.messages[*]", "A user message failed local schema validation."],
|
|
27
|
+
"assistant.schema": ["context.messages[*]", "An assistant message failed local schema validation."],
|
|
28
|
+
"assistant.deferred": ["context.messages[*]", "Assistant history contains a deferred response."],
|
|
29
|
+
"toolCall.schema": ["context.messages[*].content[*]", "A tool call failed local schema validation."],
|
|
30
|
+
"toolCall.orphan": ["context.messages[*].content[*]", "Tool-call history is missing a matching result."],
|
|
31
|
+
"toolCall.unknownTool": ["context.messages[*].content[*].name", "Tool-call history references an unavailable tool."],
|
|
32
|
+
"toolCall.argumentsError": [
|
|
33
|
+
"context.messages[*].content[*].argumentsError",
|
|
34
|
+
"Tool-call history contains invalid arguments.",
|
|
35
|
+
],
|
|
36
|
+
"toolCall.duplicate": ["context.messages[*].content[*].id", "Tool-call history contains a repeated call."],
|
|
37
|
+
"toolResult.schema": ["context.messages[*]", "A tool result failed local schema validation."],
|
|
38
|
+
"toolResult.orphan": ["context.messages[*]", "Tool-result history has no matching call."],
|
|
39
|
+
"options.schema": ["options", "Request options failed local schema validation."],
|
|
40
|
+
"toolChoice.unknownTool": ["options.toolChoice", "The current tool choice is unavailable."],
|
|
41
|
+
};
|
|
19
42
|
/** Forge's closed `x-hcode-model-unavailable-reason` values, in plain words. */
|
|
20
43
|
const modelUnavailableReasons = {
|
|
21
44
|
catalog_entry_unavailable: "This model is no longer in your HUMAIN Code catalog.",
|
|
@@ -69,10 +92,18 @@ function refusalReason(code, reason) {
|
|
|
69
92
|
return Object.hasOwn(table, reason) ? table[reason] : undefined;
|
|
70
93
|
}
|
|
71
94
|
/** Render a closed, non-reflecting reason for an inference that never reached the send boundary. */
|
|
72
|
-
export function formatHcodeLocalRefusal(reason) {
|
|
95
|
+
export function formatHcodeLocalRefusal(reason, detail) {
|
|
73
96
|
if (typeof reason !== "string" || !Object.hasOwn(localReasons, reason))
|
|
74
97
|
return undefined;
|
|
75
|
-
|
|
98
|
+
if (reason === "buildSessionEnded")
|
|
99
|
+
return BUILD_SESSION_ENDED;
|
|
100
|
+
// Persisted diagnostics are untrusted: only closed detail codes may affect presentation.
|
|
101
|
+
let explanation = "";
|
|
102
|
+
if (reason === "envelope" && typeof detail === "string" && Object.hasOwn(localDetails, detail)) {
|
|
103
|
+
const [path, message] = localDetails[detail];
|
|
104
|
+
explanation = ` ${message} [${detail} at ${path}]`;
|
|
105
|
+
}
|
|
106
|
+
return `${localReasons[reason]}${explanation} No request was sent or charged.`;
|
|
76
107
|
}
|
|
77
108
|
/** Format the server's reset instant in UTC, independently of the host timezone. */
|
|
78
109
|
export function formatHcodeReset(resetAt) {
|
|
@@ -135,7 +166,7 @@ export function formatHcodeMessageNotice(message) {
|
|
|
135
166
|
return undefined;
|
|
136
167
|
if (message.stopReason === "error") {
|
|
137
168
|
const diagnostic = message.diagnostics?.findLast((entry) => entry.type === "provider_http_error");
|
|
138
|
-
const local = formatHcodeLocalRefusal(diagnostic?.details?.hcodeLocalReason);
|
|
169
|
+
const local = formatHcodeLocalRefusal(diagnostic?.details?.hcodeLocalReason, diagnostic?.details?.hcodeLocalDetail);
|
|
139
170
|
if (local)
|
|
140
171
|
return local;
|
|
141
172
|
const refusal = diagnostic?.details?.hcode;
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rD,CAAC;YAAC,MAAM,CAAC;gBACR,sFAAsF;YACvF,CAAC;QACF,CAAC;IACF,CAAC;IACD,OAAO,sBAAsB,CAAC;AAC/B,CAAC","sourcesContent":["// Local, typed presentation of managed refusal facts; never schedules a request or reads a later balance.\nimport type { AssistantMessage } from \"@earendil-works/pi-ai\";\nimport { type HcodeInferenceError, type HcodeValue, parseHcodeInferenceError } from \"./contracts.ts\";\nimport { HCODE_PROVIDER } from \"./http.ts\";\n\nexport const HCODE_PENDING_EXPLANATION =\n\t\"Pending usage is awaiting provider confirmation. It remains reserved until confirmed or reviewed by an admin. It is not a final charge and is not free usage.\";\n\nexport const HCODE_AMBIGUOUS_NOTICE =\n\t\"HUMAIN Code couldn't confirm this request's outcome. It may still be charged. No automatic retry was sent. Check /usage before trying again.\";\n\nconst localReasons = {\n\taccount: \"The selected HUMAIN Code account or model is no longer current.\",\n\ttransport: \"HUMAIN Code only supports SSE for this request.\",\n\tenvelope: \"The CLI could not build a valid HUMAIN Code request envelope.\",\n\tsize: \"The request exceeds the HUMAIN Code model's request size limit.\",\n\tmodel: \"The request model does not match the selected HUMAIN Code model.\",\n\treasoning: \"The selected HUMAIN Code model does not support the requested thinking level or thinking history.\",\n\toutput: \"The requested output token limit exceeds the HUMAIN Code model's limit.\",\n\tcache: \"HUMAIN Code requires cache retention to be disabled.\",\n\ttools: \"The selected HUMAIN Code model does not support tools.\",\n\tstrictTools: \"HUMAIN Code does not support required strict tool sampling.\",\n\timages: \"An image is unsupported or exceeds the selected HUMAIN Code model's limits.\",\n\tcancelled: \"The HUMAIN Code request was cancelled before submission.\",\n} as const;\n\nexport type HcodeLocalReason = keyof typeof localReasons;\n\n/** Forge's closed `x-hcode-model-unavailable-reason` values, in plain words. */\nconst modelUnavailableReasons = {\n\tcatalog_entry_unavailable: \"This model is no longer in your HUMAIN Code catalog.\",\n\tcredential_unavailable: \"HUMAIN Code has no usable provider key for this model.\",\n\texecution_credentials_unavailable: \"HUMAIN Code has no usable provider key for this model.\",\n\tprovider_quota_isolation_unverified: \"This model's provider key isn't dedicated to HUMAIN Code.\",\n\tquota_mapping_unavailable: \"This model's capacity isn't set up for HUMAIN Code yet.\",\n\tconfiguration_changed: \"An admin changed this model's configuration.\",\n\texecution_config_unavailable: \"HUMAIN Code couldn't load this model's configuration.\",\n\texecution_model_mismatch: \"HUMAIN Code's configuration for this model doesn't match its catalog entry.\",\n\texecution_endpoint_mismatch: \"HUMAIN Code's endpoint for this model doesn't match its catalog entry.\",\n\texecution_region_mismatch: \"HUMAIN Code's provider key is set to a region this model can't run in.\",\n} as const;\n\n/** Forge's closed `x-hcode-unsupported-capability-reason` values, in plain words. */\nconst unsupportedCapabilityReasons = {\n\treasoning: \"This model doesn't support the requested thinking level.\",\n\ttool_choice: \"This model can't force a tool call while thinking.\",\n\ttemperature: \"This model doesn't accept a temperature setting.\",\n\tcache_retention: \"This model doesn't support the requested prompt caching.\",\n\ttools: \"This model doesn't support tools.\",\n\tstrict_tools: \"This model doesn't support strict tool schemas.\",\n\tthinking_history: \"This model can't replay thinking from earlier turns of this conversation.\",\n\ttool_call_history: \"This model can't replay tool calls from earlier turns of this conversation.\",\n\timages: \"This model can't accept these images.\",\n\testimate: \"HUMAIN Code couldn't estimate this request's cost.\",\n} as const;\n\n/** Header names and closed reason values Forge sends with deterministic refusals. */\nexport const HCODE_REFUSAL_REASON_HEADERS = {\n\tmodel_unavailable: [\"x-hcode-model-unavailable-reason\", Object.keys(modelUnavailableReasons)],\n\tunsupported_capability: [\"x-hcode-unsupported-capability-reason\", Object.keys(unsupportedCapabilityReasons)],\n} as const satisfies Partial<Record<HcodeInferenceError[\"error\"][\"code\"], readonly [string, readonly string[]]>>;\n\n// Refusals Forge returns before any provider dispatch; each settles as not dispatched, so nothing is charged.\nconst predispatchCodes = new Set<HcodeInferenceError[\"error\"][\"code\"]>([\n\t\"unauthorized\",\n\t\"forbidden\",\n\t\"legal_acknowledgment_required\",\n\t\"auth_dependency_unavailable\",\n\t\"invalid_request\",\n\t\"unsupported_capability\",\n\t\"model_unavailable\",\n]);\nconst NOT_CHARGED =\n\t\"HUMAIN Code refused this request before running it, so nothing was charged. No automatic retry was sent.\";\n\nfunction refusalReason(code: HcodeInferenceError[\"error\"][\"code\"], reason: unknown): string | undefined {\n\tif (typeof reason !== \"string\") return undefined;\n\tconst table: Record<string, string> =\n\t\tcode === \"model_unavailable\"\n\t\t\t? modelUnavailableReasons\n\t\t\t: code === \"unsupported_capability\"\n\t\t\t\t? unsupportedCapabilityReasons\n\t\t\t\t: {};\n\treturn Object.hasOwn(table, reason) ? table[reason] : undefined;\n}\n\n/** Render a closed, non-reflecting reason for an inference that never reached the send boundary. */\nexport function formatHcodeLocalRefusal(reason: unknown): string | undefined {\n\tif (typeof reason !== \"string\" || !Object.hasOwn(localReasons, reason)) return undefined;\n\treturn `${localReasons[reason as HcodeLocalReason]} No request was sent or charged.`;\n}\n\n/** Format the server's reset instant in UTC, independently of the host timezone. */\nexport function formatHcodeReset(resetAt: string): string {\n\treturn `Resets ${new Date(resetAt).toISOString().slice(0, 16).replace(\"T\", \" \")} UTC`;\n}\n\n/** Render schema-validated service facts without reading raw diagnostics or granting automatic retry. */\nexport function formatHcodeNotice(\n\tfailure: HcodeInferenceError,\n\treceivedAt: number,\n\treason?: unknown,\n): {\n\tmessage: string;\n\tlines: readonly string[];\n\tretryAfterMs?: number;\n} {\n\tconst error = failure.error;\n\tif (error.code === \"hcode_busy\") {\n\t\tconst retryAt = new Date(receivedAt + error.details.retryAfterMs);\n\t\t// A valid delay can exceed Date's range. Omit the time, not the no-dispatch fact.\n\t\tconst retryTime = Number.isNaN(retryAt.getTime())\n\t\t\t? undefined\n\t\t\t: retryAt.toISOString().split(\".\")[0].replace(\"T\", \" \");\n\t\treturn {\n\t\t\tmessage: error.message,\n\t\t\tlines: [\n\t\t\t\t...(retryTime ? [`Retry after ${retryTime} UTC.`] : []),\n\t\t\t\t\"No request was dispatched. No automatic retry was sent.\",\n\t\t\t],\n\t\t\tretryAfterMs: error.details.retryAfterMs,\n\t\t};\n\t}\n\tif (error.code === \"quota_exceeded\") {\n\t\tconst usage = error.details.usage;\n\t\tconst money = (value: HcodeValue | { kind: \"unlimited\" }) =>\n\t\t\tvalue.kind === \"known\"\n\t\t\t\t? `${value.value} ${usage.currency} ${usage.unit}${value.value === 1 ? \"\" : \"s\"}`\n\t\t\t\t: value.kind;\n\t\treturn {\n\t\t\tmessage: error.message,\n\t\t\tlines: [\n\t\t\t\t`Used${usage.costComplete ? \"\" : \" (known subtotal)\"} ${money(usage.actual)}`,\n\t\t\t\t`Pending ${money(usage.reserved)}`,\n\t\t\t\t`Remaining ${money(usage.remaining)}`,\n\t\t\t\tformatHcodeReset(usage.period.resetAt),\n\t\t\t\t\"No request was dispatched. No automatic retry was sent.\",\n\t\t\t],\n\t\t};\n\t}\n\tconst recovery =\n\t\terror.code === \"unauthorized\"\n\t\t\t? \"Sign in again with /login.\"\n\t\t\t: error.code === \"legal_acknowledgment_required\"\n\t\t\t\t? \"Accept terms in the web app, then try again.\"\n\t\t\t\t: error.code === \"model_unavailable\"\n\t\t\t\t\t? \"Choose another model with /model, or ask your admin.\"\n\t\t\t\t\t: error.code === \"unsupported_capability\"\n\t\t\t\t\t\t? \"Change the setting, start a new conversation with /new, or choose another model with /model.\"\n\t\t\t\t\t\t: undefined;\n\tif (!predispatchCodes.has(error.code)) return { message: error.message, lines: [HCODE_AMBIGUOUS_NOTICE] };\n\tconst detail = refusalReason(error.code, reason);\n\treturn {\n\t\tmessage: error.message,\n\t\tlines: [...(detail ? [detail] : []), ...(recovery ? [recovery] : []), NOT_CHARGED],\n\t};\n}\n\n/** Shared print/interactive boundary for validated refusals and separate uncertain-outcome warnings. */\nexport function formatHcodeMessageNotice(message: AssistantMessage): string | undefined {\n\tif (message.provider !== HCODE_PROVIDER) return undefined;\n\tif (message.stopReason === \"error\") {\n\t\tconst diagnostic = message.diagnostics?.findLast((entry) => entry.type === \"provider_http_error\");\n\t\tconst local = formatHcodeLocalRefusal(diagnostic?.details?.hcodeLocalReason);\n\t\tif (local) return local;\n\t\tconst refusal = diagnostic?.details?.hcode;\n\t\tif (refusal && typeof refusal === \"object\" && \"error\" in refusal) {\n\t\t\ttry {\n\t\t\t\t// Persisted diagnostics are untrusted. Revalidate only the closed service envelope, never raw error text.\n\t\t\t\tconst notice = formatHcodeNotice(\n\t\t\t\t\tparseHcodeInferenceError({ error: refusal.error }),\n\t\t\t\t\tdiagnostic!.timestamp,\n\t\t\t\t\t\"reason\" in refusal ? refusal.reason : undefined,\n\t\t\t\t);\n\t\t\t\treturn [notice.message, ...notice.lines].join(\"\\n\");\n\t\t\t} catch {\n\t\t\t\t// Malformed or ordinary-provider diagnostics retain their existing safe presentation.\n\t\t\t}\n\t\t}\n\t}\n\treturn HCODE_AMBIGUOUS_NOTICE;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"notices.js","sourceRoot":"","sources":["../../../src/humain/hcode/notices.ts"],"names":[],"mappings":"AAEA,OAAO,EAA6C,wBAAwB,EAAE,MAAM,gBAAgB,CAAC;AACrG,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAE3C,MAAM,CAAC,MAAM,yBAAyB,GACrC,+JAA+J,CAAC;AAEjK,MAAM,CAAC,MAAM,sBAAsB,GAClC,8IAA8I,CAAC;AAEhJ,MAAM,CAAC,MAAM,mBAAmB,GAAG,6CAA6C,CAAC;AAEjF,MAAM,YAAY,GAAG;IACpB,iBAAiB,EAAE,mBAAmB;IACtC,OAAO,EAAE,iEAAiE;IAC1E,SAAS,EAAE,iDAAiD;IAC5D,QAAQ,EAAE,+DAA+D;IACzE,IAAI,EAAE,iEAAiE;IACvE,KAAK,EAAE,kEAAkE;IACzE,SAAS,EAAE,mGAAmG;IAC9G,MAAM,EAAE,yEAAyE;IACjF,KAAK,EAAE,sDAAsD;IAC7D,KAAK,EAAE,wDAAwD;IAC/D,WAAW,EAAE,6DAA6D;IAC1E,MAAM,EAAE,6EAA6E;IACrF,SAAS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CAAC,IAAI,KAAK,qBAAqB,CAAC,CAAC;QAClG,MAAM,KAAK,GAAG,uBAAuB,CACpC,UAAU,EAAE,OAAO,EAAE,gBAAgB,EACrC,UAAU,EAAE,OAAO,EAAE,gBAAgB,CACrC,CAAC;QACF,IAAI,KAAK;YAAE,OAAO,KAAK,CAAC;QACxB,MAAM,OAAO,GAAG,UAAU,EAAE,OAAO,EAAE,KAAK,CAAC;QAC3C,IAAI,OAAO,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,OAAO,IAAI,OAAO,EAAE,CAAC;YAClE,IAAI,CAAC;gBACJ,0GAA0G;gBAC1G,MAAM,MAAM,GAAG,iBAAiB,CAC/B,wBAAwB,CAAC,EAAE,KAAK,EAAE,OAAO,CAAC,KAAK,EAAE,CAAC,EAClD,UAAW,CAAC,SAAS,EACrB,QAAQ,IAAI,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAChD,CAAC;gBACF,OAAO,CAAC,MAAM,CAAC,OAAO,EAAE,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YACrD,CAAC;YAAC,MAAM,CAAC;gBACR,sFAAsF;YACvF,CAAC;QACF,CAAC;IACF,CAAC;IACD,OAAO,sBAAsB,CAAC;AAC/B,CAAC","sourcesContent":["// Local, typed presentation of managed refusal facts; never schedules a request or reads a later balance.\nimport type { AssistantMessage } from \"@earendil-works/pi-ai\";\nimport { type HcodeInferenceError, type HcodeValue, parseHcodeInferenceError } from \"./contracts.ts\";\nimport { HCODE_PROVIDER } from \"./http.ts\";\n\nexport const HCODE_PENDING_EXPLANATION =\n\t\"Pending usage is awaiting provider confirmation. It remains reserved until confirmed or reviewed by an admin. It is not a final charge and is not free usage.\";\n\nexport const HCODE_AMBIGUOUS_NOTICE =\n\t\"HUMAIN Code couldn't confirm this request's outcome. It may still be charged. No automatic retry was sent. Check /usage before trying again.\";\n\nexport const BUILD_SESSION_ENDED = \"Build session ended. Start a new Build run.\";\n\nconst localReasons = {\n\tbuildSessionEnded: BUILD_SESSION_ENDED,\n\taccount: \"The selected HUMAIN Code account or model is no longer current.\",\n\ttransport: \"HUMAIN Code only supports SSE for this request.\",\n\tenvelope: \"The CLI could not build a valid HUMAIN Code request envelope.\",\n\tsize: \"The request exceeds the HUMAIN Code model's request size limit.\",\n\tmodel: \"The request model does not match the selected HUMAIN Code model.\",\n\treasoning: \"The selected HUMAIN Code model does not support the requested thinking level or thinking history.\",\n\toutput: \"The requested output token limit exceeds the HUMAIN Code model's limit.\",\n\tcache: \"HUMAIN Code requires cache retention to be disabled.\",\n\ttools: \"The selected HUMAIN Code model does not support tools.\",\n\tstrictTools: \"HUMAIN Code does not support required strict tool sampling.\",\n\timages: \"An image is unsupported or exceeds the selected HUMAIN Code model's limits.\",\n\tcancelled: \"The HUMAIN Code request was cancelled before submission.\",\n} as const;\n\nexport type HcodeLocalReason = keyof typeof localReasons;\n\nconst localDetails = {\n\tmessageLimit: [\"context.messages\", \"History exceeds 512 messages; compact the session before retrying.\"],\n\tschema: [\"$\", \"Request structure failed local schema validation.\"],\n\t\"message.schema\": [\"context.messages\", \"History failed local schema validation.\"],\n\t\"system.schema\": [\"context.messages[*]\", \"A system message failed local schema validation.\"],\n\t\"user.schema\": [\"context.messages[*]\", \"A user message failed local schema validation.\"],\n\t\"assistant.schema\": [\"context.messages[*]\", \"An assistant message failed local schema validation.\"],\n\t\"assistant.deferred\": [\"context.messages[*]\", \"Assistant history contains a deferred response.\"],\n\t\"toolCall.schema\": [\"context.messages[*].content[*]\", \"A tool call failed local schema validation.\"],\n\t\"toolCall.orphan\": [\"context.messages[*].content[*]\", \"Tool-call history is missing a matching result.\"],\n\t\"toolCall.unknownTool\": [\"context.messages[*].content[*].name\", \"Tool-call history references an unavailable tool.\"],\n\t\"toolCall.argumentsError\": [\n\t\t\"context.messages[*].content[*].argumentsError\",\n\t\t\"Tool-call history contains invalid arguments.\",\n\t],\n\t\"toolCall.duplicate\": [\"context.messages[*].content[*].id\", \"Tool-call history contains a repeated call.\"],\n\t\"toolResult.schema\": [\"context.messages[*]\", \"A tool result failed local schema validation.\"],\n\t\"toolResult.orphan\": [\"context.messages[*]\", \"Tool-result history has no matching call.\"],\n\t\"options.schema\": [\"options\", \"Request options failed local schema validation.\"],\n\t\"toolChoice.unknownTool\": [\"options.toolChoice\", \"The current tool choice is unavailable.\"],\n} as const;\n\nexport type HcodeLocalDetail = keyof typeof localDetails;\n\n/** Forge's closed `x-hcode-model-unavailable-reason` values, in plain words. */\nconst modelUnavailableReasons = {\n\tcatalog_entry_unavailable: \"This model is no longer in your HUMAIN Code catalog.\",\n\tcredential_unavailable: \"HUMAIN Code has no usable provider key for this model.\",\n\texecution_credentials_unavailable: \"HUMAIN Code has no usable provider key for this model.\",\n\tprovider_quota_isolation_unverified: \"This model's provider key isn't dedicated to HUMAIN Code.\",\n\tquota_mapping_unavailable: \"This model's capacity isn't set up for HUMAIN Code yet.\",\n\tconfiguration_changed: \"An admin changed this model's configuration.\",\n\texecution_config_unavailable: \"HUMAIN Code couldn't load this model's configuration.\",\n\texecution_model_mismatch: \"HUMAIN Code's configuration for this model doesn't match its catalog entry.\",\n\texecution_endpoint_mismatch: \"HUMAIN Code's endpoint for this model doesn't match its catalog entry.\",\n\texecution_region_mismatch: \"HUMAIN Code's provider key is set to a region this model can't run in.\",\n} as const;\n\n/** Forge's closed `x-hcode-unsupported-capability-reason` values, in plain words. */\nconst unsupportedCapabilityReasons = {\n\treasoning: \"This model doesn't support the requested thinking level.\",\n\ttool_choice: \"This model can't force a tool call while thinking.\",\n\ttemperature: \"This model doesn't accept a temperature setting.\",\n\tcache_retention: \"This model doesn't support the requested prompt caching.\",\n\ttools: \"This model doesn't support tools.\",\n\tstrict_tools: \"This model doesn't support strict tool schemas.\",\n\tthinking_history: \"This model can't replay thinking from earlier turns of this conversation.\",\n\ttool_call_history: \"This model can't replay tool calls from earlier turns of this conversation.\",\n\timages: \"This model can't accept these images.\",\n\testimate: \"HUMAIN Code couldn't estimate this request's cost.\",\n} as const;\n\n/** Header names and closed reason values Forge sends with deterministic refusals. */\nexport const HCODE_REFUSAL_REASON_HEADERS = {\n\tmodel_unavailable: [\"x-hcode-model-unavailable-reason\", Object.keys(modelUnavailableReasons)],\n\tunsupported_capability: [\"x-hcode-unsupported-capability-reason\", Object.keys(unsupportedCapabilityReasons)],\n} as const satisfies Partial<Record<HcodeInferenceError[\"error\"][\"code\"], readonly [string, readonly string[]]>>;\n\n// Refusals Forge returns before any provider dispatch; each settles as not dispatched, so nothing is charged.\nconst predispatchCodes = new Set<HcodeInferenceError[\"error\"][\"code\"]>([\n\t\"unauthorized\",\n\t\"forbidden\",\n\t\"legal_acknowledgment_required\",\n\t\"auth_dependency_unavailable\",\n\t\"invalid_request\",\n\t\"unsupported_capability\",\n\t\"model_unavailable\",\n]);\nconst NOT_CHARGED =\n\t\"HUMAIN Code refused this request before running it, so nothing was charged. No automatic retry was sent.\";\n\nfunction refusalReason(code: HcodeInferenceError[\"error\"][\"code\"], reason: unknown): string | undefined {\n\tif (typeof reason !== \"string\") return undefined;\n\tconst table: Record<string, string> =\n\t\tcode === \"model_unavailable\"\n\t\t\t? modelUnavailableReasons\n\t\t\t: code === \"unsupported_capability\"\n\t\t\t\t? unsupportedCapabilityReasons\n\t\t\t\t: {};\n\treturn Object.hasOwn(table, reason) ? table[reason] : undefined;\n}\n\n/** Render a closed, non-reflecting reason for an inference that never reached the send boundary. */\nexport function formatHcodeLocalRefusal(reason: unknown, detail?: unknown): string | undefined {\n\tif (typeof reason !== \"string\" || !Object.hasOwn(localReasons, reason)) return undefined;\n\tif (reason === \"buildSessionEnded\") return BUILD_SESSION_ENDED;\n\t// Persisted diagnostics are untrusted: only closed detail codes may affect presentation.\n\tlet explanation = \"\";\n\tif (reason === \"envelope\" && typeof detail === \"string\" && Object.hasOwn(localDetails, detail)) {\n\t\tconst [path, message] = localDetails[detail as HcodeLocalDetail];\n\t\texplanation = ` ${message} [${detail} at ${path}]`;\n\t}\n\treturn `${localReasons[reason as HcodeLocalReason]}${explanation} No request was sent or charged.`;\n}\n\n/** Format the server's reset instant in UTC, independently of the host timezone. */\nexport function formatHcodeReset(resetAt: string): string {\n\treturn `Resets ${new Date(resetAt).toISOString().slice(0, 16).replace(\"T\", \" \")} UTC`;\n}\n\n/** Render schema-validated service facts without reading raw diagnostics or granting automatic retry. */\nexport function formatHcodeNotice(\n\tfailure: HcodeInferenceError,\n\treceivedAt: number,\n\treason?: unknown,\n): {\n\tmessage: string;\n\tlines: readonly string[];\n\tretryAfterMs?: number;\n} {\n\tconst error = failure.error;\n\tif (error.code === \"hcode_busy\") {\n\t\tconst retryAt = new Date(receivedAt + error.details.retryAfterMs);\n\t\t// A valid delay can exceed Date's range. Omit the time, not the no-dispatch fact.\n\t\tconst retryTime = Number.isNaN(retryAt.getTime())\n\t\t\t? undefined\n\t\t\t: retryAt.toISOString().split(\".\")[0].replace(\"T\", \" \");\n\t\treturn {\n\t\t\tmessage: error.message,\n\t\t\tlines: [\n\t\t\t\t...(retryTime ? [`Retry after ${retryTime} UTC.`] : []),\n\t\t\t\t\"No request was dispatched. No automatic retry was sent.\",\n\t\t\t],\n\t\t\tretryAfterMs: error.details.retryAfterMs,\n\t\t};\n\t}\n\tif (error.code === \"quota_exceeded\") {\n\t\tconst usage = error.details.usage;\n\t\tconst money = (value: HcodeValue | { kind: \"unlimited\" }) =>\n\t\t\tvalue.kind === \"known\"\n\t\t\t\t? `${value.value} ${usage.currency} ${usage.unit}${value.value === 1 ? \"\" : \"s\"}`\n\t\t\t\t: value.kind;\n\t\treturn {\n\t\t\tmessage: error.message,\n\t\t\tlines: [\n\t\t\t\t`Used${usage.costComplete ? \"\" : \" (known subtotal)\"} ${money(usage.actual)}`,\n\t\t\t\t`Pending ${money(usage.reserved)}`,\n\t\t\t\t`Remaining ${money(usage.remaining)}`,\n\t\t\t\tformatHcodeReset(usage.period.resetAt),\n\t\t\t\t\"No request was dispatched. No automatic retry was sent.\",\n\t\t\t],\n\t\t};\n\t}\n\tconst recovery =\n\t\terror.code === \"unauthorized\"\n\t\t\t? \"Sign in again with /login.\"\n\t\t\t: error.code === \"legal_acknowledgment_required\"\n\t\t\t\t? \"Accept terms in the web app, then try again.\"\n\t\t\t\t: error.code === \"model_unavailable\"\n\t\t\t\t\t? \"Choose another model with /model, or ask your admin.\"\n\t\t\t\t\t: error.code === \"unsupported_capability\"\n\t\t\t\t\t\t? \"Change the setting, start a new conversation with /new, or choose another model with /model.\"\n\t\t\t\t\t\t: undefined;\n\tif (!predispatchCodes.has(error.code)) return { message: error.message, lines: [HCODE_AMBIGUOUS_NOTICE] };\n\tconst detail = refusalReason(error.code, reason);\n\treturn {\n\t\tmessage: error.message,\n\t\tlines: [...(detail ? [detail] : []), ...(recovery ? [recovery] : []), NOT_CHARGED],\n\t};\n}\n\n/** Shared print/interactive boundary for validated refusals and separate uncertain-outcome warnings. */\nexport function formatHcodeMessageNotice(message: AssistantMessage): string | undefined {\n\tif (message.provider !== HCODE_PROVIDER) return undefined;\n\tif (message.stopReason === \"error\") {\n\t\tconst diagnostic = message.diagnostics?.findLast((entry) => entry.type === \"provider_http_error\");\n\t\tconst local = formatHcodeLocalRefusal(\n\t\t\tdiagnostic?.details?.hcodeLocalReason,\n\t\t\tdiagnostic?.details?.hcodeLocalDetail,\n\t\t);\n\t\tif (local) return local;\n\t\tconst refusal = diagnostic?.details?.hcode;\n\t\tif (refusal && typeof refusal === \"object\" && \"error\" in refusal) {\n\t\t\ttry {\n\t\t\t\t// Persisted diagnostics are untrusted. Revalidate only the closed service envelope, never raw error text.\n\t\t\t\tconst notice = formatHcodeNotice(\n\t\t\t\t\tparseHcodeInferenceError({ error: refusal.error }),\n\t\t\t\t\tdiagnostic!.timestamp,\n\t\t\t\t\t\"reason\" in refusal ? refusal.reason : undefined,\n\t\t\t\t);\n\t\t\t\treturn [notice.message, ...notice.lines].join(\"\\n\");\n\t\t\t} catch {\n\t\t\t\t// Malformed or ordinary-provider diagnostics retain their existing safe presentation.\n\t\t\t}\n\t\t}\n\t}\n\treturn HCODE_AMBIGUOUS_NOTICE;\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type Api, type ApiKeyCredential, type Model, type Provider, type TranscriptContext } from "@earendil-works/pi-ai";
|
|
2
|
-
import { type HcodeCatalogEmptyReason } from "./contracts.ts";
|
|
2
|
+
import { type HcodeCatalogEmptyReason, type HcodeCatalogExclusionReason } from "./contracts.ts";
|
|
3
3
|
import { type HcodeEnvironment } from "./environment.ts";
|
|
4
4
|
import type { HcodeAccountPort, HcodeAccountRef } from "./ports.ts";
|
|
5
5
|
/** Account-bound native provider whose owning runtime must dispose its subscription and catalog. */
|
|
@@ -8,6 +8,8 @@ export interface HcodeProvider extends Provider<"pi-messages"> {
|
|
|
8
8
|
dispose(): void;
|
|
9
9
|
/** Forge's reason the current account's catalog is empty, if it sent a known one. */
|
|
10
10
|
catalogEmptyReason(): HcodeCatalogEmptyReason | undefined;
|
|
11
|
+
/** Forge's reason the current account's catalog left out this exact model ID, if it sent a known one. */
|
|
12
|
+
catalogExclusionReason(modelId: string): HcodeCatalogExclusionReason | undefined;
|
|
11
13
|
/** Whether this process has read the current account's catalog; a new process reads it when /model opens. */
|
|
12
14
|
catalogLoaded(): boolean;
|
|
13
15
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../../../src/humain/hcode/provider.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../../../src/humain/hcode/provider.ts"],"names":[],"mappings":"AAGA,OAAO,EACN,KAAK,GAAG,EACR,KAAK,gBAAgB,EAOrB,KAAK,KAAK,EACV,KAAK,QAAQ,EAGb,KAAK,iBAAiB,EACtB,MAAM,uBAAuB,CAAC;AAI/B,OAAO,EAGN,KAAK,uBAAuB,EAC5B,KAAK,2BAA2B,EAIhC,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,KAAK,gBAAgB,EAA6C,MAAM,kBAAkB,CAAC;AASpG,OAAO,KAAK,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAIpE,oGAAoG;AACpG,MAAM,WAAW,aAAc,SAAQ,QAAQ,CAAC,aAAa,CAAC;IAC7D,iFAAiF;IACjF,OAAO,IAAI,IAAI,CAAC;IAChB,qFAAqF;IACrF,kBAAkB,IAAI,uBAAuB,GAAG,SAAS,CAAC;IAC1D,yGAAyG;IACzG,sBAAsB,CAAC,OAAO,EAAE,MAAM,GAAG,2BAA2B,GAAG,SAAS,CAAC;IACjF,6GAA6G;IAC7G,aAAa,IAAI,OAAO,CAAC;CACzB;AAED,uFAAuF;AACvF,wBAAgB,wBAAwB,CAAC,GAAG,EAAE,eAAe,GAAG,gBAAgB,CAS/E;AAQD,wBAAgB,mBAAmB,CAClC,OAAO,EAAE,iBAAiB,EAC1B,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,IAAI,GAAG,WAAW,CAAC,GACzC,iBAAiB,CAuEnB;AAoBD,yGAAyG;AACzG,wBAAgB,mBAAmB,CAClC,OAAO,EAAE,gBAAgB,EACzB,WAAW,GAAE,gBAA4C,GACvD,aAAa,CA+Rf"}
|