zidane 9.1.9 → 9.1.13

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 (74) hide show
  1. package/dist/{acp-Bha_yCgU.js → acp-Cz5mFUjB.js} +3 -3
  2. package/dist/{acp-Bha_yCgU.js.map → acp-Cz5mFUjB.js.map} +1 -1
  3. package/dist/acp-cli.js +4 -4
  4. package/dist/acp.js +1 -1
  5. package/dist/{auth-store-port-BvxVXx9g.js → auth-store-port-CDJa8Q8U.js} +2 -2
  6. package/dist/{auth-store-port-BvxVXx9g.js.map → auth-store-port-CDJa8Q8U.js.map} +1 -1
  7. package/dist/{auto-update-restart-CF3uPnr4.js → auto-update-restart-B4pU7Qgf.js} +10 -10
  8. package/dist/{auto-update-restart-CF3uPnr4.js.map → auto-update-restart-B4pU7Qgf.js.map} +1 -1
  9. package/dist/chat.js +9 -9
  10. package/dist/{cli-shared-C17TUz6H.js → cli-shared-BVtiiICW.js} +3 -3
  11. package/dist/{cli-shared-C17TUz6H.js.map → cli-shared-BVtiiICW.js.map} +1 -1
  12. package/dist/{credentials-BZP-MgtZ.js → credentials-axv5VvMR.js} +2 -2
  13. package/dist/{credentials-BZP-MgtZ.js.map → credentials-axv5VvMR.js.map} +1 -1
  14. package/dist/daemon-cli.js +2 -2
  15. package/dist/{discovery-Czp7bZZP.js → discovery-D7qVZWzq.js} +4 -4
  16. package/dist/{discovery-Czp7bZZP.js.map → discovery-D7qVZWzq.js.map} +1 -1
  17. package/dist/{engine-CDuOhwbt.js → engine-DjM5NPIf.js} +3 -3
  18. package/dist/{engine-CDuOhwbt.js.map → engine-DjM5NPIf.js.map} +1 -1
  19. package/dist/{executor-CoHqHsCp.js → executor-DlW7qAeN.js} +2 -2
  20. package/dist/{executor-CoHqHsCp.js.map → executor-DlW7qAeN.js.map} +1 -1
  21. package/dist/extensions/testing.js +2 -2
  22. package/dist/{extensions-BEaWxX4e.js → extensions-D7DeZNpn.js} +6 -6
  23. package/dist/{extensions-BEaWxX4e.js.map → extensions-D7DeZNpn.js.map} +1 -1
  24. package/dist/extensions.js +5 -5
  25. package/dist/{google-Bzt7uvy9.js → google-D1zjAViO.js} +2 -2
  26. package/dist/{google-Bzt7uvy9.js.map → google-D1zjAViO.js.map} +1 -1
  27. package/dist/{host-DkqB2P7L.js → host-Ds3RDlG5.js} +9 -9
  28. package/dist/{host-DkqB2P7L.js.map → host-Ds3RDlG5.js.map} +1 -1
  29. package/dist/{host-signals-Ca_oUeYl.js → host-signals-C8x5Yso0.js} +5 -5
  30. package/dist/{host-signals-Ca_oUeYl.js.map → host-signals-C8x5Yso0.js.map} +1 -1
  31. package/dist/{host-version-BwON7XSr.js → host-version-BGZumnpZ.js} +2 -2
  32. package/dist/{host-version-BwON7XSr.js.map → host-version-BGZumnpZ.js.map} +1 -1
  33. package/dist/index.js +5 -5
  34. package/dist/ipc/remote.js +3 -3
  35. package/dist/{ipc-Dlqz_xIe.js → ipc-DGfuNEfR.js} +4 -4
  36. package/dist/{ipc-Dlqz_xIe.js.map → ipc-DGfuNEfR.js.map} +1 -1
  37. package/dist/ipc.js +4 -4
  38. package/dist/{links-B5Dz7jku.js → links-D_1RhPh5.js} +8 -8
  39. package/dist/{links-B5Dz7jku.js.map → links-D_1RhPh5.js.map} +1 -1
  40. package/dist/{loaded-entry-BGN69Fns.js → loaded-entry-CLva6GQT.js} +2 -2
  41. package/dist/{loaded-entry-BGN69Fns.js.map → loaded-entry-CLva6GQT.js.map} +1 -1
  42. package/dist/{memory-ZWFqa7di.js → memory-CaFXUvQs.js} +15 -15
  43. package/dist/{memory-ZWFqa7di.js.map → memory-CaFXUvQs.js.map} +1 -1
  44. package/dist/{path-display-B3Jeqx9E.js → path-display-ZIWdFaTI.js} +3 -3
  45. package/dist/{path-display-B3Jeqx9E.js.map → path-display-ZIWdFaTI.js.map} +1 -1
  46. package/dist/providers/google.js +1 -1
  47. package/dist/{providers-ChifjOYS.js → providers-CsYrxuX1.js} +2 -2
  48. package/dist/{providers-ChifjOYS.js.map → providers-CsYrxuX1.js.map} +1 -1
  49. package/dist/providers.js +1 -1
  50. package/dist/{registry-mmAX5qBS.js → registry-BY45AOA-.js} +2 -2
  51. package/dist/{registry-mmAX5qBS.js.map → registry-BY45AOA-.js.map} +1 -1
  52. package/dist/{registry-TW3C94iD.js → registry-DTotchq6.js} +2 -2
  53. package/dist/{registry-TW3C94iD.js.map → registry-DTotchq6.js.map} +1 -1
  54. package/dist/{registry-CYEN4C4M.js → registry-Dl6261Xh.js} +2 -2
  55. package/dist/{registry-CYEN4C4M.js.map → registry-Dl6261Xh.js.map} +1 -1
  56. package/dist/{remote-hosts-Ctg9fwQY.js → remote-hosts-usqMiMbs.js} +4 -4
  57. package/dist/{remote-hosts-Ctg9fwQY.js.map → remote-hosts-usqMiMbs.js.map} +1 -1
  58. package/dist/{setting-DPim5iCP.js → setting-DzTMJIV3.js} +2 -2
  59. package/dist/{setting-DPim5iCP.js.map → setting-DzTMJIV3.js.map} +1 -1
  60. package/dist/{settings-keys-BIWy4T_0.js → settings-keys-DDrfnBHi.js} +2 -2
  61. package/dist/{settings-keys-BIWy4T_0.js.map → settings-keys-DDrfnBHi.js.map} +1 -1
  62. package/dist/{system-freeze-CEuTQzNu.js → system-freeze-CY4Hc9WX.js} +2 -2
  63. package/dist/{system-freeze-CEuTQzNu.js.map → system-freeze-CY4Hc9WX.js.map} +1 -1
  64. package/dist/tui.js +15 -15
  65. package/dist/{version-CU8ppdCQ.js → version-Bu3Nc8-U.js} +2 -2
  66. package/dist/{version-CU8ppdCQ.js.map → version-Bu3Nc8-U.js.map} +1 -1
  67. package/dist/{wire-GwOPpxJg.js → wire-BKcREhuL.js} +2 -2
  68. package/dist/{wire-GwOPpxJg.js.map → wire-BKcREhuL.js.map} +1 -1
  69. package/dist/{ws-CqlZkB4w.js → ws-DriNRyP-.js} +4 -4
  70. package/dist/{ws-CqlZkB4w.js.map → ws-DriNRyP-.js.map} +1 -1
  71. package/dist/{ws-client-Bn_asPwE.js → ws-client-PZdbO0fj.js} +2 -2
  72. package/dist/{ws-client-Bn_asPwE.js.map → ws-client-PZdbO0fj.js.map} +1 -1
  73. package/docs/RELEASE.md +1 -1
  74. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"wire-GwOPpxJg.js","names":[],"sources":["../src/extensions/settings/domain.ts","../src/extensions/rpc/wire.ts"],"sourcesContent":["/**\n * The extension settings domain: `ctx.settings` for one extension, plus the\n * host-side surface Settings UIs use (write, actions, wire format).\n *\n * Values resolve session, then project, then user, then the declarative\n * config entry, then the default. A stored value that fails the setting's\n * checks is skipped, so the next layer answers.\n * Secret strings never sit in a settings layer: they live behind\n * {@link SettingsSecretPort} (the auth store) and take the user layer's place.\n */\n\nimport type { Disposable } from '../api/core'\nimport type { ActionSettingContext, ActionSettingStatus, ActionSettingStatusContext, SettingScope, SettingsDomain, SettingsSchema } from '../api/settings'\nimport type { ExtensionConfigActionStatus, ExtensionConfigValue } from '../config'\nimport type { ExtensionActionRunResult, ExtensionActionSummary } from '../config-actions'\nimport type { DomainDeps } from '../runtime/deps'\nimport type { StoredSettingValue, ValidateRunner, ValueSetting } from './validate'\nimport type { WireSettings } from './wire'\nimport { DisposedError } from '../api/core'\nimport { checkSettingValue, isValueSetting, normalizeSettingValue, settingDefault, settingScopes, settingsForDefinition } from './validate'\nimport { toWireActionStatus, toWireSettings, toWireValue } from './wire'\n\n/** A stored settings layer: a scope the user writes, or the declarative config entry. */\nexport type SettingsLayer = SettingScope | 'config'\n\n/** The auth store, as the settings domain sees it. Keys are per extension. */\nexport interface SettingsSecretPort {\n /** The stored secret. Synchronous: hosts read from a cache loaded before setup. */\n get: (extensionId: string, key: string) => string | undefined\n /** Stores the secret, or removes it when `value` is `undefined`. */\n set: (extensionId: string, key: string, value: string | undefined) => void | Promise<void>\n}\n\n/**\n * What a host provides to the settings domain. One port may serve every\n * extension: each call names the extension.\n */\nexport interface SettingsPort {\n /**\n * The values stored in one layer for the extension, by key. Synchronous:\n * hosts read from a cache. `sessionId` is set for the `session` layer.\n * Values are raw; the domain checks them.\n */\n read: (extensionId: string, layer: SettingsLayer, sessionId?: string) => Readonly<Record<string, unknown>> | undefined\n /** Stores a value in a user-writable scope, or clears it when `value` is `undefined`. */\n write: (extensionId: string, scope: SettingScope, key: string, value: StoredSettingValue | undefined, sessionId?: string) => void | Promise<void>\n /** Calls `listener` after any layer of the extension changed. Returns the unsubscribe. Optional: without it only writes made through the domain notify. */\n subscribe?: (extensionId: string, listener: () => void) => () => void\n /** Where secret strings live. */\n secrets: SettingsSecretPort\n}\n\n/** Which layer an effective value came from. `secret` is the auth store. */\nexport type SettingSource = SettingsLayer | 'secret' | 'default'\n\n/** A refused write. */\nexport class SettingsWriteError extends Error {\n /**\n * @param key - The setting.\n * @param reason - Why it was refused.\n */\n constructor(readonly key: string, readonly reason: string) {\n super(`setting \"${key}\": ${reason}`)\n this.name = 'SettingsWriteError'\n }\n}\n\n/** Options of a host-side write. */\nexport interface SettingsWriteOptions {\n /** The scope to write. Ignored for secrets, which always go to the auth store. */\n scope: SettingScope\n /** Required for the `session` scope. */\n sessionId?: string\n}\n\n/** The settings domain of one extension. */\nexport interface SettingsDomainInstance<S extends SettingsSchema = SettingsSchema> {\n /** `ctx.settings`: only `get`, `onChange` and `locked`. */\n readonly api: SettingsDomain<S>\n /** The cleaned schema. */\n readonly schema: SettingsSchema\n /** What `settingsForDefinition` dropped from the authored schema. */\n readonly issues: readonly string[]\n /** Where the effective value of `key` comes from, or `undefined` for an unknown or action key. */\n source: (key: string, opts?: { sessionId?: string }) => SettingSource | undefined\n /** Every effective value (secrets included), by key. Keys without a value are left out. */\n values: (opts?: { sessionId?: string }) => Record<string, StoredSettingValue>\n /** Checks a raw value for `key`. Returns an error message, or `undefined` when it would be accepted. */\n check: (key: string, value: unknown) => string | undefined\n /**\n * Writes a value (`undefined` clears it). Secret strings go to the auth\n * store. Throws {@link SettingsWriteError} for an unknown, action or\n * locked key, a scope the setting does not allow, or a value that fails\n * its checks. Listeners are notified when the effective value changed.\n */\n set: (key: string, value: unknown, opts: SettingsWriteOptions) => Promise<void>\n /**\n * What an action's `run` and `status` get besides the signal: `get` reads\n * this extension's effective values, `set` writes like a patch key (user\n * scope, else project; secrets to the auth store) and rejects with\n * {@link SettingsWriteError}. Settings-page actions get the same.\n */\n readonly actionAccess: Omit<ActionSettingContext, 'signal'>\n /** The action rows in wire shape. */\n actions: () => ExtensionActionSummary[]\n /** Runs an action's `status()` through the guard (3 s bound). `undefined`: none, failed, or empty. */\n actionStatus: (key: string) => Promise<ActionSettingStatus | undefined>\n /** Every action status in wire shape, keyed `extension:key`. */\n actionStatuses: () => Promise<Record<string, ExtensionConfigActionStatus>>\n /**\n * Runs an action. Its `patch` is checked per key: accepted values are\n * written (user scope, else project), the rest named in the message. A\n * throw, or a result with tone `error`, rejects with its message. The\n * result's `config` repeats the accepted non-secret values in wire shape\n * for UIs that persist it themselves.\n */\n runAction: (key: string, opts?: { signal?: AbortSignal }) => Promise<ExtensionActionRunResult>\n /** The schema, effective values and locks in the wire format the Settings UIs render. */\n wire: (opts?: { sessionId?: string }) => WireSettings\n}\n\n/** Bound on a passive `status()` probe, as `probeActionStatuses`. */\nconst ACTION_STATUS_TIMEOUT_MS = 3_000\n\nfunction sameValue(a: StoredSettingValue | undefined, b: StoredSettingValue | undefined): boolean {\n if (Array.isArray(a) && Array.isArray(b))\n return a.length === b.length && a.every((v, i) => v === b[i])\n return a === b\n}\n\n/**\n * `onChange` listeners of one extension: one port subscription while any\n * listener lives, each listener told only when its key's effective value\n * changed.\n */\nfunction createWatchers(deps: DomainDeps, port: SettingsPort, get: (key: string) => StoredSettingValue | undefined) {\n const { extensionId, owner, guard } = deps\n interface Watch { key: string, last: StoredSettingValue | undefined, listener: (value: StoredSettingValue | undefined) => void }\n const watches = new Set<Watch>()\n let unsubscribePort: (() => void) | undefined\n\n const recheck = (): void => {\n for (const watch of [...watches]) {\n if (!watches.has(watch))\n continue\n const next = get(watch.key)\n if (sameValue(next, watch.last))\n continue\n watch.last = next\n guard.callSync(`settings.onChange(${watch.key})`, () => watch.listener(next))\n }\n }\n\n const onChange = (key: string, listener: (value: StoredSettingValue | undefined) => void): Disposable => {\n if (owner.disposed)\n throw new DisposedError('settings.onChange')\n const watch: Watch = { key, last: get(key), listener }\n watches.add(watch)\n if (!unsubscribePort && port.subscribe)\n unsubscribePort = port.subscribe(extensionId, recheck)\n let cleanup: Disposable | undefined\n const dispose = (): void => {\n if (!watches.delete(watch))\n return\n cleanup?.dispose()\n if (watches.size === 0 && unsubscribePort) {\n unsubscribePort()\n unsubscribePort = undefined\n }\n }\n cleanup = owner.onCleanup(dispose)\n return { dispose }\n }\n\n return { onChange, recheck }\n}\n\n/**\n * Builds the settings domain of one extension.\n *\n * @param deps - The extension's runtime deps (id, owner, guard, logger).\n * @param port - The host's settings storage and auth store.\n * @param settings - The authored schema (`definition.settings`). Cleaned with `settingsForDefinition`.\n * @returns `api` for `ctx.settings`, and the host surface.\n */\nexport function createSettingsDomain<S extends SettingsSchema = SettingsSchema>(\n deps: DomainDeps,\n port: SettingsPort,\n settings?: S,\n): SettingsDomainInstance<S> {\n const { extensionId, owner, guard, logger } = deps\n const { schema, issues } = settingsForDefinition({ id: extensionId, settings })\n for (const issue of issues)\n logger.warn(`extension settings: ${issue}`, { extension: extensionId })\n\n const runValidate: ValidateRunner = (validate, value) => {\n const out = guard.callSync(`settings.validate`, () => validate(value), { fallback: 'invalid value' })\n return typeof out === 'string' && out.length > 0 ? out : undefined\n }\n\n const valueSetting = (key: string): ValueSetting | undefined => {\n const setting = Object.hasOwn(schema.items, key) ? schema.items[key] : undefined\n return setting && isValueSetting(setting) ? setting : undefined\n }\n\n const isSecret = (setting: ValueSetting): boolean => setting.type === 'string' && setting.secret === true\n\n /** The layer's value for `key` when present and valid. */\n const layerValue = (setting: ValueSetting, key: string, layer: SettingsLayer, sessionId?: string): StoredSettingValue | undefined => {\n const bag = port.read(extensionId, layer, layer === 'session' ? sessionId : undefined)\n if (!bag || !Object.hasOwn(bag, key))\n return undefined\n const raw = bag[key]\n if (raw === undefined || raw === null)\n return undefined\n const value = normalizeSettingValue(setting, raw)\n return checkSettingValue(setting, value, runValidate) === undefined ? value as StoredSettingValue : undefined\n }\n\n const secretValue = (setting: ValueSetting, key: string): StoredSettingValue | undefined => {\n const raw = port.secrets.get(extensionId, key)\n if (raw === undefined)\n return undefined\n return checkSettingValue(setting, raw, runValidate) === undefined ? raw : undefined\n }\n\n const resolve = (key: string, sessionId?: string): { value: StoredSettingValue | undefined, source: SettingSource } | undefined => {\n const setting = valueSetting(key)\n if (!setting)\n return undefined\n const layers: (SettingsLayer | 'secret')[] = isSecret(setting)\n ? ['secret', 'config']\n : sessionId !== undefined ? ['session', 'project', 'user', 'config'] : ['project', 'user', 'config']\n for (const layer of layers) {\n const value = layer === 'secret' ? secretValue(setting, key) : layerValue(setting, key, layer, sessionId)\n if (value !== undefined)\n return { value, source: layer }\n }\n return { value: settingDefault(setting), source: 'default' }\n }\n\n const get = (key: string, sessionId?: string): StoredSettingValue | undefined => resolve(key, sessionId)?.value\n\n const locked = (key: string): boolean => {\n const setting = valueSetting(key)\n return setting !== undefined && layerValue(setting, key, 'config') !== undefined\n }\n\n const { onChange, recheck } = createWatchers(deps, port, key => get(key))\n\n const api: SettingsDomain<S> = Object.freeze({\n get: ((key: string, opts?: { sessionId?: string }) => get(key, opts?.sessionId)) as SettingsDomain<S>['get'],\n onChange: onChange as unknown as SettingsDomain<S>['onChange'],\n locked: ((key: string) => locked(key)) as SettingsDomain<S>['locked'],\n })\n\n const check = (key: string, value: unknown): string | undefined => {\n const setting = valueSetting(key)\n if (!setting)\n return 'unknown setting'\n return checkSettingValue(setting, normalizeSettingValue(setting, value), runValidate)\n }\n\n const set = async (key: string, value: unknown, opts: SettingsWriteOptions): Promise<void> => {\n const setting = valueSetting(key)\n if (!setting)\n throw new SettingsWriteError(key, 'unknown setting')\n if (locked(key))\n throw new SettingsWriteError(key, 'locked by the config file')\n let normalized: StoredSettingValue | undefined\n if (value !== undefined) {\n const candidate = normalizeSettingValue(setting, value)\n const error = checkSettingValue(setting, candidate, runValidate)\n if (error !== undefined)\n throw new SettingsWriteError(key, error)\n normalized = candidate as StoredSettingValue\n }\n if (isSecret(setting)) {\n await port.secrets.set(extensionId, key, normalized as string | undefined)\n }\n else {\n if (!settingScopes(setting).includes(opts.scope))\n throw new SettingsWriteError(key, `cannot be set at the ${opts.scope} scope`)\n if (opts.scope === 'session' && !opts.sessionId)\n throw new SettingsWriteError(key, 'the session scope needs a sessionId')\n await port.write(extensionId, opts.scope, key, normalized, opts.scope === 'session' ? opts.sessionId : undefined)\n }\n recheck()\n }\n\n const values = (opts?: { sessionId?: string }): Record<string, StoredSettingValue> => {\n const out: Record<string, StoredSettingValue> = {}\n for (const key of Object.keys(schema.items)) {\n const value = get(key, opts?.sessionId)\n if (value !== undefined)\n out[key] = value\n }\n return out\n }\n\n /** Where an action's write of `key` goes: the user scope, else project; `undefined` when neither is allowed. Secrets ignore it. */\n const actionScope = (setting: ValueSetting): SettingScope | undefined =>\n isSecret(setting) ? 'user' : settingScopes(setting).find(s => s === 'user' || s === 'project')\n\n const actionAccess: Omit<ActionSettingContext, 'signal'> = Object.freeze({\n get: (key: string) => get(key),\n set: async (key: string, value: unknown) => {\n const setting = valueSetting(key)\n if (!setting)\n throw new SettingsWriteError(key, 'unknown setting')\n const scope = actionScope(setting)\n if (!scope)\n throw new SettingsWriteError(key, 'has neither a user nor a project scope')\n await set(key, value, { scope })\n },\n })\n const statusAccess: ActionSettingStatusContext = Object.freeze({ get: actionAccess.get })\n\n const actionSetting = (key: string) => {\n const setting = Object.hasOwn(schema.items, key) ? schema.items[key] : undefined\n return setting?.type === 'action' ? setting : undefined\n }\n\n const actionStatus = async (key: string): Promise<ActionSettingStatus | undefined> => {\n const status = actionSetting(key)?.status\n if (!status)\n return undefined\n const out = await guard.call(`settings.status(${key})`, () => status(statusAccess), { timeoutMs: ACTION_STATUS_TIMEOUT_MS, fallback: undefined })\n return out && typeof out.text === 'string' && out.text.length > 0 ? out : undefined\n }\n\n const actionStatuses = async (): Promise<Record<string, ExtensionConfigActionStatus>> => {\n const out: Record<string, ExtensionConfigActionStatus> = {}\n await Promise.all(Object.keys(schema.items).map(async (key) => {\n const status = await actionStatus(key)\n if (status)\n out[`${extensionId}:${key}`] = toWireActionStatus(status)\n }))\n return out\n }\n\n const runAction = async (key: string, opts: { signal?: AbortSignal } = {}): Promise<ExtensionActionRunResult> => {\n const action = actionSetting(key)\n if (!action)\n throw new Error(`\"${extensionId}\" has no action \"${key}\".`)\n if (owner.disposed)\n throw new DisposedError(`settings action \"${key}\"`)\n const signal = opts.signal ? AbortSignal.any([owner.signal, opts.signal]) : owner.signal\n let result\n try {\n result = (await action.run({ ...actionAccess, signal })) ?? undefined\n }\n catch (err) {\n logger.warn('extension settings action failed', { extension: extensionId, action: key, error: err instanceof Error ? err.message : String(err) })\n throw err\n }\n if (result?.tone === 'error')\n throw new Error(result.message || 'failed')\n const accepted: string[] = []\n const rejected: string[] = []\n const config: Record<string, ExtensionConfigValue> = {}\n for (const [patchKey, value] of Object.entries(result?.patch ?? {})) {\n const setting = valueSetting(patchKey)\n const scope = setting && actionScope(setting)\n if (!setting || !scope) {\n rejected.push(patchKey)\n continue\n }\n try {\n await set(patchKey, value, { scope })\n }\n catch (err) {\n if (!(err instanceof SettingsWriteError))\n throw err\n rejected.push(patchKey)\n continue\n }\n accepted.push(patchKey)\n if (!isSecret(setting))\n config[patchKey] = toWireValue(normalizeSettingValue(setting, value) as StoredSettingValue)\n }\n const parts = [result?.message || (accepted.length > 0 ? `updated ${accepted.join(', ')}` : 'done')]\n if (rejected.length > 0)\n parts.push(`(ignored invalid: ${rejected.join(', ')})`)\n return { message: parts.join(' '), ...(Object.keys(config).length > 0 ? { config } : {}) }\n }\n\n const wire = (opts?: { sessionId?: string }): WireSettings =>\n toWireSettings(extensionId, schema, values(opts), { locked: Object.keys(schema.items).filter(locked) })\n\n return {\n api,\n schema,\n issues,\n source: (key, opts) => resolve(key, opts?.sessionId)?.source,\n values,\n check,\n set,\n actionAccess,\n actions: () => wire().actions,\n actionStatus,\n actionStatuses,\n runAction,\n wire,\n }\n}\n","/**\n * The serializable shapes of RPC: what crosses the router, the IPC protocol\n * (`rpc.call` method, `rpc.event` signal) and HTTP (`POST /rpc/<contract>/<method>`).\n * Plain JSON only, so a host can forward them unchanged.\n */\n\nimport type { AccessScope } from '../api/core'\nimport { Buffer } from 'node:buffer'\n\n/** IPC method a protocol client calls to run an RPC method. Params {@link RpcCallParams}, result {@link RpcResponseEnvelope}. */\nexport const RPC_CALL_METHOD = 'rpc.call'\n\n/** IPC signal that carries an {@link RpcEventEnvelope} to protocol clients. */\nexport const RPC_EVENT_SIGNAL = 'rpc.event'\n\n/** Cap on the JSON size of a remote request input, response output or event data. */\nexport const RPC_MAX_PAYLOAD_BYTES = 1024 * 1024\n\n/** Reserved error types. Declared error names may not start with `rpc.`. */\nexport const RpcErrorType = {\n InvalidInput: 'rpc.invalid-input',\n InvalidOutput: 'rpc.invalid-output',\n Unavailable: 'rpc.unavailable',\n Aborted: 'rpc.aborted',\n Internal: 'rpc.internal',\n /** The caller's token scope is below the method's `scope`. */\n Forbidden: 'rpc.forbidden',\n} as const\n\n/**\n * Who made a call, as the router sees it: another extension, an\n * extension's own UI in a local renderer (named by its extension), or a\n * protocol client. What a call may reach is the host's `authorize` check\n * (the token scope of a remote connection), not the caller kind.\n */\nexport type RpcCaller\n = | { kind: 'extension', id: string }\n | { kind: 'ui', extensionId: string }\n | { kind: 'client', clientId: string }\n\n/** A call to one method. */\nexport interface RpcRequestEnvelope {\n /** Contract id. */\n contract: string\n /** Method name. */\n method: string\n /** JSON input. Absent for methods without input. */\n input?: unknown\n /** Project to route to. When several directories register the contract, this one wins; else the newest. */\n directory?: string\n}\n\n/** Params of the {@link RPC_CALL_METHOD} IPC method. */\nexport interface RpcCallParams extends RpcRequestEnvelope {\n /** Caller-chosen id, so a host can cancel the call (for example on `$/cancelRequest`). */\n callId?: string\n}\n\n/** A failed call. `type` is a declared error name or an {@link RpcErrorType}. */\nexport interface RpcWireError {\n /** Declared error name, or an {@link RpcErrorType}. */\n type: string\n /** Text for people. */\n message: string\n /** The declared error's data, validated against its schema. */\n data?: unknown\n}\n\n/** What the router recorded about a call. */\nexport interface RpcResponseMeta {\n /** Contract id of the request. */\n contract: string\n /** Method name of the request. */\n method: string\n /** The least token scope a protocol client needs for the method. `'chat'` when the method is unknown. */\n scope: AccessScope\n /** The extension that answered, when a registration was found. */\n extensionId?: string\n}\n\n/** The result of a call. */\nexport type RpcResult = { ok: true, output: unknown } | { ok: false, error: RpcWireError }\n\n/** A result with the router's metadata: the reply of {@link RPC_CALL_METHOD} and of HTTP. */\nexport type RpcResponseEnvelope = RpcResult & { meta: RpcResponseMeta }\n\n/** One emitted event, as subscribers and the {@link RPC_EVENT_SIGNAL} signal carry it. */\nexport interface RpcEventEnvelope {\n /** `rpc.<contract id>.<event>`. */\n type: string\n /** Contract id. */\n contract: string\n /** Event name within the contract. */\n event: string\n /** JSON object, validated against the event schema. */\n data: Readonly<Record<string, unknown>>\n /** The project the emitting extension runs in. */\n location: { directory: string }\n /** The emitting extension. */\n extensionId: string\n}\n\n/**\n * The HTTP path of a method.\n *\n * @param contract - Contract id.\n * @param method - Method name.\n * @returns `/rpc/<contract>/<method>`, each part URI-encoded.\n */\nexport function rpcHttpPath(contract: string, method: string): string {\n return `/rpc/${encodeURIComponent(contract)}/${encodeURIComponent(method)}`\n}\n\n/**\n * Reads contract and method from an HTTP path made by {@link rpcHttpPath}.\n *\n * @param path - The request path, without query.\n * @returns The parts, or `undefined` when the path is not an RPC path.\n */\nexport function parseRpcHttpPath(path: string): { contract: string, method: string } | undefined {\n const match = /^\\/rpc\\/([^/]+)\\/([^/]+)$/.exec(path)\n if (!match)\n return undefined\n try {\n return { contract: decodeURIComponent(match[1]!), method: decodeURIComponent(match[2]!) }\n }\n catch {\n return undefined\n }\n}\n\n/**\n * The HTTP status for a response. The body is always the envelope.\n *\n * @param response - The call's response.\n * @returns 200 ok, 400 invalid input, 404 unavailable, 499 aborted, 422 declared error, 500 otherwise.\n */\nexport function rpcHttpStatus(response: RpcResult): number {\n if (response.ok)\n return 200\n switch (response.error.type) {\n case RpcErrorType.InvalidInput: return 400\n case RpcErrorType.Forbidden: return 403\n case RpcErrorType.Unavailable: return 404\n case RpcErrorType.Aborted: return 499\n case RpcErrorType.InvalidOutput:\n case RpcErrorType.Internal: return 500\n default: return 422\n }\n}\n\n/**\n * Byte length of the JSON form of `value`, or `null` when it is not JSON.\n * `undefined` counts as 0 (an absent field).\n *\n * @param value - Value to measure.\n */\nexport function jsonBytes(value: unknown): number | null {\n if (value === undefined)\n return 0\n let text: string | undefined\n try {\n text = JSON.stringify(value)\n }\n catch {\n return null\n }\n return typeof text === 'string' ? Buffer.byteLength(text, 'utf8') : null\n}\n"],"mappings":";;;;AAwDA,IAAa,qBAAb,cAAwC,MAAM;CAKvB;CAAsB;;;;;CAA3C,YAAY,KAAsB,QAAyB;EACzD,MAAM,YAAY,IAAI,KAAK,QAAQ;EADhB,KAAA,MAAA;EAAsB,KAAA,SAAA;EAEzC,KAAK,OAAO;CACd;AACF;;AAyDA,MAAM,2BAA2B;AAEjC,SAAS,UAAU,GAAmC,GAA4C;CAChG,IAAI,MAAM,QAAQ,CAAC,KAAK,MAAM,QAAQ,CAAC,GACrC,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,OAAO,GAAG,MAAM,MAAM,EAAE,EAAE;CAC9D,OAAO,MAAM;AACf;;;;;;AAOA,SAAS,eAAe,MAAkB,MAAoB,KAAsD;CAClH,MAAM,EAAE,aAAa,OAAO,UAAU;CAEtC,MAAM,0BAAU,IAAI,IAAW;CAC/B,IAAI;CAEJ,MAAM,gBAAsB;EAC1B,KAAK,MAAM,SAAS,CAAC,GAAG,OAAO,GAAG;GAChC,IAAI,CAAC,QAAQ,IAAI,KAAK,GACpB;GAC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":["../src/extensions/settings/domain.ts","../src/extensions/rpc/wire.ts"],"sourcesContent":["/**\n * The extension settings domain: `ctx.settings` for one extension, plus the\n * host-side surface Settings UIs use (write, actions, wire format).\n *\n * Values resolve session, then project, then user, then the declarative\n * config entry, then the default. A stored value that fails the setting's\n * checks is skipped, so the next layer answers.\n * Secret strings never sit in a settings layer: they live behind\n * {@link SettingsSecretPort} (the auth store) and take the user layer's place.\n */\n\nimport type { Disposable } from '../api/core'\nimport type { ActionSettingContext, ActionSettingStatus, ActionSettingStatusContext, SettingScope, SettingsDomain, SettingsSchema } from '../api/settings'\nimport type { ExtensionConfigActionStatus, ExtensionConfigValue } from '../config'\nimport type { ExtensionActionRunResult, ExtensionActionSummary } from '../config-actions'\nimport type { DomainDeps } from '../runtime/deps'\nimport type { StoredSettingValue, ValidateRunner, ValueSetting } from './validate'\nimport type { WireSettings } from './wire'\nimport { DisposedError } from '../api/core'\nimport { checkSettingValue, isValueSetting, normalizeSettingValue, settingDefault, settingScopes, settingsForDefinition } from './validate'\nimport { toWireActionStatus, toWireSettings, toWireValue } from './wire'\n\n/** A stored settings layer: a scope the user writes, or the declarative config entry. */\nexport type SettingsLayer = SettingScope | 'config'\n\n/** The auth store, as the settings domain sees it. Keys are per extension. */\nexport interface SettingsSecretPort {\n /** The stored secret. Synchronous: hosts read from a cache loaded before setup. */\n get: (extensionId: string, key: string) => string | undefined\n /** Stores the secret, or removes it when `value` is `undefined`. */\n set: (extensionId: string, key: string, value: string | undefined) => void | Promise<void>\n}\n\n/**\n * What a host provides to the settings domain. One port may serve every\n * extension: each call names the extension.\n */\nexport interface SettingsPort {\n /**\n * The values stored in one layer for the extension, by key. Synchronous:\n * hosts read from a cache. `sessionId` is set for the `session` layer.\n * Values are raw; the domain checks them.\n */\n read: (extensionId: string, layer: SettingsLayer, sessionId?: string) => Readonly<Record<string, unknown>> | undefined\n /** Stores a value in a user-writable scope, or clears it when `value` is `undefined`. */\n write: (extensionId: string, scope: SettingScope, key: string, value: StoredSettingValue | undefined, sessionId?: string) => void | Promise<void>\n /** Calls `listener` after any layer of the extension changed. Returns the unsubscribe. Optional: without it only writes made through the domain notify. */\n subscribe?: (extensionId: string, listener: () => void) => () => void\n /** Where secret strings live. */\n secrets: SettingsSecretPort\n}\n\n/** Which layer an effective value came from. `secret` is the auth store. */\nexport type SettingSource = SettingsLayer | 'secret' | 'default'\n\n/** A refused write. */\nexport class SettingsWriteError extends Error {\n /**\n * @param key - The setting.\n * @param reason - Why it was refused.\n */\n constructor(readonly key: string, readonly reason: string) {\n super(`setting \"${key}\": ${reason}`)\n this.name = 'SettingsWriteError'\n }\n}\n\n/** Options of a host-side write. */\nexport interface SettingsWriteOptions {\n /** The scope to write. Ignored for secrets, which always go to the auth store. */\n scope: SettingScope\n /** Required for the `session` scope. */\n sessionId?: string\n}\n\n/** The settings domain of one extension. */\nexport interface SettingsDomainInstance<S extends SettingsSchema = SettingsSchema> {\n /** `ctx.settings`: only `get`, `onChange` and `locked`. */\n readonly api: SettingsDomain<S>\n /** The cleaned schema. */\n readonly schema: SettingsSchema\n /** What `settingsForDefinition` dropped from the authored schema. */\n readonly issues: readonly string[]\n /** Where the effective value of `key` comes from, or `undefined` for an unknown or action key. */\n source: (key: string, opts?: { sessionId?: string }) => SettingSource | undefined\n /** Every effective value (secrets included), by key. Keys without a value are left out. */\n values: (opts?: { sessionId?: string }) => Record<string, StoredSettingValue>\n /** Checks a raw value for `key`. Returns an error message, or `undefined` when it would be accepted. */\n check: (key: string, value: unknown) => string | undefined\n /**\n * Writes a value (`undefined` clears it). Secret strings go to the auth\n * store. Throws {@link SettingsWriteError} for an unknown, action or\n * locked key, a scope the setting does not allow, or a value that fails\n * its checks. Listeners are notified when the effective value changed.\n */\n set: (key: string, value: unknown, opts: SettingsWriteOptions) => Promise<void>\n /**\n * What an action's `run` and `status` get besides the signal: `get` reads\n * this extension's effective values, `set` writes like a patch key (user\n * scope, else project; secrets to the auth store) and rejects with\n * {@link SettingsWriteError}. Settings-page actions get the same.\n */\n readonly actionAccess: Omit<ActionSettingContext, 'signal'>\n /** The action rows in wire shape. */\n actions: () => ExtensionActionSummary[]\n /** Runs an action's `status()` through the guard (3 s bound). `undefined`: none, failed, or empty. */\n actionStatus: (key: string) => Promise<ActionSettingStatus | undefined>\n /** Every action status in wire shape, keyed `extension:key`. */\n actionStatuses: () => Promise<Record<string, ExtensionConfigActionStatus>>\n /**\n * Runs an action. Its `patch` is checked per key: accepted values are\n * written (user scope, else project), the rest named in the message. A\n * throw, or a result with tone `error`, rejects with its message. The\n * result's `config` repeats the accepted non-secret values in wire shape\n * for UIs that persist it themselves.\n */\n runAction: (key: string, opts?: { signal?: AbortSignal }) => Promise<ExtensionActionRunResult>\n /** The schema, effective values and locks in the wire format the Settings UIs render. */\n wire: (opts?: { sessionId?: string }) => WireSettings\n}\n\n/** Bound on a passive `status()` probe, as `probeActionStatuses`. */\nconst ACTION_STATUS_TIMEOUT_MS = 3_000\n\nfunction sameValue(a: StoredSettingValue | undefined, b: StoredSettingValue | undefined): boolean {\n if (Array.isArray(a) && Array.isArray(b))\n return a.length === b.length && a.every((v, i) => v === b[i])\n return a === b\n}\n\n/**\n * `onChange` listeners of one extension: one port subscription while any\n * listener lives, each listener told only when its key's effective value\n * changed.\n */\nfunction createWatchers(deps: DomainDeps, port: SettingsPort, get: (key: string) => StoredSettingValue | undefined) {\n const { extensionId, owner, guard } = deps\n interface Watch { key: string, last: StoredSettingValue | undefined, listener: (value: StoredSettingValue | undefined) => void }\n const watches = new Set<Watch>()\n let unsubscribePort: (() => void) | undefined\n\n const recheck = (): void => {\n for (const watch of [...watches]) {\n if (!watches.has(watch))\n continue\n const next = get(watch.key)\n if (sameValue(next, watch.last))\n continue\n watch.last = next\n guard.callSync(`settings.onChange(${watch.key})`, () => watch.listener(next))\n }\n }\n\n const onChange = (key: string, listener: (value: StoredSettingValue | undefined) => void): Disposable => {\n if (owner.disposed)\n throw new DisposedError('settings.onChange')\n const watch: Watch = { key, last: get(key), listener }\n watches.add(watch)\n if (!unsubscribePort && port.subscribe)\n unsubscribePort = port.subscribe(extensionId, recheck)\n let cleanup: Disposable | undefined\n const dispose = (): void => {\n if (!watches.delete(watch))\n return\n cleanup?.dispose()\n if (watches.size === 0 && unsubscribePort) {\n unsubscribePort()\n unsubscribePort = undefined\n }\n }\n cleanup = owner.onCleanup(dispose)\n return { dispose }\n }\n\n return { onChange, recheck }\n}\n\n/**\n * Builds the settings domain of one extension.\n *\n * @param deps - The extension's runtime deps (id, owner, guard, logger).\n * @param port - The host's settings storage and auth store.\n * @param settings - The authored schema (`definition.settings`). Cleaned with `settingsForDefinition`.\n * @returns `api` for `ctx.settings`, and the host surface.\n */\nexport function createSettingsDomain<S extends SettingsSchema = SettingsSchema>(\n deps: DomainDeps,\n port: SettingsPort,\n settings?: S,\n): SettingsDomainInstance<S> {\n const { extensionId, owner, guard, logger } = deps\n const { schema, issues } = settingsForDefinition({ id: extensionId, settings })\n for (const issue of issues)\n logger.warn(`extension settings: ${issue}`, { extension: extensionId })\n\n const runValidate: ValidateRunner = (validate, value) => {\n const out = guard.callSync(`settings.validate`, () => validate(value), { fallback: 'invalid value' })\n return typeof out === 'string' && out.length > 0 ? out : undefined\n }\n\n const valueSetting = (key: string): ValueSetting | undefined => {\n const setting = Object.hasOwn(schema.items, key) ? schema.items[key] : undefined\n return setting && isValueSetting(setting) ? setting : undefined\n }\n\n const isSecret = (setting: ValueSetting): boolean => setting.type === 'string' && setting.secret === true\n\n /** The layer's value for `key` when present and valid. */\n const layerValue = (setting: ValueSetting, key: string, layer: SettingsLayer, sessionId?: string): StoredSettingValue | undefined => {\n const bag = port.read(extensionId, layer, layer === 'session' ? sessionId : undefined)\n if (!bag || !Object.hasOwn(bag, key))\n return undefined\n const raw = bag[key]\n if (raw === undefined || raw === null)\n return undefined\n const value = normalizeSettingValue(setting, raw)\n return checkSettingValue(setting, value, runValidate) === undefined ? value as StoredSettingValue : undefined\n }\n\n const secretValue = (setting: ValueSetting, key: string): StoredSettingValue | undefined => {\n const raw = port.secrets.get(extensionId, key)\n if (raw === undefined)\n return undefined\n return checkSettingValue(setting, raw, runValidate) === undefined ? raw : undefined\n }\n\n const resolve = (key: string, sessionId?: string): { value: StoredSettingValue | undefined, source: SettingSource } | undefined => {\n const setting = valueSetting(key)\n if (!setting)\n return undefined\n const layers: (SettingsLayer | 'secret')[] = isSecret(setting)\n ? ['secret', 'config']\n : sessionId !== undefined ? ['session', 'project', 'user', 'config'] : ['project', 'user', 'config']\n for (const layer of layers) {\n const value = layer === 'secret' ? secretValue(setting, key) : layerValue(setting, key, layer, sessionId)\n if (value !== undefined)\n return { value, source: layer }\n }\n return { value: settingDefault(setting), source: 'default' }\n }\n\n const get = (key: string, sessionId?: string): StoredSettingValue | undefined => resolve(key, sessionId)?.value\n\n const locked = (key: string): boolean => {\n const setting = valueSetting(key)\n return setting !== undefined && layerValue(setting, key, 'config') !== undefined\n }\n\n const { onChange, recheck } = createWatchers(deps, port, key => get(key))\n\n const api: SettingsDomain<S> = Object.freeze({\n get: ((key: string, opts?: { sessionId?: string }) => get(key, opts?.sessionId)) as SettingsDomain<S>['get'],\n onChange: onChange as unknown as SettingsDomain<S>['onChange'],\n locked: ((key: string) => locked(key)) as SettingsDomain<S>['locked'],\n })\n\n const check = (key: string, value: unknown): string | undefined => {\n const setting = valueSetting(key)\n if (!setting)\n return 'unknown setting'\n return checkSettingValue(setting, normalizeSettingValue(setting, value), runValidate)\n }\n\n const set = async (key: string, value: unknown, opts: SettingsWriteOptions): Promise<void> => {\n const setting = valueSetting(key)\n if (!setting)\n throw new SettingsWriteError(key, 'unknown setting')\n if (locked(key))\n throw new SettingsWriteError(key, 'locked by the config file')\n let normalized: StoredSettingValue | undefined\n if (value !== undefined) {\n const candidate = normalizeSettingValue(setting, value)\n const error = checkSettingValue(setting, candidate, runValidate)\n if (error !== undefined)\n throw new SettingsWriteError(key, error)\n normalized = candidate as StoredSettingValue\n }\n if (isSecret(setting)) {\n await port.secrets.set(extensionId, key, normalized as string | undefined)\n }\n else {\n if (!settingScopes(setting).includes(opts.scope))\n throw new SettingsWriteError(key, `cannot be set at the ${opts.scope} scope`)\n if (opts.scope === 'session' && !opts.sessionId)\n throw new SettingsWriteError(key, 'the session scope needs a sessionId')\n await port.write(extensionId, opts.scope, key, normalized, opts.scope === 'session' ? opts.sessionId : undefined)\n }\n recheck()\n }\n\n const values = (opts?: { sessionId?: string }): Record<string, StoredSettingValue> => {\n const out: Record<string, StoredSettingValue> = {}\n for (const key of Object.keys(schema.items)) {\n const value = get(key, opts?.sessionId)\n if (value !== undefined)\n out[key] = value\n }\n return out\n }\n\n /** Where an action's write of `key` goes: the user scope, else project; `undefined` when neither is allowed. Secrets ignore it. */\n const actionScope = (setting: ValueSetting): SettingScope | undefined =>\n isSecret(setting) ? 'user' : settingScopes(setting).find(s => s === 'user' || s === 'project')\n\n const actionAccess: Omit<ActionSettingContext, 'signal'> = Object.freeze({\n get: (key: string) => get(key),\n set: async (key: string, value: unknown) => {\n const setting = valueSetting(key)\n if (!setting)\n throw new SettingsWriteError(key, 'unknown setting')\n const scope = actionScope(setting)\n if (!scope)\n throw new SettingsWriteError(key, 'has neither a user nor a project scope')\n await set(key, value, { scope })\n },\n })\n const statusAccess: ActionSettingStatusContext = Object.freeze({ get: actionAccess.get })\n\n const actionSetting = (key: string) => {\n const setting = Object.hasOwn(schema.items, key) ? schema.items[key] : undefined\n return setting?.type === 'action' ? setting : undefined\n }\n\n const actionStatus = async (key: string): Promise<ActionSettingStatus | undefined> => {\n const status = actionSetting(key)?.status\n if (!status)\n return undefined\n const out = await guard.call(`settings.status(${key})`, () => status(statusAccess), { timeoutMs: ACTION_STATUS_TIMEOUT_MS, fallback: undefined })\n return out && typeof out.text === 'string' && out.text.length > 0 ? out : undefined\n }\n\n const actionStatuses = async (): Promise<Record<string, ExtensionConfigActionStatus>> => {\n const out: Record<string, ExtensionConfigActionStatus> = {}\n await Promise.all(Object.keys(schema.items).map(async (key) => {\n const status = await actionStatus(key)\n if (status)\n out[`${extensionId}:${key}`] = toWireActionStatus(status)\n }))\n return out\n }\n\n const runAction = async (key: string, opts: { signal?: AbortSignal } = {}): Promise<ExtensionActionRunResult> => {\n const action = actionSetting(key)\n if (!action)\n throw new Error(`\"${extensionId}\" has no action \"${key}\".`)\n if (owner.disposed)\n throw new DisposedError(`settings action \"${key}\"`)\n const signal = opts.signal ? AbortSignal.any([owner.signal, opts.signal]) : owner.signal\n let result\n try {\n result = (await action.run({ ...actionAccess, signal })) ?? undefined\n }\n catch (err) {\n logger.warn('extension settings action failed', { extension: extensionId, action: key, error: err instanceof Error ? err.message : String(err) })\n throw err\n }\n if (result?.tone === 'error')\n throw new Error(result.message || 'failed')\n const accepted: string[] = []\n const rejected: string[] = []\n const config: Record<string, ExtensionConfigValue> = {}\n for (const [patchKey, value] of Object.entries(result?.patch ?? {})) {\n const setting = valueSetting(patchKey)\n const scope = setting && actionScope(setting)\n if (!setting || !scope) {\n rejected.push(patchKey)\n continue\n }\n try {\n await set(patchKey, value, { scope })\n }\n catch (err) {\n if (!(err instanceof SettingsWriteError))\n throw err\n rejected.push(patchKey)\n continue\n }\n accepted.push(patchKey)\n if (!isSecret(setting))\n config[patchKey] = toWireValue(normalizeSettingValue(setting, value) as StoredSettingValue)\n }\n const parts = [result?.message || (accepted.length > 0 ? `updated ${accepted.join(', ')}` : 'done')]\n if (rejected.length > 0)\n parts.push(`(ignored invalid: ${rejected.join(', ')})`)\n return { message: parts.join(' '), ...(Object.keys(config).length > 0 ? { config } : {}) }\n }\n\n const wire = (opts?: { sessionId?: string }): WireSettings =>\n toWireSettings(extensionId, schema, values(opts), { locked: Object.keys(schema.items).filter(locked) })\n\n return {\n api,\n schema,\n issues,\n source: (key, opts) => resolve(key, opts?.sessionId)?.source,\n values,\n check,\n set,\n actionAccess,\n actions: () => wire().actions,\n actionStatus,\n actionStatuses,\n runAction,\n wire,\n }\n}\n","/**\n * The serializable shapes of RPC: what crosses the router, the IPC protocol\n * (`rpc.call` method, `rpc.event` signal) and HTTP (`POST /rpc/<contract>/<method>`).\n * Plain JSON only, so a host can forward them unchanged.\n */\n\nimport type { AccessScope } from '../api/core'\nimport { Buffer } from 'node:buffer'\n\n/** IPC method a protocol client calls to run an RPC method. Params {@link RpcCallParams}, result {@link RpcResponseEnvelope}. */\nexport const RPC_CALL_METHOD = 'rpc.call'\n\n/** IPC signal that carries an {@link RpcEventEnvelope} to protocol clients. */\nexport const RPC_EVENT_SIGNAL = 'rpc.event'\n\n/** Cap on the JSON size of a remote request input, response output or event data. */\nexport const RPC_MAX_PAYLOAD_BYTES = 1024 * 1024\n\n/** Reserved error types. Declared error names may not start with `rpc.`. */\nexport const RpcErrorType = {\n InvalidInput: 'rpc.invalid-input',\n InvalidOutput: 'rpc.invalid-output',\n Unavailable: 'rpc.unavailable',\n Aborted: 'rpc.aborted',\n Internal: 'rpc.internal',\n /** The caller's token scope is below the method's `scope`. */\n Forbidden: 'rpc.forbidden',\n} as const\n\n/**\n * Who made a call, as the router sees it: another extension, an\n * extension's own UI in a local renderer (named by its extension), or a\n * protocol client. What a call may reach is the host's `authorize` check\n * (the token scope of a remote connection), not the caller kind.\n */\nexport type RpcCaller\n = | { kind: 'extension', id: string }\n | { kind: 'ui', extensionId: string }\n | { kind: 'client', clientId: string }\n\n/** A call to one method. */\nexport interface RpcRequestEnvelope {\n /** Contract id. */\n contract: string\n /** Method name. */\n method: string\n /** JSON input. Absent for methods without input. */\n input?: unknown\n /** Project to route to. When several directories register the contract, this one wins; else the newest. */\n directory?: string\n}\n\n/** Params of the {@link RPC_CALL_METHOD} IPC method. */\nexport interface RpcCallParams extends RpcRequestEnvelope {\n /** Caller-chosen id, so a host can cancel the call (for example on `$/cancelRequest`). */\n callId?: string\n}\n\n/** A failed call. `type` is a declared error name or an {@link RpcErrorType}. */\nexport interface RpcWireError {\n /** Declared error name, or an {@link RpcErrorType}. */\n type: string\n /** Text for people. */\n message: string\n /** The declared error's data, validated against its schema. */\n data?: unknown\n}\n\n/** What the router recorded about a call. */\nexport interface RpcResponseMeta {\n /** Contract id of the request. */\n contract: string\n /** Method name of the request. */\n method: string\n /** The least token scope a protocol client needs for the method. `'chat'` when the method is unknown. */\n scope: AccessScope\n /** The extension that answered, when a registration was found. */\n extensionId?: string\n}\n\n/** The result of a call. */\nexport type RpcResult = { ok: true, output: unknown } | { ok: false, error: RpcWireError }\n\n/** A result with the router's metadata: the reply of {@link RPC_CALL_METHOD} and of HTTP. */\nexport type RpcResponseEnvelope = RpcResult & { meta: RpcResponseMeta }\n\n/** One emitted event, as subscribers and the {@link RPC_EVENT_SIGNAL} signal carry it. */\nexport interface RpcEventEnvelope {\n /** `rpc.<contract id>.<event>`. */\n type: string\n /** Contract id. */\n contract: string\n /** Event name within the contract. */\n event: string\n /** JSON object, validated against the event schema. */\n data: Readonly<Record<string, unknown>>\n /** The project the emitting extension runs in. */\n location: { directory: string }\n /** The emitting extension. */\n extensionId: string\n}\n\n/**\n * The HTTP path of a method.\n *\n * @param contract - Contract id.\n * @param method - Method name.\n * @returns `/rpc/<contract>/<method>`, each part URI-encoded.\n */\nexport function rpcHttpPath(contract: string, method: string): string {\n return `/rpc/${encodeURIComponent(contract)}/${encodeURIComponent(method)}`\n}\n\n/**\n * Reads contract and method from an HTTP path made by {@link rpcHttpPath}.\n *\n * @param path - The request path, without query.\n * @returns The parts, or `undefined` when the path is not an RPC path.\n */\nexport function parseRpcHttpPath(path: string): { contract: string, method: string } | undefined {\n const match = /^\\/rpc\\/([^/]+)\\/([^/]+)$/.exec(path)\n if (!match)\n return undefined\n try {\n return { contract: decodeURIComponent(match[1]!), method: decodeURIComponent(match[2]!) }\n }\n catch {\n return undefined\n }\n}\n\n/**\n * The HTTP status for a response. The body is always the envelope.\n *\n * @param response - The call's response.\n * @returns 200 ok, 400 invalid input, 404 unavailable, 499 aborted, 422 declared error, 500 otherwise.\n */\nexport function rpcHttpStatus(response: RpcResult): number {\n if (response.ok)\n return 200\n switch (response.error.type) {\n case RpcErrorType.InvalidInput: return 400\n case RpcErrorType.Forbidden: return 403\n case RpcErrorType.Unavailable: return 404\n case RpcErrorType.Aborted: return 499\n case RpcErrorType.InvalidOutput:\n case RpcErrorType.Internal: return 500\n default: return 422\n }\n}\n\n/**\n * Byte length of the JSON form of `value`, or `null` when it is not JSON.\n * `undefined` counts as 0 (an absent field).\n *\n * @param value - Value to measure.\n */\nexport function jsonBytes(value: unknown): number | null {\n if (value === undefined)\n return 0\n let text: string | undefined\n try {\n text = JSON.stringify(value)\n }\n catch {\n return null\n }\n return typeof text === 'string' ? Buffer.byteLength(text, 'utf8') : null\n}\n"],"mappings":";;;;AAwDA,IAAa,qBAAb,cAAwC,MAAM;CAKvB;CAAsB;;;;;CAA3C,YAAY,KAAsB,QAAyB;EACzD,MAAM,YAAY,IAAI,KAAK,QAAQ;EADhB,KAAA,MAAA;EAAsB,KAAA,SAAA;EAEzC,KAAK,OAAO;CACd;AACF;;AAyDA,MAAM,2BAA2B;AAEjC,SAAS,UAAU,GAAmC,GAA4C;CAChG,IAAI,MAAM,QAAQ,CAAC,KAAK,MAAM,QAAQ,CAAC,GACrC,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,OAAO,GAAG,MAAM,MAAM,EAAE,EAAE;CAC9D,OAAO,MAAM;AACf;;;;;;AAOA,SAAS,eAAe,MAAkB,MAAoB,KAAsD;CAClH,MAAM,EAAE,aAAa,OAAO,UAAU;CAEtC,MAAM,0BAAU,IAAI,IAAW;CAC/B,IAAI;CAEJ,MAAM,gBAAsB;EAC1B,KAAK,MAAM,SAAS,CAAC,GAAG,OAAO,GAAG;GAChC,IAAI,CAAC,QAAQ,IAAI,KAAK,GACpB;GACF,MAAM,OAAO,IAAI,MAAM,GAAG;GAC1B,IAAI,UAAU,MAAM,MAAM,IAAI,GAC5B;GACF,MAAM,OAAO;GACb,MAAM,SAAS,qBAAqB,MAAM,IAAI,UAAU,MAAM,SAAS,IAAI,CAAC;EAC9E;CACF;CAEA,MAAM,YAAY,KAAa,aAA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Y,YAAY,sBAAsB,SAAS,KAAK,CAAuB;EAC9F;EACA,MAAM,QAAQ,CAAC,QAAQ,YAAY,SAAS,SAAS,IAAI,WAAW,SAAS,KAAK,IAAI,MAAM,OAAO;EACnG,IAAI,SAAS,SAAS,GACpB,MAAM,KAAK,qBAAqB,SAAS,KAAK,IAAI,EAAE,EAAE;EACxD,OAAO;GAAE,SAAS,MAAM,KAAK,GAAG;GAAG,GAAI,OAAO,KAAK,MAAM,CAAC,CAAC,SAAS,IAAI,EAAE,OAAO,IAAI,CAAC;EAAG;CAC3F;CAEA,MAAM,QAAQ,SACZ,eAAe,aAAa,QAAQ,OAAO,IAAI,GAAG,EAAE,QAAQ,OAAO,KAAK,OAAO,KAAK,CAAC,CAAC,OAAO,MAAM,EAAE,CAAC;CAExG,OAAO;EACL;EACA;EACA;EACA,SAAS,KAAK,SAAS,QAAQ,KAAK,MAAM,SAAS,CAAC,EAAE;EACtD;EACA;EACA;EACA;EACA,eAAe,KAAK,CAAC,CAAC;EACtB;EACA;EACA;EACA;CACF;AACF;;;;ACrYA,MAAa,wBAAwB;;AAGrC,MAAa,eAAe;CAC1B,cAAc;CACd,eAAe;CACf,aAAa;CACb,SAAS;CACT,UAAU;;CAEV,WAAW;AACb;;;;;;;AAkIA,SAAgB,UAAU,OAA+B;CACvD,IAAI,UAAU,KAAA,GACZ,OAAO;CACT,IAAI;CACJ,IAAI;EACF,OAAO,KAAK,UAAU,KAAK;CAC7B,QACM;EACJ,OAAO;CACT;CACA,OAAO,OAAO,SAAS,WAAW,OAAO,WAAW,MAAM,MAAM,IAAI;AACtE"}
@@ -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-BIWy4T_0.js";
3
+ import { i as IpcVersionMismatchError } from "./settings-keys-DDrfnBHi.js";
4
4
  import { f as hostRefOf } from "./protocol-Dad2fl5r.js";
5
5
  import { t as keepHostConnected } from "./connection-loop-DSCehV3W.js";
6
6
  import { n as displayHostUrl } from "./url-znC3tmKE.js";
7
- import { i as probeUnsavedHost, t as createHostRegistry } from "./registry-CYEN4C4M.js";
8
- import { a as hostCaBundle, r as connectWsClient, t as HostAuthError } from "./ws-client-Bn_asPwE.js";
7
+ import { i as probeUnsavedHost, t as createHostRegistry } from "./registry-Dl6261Xh.js";
8
+ import { a as hostCaBundle, r as connectWsClient, t as HostAuthError } from "./ws-client-PZdbO0fj.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;
@@ -288,4 +288,4 @@ function startWsSavedHosts(options) {
288
288
  //#endregion
289
289
  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 };
290
290
 
291
- //# sourceMappingURL=ws-CqlZkB4w.js.map
291
+ //# sourceMappingURL=ws-DriNRyP-.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"ws-CqlZkB4w.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 // The OS certificate store is read once per process, synchronously (seconds on a loaded\n // machine): read it before the deadline starts, or that cost is misread as a host with no answer.\n if (typeof (globalThis as { Bun?: unknown }).Bun !== 'undefined' && /^wss:/i.test(target.url))\n hostCaBundle()\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 /** Move a saved server to a new URL (its saved token; the same server must answer), then reconnect it in place. Throws a `HostRegistryError`. */\n setUrl: (id: string, url: string) => Promise<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 setUrl: async (id, url) => {\n const entry = await registry.setUrl(id, url)\n if (!skip(entry))\n connect(entry)\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,IA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E;GACrC,IAAI,OAAO,IAAI;IACb,UAAU,OAAO,IAAI;KAAE,YAAY,OAAO,QAAQ;KAAM,GAAI,OAAO,gBAAgB,EAAE,eAAe,OAAO,cAAc,IAAI,CAAC;IAAG,CAAC;IAClI,MAAM,IAAI,EAAE,CAAC,EAAE,MAAM;GACvB;GACA,OAAO;EACT;EACA,QAAO,OAAM,MAAM,IAAI,EAAE,CAAC,EAAE,MAAM;EAClC,gBAAgB;GACd,KAAK,MAAM,QAAQ,MAAM,OAAO,GAC9B,KAAK,MAAM;EACf;EACA,YAAY;GACV,KAAK,MAAM,OAAO,CAAC,GAAG,MAAM,KAAK,CAAC,GAAG;IACnC,WAAW,GAAG;IACd,UAAU,OAAO,GAAG;GACtB;EACF;CACF;AACF;;;;;;;;;;;;;;ACxMA,SAAgB,kBAAkB,KAA+B;CAC/D,IAAI,eAAe,eACjB,OAAO;CACT,IAAI,eAAe,mBACjB,OAAO;CACT,OAAO,eAAe,0BAA0B,aAAa;AAC/D;;;;;;AAOA,SAAgB,mBAAmB,QAAkE;CACnG,OAAO,iBAAiB,aAAa,MAAM;AAC7C;;;;;;;AAqBA,SAAgB,kBAAkB,SAAoD;CACpF,MAAM,EAAE,SAAS,YAAY,SAAS,UAAU,GAAG,SAAS;CAC5D,OAAO,gBAAgB;EACrB,GAAG;EACH,UAAU,YAAY,qBAAqB,EAAE,QAAQ,CAAC;EACtD,UAAU;EACV,cAAc;EACd,SAAS,aAAa,OAAO,OAAO,YAAY,gBAAgB;GAC9D,KAAK,MAAM;GACX;GACA,cAAc,MAAM;GACpB,GAAI,aAAa,EAAE,WAAW,IAAI,CAAC;GACnC,QAAQ,QAAQ;GAChB,SAAS,QAAQ;EACnB,CAAC;CACH,CAAC;AACH"}
1
+ {"version":3,"file":"ws-DriNRyP-.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 // The OS certificate store is read once per process, synchronously (seconds on a loaded\n // machine): read it before the deadline starts, or that cost is misread as a host with no answer.\n if (typeof (globalThis as { Bun?: unknown }).Bun !== 'undefined' && /^wss:/i.test(target.url))\n hostCaBundle()\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 /** Move a saved server to a new URL (its saved token; the same server must answer), then reconnect it in place. Throws a `HostRegistryError`. */\n setUrl: (id: string, url: string) => Promise<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 setUrl: async (id, url) => {\n const entry = await registry.setUrl(id, url)\n if (!skip(entry))\n connect(entry)\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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,cAAc;EACd,SAAS,aAAa,OAAO,OAAO,YAAY,gBAAgB;GAC9D,KAAK,MAAM;GACX;GACA,cAAc,MAAM;GACpB,GAAI,aAAa,EAAE,WAAW,IAAI,CAAC;GACnC,QAAQ,QAAQ;GAChB,SAAS,QAAQ;EACnB,CAAC;CACH,CAAC;AACH"}
@@ -1,7 +1,7 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-BhDjJH2R.js";
2
2
  import { a as errorResponse, 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-BIWy4T_0.js";
4
+ import { a as createSignalListeners, o as openIpcClient } from "./settings-keys-DDrfnBHi.js";
5
5
  import { f as hostRefOf } from "./protocol-Dad2fl5r.js";
6
6
  import { n as displayHostUrl } from "./url-znC3tmKE.js";
7
7
  import tls from "node:tls";
@@ -313,4 +313,4 @@ async function connectWsClient(options) {
313
313
  //#endregion
314
314
  export { hostCaBundle as a, ws_client_exports as i, HostBusyError as n, trustSystemCertificates as o, connectWsClient as r, HostAuthError as t };
315
315
 
316
- //# sourceMappingURL=ws-client-Bn_asPwE.js.map
316
+ //# sourceMappingURL=ws-client-PZdbO0fj.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"ws-client-Bn_asPwE.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\nimport type { ClientScope } from '../scopes'\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, and\n * `grant` is a client connection's reach (`../scopes`; absent: everything).\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, grant?: ClientScope }\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?.remove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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"}
1
+ {"version":3,"file":"ws-client-PZdbO0fj.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\nimport type { ClientScope } from '../scopes'\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, and\n * `grant` is a client connection's reach (`../scopes`; absent: everything).\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, grant?: ClientScope }\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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;GAC3B,IAAI,QAAQ,WAAW,gBAAgB,CAAC,QAAQ,OAAO,cACrD,OAAO,QAAQ,eAAe,OAAO;GACvC,QAAQ,MAAM,aAAa,QAAQ,QAAS,QAAiC,MAAM;EACrF;CACF,CAAC;CAED,MAAM,UAAU,IAAI,YAAY;CAChC,GAAG,iBAAiB,YAAY,UAAwB;EACtD,IAAI,QACF;EACF,IAAI,QAAQ,OAAO,MAAM,SAAS,WAAW,MAAM,OAAO,QAAQ,OAAO,MAAM,IAAmB,CAAC;CACrG,CAAC;;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"}
package/docs/RELEASE.md CHANGED
@@ -5,7 +5,7 @@ does the rest:
5
5
 
6
6
  | Job | What it does |
7
7
  |---|---|
8
- | `release` (macOS) | Gates (typecheck, lint, tests, smokes), the TUI and server binaries (darwin ones Developer ID signed and notarized), their archives, the GitHub release, `NOTES.md`, then npm: `zidane-tui-*`, `zidane-tui`, `zidane`, `zidane-ui`, `zidane-gui`. |
8
+ | `release` (macOS) | Gates (typecheck, lint, tests, smokes), the TUI and server binaries (darwin ones Developer ID signed and notarized), their archives, the GitHub release, `NOTES.md`, then npm: `zidane-tui-*`, `zidane-tui`, `zidane`, `zidane-ui`, `zidane-gui`. Each package waits until npm serves it before the next one, except `zidane-gui`, the last: npm can take over an hour to serve it, so a version npm accepted but does not serve after 15 minutes is a warning, and the feed still goes out. |
9
9
  | `desktop-mac` (macOS) | `gui` `dist:mac`: `Zidane-<v>-mac-{arm64,x64}.{dmg,zip}` and `latest-mac.yml`. |
10
10
  | `desktop-linux` (Ubuntu) | `gui` `dist:linux`: `Zidane-<v>-linux-{x64,arm64}.{AppImage,deb}` and `latest-linux*.yml`. |
11
11
  | `server-image` | `ghcr.io/<owner>/zidane-server` (server-image.yml), and its digest. |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zidane",
3
- "version": "9.1.9",
3
+ "version": "9.1.13",
4
4
  "description": "an agent that goes straight to the goal",
5
5
  "type": "module",
6
6
  "private": false,