@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.
Files changed (224) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/dist/bundle/chunks/{anthropic-messages-UZB5HJE3.js → anthropic-messages-XFCDMGD6.js} +4 -4
  3. package/dist/bundle/chunks/{azure-openai-responses-J3LCMWPQ.js → azure-openai-responses-F4KQM3NK.js} +3 -3
  4. package/dist/bundle/chunks/{chunk-7EONJCBE.js → chunk-2JNJJ6SZ.js} +1 -1
  5. package/dist/bundle/chunks/{chunk-WRYGY5XG.js → chunk-4MKATHT2.js} +1 -1
  6. package/dist/bundle/chunks/{chunk-ATFZAFMS.js → chunk-65FLSKDA.js} +1 -1
  7. package/dist/bundle/chunks/{chunk-CET2MXXN.js → chunk-6P6MMQUH.js} +1 -1
  8. package/dist/bundle/chunks/{chunk-CU6KU7JK.js → chunk-6TTMNQXI.js} +13 -13
  9. package/dist/bundle/chunks/{chunk-KQXXBQ57.js → chunk-6YVORXTX.js} +155 -125
  10. package/dist/bundle/chunks/{chunk-SQ7NTRLJ.js → chunk-7X6DNT45.js} +17 -16
  11. package/dist/bundle/chunks/{chunk-PGVDL4KB.js → chunk-CQ2CE3RB.js} +1 -1
  12. package/dist/bundle/chunks/{chunk-QRYDGY5I.js → chunk-DJG2WUNM.js} +1 -1
  13. package/dist/bundle/chunks/{chunk-R3VDXQW2.js → chunk-E7OBH44W.js} +5 -5
  14. package/dist/bundle/chunks/{chunk-4EV7CK26.js → chunk-F2H47FRF.js} +1 -1
  15. package/dist/bundle/chunks/chunk-FQ4KS5S4.js +23 -0
  16. package/dist/bundle/chunks/{chunk-TYN46EVI.js → chunk-GPLWWO5Q.js} +1 -1
  17. package/dist/bundle/chunks/{chunk-EMBIUIQ2.js → chunk-IMUFBWEK.js} +4 -4
  18. package/dist/bundle/chunks/{chunk-Z5UFSRO4.js → chunk-KI7CHPWC.js} +1 -1
  19. package/dist/bundle/chunks/{chunk-VKQNYZUA.js → chunk-KRBELWQH.js} +1 -1
  20. package/dist/bundle/chunks/{chunk-AI7EHDAX.js → chunk-LSRXA7OS.js} +1 -1
  21. package/dist/bundle/chunks/{chunk-XVIQYONJ.js → chunk-MIAXMK5F.js} +1 -1
  22. package/dist/bundle/chunks/{chunk-NNWNIBLG.js → chunk-NICPFMOP.js} +1 -1
  23. package/dist/bundle/chunks/{chunk-4SFWYKL5.js → chunk-P42E6YY6.js} +441 -415
  24. package/dist/bundle/chunks/{chunk-WGXMYMPE.js → chunk-PFBAIRCY.js} +2 -2
  25. package/dist/bundle/chunks/{chunk-OVDMYBIT.js → chunk-PWFM6AQQ.js} +1 -1
  26. package/dist/bundle/chunks/{chunk-JV7VHOAY.js → chunk-QRRVZYTG.js} +1 -1
  27. package/dist/bundle/chunks/{chunk-IOLLZXQN.js → chunk-ROFZVEFN.js} +125 -114
  28. package/dist/bundle/chunks/{chunk-C4DHVDYT.js → chunk-SXOIQWNX.js} +1 -1
  29. package/dist/bundle/chunks/{chunk-IXQYPQRQ.js → chunk-XZ7FTBXS.js} +1446 -1423
  30. package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-ETKC6B2S.js → cloudflare-workers-ai-system-one-JEZVYITT.js} +1 -1
  31. package/dist/bundle/chunks/{compat-HS4ARZK3.js → compat-SRCNS6OQ.js} +6 -6
  32. package/dist/bundle/chunks/{curator-server-TC7RVVN2.js → curator-server-QB4GITGS.js} +1 -1
  33. package/dist/bundle/chunks/{dist-5AQPJ2TI.js → dist-4OMLHRJE.js} +1 -1
  34. package/dist/bundle/chunks/{dist-NMEXYUP3.js → dist-CBODG4CA.js} +5 -5
  35. package/dist/bundle/chunks/{dist-DYB3AR7C.js → dist-TRAK7EXI.js} +7 -7
  36. package/dist/bundle/chunks/{extract-QHZTEVJP.js → extract-L373D6O7.js} +2 -2
  37. package/dist/bundle/chunks/{flow-implementer-QMN3HKE2.js → flow-implementer-4KO3Q4B5.js} +4 -4
  38. package/dist/bundle/chunks/github-copilot.js +53 -56
  39. package/dist/bundle/chunks/{google-generative-ai-ZND73WDQ.js → google-generative-ai-WIASMWS3.js} +2 -2
  40. package/dist/bundle/chunks/{google-vertex-YAH62YRM.js → google-vertex-WSPHRZIZ.js} +3 -3
  41. package/dist/bundle/chunks/{host-Q565BCXB.js → host-WOLZCWQQ.js} +1 -1
  42. package/dist/bundle/chunks/{inprocess-453SLFL5.js → inprocess-TOBRVK4C.js} +5 -5
  43. package/dist/bundle/chunks/{interactive-mode-MVZOJ5OU.js → interactive-mode-BJJKPBXD.js} +3 -3
  44. package/dist/bundle/chunks/{llama-cpp-classify-Z4GZY4GC.js → llama-cpp-classify-KYZT532X.js} +1 -1
  45. package/dist/bundle/chunks/{mistral-conversations-7I5JURDP.js → mistral-conversations-7JYDDRUT.js} +2 -2
  46. package/dist/bundle/chunks/{node-IMSYVRPL.js → node-N7TPBUJB.js} +1 -1
  47. package/dist/bundle/chunks/{openai-codex-responses-LTHOMN37.js → openai-codex-responses-7PAML4NF.js} +3 -3
  48. package/dist/bundle/chunks/{openai-completions-W2X635EE.js → openai-completions-UJDAIGTK.js} +3 -3
  49. package/dist/bundle/chunks/{openai-decisions-TN2GNOYI.js → openai-decisions-JMSDGR7K.js} +1 -1
  50. package/dist/bundle/chunks/{openai-responses-DVY4QXOG.js → openai-responses-2WNCE6AY.js} +3 -3
  51. package/dist/bundle/chunks/{openrouter-images-SE2JMS44.js → openrouter-images-V3UCCO6X.js} +1 -1
  52. package/dist/bundle/chunks/{pi-messages-WAS6Z5L5.js → pi-messages-TQ7LJUNQ.js} +2 -2
  53. package/dist/bundle/chunks/{session-picker-XNVLSJ22.js → session-picker-4JQEGLDD.js} +1 -1
  54. package/dist/bundle/chunks/{startup-ui-3TCT465D.js → startup-ui-AKTA4NDP.js} +1 -1
  55. package/dist/bundle/chunks/{typesafe-system-one-AAZH6S3I.js → typesafe-system-one-YP7GGN4C.js} +1 -1
  56. package/dist/bundle/chunks/{virtual-modules-CIVXCEAN.js → virtual-modules-3CT5BMBA.js} +8 -8
  57. package/dist/bundle/cli-runtime.js +5 -5
  58. package/dist/bundle/index.js +8 -8
  59. package/dist/bundle/rpc-entry.js +4 -4
  60. package/dist/cli/args.js +1 -1
  61. package/dist/cli/args.js.map +1 -1
  62. package/dist/cli/list-models.d.ts.map +1 -1
  63. package/dist/cli/list-models.js +16 -1
  64. package/dist/cli/list-models.js.map +1 -1
  65. package/dist/cli/setup.d.ts +1 -1
  66. package/dist/cli/setup.d.ts.map +1 -1
  67. package/dist/cli/setup.js +3 -2
  68. package/dist/cli/setup.js.map +1 -1
  69. package/dist/cli.js.map +1 -1
  70. package/dist/core/agent-session-runtime.d.ts +3 -0
  71. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  72. package/dist/core/agent-session-runtime.js +11 -2
  73. package/dist/core/agent-session-runtime.js.map +1 -1
  74. package/dist/core/keybindings.d.ts +24 -0
  75. package/dist/core/keybindings.d.ts.map +1 -1
  76. package/dist/core/keybindings.js +3 -0
  77. package/dist/core/keybindings.js.map +1 -1
  78. package/dist/core/model-registry.d.ts.map +1 -1
  79. package/dist/core/model-registry.js +12 -1
  80. package/dist/core/model-registry.js.map +1 -1
  81. package/dist/core/model-resolver.d.ts.map +1 -1
  82. package/dist/core/model-resolver.js +11 -7
  83. package/dist/core/model-resolver.js.map +1 -1
  84. package/dist/core/model-runtime.d.ts +11 -2
  85. package/dist/core/model-runtime.d.ts.map +1 -1
  86. package/dist/core/model-runtime.js +23 -6
  87. package/dist/core/model-runtime.js.map +1 -1
  88. package/dist/core/oauth-account-pool.d.ts +4 -0
  89. package/dist/core/oauth-account-pool.d.ts.map +1 -1
  90. package/dist/core/oauth-account-pool.js +104 -20
  91. package/dist/core/oauth-account-pool.js.map +1 -1
  92. package/dist/core/sdk.js +2 -2
  93. package/dist/core/sdk.js.map +1 -1
  94. package/dist/core/slash-commands.d.ts.map +1 -1
  95. package/dist/core/slash-commands.js +1 -0
  96. package/dist/core/slash-commands.js.map +1 -1
  97. package/dist/extensions/usage/confirmation.d.ts.map +1 -1
  98. package/dist/extensions/usage/confirmation.js +1 -1
  99. package/dist/extensions/usage/confirmation.js.map +1 -1
  100. package/dist/extensions/usage/index.js +1 -1
  101. package/dist/extensions/usage/index.js.map +1 -1
  102. package/dist/extensions/usage/panes.d.ts +5 -0
  103. package/dist/extensions/usage/panes.d.ts.map +1 -0
  104. package/dist/extensions/usage/panes.js +10 -0
  105. package/dist/extensions/usage/panes.js.map +1 -0
  106. package/dist/extensions/usage/popup.d.ts.map +1 -1
  107. package/dist/extensions/usage/popup.js +9 -18
  108. package/dist/extensions/usage/popup.js.map +1 -1
  109. package/dist/humain/hcode/contracts.d.ts +15 -0
  110. package/dist/humain/hcode/contracts.d.ts.map +1 -1
  111. package/dist/humain/hcode/contracts.js +85 -10
  112. package/dist/humain/hcode/contracts.js.map +1 -1
  113. package/dist/humain/hcode/environment.d.ts.map +1 -1
  114. package/dist/humain/hcode/environment.js +4 -2
  115. package/dist/humain/hcode/environment.js.map +1 -1
  116. package/dist/humain/hcode/images.d.ts.map +1 -1
  117. package/dist/humain/hcode/images.js +4 -2
  118. package/dist/humain/hcode/images.js.map +1 -1
  119. package/dist/humain/hcode/login-copy.js +1 -1
  120. package/dist/humain/hcode/login-copy.js.map +1 -1
  121. package/dist/humain/hcode/notices.d.ts +22 -1
  122. package/dist/humain/hcode/notices.d.ts.map +1 -1
  123. package/dist/humain/hcode/notices.js +34 -3
  124. package/dist/humain/hcode/notices.js.map +1 -1
  125. package/dist/humain/hcode/provider.d.ts +3 -1
  126. package/dist/humain/hcode/provider.d.ts.map +1 -1
  127. package/dist/humain/hcode/provider.js +126 -46
  128. package/dist/humain/hcode/provider.js.map +1 -1
  129. package/dist/humain/hcode/run-credential.d.ts +21 -0
  130. package/dist/humain/hcode/run-credential.d.ts.map +1 -0
  131. package/dist/humain/hcode/run-credential.js +140 -0
  132. package/dist/humain/hcode/run-credential.js.map +1 -0
  133. package/dist/humain/hcode/sandbox.d.ts +6 -0
  134. package/dist/humain/hcode/sandbox.d.ts.map +1 -0
  135. package/dist/humain/hcode/sandbox.js +139 -0
  136. package/dist/humain/hcode/sandbox.js.map +1 -0
  137. package/dist/humain/hcode/selection.d.ts +7 -2
  138. package/dist/humain/hcode/selection.d.ts.map +1 -1
  139. package/dist/humain/hcode/selection.js +29 -5
  140. package/dist/humain/hcode/selection.js.map +1 -1
  141. package/dist/humain/hcode/transport.d.ts +3 -2
  142. package/dist/humain/hcode/transport.d.ts.map +1 -1
  143. package/dist/humain/hcode/transport.js +22 -7
  144. package/dist/humain/hcode/transport.js.map +1 -1
  145. package/dist/humain/remote/broker.d.ts +84 -0
  146. package/dist/humain/remote/broker.d.ts.map +1 -0
  147. package/dist/humain/remote/broker.js +427 -0
  148. package/dist/humain/remote/broker.js.map +1 -0
  149. package/dist/humain/remote/deny-store.d.ts +12 -0
  150. package/dist/humain/remote/deny-store.d.ts.map +1 -0
  151. package/dist/humain/remote/deny-store.js +164 -0
  152. package/dist/humain/remote/deny-store.js.map +1 -0
  153. package/dist/humain/remote/enablement.d.ts +5 -0
  154. package/dist/humain/remote/enablement.d.ts.map +1 -0
  155. package/dist/humain/remote/enablement.js +8 -0
  156. package/dist/humain/remote/enablement.js.map +1 -0
  157. package/dist/humain/remote/environment.d.ts +11 -0
  158. package/dist/humain/remote/environment.d.ts.map +1 -0
  159. package/dist/humain/remote/environment.js +19 -0
  160. package/dist/humain/remote/environment.js.map +1 -0
  161. package/dist/humain/remote/host-watch.d.ts +21 -0
  162. package/dist/humain/remote/host-watch.d.ts.map +1 -0
  163. package/dist/humain/remote/host-watch.js +186 -0
  164. package/dist/humain/remote/host-watch.js.map +1 -0
  165. package/dist/humain/remote/ipc-posix.d.ts +5 -0
  166. package/dist/humain/remote/ipc-posix.d.ts.map +1 -0
  167. package/dist/humain/remote/ipc-posix.js +29 -0
  168. package/dist/humain/remote/ipc-posix.js.map +1 -0
  169. package/dist/humain/remote/ipc-windows.d.ts +3 -0
  170. package/dist/humain/remote/ipc-windows.d.ts.map +1 -0
  171. package/dist/humain/remote/ipc-windows.js +5 -0
  172. package/dist/humain/remote/ipc-windows.js.map +1 -0
  173. package/dist/humain/remote/ipc.d.ts +10 -0
  174. package/dist/humain/remote/ipc.d.ts.map +1 -0
  175. package/dist/humain/remote/ipc.js +19 -0
  176. package/dist/humain/remote/ipc.js.map +1 -0
  177. package/dist/humain/remote/protocol.d.ts +43 -0
  178. package/dist/humain/remote/protocol.d.ts.map +1 -0
  179. package/dist/humain/remote/protocol.js +76 -0
  180. package/dist/humain/remote/protocol.js.map +1 -0
  181. package/dist/humain/remote/relay-socket.d.ts +30 -0
  182. package/dist/humain/remote/relay-socket.d.ts.map +1 -0
  183. package/dist/humain/remote/relay-socket.js +137 -0
  184. package/dist/humain/remote/relay-socket.js.map +1 -0
  185. package/dist/humain/remote/secure-channel.d.ts +10 -0
  186. package/dist/humain/remote/secure-channel.d.ts.map +1 -0
  187. package/dist/humain/remote/secure-channel.js +5 -0
  188. package/dist/humain/remote/secure-channel.js.map +1 -0
  189. package/dist/humain/remote/terminal.d.ts +48 -0
  190. package/dist/humain/remote/terminal.d.ts.map +1 -0
  191. package/dist/humain/remote/terminal.js +119 -0
  192. package/dist/humain/remote/terminal.js.map +1 -0
  193. package/dist/humain/remote/tickets.d.ts +35 -0
  194. package/dist/humain/remote/tickets.d.ts.map +1 -0
  195. package/dist/humain/remote/tickets.js +132 -0
  196. package/dist/humain/remote/tickets.js.map +1 -0
  197. package/dist/main.d.ts +1 -1
  198. package/dist/main.d.ts.map +1 -1
  199. package/dist/main.js +13 -1
  200. package/dist/main.js.map +1 -1
  201. package/dist/modes/interactive/components/account-picker.d.ts +31 -0
  202. package/dist/modes/interactive/components/account-picker.d.ts.map +1 -0
  203. package/dist/modes/interactive/components/account-picker.js +150 -0
  204. package/dist/modes/interactive/components/account-picker.js.map +1 -0
  205. package/dist/modes/interactive/interactive-mode.d.ts +15 -2
  206. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  207. package/dist/modes/interactive/interactive-mode.js +225 -36
  208. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  209. package/dist/modes/interactive/oauth-account-format.d.ts +9 -0
  210. package/dist/modes/interactive/oauth-account-format.d.ts.map +1 -1
  211. package/dist/modes/interactive/oauth-account-format.js +31 -22
  212. package/dist/modes/interactive/oauth-account-format.js.map +1 -1
  213. package/docs/cli.md +1 -1
  214. package/docs/forge-run-bootstrap.md +46 -0
  215. package/docs/humain-code.md +2 -2
  216. package/docs/index.md +2 -1
  217. package/docs/keybindings.md +10 -0
  218. package/docs/providers.md +2 -2
  219. package/docs/quickstart.md +16 -2
  220. package/docs/slash-commands.md +4 -2
  221. package/npm-shrinkwrap.json +2 -2
  222. package/package.json +1 -1
  223. package/schemas/keybindings.schema.json +12 -0
  224. package/dist/bundle/chunks/chunk-J5TSAJGC.js +0 -22
@@ -1,10 +1,11 @@
1
1
  // Managed account provider: reference-only auth and account-scoped pi-messages catalog.
2
2
  import { createHash, randomUUID } from "node:crypto";
3
+ import { isDeepStrictEqual } from "node:util";
3
4
  import { createDelegatedFetch, createProvider, lazyStream, ManagedAssistantMessageQueue, } from "@earendil-works/pi-ai";
4
5
  import { piMessagesApi } from "@earendil-works/pi-ai/api/pi-messages.lazy";
5
6
  import { sameReference } from "./account-store.js";
6
7
  import { deriveHcodeCatalog } from "./catalog.js";
7
- import { HCODE_CATALOG_EMPTY_REASON_HEADER, parseHcodeCatalogEmptyReason, parseHcodeModelList, } from "./contracts.js";
8
+ import { HCODE_CATALOG_EMPTY_REASON_HEADER, HCODE_CATALOG_EXCLUSIONS_HEADER, parseHcodeCatalogEmptyReason, parseHcodeCatalogExclusions, parseHcodeModelList, } from "./contracts.js";
8
9
  import { hcodeDisplayName, resolveHcodeEnvironment } from "./environment.js";
9
10
  import { HCODE_PROVIDER, hcodeJson } from "./http.js";
10
11
  import { fitHcodeRequestSize, hcodeActivePrompts, hcodeImagePayloadDraft, reportHcodeImageSizeRefusal, } from "./images.js";
@@ -26,49 +27,97 @@ const replayableToolCallId = /^[A-Za-z0-9_-]{1,64}$/;
26
27
  const foreignToolCallId = (id) => replayableToolCallId.test(id) ? id : `call_${createHash("sha256").update(id).digest("hex").slice(0, 32)}`;
27
28
  // Project history for the destination model without changing the saved transcript.
28
29
  export function projectHcodeContext(context, model) {
29
- const reasoning = model.reasoning;
30
- const toolCallIds = new Map();
30
+ const messages = [];
31
+ const activeTools = new Set();
32
+ const pending = new Map();
33
+ const closeTurn = () => {
34
+ for (const call of pending.values()) {
35
+ messages.push({
36
+ role: "toolResult",
37
+ toolCallId: call.id,
38
+ toolName: call.name,
39
+ content: [{ type: "text", text: "No result provided" }],
40
+ isError: true,
41
+ timestamp: call.timestamp,
42
+ });
43
+ }
44
+ pending.clear();
45
+ };
46
+ for (const message of context.messages) {
47
+ if (message.role === "system") {
48
+ // Evaluate calls against the tools declared at their turn, not the final live loadout.
49
+ for (const tool of message.toolsRemoved ?? [])
50
+ activeTools.delete(tool.name);
51
+ for (const tool of message.toolsAdded ?? [])
52
+ activeTools.add(tool.name);
53
+ messages.push(projectHcodeSystemMessage(message));
54
+ continue;
55
+ }
56
+ if (message.role === "toolResult") {
57
+ const call = pending.get(message.toolCallId);
58
+ if (!call || call.name !== message.toolName)
59
+ continue;
60
+ pending.delete(message.toolCallId);
61
+ // Execution details and nested calls are session/UI bookkeeping, not model input.
62
+ messages.push({
63
+ role: "toolResult",
64
+ toolCallId: call.id,
65
+ toolName: message.toolName,
66
+ content: message.content,
67
+ isError: message.isError,
68
+ timestamp: message.timestamp,
69
+ });
70
+ continue;
71
+ }
72
+ closeTurn();
73
+ if (message.role === "user") {
74
+ messages.push(message);
75
+ continue;
76
+ }
77
+ // Incomplete turns were never replayable and may contain calls that never ran.
78
+ if (message.stopReason === "error" || message.stopReason === "aborted" || message.stopReason === "deferred")
79
+ continue;
80
+ const sameModel = message.provider === HCODE_PROVIDER && message.api === "pi-messages" && message.model === model.id;
81
+ const { deferred: _handle, providerThinkingLevel, ...assistant } = message;
82
+ const content = assistant.content.flatMap((block) => {
83
+ if (block.type === "thinking")
84
+ return sameModel && model.reasoning ? [block] : [];
85
+ if (block.type === "text")
86
+ return [sameModel ? block : { type: "text", text: block.text }];
87
+ if (block.argumentsError !== undefined || !activeTools.has(block.name))
88
+ return [];
89
+ const id = sameModel ? block.id : foreignToolCallId(block.id);
90
+ pending.set(block.id, { id, name: block.name, timestamp: message.timestamp });
91
+ if (sameModel)
92
+ return [block];
93
+ const { thoughtSignature: _signature, ...call } = block;
94
+ return [{ ...call, id }];
95
+ });
96
+ if (!content.length && (!sameModel || message.content.length))
97
+ continue;
98
+ messages.push({
99
+ ...assistant,
100
+ content,
101
+ stopReason: assistant.stopReason === "toolUse" && !pending.size ? "stop" : assistant.stopReason,
102
+ ...(sameModel && providerThinkingLevel !== undefined ? { providerThinkingLevel } : {}),
103
+ });
104
+ }
105
+ closeTurn();
106
+ return { ...context, messages };
107
+ }
108
+ function projectHcodeSystemMessage(message) {
109
+ // Catalog v1 qualifies ordinary JSON-schema tools, not provider-side constrained sampling.
110
+ if (!message.toolsAdded?.some((tool) => tool.constrainedSampling))
111
+ return message;
31
112
  return {
32
- ...context,
33
- messages: context.messages.flatMap((message) => {
34
- if (message.role === "assistant" &&
35
- (message.provider !== HCODE_PROVIDER || message.api !== "pi-messages" || message.model !== model.id)) {
36
- // Signatures, thinking and provider thinking levels are valid only for the model that produced them;
37
- // Forge refuses them from any other model, so a model switch keeps only the visible turn.
38
- const { providerThinkingLevel: _level, ...foreign } = message;
39
- const content = foreign.content.flatMap((block) => {
40
- if (block.type === "thinking")
41
- return [];
42
- if (block.type === "text")
43
- return [{ type: "text", text: block.text }];
44
- const { thoughtSignature: _signature, ...call } = block;
45
- const id = foreignToolCallId(call.id);
46
- if (id !== call.id)
47
- toolCallIds.set(call.id, id);
48
- return [{ ...call, id }];
49
- });
50
- return content.length ? { ...foreign, content } : [];
51
- }
52
- if (message.role === "toolResult" && toolCallIds.has(message.toolCallId))
53
- return { ...message, toolCallId: toolCallIds.get(message.toolCallId) };
54
- if (!reasoning && message.role === "assistant" && message.content.some((block) => block.type === "thinking")) {
55
- const content = message.content.filter((block) => block.type !== "thinking");
56
- return content.length ? { ...message, content } : [];
57
- }
58
- // Catalog v1 qualifies ordinary JSON-schema tools, not provider-side constrained sampling.
59
- if (message.role !== "system" || !message.toolsAdded?.some((tool) => tool.constrainedSampling))
60
- return message;
61
- return {
62
- ...message,
63
- toolsAdded: message.toolsAdded.map((tool) => {
64
- const { constrainedSampling, ...ordinaryTool } = tool;
65
- if (constrainedSampling &&
66
- constrainedSampling.type === "json_schema" &&
67
- constrainedSampling.strict === "require")
68
- throw new HcodeLocalRefusal("strictTools");
69
- return constrainedSampling ? ordinaryTool : tool;
70
- }),
71
- };
113
+ ...message,
114
+ toolsAdded: message.toolsAdded.map((tool) => {
115
+ const { constrainedSampling, ...ordinaryTool } = tool;
116
+ if (constrainedSampling &&
117
+ constrainedSampling.type === "json_schema" &&
118
+ constrainedSampling.strict === "require")
119
+ throw new HcodeLocalRefusal("strictTools");
120
+ return constrainedSampling ? ordinaryTool : tool;
72
121
  }),
73
122
  };
74
123
  }
@@ -79,10 +128,12 @@ export function createHcodeProvider(account, environment = resolveHcodeEnvironme
79
128
  let scope = null;
80
129
  let models = Object.freeze([]);
81
130
  let emptyReason;
131
+ let exclusions = new Map();
82
132
  const clear = () => {
83
133
  scope = null;
84
134
  models = Object.freeze([]);
85
135
  emptyReason = undefined;
136
+ exclusions = new Map();
86
137
  };
87
138
  const unsubscribe = account.subscribe(clear);
88
139
  const current = () => !disposed && scope && sameReference(account.status(scope.environmentId), scope);
@@ -170,6 +221,9 @@ export function createHcodeProvider(account, environment = resolveHcodeEnvironme
170
221
  envelope = changed === undefined ? hook.draft : changed;
171
222
  protectedMessages = hook.protectedMessages(envelope.context.messages);
172
223
  }
224
+ if (Array.isArray(envelope.context.messages) && envelope.context.messages.length > 512) {
225
+ throw new HcodeLocalRefusal("envelope", "messageLimit");
226
+ }
173
227
  const fitted = await fitHcodeRequestSize(canonical, envelope.context.messages, protectedMessages, (messages) => JSON.stringify({ ...envelope, context: { ...envelope.context, messages } }));
174
228
  if (!fitted) {
175
229
  if (active.size && protectedMessages.size)
@@ -180,7 +234,11 @@ export function createHcodeProvider(account, environment = resolveHcodeEnvironme
180
234
  return parseHcodeRequestBody(fitted.body);
181
235
  }
182
236
  catch (error) {
183
- return refuse(error instanceof HcodeLocalRefusal ? error.reason : "envelope");
237
+ if (error instanceof HcodeLocalRefusal) {
238
+ failure = error;
239
+ throw error;
240
+ }
241
+ return refuse("envelope");
184
242
  }
185
243
  },
186
244
  onRequest: options?.onRequest,
@@ -210,7 +268,10 @@ export function createHcodeProvider(account, environment = resolveHcodeEnvironme
210
268
  details: {
211
269
  retryable: false,
212
270
  ...(failure instanceof HcodeLocalRefusal
213
- ? { hcodeLocalReason: failure.reason }
271
+ ? {
272
+ hcodeLocalReason: failure.reason,
273
+ ...(failure.detail ? { hcodeLocalDetail: failure.detail } : {}),
274
+ }
214
275
  : failure?.failure
215
276
  ? { hcode: failure.diagnostics() }
216
277
  : {}),
@@ -268,6 +329,20 @@ export function createHcodeProvider(account, environment = resolveHcodeEnvironme
268
329
  getModels,
269
330
  getAllModels: getModels,
270
331
  catalogEmptyReason: () => (getModels().length ? undefined : emptyReason),
332
+ catalogExclusionReason: (modelId) => {
333
+ // Match `/model` exact references, which compare IDs case-insensitively.
334
+ const normalized = modelId.toLowerCase();
335
+ if (getModels().some((model) => model.id.toLowerCase() === normalized))
336
+ return undefined;
337
+ const exact = exclusions.get(modelId);
338
+ if (exact)
339
+ return exact;
340
+ for (const [id, reason] of exclusions) {
341
+ if (id.toLowerCase() === normalized)
342
+ return reason;
343
+ }
344
+ return undefined;
345
+ },
271
346
  catalogLoaded: () => !!current(),
272
347
  async refreshModels(context) {
273
348
  const expected = context.credential?.type === "api_key" ? credentialReference(context.credential) : null;
@@ -278,9 +353,11 @@ export function createHcodeProvider(account, environment = resolveHcodeEnvironme
278
353
  if (!context.allowNetwork || context.signal.aborted)
279
354
  return;
280
355
  let reason;
356
+ let excluded = new Map();
281
357
  const entries = parseHcodeModelList(await hcodeJson(async (url, init) => {
282
358
  const response = await account.authorizedFetch(expected, String(url), init ?? {});
283
359
  reason = parseHcodeCatalogEmptyReason(response.headers.get(HCODE_CATALOG_EMPTY_REASON_HEADER));
360
+ excluded = parseHcodeCatalogExclusions(response.headers.get(HCODE_CATALOG_EXCLUSIONS_HEADER));
284
361
  return response;
285
362
  }, `${environment.inferenceBaseUrl}/models`, { signal: context.signal })).data;
286
363
  const next = deriveHcodeCatalog(entries, environment);
@@ -293,9 +370,12 @@ export function createHcodeProvider(account, environment = resolveHcodeEnvironme
293
370
  context.signal.aborted ||
294
371
  !sameReference(account.status(expected.environmentId), expected))
295
372
  return;
373
+ // Unchanged approval must not invalidate a picker row or an in-flight selection.
374
+ if (!sameReference(scope, expected) || !isDeepStrictEqual(models, next))
375
+ models = next;
296
376
  scope = expected;
297
- models = next;
298
377
  emptyReason = next.length ? undefined : reason;
378
+ exclusions = excluded;
299
379
  },
300
380
  });
301
381
  },
@@ -1 +1 @@
1
- {"version":3,"file":"provider.js","sourceRoot":"","sources":["../../../src/humain/hcode/provider.ts"],"names":[],"mappings":"AAAA,wFAAwF;AACxF,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACrD,OAAO,EAKN,oBAAoB,EACpB,cAAc,EACd,UAAU,EACV,4BAA4B,GAK5B,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,aAAa,EAAE,MAAM,4CAA4C,CAAC;AAC3E,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAClD,OAAO,EACN,iCAAiC,EAEjC,4BAA4B,EAC5B,mBAAmB,GACnB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAA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AI,GAAG,kBAAkB,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC;YACtD,IAAI,QAAQ,IAAI,OAAO,CAAC,MAAM,CAAC,OAAO,IAAI,CAAC,aAAa,CAAC,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,aAAa,CAAC,EAAE,QAAQ,CAAC;gBACzG,OAAO;YACR,MAAM,OAAO,CAAC,OAAO,CAAC;gBACrB,OAAO,EAAE,IAAI;gBACb,MAAM,EAAE,GAAG,EAAE;oBACZ,IACC,QAAQ;wBACR,OAAO,CAAC,MAAM,CAAC,OAAO;wBACtB,CAAC,aAAa,CAAC,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,aAAa,CAAC,EAAE,QAAQ,CAAC;wBAEhE,OAAO;oBACR,KAAK,GAAG,QAAQ,CAAC;oBACjB,MAAM,GAAG,IAAI,CAAC;oBACd,WAAW,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC;gBAChD,CAAC;aACD,CAAC,CAAC;QACJ,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["// Managed account provider: reference-only auth and account-scoped pi-messages catalog.\nimport { createHash, randomUUID } from \"node:crypto\";\nimport {\n\ttype Api,\n\ttype ApiKeyCredential,\n\ttype AssistantMessage,\n\ttype AssistantMessageEvent,\n\tcreateDelegatedFetch,\n\tcreateProvider,\n\tlazyStream,\n\tManagedAssistantMessageQueue,\n\ttype Model,\n\ttype Provider,\n\ttype SimpleStreamOptions,\n\ttype TranscriptContext,\n} from \"@earendil-works/pi-ai\";\nimport { piMessagesApi } from \"@earendil-works/pi-ai/api/pi-messages.lazy\";\nimport { sameReference } from \"./account-store.ts\";\nimport { deriveHcodeCatalog } from \"./catalog.ts\";\nimport {\n\tHCODE_CATALOG_EMPTY_REASON_HEADER,\n\ttype HcodeCatalogEmptyReason,\n\tparseHcodeCatalogEmptyReason,\n\tparseHcodeModelList,\n} from \"./contracts.ts\";\nimport { type HcodeEnvironment, hcodeDisplayName, resolveHcodeEnvironment } from \"./environment.ts\";\nimport { HCODE_PROVIDER, hcodeJson } from \"./http.ts\";\nimport {\n\tfitHcodeRequestSize,\n\thcodeActivePrompts,\n\thcodeImagePayloadDraft,\n\treportHcodeImageSizeRefusal,\n} from \"./images.ts\";\nimport type { HcodeLocalReason } from \"./notices.ts\";\nimport type { HcodeAccountPort, HcodeAccountRef } from \"./ports.ts\";\nimport { createHcodeTransport, HcodeLocalRefusal, HcodeTransportError, parseHcodeRequestBody } from \"./transport.ts\";\nimport * as wire from \"./wire.ts\";\n\n/** Account-bound native provider whose owning runtime must dispose its subscription and catalog. */\nexport interface HcodeProvider extends Provider<\"pi-messages\"> {\n\t/** Release account observation and prevent further catalog/auth/request work. */\n\tdispose(): void;\n\t/** Forge's reason the current account's catalog is empty, if it sent a known one. */\n\tcatalogEmptyReason(): HcodeCatalogEmptyReason | undefined;\n\t/** Whether this process has read the current account's catalog; a new process reads it when /model opens. */\n\tcatalogLoaded(): boolean;\n}\n\n/** Returns only the keyless local reference allowed in the generic credential pool. */\nexport function hcodeReferenceCredential(ref: HcodeAccountRef): ApiKeyCredential {\n\treturn {\n\t\ttype: \"api_key\",\n\t\tenv: {\n\t\t\tHCODE_ENVIRONMENT_ID: ref.environmentId,\n\t\t\tHCODE_ACCOUNT_ID: ref.accountId,\n\t\t\tHCODE_GENERATION: ref.generation,\n\t\t},\n\t};\n}\n\n// Forge replays tool call IDs only in this form; other providers' IDs (for example `call_…|fc_…`) are rewritten.\nconst replayableToolCallId = /^[A-Za-z0-9_-]{1,64}$/;\nconst foreignToolCallId = (id: string) =>\n\treplayableToolCallId.test(id) ? id : `call_${createHash(\"sha256\").update(id).digest(\"hex\").slice(0, 32)}`;\n\n// Project history for the destination model without changing the saved transcript.\nexport function projectHcodeContext(\n\tcontext: TranscriptContext,\n\tmodel: Pick<Model<Api>, \"id\" | \"reasoning\">,\n): TranscriptContext {\n\tconst reasoning = model.reasoning;\n\tconst toolCallIds = new Map<string, string>();\n\treturn {\n\t\t...context,\n\t\tmessages: context.messages.flatMap((message) => {\n\t\t\tif (\n\t\t\t\tmessage.role === \"assistant\" &&\n\t\t\t\t(message.provider !== HCODE_PROVIDER || message.api !== \"pi-messages\" || message.model !== model.id)\n\t\t\t) {\n\t\t\t\t// Signatures, thinking and provider thinking levels are valid only for the model that produced them;\n\t\t\t\t// Forge refuses them from any other model, so a model switch keeps only the visible turn.\n\t\t\t\tconst { providerThinkingLevel: _level, ...foreign } = message;\n\t\t\t\tconst content = foreign.content.flatMap((block): AssistantMessage[\"content\"] => {\n\t\t\t\t\tif (block.type === \"thinking\") return [];\n\t\t\t\t\tif (block.type === \"text\") return [{ type: \"text\", text: block.text }];\n\t\t\t\t\tconst { thoughtSignature: _signature, ...call } = block;\n\t\t\t\t\tconst id = foreignToolCallId(call.id);\n\t\t\t\t\tif (id !== call.id) toolCallIds.set(call.id, id);\n\t\t\t\t\treturn [{ ...call, id }];\n\t\t\t\t});\n\t\t\t\treturn content.length ? { ...foreign, content } : [];\n\t\t\t}\n\t\t\tif (message.role === \"toolResult\" && toolCallIds.has(message.toolCallId))\n\t\t\t\treturn { ...message, toolCallId: toolCallIds.get(message.toolCallId)! };\n\t\t\tif (!reasoning && message.role === \"assistant\" && message.content.some((block) => block.type === \"thinking\")) {\n\t\t\t\tconst content = message.content.filter((block) => block.type !== \"thinking\");\n\t\t\t\treturn content.length ? { ...message, content } : [];\n\t\t\t}\n\t\t\t// Catalog v1 qualifies ordinary JSON-schema tools, not provider-side constrained sampling.\n\t\t\tif (message.role !== \"system\" || !message.toolsAdded?.some((tool) => tool.constrainedSampling)) return message;\n\t\t\treturn {\n\t\t\t\t...message,\n\t\t\t\ttoolsAdded: message.toolsAdded.map((tool) => {\n\t\t\t\t\tconst { constrainedSampling, ...ordinaryTool } = tool;\n\t\t\t\t\tif (\n\t\t\t\t\t\tconstrainedSampling &&\n\t\t\t\t\t\tconstrainedSampling.type === \"json_schema\" &&\n\t\t\t\t\t\tconstrainedSampling.strict === \"require\"\n\t\t\t\t\t)\n\t\t\t\t\t\tthrow new HcodeLocalRefusal(\"strictTools\");\n\t\t\t\t\treturn constrainedSampling ? ordinaryTool : tool;\n\t\t\t\t}),\n\t\t\t};\n\t\t}),\n\t};\n}\n\n/** Creates the dormant provider; no registration-time credential reads, probes or network work occur. */\nexport function createHcodeProvider(\n\taccount: HcodeAccountPort,\n\tenvironment: HcodeEnvironment = resolveHcodeEnvironment(),\n): HcodeProvider {\n\tconst name = hcodeDisplayName(environment.id);\n\tlet disposed = false;\n\tlet scope: HcodeAccountRef | null = null;\n\tlet models: readonly Model<\"pi-messages\">[] = Object.freeze([]);\n\tlet emptyReason: HcodeCatalogEmptyReason | undefined;\n\tconst clear = () => {\n\t\tscope = null;\n\t\tmodels = Object.freeze([]);\n\t\temptyReason = undefined;\n\t};\n\tconst unsubscribe = account.subscribe(clear);\n\tconst current = () => !disposed && scope && sameReference(account.status(scope.environmentId), scope);\n\tconst getModels = () => {\n\t\tif (!current()) clear();\n\t\treturn models;\n\t};\n\tconst credentialReference = (credential: ApiKeyCredential | undefined): HcodeAccountRef | null => {\n\t\tif (disposed || !credential || credential.key !== undefined || !credential.env) return null;\n\t\ttry {\n\t\t\tconst env = credential.env;\n\t\t\tconst ref = {\n\t\t\t\tenvironmentId: wire.string(env.HCODE_ENVIRONMENT_ID),\n\t\t\t\taccountId: wire.string(env.HCODE_ACCOUNT_ID),\n\t\t\t\tgeneration: wire.string(env.HCODE_GENERATION, 36),\n\t\t\t};\n\t\t\treturn ref.environmentId === environment.id && sameReference(account.status(ref.environmentId), ref)\n\t\t\t\t? ref\n\t\t\t\t: null;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t};\n\tconst native = piMessagesApi();\n\tconst run = (\n\t\tmodel: Model<Api>,\n\t\tcontext: TranscriptContext,\n\t\toptions: SimpleStreamOptions | undefined,\n\t\tmethod: \"stream\" | \"streamSimple\",\n\t) => {\n\t\t// Capture before lazy loading, auth resolution, callbacks or refresh can yield.\n\t\tconst expected = current() ? scope : null;\n\t\tconst canonical = models.find((entry) => entry.id === model.id);\n\t\tconst idempotencyKey = randomUUID();\n\t\tlet failure: HcodeTransportError | HcodeLocalRefusal | undefined;\n\t\tconst refuse = (reason: HcodeLocalReason): never => {\n\t\t\tfailure = new HcodeLocalRefusal(reason);\n\t\t\tthrow failure;\n\t\t};\n\t\tconst controller = new AbortController();\n\t\tconst signal = options?.signal ? AbortSignal.any([options.signal, controller.signal]) : controller.signal;\n\t\tconst queue = new ManagedAssistantMessageQueue(model, new HcodeTransportError().message, () =>\n\t\t\tcontroller.abort(),\n\t\t);\n\t\tconst source = lazyStream(\n\t\t\tmodel,\n\t\t\tasync () => {\n\t\t\t\tif (\n\t\t\t\t\t!expected ||\n\t\t\t\t\t!canonical ||\n\t\t\t\t\tdisposed ||\n\t\t\t\t\tmodel.provider !== HCODE_PROVIDER ||\n\t\t\t\t\tmodel.api !== \"pi-messages\" ||\n\t\t\t\t\t!sameReference(account.status(expected.environmentId), expected)\n\t\t\t\t)\n\t\t\t\t\treturn refuse(\"account\");\n\t\t\t\tif (options?.transport && options.transport !== \"sse\") return refuse(\"transport\");\n\t\t\t\tlet projected: TranscriptContext;\n\t\t\t\ttry {\n\t\t\t\t\tprojected = projectHcodeContext(context, canonical);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (error instanceof HcodeLocalRefusal) failure = error;\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tconst active = new Set(\n\t\t\t\t\tprojected.messages.flatMap((message, index) =>\n\t\t\t\t\t\tArray.isArray(message.content) && hcodeActivePrompts.has(message.content) ? [index] : [],\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tlet wireOmissions = 0;\n\t\t\t\tconst delegated = createHcodeTransport(\n\t\t\t\t\t{\n\t\t\t\t\t\t...account,\n\t\t\t\t\t\tstatus: (id) => (!disposed && models.includes(canonical) ? account.status(id) : null),\n\t\t\t\t\t},\n\t\t\t\t\tenvironment,\n\t\t\t\t\texpected,\n\t\t\t\t\tcanonical,\n\t\t\t\t\tidempotencyKey,\n\t\t\t\t\t() => wireOmissions,\n\t\t\t\t);\n\t\t\t\tconst safeOptions: SimpleStreamOptions & { managedQueue: ManagedAssistantMessageQueue } = {\n\t\t\t\t\tmanagedQueue: queue,\n\t\t\t\t\tsignal,\n\t\t\t\t\ttemperature: options?.temperature,\n\t\t\t\t\tmaxTokens: options?.maxTokens ?? Math.min(4096, canonical.maxTokens),\n\t\t\t\t\treasoning: options?.reasoning,\n\t\t\t\t\ttoolChoice: options?.toolChoice,\n\t\t\t\t\ttransport: \"sse\",\n\t\t\t\t\tcacheRetention: \"none\",\n\t\t\t\t\tmaxRetries: 0,\n\t\t\t\t\tonPayload: async (payload, nativeModel) => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t// Native pi-messages constructs this envelope from the projected transcript.\n\t\t\t\t\t\t\tlet envelope = payload as { context: TranscriptContext };\n\t\t\t\t\t\t\tlet protectedMessages = active;\n\t\t\t\t\t\t\tif (options?.onPayload) {\n\t\t\t\t\t\t\t\tconst hook = hcodeImagePayloadDraft(envelope, active);\n\t\t\t\t\t\t\t\tconst changed = await options.onPayload(hook.draft, nativeModel);\n\t\t\t\t\t\t\t\t// The hook returns unknown; the strict parser below remains the final schema check.\n\t\t\t\t\t\t\t\tenvelope = changed === undefined ? hook.draft : (changed as typeof envelope);\n\t\t\t\t\t\t\t\tprotectedMessages = hook.protectedMessages(envelope.context.messages);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst fitted = await fitHcodeRequestSize(\n\t\t\t\t\t\t\t\tcanonical,\n\t\t\t\t\t\t\t\tenvelope.context.messages,\n\t\t\t\t\t\t\t\tprotectedMessages,\n\t\t\t\t\t\t\t\t(messages) => JSON.stringify({ ...envelope, context: { ...envelope.context, messages } }),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tif (!fitted) {\n\t\t\t\t\t\t\t\tif (active.size && protectedMessages.size) reportHcodeImageSizeRefusal();\n\t\t\t\t\t\t\t\treturn refuse(\"size\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\twireOmissions = fitted.omitted;\n\t\t\t\t\t\t\treturn parseHcodeRequestBody(fitted.body);\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\treturn refuse(error instanceof HcodeLocalRefusal ? error.reason : \"envelope\");\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tonRequest: options?.onRequest,\n\t\t\t\t\tonResponse: options?.onResponse,\n\t\t\t\t\tonProviderStreamEvent: options?.onProviderStreamEvent,\n\t\t\t\t\tfetch: createDelegatedFetch(async (input, init) => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\treturn await delegated(input, init);\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tfailure =\n\t\t\t\t\t\t\t\terror instanceof HcodeTransportError || error instanceof HcodeLocalRefusal ? error : undefined;\n\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t}\n\t\t\t\t\t}),\n\t\t\t\t};\n\t\t\t\treturn native[method](canonical, projected, safeOptions);\n\t\t\t},\n\t\t\tundefined,\n\t\t\tsignal,\n\t\t\tqueue,\n\t\t);\n\t\treturn lazyStream(\n\t\t\tmodel,\n\t\t\tasync () =>\n\t\t\t\t(async function* (): AsyncGenerator<AssistantMessageEvent> {\n\t\t\t\t\tfor await (const event of source) {\n\t\t\t\t\t\tif (event.type === \"error\") {\n\t\t\t\t\t\t\tevent.error.errorMessage = failure?.message ?? new HcodeTransportError().message;\n\t\t\t\t\t\t\tevent.error.diagnostics = [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\ttype: \"provider_http_error\",\n\t\t\t\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\t\t\t\tdetails: {\n\t\t\t\t\t\t\t\t\t\tretryable: false,\n\t\t\t\t\t\t\t\t\t\t...(failure instanceof HcodeLocalRefusal\n\t\t\t\t\t\t\t\t\t\t\t? { hcodeLocalReason: failure.reason }\n\t\t\t\t\t\t\t\t\t\t\t: failure?.failure\n\t\t\t\t\t\t\t\t\t\t\t\t? { hcode: failure.diagnostics() }\n\t\t\t\t\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tyield event;\n\t\t\t\t\t}\n\t\t\t\t})(),\n\t\t\tundefined,\n\t\t\tsignal,\n\t\t\tqueue,\n\t\t);\n\t};\n\tconst base = createProvider<\"pi-messages\">({\n\t\tid: HCODE_PROVIDER,\n\t\tname,\n\t\tbaseUrl: environment.inferenceBaseUrl,\n\t\tmodels: [],\n\t\tauth: {\n\t\t\tapiKey: {\n\t\t\t\tname,\n\t\t\t\tlogin: async (interaction) => {\n\t\t\t\t\tif (disposed) throw new Error(\"HUMAIN Code account provider is disposed.\");\n\t\t\t\t\tconst reference = await account.login(interaction, interaction.signal);\n\t\t\t\t\tif (disposed) throw new Error(\"HUMAIN Code account provider is disposed.\");\n\t\t\t\t\treturn hcodeReferenceCredential(reference);\n\t\t\t\t},\n\t\t\t\tcheck: async ({ credential, signal }) => {\n\t\t\t\t\tsignal.throwIfAborted();\n\t\t\t\t\treturn credentialReference(credential) ? { type: \"api_key\", source: \"HUMAIN Code account\" } : undefined;\n\t\t\t\t},\n\t\t\t\tresolve: async ({ credential, signal }) => {\n\t\t\t\t\tsignal.throwIfAborted();\n\t\t\t\t\tconst ref = credentialReference(credential);\n\t\t\t\t\treturn ref\n\t\t\t\t\t\t? { auth: {}, env: hcodeReferenceCredential(ref).env, source: \"HUMAIN Code account\" }\n\t\t\t\t\t\t: undefined;\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tapi: {\n\t\t\tstream: (model, context, options) => run(model, context, options, \"stream\"),\n\t\t\tstreamSimple: (model, context, options) => run(model, context, options, \"streamSimple\"),\n\t\t},\n\t});\n\treturn {\n\t\t...base,\n\t\tdispose() {\n\t\t\tif (disposed) return;\n\t\t\tdisposed = true;\n\t\t\tunsubscribe();\n\t\t\tclear();\n\t\t},\n\t\tgetModels,\n\t\tgetAllModels: getModels,\n\t\tcatalogEmptyReason: () => (getModels().length ? undefined : emptyReason),\n\t\tcatalogLoaded: () => !!current(),\n\t\tasync refreshModels(context) {\n\t\t\tconst expected = context.credential?.type === \"api_key\" ? credentialReference(context.credential) : null;\n\t\t\tif (!expected) {\n\t\t\t\tclear();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!context.allowNetwork || context.signal.aborted) return;\n\t\t\tlet reason: HcodeCatalogEmptyReason | undefined;\n\t\t\tconst entries = parseHcodeModelList(\n\t\t\t\tawait hcodeJson(\n\t\t\t\t\tasync (url, init) => {\n\t\t\t\t\t\tconst response = await account.authorizedFetch(expected, String(url), init ?? {});\n\t\t\t\t\t\treason = parseHcodeCatalogEmptyReason(response.headers.get(HCODE_CATALOG_EMPTY_REASON_HEADER));\n\t\t\t\t\t\treturn response;\n\t\t\t\t\t},\n\t\t\t\t\t`${environment.inferenceBaseUrl}/models`,\n\t\t\t\t\t{ signal: context.signal },\n\t\t\t\t),\n\t\t\t).data;\n\t\t\tconst next = deriveHcodeCatalog(entries, environment);\n\t\t\tif (disposed || context.signal.aborted || !sameReference(account.status(expected.environmentId), expected))\n\t\t\t\treturn;\n\t\t\tawait context.publish({\n\t\t\t\tpersist: null,\n\t\t\t\tupdate: () => {\n\t\t\t\t\tif (\n\t\t\t\t\t\tdisposed ||\n\t\t\t\t\t\tcontext.signal.aborted ||\n\t\t\t\t\t\t!sameReference(account.status(expected.environmentId), expected)\n\t\t\t\t\t)\n\t\t\t\t\t\treturn;\n\t\t\t\t\tscope = expected;\n\t\t\t\t\tmodels = next;\n\t\t\t\t\temptyReason = next.length ? undefined : reason;\n\t\t\t\t},\n\t\t\t});\n\t\t},\n\t};\n}\n"]}
1
+ {"version":3,"file":"provider.js","sourceRoot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,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,aAAa,CAAC,EAAE,QAAQ,CAAC;gBACzG,OAAO;YACR,MAAM,OAAO,CAAC,OAAO,CAAC;gBACrB,OAAO,EAAE,IAAI;gBACb,MAAM,EAAE,GAAG,EAAE;oBACZ,IACC,QAAQ;wBACR,OAAO,CAAC,MAAM,CAAC,OAAO;wBACtB,CAAC,aAAa,CAAC,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,aAAa,CAAC,EAAE,QAAQ,CAAC;wBAEhE,OAAO;oBACR,iFAAiF;oBACjF,IAAI,CAAC,aAAa,CAAC,KAAK,EAAE,QAAQ,CAAC,IAAI,CAAC,iBAAiB,CAAC,MAAM,EAAE,IAAI,CAAC;wBAAE,MAAM,GAAG,IAAI,CAAC;oBACvF,KAAK,GAAG,QAAQ,CAAC;oBACjB,WAAW,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC;oBAC/C,UAAU,GAAG,QAAQ,CAAC;gBACvB,CAAC;aACD,CAAC,CAAC;QACJ,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["// Managed account provider: reference-only auth and account-scoped pi-messages catalog.\nimport { createHash, randomUUID } from \"node:crypto\";\nimport { isDeepStrictEqual } from \"node:util\";\nimport {\n\ttype Api,\n\ttype ApiKeyCredential,\n\ttype AssistantMessage,\n\ttype AssistantMessageEvent,\n\tcreateDelegatedFetch,\n\tcreateProvider,\n\tlazyStream,\n\tManagedAssistantMessageQueue,\n\ttype Model,\n\ttype Provider,\n\ttype SimpleStreamOptions,\n\ttype SystemMessage,\n\ttype TranscriptContext,\n} from \"@earendil-works/pi-ai\";\nimport { piMessagesApi } from \"@earendil-works/pi-ai/api/pi-messages.lazy\";\nimport { sameReference } from \"./account-store.ts\";\nimport { deriveHcodeCatalog } from \"./catalog.ts\";\nimport {\n\tHCODE_CATALOG_EMPTY_REASON_HEADER,\n\tHCODE_CATALOG_EXCLUSIONS_HEADER,\n\ttype HcodeCatalogEmptyReason,\n\ttype HcodeCatalogExclusionReason,\n\tparseHcodeCatalogEmptyReason,\n\tparseHcodeCatalogExclusions,\n\tparseHcodeModelList,\n} from \"./contracts.ts\";\nimport { type HcodeEnvironment, hcodeDisplayName, resolveHcodeEnvironment } from \"./environment.ts\";\nimport { HCODE_PROVIDER, hcodeJson } from \"./http.ts\";\nimport {\n\tfitHcodeRequestSize,\n\thcodeActivePrompts,\n\thcodeImagePayloadDraft,\n\treportHcodeImageSizeRefusal,\n} from \"./images.ts\";\nimport type { HcodeLocalReason } from \"./notices.ts\";\nimport type { HcodeAccountPort, HcodeAccountRef } from \"./ports.ts\";\nimport { createHcodeTransport, HcodeLocalRefusal, HcodeTransportError, parseHcodeRequestBody } from \"./transport.ts\";\nimport * as wire from \"./wire.ts\";\n\n/** Account-bound native provider whose owning runtime must dispose its subscription and catalog. */\nexport interface HcodeProvider extends Provider<\"pi-messages\"> {\n\t/** Release account observation and prevent further catalog/auth/request work. */\n\tdispose(): void;\n\t/** Forge's reason the current account's catalog is empty, if it sent a known one. */\n\tcatalogEmptyReason(): HcodeCatalogEmptyReason | undefined;\n\t/** Forge's reason the current account's catalog left out this exact model ID, if it sent a known one. */\n\tcatalogExclusionReason(modelId: string): HcodeCatalogExclusionReason | undefined;\n\t/** Whether this process has read the current account's catalog; a new process reads it when /model opens. */\n\tcatalogLoaded(): boolean;\n}\n\n/** Returns only the keyless local reference allowed in the generic credential pool. */\nexport function hcodeReferenceCredential(ref: HcodeAccountRef): ApiKeyCredential {\n\treturn {\n\t\ttype: \"api_key\",\n\t\tenv: {\n\t\t\tHCODE_ENVIRONMENT_ID: ref.environmentId,\n\t\t\tHCODE_ACCOUNT_ID: ref.accountId,\n\t\t\tHCODE_GENERATION: ref.generation,\n\t\t},\n\t};\n}\n\n// Forge replays tool call IDs only in this form; other providers' IDs (for example `call_…|fc_…`) are rewritten.\nconst replayableToolCallId = /^[A-Za-z0-9_-]{1,64}$/;\nconst foreignToolCallId = (id: string) =>\n\treplayableToolCallId.test(id) ? id : `call_${createHash(\"sha256\").update(id).digest(\"hex\").slice(0, 32)}`;\n\n// Project history for the destination model without changing the saved transcript.\nexport function projectHcodeContext(\n\tcontext: TranscriptContext,\n\tmodel: Pick<Model<Api>, \"id\" | \"reasoning\">,\n): TranscriptContext {\n\tconst messages: TranscriptContext[\"messages\"] = [];\n\tconst activeTools = new Set<string>();\n\tconst pending = new Map<string, { id: string; name: string; timestamp: number }>();\n\tconst closeTurn = () => {\n\t\tfor (const call of pending.values()) {\n\t\t\tmessages.push({\n\t\t\t\trole: \"toolResult\",\n\t\t\t\ttoolCallId: call.id,\n\t\t\t\ttoolName: call.name,\n\t\t\t\tcontent: [{ type: \"text\", text: \"No result provided\" }],\n\t\t\t\tisError: true,\n\t\t\t\ttimestamp: call.timestamp,\n\t\t\t});\n\t\t}\n\t\tpending.clear();\n\t};\n\tfor (const message of context.messages) {\n\t\tif (message.role === \"system\") {\n\t\t\t// Evaluate calls against the tools declared at their turn, not the final live loadout.\n\t\t\tfor (const tool of message.toolsRemoved ?? []) activeTools.delete(tool.name);\n\t\t\tfor (const tool of message.toolsAdded ?? []) activeTools.add(tool.name);\n\t\t\tmessages.push(projectHcodeSystemMessage(message));\n\t\t\tcontinue;\n\t\t}\n\t\tif (message.role === \"toolResult\") {\n\t\t\tconst call = pending.get(message.toolCallId);\n\t\t\tif (!call || call.name !== message.toolName) continue;\n\t\t\tpending.delete(message.toolCallId);\n\t\t\t// Execution details and nested calls are session/UI bookkeeping, not model input.\n\t\t\tmessages.push({\n\t\t\t\trole: \"toolResult\",\n\t\t\t\ttoolCallId: call.id,\n\t\t\t\ttoolName: message.toolName,\n\t\t\t\tcontent: message.content,\n\t\t\t\tisError: message.isError,\n\t\t\t\ttimestamp: message.timestamp,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tcloseTurn();\n\t\tif (message.role === \"user\") {\n\t\t\tmessages.push(message);\n\t\t\tcontinue;\n\t\t}\n\t\t// Incomplete turns were never replayable and may contain calls that never ran.\n\t\tif (message.stopReason === \"error\" || message.stopReason === \"aborted\" || message.stopReason === \"deferred\")\n\t\t\tcontinue;\n\t\tconst sameModel =\n\t\t\tmessage.provider === HCODE_PROVIDER && message.api === \"pi-messages\" && message.model === model.id;\n\t\tconst { deferred: _handle, providerThinkingLevel, ...assistant } = message;\n\t\tconst content = assistant.content.flatMap((block): AssistantMessage[\"content\"] => {\n\t\t\tif (block.type === \"thinking\") return sameModel && model.reasoning ? [block] : [];\n\t\t\tif (block.type === \"text\") return [sameModel ? block : { type: \"text\", text: block.text }];\n\t\t\tif (block.argumentsError !== undefined || !activeTools.has(block.name)) return [];\n\t\t\tconst id = sameModel ? block.id : foreignToolCallId(block.id);\n\t\t\tpending.set(block.id, { id, name: block.name, timestamp: message.timestamp });\n\t\t\tif (sameModel) return [block];\n\t\t\tconst { thoughtSignature: _signature, ...call } = block;\n\t\t\treturn [{ ...call, id }];\n\t\t});\n\t\tif (!content.length && (!sameModel || message.content.length)) continue;\n\t\tmessages.push({\n\t\t\t...assistant,\n\t\t\tcontent,\n\t\t\tstopReason: assistant.stopReason === \"toolUse\" && !pending.size ? \"stop\" : assistant.stopReason,\n\t\t\t...(sameModel && providerThinkingLevel !== undefined ? { providerThinkingLevel } : {}),\n\t\t});\n\t}\n\tcloseTurn();\n\treturn { ...context, messages };\n}\n\nfunction projectHcodeSystemMessage(message: SystemMessage): SystemMessage {\n\t// Catalog v1 qualifies ordinary JSON-schema tools, not provider-side constrained sampling.\n\tif (!message.toolsAdded?.some((tool) => tool.constrainedSampling)) return message;\n\treturn {\n\t\t...message,\n\t\ttoolsAdded: message.toolsAdded.map((tool) => {\n\t\t\tconst { constrainedSampling, ...ordinaryTool } = tool;\n\t\t\tif (\n\t\t\t\tconstrainedSampling &&\n\t\t\t\tconstrainedSampling.type === \"json_schema\" &&\n\t\t\t\tconstrainedSampling.strict === \"require\"\n\t\t\t)\n\t\t\t\tthrow new HcodeLocalRefusal(\"strictTools\");\n\t\t\treturn constrainedSampling ? ordinaryTool : tool;\n\t\t}),\n\t};\n}\n\n/** Creates the dormant provider; no registration-time credential reads, probes or network work occur. */\nexport function createHcodeProvider(\n\taccount: HcodeAccountPort,\n\tenvironment: HcodeEnvironment = resolveHcodeEnvironment(),\n): HcodeProvider {\n\tconst name = hcodeDisplayName(environment.id);\n\tlet disposed = false;\n\tlet scope: HcodeAccountRef | null = null;\n\tlet models: readonly Model<\"pi-messages\">[] = Object.freeze([]);\n\tlet emptyReason: HcodeCatalogEmptyReason | undefined;\n\tlet exclusions: ReadonlyMap<string, HcodeCatalogExclusionReason> = new Map();\n\tconst clear = () => {\n\t\tscope = null;\n\t\tmodels = Object.freeze([]);\n\t\temptyReason = undefined;\n\t\texclusions = new Map();\n\t};\n\tconst unsubscribe = account.subscribe(clear);\n\tconst current = () => !disposed && scope && sameReference(account.status(scope.environmentId), scope);\n\tconst getModels = () => {\n\t\tif (!current()) clear();\n\t\treturn models;\n\t};\n\tconst credentialReference = (credential: ApiKeyCredential | undefined): HcodeAccountRef | null => {\n\t\tif (disposed || !credential || credential.key !== undefined || !credential.env) return null;\n\t\ttry {\n\t\t\tconst env = credential.env;\n\t\t\tconst ref = {\n\t\t\t\tenvironmentId: wire.string(env.HCODE_ENVIRONMENT_ID),\n\t\t\t\taccountId: wire.string(env.HCODE_ACCOUNT_ID),\n\t\t\t\tgeneration: wire.string(env.HCODE_GENERATION, 36),\n\t\t\t};\n\t\t\treturn ref.environmentId === environment.id && sameReference(account.status(ref.environmentId), ref)\n\t\t\t\t? ref\n\t\t\t\t: null;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t};\n\tconst native = piMessagesApi();\n\tconst run = (\n\t\tmodel: Model<Api>,\n\t\tcontext: TranscriptContext,\n\t\toptions: SimpleStreamOptions | undefined,\n\t\tmethod: \"stream\" | \"streamSimple\",\n\t) => {\n\t\t// Capture before lazy loading, auth resolution, callbacks or refresh can yield.\n\t\tconst expected = current() ? scope : null;\n\t\tconst canonical = models.find((entry) => entry.id === model.id);\n\t\tconst idempotencyKey = randomUUID();\n\t\tlet failure: HcodeTransportError | HcodeLocalRefusal | undefined;\n\t\tconst refuse = (reason: HcodeLocalReason): never => {\n\t\t\tfailure = new HcodeLocalRefusal(reason);\n\t\t\tthrow failure;\n\t\t};\n\t\tconst controller = new AbortController();\n\t\tconst signal = options?.signal ? AbortSignal.any([options.signal, controller.signal]) : controller.signal;\n\t\tconst queue = new ManagedAssistantMessageQueue(model, new HcodeTransportError().message, () =>\n\t\t\tcontroller.abort(),\n\t\t);\n\t\tconst source = lazyStream(\n\t\t\tmodel,\n\t\t\tasync () => {\n\t\t\t\tif (\n\t\t\t\t\t!expected ||\n\t\t\t\t\t!canonical ||\n\t\t\t\t\tdisposed ||\n\t\t\t\t\tmodel.provider !== HCODE_PROVIDER ||\n\t\t\t\t\tmodel.api !== \"pi-messages\" ||\n\t\t\t\t\t!sameReference(account.status(expected.environmentId), expected)\n\t\t\t\t)\n\t\t\t\t\treturn refuse(\"account\");\n\t\t\t\tif (options?.transport && options.transport !== \"sse\") return refuse(\"transport\");\n\t\t\t\tlet projected: TranscriptContext;\n\t\t\t\ttry {\n\t\t\t\t\tprojected = projectHcodeContext(context, canonical);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (error instanceof HcodeLocalRefusal) failure = error;\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tconst active = new Set(\n\t\t\t\t\tprojected.messages.flatMap((message, index) =>\n\t\t\t\t\t\tArray.isArray(message.content) && hcodeActivePrompts.has(message.content) ? [index] : [],\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tlet wireOmissions = 0;\n\t\t\t\tconst delegated = createHcodeTransport(\n\t\t\t\t\t{\n\t\t\t\t\t\t...account,\n\t\t\t\t\t\tstatus: (id) => (!disposed && models.includes(canonical) ? account.status(id) : null),\n\t\t\t\t\t},\n\t\t\t\t\tenvironment,\n\t\t\t\t\texpected,\n\t\t\t\t\tcanonical,\n\t\t\t\t\tidempotencyKey,\n\t\t\t\t\t() => wireOmissions,\n\t\t\t\t);\n\t\t\t\tconst safeOptions: SimpleStreamOptions & { managedQueue: ManagedAssistantMessageQueue } = {\n\t\t\t\t\tmanagedQueue: queue,\n\t\t\t\t\tsignal,\n\t\t\t\t\ttemperature: options?.temperature,\n\t\t\t\t\tmaxTokens: options?.maxTokens ?? Math.min(4096, canonical.maxTokens),\n\t\t\t\t\treasoning: options?.reasoning,\n\t\t\t\t\ttoolChoice: options?.toolChoice,\n\t\t\t\t\ttransport: \"sse\",\n\t\t\t\t\tcacheRetention: \"none\",\n\t\t\t\t\tmaxRetries: 0,\n\t\t\t\t\tonPayload: async (payload, nativeModel) => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t// Native pi-messages constructs this envelope from the projected transcript.\n\t\t\t\t\t\t\tlet envelope = payload as { context: TranscriptContext };\n\t\t\t\t\t\t\tlet protectedMessages = active;\n\t\t\t\t\t\t\tif (options?.onPayload) {\n\t\t\t\t\t\t\t\tconst hook = hcodeImagePayloadDraft(envelope, active);\n\t\t\t\t\t\t\t\tconst changed = await options.onPayload(hook.draft, nativeModel);\n\t\t\t\t\t\t\t\t// The hook returns unknown; the strict parser below remains the final schema check.\n\t\t\t\t\t\t\t\tenvelope = changed === undefined ? hook.draft : (changed as typeof envelope);\n\t\t\t\t\t\t\t\tprotectedMessages = hook.protectedMessages(envelope.context.messages);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (Array.isArray(envelope.context.messages) && envelope.context.messages.length > 512) {\n\t\t\t\t\t\t\t\tthrow new HcodeLocalRefusal(\"envelope\", \"messageLimit\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst fitted = await fitHcodeRequestSize(\n\t\t\t\t\t\t\t\tcanonical,\n\t\t\t\t\t\t\t\tenvelope.context.messages,\n\t\t\t\t\t\t\t\tprotectedMessages,\n\t\t\t\t\t\t\t\t(messages) => JSON.stringify({ ...envelope, context: { ...envelope.context, messages } }),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tif (!fitted) {\n\t\t\t\t\t\t\t\tif (active.size && protectedMessages.size) reportHcodeImageSizeRefusal();\n\t\t\t\t\t\t\t\treturn refuse(\"size\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\twireOmissions = fitted.omitted;\n\t\t\t\t\t\t\treturn parseHcodeRequestBody(fitted.body);\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tif (error instanceof HcodeLocalRefusal) {\n\t\t\t\t\t\t\t\tfailure = error;\n\t\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn refuse(\"envelope\");\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tonRequest: options?.onRequest,\n\t\t\t\t\tonResponse: options?.onResponse,\n\t\t\t\t\tonProviderStreamEvent: options?.onProviderStreamEvent,\n\t\t\t\t\tfetch: createDelegatedFetch(async (input, init) => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\treturn await delegated(input, init);\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tfailure =\n\t\t\t\t\t\t\t\terror instanceof HcodeTransportError || error instanceof HcodeLocalRefusal ? error : undefined;\n\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t}\n\t\t\t\t\t}),\n\t\t\t\t};\n\t\t\t\treturn native[method](canonical, projected, safeOptions);\n\t\t\t},\n\t\t\tundefined,\n\t\t\tsignal,\n\t\t\tqueue,\n\t\t);\n\t\treturn lazyStream(\n\t\t\tmodel,\n\t\t\tasync () =>\n\t\t\t\t(async function* (): AsyncGenerator<AssistantMessageEvent> {\n\t\t\t\t\tfor await (const event of source) {\n\t\t\t\t\t\tif (event.type === \"error\") {\n\t\t\t\t\t\t\tevent.error.errorMessage = failure?.message ?? new HcodeTransportError().message;\n\t\t\t\t\t\t\tevent.error.diagnostics = [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\ttype: \"provider_http_error\",\n\t\t\t\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\t\t\t\tdetails: {\n\t\t\t\t\t\t\t\t\t\tretryable: false,\n\t\t\t\t\t\t\t\t\t\t...(failure instanceof HcodeLocalRefusal\n\t\t\t\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\t\t\t\thcodeLocalReason: failure.reason,\n\t\t\t\t\t\t\t\t\t\t\t\t\t...(failure.detail ? { hcodeLocalDetail: failure.detail } : {}),\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t: failure?.failure\n\t\t\t\t\t\t\t\t\t\t\t\t? { hcode: failure.diagnostics() }\n\t\t\t\t\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tyield event;\n\t\t\t\t\t}\n\t\t\t\t})(),\n\t\t\tundefined,\n\t\t\tsignal,\n\t\t\tqueue,\n\t\t);\n\t};\n\tconst base = createProvider<\"pi-messages\">({\n\t\tid: HCODE_PROVIDER,\n\t\tname,\n\t\tbaseUrl: environment.inferenceBaseUrl,\n\t\tmodels: [],\n\t\tauth: {\n\t\t\tapiKey: {\n\t\t\t\tname,\n\t\t\t\tlogin: async (interaction) => {\n\t\t\t\t\tif (disposed) throw new Error(\"HUMAIN Code account provider is disposed.\");\n\t\t\t\t\tconst reference = await account.login(interaction, interaction.signal);\n\t\t\t\t\tif (disposed) throw new Error(\"HUMAIN Code account provider is disposed.\");\n\t\t\t\t\treturn hcodeReferenceCredential(reference);\n\t\t\t\t},\n\t\t\t\tcheck: async ({ credential, signal }) => {\n\t\t\t\t\tsignal.throwIfAborted();\n\t\t\t\t\treturn credentialReference(credential) ? { type: \"api_key\", source: \"HUMAIN Code account\" } : undefined;\n\t\t\t\t},\n\t\t\t\tresolve: async ({ credential, signal }) => {\n\t\t\t\t\tsignal.throwIfAborted();\n\t\t\t\t\tconst ref = credentialReference(credential);\n\t\t\t\t\treturn ref\n\t\t\t\t\t\t? { auth: {}, env: hcodeReferenceCredential(ref).env, source: \"HUMAIN Code account\" }\n\t\t\t\t\t\t: undefined;\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tapi: {\n\t\t\tstream: (model, context, options) => run(model, context, options, \"stream\"),\n\t\t\tstreamSimple: (model, context, options) => run(model, context, options, \"streamSimple\"),\n\t\t},\n\t});\n\treturn {\n\t\t...base,\n\t\tdispose() {\n\t\t\tif (disposed) return;\n\t\t\tdisposed = true;\n\t\t\tunsubscribe();\n\t\t\tclear();\n\t\t},\n\t\tgetModels,\n\t\tgetAllModels: getModels,\n\t\tcatalogEmptyReason: () => (getModels().length ? undefined : emptyReason),\n\t\tcatalogExclusionReason: (modelId) => {\n\t\t\t// Match `/model` exact references, which compare IDs case-insensitively.\n\t\t\tconst normalized = modelId.toLowerCase();\n\t\t\tif (getModels().some((model) => model.id.toLowerCase() === normalized)) return undefined;\n\t\t\tconst exact = exclusions.get(modelId);\n\t\t\tif (exact) return exact;\n\t\t\tfor (const [id, reason] of exclusions) {\n\t\t\t\tif (id.toLowerCase() === normalized) return reason;\n\t\t\t}\n\t\t\treturn undefined;\n\t\t},\n\t\tcatalogLoaded: () => !!current(),\n\t\tasync refreshModels(context) {\n\t\t\tconst expected = context.credential?.type === \"api_key\" ? credentialReference(context.credential) : null;\n\t\t\tif (!expected) {\n\t\t\t\tclear();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!context.allowNetwork || context.signal.aborted) return;\n\t\t\tlet reason: HcodeCatalogEmptyReason | undefined;\n\t\t\tlet excluded: ReadonlyMap<string, HcodeCatalogExclusionReason> = new Map();\n\t\t\tconst entries = parseHcodeModelList(\n\t\t\t\tawait hcodeJson(\n\t\t\t\t\tasync (url, init) => {\n\t\t\t\t\t\tconst response = await account.authorizedFetch(expected, String(url), init ?? {});\n\t\t\t\t\t\treason = parseHcodeCatalogEmptyReason(response.headers.get(HCODE_CATALOG_EMPTY_REASON_HEADER));\n\t\t\t\t\t\texcluded = parseHcodeCatalogExclusions(response.headers.get(HCODE_CATALOG_EXCLUSIONS_HEADER));\n\t\t\t\t\t\treturn response;\n\t\t\t\t\t},\n\t\t\t\t\t`${environment.inferenceBaseUrl}/models`,\n\t\t\t\t\t{ signal: context.signal },\n\t\t\t\t),\n\t\t\t).data;\n\t\t\tconst next = deriveHcodeCatalog(entries, environment);\n\t\t\tif (disposed || context.signal.aborted || !sameReference(account.status(expected.environmentId), expected))\n\t\t\t\treturn;\n\t\t\tawait context.publish({\n\t\t\t\tpersist: null,\n\t\t\t\tupdate: () => {\n\t\t\t\t\tif (\n\t\t\t\t\t\tdisposed ||\n\t\t\t\t\t\tcontext.signal.aborted ||\n\t\t\t\t\t\t!sameReference(account.status(expected.environmentId), expected)\n\t\t\t\t\t)\n\t\t\t\t\t\treturn;\n\t\t\t\t\t// Unchanged approval must not invalidate a picker row or an in-flight selection.\n\t\t\t\t\tif (!sameReference(scope, expected) || !isDeepStrictEqual(models, next)) models = next;\n\t\t\t\t\tscope = expected;\n\t\t\t\t\temptyReason = next.length ? undefined : reason;\n\t\t\t\t\texclusions = excluded;\n\t\t\t\t},\n\t\t\t});\n\t\t},\n\t};\n}\n"]}
@@ -0,0 +1,21 @@
1
+ import { type HcodeEnvironment } from "./environment.ts";
2
+ import type { HcodeFacade } from "./facade.ts";
3
+ import type { HcodeAccountRef } from "./ports.ts";
4
+ export type HcodeRunBootstrap = {
5
+ kind: "desktop";
6
+ } | {
7
+ kind: "invalid";
8
+ } | {
9
+ kind: "run";
10
+ environment: HcodeEnvironment;
11
+ open: () => HcodeRunFacade;
12
+ };
13
+ export type HcodeRunFacade = Omit<HcodeFacade, "metadata"> & {
14
+ readonly metadata?: undefined;
15
+ readonly reference: HcodeAccountRef;
16
+ /** True once Forge answered 401: the Build token is expired or revoked. */
17
+ tokenRejected(): boolean;
18
+ };
19
+ /** Capture once, before parsing args or starting code that can load resources or fork. */
20
+ export declare function takeHcodeRunBootstrap(env: NodeJS.ProcessEnv): HcodeRunBootstrap;
21
+ //# sourceMappingURL=run-credential.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-credential.d.ts","sourceRoot":"","sources":["../../../src/humain/hcode/run-credential.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,KAAK,gBAAgB,EAA2B,MAAM,kBAAkB,CAAC;AAClF,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,KAAK,EAAoB,eAAe,EAAE,MAAM,YAAY,CAAC;AAQpE,MAAM,MAAM,iBAAiB,GAC1B;IAAE,IAAI,EAAE,SAAS,CAAA;CAAE,GACnB;IAAE,IAAI,EAAE,SAAS,CAAA;CAAE,GACnB;IAAE,IAAI,EAAE,KAAK,CAAC;IAAC,WAAW,EAAE,gBAAgB,CAAC;IAAC,IAAI,EAAE,MAAM,cAAc,CAAA;CAAE,CAAC;AAE9E,MAAM,MAAM,cAAc,GAAG,IAAI,CAAC,WAAW,EAAE,UAAU,CAAC,GAAG;IAC5D,QAAQ,CAAC,QAAQ,CAAC,EAAE,SAAS,CAAC;IAC9B,QAAQ,CAAC,SAAS,EAAE,eAAe,CAAC;IACpC,2EAA2E;IAC3E,aAAa,IAAI,OAAO,CAAC;CACzB,CAAC;AAEF,0FAA0F;AAC1F,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,MAAM,CAAC,UAAU,GAAG,iBAAiB,CA+B/E"}
@@ -0,0 +1,140 @@
1
+ // Forge owns the launch credential; only the native inference provider gets its send authority.
2
+ import { randomUUID } from "node:crypto";
3
+ import { sameReference } from "./account-store.js";
4
+ import { resolveHcodeEnvironment } from "./environment.js";
5
+ import { createHcodeProvider } from "./provider.js";
6
+ import { HcodeLocalRefusal } from "./transport.js";
7
+ const ORIGIN_ENV = "HUMAIN_CODE_FORGE_ORIGIN";
8
+ const TOKEN_ENV = "HUMAIN_CODE_RUN_TOKEN";
9
+ const UNAVAILABLE = "Forge run inference is unavailable.";
10
+ /** Capture once, before parsing args or starting code that can load resources or fork. */
11
+ export function takeHcodeRunBootstrap(env) {
12
+ const origin = env[ORIGIN_ENV];
13
+ const token = env[TOKEN_ENV];
14
+ let present = false;
15
+ let ambiguous = false;
16
+ for (const key of Object.keys(env)) {
17
+ const name = key.toUpperCase();
18
+ if (name !== TOKEN_ENV && name !== ORIGIN_ENV)
19
+ continue;
20
+ present = true;
21
+ ambiguous ||= key !== name;
22
+ delete env[key];
23
+ }
24
+ if (!present)
25
+ return { kind: "desktop" };
26
+ // Forge !839 sets exactly these two variables on the fresh agent command. Compare literal origins
27
+ // so the bearer cannot be sent to an alias, explicit port, or path supplied by the caller.
28
+ const environment = ["dev", "staging", "production"]
29
+ .map((name) => resolveHcodeEnvironment(name))
30
+ .find((candidate) => candidate.origin === origin);
31
+ if (ambiguous || !environment || !token || !/^frt_v1_[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/.test(token))
32
+ return { kind: "invalid" };
33
+ let bearer = token;
34
+ return {
35
+ kind: "run",
36
+ environment,
37
+ open() {
38
+ if (bearer === undefined)
39
+ throw new Error(UNAVAILABLE);
40
+ const credential = bearer;
41
+ bearer = undefined;
42
+ return createRunFacade(environment, credential);
43
+ },
44
+ };
45
+ }
46
+ function createRunFacade(environment, token) {
47
+ // Forge checks the sliding idle deadline at admission, not while a response is streaming.
48
+ const lifetime = new AbortController();
49
+ const signal = lifetime.signal;
50
+ const reference = {
51
+ environmentId: environment.id,
52
+ accountId: "forge-run",
53
+ generation: randomUUID(),
54
+ };
55
+ let tokenRejected = false;
56
+ const refuse = async () => {
57
+ throw new Error(UNAVAILABLE);
58
+ };
59
+ const account = {
60
+ // The selection fence needs a launch identity, not a signed-in account or its authority.
61
+ status: (id) => (!signal.aborted && id === environment.id ? reference : null),
62
+ login: refuse,
63
+ logout: refuse,
64
+ authorizedFetch: refuse,
65
+ subscribe: () => () => { },
66
+ };
67
+ const provider = createHcodeProvider({
68
+ ...account,
69
+ async authorizedFetch(expected, url, init) {
70
+ const method = init.method ?? "GET";
71
+ if (!sameReference(expected, reference) ||
72
+ // Forge sets HUMAIN_TERMINAL_OFFLINE to disable ambient discovery, not this scoped route.
73
+ process.env.PI_OFFLINE ||
74
+ !((method === "GET" && url === `${environment.inferenceBaseUrl}/models`) ||
75
+ (method === "POST" && url === `${environment.inferenceBaseUrl}/messages`)))
76
+ return refuse();
77
+ if (tokenRejected)
78
+ throw new HcodeLocalRefusal("buildSessionEnded");
79
+ const requestSignal = init.signal ? AbortSignal.any([signal, init.signal]) : signal;
80
+ requestSignal.throwIfAborted();
81
+ const headers = new Headers(init.headers);
82
+ headers.set("authorization", `Bearer ${token}`);
83
+ let response;
84
+ try {
85
+ response = await globalThis.fetch(url, {
86
+ method,
87
+ body: init.body,
88
+ headers,
89
+ signal: requestSignal,
90
+ redirect: "error",
91
+ credentials: "omit",
92
+ cache: "no-store",
93
+ });
94
+ }
95
+ catch {
96
+ return refuse();
97
+ }
98
+ if (response.redirected || (response.status >= 300 && response.status < 400)) {
99
+ void response.body?.cancel().catch(() => { });
100
+ return refuse();
101
+ }
102
+ if (response.status === 401) {
103
+ tokenRejected = true;
104
+ void response.body?.cancel().catch(() => { });
105
+ throw new HcodeLocalRefusal("buildSessionEnded");
106
+ }
107
+ // The native transport validates refusal details against a closed schema before display.
108
+ return response;
109
+ },
110
+ }, environment);
111
+ return {
112
+ reference,
113
+ tokenRejected: () => tokenRejected,
114
+ provider,
115
+ signal,
116
+ context: { account, usage: { read: refuse }, environment, environmentId: environment.id },
117
+ observeVersion() { },
118
+ async supportSnapshot() {
119
+ return { environmentId: environment.id };
120
+ },
121
+ async probeLogin() {
122
+ return { kind: "unavailable" };
123
+ },
124
+ accountEmail: () => undefined,
125
+ adopt: () => false,
126
+ signedInElsewhere: () => [],
127
+ async recover() { },
128
+ persistence: () => undefined,
129
+ login: refuse,
130
+ logoutStored: refuse,
131
+ async shutdown() {
132
+ return { remoteRevocation: "not-needed" };
133
+ },
134
+ dispose() {
135
+ lifetime.abort();
136
+ provider.dispose();
137
+ },
138
+ };
139
+ }
140
+ //# sourceMappingURL=run-credential.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-credential.js","sourceRoot":"","sources":["../../../src/humain/hcode/run-credential.ts"],"names":[],"mappings":"AAAA,gGAAgG;AAChG,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAyB,uBAAuB,EAAE,MAAM,kBAAkB,CAAC;AAGlF,OAAO,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AACpD,OAAO,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAEnD,MAAM,UAAU,GAAG,0BAA0B,CAAC;AAC9C,MAAM,SAAS,GAAG,uBAAuB,CAAC;AAC1C,MAAM,WAAW,GAAG,qCAAqC,CAAC;AAc1D,0FAA0F;AAC1F,MAAM,UAAU,qBAAqB,CAAC,GAAsB;IAC3D,MAAM,MAAM,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC;IAC/B,MAAM,KAAK,GAAG,GAAG,CAAC,SAAS,CAAC,CAAC;IAC7B,IAAI,OAAO,GAAG,KAAK,CAAC;IACpB,IAAI,SAAS,GAAG,KAAK,CAAC;IACtB,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;QACpC,MAAM,IAAI,GAAG,GAAG,CAAC,WAAW,EAAE,CAAC;QAC/B,IAAI,IAAI,KAAK,SAAS,IAAI,IAAI,KAAK,UAAU;YAAE,SAAS;QACxD,OAAO,GAAG,IAAI,CAAC;QACf,SAAS,KAAK,GAAG,KAAK,IAAI,CAAC;QAC3B,OAAO,GAAG,CAAC,GAAG,CAAC,CAAC;IACjB,CAAC;IACD,IAAI,CAAC,O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,EAAE;QACzF,cAAc,KAAI,CAAC;QACnB,KAAK,CAAC,eAAe;YACpB,OAAO,EAAE,aAAa,EAAE,WAAW,CAAC,EAAE,EAAE,CAAC;QAC1C,CAAC;QACD,KAAK,CAAC,UAAU;YACf,OAAO,EAAE,IAAI,EAAE,aAAa,EAAE,CAAC;QAChC,CAAC;QACD,YAAY,EAAE,GAAG,EAAE,CAAC,SAAS;QAC7B,KAAK,EAAE,GAAG,EAAE,CAAC,KAAK;QAClB,iBAAiB,EAAE,GAAG,EAAE,CAAC,EAAE;QAC3B,KAAK,CAAC,OAAO,KAAI,CAAC;QAClB,WAAW,EAAE,GAAG,EAAE,CAAC,SAAS;QAC5B,KAAK,EAAE,MAAM;QACb,YAAY,EAAE,MAAM;QACpB,KAAK,CAAC,QAAQ;YACb,OAAO,EAAE,gBAAgB,EAAE,YAAY,EAAE,CAAC;QAC3C,CAAC;QACD,OAAO;YACN,QAAQ,CAAC,KAAK,EAAE,CAAC;YACjB,QAAQ,CAAC,OAAO,EAAE,CAAC;QACpB,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["// Forge owns the launch credential; only the native inference provider gets its send authority.\nimport { randomUUID } from \"node:crypto\";\nimport { sameReference } from \"./account-store.ts\";\nimport { type HcodeEnvironment, resolveHcodeEnvironment } from \"./environment.ts\";\nimport type { HcodeFacade } from \"./facade.ts\";\nimport type { HcodeAccountPort, HcodeAccountRef } from \"./ports.ts\";\nimport { createHcodeProvider } from \"./provider.ts\";\nimport { HcodeLocalRefusal } from \"./transport.ts\";\n\nconst ORIGIN_ENV = \"HUMAIN_CODE_FORGE_ORIGIN\";\nconst TOKEN_ENV = \"HUMAIN_CODE_RUN_TOKEN\";\nconst UNAVAILABLE = \"Forge run inference is unavailable.\";\n\nexport type HcodeRunBootstrap =\n\t| { kind: \"desktop\" }\n\t| { kind: \"invalid\" }\n\t| { kind: \"run\"; environment: HcodeEnvironment; open: () => HcodeRunFacade };\n\nexport type HcodeRunFacade = Omit<HcodeFacade, \"metadata\"> & {\n\treadonly metadata?: undefined;\n\treadonly reference: HcodeAccountRef;\n\t/** True once Forge answered 401: the Build token is expired or revoked. */\n\ttokenRejected(): boolean;\n};\n\n/** Capture once, before parsing args or starting code that can load resources or fork. */\nexport function takeHcodeRunBootstrap(env: NodeJS.ProcessEnv): HcodeRunBootstrap {\n\tconst origin = env[ORIGIN_ENV];\n\tconst token = env[TOKEN_ENV];\n\tlet present = false;\n\tlet ambiguous = false;\n\tfor (const key of Object.keys(env)) {\n\t\tconst name = key.toUpperCase();\n\t\tif (name !== TOKEN_ENV && name !== ORIGIN_ENV) continue;\n\t\tpresent = true;\n\t\tambiguous ||= key !== name;\n\t\tdelete env[key];\n\t}\n\tif (!present) return { kind: \"desktop\" };\n\t// Forge !839 sets exactly these two variables on the fresh agent command. Compare literal origins\n\t// so the bearer cannot be sent to an alias, explicit port, or path supplied by the caller.\n\tconst environment = ([\"dev\", \"staging\", \"production\"] as const)\n\t\t.map((name) => resolveHcodeEnvironment(name))\n\t\t.find((candidate) => candidate.origin === origin);\n\tif (ambiguous || !environment || !token || !/^frt_v1_[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/.test(token))\n\t\treturn { kind: \"invalid\" };\n\tlet bearer: string | undefined = token;\n\treturn {\n\t\tkind: \"run\",\n\t\tenvironment,\n\t\topen() {\n\t\t\tif (bearer === undefined) throw new Error(UNAVAILABLE);\n\t\t\tconst credential = bearer;\n\t\t\tbearer = undefined;\n\t\t\treturn createRunFacade(environment, credential);\n\t\t},\n\t};\n}\n\nfunction createRunFacade(environment: HcodeEnvironment, token: string): HcodeRunFacade {\n\t// Forge checks the sliding idle deadline at admission, not while a response is streaming.\n\tconst lifetime = new AbortController();\n\tconst signal = lifetime.signal;\n\tconst reference: HcodeAccountRef = {\n\t\tenvironmentId: environment.id,\n\t\taccountId: \"forge-run\",\n\t\tgeneration: randomUUID(),\n\t};\n\tlet tokenRejected = false;\n\tconst refuse = async (): Promise<never> => {\n\t\tthrow new Error(UNAVAILABLE);\n\t};\n\tconst account: HcodeAccountPort = {\n\t\t// The selection fence needs a launch identity, not a signed-in account or its authority.\n\t\tstatus: (id) => (!signal.aborted && id === environment.id ? reference : null),\n\t\tlogin: refuse,\n\t\tlogout: refuse,\n\t\tauthorizedFetch: refuse,\n\t\tsubscribe: () => () => {},\n\t};\n\tconst provider = createHcodeProvider(\n\t\t{\n\t\t\t...account,\n\t\t\tasync authorizedFetch(expected, url, init) {\n\t\t\t\tconst method = init.method ?? \"GET\";\n\t\t\t\tif (\n\t\t\t\t\t!sameReference(expected, reference) ||\n\t\t\t\t\t// Forge sets HUMAIN_TERMINAL_OFFLINE to disable ambient discovery, not this scoped route.\n\t\t\t\t\tprocess.env.PI_OFFLINE ||\n\t\t\t\t\t!(\n\t\t\t\t\t\t(method === \"GET\" && url === `${environment.inferenceBaseUrl}/models`) ||\n\t\t\t\t\t\t(method === \"POST\" && url === `${environment.inferenceBaseUrl}/messages`)\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t\t\treturn refuse();\n\t\t\t\tif (tokenRejected) throw new HcodeLocalRefusal(\"buildSessionEnded\");\n\t\t\t\tconst requestSignal = init.signal ? AbortSignal.any([signal, init.signal]) : signal;\n\t\t\t\trequestSignal.throwIfAborted();\n\t\t\t\tconst headers = new Headers(init.headers);\n\t\t\t\theaders.set(\"authorization\", `Bearer ${token}`);\n\t\t\t\tlet response: Response;\n\t\t\t\ttry {\n\t\t\t\t\tresponse = await globalThis.fetch(url, {\n\t\t\t\t\t\tmethod,\n\t\t\t\t\t\tbody: init.body,\n\t\t\t\t\t\theaders,\n\t\t\t\t\t\tsignal: requestSignal,\n\t\t\t\t\t\tredirect: \"error\",\n\t\t\t\t\t\tcredentials: \"omit\",\n\t\t\t\t\t\tcache: \"no-store\",\n\t\t\t\t\t});\n\t\t\t\t} catch {\n\t\t\t\t\treturn refuse();\n\t\t\t\t}\n\t\t\t\tif (response.redirected || (response.status >= 300 && response.status < 400)) {\n\t\t\t\t\tvoid response.body?.cancel().catch(() => {});\n\t\t\t\t\treturn refuse();\n\t\t\t\t}\n\t\t\t\tif (response.status === 401) {\n\t\t\t\t\ttokenRejected = true;\n\t\t\t\t\tvoid response.body?.cancel().catch(() => {});\n\t\t\t\t\tthrow new HcodeLocalRefusal(\"buildSessionEnded\");\n\t\t\t\t}\n\t\t\t\t// The native transport validates refusal details against a closed schema before display.\n\t\t\t\treturn response;\n\t\t\t},\n\t\t},\n\t\tenvironment,\n\t);\n\treturn {\n\t\treference,\n\t\ttokenRejected: () => tokenRejected,\n\t\tprovider,\n\t\tsignal,\n\t\tcontext: { account, usage: { read: refuse }, environment, environmentId: environment.id },\n\t\tobserveVersion() {},\n\t\tasync supportSnapshot() {\n\t\t\treturn { environmentId: environment.id };\n\t\t},\n\t\tasync probeLogin() {\n\t\t\treturn { kind: \"unavailable\" };\n\t\t},\n\t\taccountEmail: () => undefined,\n\t\tadopt: () => false,\n\t\tsignedInElsewhere: () => [],\n\t\tasync recover() {},\n\t\tpersistence: () => undefined,\n\t\tlogin: refuse,\n\t\tlogoutStored: refuse,\n\t\tasync shutdown() {\n\t\t\treturn { remoteRevocation: \"not-needed\" };\n\t\t},\n\t\tdispose() {\n\t\t\tlifetime.abort();\n\t\t\tprovider.dispose();\n\t\t},\n\t};\n}\n"]}
@@ -0,0 +1,6 @@
1
+ import { type Args } from "../../cli/args.ts";
2
+ import type { HcodeRunBootstrap } from "./run-credential.ts";
3
+ export declare function runHcodeSandbox(args: string[], bootstrap: Extract<HcodeRunBootstrap, {
4
+ kind: "run";
5
+ }>, resolveCwd: (parsed: Pick<Args, "cwd">, env: NodeJS.ProcessEnv, cwd: string) => string): Promise<number>;
6
+ //# sourceMappingURL=sandbox.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sandbox.d.ts","sourceRoot":"","sources":["../../../src/humain/hcode/sandbox.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,IAAI,EAAa,MAAM,mBAAmB,CAAC;AAWzD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AA6B7D,wBAAsB,eAAe,CACpC,IAAI,EAAE,MAAM,EAAE,EACd,SAAS,EAAE,OAAO,CAAC,iBAAiB,EAAE;IAAE,IAAI,EAAE,KAAK,CAAA;CAAE,CAAC,EACtD,UAAU,EAAE,CAAC,MAAM,EAAE,IAAI,CAAC,IAAI,EAAE,KAAK,CAAC,EAAE,GAAG,EAAE,MAAM,CAAC,UAAU,EAAE,GAAG,EAAE,MAAM,KAAK,MAAM,GACpF,OAAO,CAAC,MAAM,CAAC,CAiGjB"}