zidane 8.2.1 → 8.2.3

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 (187) hide show
  1. package/dist/acp-cli.js +8 -8
  2. package/dist/{acp-D7Pr8NGt.js → acp-oYRjlh71.js} +6 -6
  3. package/dist/{acp-D7Pr8NGt.js.map → acp-oYRjlh71.js.map} +1 -1
  4. package/dist/acp.d.ts +2 -2
  5. package/dist/acp.js +1 -1
  6. package/dist/{agent-DecDtKA_.js → agent-CBQglXtH.js} +9 -379
  7. package/dist/agent-CBQglXtH.js.map +1 -0
  8. package/dist/agent.d.ts +1 -1
  9. package/dist/agent.js +1 -1
  10. package/dist/{builtin-artifact-kinds-B_OEgf8b.js → builtin-artifact-kinds-BmorPkgz.js} +36 -9
  11. package/dist/builtin-artifact-kinds-BmorPkgz.js.map +1 -0
  12. package/dist/chat/pure.d.ts +4 -4
  13. package/dist/chat/pure.js +6 -6
  14. package/dist/chat.d.ts +4 -4
  15. package/dist/chat.js +15 -15
  16. package/dist/{cli-shared-Dx4vmif6.js → cli-shared-E5m_pI8A.js} +2 -2
  17. package/dist/{cli-shared-Dx4vmif6.js.map → cli-shared-E5m_pI8A.js.map} +1 -1
  18. package/dist/{client-core-imHuBWV3.d.ts → client-core-EEEX_u6D.d.ts} +24 -5
  19. package/dist/{client-core-imHuBWV3.d.ts.map → client-core-EEEX_u6D.d.ts.map} +1 -1
  20. package/dist/{connection-loop-CdHt3iQi.d.ts → connection-loop-CpgfUmuw.d.ts} +3 -3
  21. package/dist/{connection-loop-CdHt3iQi.d.ts.map → connection-loop-CpgfUmuw.d.ts.map} +1 -1
  22. package/dist/contexts/daytona.d.ts +1 -1
  23. package/dist/contexts/e2b.d.ts +1 -1
  24. package/dist/{credentials-Dti61yoi.js → credentials-B9DfBJP9.js} +11 -7
  25. package/dist/credentials-B9DfBJP9.js.map +1 -0
  26. package/dist/daemon-cli.js +2 -2
  27. package/dist/{dispatcher-vy3J6JMA.js → dispatcher-Bv9-c6I2.js} +28 -14
  28. package/dist/dispatcher-Bv9-c6I2.js.map +1 -0
  29. package/dist/{engine-BN6PjWAW.js → engine-XmoPPB6U.js} +5 -5
  30. package/dist/{engine-BN6PjWAW.js.map → engine-XmoPPB6U.js.map} +1 -1
  31. package/dist/{eval-BaJtxLCW.js → eval-CfQlBR81.js} +2 -2
  32. package/dist/{eval-BaJtxLCW.js.map → eval-CfQlBR81.js.map} +1 -1
  33. package/dist/eval.d.ts +1 -1
  34. package/dist/eval.js +1 -1
  35. package/dist/{executor-CT4oUkg6.js → executor-BhthPE1q.js} +3 -3
  36. package/dist/{executor-CT4oUkg6.js.map → executor-BhthPE1q.js.map} +1 -1
  37. package/dist/{extensions-BKt7lxxv.js → extensions-BgBwogRW.js} +114 -113
  38. package/dist/extensions-BgBwogRW.js.map +1 -0
  39. package/dist/extensions.d.ts +1 -1
  40. package/dist/extensions.js +2 -2
  41. package/dist/{fold-rules-BYedvsH7.d.ts → fold-rules-DSypi36k.d.ts} +2 -2
  42. package/dist/{fold-rules-BYedvsH7.d.ts.map → fold-rules-DSypi36k.d.ts.map} +1 -1
  43. package/dist/google-O6pRnddf.js +881 -0
  44. package/dist/google-O6pRnddf.js.map +1 -0
  45. package/dist/{headless-Ebd1ZEzC.js → headless-R4pbpTkm.js} +3 -3
  46. package/dist/{headless-Ebd1ZEzC.js.map → headless-R4pbpTkm.js.map} +1 -1
  47. package/dist/headless.d.ts +1 -1
  48. package/dist/headless.js +1 -1
  49. package/dist/{host-scoped-settings-Cy_zbmB_.js → host-scoped-settings-C-Nmb6vr.js} +2 -2
  50. package/dist/{host-scoped-settings-Cy_zbmB_.js.map → host-scoped-settings-C-Nmb6vr.js.map} +1 -1
  51. package/dist/{host-signals-Cx2IAbHh.js → host-signals-BFudPyCT.js} +5 -5
  52. package/dist/{host-signals-Cx2IAbHh.js.map → host-signals-BFudPyCT.js.map} +1 -1
  53. package/dist/{index-pc71ADi6.d.ts → index-AqRZ3gEz.d.ts} +71 -4
  54. package/dist/index-AqRZ3gEz.d.ts.map +1 -0
  55. package/dist/{index-Bt_G2Z_2.d.ts → index-CDS7YdUC.d.ts} +5 -5
  56. package/dist/{index-Bt_G2Z_2.d.ts.map → index-CDS7YdUC.d.ts.map} +1 -1
  57. package/dist/{index-CidMTcxS.d.ts → index-DyQyDLX1.d.ts} +167 -10
  58. package/dist/index-DyQyDLX1.d.ts.map +1 -0
  59. package/dist/index.d.ts +3 -3
  60. package/dist/index.js +15 -15
  61. package/dist/ipc/remote.d.ts +5 -5
  62. package/dist/ipc/remote.js +3 -3
  63. package/dist/ipc.d.ts +5 -5
  64. package/dist/ipc.js +7 -7
  65. package/dist/{links-DSZ4uQ5w.js → links-rFaWqS2Y.js} +10 -10
  66. package/dist/{links-DSZ4uQ5w.js.map → links-rFaWqS2Y.js.map} +1 -1
  67. package/dist/{mcp-allowlist-BQ5MvhHi.js → mcp-allowlist-CLXweyxk.js} +14 -3
  68. package/dist/mcp-allowlist-CLXweyxk.js.map +1 -0
  69. package/dist/mcp.d.ts +1 -1
  70. package/dist/{oauth-BSqXgads.js → oauth-7_48zR7n.js} +226 -40
  71. package/dist/oauth-7_48zR7n.js.map +1 -0
  72. package/dist/{openai-dTmPxM6T.js → openai-Rh6u5NXF.js} +121 -2
  73. package/dist/openai-Rh6u5NXF.js.map +1 -0
  74. package/dist/{openrouter-CtZbQDa0.js → openrouter-Dg0yaI-o.js} +91 -2
  75. package/dist/openrouter-Dg0yaI-o.js.map +1 -0
  76. package/dist/output/stream-json.d.ts +1 -1
  77. package/dist/output/terminal.d.ts +1 -1
  78. package/dist/plugins.d.ts +1 -1
  79. package/dist/{presets-EzlHyFSi.js → presets-DXeHsd24.js} +3 -3
  80. package/dist/{presets-EzlHyFSi.js.map → presets-DXeHsd24.js.map} +1 -1
  81. package/dist/presets.d.ts +1 -1
  82. package/dist/presets.js +1 -1
  83. package/dist/{prompts-D2lPHLOV.d.ts → prompts-DmY13jvF.d.ts} +2 -1
  84. package/dist/prompts-DmY13jvF.d.ts.map +1 -0
  85. package/dist/protocol-BIv1Yuvl.js.map +1 -1
  86. package/dist/providers/anthropic.d.ts +1 -1
  87. package/dist/providers/arcee.d.ts +1 -1
  88. package/dist/providers/baseten.d.ts +1 -1
  89. package/dist/providers/cerebras.d.ts +1 -1
  90. package/dist/providers/google.d.ts +1 -1
  91. package/dist/providers/google.js +1 -784
  92. package/dist/providers/local.d.ts +1 -1
  93. package/dist/providers/neuralwatt.d.ts +1 -1
  94. package/dist/providers/openai-compat.d.ts +1 -1
  95. package/dist/providers/openai.d.ts +1 -1
  96. package/dist/providers/openai.js +1 -1
  97. package/dist/providers/openrouter.d.ts +1 -1
  98. package/dist/providers/openrouter.js +1 -1
  99. package/dist/providers/xai.d.ts +1 -1
  100. package/dist/providers/xai.js +1 -101
  101. package/dist/providers.d.ts +2 -2
  102. package/dist/providers.js +6 -5
  103. package/dist/{registry-BBaEgTsX.js → registry-eourRLY2.js} +3 -3
  104. package/dist/{registry-BBaEgTsX.js.map → registry-eourRLY2.js.map} +1 -1
  105. package/dist/{remote-hosts-bO7wOt44.js → remote-hosts-DY2J07ut.js} +4 -4
  106. package/dist/{remote-hosts-bO7wOt44.js.map → remote-hosts-DY2J07ut.js.map} +1 -1
  107. package/dist/restate.d.ts +1 -1
  108. package/dist/{secret-shapes-Cda65uDH.js → secret-shapes-BjW4l6U0.js} +17 -3
  109. package/dist/secret-shapes-BjW4l6U0.js.map +1 -0
  110. package/dist/session/sqlite.d.ts +1 -1
  111. package/dist/{session-factory-BazyVdzj.js → session-factory-CMwIXE-7.js} +5 -5
  112. package/dist/{session-factory-BazyVdzj.js.map → session-factory-CMwIXE-7.js.map} +1 -1
  113. package/dist/session.d.ts +1 -1
  114. package/dist/{settings-keys-zYaer8DY.js → settings-keys-CPdmkTz7.js} +3 -3
  115. package/dist/{settings-keys-zYaer8DY.js.map → settings-keys-CPdmkTz7.js.map} +1 -1
  116. package/dist/{shell-path-od9XHRPt.js → shell-path-B8b3EOtK.js} +3 -3
  117. package/dist/{shell-path-od9XHRPt.js.map → shell-path-B8b3EOtK.js.map} +1 -1
  118. package/dist/{skills-use-D68a1gyZ.js → skills-use-CssTEaIj.js} +375 -2
  119. package/dist/skills-use-CssTEaIj.js.map +1 -0
  120. package/dist/skills.d.ts +1 -1
  121. package/dist/store-L01W0gGI.js.map +1 -1
  122. package/dist/{system-freeze-DXvJpveP.js → system-freeze-Um9ZJiPo.js} +24 -9
  123. package/dist/system-freeze-Um9ZJiPo.js.map +1 -0
  124. package/dist/{todo-edits-CmqNFvLJ.js → todo-edits-BERpCRPj.js} +3 -3
  125. package/dist/{todo-edits-CmqNFvLJ.js.map → todo-edits-BERpCRPj.js.map} +1 -1
  126. package/dist/tools/fetch-url.d.ts +1 -1
  127. package/dist/tools/prompts.d.ts +1 -1
  128. package/dist/tools/prompts.js +7 -0
  129. package/dist/tools/prompts.js.map +1 -1
  130. package/dist/tools/web-search.d.ts +1 -1
  131. package/dist/{tools-9Dpm8F-f.js → tools-pZVFIJ_K.js} +273 -2
  132. package/dist/tools-pZVFIJ_K.js.map +1 -0
  133. package/dist/tools.d.ts +3 -3
  134. package/dist/tools.js +4 -4
  135. package/dist/{transcript-anchors-B3TFJqr_.js → transcript-anchors-jHrg-r-H.js} +10 -10
  136. package/dist/{transcript-anchors-B3TFJqr_.js.map → transcript-anchors-jHrg-r-H.js.map} +1 -1
  137. package/dist/{transcript-reconcile-BC2DbTmp.js → transcript-reconcile-CPdrNbbR.js} +19 -2
  138. package/dist/{transcript-reconcile-BC2DbTmp.js.map → transcript-reconcile-CPdrNbbR.js.map} +1 -1
  139. package/dist/tui.d.ts +7 -7
  140. package/dist/tui.js +25 -23
  141. package/dist/tui.js.map +1 -1
  142. package/dist/{turn-operations-CIFoOebZ.d.ts → turn-operations-DuGtKuc_.d.ts} +10 -3
  143. package/dist/turn-operations-DuGtKuc_.d.ts.map +1 -0
  144. package/dist/{types-iFLlZKd0.d.ts → types-C0PJmBaO.d.ts} +2 -2
  145. package/dist/{types-iFLlZKd0.d.ts.map → types-C0PJmBaO.d.ts.map} +1 -1
  146. package/dist/types-JzccL5GE.js +24 -0
  147. package/dist/types-JzccL5GE.js.map +1 -0
  148. package/dist/types.d.ts +2 -2
  149. package/dist/{url-BTH-HE9Y.js → url-D8KZ7Edw.js} +2 -2
  150. package/dist/{url-BTH-HE9Y.js.map → url-D8KZ7Edw.js.map} +1 -1
  151. package/dist/{version-4T82xRxQ.js → version-bd3DQJkc.js} +2 -2
  152. package/dist/{version-4T82xRxQ.js.map → version-bd3DQJkc.js.map} +1 -1
  153. package/dist/wire-DH77Z-rr.js +80 -0
  154. package/dist/wire-DH77Z-rr.js.map +1 -0
  155. package/dist/{workspace-exec-stream-By8na6vz.js → workspace-exec-stream-CyfYgqAh.js} +4 -4
  156. package/dist/{workspace-exec-stream-By8na6vz.js.map → workspace-exec-stream-CyfYgqAh.js.map} +1 -1
  157. package/dist/{write-file-B4vi3SvQ.js → write-file-QYrcDdl3.js} +3 -3
  158. package/dist/{write-file-B4vi3SvQ.js.map → write-file-QYrcDdl3.js.map} +1 -1
  159. package/dist/{ws-CS312Jpx.js → ws-CURQ2igk.js} +5 -5
  160. package/dist/{ws-CS312Jpx.js.map → ws-CURQ2igk.js.map} +1 -1
  161. package/dist/{ws-client-wWka-Jku.js → ws-client-BVljYbdb.js} +3 -3
  162. package/dist/{ws-client-wWka-Jku.js.map → ws-client-BVljYbdb.js.map} +1 -1
  163. package/dist/xai-CStTwCV2.js +182 -0
  164. package/dist/xai-CStTwCV2.js.map +1 -0
  165. package/docs/ARCHITECTURE.md +1 -0
  166. package/docs/ARTIFACTS.md +1 -1
  167. package/docs/EXTENSIONS.md +9 -5
  168. package/package.json +2 -2
  169. package/dist/agent-DecDtKA_.js.map +0 -1
  170. package/dist/builtin-artifact-kinds-B_OEgf8b.js.map +0 -1
  171. package/dist/credentials-Dti61yoi.js.map +0 -1
  172. package/dist/dispatcher-vy3J6JMA.js.map +0 -1
  173. package/dist/extensions-BKt7lxxv.js.map +0 -1
  174. package/dist/index-CidMTcxS.d.ts.map +0 -1
  175. package/dist/index-pc71ADi6.d.ts.map +0 -1
  176. package/dist/mcp-allowlist-BQ5MvhHi.js.map +0 -1
  177. package/dist/oauth-BSqXgads.js.map +0 -1
  178. package/dist/openai-dTmPxM6T.js.map +0 -1
  179. package/dist/openrouter-CtZbQDa0.js.map +0 -1
  180. package/dist/prompts-D2lPHLOV.d.ts.map +0 -1
  181. package/dist/providers/google.js.map +0 -1
  182. package/dist/providers/xai.js.map +0 -1
  183. package/dist/secret-shapes-Cda65uDH.js.map +0 -1
  184. package/dist/skills-use-D68a1gyZ.js.map +0 -1
  185. package/dist/system-freeze-DXvJpveP.js.map +0 -1
  186. package/dist/tools-9Dpm8F-f.js.map +0 -1
  187. package/dist/turn-operations-CIFoOebZ.d.ts.map +0 -1
@@ -1,11 +1,11 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-BhDjJH2R.js";
2
2
  import { t as HostIdentityError } from "./connection-BaHd3T-D.js";
3
- import { i as IpcVersionMismatchError } from "./settings-keys-zYaer8DY.js";
3
+ import { i as IpcVersionMismatchError } from "./settings-keys-CPdmkTz7.js";
4
4
  import { u as hostRefOf } from "./protocol-BIv1Yuvl.js";
5
5
  import { t as keepHostConnected } from "./connection-loop-DSCehV3W.js";
6
- import { n as displayHostUrl } from "./url-BTH-HE9Y.js";
7
- import { i as probeUnsavedHost, t as createHostRegistry } from "./registry-BBaEgTsX.js";
8
- import { a as hostCaBundle, r as connectWsClient, t as HostAuthError } from "./ws-client-wWka-Jku.js";
6
+ import { n as displayHostUrl } from "./url-D8KZ7Edw.js";
7
+ import { i as probeUnsavedHost, t as createHostRegistry } from "./registry-eourRLY2.js";
8
+ import { a as hostCaBundle, r as connectWsClient, t as HostAuthError } from "./ws-client-BVljYbdb.js";
9
9
  //#region src/ipc/hosts/probe.ts
10
10
  /** Bound on one probe: the upgrade, the handshake and `daemon.info`. */
11
11
  const HOST_PROBE_TIMEOUT_MS = 1e4;
@@ -281,4 +281,4 @@ function startWsSavedHosts(options) {
281
281
  //#endregion
282
282
  export { MissingHostTokenError as a, createWsHostRegistry as c, ws_exports as i, probeWsHost as l, probeUnsavedWsHost as n, startSavedHosts as o, startWsSavedHosts as r, HOST_PROBE_TIMEOUT_MS as s, classifyWsFailure as t };
283
283
 
284
- //# sourceMappingURL=ws-CS312Jpx.js.map
284
+ //# sourceMappingURL=ws-CURQ2igk.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"ws-CS312Jpx.js","names":[],"sources":["../src/ipc/hosts/probe.ts","../src/ipc/hosts/saved-hosts.ts","../src/ipc/hosts/ws.ts"],"sourcesContent":["/**\n * The host registry's connection (`src/chat/hosts`): a WebSocket probe that\n * says who answers at a URL with a token, and the registry wired to it.\n */\nimport type { HostErrorCode, HostProbeResult, HostRegistry } from '../../chat/hosts'\nimport { createHostRegistry, displayHostUrl } from '../../chat/hosts'\nimport { hostRefOf } from '../protocol'\nimport { IpcVersionMismatchError } from '../transports/client-core'\nimport { hostCaBundle } from '../transports/tls-trust'\nimport { connectWsClient, HostAuthError } from '../transports/ws-client'\n\n/** Bound on one probe: the upgrade, the handshake and `daemon.info`. */\nexport const HOST_PROBE_TIMEOUT_MS = 10_000\n\nconst TLS_FAILURE = /certificate|self[- ]signed|\\btls\\b|\\bssl\\b|UNABLE_TO_VERIFY|CERT_|ERR_TLS/i\n\nfunction classify(err: unknown): { error: HostErrorCode, message: string } {\n if (err instanceof HostAuthError) {\n return err.status === 401\n ? { error: 'auth', message: 'The host refused the token (401). Create a new one on the server: zidane server token create --name <device>.' }\n : { error: 'auth', message: err.message }\n }\n if (err instanceof IpcVersionMismatchError)\n return { error: 'protocol', message: err.message }\n const message = err instanceof Error ? err.message : String(err)\n if (TLS_FAILURE.test(message))\n return { error: 'tls', message: `TLS failed: ${message}` }\n return { error: 'unreachable', message }\n}\n\n/**\n * A failed WebSocket says nothing about why. For `wss://`, ask the same\n * address over HTTPS: a certificate or handshake failure there is a TLS\n * problem, anything else stays \"unreachable\".\n */\nasync function tlsFailure(url: string, signal: AbortSignal): Promise<string | null> {\n if (!url.startsWith('wss:'))\n return null\n try {\n // No token, and no redirect followed: only the TLS handshake with this origin matters.\n // The same CAs as the socket (Bun takes them per request; Node uses its process default).\n const ca = typeof (globalThis as { Bun?: unknown }).Bun !== 'undefined' ? hostCaBundle() : null\n const response = await fetch(`https:${url.slice('wss:'.length)}`, { redirect: 'manual', signal: AbortSignal.any([signal, AbortSignal.timeout(5000)]), ...(ca ? { tls: { ca } } : {}) } as RequestInit)\n void response.body?.cancel().catch(() => {})\n return null\n }\n catch (err) {\n const e = err as { code?: unknown, message?: unknown }\n const detail = `${typeof e.code === 'string' ? e.code : ''} ${typeof e.message === 'string' ? e.message : ''}`\n return TLS_FAILURE.test(detail) ? `TLS failed: ${String(e.message ?? e.code)}` : null\n }\n}\n\n/**\n * Connect, read the host's identity and `daemon.info`, disconnect. Never throws.\n * @param target - URL, token and an optional timeout in milliseconds. The timeout defaults to {@link HOST_PROBE_TIMEOUT_MS}.\n * @returns Who answered and how fast, or a classified failure.\n */\nexport async function probeWsHost(target: { url: string, token: string, timeoutMs?: number }): Promise<HostProbeResult> {\n const started = performance.now()\n const signal = AbortSignal.timeout(target.timeoutMs ?? HOST_PROBE_TIMEOUT_MS)\n let client: Awaited<ReturnType<typeof connectWsClient>> | undefined\n try {\n client = await connectWsClient({ url: target.url, token: target.token, heartbeatMs: 0, signal })\n const hostRef = hostRefOf(client.hello)\n if (!hostRef)\n return { ok: false, error: 'protocol', message: `${displayHostUrl(target.url)} runs a zidane too old to say which host it is. Upgrade the server.` }\n const info = await client.request('daemon.info', {})\n const serverVersion = info.codeVersion ?? info.appVersion\n return { ok: true, hostRef, ...(serverVersion ? { serverVersion } : {}), latencyMs: Math.round(performance.now() - started) }\n }\n catch (err) {\n if (signal.aborted && !(err instanceof HostAuthError))\n return { ok: false, error: 'unreachable', message: `No answer from ${displayHostUrl(target.url)} within ${target.timeoutMs ?? HOST_PROBE_TIMEOUT_MS} ms.` }\n const classified = classify(err)\n if (classified.error === 'unreachable') {\n const tls = await tlsFailure(target.url, signal).catch(() => null)\n if (tls)\n return { ok: false, error: 'tls', message: tls }\n }\n return { ok: false, ...classified }\n }\n finally {\n client?.close()\n }\n}\n\n/**\n * The registry in `dataDir`, connecting over WebSocket.\n * @param options - Where the registry keeps its data.\n * @returns The host registry.\n */\nexport function createWsHostRegistry(options: { dataDir: string }): HostRegistry {\n return createHostRegistry({ dataDir: options.dataDir, probe: probeWsHost })\n}\n","/**\n * A client's saved servers, kept in its host directory: one directory entry\n * and one app-lifetime connection (`connection-loop`) per server in the\n * registry, in step with it. Shared by the TUI and the GUI main process,\n * which each supply their directory (`SavedHostsDirectory`) and how to dial.\n *\n * Saving a server that is already saved (same host id: a new token, a new\n * URL) reconfigures its entry IN PLACE and reconnects: the entry is never\n * removed, so the sessions routed to it stay routed. Only a server leaving\n * the registry (removed here or by another window) or `stop()` removes an\n * entry, and the directory decides what that means for an open session.\n *\n * Every connection is checked against the saved entry's id (the server's\n * `hostId` when it was added): another host answering at the URL is closed\n * at once, reported as `identity` and not retried, so nothing it says is\n * recorded under the saved id. Dialers may check first (`expectHostId`).\n *\n * No WebSocket import: the WebSocket wiring is `./ws.ts`.\n */\nimport type { HostEntry, HostProbeResult, HostRegistry, HostTestResult } from '../../chat/hosts'\nimport type { HostSignal } from '../protocol'\nimport type { IpcClient } from '../transports/client-core'\nimport type { HostConnectionLoop, HostConnectionPatch, HostFailureKind } from './connection-loop'\nimport { displayHostUrl, HostIdentityError } from '../../chat/hosts'\nimport { hostRefOf } from '../protocol'\nimport { keepHostConnected } from './connection-loop'\n\n/** The client's host directory, as the saved servers see it. Keys are host ids. */\nexport interface SavedHostsDirectory {\n /** The saved servers it holds now, with their URL (a `--host` server excluded). */\n saved: () => { key: string, url: string }[]\n /** Add the entry, or reconfigure the one under its key in place (status `connecting`). */\n upsert: (entry: HostEntry, token: string | undefined) => void\n /** Applies a connection patch, a new name or a server version to the entry. */\n update: (key: string, patch: HostConnectionPatch & { name?: string, serverVersion?: string }) => void\n /** The server left the registry, or the saved servers stopped. */\n remove: (key: string) => void\n}\n\n/** No token is saved for this server (removed by hand, or another window removed it). */\nexport class MissingHostTokenError extends Error {\n constructor() {\n super('No token saved for this server: add it again.')\n this.name = 'MissingHostTokenError'\n }\n}\n\n/** Options for {@link startSavedHosts}: the registry, the host directory, the connect function and callbacks. */\nexport interface SavedHostsOptions {\n /** The registry of saved servers. */\n registry: HostRegistry\n /** The client's host directory the entries are kept in. */\n directory: SavedHostsDirectory\n /** One connect attempt to a saved server, with its token read fresh. */\n connect: (entry: HostEntry, token: string, options: { signal: AbortSignal, onClose: () => void }) => Promise<IpcClient>\n /** `auth`: refused for good. A missing token is always `auth`, another host answering always `identity`. */\n classify?: (err: unknown) => HostFailureKind\n /** The add form's test of an unsaved URL + token (`probeUnsavedHost`). */\n probeUnsaved?: (target: { url: string, token: string }) => Promise<HostProbeResult>\n /** Saved entries the directory already reaches another way (the TUI's `--host` server). */\n skip?: (entry: HostEntry) => boolean\n /** Called with every signal of a connected saved server. */\n onSignal?: (key: string, signal: HostSignal) => void\n /** Called when a saved server connects, also after a reconnect. */\n onConnected?: (key: string, client: IpcClient) => void\n /** Called when a saved server's connection drops. */\n onDisconnected?: (key: string) => void\n /**\n * Lower backoff bound in milliseconds.\n * @default 1000\n */\n minDelayMs?: number\n /**\n * Upper backoff bound in milliseconds.\n * @default 30000\n */\n maxDelayMs?: number\n}\n\n/** Handle returned by {@link startSavedHosts} to list, add, remove, rename, test and retry saved servers. */\nexport interface SavedHostsController {\n /** The saved hosts, read fresh (other windows share the file). */\n list: () => HostEntry[]\n /** Verify, save, connect (in place when already saved). Throws a `HostRegistryError`. */\n add: (input: { url: string, token: string, name?: string }) => Promise<HostEntry>\n /** Removes a server from the registry and its entry from the directory. Returns whether it existed. */\n remove: (id: string) => boolean\n /** Renames a saved server and returns the updated entry. */\n rename: (id: string, name: string) => HostEntry\n /** A saved server (by id), or an unsaved URL + token (the add form's test). */\n test: (target: string | { id: string } | { url: string, token: string }) => Promise<HostTestResult>\n /** Reconnect now (after an outage or a token fix). */\n retry: (id: string) => void\n /** Reconnect every saved server that is not connected now, its backoff reset (the computer woke up). */\n retryAll: () => void\n /** Disconnects every saved server and removes their directory entries. The registry is not changed. */\n stop: () => void\n}\n\n/**\n * Starts the connections of a client's saved servers and keeps the directory in step with the registry.\n * Each saved server gets a directory entry and a connection loop. A connection whose host id differs from the saved one is closed and reported as `identity`.\n * @param options - Registry, directory and how to dial.\n * @returns A controller over the saved servers.\n */\nexport function startSavedHosts(options: SavedHostsOptions): SavedHostsController {\n const { registry, directory, skip = () => false } = options\n const classify = (err: unknown): HostFailureKind => err instanceof MissingHostTokenError ? 'auth' : err instanceof HostIdentityError ? 'identity' : (options.classify?.(err) ?? 'retry')\n\n /** The saved server, or nobody: a connection from another host is closed before anyone sees it. */\n const dial = async (entry: HostEntry, token: string, attempt: { signal: AbortSignal, onClose: () => void }): Promise<IpcClient> => {\n const client = await options.connect(entry, token, attempt)\n const ref = hostRefOf(client.hello)\n if (ref?.id === entry.id)\n return client\n client.close()\n throw new HostIdentityError(displayHostUrl(entry.url), ref?.name)\n }\n const loops = new Map<string, HostConnectionLoop>()\n\n const disconnect = (key: string): void => {\n loops.get(key)?.stop()\n loops.delete(key)\n }\n\n /** (Re)connect `entry` with the token saved now, its directory entry kept or created in place. */\n const connect = (entry: HostEntry): void => {\n const key = entry.id\n disconnect(key)\n directory.upsert(entry, registry.token(key))\n loops.set(key, keepHostConnected({\n connect: (attempt) => {\n const token = registry.token(key)\n return token ? dial(entry, token, attempt) : Promise.reject(new MissingHostTokenError())\n },\n update: patch => directory.update(key, patch),\n classify,\n ...(options.onSignal ? { onSignal: (signal: HostSignal) => options.onSignal!(key, signal) } : {}),\n ...(options.onConnected ? { onConnected: (client: IpcClient) => options.onConnected!(key, client) } : {}),\n ...(options.onDisconnected ? { onDisconnected: () => options.onDisconnected!(key) } : {}),\n ...(options.minDelayMs !== undefined ? { minDelayMs: options.minDelayMs } : {}),\n ...(options.maxDelayMs !== undefined ? { maxDelayMs: options.maxDelayMs } : {}),\n }))\n }\n\n /** Bring the directory in line with the saved hosts. */\n const sync = (): void => {\n const entries = registry.list().filter(entry => !skip(entry))\n const saved = new Set(entries.map(entry => entry.id))\n const known = new Map(directory.saved().map(host => [host.key, host.url]))\n for (const key of known.keys()) {\n if (!saved.has(key)) {\n disconnect(key)\n directory.remove(key)\n }\n }\n for (const entry of entries) {\n if (known.get(entry.id) !== entry.url)\n connect(entry)\n else\n directory.update(entry.id, { name: entry.name, ...(entry.serverVersion ? { serverVersion: entry.serverVersion } : {}) })\n }\n }\n\n sync()\n return {\n list: () => registry.list(),\n add: async (input) => {\n const entry = await registry.add(input)\n // Saved again (a new token or URL): reconnect with them, the entry kept.\n if (!skip(entry))\n connect(entry)\n sync()\n return entry\n },\n remove: (id) => {\n const removed = registry.remove(id)\n sync()\n return removed\n },\n rename: (id, name) => {\n const entry = registry.rename(id, name)\n sync()\n return entry\n },\n test: async (target) => {\n if (typeof target === 'object' && !('id' in target)) {\n if (!options.probeUnsaved)\n throw new Error('Testing an unsaved host is not available here.')\n return options.probeUnsaved(target)\n }\n const id = typeof target === 'string' ? target : target.id\n const result = await registry.test(id)\n if (result.ok) {\n directory.update(id, { serverName: result.hostRef.name, ...(result.serverVersion ? { serverVersion: result.serverVersion } : {}) })\n loops.get(id)?.retry()\n }\n return result\n },\n retry: id => loops.get(id)?.retry(),\n retryAll: () => {\n for (const loop of loops.values())\n loop.retry()\n },\n stop: () => {\n for (const key of [...loops.keys()]) {\n disconnect(key)\n directory.remove(key)\n }\n },\n }\n}\n","/**\n * Saved servers over WebSocket: the registry in `dataDir`, the add form's\n * unsaved test, the refusal classification and (by default) the dial, wired\n * for `startSavedHosts`. Loaded behind each client's remote-hosts gate.\n */\nimport type { HostProbeResult } from '../../chat/hosts'\nimport type { HostFailureKind } from './connection-loop'\nimport type { SavedHostsController, SavedHostsOptions } from './saved-hosts'\nimport { HostIdentityError, probeUnsavedHost } from '../../chat/hosts'\nimport { IpcVersionMismatchError } from '../transports/client-core'\nimport { connectWsClient, HostAuthError } from '../transports/ws-client'\nimport { createWsHostRegistry, probeWsHost } from './probe'\nimport { startSavedHosts } from './saved-hosts'\n\n/**\n * A refused token stays refused until the user changes something: no retry\n * loop. Another protocol version stays until one side is upgraded: a slow re-check.\n * @param err - The error a connect attempt failed with.\n * @returns `auth` for a refused token, `identity` for another host answering, `protocol` for a version mismatch, `retry` otherwise.\n */\nexport function classifyWsFailure(err: unknown): HostFailureKind {\n if (err instanceof HostAuthError)\n return 'auth'\n if (err instanceof HostIdentityError)\n return 'identity'\n return err instanceof IpcVersionMismatchError ? 'protocol' : 'retry'\n}\n\n/**\n * The add form's \"test\": the registry's own checks and probe over WebSocket, saving nothing.\n * @param target - URL and token to try.\n * @returns The probe result.\n */\nexport function probeUnsavedWsHost(target: { url: string, token: string }): Promise<HostProbeResult> {\n return probeUnsavedHost(probeWsHost, target)\n}\n\n/**\n * Options for {@link startWsSavedHosts}: {@link SavedHostsOptions} with the registry, dialer and classifier filled in.\n * `dataDir` holds the saved-hosts registry file.\n */\nexport type WsSavedHostsOptions = Omit<SavedHostsOptions, 'registry' | 'connect' | 'classify' | 'probeUnsaved'> & {\n dataDir: string\n /** Client version in the server's diagnostics (default dial only). */\n appVersion?: string\n /** Dial another way (the TUI goes through its directory entry's transport). Default: `connectWsClient`. */\n connect?: SavedHostsOptions['connect']\n registry?: SavedHostsOptions['registry']\n}\n\n/**\n * Keeps the saved servers of a client connected over WebSocket.\n * Uses the registry in `dataDir` unless `registry` is given, and dials with {@link connectWsClient} unless `connect` is given.\n * @param options - Data directory, host directory and callbacks.\n * @returns A controller to list, add, remove, test and retry hosts, and to stop them all.\n */\nexport function startWsSavedHosts(options: WsSavedHostsOptions): SavedHostsController {\n const { dataDir, appVersion, connect, registry, ...rest } = options\n return startSavedHosts({\n ...rest,\n registry: registry ?? createWsHostRegistry({ dataDir }),\n classify: classifyWsFailure,\n probeUnsaved: probeUnsavedWsHost,\n connect: connect ?? ((entry, token, attempt) => connectWsClient({\n url: entry.url,\n token,\n expectHostId: entry.id,\n ...(appVersion ? { appVersion } : {}),\n signal: attempt.signal,\n onClose: attempt.onClose,\n })),\n })\n}\n"],"mappings":";;;;;;;;;;AAYA,MAAa,wBAAwB;AAErC,MAAM,cAAc;AAEpB,SAAS,SAAS,KAAyD;CACzE,IAAI,eAAe,eACjB,OAAO,IAAI,WAAW,MAClB;EAAE,OAAO;EAAQ,SAAS;CAAgH,IAC1I;EAAE,OAAO;EAAQ,SAAS,IAAI;CAAQ;CAE5C,IAAI,eAAe,yBACjB,OAAO;EAAE,OAAO;EAAY,SAAS,IAAI;CAAQ;CACnD,MAAM,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;CAC/D,IAAI,YAAY,KAAK,OAAO,GAC1B,OAAO;EAAE,OAAO;EAAO,SAAS,eAAe;CAAU;CAC3D,OAAO;EAAE,OAAO;EAAe;CAAQ;AACzC;;;;;;AAOA,eAAe,WAAW,KAAa,QAA6C;CAClF,IAAI,CAAC,IAAI,WAAW,MAAM,GACxB,OAAO;CACT,IAAI;EAGF,MAAM,KAAK,OAAQ,WAAiC,QAAQ,cAAc,aAAa,IAAI;EAE3F,CAAK,MADkB,MAAM,SAAS,IAAI,MAAM,CAAa,KAAK;GAAE,UAAU;GAAU,QAAQ,YAAY,IAAI,CAAC,QAAQ,YAAY,QAAQ,GAAI,CAAC,CAAC;GAAG,GAAI,KAAK,EAAE,KAAK,EAAE,GAAG,EAAE,IAAI,CAAC;EAAG,CAAgB,EAAA,CACvL,MAAM,OAAO,CAAC,CAAC,YAAY,CAAC,CAAC;EAC3C,OAAO;CACT,SACO,KAAK;EACV,MAAM,IAAI;EACV,MAAM,SAAS,GAAG,OAAO,EAAE,SAAS,WAAW,EAAE,OAAO,GAAG,GAAG,OAA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AAM;GACpB,GAAI,aAAa,EAAE,WAAW,IAAI,CAAC;GACnC,QAAQ,QAAQ;GAChB,SAAS,QAAQ;EACnB,CAAC;CACH,CAAC;AACH"}
1
+ {"version":3,"file":"ws-CURQ2igk.js","names":[],"sources":["../src/ipc/hosts/probe.ts","../src/ipc/hosts/saved-hosts.ts","../src/ipc/hosts/ws.ts"],"sourcesContent":["/**\n * The host registry's connection (`src/chat/hosts`): a WebSocket probe that\n * says who answers at a URL with a token, and the registry wired to it.\n */\nimport type { HostErrorCode, HostProbeResult, HostRegistry } from '../../chat/hosts'\nimport { createHostRegistry, displayHostUrl } from '../../chat/hosts'\nimport { hostRefOf } from '../protocol'\nimport { IpcVersionMismatchError } from '../transports/client-core'\nimport { hostCaBundle } from '../transports/tls-trust'\nimport { connectWsClient, HostAuthError } from '../transports/ws-client'\n\n/** Bound on one probe: the upgrade, the handshake and `daemon.info`. */\nexport const HOST_PROBE_TIMEOUT_MS = 10_000\n\nconst TLS_FAILURE = /certificate|self[- ]signed|\\btls\\b|\\bssl\\b|UNABLE_TO_VERIFY|CERT_|ERR_TLS/i\n\nfunction classify(err: unknown): { error: HostErrorCode, message: string } {\n if (err instanceof HostAuthError) {\n return err.status === 401\n ? { error: 'auth', message: 'The host refused the token (401). Create a new one on the server: zidane server token create --name <device>.' }\n : { error: 'auth', message: err.message }\n }\n if (err instanceof IpcVersionMismatchError)\n return { error: 'protocol', message: err.message }\n const message = err instanceof Error ? err.message : String(err)\n if (TLS_FAILURE.test(message))\n return { error: 'tls', message: `TLS failed: ${message}` }\n return { error: 'unreachable', message }\n}\n\n/**\n * A failed WebSocket says nothing about why. For `wss://`, ask the same\n * address over HTTPS: a certificate or handshake failure there is a TLS\n * problem, anything else stays \"unreachable\".\n */\nasync function tlsFailure(url: string, signal: AbortSignal): Promise<string | null> {\n if (!url.startsWith('wss:'))\n return null\n try {\n // No token, and no redirect followed: only the TLS handshake with this origin matters.\n // The same CAs as the socket (Bun takes them per request; Node uses its process default).\n const ca = typeof (globalThis as { Bun?: unknown }).Bun !== 'undefined' ? hostCaBundle() : null\n const response = await fetch(`https:${url.slice('wss:'.length)}`, { redirect: 'manual', signal: AbortSignal.any([signal, AbortSignal.timeout(5000)]), ...(ca ? { tls: { ca } } : {}) } as RequestInit)\n void response.body?.cancel().catch(() => {})\n return null\n }\n catch (err) {\n const e = err as { code?: unknown, message?: unknown }\n const detail = `${typeof e.code === 'string' ? e.code : ''} ${typeof e.message === 'string' ? e.message : ''}`\n return TLS_FAILURE.test(detail) ? `TLS failed: ${String(e.message ?? e.code)}` : null\n }\n}\n\n/**\n * Connect, read the host's identity and `daemon.info`, disconnect. Never throws.\n * @param target - URL, token and an optional timeout in milliseconds. The timeout defaults to {@link HOST_PROBE_TIMEOUT_MS}.\n * @returns Who answered and how fast, or a classified failure.\n */\nexport async function probeWsHost(target: { url: string, token: string, timeoutMs?: number }): Promise<HostProbeResult> {\n const started = performance.now()\n const signal = AbortSignal.timeout(target.timeoutMs ?? HOST_PROBE_TIMEOUT_MS)\n let client: Awaited<ReturnType<typeof connectWsClient>> | undefined\n try {\n client = await connectWsClient({ url: target.url, token: target.token, heartbeatMs: 0, signal })\n const hostRef = hostRefOf(client.hello)\n if (!hostRef)\n return { ok: false, error: 'protocol', message: `${displayHostUrl(target.url)} runs a zidane too old to say which host it is. Upgrade the server.` }\n const info = await client.request('daemon.info', {})\n const serverVersion = info.codeVersion ?? info.appVersion\n return { ok: true, hostRef, ...(serverVersion ? { serverVersion } : {}), latencyMs: Math.round(performance.now() - started) }\n }\n catch (err) {\n if (signal.aborted && !(err instanceof HostAuthError))\n return { ok: false, error: 'unreachable', message: `No answer from ${displayHostUrl(target.url)} within ${target.timeoutMs ?? HOST_PROBE_TIMEOUT_MS} ms.` }\n const classified = classify(err)\n if (classified.error === 'unreachable') {\n const tls = await tlsFailure(target.url, signal).catch(() => null)\n if (tls)\n return { ok: false, error: 'tls', message: tls }\n }\n return { ok: false, ...classified }\n }\n finally {\n client?.close()\n }\n}\n\n/**\n * The registry in `dataDir`, connecting over WebSocket.\n * @param options - Where the registry keeps its data.\n * @returns The host registry.\n */\nexport function createWsHostRegistry(options: { dataDir: string }): HostRegistry {\n return createHostRegistry({ dataDir: options.dataDir, probe: probeWsHost })\n}\n","/**\n * A client's saved servers, kept in its host directory: one directory entry\n * and one app-lifetime connection (`connection-loop`) per server in the\n * registry, in step with it. Shared by the TUI and the GUI main process,\n * which each supply their directory (`SavedHostsDirectory`) and how to dial.\n *\n * Saving a server that is already saved (same host id: a new token, a new\n * URL) reconfigures its entry IN PLACE and reconnects: the entry is never\n * removed, so the sessions routed to it stay routed. Only a server leaving\n * the registry (removed here or by another window) or `stop()` removes an\n * entry, and the directory decides what that means for an open session.\n *\n * Every connection is checked against the saved entry's id (the server's\n * `hostId` when it was added): another host answering at the URL is closed\n * at once, reported as `identity` and not retried, so nothing it says is\n * recorded under the saved id. Dialers may check first (`expectHostId`).\n *\n * No WebSocket import: the WebSocket wiring is `./ws.ts`.\n */\nimport type { HostEntry, HostProbeResult, HostRegistry, HostTestResult } from '../../chat/hosts'\nimport type { HostSignal } from '../protocol'\nimport type { IpcClient } from '../transports/client-core'\nimport type { HostConnectionLoop, HostConnectionPatch, HostFailureKind } from './connection-loop'\nimport { displayHostUrl, HostIdentityError } from '../../chat/hosts'\nimport { hostRefOf } from '../protocol'\nimport { keepHostConnected } from './connection-loop'\n\n/** The client's host directory, as the saved servers see it. Keys are host ids. */\nexport interface SavedHostsDirectory {\n /** The saved servers it holds now, with their URL (a `--host` server excluded). */\n saved: () => { key: string, url: string }[]\n /** Add the entry, or reconfigure the one under its key in place (status `connecting`). */\n upsert: (entry: HostEntry, token: string | undefined) => void\n /** Applies a connection patch, a new name or a server version to the entry. */\n update: (key: string, patch: HostConnectionPatch & { name?: string, serverVersion?: string }) => void\n /** The server left the registry, or the saved servers stopped. */\n remove: (key: string) => void\n}\n\n/** No token is saved for this server (removed by hand, or another window removed it). */\nexport class MissingHostTokenError extends Error {\n constructor() {\n super('No token saved for this server: add it again.')\n this.name = 'MissingHostTokenError'\n }\n}\n\n/** Options for {@link startSavedHosts}: the registry, the host directory, the connect function and callbacks. */\nexport interface SavedHostsOptions {\n /** The registry of saved servers. */\n registry: HostRegistry\n /** The client's host directory the entries are kept in. */\n directory: SavedHostsDirectory\n /** One connect attempt to a saved server, with its token read fresh. */\n connect: (entry: HostEntry, token: string, options: { signal: AbortSignal, onClose: () => void }) => Promise<IpcClient>\n /** `auth`: refused for good. A missing token is always `auth`, another host answering always `identity`. */\n classify?: (err: unknown) => HostFailureKind\n /** The add form's test of an unsaved URL + token (`probeUnsavedHost`). */\n probeUnsaved?: (target: { url: string, token: string }) => Promise<HostProbeResult>\n /** Saved entries the directory already reaches another way (the TUI's `--host` server). */\n skip?: (entry: HostEntry) => boolean\n /** Called with every signal of a connected saved server. */\n onSignal?: (key: string, signal: HostSignal) => void\n /** Called when a saved server connects, also after a reconnect. */\n onConnected?: (key: string, client: IpcClient) => void\n /** Called when a saved server's connection drops. */\n onDisconnected?: (key: string) => void\n /**\n * Lower backoff bound in milliseconds.\n * @default 1000\n */\n minDelayMs?: number\n /**\n * Upper backoff bound in milliseconds.\n * @default 30000\n */\n maxDelayMs?: number\n}\n\n/** Handle returned by {@link startSavedHosts} to list, add, remove, rename, test and retry saved servers. */\nexport interface SavedHostsController {\n /** The saved hosts, read fresh (other windows share the file). */\n list: () => HostEntry[]\n /** Verify, save, connect (in place when already saved). Throws a `HostRegistryError`. */\n add: (input: { url: string, token: string, name?: string }) => Promise<HostEntry>\n /** Removes a server from the registry and its entry from the directory. Returns whether it existed. */\n remove: (id: string) => boolean\n /** Renames a saved server and returns the updated entry. */\n rename: (id: string, name: string) => HostEntry\n /** A saved server (by id), or an unsaved URL + token (the add form's test). */\n test: (target: string | { id: string } | { url: string, token: string }) => Promise<HostTestResult>\n /** Reconnect now (after an outage or a token fix). */\n retry: (id: string) => void\n /** Reconnect every saved server that is not connected now, its backoff reset (the computer woke up). */\n retryAll: () => void\n /** Disconnects every saved server and removes their directory entries. The registry is not changed. */\n stop: () => void\n}\n\n/**\n * Starts the connections of a client's saved servers and keeps the directory in step with the registry.\n * Each saved server gets a directory entry and a connection loop. A connection whose host id differs from the saved one is closed and reported as `identity`.\n * @param options - Registry, directory and how to dial.\n * @returns A controller over the saved servers.\n */\nexport function startSavedHosts(options: SavedHostsOptions): SavedHostsController {\n const { registry, directory, skip = () => false } = options\n const classify = (err: unknown): HostFailureKind => err instanceof MissingHostTokenError ? 'auth' : err instanceof HostIdentityError ? 'identity' : (options.classify?.(err) ?? 'retry')\n\n /** The saved server, or nobody: a connection from another host is closed before anyone sees it. */\n const dial = async (entry: HostEntry, token: string, attempt: { signal: AbortSignal, onClose: () => void }): Promise<IpcClient> => {\n const client = await options.connect(entry, token, attempt)\n const ref = hostRefOf(client.hello)\n if (ref?.id === entry.id)\n return client\n client.close()\n throw new HostIdentityError(displayHostUrl(entry.url), ref?.name)\n }\n const loops = new Map<string, HostConnectionLoop>()\n\n const disconnect = (key: string): void => {\n loops.get(key)?.stop()\n loops.delete(key)\n }\n\n /** (Re)connect `entry` with the token saved now, its directory entry kept or created in place. */\n const connect = (entry: HostEntry): void => {\n const key = entry.id\n disconnect(key)\n directory.upsert(entry, registry.token(key))\n loops.set(key, keepHostConnected({\n connect: (attempt) => {\n const token = registry.token(key)\n return token ? dial(entry, token, attempt) : Promise.reject(new MissingHostTokenError())\n },\n update: patch => directory.update(key, patch),\n classify,\n ...(options.onSignal ? { onSignal: (signal: HostSignal) => options.onSignal!(key, signal) } : {}),\n ...(options.onConnected ? { onConnected: (client: IpcClient) => options.onConnected!(key, client) } : {}),\n ...(options.onDisconnected ? { onDisconnected: () => options.onDisconnected!(key) } : {}),\n ...(options.minDelayMs !== undefined ? { minDelayMs: options.minDelayMs } : {}),\n ...(options.maxDelayMs !== undefined ? { maxDelayMs: options.maxDelayMs } : {}),\n }))\n }\n\n /** Bring the directory in line with the saved hosts. */\n const sync = (): void => {\n const entries = registry.list().filter(entry => !skip(entry))\n const saved = new Set(entries.map(entry => entry.id))\n const known = new Map(directory.saved().map(host => [host.key, host.url]))\n for (const key of known.keys()) {\n if (!saved.has(key)) {\n disconnect(key)\n directory.remove(key)\n }\n }\n for (const entry of entries) {\n if (known.get(entry.id) !== entry.url)\n connect(entry)\n else\n directory.update(entry.id, { name: entry.name, ...(entry.serverVersion ? { serverVersion: entry.serverVersion } : {}) })\n }\n }\n\n sync()\n return {\n list: () => registry.list(),\n add: async (input) => {\n const entry = await registry.add(input)\n // Saved again (a new token or URL): reconnect with them, the entry kept.\n if (!skip(entry))\n connect(entry)\n sync()\n return entry\n },\n remove: (id) => {\n const removed = registry.remove(id)\n sync()\n return removed\n },\n rename: (id, name) => {\n const entry = registry.rename(id, name)\n sync()\n return entry\n },\n test: async (target) => {\n if (typeof target === 'object' && !('id' in target)) {\n if (!options.probeUnsaved)\n throw new Error('Testing an unsaved host is not available here.')\n return options.probeUnsaved(target)\n }\n const id = typeof target === 'string' ? target : target.id\n const result = await registry.test(id)\n if (result.ok) {\n directory.update(id, { serverName: result.hostRef.name, ...(result.serverVersion ? { serverVersion: result.serverVersion } : {}) })\n loops.get(id)?.retry()\n }\n return result\n },\n retry: id => loops.get(id)?.retry(),\n retryAll: () => {\n for (const loop of loops.values())\n loop.retry()\n },\n stop: () => {\n for (const key of [...loops.keys()]) {\n disconnect(key)\n directory.remove(key)\n }\n },\n }\n}\n","/**\n * Saved servers over WebSocket: the registry in `dataDir`, the add form's\n * unsaved test, the refusal classification and (by default) the dial, wired\n * for `startSavedHosts`. Loaded behind each client's remote-hosts gate.\n */\nimport type { HostProbeResult } from '../../chat/hosts'\nimport type { HostFailureKind } from './connection-loop'\nimport type { SavedHostsController, SavedHostsOptions } from './saved-hosts'\nimport { HostIdentityError, probeUnsavedHost } from '../../chat/hosts'\nimport { IpcVersionMismatchError } from '../transports/client-core'\nimport { connectWsClient, HostAuthError } from '../transports/ws-client'\nimport { createWsHostRegistry, probeWsHost } from './probe'\nimport { startSavedHosts } from './saved-hosts'\n\n/**\n * A refused token stays refused until the user changes something: no retry\n * loop. Another protocol version stays until one side is upgraded: a slow re-check.\n * @param err - The error a connect attempt failed with.\n * @returns `auth` for a refused token, `identity` for another host answering, `protocol` for a version mismatch, `retry` otherwise.\n */\nexport function classifyWsFailure(err: unknown): HostFailureKind {\n if (err instanceof HostAuthError)\n return 'auth'\n if (err instanceof HostIdentityError)\n return 'identity'\n return err instanceof IpcVersionMismatchError ? 'protocol' : 'retry'\n}\n\n/**\n * The add form's \"test\": the registry's own checks and probe over WebSocket, saving nothing.\n * @param target - URL and token to try.\n * @returns The probe result.\n */\nexport function probeUnsavedWsHost(target: { url: string, token: string }): Promise<HostProbeResult> {\n return probeUnsavedHost(probeWsHost, target)\n}\n\n/**\n * Options for {@link startWsSavedHosts}: {@link SavedHostsOptions} with the registry, dialer and classifier filled in.\n * `dataDir` holds the saved-hosts registry file.\n */\nexport type WsSavedHostsOptions = Omit<SavedHostsOptions, 'registry' | 'connect' | 'classify' | 'probeUnsaved'> & {\n dataDir: string\n /** Client version in the server's diagnostics (default dial only). */\n appVersion?: string\n /** Dial another way (the TUI goes through its directory entry's transport). Default: `connectWsClient`. */\n connect?: SavedHostsOptions['connect']\n registry?: SavedHostsOptions['registry']\n}\n\n/**\n * Keeps the saved servers of a client connected over WebSocket.\n * Uses the registry in `dataDir` unless `registry` is given, and dials with {@link connectWsClient} unless `connect` is given.\n * @param options - Data directory, host directory and callbacks.\n * @returns A controller to list, add, remove, test and retry hosts, and to stop them all.\n */\nexport function startWsSavedHosts(options: WsSavedHostsOptions): SavedHostsController {\n const { dataDir, appVersion, connect, registry, ...rest } = options\n return startSavedHosts({\n ...rest,\n registry: registry ?? createWsHostRegistry({ dataDir }),\n classify: classifyWsFailure,\n probeUnsaved: probeUnsavedWsHost,\n connect: connect ?? ((entry, token, attempt) => connectWsClient({\n url: entry.url,\n token,\n expectHostId: entry.id,\n ...(appVersion ? { appVersion } : {}),\n signal: attempt.sign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ponse, i as createJsonRpcEndpoint, o as successResponse } from "./json-rpc-G0rBfEar.js";
3
3
  import { i as METHOD_NOT_FOUND, t as HostIdentityError } from "./connection-BaHd3T-D.js";
4
- import { a as createSignalListeners, o as openIpcClient } from "./settings-keys-zYaer8DY.js";
4
+ import { a as createSignalListeners, o as openIpcClient } from "./settings-keys-CPdmkTz7.js";
5
5
  import { u as hostRefOf } from "./protocol-BIv1Yuvl.js";
6
- import { n as displayHostUrl } from "./url-BTH-HE9Y.js";
6
+ import { n as displayHostUrl } from "./url-D8KZ7Edw.js";
7
7
  import tls from "node:tls";
8
8
  //#region src/ipc/transports/tls-trust.ts
9
9
  /**
@@ -323,4 +323,4 @@ async function connectWsClient(options) {
323
323
  //#endregion
324
324
  export { hostCaBundle as a, ws_client_exports as i, HostBusyError as n, trustSystemCertificates as o, connectWsClient as r, HostAuthError as t };
325
325
 
326
- //# sourceMappingURL=ws-client-wWka-Jku.js.map
326
+ //# sourceMappingURL=ws-client-BVljYbdb.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"ws-client-wWka-Jku.js","names":["BunWebSocket"],"sources":["../src/ipc/transports/tls-trust.ts","../src/ipc/transports/ws-auth.ts","../src/ipc/transports/ws-client.ts"],"sourcesContent":["/**\n * Which certificate authorities a client trusts for a remote zidane-server:\n * the runtime's own roots plus the operating system's store (the macOS\n * keychain, the Linux CA bundle). A server behind a private CA, an mkcert\n * certificate or a self-signed one the user trusted in the OS then works\n * like a public one. `NODE_EXTRA_CA_CERTS` adds certificates at launch, in\n * both runtimes.\n *\n * Bun's WebSocket and fetch ignore `tls.setDefaultCACertificates`, so Bun\n * clients (the TUI, `zidane machine share`) pass the bundle with each\n * connection (`hostCaBundle`). Node honors it, so the desktop app's main\n * process trusts the store once, when it turns remote hosts on\n * (`trustSystemCertificates`).\n */\nimport tls from 'node:tls'\n\ntype CaKind = 'default' | 'system' | 'extra'\nconst api = tls as unknown as {\n getCACertificates?: (kind: CaKind) => string[]\n setDefaultCACertificates?: (certs: readonly string[]) => void\n}\n\nfunction certificates(kind: CaKind): string[] {\n try {\n return api.getCACertificates?.(kind) ?? []\n }\n catch {\n return []\n }\n}\n\nlet bundle: string[] | null | undefined\n\n/**\n * The runtime's roots, the OS store's and `NODE_EXTRA_CA_CERTS`'s, read once.\n * `null` when the OS store adds nothing (or can't be read): the runtime's\n * default then applies as it is.\n */\nexport function hostCaBundle(): string[] | null {\n if (bundle === undefined) {\n const system = certificates('system')\n bundle = system.length === 0 ? null : [...new Set([...certificates('default'), ...system, ...certificates('extra')])]\n }\n return bundle\n}\n\n/**\n * Node: every TLS client of this process trusts {@link hostCaBundle} from now\n * on (the desktop app's main process). Whether it applied.\n */\nexport function trustSystemCertificates(): boolean {\n const ca = hostCaBundle()\n if (!ca || !api.setDefaultCACertificates || typeof (globalThis as { Bun?: unknown }).Bun !== 'undefined')\n return false\n api.setDefaultCACertificates(ca)\n return true\n}\n","/**\n * How a WebSocket client's token reaches the server, shared by both ends.\n *\n * Preferred: `Authorization: Bearer <token>` (Bun's WebSocket can set it).\n * Fallback for clients that can't set handshake headers (Node's and the\n * browser's WebSocket): a `zidane.bearer.<token>` entry in\n * `Sec-WebSocket-Protocol`, offered next to `zidane`, the subprotocol the\n * server selects. A token sent this way must be a valid subprotocol token\n * (base64url is).\n */\n\n/** The subprotocol clients offer and the server selects. */\nexport const WS_SUBPROTOCOL = 'zidane'\n/** Prefix of the subprotocol entry carrying the bearer token. */\nexport const WS_BEARER_PREFIX = 'zidane.bearer.'\n\nexport type WsTokenCarrier = 'header' | 'subprotocol'\n\n/**\n * What an accepted connection is: a `client` (a window: the whole method\n * table, signals) or a `machine` lending its execution (`docs/MACHINES.md`:\n * only `ipc.hello`, `$/ping`, `machine.register`, never a peer). Default `client`.\n */\nexport type WsConnectionScope = 'client' | 'machine'\n\n/**\n * A server's answer to an upgrade's token. Accepted: `principal` names what\n * authenticated (a token id), so connections can be dropped by it later.\n * Refused: the HTTP status, sent before any JSON-RPC (401 no valid\n * credential, 403 a credential not allowed here).\n */\nexport type WsAuthVerdict\n = | { ok: true, principal?: string, scope?: WsConnectionScope }\n | { ok: false, status: 401 | 403, reason?: WsRefusalReason }\n\n/**\n * Why a server refused an upgrade with a 403, as a machine-readable code in\n * {@link WS_REFUSAL_HEADER}. Clients show a fixed text per code (never the\n * response body, which a proxy may fill with anything, the request's own\n * headers included) and ignore codes they don't know.\n */\nexport const WS_REFUSAL_HEADER = 'X-Zidane-Refusal'\nconst WS_REFUSAL_REASONS = ['origin', 'insecure-transport', 'untrusted-proxy', 'scope'] as const\nexport type WsRefusalReason = typeof WS_REFUSAL_REASONS[number]\n\nexport function isWsRefusalReason(value: unknown): value is WsRefusalReason {\n return typeof value === 'string' && (WS_REFUSAL_REASONS as readonly string[]).includes(value)\n}\n\n/** Subprotocols offered in `Sec-WebSocket-Protocol`. */\nexport function offeredSubprotocols(request: Request): string[] {\n return (request.headers.get('sec-websocket-protocol') ?? '').split(',').map(p => p.trim()).filter(Boolean)\n}\n\n/** The client's token: `Authorization: Bearer`, else the subprotocol entry. */\nexport function requestToken(request: Request): string | undefined {\n const auth = request.headers.get('authorization')\n const bearer = auth && /^Bearer\\s+(\\S+)$/i.exec(auth.trim())\n if (bearer)\n return bearer[1]\n const entry = offeredSubprotocols(request).find(p => p.startsWith(WS_BEARER_PREFIX))\n return entry ? entry.slice(WS_BEARER_PREFIX.length) : undefined\n}\n","/**\n * `IpcClient` over a WebSocket (a remote `zidane-server`, `./ws-server`):\n * one JSON-RPC message per text frame, the same handshake, deadlines and\n * signal delivery as the unix-socket client (`./client-core`).\n *\n * Uses the runtime's global `WebSocket` (Bun; Node >= 22), so it is safe in\n * the Node-imported `zidane/ipc` barrel. Unlike a local daemon client it\n * never asks the host to drain on a version mismatch (a remote server's\n * lifetime is not a client's to end) and opts out of the dev build fence.\n *\n * Opening is bounded (`openTimeoutMs`) and abortable (`signal`, up to the\n * end of the handshake). A refused upgrade is opaque to a WebSocket (no\n * status, just \"expected 101\", close 1002), so on failure the client asks\n * the same URL over plain HTTP, with the same token, why: a 401 or 403\n * becomes a {@link HostAuthError}, a 429 a {@link HostBusyError}, each with a\n * fixed message (the response body\n * is never read: a proxy may echo the request's headers, the token\n * included, and the message reaches a GUI renderer). That request never\n * follows a redirect: a 3xx is reported as a misconfigured URL, and the\n * token goes nowhere but the URL's own origin.\n *\n * Messages name the URL by scheme, host and path only (`displayHostUrl`).\n *\n * Certificates: the runtime's roots and the OS store (`./tls-trust`). Under\n * Bun the bundle goes with each socket and refusal probe; under Node the\n * process default applies (the desktop app sets it).\n */\nimport type { IpcClient } from './client-core'\nimport type { WsRefusalReason, WsTokenCarrier } from './ws-auth'\nimport { createJsonRpcEndpoint, errorResponse, successResponse } from '../../acp/json-rpc'\nimport { HostIdentityError, METHOD_NOT_FOUND } from '../../chat/hosts/connection'\nimport { displayHostUrl } from '../../chat/hosts/url'\nimport { hostRefOf } from '../protocol'\nimport { createSignalListeners, openIpcClient } from './client-core'\nimport { hostCaBundle } from './tls-trust'\nimport { isWsRefusalReason, WS_BEARER_PREFIX, WS_REFUSAL_HEADER, WS_SUBPROTOCOL } from './ws-auth'\n\n/** Options for {@link connectWsClient}. */\nexport interface WsClientOptions {\n /** `ws://` or `wss://` URL of the server. */\n url: string\n /** Bearer token for the server, see `./ws-auth`. */\n token?: string\n /**\n * How the token travels. Default: the `Authorization` header where the\n * runtime's WebSocket can set one (Bun), else the subprotocol fallback.\n */\n tokenCarrier?: WsTokenCarrier\n /** Client zidane version, surfaced in the host's diagnostics. */\n appVersion?: string\n /**\n * Certificate authorities (PEM) a `wss://` server's certificate may chain\n * to. Default: the runtime's roots and the OS store (`hostCaBundle`). Bun\n * only: under Node the process default applies.\n */\n ca?: readonly string[]\n /** The connection dropped (server exit, network error, a missed deadline or heartbeat). Not called for `close()`. */\n onClose?: () => void\n /** `$/ping` interval (`./client-core`). Default {@link WS_HEARTBEAT_MS}; `0` disables. */\n heartbeatMs?: number\n /** Bound on the upgrade (not the handshake, which has its own). Default {@link WS_OPEN_TIMEOUT_MS}. */\n openTimeoutMs?: number\n /** Abandon the connect (upgrade and handshake): it rejects with the signal's reason. */\n signal?: AbortSignal\n /**\n * The host id a saved host answered with when it was added: a hello with\n * any other id closes the connection and rejects with a\n * {@link HostIdentityError} (nothing is read from that host).\n */\n expectHostId?: string\n /**\n * Answer the host's requests and notifications on this connection: a\n * machine serving its host (`docs/MACHINES.md`). A throw becomes a\n * JSON-RPC error (its `code` when it carries one). Default: a client\n * refuses requests and reads only `ipc.signal`.\n */\n serve?: {\n request: (method: string, params: unknown) => Promise<unknown>\n notification?: (method: string, params: unknown) => void\n }\n}\n\n/** Heartbeat interval on both ends of a WebSocket by default. */\nexport const WS_HEARTBEAT_MS = 20_000\n/** How long an upgrade may take by default. */\nconst WS_OPEN_TIMEOUT_MS = 15_000\n\nconst FORBIDDEN: Record<WsRefusalReason, string> = {\n 'origin': 'this client\\'s origin is not allowed by the server (allowedOrigins)',\n 'insecure-transport': 'the server only accepts connections through its HTTPS proxy',\n 'untrusted-proxy': 'the server only accepts connections from its trusted proxies',\n 'scope': 'this token\\'s scope cannot open a client connection',\n}\n\n/**\n * The server refused this client's credential: 401 (no valid token) or 403\n * (not allowed here). `reason` only when the server sent a code clients know.\n */\nexport class HostAuthError extends Error {\n /** The server URL, scheme, host and path only. */\n readonly url: string\n /**\n * @param url - The server URL.\n * @param status - HTTP status of the refusal.\n * @param reason - Refusal code the server sent, when any.\n */\n constructor(url: string, readonly status: 401 | 403, readonly reason?: WsRefusalReason) {\n const shown = displayHostUrl(url)\n super(`WebSocket connection to ${shown} failed: ${status === 401\n ? 'token refused (401): the server does not know this token, or it was revoked. Create a new one on the server (zidane server token create --name <device>) and use it here'\n : `forbidden (403): ${reason ? FORBIDDEN[reason] : 'refused by the server or a proxy in front of it (origin, token scope or proxy rules)'}`}.`)\n this.name = 'HostAuthError'\n this.url = shown\n }\n}\n\n/** The server turned the upgrade down with a 429: too many open connections (per token, per address) or upgrades (per address). Transient. */\nexport class HostBusyError extends Error {\n /** @param url - The server URL. */\n constructor(url: string) {\n super(`WebSocket connection to ${displayHostUrl(url)} failed: too many connections or connection attempts (429). The server caps open connections per token and per address: close other windows that use this token, or wait a few seconds.`)\n this.name = 'HostBusyError'\n }\n}\n\n/** The URL answered with a redirect: not followed (the token would go along). */\nexport class HostRedirectError extends Error {\n constructor(url: string, status: number) {\n super(`WebSocket connection to ${displayHostUrl(url)} failed: the server redirects (${status}); not following it with the token. Check the URL (scheme, host, path) or the proxy in front of the server.`)\n this.name = 'HostRedirectError'\n }\n}\n\n/** Bun's WebSocket and fetch take handshake headers and TLS options; the WHATWG ones (Node, browsers) do not. */\nconst isBun = (): boolean => typeof (globalThis as { Bun?: unknown }).Bun !== 'undefined'\n\n/** Under Bun, the CAs to pass along for a `wss:` / `https:` URL; `null`: the runtime's default. */\nfunction bunCa(options: WsClientOptions): readonly string[] | null {\n return isBun() && /^(?:wss|https):/i.test(options.url) ? options.ca ?? hostCaBundle() : null\n}\n\nfunction createSocket(options: WsClientOptions): WebSocket {\n const protocols = [WS_SUBPROTOCOL]\n const carrier = options.tokenCarrier ?? (isBun() ? 'header' : 'subprotocol')\n if (options.token && carrier === 'subprotocol')\n protocols.push(`${WS_BEARER_PREFIX}${options.token}`)\n const headers = options.token && carrier === 'header' ? { Authorization: `Bearer ${options.token}` } : null\n const ca = bunCa(options)\n if (headers || ca) {\n // Bun's constructor extension: `{ headers, protocols, tls }` in place of the protocol list.\n const BunWebSocket = WebSocket as unknown as new (url: string, init: { headers?: Record<string, string>, protocols: string[], tls?: { ca: readonly string[] } }) => WebSocket\n return new BunWebSocket(options.url, { ...(headers ? { headers } : {}), protocols, ...(ca ? { tls: { ca } } : {}) })\n }\n return new WebSocket(options.url, protocols)\n}\n\n/** The upgrade took longer than `openTimeoutMs`: nothing answered, so there is no refusal to ask about. */\nclass WsOpenTimeoutError extends Error {\n constructor(url: string, timeoutMs: number) {\n super(`WebSocket connection to ${displayHostUrl(url)} timed out after ${timeoutMs} ms.`)\n this.name = 'WsOpenTimeoutError'\n }\n}\n\nfunction abortError(signal: AbortSignal): Error {\n return signal.reason instanceof Error ? signal.reason : new DOMException('The connect was aborted.', 'AbortError')\n}\n\n/** Resolves on `open`; rejects on failure, timeout or abort (closing the socket). */\nfunction opened(ws: WebSocket, url: string, timeoutMs: number, signal: AbortSignal | undefined): Promise<void> {\n return new Promise((resolve, reject) => {\n const done = new AbortController()\n let timer: ReturnType<typeof setTimeout> | undefined\n const settle = (err?: Error): void => {\n if (done.signal.aborted)\n return\n done.abort()\n clearTimeout(timer)\n if (!err)\n return resolve()\n ws.close()\n reject(err)\n }\n const fail = (detail: string) => () => settle(new Error(`WebSocket connection to ${displayHostUrl(url)} failed${detail}.`))\n ws.addEventListener('open', () => settle(), { signal: done.signal })\n ws.addEventListener('error', fail(''), { signal: done.signal })\n ws.addEventListener('close', event => fail(` (close ${event.code}${event.reason ? `: ${event.reason}` : ''})`)(), { signal: done.signal })\n signal?.addEventListener('abort', () => settle(abortError(signal)), { signal: done.signal })\n timer = setTimeout(() => settle(new WsOpenTimeoutError(url, timeoutMs)), timeoutMs)\n })\n}\n\n/** Why an upgrade failed, asked over plain HTTP: a {@link HostAuthError} for 401 / 403, a {@link HostBusyError} for 429, a {@link HostRedirectError} for 3xx, else `null`. */\nasync function refusal(options: WsClientOptions): Promise<Error | null> {\n try {\n const url = new URL(options.url)\n url.protocol = url.protocol === 'wss:' ? 'https:' : 'http:'\n const timeout = AbortSignal.timeout(5000)\n const ca = bunCa(options)\n const response = await fetch(url, {\n headers: options.token ? { Authorization: `Bearer ${options.token}` } : {},\n redirect: 'manual',\n signal: options.signal ? AbortSignal.any([options.signal, timeout]) : timeout,\n // Bun's fetch extension, as for the socket.\n ...(ca ? { tls: { ca } } : {}),\n } as RequestInit)\n void response.body?.cancel().catch(() => {})\n if (response.type === 'opaqueredirect' || (response.status >= 300 && response.status < 400))\n return new HostRedirectError(options.url, response.status)\n if (response.status === 429)\n return new HostBusyError(options.url)\n if (response.status !== 401 && response.status !== 403)\n return null\n const reason = response.headers.get(WS_REFUSAL_HEADER)\n return new HostAuthError(options.url, response.status, response.status === 403 && isWsRefusalReason(reason) ? reason : undefined)\n }\n catch {\n return null\n }\n}\n\n/** Close a connection whose host is not the one expected, and say so. */\nfunction checkIdentity(client: IpcClient, options: WsClientOptions): IpcClient {\n if (options.expectHostId === undefined)\n return client\n const ref = hostRefOf(client.hello)\n if (ref?.id === options.expectHostId)\n return client\n client.close()\n throw new HostIdentityError(displayHostUrl(options.url), ref?.name)\n}\n\n/**\n * Connects to a remote zidane server over WebSocket and completes the `ipc.hello` handshake.\n * A refused upgrade rejects with {@link HostAuthError} for a 401 or 403, and {@link HostBusyError} for a 429. A hello from another host than `expectHostId` rejects with `HostIdentityError`. A version mismatch rejects with {@link IpcVersionMismatchError} and leaves the server running.\n * @param options - Server URL, token and connection settings.\n * @returns A typed client.\n * @example\n * ```ts\n * import { connectWsClient } from 'zidane/ipc/remote'\n *\n * const client = await connectWsClient({\n * url: 'wss://zidane.example.com/',\n * token: process.env.ZIDANE_HOST_TOKEN,\n * })\n * const sessions = await client.request('sessions.list', {})\n * console.log(sessions.length)\n * client.close()\n * ```\n */\nexport async function connectWsClient(options: WsClientOptions): Promise<IpcClient> {\n const { signal } = options\n signal?.throwIfAborted()\n const ws = createSocket(options)\n ws.binaryType = 'arraybuffer'\n try {\n await opened(ws, options.url, options.openTimeoutMs ?? WS_OPEN_TIMEOUT_MS, signal)\n }\n catch (err) {\n if (signal?.aborted || err instanceof WsOpenTimeoutError)\n throw err\n throw (await refusal(options)) ?? err\n }\n\n const signals = createSignalListeners()\n let closed = false\n\n const rpc = createJsonRpcEndpoint({\n send: (json) => {\n try {\n ws.send(json)\n }\n catch {\n // A closing socket: the close handler fails what is pending.\n }\n },\n // The host never sends requests to clients, only notifications; a machine serves them.\n onRequest: async (message) => {\n const serve = options.serve\n if (!serve)\n return errorResponse(message.id, METHOD_NOT_FOUND, 'Clients do not accept requests.')\n try {\n return successResponse(message.id, (await serve.request(message.method, message.params)) ?? null)\n }\n catch (err) {\n const code = (err as { code?: unknown }).code\n return errorResponse(message.id, typeof code === 'number' ? code : -32000, err instanceof Error ? err.message : String(err))\n }\n },\n onNotification: (message) => {\n if (message.method === 'ipc.signal' || !options.serve?.notification)\n return signals.onNotification(message)\n options.serve.notification(message.method, (message as { params?: unknown }).params)\n },\n })\n\n const decoder = new TextDecoder()\n ws.addEventListener('message', (event: MessageEvent) => {\n if (closed)\n return\n rpc.receive(typeof event.data === 'string' ? event.data : decoder.decode(event.data as ArrayBuffer))\n })\n\n /** The host went away (or the connection was given up): fail what is pending, tell the owner. */\n const lost = (): void => {\n if (closed)\n return\n closed = true\n rpc.close()\n options.onClose?.()\n }\n ws.addEventListener('close', lost)\n ws.addEventListener('error', () => {\n // 'close' follows.\n })\n\n const close = (): void => {\n if (closed)\n return\n closed = true\n rpc.close()\n ws.close(1000)\n }\n\n // Aborted mid-handshake: the close fails the pending hello, and the connect rejects with the signal's reason.\n const onAbort = (): void => close()\n signal?.addEventListener('abort', onAbort, { once: true })\n try {\n return checkIdentity(await openIpcClient(\n {\n rpc,\n close,\n abort: () => {\n lost()\n ws.close(1000)\n },\n where: displayHostUrl(options.url),\n },\n signals.listeners,\n {\n ...(options.appVersion ? { appVersion: options.appVersion } : {}),\n drain: 'never',\n buildFence: false,\n heartbeatMs: options.heartbeatMs ?? WS_HEARTBEAT_MS,\n },\n ), options)\n }\n catch (err) {\n throw signal?.aborted ? abortError(signal) : err\n }\n finally {\n signal?.removeEventListener('abort', onAbort)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAiBA,MAAM,MAAM;AAKZ,SAAS,aAAa,MAAwB;CAC5C,IAAI;EACF,OAAO,IAAI,oBAAoB,IAAI,KAAK,CAAC;CAC3C,QACM;EACJ,OAAO,CAAC;CACV;AACF;AAEA,IAAI;;;;;;AAOJ,SAAgB,eAAgC;CAC9C,IAAI,WAAW,KAAA,GAAW;EACxB,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MAAM,IAAI;CAC/C,UACQ;EACN,QAAQ,oBAAoB,SAAS,OAAO;CAC9C;AACF"}
1
+ {"version":3,"file":"ws-client-BVljYbdb.js","names":["BunWebSocket"],"sources":["../src/ipc/transports/tls-trust.ts","../src/ipc/transports/ws-auth.ts","../src/ipc/transports/ws-client.ts"],"sourcesContent":["/**\n * Which certificate authorities a client trusts for a remote zidane-server:\n * the runtime's own roots plus the operating system's store (the macOS\n * keychain, the Linux CA bundle). A server behind a private CA, an mkcert\n * certificate or a self-signed one the user trusted in the OS then works\n * like a public one. `NODE_EXTRA_CA_CERTS` adds certificates at launch, in\n * both runtimes.\n *\n * Bun's WebSocket and fetch ignore `tls.setDefaultCACertificates`, so Bun\n * clients (the TUI, `zidane machine share`) pass the bundle with each\n * connection (`hostCaBundle`). Node honors it, so the desktop app's main\n * process trusts the store once, when it turns remote hosts on\n * (`trustSystemCertificates`).\n */\nimport tls from 'node:tls'\n\ntype CaKind = 'default' | 'system' | 'extra'\nconst api = tls as unknown as {\n getCACertificates?: (kind: CaKind) => string[]\n setDefaultCACertificates?: (certs: readonly string[]) => void\n}\n\nfunction certificates(kind: CaKind): string[] {\n try {\n return api.getCACertificates?.(kind) ?? []\n }\n catch {\n return []\n }\n}\n\nlet bundle: string[] | null | undefined\n\n/**\n * The runtime's roots, the OS store's and `NODE_EXTRA_CA_CERTS`'s, read once.\n * `null` when the OS store adds nothing (or can't be read): the runtime's\n * default then applies as it is.\n */\nexport function hostCaBundle(): string[] | null {\n if (bundle === undefined) {\n const system = certificates('system')\n bundle = system.length === 0 ? null : [...new Set([...certificates('default'), ...system, ...certificates('extra')])]\n }\n return bundle\n}\n\n/**\n * Node: every TLS client of this process trusts {@link hostCaBundle} from now\n * on (the desktop app's main process). Whether it applied.\n */\nexport function trustSystemCertificates(): boolean {\n const ca = hostCaBundle()\n if (!ca || !api.setDefaultCACertificates || typeof (globalThis as { Bun?: unknown }).Bun !== 'undefined')\n return false\n api.setDefaultCACertificates(ca)\n return true\n}\n","/**\n * How a WebSocket client's token reaches the server, shared by both ends.\n *\n * Preferred: `Authorization: Bearer <token>` (Bun's WebSocket can set it).\n * Fallback for clients that can't set handshake headers (Node's and the\n * browser's WebSocket): a `zidane.bearer.<token>` entry in\n * `Sec-WebSocket-Protocol`, offered next to `zidane`, the subprotocol the\n * server selects. A token sent this way must be a valid subprotocol token\n * (base64url is).\n */\n\n/** The subprotocol clients offer and the server selects. */\nexport const WS_SUBPROTOCOL = 'zidane'\n/** Prefix of the subprotocol entry carrying the bearer token. */\nexport const WS_BEARER_PREFIX = 'zidane.bearer.'\n\nexport type WsTokenCarrier = 'header' | 'subprotocol'\n\n/**\n * What an accepted connection is: a `client` (a window: the whole method\n * table, signals) or a `machine` lending its execution (`docs/MACHINES.md`:\n * only `ipc.hello`, `$/ping`, `machine.register`, never a peer). Default `client`.\n */\nexport type WsConnectionScope = 'client' | 'machine'\n\n/**\n * A server's answer to an upgrade's token. Accepted: `principal` names what\n * authenticated (a token id), so connections can be dropped by it later.\n * Refused: the HTTP status, sent before any JSON-RPC (401 no valid\n * credential, 403 a credential not allowed here).\n */\nexport type WsAuthVerdict\n = | { ok: true, principal?: string, scope?: WsConnectionScope }\n | { ok: false, status: 401 | 403, reason?: WsRefusalReason }\n\n/**\n * Why a server refused an upgrade with a 403, as a machine-readable code in\n * {@link WS_REFUSAL_HEADER}. Clients show a fixed text per code (never the\n * response body, which a proxy may fill with anything, the request's own\n * headers included) and ignore codes they don't know.\n */\nexport const WS_REFUSAL_HEADER = 'X-Zidane-Refusal'\nconst WS_REFUSAL_REASONS = ['origin', 'insecure-transport', 'untrusted-proxy', 'scope'] as const\nexport type WsRefusalReason = typeof WS_REFUSAL_REASONS[number]\n\nexport function isWsRefusalReason(value: unknown): value is WsRefusalReason {\n return typeof value === 'string' && (WS_REFUSAL_REASONS as readonly string[]).includes(value)\n}\n\n/** Subprotocols offered in `Sec-WebSocket-Protocol`. */\nexport function offeredSubprotocols(request: Request): string[] {\n return (request.headers.get('sec-websocket-protocol') ?? '').split(',').map(p => p.trim()).filter(Boolean)\n}\n\n/** The client's token: `Authorization: Bearer`, else the subprotocol entry. */\nexport function requestToken(request: Request): string | undefined {\n const auth = request.headers.get('authorization')\n const bearer = auth && /^Bearer\\s+(\\S+)$/i.exec(auth.trim())\n if (bearer)\n return bearer[1]\n const entry = offeredSubprotocols(request).find(p => p.startsWith(WS_BEARER_PREFIX))\n return entry ? entry.slice(WS_BEARER_PREFIX.length) : undefined\n}\n","/**\n * `IpcClient` over a WebSocket (a remote `zidane-server`, `./ws-server`):\n * one JSON-RPC message per text frame, the same handshake, deadlines and\n * signal delivery as the unix-socket client (`./client-core`).\n *\n * Uses the runtime's global `WebSocket` (Bun; Node >= 22), so it is safe in\n * the Node-imported `zidane/ipc` barrel. Unlike a local daemon client it\n * never asks the host to drain on a version mismatch (a remote server's\n * lifetime is not a client's to end) and opts out of the dev build fence.\n *\n * Opening is bounded (`openTimeoutMs`) and abortable (`signal`, up to the\n * end of the handshake). A refused upgrade is opaque to a WebSocket (no\n * status, just \"expected 101\", close 1002), so on failure the client asks\n * the same URL over plain HTTP, with the same token, why: a 401 or 403\n * becomes a {@link HostAuthError}, a 429 a {@link HostBusyError}, each with a\n * fixed message (the response body\n * is never read: a proxy may echo the request's headers, the token\n * included, and the message reaches a GUI renderer). That request never\n * follows a redirect: a 3xx is reported as a misconfigured URL, and the\n * token goes nowhere but the URL's own origin.\n *\n * Messages name the URL by scheme, host and path only (`displayHostUrl`).\n *\n * Certificates: the runtime's roots and the OS store (`./tls-trust`). Under\n * Bun the bundle goes with each socket and refusal probe; under Node the\n * process default applies (the desktop app sets it).\n */\nimport type { IpcClient } from './client-core'\nimport type { WsRefusalReason, WsTokenCarrier } from './ws-auth'\nimport { createJsonRpcEndpoint, errorResponse, successResponse } from '../../acp/json-rpc'\nimport { HostIdentityError, METHOD_NOT_FOUND } from '../../chat/hosts/connection'\nimport { displayHostUrl } from '../../chat/hosts/url'\nimport { hostRefOf } from '../protocol'\nimport { createSignalListeners, openIpcClient } from './client-core'\nimport { hostCaBundle } from './tls-trust'\nimport { isWsRefusalReason, WS_BEARER_PREFIX, WS_REFUSAL_HEADER, WS_SUBPROTOCOL } from './ws-auth'\n\n/** Options for {@link connectWsClient}. */\nexport interface WsClientOptions {\n /** `ws://` or `wss://` URL of the server. */\n url: string\n /** Bearer token for the server, see `./ws-auth`. */\n token?: string\n /**\n * How the token travels. Default: the `Authorization` header where the\n * runtime's WebSocket can set one (Bun), else the subprotocol fallback.\n */\n tokenCarrier?: WsTokenCarrier\n /** Client zidane version, surfaced in the host's diagnostics. */\n appVersion?: string\n /**\n * Certificate authorities (PEM) a `wss://` server's certificate may chain\n * to. Default: the runtime's roots and the OS store (`hostCaBundle`). Bun\n * only: under Node the process default applies.\n */\n ca?: readonly string[]\n /** The connection dropped (server exit, network error, a missed deadline or heartbeat). Not called for `close()`. */\n onClose?: () => void\n /** `$/ping` interval (`./client-core`). Default {@link WS_HEARTBEAT_MS}; `0` disables. */\n heartbeatMs?: number\n /** Bound on the upgrade (not the handshake, which has its own). Default {@link WS_OPEN_TIMEOUT_MS}. */\n openTimeoutMs?: number\n /** Abandon the connect (upgrade and handshake): it rejects with the signal's reason. */\n signal?: AbortSignal\n /**\n * The host id a saved host answered with when it was added: a hello with\n * any other id closes the connection and rejects with a\n * {@link HostIdentityError} (nothing is read from that host).\n */\n expectHostId?: string\n /**\n * Answer the host's requests and notifications on this connection: a\n * machine serving its host (`docs/MACHINES.md`). A throw becomes a\n * JSON-RPC error (its `code` when it carries one). Default: a client\n * refuses requests and reads only `ipc.signal`.\n */\n serve?: {\n request: (method: string, params: unknown) => Promise<unknown>\n notification?: (method: string, params: unknown) => void\n }\n}\n\n/** Heartbeat interval on both ends of a WebSocket by default. */\nexport const WS_HEARTBEAT_MS = 20_000\n/** How long an upgrade may take by default. */\nconst WS_OPEN_TIMEOUT_MS = 15_000\n\nconst FORBIDDEN: Record<WsRefusalReason, string> = {\n 'origin': 'this client\\'s origin is not allowed by the server (allowedOrigins)',\n 'insecure-transport': 'the server only accepts connections through its HTTPS proxy',\n 'untrusted-proxy': 'the server only accepts connections from its trusted proxies',\n 'scope': 'this token\\'s scope cannot open a client connection',\n}\n\n/**\n * The server refused this client's credential: 401 (no valid token) or 403\n * (not allowed here). `reason` only when the server sent a code clients know.\n */\nexport class HostAuthError extends Error {\n /** The server URL, scheme, host and path only. */\n readonly url: string\n /**\n * @param url - The server URL.\n * @param status - HTTP status of the refusal.\n * @param reason - Refusal code the server sent, when any.\n */\n constructor(url: string, readonly status: 401 | 403, readonly reason?: WsRefusalReason) {\n const shown = displayHostUrl(url)\n super(`WebSocket connection to ${shown} failed: ${status === 401\n ? 'token refused (401): the server does not know this token, or it was revoked. Create a new one on the server (zidane server token create --name <device>) and use it here'\n : `forbidden (403): ${reason ? FORBIDDEN[reason] : 'refused by the server or a proxy in front of it (origin, token scope or proxy rules)'}`}.`)\n this.name = 'HostAuthError'\n this.url = shown\n }\n}\n\n/** The server turned the upgrade down with a 429: too many open connections (per token, per address) or upgrades (per address). Transient. */\nexport class HostBusyError extends Error {\n /** @param url - The server URL. */\n constructor(url: string) {\n super(`WebSocket connection to ${displayHostUrl(url)} failed: too many connections or connection attempts (429). The server caps open connections per token and per address: close other windows that use this token, or wait a few seconds.`)\n this.name = 'HostBusyError'\n }\n}\n\n/** The URL answered with a redirect: not followed (the token would go along). */\nexport class HostRedirectError extends Error {\n constructor(url: string, status: number) {\n super(`WebSocket connection to ${displayHostUrl(url)} failed: the server redirects (${status}); not following it with the token. Check the URL (scheme, host, path) or the proxy in front of the server.`)\n this.name = 'HostRedirectError'\n }\n}\n\n/** Bun's WebSocket and fetch take handshake headers and TLS options; the WHATWG ones (Node, browsers) do not. */\nconst isBun = (): boolean => typeof (globalThis as { Bun?: unknown }).Bun !== 'undefined'\n\n/** Under Bun, the CAs to pass along for a `wss:` / `https:` URL; `null`: the runtime's default. */\nfunction bunCa(options: WsClientOptions): readonly string[] | null {\n return isBun() && /^(?:wss|https):/i.test(options.url) ? options.ca ?? hostCaBundle() : null\n}\n\nfunction createSocket(options: WsClientOptions): WebSocket {\n const protocols = [WS_SUBPROTOCOL]\n const carrier = options.tokenCarrier ?? (isBun() ? 'header' : 'subprotocol')\n if (options.token && carrier === 'subprotocol')\n protocols.push(`${WS_BEARER_PREFIX}${options.token}`)\n const headers = options.token && carrier === 'header' ? { Authorization: `Bearer ${options.token}` } : null\n const ca = bunCa(options)\n if (headers || ca) {\n // Bun's constructor extension: `{ headers, protocols, tls }` in place of the protocol list.\n const BunWebSocket = WebSocket as unknown as new (url: string, init: { headers?: Record<string, string>, protocols: string[], tls?: { ca: readonly string[] } }) => WebSocket\n return new BunWebSocket(options.url, { ...(headers ? { headers } : {}), protocols, ...(ca ? { tls: { ca } } : {}) })\n }\n return new WebSocket(options.url, protocols)\n}\n\n/** The upgrade took longer than `openTimeoutMs`: nothing answered, so there is no refusal to ask about. */\nclass WsOpenTimeoutError extends Error {\n constructor(url: string, timeoutMs: number) {\n super(`WebSocket connection to ${displayHostUrl(url)} timed out after ${timeoutMs} ms.`)\n this.name = 'WsOpenTimeoutError'\n }\n}\n\nfunction abortError(signal: AbortSignal): Error {\n return signal.reason instanceof Error ? signal.reason : new DOMException('The connect was aborted.', 'AbortError')\n}\n\n/** Resolves on `open`; rejects on failure, timeout or abort (closing the socket). */\nfunction opened(ws: WebSocket, url: string, timeoutMs: number, signal: AbortSignal | undefined): Promise<void> {\n return new Promise((resolve, reject) => {\n const done = new AbortController()\n let timer: ReturnType<typeof setTimeout> | undefined\n const settle = (err?: Error): void => {\n if (done.signal.aborted)\n return\n done.abort()\n clearTimeout(timer)\n if (!err)\n return resolve()\n ws.close()\n reject(err)\n }\n const fail = (detail: string) => () => settle(new Error(`WebSocket connection to ${displayHostUrl(url)} failed${detail}.`))\n ws.addEventListener('open', () => settle(), { signal: done.signal })\n ws.addEventListener('error', fail(''), { signal: done.signal })\n ws.addEventListener('close', event => fail(` (close ${event.code}${event.reason ? `: ${event.reason}` : ''})`)(), { signal: done.signal })\n signal?.addEventListener('abort', () => settle(abortError(signal)), { signal: done.signal })\n timer = setTimeout(() => settle(new WsOpenTimeoutError(url, timeoutMs)), timeoutMs)\n })\n}\n\n/** Why an upgrade failed, asked over plain HTTP: a {@link HostAuthError} for 401 / 403, a {@link HostBusyError} for 429, a {@link HostRedirectError} for 3xx, else `null`. */\nasync function refusal(options: WsClientOptions): Promise<Error | null> {\n try {\n const url = new URL(options.url)\n url.protocol = url.protocol === 'wss:' ? 'https:' : 'http:'\n const timeout = AbortSignal.timeout(5000)\n const ca = bunCa(options)\n const response = await fetch(url, {\n headers: options.token ? { Authorization: `Bearer ${options.token}` } : {},\n redirect: 'manual',\n signal: options.signal ? AbortSignal.any([options.signal, timeout]) : timeout,\n // Bun's fetch extension, as for the socket.\n ...(ca ? { tls: { ca } } : {}),\n } as RequestInit)\n void response.body?.cancel().catch(() => {})\n if (response.type === 'opaqueredirect' || (response.status >= 300 && response.status < 400))\n return new HostRedirectError(options.url, response.status)\n if (response.status === 429)\n return new HostBusyError(options.url)\n if (response.status !== 401 && response.status !== 403)\n return null\n const reason = response.headers.get(WS_REFUSAL_HEADER)\n return new HostAuthError(options.url, response.status, response.status === 403 && isWsRefusalReason(reason) ? reason : undefined)\n }\n catch {\n return null\n }\n}\n\n/** Close a connection whose host is not the one expected, and say so. */\nfunction checkIdentity(client: IpcClient, options: WsClientOptions): IpcClient {\n if (options.expectHostId === undefined)\n return client\n const ref = hostRefOf(client.hello)\n if (ref?.id === options.expectHostId)\n return client\n client.close()\n throw new HostIdentityError(displayHostUrl(options.url), ref?.name)\n}\n\n/**\n * Connects to a remote zidane server over WebSocket and completes the `ipc.hello` handshake.\n * A refused upgrade rejects with {@link HostAuthError} for a 401 or 403, and {@link HostBusyError} for a 429. A hello from another host than `expectHostId` rejects with `HostIdentityError`. A version mismatch rejects with {@link IpcVersionMismatchError} and leaves the server running.\n * @param options - Server URL, token and connection settings.\n * @returns A typed client.\n * @example\n * ```ts\n * import { connectWsClient } from 'zidane/ipc/remote'\n *\n * const client = await connectWsClient({\n * url: 'wss://zidane.example.com/',\n * token: process.env.ZIDANE_HOST_TOKEN,\n * })\n * const sessions = await client.request('sessions.list', {})\n * console.log(sessions.length)\n * client.close()\n * ```\n */\nexport async function connectWsClient(options: WsClientOptions): Promise<IpcClient> {\n const { signal } = options\n signal?.throwIfAborted()\n const ws = createSocket(options)\n ws.binaryType = 'arraybuffer'\n try {\n await opened(ws, options.url, options.openTimeoutMs ?? WS_OPEN_TIMEOUT_MS, signal)\n }\n catch (err) {\n if (signal?.aborted || err instanceof WsOpenTimeoutError)\n throw err\n throw (await refusal(options)) ?? err\n }\n\n const signals = createSignalListeners()\n let closed = false\n\n const rpc = createJsonRpcEndpoint({\n send: (json) => {\n try {\n ws.send(json)\n }\n catch {\n // A closing socket: the close handler fails what is pending.\n }\n },\n // The host never sends requests to clients, only notifications; a machine serves them.\n onRequest: async (message) => {\n const serve = options.serve\n if (!serve)\n return errorResponse(message.id, METHOD_NOT_FOUND, 'Clients do not accept requests.')\n try {\n return successResponse(message.id, (await serve.request(message.method, message.params)) ?? null)\n }\n catch (err) {\n const code = (err as { code?: unknown }).code\n return errorResponse(message.id, typeof code === 'number' ? code : -32000, err instanceof Error ? err.message : String(err))\n }\n },\n onNotification: (message) => {\n if (message.method === 'ipc.signal' || !options.serve?.notification)\n return signals.onNotification(message)\n options.serve.notification(message.method, (message as { params?: unknown }).params)\n },\n })\n\n const decoder = new TextDecoder()\n ws.addEventListener('message', (event: MessageEvent) => {\n if (closed)\n return\n rpc.receive(typeof event.data === 'string' ? event.data : decoder.decode(event.data as ArrayBuffer))\n })\n\n /** The host went away (or the connection was given up): fail what is pending, tell the owner. */\n const lost = (): void => {\n if (closed)\n return\n closed = true\n rpc.close()\n options.onClose?.()\n }\n ws.addEventListener('close', lost)\n ws.addEventListener('error', () => {\n // 'close' follows.\n })\n\n const close = (): void => {\n if (closed)\n return\n closed = true\n rpc.close()\n ws.close(1000)\n }\n\n // Aborted mid-handshake: the close fails the pending hello, and the connect rejects with the signal's reason.\n const onAbort = (): void => close()\n signal?.addEventListener('abort', onAbort, { once: true })\n try {\n return checkIdentity(await openIpcClient(\n {\n rpc,\n close,\n abort: () => {\n lost()\n ws.close(1000)\n },\n where: displayHostUrl(options.url),\n },\n signals.listeners,\n {\n ...(options.appVersion ? { appVersion: options.appVersion } : {}),\n drain: 'never',\n buildFence: false,\n heartbeatMs: options.heartbeatMs ?? WS_HEARTBEAT_MS,\n },\n ), options)\n }\n catch (err) {\n throw signal?.aborted ? abortError(signal) : err\n }\n finally {\n signal?.removeEventListener('abort', onAbort)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAiBA,MAAM,MAAM;AAKZ,SAAS,aAAa,MAAwB;CAC5C,IAAI;EACF,OAAO,IAAI,oBAAoB,IAAI,KAAK,CAAC;CAC3C,QACM;EACJ,OAAO,CAAC;CACV;AACF;AAEA,IAAI;;;;;;AAOJ,SAAgB,eAAgC;CAC9C,IAAI,WAAW,KAAA,GAAW;EACxB,MAAM,SAAS,aAAa,QAAQ;EACpC,SAAS,OAAO,WAAW,IAAI,OAAO,CAAC,mBAAG,IAAI,IAAI;GAAC,GAAG,aAAa,SAAS;GAAG,GAAG;GAAQ,GAAG,aAAa,OAAO;EAAC,CAAC,CAAC;CACtH;CACA,OAAO;AACT;;;;;AAMA,SAAgB,0BAAmC;CACjD,MAAM,KAAK,aAAa;CACxB,IAAI,CAAC,MAAM,CAAC,IAAI,4BAA4B,OAAQ,WAAiC,QAAQ,aAC3F,OAAO;CACT,IAAI,yBAAyB,EAAE;CAC/B,OAAO;AACT;;;;;;;;;;;;;;AC5CA,MAAa,iBAAiB;;AAE9B,MAAa,mBAAmB;;;;;;;AA2BhC,MAAa,oBAAoB;AACjC,MAAM,qBAAqB;CAAC;CAAU;CAAsB;CAAmB;AAAO;AAGtF,SAAgB,kBAAkB,OAA0C;CAC1E,OAAO,OAAO,UAAU,Y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AC;;CAGD,MAAM,aAAmB;EACvB,IAAI,QACF;EACF,SAAS;EACT,IAAI,MAAM;EACV,QAAQ,UAAU;CACpB;CACA,GAAG,iBAAiB,SAAS,IAAI;CACjC,GAAG,iBAAiB,eAAe,CAEnC,CAAC;CAED,MAAM,cAAoB;EACxB,IAAI,QACF;EACF,SAAS;EACT,IAAI,MAAM;EACV,GAAG,MAAM,GAAI;CACf;CAGA,MAAM,gBAAsB,MAAM;CAClC,QAAQ,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;CACzD,IAAI;EACF,OAAO,cAAc,MAAM,cACzB;GACE;GACA;GACA,aAAa;IACX,KAAK;IACL,GAAG,MAAM,GAAI;GACf;GACA,OAAO,eAAe,QAAQ,GAAG;EACnC,GACA,QAAQ,WACR;GACE,GAAI,QAAQ,aAAa,EAAE,YAAY,QAAQ,WAAW,IAAI,CAAC;GAC/D,OAAO;GACP,YAAY;GACZ,aAAa,QAAQ,eAAA;EACvB,CACF,GAAG,OAAO;CACZ,SACO,KAAK;EACV,MAAM,QAAQ,UAAU,WAAW,MAAM,IAAI;CAC/C,UACQ;EACN,QAAQ,oBAAoB,SAAS,OAAO;CAC9C;AACF"}
@@ -0,0 +1,182 @@
1
+ import { f as openaiCompat } from "./openai-compat-5HkREis_.js";
2
+ import { i as isOAuthAccessToken, l as resolveOAuthApiKey, o as readAccountOAuthCredential, r as extractRuntimeCredentials, s as readOAuthCredentials } from "./oauth-DRrs-65k.js";
3
+ import { a as imageHttpError, i as imageFromBase64, n as dataUrl, r as imageCount } from "./wire-DH77Z-rr.js";
4
+ import { r as xaiBaseUrl, t as XAI_OAUTH_PROVIDER_ID } from "./xai-6tBTk6CU.js";
5
+ //#region src/providers/images/xai.ts
6
+ /** xAI's Grok Imagine image models. */
7
+ const XAI_IMAGE_MODELS = [{
8
+ id: "grok-imagine-image-2.0",
9
+ name: "Grok Imagine Image 2.0",
10
+ input: ["text", "image"]
11
+ }, {
12
+ id: "grok-imagine-image-quality",
13
+ name: "Grok Imagine Image Quality",
14
+ input: ["text", "image"]
15
+ }];
16
+ /**
17
+ * xAI image generation as a {@link ProviderImages}. Unavailable while
18
+ * `hasCredential` returns false; the bearer itself resolves per request.
19
+ *
20
+ * @param options - Bearer resolver, credential check, endpoint and test overrides.
21
+ * @param options.resolveKey - Returns the API key or a fresh OAuth access token.
22
+ * @param options.hasCredential - Whether an API key or a stored sign-in exists. No network.
23
+ * @param options.baseURL - API base URL, for example `https://api.x.ai/v1`.
24
+ * @param options.headers - Extra request headers.
25
+ * @param options.fetch - Fetch override, for tests.
26
+ */
27
+ function xaiImages(options) {
28
+ const doFetch = options.fetch ?? fetch;
29
+ return {
30
+ defaultModel: XAI_IMAGE_MODELS[0].id,
31
+ models: XAI_IMAGE_MODELS,
32
+ availability: () => options.hasCredential() ? { available: true } : {
33
+ available: false,
34
+ reason: "xAI image generation needs an xAI API key (XAI_API_KEY) or a SuperGrok sign-in."
35
+ },
36
+ async generate(request, signal) {
37
+ const references = request.references ?? [];
38
+ if (references.length > 1) throw new Error("xAI image editing takes one reference image. Pass one, or use an OpenRouter, OpenAI or Gemini model for several.");
39
+ const key = await options.resolveKey();
40
+ const edit = references[0];
41
+ const res = await doFetch(`${options.baseURL}/images/${edit ? "edits" : "generations"}`, {
42
+ method: "POST",
43
+ headers: {
44
+ ...options.headers,
45
+ "authorization": `Bearer ${key}`,
46
+ "content-type": "application/json"
47
+ },
48
+ body: JSON.stringify({
49
+ model: request.model,
50
+ prompt: request.prompt,
51
+ n: imageCount(request.count),
52
+ response_format: "b64_json",
53
+ ...request.aspectRatio ? { aspect_ratio: request.aspectRatio } : {},
54
+ ...edit ? { image: {
55
+ url: dataUrl(edit),
56
+ type: "image_url"
57
+ } } : {}
58
+ }),
59
+ signal
60
+ });
61
+ if (!res.ok) throw await imageHttpError("xAI", res);
62
+ const json = await res.json();
63
+ const images = (json.data ?? []).flatMap((item) => item.b64_json ? [imageFromBase64(item.b64_json, "image/jpeg")] : []);
64
+ if (images.length === 0) throw new Error("xAI returned no image.");
65
+ const revised = json.data?.find((item) => item.revised_prompt)?.revised_prompt;
66
+ return {
67
+ images,
68
+ model: request.model,
69
+ ...revised ? { text: `Revised prompt: ${revised}` } : {}
70
+ };
71
+ }
72
+ };
73
+ }
74
+ //#endregion
75
+ //#region src/providers/xai.ts
76
+ const DEFAULT_MODEL = "grok-4.6";
77
+ /**
78
+ * xAI Grok provider — supports both a static API key (`XAI_API_KEY`) and the
79
+ * SuperGrok / X Premium+ OAuth subscription.
80
+ *
81
+ * Both auth modes hit the same OpenAI-compatible endpoint (`https://api.x.ai/v1`
82
+ * unless `XAI_BASE_URL` or `PI_XAI_BASE_URL` overrides it),
83
+ * so the wire handling is entirely {@link openaiCompat}. The only difference is
84
+ * the bearer:
85
+ *
86
+ * - **API key**: `XAI_API_KEY` (or `params.apiKey`) → used verbatim.
87
+ * - **OAuth**: no static key → {@link resolveOAuthApiKey} resolves + lazily
88
+ * refreshes the stored `xai-oauth` token on every turn.
89
+ *
90
+ * `resolveOAuthApiKey` unifies the two: a real API key in `XAI_API_KEY` is
91
+ * returned as-is, while an OAuth access token (or no env value at all) falls
92
+ * through to the refreshable stored credentials. So this single factory serves
93
+ * both paths without branching at construction time.
94
+ *
95
+ * @param params - API key or OAuth credentials, default model, capabilities and extra headers.
96
+ *
97
+ * @example
98
+ * ```ts
99
+ * import { createAgent } from 'zidane'
100
+ * import { xai } from 'zidane/providers/xai'
101
+ *
102
+ * const agent = createAgent({
103
+ * provider: xai({ apiKey: process.env.XAI_API_KEY }),
104
+ * })
105
+ * await agent.run({ prompt: 'Say hello.' })
106
+ * ```
107
+ */
108
+ function xai(params) {
109
+ const defaultModel = params?.defaultModel || DEFAULT_MODEL;
110
+ const baseURL = xaiBaseUrl();
111
+ const capabilities = params?.capabilities ?? {
112
+ vision: true,
113
+ imageInToolResult: false
114
+ };
115
+ const baseCredentials = extractRuntimeCredentials(params);
116
+ let runtimeCredentials = baseCredentials;
117
+ const staticKey = params?.apiKey ?? (params?.account ? void 0 : process.env.XAI_API_KEY);
118
+ const isOAuth = baseCredentials !== void 0 || !staticKey || isOAuthAccessToken(staticKey);
119
+ /**
120
+ * Build the openai-compat delegate for a resolved bearer. Cheap — the factory
121
+ * only wires closures — so we re-create it per turn with the freshly resolved
122
+ * (possibly refreshed) OAuth token rather than baking a stale key in once.
123
+ */
124
+ function delegateFor(apiKey) {
125
+ return openaiCompat({
126
+ name: "xai",
127
+ label: "xAI",
128
+ apiKey,
129
+ baseURL,
130
+ defaultModel,
131
+ capabilities,
132
+ extraHeaders: params?.extraHeaders
133
+ });
134
+ }
135
+ const skeleton = delegateFor("placeholder-resolved-at-stream");
136
+ /** The bearer for one request: the static key, or the OAuth access token, refreshed when expired. */
137
+ function resolveBearer(callbacks) {
138
+ return resolveOAuthApiKey({
139
+ provider: "xai",
140
+ providerId: XAI_OAUTH_PROVIDER_ID,
141
+ params: runtimeCredentials ? {
142
+ ...params,
143
+ ...runtimeCredentials
144
+ } : params,
145
+ envKey: "XAI_API_KEY",
146
+ missingError: "No xAI credentials found. Set XAI_API_KEY or run `bun run auth --xai` first.",
147
+ refreshError: (reason) => `xAI OAuth token refresh failed. Run \`bun run auth --xai\` again. ${reason}`
148
+ }, {
149
+ ...callbacks,
150
+ async onOAuthRefresh(ctx) {
151
+ if (ctx.source === "params") runtimeCredentials = {
152
+ access: ctx.credentials.access,
153
+ refresh: ctx.credentials.refresh,
154
+ expires: ctx.credentials.expires
155
+ };
156
+ await callbacks?.onOAuthRefresh?.(ctx);
157
+ }
158
+ });
159
+ }
160
+ return {
161
+ ...skeleton,
162
+ name: "xai",
163
+ meta: {
164
+ ...skeleton.meta,
165
+ defaultModel,
166
+ isOAuth
167
+ },
168
+ images: xaiImages({
169
+ resolveKey: () => resolveBearer(),
170
+ hasCredential: () => Boolean(staticKey || runtimeCredentials || (params?.account ? readAccountOAuthCredential("xai-oauth", params.account) : readOAuthCredentials()["xai-oauth"])),
171
+ baseURL,
172
+ ...params?.extraHeaders ? { headers: params.extraHeaders } : {}
173
+ }),
174
+ async stream(options, callbacks) {
175
+ return delegateFor(await resolveBearer(callbacks)).stream(options, callbacks);
176
+ }
177
+ };
178
+ }
179
+ //#endregion
180
+ export { XAI_IMAGE_MODELS as n, xai as t };
181
+
182
+ //# sourceMappingURL=xai-CStTwCV2.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"xai-CStTwCV2.js","names":[],"sources":["../src/providers/images/xai.ts","../src/providers/xai.ts"],"sourcesContent":["/**\n * xAI Grok Imagine on the xAI API: `POST /v1/images/generations`, or\n * `POST /v1/images/edits` with one reference image as a `data:` URL. Works\n * with an API key or the SuperGrok / X Premium+ sign-in: `resolveKey`\n * returns whichever bearer the chat provider would use.\n */\n\nimport type { ImageModelInfo, ProviderImages } from './types'\nimport type { ImageFetch } from './wire'\nimport { dataUrl, imageCount, imageFromBase64, imageHttpError } from './wire'\n\n/** xAI's Grok Imagine image models. */\nexport const XAI_IMAGE_MODELS: readonly ImageModelInfo[] = [\n { id: 'grok-imagine-image-2.0', name: 'Grok Imagine Image 2.0', input: ['text', 'image'] },\n { id: 'grok-imagine-image-quality', name: 'Grok Imagine Image Quality', input: ['text', 'image'] },\n]\n\ninterface ImagesResponse {\n data?: Array<{ b64_json?: string, revised_prompt?: string }>\n}\n\n/**\n * xAI image generation as a {@link ProviderImages}. Unavailable while\n * `hasCredential` returns false; the bearer itself resolves per request.\n *\n * @param options - Bearer resolver, credential check, endpoint and test overrides.\n * @param options.resolveKey - Returns the API key or a fresh OAuth access token.\n * @param options.hasCredential - Whether an API key or a stored sign-in exists. No network.\n * @param options.baseURL - API base URL, for example `https://api.x.ai/v1`.\n * @param options.headers - Extra request headers.\n * @param options.fetch - Fetch override, for tests.\n */\nexport function xaiImages(options: { resolveKey: () => Promise<string>, hasCredential: () => boolean, baseURL: string, headers?: Record<string, string>, fetch?: ImageFetch }): ProviderImages {\n const doFetch = options.fetch ?? fetch\n return {\n defaultModel: XAI_IMAGE_MODELS[0]!.id,\n models: XAI_IMAGE_MODELS,\n availability: () => options.hasCredential()\n ? { available: true }\n : { available: false, reason: 'xAI image generation needs an xAI API key (XAI_API_KEY) or a SuperGrok sign-in.' },\n async generate(request, signal) {\n const references = request.references ?? []\n if (references.length > 1)\n throw new Error('xAI image editing takes one reference image. Pass one, or use an OpenRouter, OpenAI or Gemini model for several.')\n const key = await options.resolveKey()\n const edit = references[0]\n const res = await doFetch(`${options.baseURL}/images/${edit ? 'edits' : 'generations'}`, {\n method: 'POST',\n headers: { ...options.headers, 'authorization': `Bearer ${key}`, 'content-type': 'application/json' },\n body: JSON.stringify({\n model: request.model,\n prompt: request.prompt,\n n: imageCount(request.count),\n response_format: 'b64_json',\n ...(request.aspectRatio ? { aspect_ratio: request.aspectRatio } : {}),\n ...(edit ? { image: { url: dataUrl(edit), type: 'image_url' } } : {}),\n }),\n signal,\n })\n if (!res.ok)\n throw await imageHttpError('xAI', res)\n const json = await res.json() as ImagesResponse\n // Grok Imagine returns JPEG; the bytes decide the type.\n const images = (json.data ?? []).flatMap(item => item.b64_json ? [imageFromBase64(item.b64_json, 'image/jpeg')] : [])\n if (images.length === 0)\n throw new Error('xAI returned no image.')\n const revised = json.data?.find(item => item.revised_prompt)?.revised_prompt\n return { images, model: request.model, ...(revised ? { text: `Revised prompt: ${revised}` } : {}) }\n },\n }\n}\n","import type { Provider, ProviderCapabilities, StreamCallbacks, StreamOptions, TurnResult } from '.'\nimport type { OAuthParams } from './oauth'\nimport { XAI_OAUTH_PROVIDER_ID, xaiBaseUrl } from '../chat/oauth-page/xai'\nimport { xaiImages } from './images/xai'\nimport { extractRuntimeCredentials, isOAuthAccessToken, readAccountOAuthCredential, readOAuthCredentials, resolveOAuthApiKey } from './oauth'\nimport { openaiCompat } from './openai-compat'\n\nconst DEFAULT_MODEL = 'grok-4.6'\n\n/** Options for {@link xai}. */\nexport interface XaiParams extends OAuthParams {\n /**\n * Model used when a request does not set one.\n * @default 'grok-4.6'\n */\n defaultModel?: string\n /**\n * Provider capability flags. Grok models are vision-capable; default\n * `{ vision: true, imageInToolResult: false }`. Override for text-only\n * deployments.\n */\n capabilities?: ProviderCapabilities\n /** Extra HTTP headers sent on every request. */\n extraHeaders?: Record<string, string>\n}\n\n/**\n * xAI Grok provider — supports both a static API key (`XAI_API_KEY`) and the\n * SuperGrok / X Premium+ OAuth subscription.\n *\n * Both auth modes hit the same OpenAI-compatible endpoint (`https://api.x.ai/v1`\n * unless `XAI_BASE_URL` or `PI_XAI_BASE_URL` overrides it),\n * so the wire handling is entirely {@link openaiCompat}. The only difference is\n * the bearer:\n *\n * - **API key**: `XAI_API_KEY` (or `params.apiKey`) → used verbatim.\n * - **OAuth**: no static key → {@link resolveOAuthApiKey} resolves + lazily\n * refreshes the stored `xai-oauth` token on every turn.\n *\n * `resolveOAuthApiKey` unifies the two: a real API key in `XAI_API_KEY` is\n * returned as-is, while an OAuth access token (or no env value at all) falls\n * through to the refreshable stored credentials. So this single factory serves\n * both paths without branching at construction time.\n *\n * @param params - API key or OAuth credentials, default model, capabilities and extra headers.\n *\n * @example\n * ```ts\n * import { createAgent } from 'zidane'\n * import { xai } from 'zidane/providers/xai'\n *\n * const agent = createAgent({\n * provider: xai({ apiKey: process.env.XAI_API_KEY }),\n * })\n * await agent.run({ prompt: 'Say hello.' })\n * ```\n */\nexport function xai(params?: XaiParams): Provider {\n const defaultModel = params?.defaultModel || DEFAULT_MODEL\n const baseURL = xaiBaseUrl()\n const capabilities: ProviderCapabilities = params?.capabilities ?? {\n vision: true,\n imageInToolResult: false,\n }\n const baseCredentials = extractRuntimeCredentials(params)\n let runtimeCredentials = baseCredentials\n\n // Factory-time snapshot for the static `meta.isOAuth` display flag only (the\n // terminal header's `oauth`/`key` badge). The real bearer resolves per turn\n // in `stream`, so this is best-effort, mirroring anthropic's pattern. It's\n // OAuth unless a genuine static API key is present: a `xai-…` key → key mode;\n // runtime OAuth creds, a JWT access token, or no static key (stored creds\n // used) → oauth mode.\n // A pinned account is that account's OAuth grant, whatever the env holds.\n const staticKey = params?.apiKey ?? (params?.account ? undefined : process.env.XAI_API_KEY)\n const isOAuth = baseCredentials !== undefined || !staticKey || isOAuthAccessToken(staticKey)\n\n /**\n * Build the openai-compat delegate for a resolved bearer. Cheap — the factory\n * only wires closures — so we re-create it per turn with the freshly resolved\n * (possibly refreshed) OAuth token rather than baking a stale key in once.\n */\n function delegateFor(apiKey: string): Provider {\n return openaiCompat({\n name: 'xai',\n label: 'xAI',\n apiKey,\n baseURL,\n defaultModel,\n capabilities,\n extraHeaders: params?.extraHeaders,\n })\n }\n\n // A delegate built with a placeholder key supplies the non-stream methods\n // (formatTools, userMessage, message builders, classifyError). Only `stream`\n // resolves the real bearer, so the placeholder never reaches the wire.\n const skeleton = delegateFor('placeholder-resolved-at-stream')\n\n /** The bearer for one request: the static key, or the OAuth access token, refreshed when expired. */\n function resolveBearer(callbacks?: Parameters<typeof resolveOAuthApiKey>[1]): Promise<string> {\n return resolveOAuthApiKey(\n {\n provider: 'xai',\n providerId: XAI_OAUTH_PROVIDER_ID,\n params: runtimeCredentials ? { ...params, ...runtimeCredentials } : params,\n envKey: 'XAI_API_KEY',\n missingError: 'No xAI credentials found. Set XAI_API_KEY or run `bun run auth --xai` first.',\n refreshError: reason => `xAI OAuth token refresh failed. Run \\`bun run auth --xai\\` again. ${reason}`,\n },\n {\n ...callbacks,\n async onOAuthRefresh(ctx) {\n // Keep param-sourced credentials current so a long-lived provider\n // instance reuses the rotated token instead of re-refreshing.\n if (ctx.source === 'params') {\n runtimeCredentials = {\n access: ctx.credentials.access,\n refresh: ctx.credentials.refresh,\n expires: ctx.credentials.expires,\n }\n }\n await callbacks?.onOAuthRefresh?.(ctx)\n },\n },\n )\n }\n\n return {\n ...skeleton,\n name: 'xai',\n // Reuse the delegate's normalized capability flags (openaiCompat fills the\n // audio/video/documents defaults) so the advertised shape matches the wire.\n meta: { ...skeleton.meta, defaultModel, isOAuth },\n images: xaiImages({\n resolveKey: () => resolveBearer(),\n hasCredential: () => Boolean(staticKey || runtimeCredentials || (params?.account\n ? readAccountOAuthCredential(XAI_OAUTH_PROVIDER_ID, params.account)\n : readOAuthCredentials()[XAI_OAUTH_PROVIDER_ID])),\n baseURL,\n ...(params?.extraHeaders ? { headers: params.extraHeaders } : {}),\n }),\n\n async stream(options: StreamOptions, callbacks: StreamCallbacks): Promise<TurnResult> {\n const apiKey = await resolveBearer(callbacks)\n return delegateFor(apiKey).stream(options, callbacks)\n },\n }\n}\n"],"mappings":";;;;;;AAYA,MAAa,mBAA8C,CACzD;CAAE,IAAI;CAA0B,MAAM;CAA0B,OAAO,CAAC,QAAQ,OAAO;AAAE,GACzF;CAAE,IAAI;CAA8B,MAAM;CAA8B,OAAO,CAAC,QAAQ,OAAO;AAAE,CACnG;;;;;;;;;;;;AAiBA,SAAgB,UAAU,SAAqK;CAC7L,MAAM,UAAU,QAAQ,SAAS;CACjC,OAAO;EACL,cAAc,iBAAiB,EAAE,CAAE;EACnC,QAAQ;EACR,oBAAoB,QAAQ,cAAc,IACtC,EAAE,WAAW,KAAK,IAClB;GAAE,WAAW;GAAO,QAAQ;EAAkF;EAClH,MAAM,SAAS,SAAS,QAAQ;GAC9B,MAAM,aAAa,QAAQ,cAAc,CAAC;GAC1C,IAAI,WAAW,SAAS,GACtB,MAAM,IAAI,MAAM,kHAAkH;GACpI,MAAM,MAAM,MAAM,QAAQ,WAAW;GACrC,MAAM,OAAO,WAAW;GACxB,MAAM,MAAM,MAAM,QAAQ,GAAG,QAAQ,QAAQ,UAAU,OAAO,UAAU,iBAAiB;IACvF,QAAQ;IACR,SAAS;KAAE,GAAG,QAAQ;KAAS,iBAAiB,UAAU;KAAO,gBAAgB;IAAmB;IACpG,MAAM,KAAK,UAAU;KACnB,OAAO,QAAQ;KACf,QAAQ,QAAQ;KAChB,GAAG,WAAW,QAAQ,KAAK;KAC3B,iBAAiB;KACjB,GAAI,QAAQ,cAAc,EAAE,cAAc,QAAQ,YAAY,IAAI,CAAC;KACnE,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,qBAAqB;IAAE,GAAG;IAAQ,GAAG;GAAmB,IAAI;GACpE,QAAQ;GACR,cAAc;GACd,eAAc,WAAU,qEAAqE;EAC/F,GACA;GACE,GAAG;GACH,MAAM,eAAe,KAAK;IAGxB,IAAI,IAAI,WAAW,UACjB,qBAAqB;KACnB,QAAQ,IAAI,YAAY;KACxB,SAAS,IAAI,YAAY;KACzB,SAAS,IAAI,YAAY;IAC3B;IAEF,MAAM,WAAW,iBAAiB,GAAG;GACvC;EACF,CACF;CACF;CAEA,OAAO;EACL,GAAG;EACH,MAAM;EAGN,MAAM;GAAE,GAAG,SAAS;GAAM;GAAc;EAAQ;EAChD,QAAQ,UAAU;GAChB,kBAAkB,cAAc;GAChC,qBAAqB,QAAQ,aAAa,uBAAuB,QAAQ,UACrE,2BAAA,aAAkD,OAAO,OAAO,IAChE,qBAAqB,CAAC,CAAA,aAAwB;GAClD;GACA,GAAI,QAAQ,eAAe,EAAE,SAAS,OAAO,aAAa,IAAI,CAAC;EACjE,CAAC;EAED,MAAM,OAAO,SAAwB,WAAiD;GAEpF,OAAO,YAAY,MADE,cAAc,SAAS,CACnB,CAAC,CAAC,OAAO,SAAS,SAAS;EACtD;CACF;AACF"}
@@ -282,6 +282,7 @@ Built-in tools set their own output size limits, so drop your own `tool:transfor
282
282
  | `multi_edit` | Sequential, best-effort per-hunk edits to one file. A per-step failure does not block siblings. The chat layer owns approval and the `<edit-outcomes>` annotation contract. See `docs/CHAT.md` § Per-edit approval. |
283
283
  | `grep` | Wraps `rg` when present, and falls back to `find` through `exec` otherwise. Skips git-ignored files by default (`gitignore`, default `true`). `head_limit=250`, and `offset` paginates. |
284
284
  | `glob` | Default path intersects the pattern with `git ls-files` so ignored trees are skipped (`gitignore`, default `true`). Falls back to a native scanner otherwise. 20s tool-level timeout. |
285
+ | `generate_image` | `createGenerateImageTool` (`src/tools/generate-image.ts`) over `Provider.images` (`src/providers/images/`: OpenRouter through pi-ai's `openrouter-images` API, OpenAI, Gemini and xAI over HTTP). It saves full-size files and a `<file>.json` record next to each, and returns paths plus a preview capped at 768 px. The chat host adds it through `imageGenerationTools` (`src/chat/image-models.ts`), gated on `Settings.imageGeneration`. `generatedImageKind` records each saved file as a `file` artifact. |
285
286
  | `record_artifact` | The `artifacts` preset tool (`src/tools/record-artifact.ts`). It is the explicit path for artifacts that detection cannot see (background-shell PRs, deployments, issues). Input is `{ kind, uri, label?, meta? }`. It is idempotent per `(kind, uri)`. See `docs/ARTIFACTS.md` § Producers. |
286
287
 
287
288
  ## `StreamEvent.callId` pairing contract
package/docs/ARTIFACTS.md CHANGED
@@ -46,7 +46,7 @@ Tool-driven paths converge on one channel, the reserved `artifacts` key of tool-
46
46
  | Path | How |
47
47
  |---|---|
48
48
  | Tool-result metadata | Any `tool:transform` hook appends `SessionArtifactInput[]` to `ctx.metadata.artifacts`. After the tool settles, the loop normalizes each entry (`normalizeArtifactInput`), canonicalizes `file:` URIs against the execution cwd, and calls `session.addArtifact`. A tool result can carry at most 50 entries. |
49
- | Built-in detectors (`artifactsPreset`) | Detectors key on the command or tool name, never on free text. `gh pr create`, `glab mr create` and `*create_pull_request` produce `pull_request`. `git commit` produces `commit`. `git switch -c`, `checkout -b` and `push -u` produce `branch`. Files are never auto-detected, because a source edit is not a deliverable. `file` artifacts exist only through `record_artifact` or `ctx.artifacts.record`. The preset is composed under every TUI, daemon and GUI profile when `Settings.artifacts` is on. SDK users opt in with `composePresets(artifactsPreset, …)`. |
49
+ | Built-in detectors (`artifactsPreset`) | Detectors key on the command or tool name, never on free text. `gh pr create`, `glab mr create` and `*create_pull_request` produce `pull_request`. `git commit` produces `commit`. `git switch -c`, `checkout -b` and `push -u` produce `branch`. Plain file writes are never auto-detected, because a source edit is not a deliverable. `file` artifacts come from `record_artifact`, `ctx.artifacts.record`, or a `generate_image` call: its detector records each saved image from the result's `Saved:` lines. The preset is composed under every TUI, daemon and GUI profile when `Settings.artifacts` is on. SDK users opt in with `composePresets(artifactsPreset, …)`. |
50
50
  | `record_artifact` tool | The model marks a deliverable: a PR the detectors cannot see (background shell), a deployment or preview URL, an issue it filed, a release, or a generated report or export the user asked for. The tool description says what is worth recording and what is not. Source edits, scratch files and logs are not artifacts. The input is `{ kind, uri, label?, meta? }`. The preset's detector reads the input and emits it. |
51
51
  | `ctx.artifacts.record` (extensions) | Use it for work that never passes through a tool result. An example is a `/` command that runs `gh pr create` via `ctx.workspace.exec`. It stamps the active session (and `runId` when in a run), writes the store (the daemon owns the store when attached) and fans out `artifact:changed`. The git-flow commands `/pr` (PR and created branch) and `/commit` use it with the same locators the detectors emit, so agent-made and command-made rows merge. |
52
52
 
@@ -18,6 +18,8 @@ export default defineExtension({
18
18
 
19
19
  The TUI scans the extension folders every 3 seconds and reloads when a folder appears or goes away. It skips the scan while a run is in progress or a modal is open. Run `/reload` to load the extension at once. The extension then shows up in `Settings → Extensions & Plugins`, where you can turn it on and off. Its keybindings show up in `Settings → Keybindings`.
20
20
 
21
+ The desktop app watches each user and project extension folder it loaded. Saving a source file (`.ts`, `.tsx`, `.js`, `.mjs`, `.cjs` or the root `package.json`) reloads extensions about 300 ms after the last write. A run in progress finishes first. Writes under `node_modules`, dot-folders and data files the extension stores in its folder do not reload. Installed extensions (with `.install.json`) are not watched; update reloads them.
22
+
21
23
  A project extension (under `<project>/`) loads only after you turn on "Load project extensions". See [Project trust](#project-trust).
22
24
 
23
25
  Contents: [Discovery](#discovery), [defineExtension API](#the-defineextension-api), [The ctx surface](#the-ctx-surface), [How it boots](#how-it-boots), [Enabling and disabling](#enabling--disabling), [Installing from GitHub or npm](#installing-from-github--npm), [Collisions](#collisions--precedence), [Hooks, parent versus subagent](#hooks-parent-vs-subagent), [Authoring patterns](#authoring-patterns), [Settings UI](#settings-ui), [Limitations](#limitations--gotchas-v1), [SDK surface](#sdk-surface), [Preset versus extensions](#preset-vs-extensions), [File layout](#file-layout-reference)
@@ -62,7 +64,7 @@ interface ExtensionDefinition {
62
64
  name: string // stable, kebab-case-ish
63
65
  apiVersion?: 1 // omitted means v1
64
66
  displayName?: string
65
- permissions?: readonly ExtensionPermission[] // descriptive, not a sandbox
67
+ permissions?: readonly ExtensionPermission[] // descriptive, not a sandbox; 'ipc' and 'mcp:call' gate ctx.bus / ctx.mcp
66
68
  capabilities?: readonly ExtensionCapability[] // shown before setup runs
67
69
  version?: string
68
70
  description?: string
@@ -77,7 +79,7 @@ The registry catches errors thrown inside `setup` and shows them on the extensio
77
79
 
78
80
  ### Zero-import alternative
79
81
 
80
- Compiled `zidane-tui` binaries do not expose their bundled `node_modules/zidane` to dynamic imports outside the bundle. For binaries, drop the `import`. The loader accepts a plain object:
82
+ `import { defineExtension } from 'zidane'` works on every host: the TUI, compiled binaries, the desktop app and headless hosts all map `zidane` to their own copy (see [Bare imports](#limitations--gotchas-v1)). `defineExtension` only returns its argument, so the loader also accepts a plain object:
81
83
 
82
84
  ```ts
83
85
  export default {
@@ -1000,13 +1002,15 @@ ctx.registerConfigItem('headroom', {
1000
1002
 
1001
1003
  ## Limitations + gotchas (v1)
1002
1004
 
1003
- - `/reload` applies code edits. Discovery evicts the extension's module graph before it imports, so on-disk edits apply. Module-level state resets with it. The 3-second folder scan does not catch an edit inside an existing folder, so run `/reload` after an edit. `teardown` runs on registry disposal (`/reload`, cwd change, process teardown), not on an in-session enable or disable toggle.
1005
+ - `/reload` applies code edits in the TUI. Discovery evicts the extension's module graph before it imports, so on-disk edits apply, deep imports included. Module-level state resets with it. The TUI's 3-second folder scan does not catch an edit inside an existing folder, so run `/reload` after an edit. The desktop app reloads on save (see [the top of this page](#zidane-extensions)). `teardown` runs on registry disposal (`/reload`, a desktop reload, cwd change, process teardown), not on an in-session enable or disable toggle.
1006
+ - Old code is freed on reload only if `teardown` (or `ctx.signal`) stops what `setup` started. A timer, socket or listener left running keeps the previous version of the extension in memory.
1004
1007
  - Extensions have no sandbox. They run with the host's full Node access. This is the same trust model as `SKILL.md` shell access.
1005
1008
  - An extension cannot declare a dependency on another extension. The authors coordinate.
1006
1009
  - An extension cannot provide compaction. The agent loop runs auto-compaction, and the host runs Compact now through `agent.compact()`.
1007
1010
  - An eager modal `node` loads UI on every host. A modal registered with `node: <Panel/>` builds its UI at `setup()`. That UI joins the import graph of headless hosts too. Use the lazy `node: () => import('./panel')` form. See [Headless-safe UI](#headless-safe-ui).
1008
1011
  - Hooks do not bubble to subagents. See [Hooks, parent versus subagent](#hooks-parent-vs-subagent).
1009
- - Bare imports resolve from the extension's folder, except the host-mapped ones. The host-mapped ones are `zidane`, `zidane/providers`, `zidane/providers/google` and `zidane/oauth`, plus `react` and `@opentui/*` in the TUI. They get the host's live modules, compiled binaries included. Reach pi-ai through zidane (`loadGoogleWireKit`) rather than importing it.
1012
+ - Bare imports resolve from the extension's folder, except the host-mapped ones. The host-mapped ones are `zidane`, `zidane/providers`, `zidane/providers/google` and `zidane/oauth`, plus `react` and `@opentui/*` in the TUI. They get the host's live modules, compiled binaries included. Reach pi-ai through zidane (`loadGoogleWireKit`) rather than importing it. The desktop app maps only the `zidane` ones; `react` and `@opentui/*` resolve from the extension's folder there.
1013
+ - Node hosts (the desktop app's main process) load extensions through [jiti](https://github.com/unjs/jiti), not native `import()`. Bun loads them natively. All TypeScript and TSX syntax works on both, enums included, and so do extensionless relative imports (`./helper`). jiti runs the module graph as CommonJS, so the reload can free old versions. Two differences follow: `import.meta.dirname` and `import.meta.filename` are `undefined` (use `ctx.dir`, or `fileURLToPath(import.meta.url)`), and ESM live bindings between your own files do not update. Dependencies in the extension's `node_modules` load through the same path.
1010
1014
  - Setup runs during boot. Slow imports add time to TUI startup, up to the 10-second import and setup limits. Keep `setup` cheap.
1011
1015
 
1012
1016
  ## SDK surface
@@ -1113,6 +1117,6 @@ Each `<name>/` can ship whatever it needs, such as additional files, `package.js
1113
1117
  - [ ] `export default defineExtension({ name, setup })` (or the zero-import object form)
1114
1118
  - [ ] Optionally add `extension.json` with `apiVersion: 1`, `capabilities`, `permissions`
1115
1119
  - [ ] Register what you need with `ctx.*` inside `setup`
1116
- - [ ] Run `/reload`, or wait 3 seconds for a new folder
1120
+ - [ ] Run `/reload` or wait 3 seconds for a new folder (TUI). The desktop app reloads on save
1117
1121
  - [ ] Turn it on or off in `Settings → Extensions & Plugins`
1118
1122
  - [ ] If you want different defaults, rebind any contributed keybindings in `~/.zidane/keybindings.json`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zidane",
3
- "version": "8.2.1",
3
+ "version": "8.2.3",
4
4
  "description": "an agent that goes straight to the goal",
5
5
  "type": "module",
6
6
  "private": false,
@@ -323,6 +323,7 @@
323
323
  "chalk": "^5.6.2",
324
324
  "fzf": "^0.5.2",
325
325
  "hookable": "^6.1.2",
326
+ "jiti": "^2.7.0",
326
327
  "marked": "18.0.9",
327
328
  "openai": "7.19.0",
328
329
  "partial-json": "0.1.7"
@@ -412,7 +413,6 @@
412
413
  "dockerode": "^5.0.1",
413
414
  "e2b": "^2.53.1",
414
415
  "eslint": "^10.12.0",
415
- "jiti": "^2.7.0",
416
416
  "quickjs-wasi": "3.6.2",
417
417
  "react": "^19.3.0",
418
418
  "tar-stream": "^3.2.2",