zidane 9.1.5 → 9.1.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{acp-BWLdmJDt.js → acp-DMIhIsAi.js} +3 -3
- package/dist/{acp-BWLdmJDt.js.map → acp-DMIhIsAi.js.map} +1 -1
- package/dist/acp-cli.js +4 -4
- package/dist/acp.d.ts +2 -2
- package/dist/acp.js +1 -1
- package/dist/agent.d.ts +1 -1
- package/dist/{auth-store-port-DYsWAuUj.js → auth-store-port-BHEXS3VS.js} +2 -2
- package/dist/{auth-store-port-DYsWAuUj.js.map → auth-store-port-BHEXS3VS.js.map} +1 -1
- package/dist/{auto-update-restart-BLW0dTui.js → auto-update-restart-Dkdz6rq4.js} +10 -10
- package/dist/{auto-update-restart-BLW0dTui.js.map → auto-update-restart-Dkdz6rq4.js.map} +1 -1
- package/dist/{browser-entry-CHX7eDd5.d.ts → browser-entry-DP6PZ2Ar.d.ts} +4 -4
- package/dist/{browser-entry-CHX7eDd5.d.ts.map → browser-entry-DP6PZ2Ar.d.ts.map} +1 -1
- package/dist/channels.d.ts +5 -5
- package/dist/chat/browser.d.ts +3 -3
- package/dist/chat/pure.d.ts +3 -3
- package/dist/chat.d.ts +4 -4
- package/dist/chat.js +9 -9
- package/dist/{cli-shared-DyAIGvCc.js → cli-shared-VGYq10bZ.js} +3 -3
- package/dist/{cli-shared-DyAIGvCc.js.map → cli-shared-VGYq10bZ.js.map} +1 -1
- package/dist/{client-core-BdLvnaYK.d.ts → client-core-CG_5I6Ol.d.ts} +4 -4
- package/dist/{client-core-BdLvnaYK.d.ts.map → client-core-CG_5I6Ol.d.ts.map} +1 -1
- package/dist/{client-CK_UrIhx.d.ts → client-tLbAFn0W.d.ts} +2 -2
- package/dist/{client-CK_UrIhx.d.ts.map → client-tLbAFn0W.d.ts.map} +1 -1
- package/dist/{connection-loop--yxMYRBl.d.ts → connection-loop-CPeQsGRl.d.ts} +4 -4
- package/dist/{connection-loop--yxMYRBl.d.ts.map → connection-loop-CPeQsGRl.d.ts.map} +1 -1
- package/dist/contexts/daytona.d.ts +1 -1
- package/dist/contexts/e2b.d.ts +1 -1
- package/dist/{credentials-CKZXFn6X.js → credentials-Bf8Bz4X-.js} +2 -2
- package/dist/{credentials-CKZXFn6X.js.map → credentials-Bf8Bz4X-.js.map} +1 -1
- package/dist/daemon-cli.js +2 -2
- package/dist/{discovery-Cma3l0tG.js → discovery-CC6Uhvm8.js} +4 -4
- package/dist/{discovery-Cma3l0tG.js.map → discovery-CC6Uhvm8.js.map} +1 -1
- package/dist/durable/sqlite.d.ts +2 -2
- package/dist/durable.d.ts +1 -1
- package/dist/{engine-DH7FBsXF.js → engine-d8V1hEDw.js} +3 -3
- package/dist/{engine-DH7FBsXF.js.map → engine-d8V1hEDw.js.map} +1 -1
- package/dist/eval.d.ts +1 -1
- package/dist/{executor-Cj6ilahP.js → executor-C5VCLmPj.js} +2 -2
- package/dist/{executor-Cj6ilahP.js.map → executor-C5VCLmPj.js.map} +1 -1
- package/dist/extensions/testing.d.ts +1 -1
- package/dist/extensions/testing.js +2 -2
- package/dist/{extensions-client-CGL8cTfx.d.ts → extensions-client-ke2jcWfp.d.ts} +4 -4
- package/dist/{extensions-client-CGL8cTfx.d.ts.map → extensions-client-ke2jcWfp.d.ts.map} +1 -1
- package/dist/{extensions-DjEPVNyg.js → extensions-hHKXiXSo.js} +6 -6
- package/dist/{extensions-DjEPVNyg.js.map → extensions-hHKXiXSo.js.map} +1 -1
- package/dist/extensions.d.ts +1 -1
- package/dist/extensions.js +5 -5
- package/dist/{fold-rules-C6udT9hM.d.ts → fold-rules-NGK3F6IS.d.ts} +2 -2
- package/dist/{fold-rules-C6udT9hM.d.ts.map → fold-rules-NGK3F6IS.d.ts.map} +1 -1
- package/dist/{google-DJV9Hjyw.js → google-BxIUmp_8.js} +2 -2
- package/dist/{google-DJV9Hjyw.js.map → google-BxIUmp_8.js.map} +1 -1
- package/dist/headless.d.ts +1 -1
- package/dist/{host-9vLbGyJq.js → host-n1AYC9-H.js} +9 -9
- package/dist/{host-9vLbGyJq.js.map → host-n1AYC9-H.js.map} +1 -1
- package/dist/{host-signals-DMndC3WQ.js → host-signals-eQf9F1Rl.js} +5 -5
- package/dist/{host-signals-DMndC3WQ.js.map → host-signals-eQf9F1Rl.js.map} +1 -1
- package/dist/{host-version-B6zEy_l1.js → host-version-EkzK6xdV.js} +2 -2
- package/dist/{host-version-B6zEy_l1.js.map → host-version-EkzK6xdV.js.map} +1 -1
- package/dist/{index-D2HJUCR1.d.ts → index-BypbUp-D.d.ts} +4 -4
- package/dist/{index-D2HJUCR1.d.ts.map → index-BypbUp-D.d.ts.map} +1 -1
- package/dist/{index-ByR7Be4d.d.ts → index-CNq4AYES.d.ts} +37 -10
- package/dist/index-CNq4AYES.d.ts.map +1 -0
- package/dist/{index-BI6RZc60.d.ts → index-DqCio7Nd.d.ts} +7 -4
- package/dist/{index-BI6RZc60.d.ts.map → index-DqCio7Nd.d.ts.map} +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +5 -5
- package/dist/ipc/browser.d.ts +3 -3
- package/dist/ipc/remote.d.ts +6 -6
- package/dist/ipc/remote.js +3 -3
- package/dist/{ipc-DBOylNnG.js → ipc-DUqSK-SB.js} +4 -4
- package/dist/{ipc-DBOylNnG.js.map → ipc-DUqSK-SB.js.map} +1 -1
- package/dist/ipc.d.ts +10 -10
- package/dist/ipc.js +5 -5
- package/dist/{links-DMWKvAmD.js → links-DivTLyDT.js} +8 -8
- package/dist/{links-DMWKvAmD.js.map → links-DivTLyDT.js.map} +1 -1
- package/dist/{loaded-entry-CaFgDCMz.js → loaded-entry-D93ZwfH8.js} +2 -2
- package/dist/{loaded-entry-CaFgDCMz.js.map → loaded-entry-D93ZwfH8.js.map} +1 -1
- package/dist/mcp.d.ts +1 -1
- package/dist/{media-type-DDrpCEf9.d.ts → media-type-vJuUTlW5.d.ts} +2 -2
- package/dist/{media-type-DDrpCEf9.d.ts.map → media-type-vJuUTlW5.d.ts.map} +1 -1
- package/dist/{memory-CoaLfuI2.js → memory-D060YOj_.js} +27 -19
- package/dist/memory-D060YOj_.js.map +1 -0
- package/dist/output/stream-json.d.ts +1 -1
- package/dist/output/terminal.d.ts +1 -1
- package/dist/{path-display-DV6PlTOE.js → path-display-Dm4nSwwF.js} +3 -3
- package/dist/{path-display-DV6PlTOE.js.map → path-display-Dm4nSwwF.js.map} +1 -1
- package/dist/plugins.d.ts +1 -1
- package/dist/presets.d.ts +1 -1
- package/dist/{protocol-BAXNtbj5.d.ts → protocol-DlFZqIbu.d.ts} +5 -5
- package/dist/{protocol-BAXNtbj5.d.ts.map → protocol-DlFZqIbu.d.ts.map} +1 -1
- package/dist/providers/anthropic.d.ts +1 -1
- package/dist/providers/arcee.d.ts +1 -1
- package/dist/providers/baseten.d.ts +1 -1
- package/dist/providers/cerebras.d.ts +1 -1
- package/dist/providers/google.d.ts +1 -1
- package/dist/providers/google.js +1 -1
- package/dist/providers/local.d.ts +1 -1
- package/dist/providers/neuralwatt.d.ts +1 -1
- package/dist/providers/openai-compat.d.ts +1 -1
- package/dist/providers/openai.d.ts +1 -1
- package/dist/providers/openrouter.d.ts +1 -1
- package/dist/providers/xai.d.ts +1 -1
- package/dist/{providers-cSrUyM2h.js → providers-CuMn0Kkq.js} +2 -2
- package/dist/{providers-cSrUyM2h.js.map → providers-CuMn0Kkq.js.map} +1 -1
- package/dist/providers.d.ts +1 -1
- package/dist/providers.js +1 -1
- package/dist/{registry-4T13yxMT.js → registry-CGYWxMNj.js} +2 -2
- package/dist/{registry-4T13yxMT.js.map → registry-CGYWxMNj.js.map} +1 -1
- package/dist/{registry-8mnp3zJf.js → registry-DWYR40B2.js} +2 -2
- package/dist/{registry-8mnp3zJf.js.map → registry-DWYR40B2.js.map} +1 -1
- package/dist/{registry-BBzysAGz.js → registry-yhXC9O2x.js} +2 -2
- package/dist/{registry-BBzysAGz.js.map → registry-yhXC9O2x.js.map} +1 -1
- package/dist/{remote-hosts-G62uJ45a.js → remote-hosts-DpAyu0ER.js} +4 -4
- package/dist/{remote-hosts-G62uJ45a.js.map → remote-hosts-DpAyu0ER.js.map} +1 -1
- package/dist/restate.d.ts +1 -1
- package/dist/session/sqlite.d.ts +1 -1
- package/dist/session.d.ts +1 -1
- package/dist/{setting-BWlU8Liz.js → setting-wx57dbgJ.js} +2 -2
- package/dist/{setting-BWlU8Liz.js.map → setting-wx57dbgJ.js.map} +1 -1
- package/dist/{settings-keys-DpQ5m5oZ.js → settings-keys-Dmig23l3.js} +2 -2
- package/dist/{settings-keys-DpQ5m5oZ.js.map → settings-keys-Dmig23l3.js.map} +1 -1
- package/dist/skills.d.ts +1 -1
- package/dist/{sqlite-runtime-D7WG9VL_.d.ts → sqlite-runtime-D2N0m9XE.d.ts} +2 -2
- package/dist/sqlite-runtime-D2N0m9XE.d.ts.map +1 -0
- package/dist/{system-freeze-CGSHvvCg.js → system-freeze-C3g8HY4t.js} +2 -2
- package/dist/{system-freeze-CGSHvvCg.js.map → system-freeze-C3g8HY4t.js.map} +1 -1
- package/dist/tools/fetch-url.d.ts +1 -1
- package/dist/tools/web-search.d.ts +1 -1
- package/dist/tools.d.ts +1 -1
- package/dist/tui.d.ts +9 -9
- package/dist/tui.js +15 -15
- package/dist/{types-DVuB6yk8.d.ts → types-CPxqnCeG.d.ts} +2 -2
- package/dist/{types-DVuB6yk8.d.ts.map → types-CPxqnCeG.d.ts.map} +1 -1
- package/dist/types.d.ts +1 -1
- package/dist/{version-BoECn_c8.js → version-3w8QMAyl.js} +2 -2
- package/dist/{version-BoECn_c8.js.map → version-3w8QMAyl.js.map} +1 -1
- package/dist/{wire-DYBrjw6p.js → wire-Ct6nuXL5.js} +2 -2
- package/dist/{wire-DYBrjw6p.js.map → wire-Ct6nuXL5.js.map} +1 -1
- package/dist/{ws-client-iv10YsKH.js → ws-client-DAm6UPtq.js} +2 -2
- package/dist/{ws-client-iv10YsKH.js.map → ws-client-DAm6UPtq.js.map} +1 -1
- package/dist/{ws-ByUKaCyV.js → ws-olbe6ZfF.js} +4 -4
- package/dist/{ws-ByUKaCyV.js.map → ws-olbe6ZfF.js.map} +1 -1
- package/docs/EXTENSIONS.md +1 -1
- package/package.json +1 -1
- package/dist/index-ByR7Be4d.d.ts.map +0 -1
- package/dist/memory-CoaLfuI2.js.map +0 -1
- package/dist/sqlite-runtime-D7WG9VL_.d.ts.map +0 -1
package/dist/tui.js
CHANGED
|
@@ -9,7 +9,7 @@ import { splitSystemPrompt } from "./prompt.js";
|
|
|
9
9
|
import { a as getExtensionSessionState, l as setExtensionSessionState, r as deleteExtensionSessionState, s as loadSession, t as createSession, u as withExtensionSession } from "./session-DKj1VfH0.js";
|
|
10
10
|
import { n as humanBytes } from "./format-bytes-LHrZVMIt.js";
|
|
11
11
|
import { r as isJson } from "./json-BjClr43H.js";
|
|
12
|
-
import { At as ensureKeybindingsFile, Dt as KEYBINDING_DEFS, I as UI_TOKEN_NAMES, Mt as groupBindings, Nt as keybindingsPath, Pt as matchesBinding, Rt as readKeybindingsRaw, St as chordKey, Tt as resolveMod, bt as withSettingsPages, i as onPanelChanged, jt as formatBindingForDisplay, kt as KEYBINDING_KEY_COL_WIDTH, l as onSettingsPagesChanged, pt as createExtensionHostRuntimeBridge, qt as isValueSetting, u as runtimeSettingsWire, xt as builtinKeymapEntries, z as settingsWire, zt as resolveExtensionKeybindings } from "./registry-
|
|
12
|
+
import { At as ensureKeybindingsFile, Dt as KEYBINDING_DEFS, I as UI_TOKEN_NAMES, Mt as groupBindings, Nt as keybindingsPath, Pt as matchesBinding, Rt as readKeybindingsRaw, St as chordKey, Tt as resolveMod, bt as withSettingsPages, i as onPanelChanged, jt as formatBindingForDisplay, kt as KEYBINDING_KEY_COL_WIDTH, l as onSettingsPagesChanged, pt as createExtensionHostRuntimeBridge, qt as isValueSetting, u as runtimeSettingsWire, xt as builtinKeymapEntries, z as settingsWire, zt as resolveExtensionKeybindings } from "./registry-DWYR40B2.js";
|
|
13
13
|
import { p as tailTruncate } from "./wait-task-CmDnlfkC.js";
|
|
14
14
|
import { n as appendCapped } from "./output-cap-DajSaBRo.js";
|
|
15
15
|
import { n as setDebugLogSink, t as createDebugLog } from "./debug-log-DyKmu0Wv.js";
|
|
@@ -27,35 +27,35 @@ import { i as loadMarkdownCommands } from "./headless-CmXXkd-6.js";
|
|
|
27
27
|
import { F as configureGithubClient, i as isBadgeColor } from "./row-fields-CAYcZogp.js";
|
|
28
28
|
import { f as sessionBadges, l as refreshArtifact, r as artifactKindLabel, u as renderArtifactRow } from "./builtin-artifact-kinds-DsqaAQjX.js";
|
|
29
29
|
import { n as basic_default } from "./presets-NL1CRPXN.js";
|
|
30
|
-
import { t as ZIDANE_VERSION } from "./version-
|
|
30
|
+
import { t as ZIDANE_VERSION } from "./version-3w8QMAyl.js";
|
|
31
31
|
import { r as browseSkillSource, s as installSkillFromSpec } from "./skills-CQPEsEfn.js";
|
|
32
32
|
import { a as skillCategory, i as groupSkillPicks, o as skillPickKey, s as skillPickOf, t as RECOMMENDED_SKILL_SOURCES } from "./sources-h464u_hH.js";
|
|
33
|
-
import { _ as extensionScaffold, b as validateExtensionName$1, d as ZIDANE_SKILL_EDIT_SKILL_NAME, u as ZIDANE_EXTENSION_SKILL_NAME } from "./system-freeze-
|
|
33
|
+
import { _ as extensionScaffold, b as validateExtensionName$1, d as ZIDANE_SKILL_EDIT_SKILL_NAME, u as ZIDANE_EXTENSION_SKILL_NAME } from "./system-freeze-C3g8HY4t.js";
|
|
34
34
|
import { B as badgeMenu, F as bindingAlternatives, J as runBadgeAction, L as parseBindingSpec, O as panelBadgeText, T as normalizePanelContent, Y as sessionBadgeTarget, _ as sortRows, b as filterRows, c as renderTemplate, q as normalizeBadgeTarget, y as compileQuery$1, z as artifactBadgeTarget } from "./references-4kd0dyV5.js";
|
|
35
35
|
import { i as nextLogLevel, n as filterLogRecords, r as formatLogLine } from "./logs-view-DF7ArI6t.js";
|
|
36
36
|
import { a as createRingBufferSink, c as logFileTimestamp, i as createLoggingHooks, n as createFileSink, o as fanoutSink, r as createLogger } from "./logger-BQj8QCJp.js";
|
|
37
|
-
import { c as inlineLoadedExtension, d as parseExtensionScanPathEnv, m as scanExtensionDirectories, s as importExtensionEntry, u as loadableExtensionDirs } from "./discovery-
|
|
37
|
+
import { c as inlineLoadedExtension, d as parseExtensionScanPathEnv, m as scanExtensionDirectories, s as importExtensionEntry, u as loadableExtensionDirs } from "./discovery-CC6Uhvm8.js";
|
|
38
38
|
import { a as registerExtensionApiHostModules, o as registerExtensionHostModules } from "./host-modules-C2GGiSjg.js";
|
|
39
|
-
import { A as removeInstalledExtension, F as extensionRuntimeOf, H as registryViewState, I as filterExtensionRegistry, L as filterRegistryPlugins, M as reloadChangedExtensions, N as buildExtensionRegistry, O as readExtensionInstallOrigin, P as disposeExtensionRegistry, Q as sanitizeExtensionConfigActionPatch, R as partitionExtensionCatalog, S as changeExtensionOrigin, T as installExtensionFromSpec, Z as resolveExtensionConfigValue, b as loadExtensionsConfig, g as applyExtensionsConfigReport, h as createConfigSettingsLayer, i as createExtensionPromptBridge, j as updateInstalledExtension, m as discoverAndBuildExtensionRegistry, q as coerceExtensionConfigInput, st as resolveUiEntries, v as configuredExtensions, x as ExtensionInstallError, y as createExtensionsConfigSync, z as createRegistryView } from "./extensions-
|
|
40
|
-
import { C as createSessionSettingsStore, D as
|
|
39
|
+
import { A as removeInstalledExtension, F as extensionRuntimeOf, H as registryViewState, I as filterExtensionRegistry, L as filterRegistryPlugins, M as reloadChangedExtensions, N as buildExtensionRegistry, O as readExtensionInstallOrigin, P as disposeExtensionRegistry, Q as sanitizeExtensionConfigActionPatch, R as partitionExtensionCatalog, S as changeExtensionOrigin, T as installExtensionFromSpec, Z as resolveExtensionConfigValue, b as loadExtensionsConfig, g as applyExtensionsConfigReport, h as createConfigSettingsLayer, i as createExtensionPromptBridge, j as updateInstalledExtension, m as discoverAndBuildExtensionRegistry, q as coerceExtensionConfigInput, st as resolveUiEntries, v as configuredExtensions, x as ExtensionInstallError, y as createExtensionsConfigSync, z as createRegistryView } from "./extensions-hHKXiXSo.js";
|
|
40
|
+
import { C as createSessionSettingsStore, D as createFlowRegistry, O as watchFileChanges, S as createDaemonSettingsPort, b as createHostEnvironment, c as wireIntegration, k as watchExtensionFolders, n as startInProcessHost, w as createHostImagePort, x as createStorageSyncHub } from "./memory-D060YOj_.js";
|
|
41
41
|
import { d as pushPaletteRecent, f as rankPaletteItems, m as settingsSidebar, o as fuzzyMatch, p as settingsSearchIndex, s as groupPaletteRows } from "./palette-DhfYhvnx.js";
|
|
42
42
|
import { a as DEFAULT_OAUTH_ACCOUNT_LABEL, p as oauthAccountLabel } from "./cred-keys-C0KaSRp7.js";
|
|
43
|
-
import { A as getContextWindow, B as restoreModelOptions, D as credKeyOf, F as modelSupportsReasoning, N as modelLabel, P as modelOptionsFor, _ as setCredentialLabel, g as removeStoredCredential, i as credentialsPath, j as getModelInfo, k as enabledModelOptions, m as readProviderCredentials, t as applyApiKeyEnv, v as setPreferredCredential, w as BUILTIN_PROVIDERS, y as setProviderCredential, z as piIdOf } from "./credentials-
|
|
43
|
+
import { A as getContextWindow, B as restoreModelOptions, D as credKeyOf, F as modelSupportsReasoning, N as modelLabel, P as modelOptionsFor, _ as setCredentialLabel, g as removeStoredCredential, i as credentialsPath, j as getModelInfo, k as enabledModelOptions, m as readProviderCredentials, t as applyApiKeyEnv, v as setPreferredCredential, w as BUILTIN_PROVIDERS, y as setProviderCredential, z as piIdOf } from "./credentials-Bf8Bz4X-.js";
|
|
44
44
|
import { n as renderDefaultCallbackPage } from "./render-gPS08Uiz.js";
|
|
45
|
-
import { n as createCredentialsAuthStore } from "./auth-store-port-
|
|
45
|
+
import { n as createCredentialsAuthStore } from "./auth-store-port-BHEXS3VS.js";
|
|
46
46
|
import { n as RpcCallError } from "./rpc-Daec0xVh.js";
|
|
47
47
|
import { $ as instructionPreviewLines, A as NOTICE_GLYPH, At as sessionKey, F as MACHINE_LINK_STATE_TEXT, Ft as CONTINUE_PROMPT, G as machineSetupCommand, J as offlineSinceText, K as machineVersionDiffers, Lt as viewQuery, Mt as HostRemovedError, Nt as UnknownHostIdError, O as resolveActiveTab, P as validateMcpForm, Pt as createHostIndex, Q as instructionOriginBadge, R as clockText, St as sameAuthTarget, T as pickTab, Tt as MAX_IMAGE_ATTACHMENT_BYTES, V as lastSeenText, Z as buildVisibleInstructionRows, _t as selectableSources, a as createRunStopMarker, at as noteLabel, bt as authPrimaryAction, dt as toolOverview, et as daysEndingAt, gt as parentProviderKey, i as streamRateValue, it as foldsInCompactShape, j as MCP_TRANSPORTS, k as togglePanel, kt as parseSessionKey, lt as messagePreview, mt as indexOfProviderRow, nt as heatmapThresholds, o as tidyPromptText, ot as planFold, p as INITIAL_PANEL_STATE, pt as buildVisibleAuthRows, q as machineWaiting, r as stepStreamRate, rt as foldSummary, s as ARTIFACTS_PANEL_ID, st as thoughtLabel, t as EMPTY_RATE, tt as heatmapLevel, vt as authFailureHeadline, wt as MAX_FILE_ATTACHMENT_BYTES, x as cycleTab, xt as authProviderKeys, y as buildPanelCatalog, yt as authOffersSignInFallback, z as environmentLabel, zt as groupRows } from "./stream-rate-_85QrCSG.js";
|
|
48
48
|
import { t as JsonRpcConnectionClosedError } from "./json-rpc-G0rBfEar.js";
|
|
49
49
|
import { d as buildBuildSystem, f as buildPlanSystem } from "./agent-prompt-BXVwL89Y.js";
|
|
50
50
|
import { E as buildStepRetryMessage, F as planProgressLabel, P as planProgress, T as buildPlanResumeMessage, a as SECRET_TTLS, c as isSecretAnswer, l as isSecretName, o as SECRET_TTL_LABELS, r as SECRETS_ENV_VAR } from "./protocol-741icQKD.js";
|
|
51
51
|
import { i as PRESENT_PLAN_TOOL, o as createAutomaticInteractionResponse, r as HOST_INTERACTION_ID_PREFIX, t as ASK_USER_TOOL, u as isModelInteraction } from "./interactions-protocol-8n_AKn7Q.js";
|
|
52
|
-
import { S as profileComposition, _ as availableAgents, a as deleteSessionData, i as createSessionInStore, v as builtInPromptOf } from "./setting-
|
|
52
|
+
import { S as profileComposition, _ as availableAgents, a as deleteSessionData, i as createSessionInStore, v as builtInPromptOf } from "./setting-wx57dbgJ.js";
|
|
53
53
|
import { a as mostConstrainedWindow, c as updatedLabel, d as TODO_STATUS_GLYPHS, i as formatUsagePercent, l as usageTone, n as formatBalance, o as resetLabel, s as showsAccount, u as accentColor } from "./provider-usage-format-cOCNGSjh.js";
|
|
54
54
|
import { i as assertEnvironmentReady, n as EnvironmentNotReadyError, o as createEnvironmentRegistry, p as readSessionEnvironment, r as LOCAL_ENVIRONMENT, u as initialEnvironment, v as verifyEnvironment } from "./environment-DAZPEz-r.js";
|
|
55
55
|
import { E as restoreChainFallbacks, O as toggleChainEntry, T as reorderKeyed, b as pickChainPrimary, g as chainsEqual, h as chainPositionOf, m as chainEntryKey, p as chainAccountConflict, r as editableTurnText, s as turnAsText, u as readSessionAccount, v as filterChainFallbacks, w as rememberableChain } from "./turn-operations-CWoCTC_L.js";
|
|
56
56
|
import { A as SESSION_EVENT_STATUS_STYLE, C as formatModelSetting, Q as sessionEventMeta, R as isMainSession, S as spacesEnabled, X as sessionEventExcerpt, Y as sessionDirLabel, _ as spaceIdForNewSession, a as defaultSessionAgent, b as spaceOfSwitchItem, ct as formatCostUsd, f as newSpaceId, ft as formatTokenCount, h as resolveSessionSpace, ht as nameFromModelId, m as readSessionSpaceId, n as DEFAULT_SPACE_NAME, o as defaultSessionKnobs, p as normalizeSpaces, r as SPACE_METADATA_KEY, rt as truncateTitle, s as defaultSessionModel, st as fitRunReceiptCells, t as DEFAULT_SPACE_ID, tt as shortSessionId, ut as formatRunReceiptCells, w as parseModelSetting, x as spaceSwitchItems } from "./spaces-BdDAbJDx.js";
|
|
57
57
|
import { N as suggestSafelistEntries, a as renderSystemMdSeed, d as discoverProjectMcps, i as discoverSystemMd, o as userScopeOverridesLoad, s as userSystemMdPath, t as createFileEnvironmentSecrets } from "./environment-credentials-B0nivYLV.js";
|
|
58
|
-
import { A as clearProviderUsageCache, Bt as mcpsWritePath, Dn as createBuiltinCommands, En as discoverProjectSkills, Fn as resolveSessionModel, G as detectOnboardingEnvironment, Gn as readRemoteSandboxRef, Gt as runIntegrationSignIn, Ht as upsertMcpServer, I as usageChecksOptedOut, Jt as supportsOAuth, Kt as runOAuthLogin, M as fetchProviderUsage, Mn as discoverAgentsMd, On as applyThinkingBindingSetting, P as providerUsageSupported, Pn as createProviderBuilder, Q as listExtensionSource, Qt as createArtifactKindsHost, R as fetchGithubUsage, Rt as listProjectFiles, U as writeSessionExport, Ut as oauthUsesManualCodePaste, Vt as removeMcpServer, W as connectorGithubToken, Wt as pickOAuthSelectOption, X as onboardingProviders, Xt as tryRevealPath, Yt as tryOpenBrowser, _n as storeHasDurability, _r as testDecisionModel, cr as refreshMcpToolsCatalog, en as resolveConfig, er as resolveSessionCwd, et as claudeImportHostNote, fn as createCatalogPorts, gn as readPinnedSkills, hr as parseDecisionModel, ir as parsePluginScanPathEnv, it as previewClaudeImport, j as fetchAllProviderUsage, jn as installProviderDiagnosticHook, ln as provisionSessionEnvironment, mn as PINNED_SKILLS_META_KEY, mr as listDecisionModels, nr as buildPluginContributions, nt as hasClaudeCodeSetup, on as createFileMcpCredentialStore, or as loadMcpToolsCache, pn as linkCatalogs, q as onboardingInstallSignals, qt as signsInWithIntegration, rr as discoverProjectPlugins, rt as importFromClaudeCode, sr as mcpToolsCachePath, tn as resolveStoragePaths, tt as countClaudeSessionFiles, ur as subscribeMcpToolsCache, vr as applyExtensionAgents, wn as createSkillNameProbe, yr as changedCatalogItems, z as aggregateUsage, zn as builtinEnvironmentProviders } from "./auto-update-restart-
|
|
58
|
+
import { A as clearProviderUsageCache, Bt as mcpsWritePath, Dn as createBuiltinCommands, En as discoverProjectSkills, Fn as resolveSessionModel, G as detectOnboardingEnvironment, Gn as readRemoteSandboxRef, Gt as runIntegrationSignIn, Ht as upsertMcpServer, I as usageChecksOptedOut, Jt as supportsOAuth, Kt as runOAuthLogin, M as fetchProviderUsage, Mn as discoverAgentsMd, On as applyThinkingBindingSetting, P as providerUsageSupported, Pn as createProviderBuilder, Q as listExtensionSource, Qt as createArtifactKindsHost, R as fetchGithubUsage, Rt as listProjectFiles, U as writeSessionExport, Ut as oauthUsesManualCodePaste, Vt as removeMcpServer, W as connectorGithubToken, Wt as pickOAuthSelectOption, X as onboardingProviders, Xt as tryRevealPath, Yt as tryOpenBrowser, _n as storeHasDurability, _r as testDecisionModel, cr as refreshMcpToolsCatalog, en as resolveConfig, er as resolveSessionCwd, et as claudeImportHostNote, fn as createCatalogPorts, gn as readPinnedSkills, hr as parseDecisionModel, ir as parsePluginScanPathEnv, it as previewClaudeImport, j as fetchAllProviderUsage, jn as installProviderDiagnosticHook, ln as provisionSessionEnvironment, mn as PINNED_SKILLS_META_KEY, mr as listDecisionModels, nr as buildPluginContributions, nt as hasClaudeCodeSetup, on as createFileMcpCredentialStore, or as loadMcpToolsCache, pn as linkCatalogs, q as onboardingInstallSignals, qt as signsInWithIntegration, rr as discoverProjectPlugins, rt as importFromClaudeCode, sr as mcpToolsCachePath, tn as resolveStoragePaths, tt as countClaudeSessionFiles, ur as subscribeMcpToolsCache, vr as applyExtensionAgents, wn as createSkillNameProbe, yr as changedCatalogItems, z as aggregateUsage, zn as builtinEnvironmentProviders } from "./auto-update-restart-Dkdz6rq4.js";
|
|
59
59
|
import { C as commandHeaderBlock, D as noteDisplay, E as gatherCommandNotes, d as upsertToolProgress, l as scriptProgressKey, s as scriptProgressByCall, u as scriptProgressView, w as commandNoteText } from "./script-progress-ByANn11p.js";
|
|
60
60
|
import { A as summarizeOutcomes, _ as extractEditPayload, f as buildContextualDiff, l as promptSegmentLines, m as clipDiffForRender, p as buildUnifiedDiff, t as oneLineTitle, u as splitPromptSegments, v as filetypeFromPath, x as summarizeEditPayload, y as previewEditPayload } from "./session-title-text-CQvgo3yS.js";
|
|
61
61
|
import { D as usageByModel, S as sumRunCosts, a as eventsFromTurns, b as sessionEnvironmentSummary, c as headerFromData, d as loadState, f as marginTopFor, i as deriveSessionTitle, l as lastContextSizeFromTurns, o as getSessionHeader, p as noticeTurnContent, s as getSessionMeta, u as listSessionMeta, v as saveState, w as toolCallPreview } from "./store-CjpqVefW.js";
|
|
@@ -64,22 +64,22 @@ import { At as isVisibleDuringSearch, Ct as EDIT_TOOL_NAMES, Dt as isTurnHighlig
|
|
|
64
64
|
import { d as launchOverridesFrom, n as createSessionExecutionCache, s as describeTitleStatus, t as testModel } from "./model-test-B-Y0ne-s.js";
|
|
65
65
|
import { A as decisionsEnabled, E as DEFAULT_SETTINGS, M as settingsFromStored, N as sparseSettingsUpdate, _ as resolveChipColor, a as SETTINGS_INPUTS, c as clampFps, d as settingKeywords, f as settingsSectionOf, h as BUILTIN_THEMES, i as SETTINGS_CHOICES, l as enforceSettingsInvariants, m as toggleHeldOn, r as SETTINGS_CATEGORIES, s as SETTINGS_TOGGLES, t as APPROVAL_MODE_OPTIONS, u as requirementMet, v as resolveTheme } from "./settings-catalog-C8uSElb9.js";
|
|
66
66
|
import { $ as nativeExtensionSource, A as transcriptPresetNotice, At as currentModelKeys, Bt as compactingParts, C as SETUP_PALETTE_ITEM, D as TRANSCRIPT_PRESET_KEYS, E as TRANSCRIPT_PRESETS, Ft as createChatsCompletionProvider, Gt as daemonGate, Ht as retryLabel, I as ONBOARDING_FEATURE_GROUPS, Jt as isKillSwitchEngaged, L as onboardingFeatureCopy, Lt as cacheBreakChip, M as transcriptPresetOfPaletteItem, N as transcriptPresetPaletteItem, P as transcriptPresetPalettePicker, Q as nativeExtensionByName, R as onboardingFeatures, U as DEFAULT_EXTENSION_SOURCE, Ut as runStatusCells, Vt as liveSessionCost, Y as NATIVE_EXTENSIONS, Yt as remoteHostsGate, Z as NATIVE_EXTENSION_GROUPS, c as migratedOnboardingRecords, et as enabledMcpsWith, g as canSkipOnboardingStep, j as transcriptPresetOf, k as transcriptPreset, l as needsOnboarding, rt as classifyMcpTest, s as mergeOnboardingState, tt as enabledMcpsWithout, w as onboardingStep } from "./usage-summary-3xm9Zadp.js";
|
|
67
|
-
import { i as detectAuth, r as activeAccountOf } from "./cli-shared-
|
|
67
|
+
import { i as detectAuth, r as activeAccountOf } from "./cli-shared-VGYq10bZ.js";
|
|
68
68
|
import { a as scheduleTargetSession, i as scheduleLabel } from "./validate-53YmvQ3V.js";
|
|
69
69
|
import { a as settingsFromWire, c as applyEnvironmentSettingsChange, i as overlayHostSettings, n as WINDOW_LOCAL_SETTINGS, o as settingsToWire, p as resolveProviderConfig, r as isWindowOnlySetting, s as splitHostSettingsPatch, u as describeEnvironments } from "./host-scoped-settings-jlq5zWs4.js";
|
|
70
70
|
import { a as isMethodNotFound, n as LOCAL_HOST_KEY, r as LOCAL_HOST_NAME } from "./connection-BaHd3T-D.js";
|
|
71
71
|
import { f as hostRefOf, g as loadSessionDocument, h as loadEventsTail, m as loadEventsPage, p as loadAllEvents, r as IpcErrorCode } from "./protocol-MxDL3YeM.js";
|
|
72
|
-
import { n as runRemoteOAuth, t as runWorkspaceExecStream } from "./ipc-
|
|
72
|
+
import { n as runRemoteOAuth, t as runWorkspaceExecStream } from "./ipc-DUqSK-SB.js";
|
|
73
73
|
import { c as formatJoinString, u as createExtensionsClient, v as scopeAllows } from "./browser-Cu-qGbMl.js";
|
|
74
74
|
import { a as SYNC_MODES, f as syncAgo, i as SYNC_CATEGORY_INFO, o as SYNC_MODE_LABEL, p as syncMarkerOf, r as SYNC_CATEGORIES, u as settingField } from "./types-Skz6Z48Z.js";
|
|
75
75
|
import { t as keepHostConnected } from "./connection-loop-DSCehV3W.js";
|
|
76
76
|
import { r as parseRemoteHostUrl, t as RemoteHostError } from "./url-znC3tmKE.js";
|
|
77
77
|
import { createTuiStore } from "./session/sqlite.js";
|
|
78
|
-
import { E as groupArtifacts, d as buildRestartHint, f as buildUpdateHint, h as useUpdateCheck, m as useRestartRequired, n as buildHints, o as autoInstallViaWorker, p as useAutoInstallUpdate, t as formatPathForCwd } from "./path-display-
|
|
78
|
+
import { E as groupArtifacts, d as buildRestartHint, f as buildUpdateHint, h as useUpdateCheck, m as useRestartRequired, n as buildHints, o as autoInstallViaWorker, p as useAutoInstallUpdate, t as formatPathForCwd } from "./path-display-Dm4nSwwF.js";
|
|
79
79
|
import { A as clipHintsToWidth, B as createDiscoverySlot, C as McpAuthProvider, D as useInteractionsActions, E as InteractionsProvider, F as SettingsOverride, G as ConfigProvider, H as useDiscovery, I as SettingsProvider, J as createArtifactsCompletionProvider, K as useConfig, L as useSettings$1, M as hintsLength, N as truncateTrailing, O as useInteractionsQueue, P as useEnabledToggleSet, Q as bootTick, R as parseEditorCommand, S as parentServerName, T as useMcpAuthState, U as useDiscoveryOptional, V as DiscoveryProvider, W as ConfigContext, X as useCompletion, a as useSurfaces, b as buildVisibleMcpRows, c as useStreamBuffer, d as useSafeModeQueue, g as redirectUriFromAuthUrl, i as useSelectStyle, k as EMPTY_HINTS, l as SafeModeProvider, m as fetchOAuthRedirect, n as ThemeProvider, o as useSyntaxStyles, p as withRunningCallStarts, r as useColors, s as useTheme, t as computeTurnAnchors, u as useSafeModeActions, v as useMcpToolToggleMap, w as useMcpAuthDispatch, x as indexOfServerRow, z as quoteForShell } from "./transcript-anchors-CJDv-zeW.js";
|
|
80
80
|
import { $ as ONBOARDING_WORDS, A as stepTranscriptCap, B as RUN_WAITING_LABEL, C as isEarlierHiddenMarker, Ct as getMcpAuthStatus, D as revealEarlierTranscriptEvents, Dt as chunkMarkdownForRender, E as replaceTranscriptTurnEvents, G as APPROVAL_MODE_TRADEOFFS, Gt as blendHsl, H as runRetryingLabel, It as DAEMON_HEALTH_STYLE, J as createOnboardingRun, Jt as cacheHintText, K as SETTING_TRADEOFFS, Kt as buildLinearRamp, L as spawnParents, N as turnContextSize, Nt as splitMarkdownCodeBlocks, Ot as closeDanglingCodeFence, P as withEarlierHidden, Pt as stripHtmlCommentsOutsideCode, Q as ONBOARDING_AGENT_NAMES, Rt as createSkillsCompletionProvider, S as hiddenEarlierTranscriptCount, St as MCP_STATUS_LABEL, U as runStatusKey, V as runFoldStatus, Vt as createFilesCompletionProvider, W as runTailActivity, Wt as createCommandsCompletionProvider, X as onboardingSwitchedFeatures, Y as onboardingImportParts, _ as capTranscriptEvents, _t as buildModelCatalog, a as displayNameFor, b as finalizeStreamingMarkdown, ct as ONBOARDING_PREVIEW_EVENTS, dt as CONNECTORS, et as connectorAuthText, ft as CONNECTOR_CATEGORIES, gt as connectorServerConfig, ht as connectorInstalled, j as streamTailRoot, jt as normalizeMarkdownCodeFences, kt as codeTokenHasClosingFence, lt as defaultImportSelection, mt as connectorInputError, n as reconcileEvents, nt as joinNames, o as formatToolCall, pt as connectorById, q as connectorsFromImport, r as TOOL_DISPLAY, rt as nativeExtensionNeedText, s as toolInputCode, t as convergeTranscript, v as coversTranscriptCap, vt as customModelTargets, wt as mcpFailureEvent, x as finalizeStreamingMarkdownForOwner, y as discardThinking, yt as filterModelCatalog, zt as uniqueSkillNamesFromReferences } from "./transcript-reconcile-Y_ukF9uY.js";
|
|
81
81
|
import { A as Well, B as useModalState, C as ListHeader, D as Switch, E as Segmented, F as Modal, G as inCheckboxZone, H as ModalHints, I as ModalRoot, K as parseHintKeySpec, L as ModalTopLayer, M as badgeWidth, N as badgesWidth, O as SwitchSpan, P as cellWidth, R as useModal, S as CursorMarkSpan, T as PickerRow, U as dispatchHintKey, V as HintRow, W as hintSpans, _ as BADGE_GAP, a as HostPickerModal, b as Check, c as hostStatusLook, d as EnvironmentPickerModal, f as hostUnavailableReason, g as waitForHostSettled, h as sessionHostGroups, i as pickMachineFolder, j as badgeColor$1, k as TitleBadges, l as orderRowsByHost, m as listAcrossHosts, n as localMachineKinds, o as ServerFolderPickerModal, p as isHostReachable, r as machineOfPick, s as SessionHostHeader, t as CwdPickerModal, u as placeHostHeaders, v as Badge$1, w as Note, x as CursorMark, y as Badges, z as useModalAwareFocus } from "./cwd-picker-Ca5MN5wC.js";
|
|
82
|
-
import { i as wsTransport, n as lazyInProcessTransport, r as socketTransport, t as hostSignalHandlers } from "./host-signals-
|
|
82
|
+
import { i as wsTransport, n as lazyInProcessTransport, r as socketTransport, t as hostSignalHandlers } from "./host-signals-eQf9F1Rl.js";
|
|
83
83
|
import { Buffer } from "node:buffer";
|
|
84
84
|
import { basename, dirname, isAbsolute, join, resolve } from "node:path";
|
|
85
85
|
import * as fs from "node:fs";
|
|
@@ -17842,7 +17842,7 @@ function useRemoteHosts(deps) {
|
|
|
17842
17842
|
let cancelled = false;
|
|
17843
17843
|
let started = null;
|
|
17844
17844
|
remoteHostsLoads++;
|
|
17845
|
-
import("./remote-hosts-
|
|
17845
|
+
import("./remote-hosts-DpAyu0ER.js").then(({ startRemoteHosts }) => {
|
|
17846
17846
|
if (cancelled) return;
|
|
17847
17847
|
started = startRemoteHosts({
|
|
17848
17848
|
dataDir,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Eo as Preset, Hj as Provider, MF as PromptPart, QP as AgentBehavior, VF as SessionContentBlock, Wo as AgentOptions, XR as Session, bF as McpServerConfig, iz as SessionStore, sI as ToolResultContent, wI as ToolDef, zo as Agent } from "./index-DqCio7Nd.js";
|
|
2
2
|
import { f as ExecutionContext } from "./types-2HrgolQz.js";
|
|
3
3
|
//#region src/acp/client-declared-tools.d.ts
|
|
4
4
|
/** JSON-RPC method the agent sends to the client to run a client-declared tool. */
|
|
@@ -1044,4 +1044,4 @@ type AcpContentMapper = (content: string | ToolResultContent[]) => ToolCallConte
|
|
|
1044
1044
|
type AcpSessionContentMapper = (blocks: SessionContentBlock[]) => ContentBlock[];
|
|
1045
1045
|
//#endregion
|
|
1046
1046
|
export { PermissionOption as $, DeleteSessionRequest as A, ToolCallContent as At, JsonRpcId as B, createClientDeclaredTools as Bt, CancelNotification as C, SetSessionConfigOptionResponse as Ct, ContentChunk as D, TerminalOutputResponse as Dt, ContentBlock as E, TerminalExitStatus as Et, ImageContent as F, WriteTextFileRequest as Ft, JsonRpcSuccess as G, JsonRpcNotification as H, InitializeRequest as I, AcpClientToolSpec as It, LoadSessionRequest as J, ListSessionsRequest as K, InitializeResponse as L, CLIENT_TOOL_CALL_METHOD as Lt, EmbeddedResourceResource as M, ToolCallStatus as Mt, EnvVariable as N, ToolCallUpdate as Nt, Cost as O, TextContent as Ot, HttpHeader as P, ToolKind as Pt, NewSessionResponse as Q, JsonRpcError as R, CLIENT_TOOL_CANCEL_METHOD as Rt, BlobResourceContents as S, SetSessionConfigOptionRequest as St, ContentAnnotations as T, StopReason as Tt, JsonRpcRequest as U, JsonRpcMessage as V, parseClientToolSpecs as Vt, JsonRpcResponse as W, McpCapabilities as X, LoadSessionResponse as Y, NewSessionRequest as Z, AudioContent as _, SessionInfo as _t, AcpImplementationInfo as a, RequestPermissionOutcome as at, AvailableCommand as b, SessionNotification as bt, AcpModelOption as c, ResumeSessionRequest as ct, AcpPromptMapping as d, SessionCapabilities as dt, PlanEntry as et, AcpServerOptions as f, SessionConfigOption as ft, AgentCapabilities as g, SessionConfigSelectOptions as gt, AgentAuthCapabilities as h, SessionConfigSelectOption as ht, AcpErrorCode as i, ReadTextFileRequest as it, EmbeddedResource as j, ToolCallLocation as jt, CreateTerminalRequest as k, TextResourceContents as kt, AcpPeer as l, ResumeSessionResponse as lt, AcpSessionRuntime as m, SessionConfigSelectGroup as mt, AcpClientCapabilities as n, PromptRequest as nt, AcpMcpServer as o, RequestPermissionRequest as ot, AcpSessionContentMapper as p, SessionConfigOptionCategory as pt, ListSessionsResponse as q, AcpContentMapper as r, PromptResponse as rt, AcpModelChoice as s, ResourceLink as st, ACP_PROTOCOL_VERSION as t, PromptCapabilities as tt, AcpPermissionPolicy as u, Role as ut, AuthMethod as v, SessionMode as vt, CloseSessionRequest as w, SetSessionModeRequest as wt, AvailableCommandInput as x, SessionUpdate as xt, AuthenticateRequest as y, SessionModeState as yt, JsonRpcFailure as z, ClientToolCallResponse as zt };
|
|
1047
|
-
//# sourceMappingURL=types-
|
|
1047
|
+
//# sourceMappingURL=types-CPxqnCeG.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types-
|
|
1
|
+
{"version":3,"file":"types-CPxqnCeG.d.ts","names":["_$__client_declared_tools0.AcpClientToolSpec","_$___agent0.Agent"],"sources":["../src/acp/client-declared-tools.ts","../src/acp/types.ts"],"mappings":";;;;cAKa;;cAGA;;;;;;;UAUI;;EAEf;;EAEA;;EAEA,aAAa;;EAEb;;;UAIe;;EAEf;;EAEA;;;;;;;iBAac,qBAAqB,MAAM,6CAA6C;;;;;;;;iBAwDxE,0BACd,gBAAgB,qBAChB;EAAW,QAAQ;EAAS;IAC3B,eAAe;;;;cCjGL;;KAGD;;UAGK;;EAEf;;EAEA,IAAI;;EAEJ;;EAEA;;;UAIe;;EAEf;;EAEA;;EAEA;;;UAIe;;EAEf;;EAEA,IAAI;;EAEJ;;;UAIe;;EAEf;;EAEA,IAAI;;EAEJ,OAAO;;;KAIG,kBAAkB,iBAAiB;;KAEnC,iBAAiB,iBAAiB,sBAAsB;;UAGnD;;EAEf;;EAEA;;EAEA;;;aAIU;;EAEV;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;;UAIe;;EAEf,cAAc,gBAAgB,qBAAqB;;EAEnD,mBAAmB,gBAAgB,4BAA4B;;;;;;;UAQhD;;EAEf;;EAEA;;EAEA;;EAEA,QAAQ;;;UAIO;;EAEf;;IAEE;;IAEA;;;EAGF;;EAEA,QAAQ;;;UAIO;;EAEf;;EAEA,qBAAqB;;EAErB,aAAa,QAAQ;;EAErB,QAAQ;;;UAIO;;EAEf;;EAEA,qBAAqB;;EAErB,kBAAkB;;EAElB,sBAAsB;;EAEtB,OAAO;;EAEP,QAAQ;;;UAIO;;EAEf;;EAEA;;EAEA;;EAEA,QAAQ;;;UAIO;;EAEf;;EAEA;;EAEA,QAAQ;;;UAIO;;EAEf,SAAS;;EAET,QAAQ;;;UAIO;;EAEf,OAAO;;EAEP,SAAS;;EAET,wBAAwB;;EAExB,SAAS;;EAET,QAAQ;;EAER,Q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5G,YAAY;;;;;EAKZ,cAAc;;EAEd,gBAAgB,SAAS,wBAAwB;;EAEjD,eAAe;;;;;EAKf,QAAQ;;;;;EAKR;;EAEA,gBAAgB;;EAEhB,WAAW;;;;;;;EAOX;;EAEA,aAAa;;;;;EAKb;;;;;EAKA;;;;;EAKA;;EAEA,eAAe,QAAQ,KAAK;;;UAIb;;EAEf,QAAQ;;EAER;;;KAIU,oBAAoB,kBAAkB,wBAAwB;;KAG9D,2BAA2B,QAAQ,0BAA0B"}
|
package/dist/types.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { $P as
|
|
1
|
+
import { $P as AgentClock, $j as ToolResult, AF as PromptDocumentPart, AR as ToolStateStore, Ai as ValidationResult, BF as RunHookMap, BI as SkillConfig, Bt as MutationValidationMutation, C as statsByModel, CI as ToolContext, DF as ProgressNudgeKind, DI as ToolDescriptions, DP as AgentDecide, DR as StagedToolState, EF as OAuthRefreshHookContext, EI as ToolDescriptionTarget, EN as CerebrasParams, Eo as Preset, FF as RepeatGuardConfig, FP as DecisionFailure, FR as ThinkingLevel, GF as SessionTurn, GP as DecisionRequest, GR as CreateSessionOptions, Go as AgentToolState, HF as SessionEndStatus, HI as SkillResource, HP as DecisionQuestion, Hj as Provider, Ht as SuccessfulMutationOutcome, IF as RepeatGuardToolMatcher, IP as DecisionFailureReason, KF as SpawnHookContext, KI as McpConnection, KN as AnthropicParams, LF as ResolveContentRef, LM as OpenAIParams, LP as DecisionInput, Lt as MutationValidationBatch, MF as PromptPart, MI as ReadStateMap, NF as PromptTextPart, OF as ProgressNudgeMessage, OI as ToolMap, OP as AgentDecisionsOptions, OR as ToolStateController, PF as PromptVideoPart, PP as DecisionEndHookContext, QP as AgentBehavior, Qj as ToolCall, RF as ResolveContentRefBlock, Rt as MutationValidationFailure, TI as ToolDescriptionOverride, UF as SessionHookContext, UP as DecisionQuestions, Uj as ProviderCapabilities, VF as SessionContentBlock, Vt as MutationValidationResult, WF as SessionMessage, WI as SkillsConfig, Wo as AgentOptions, XF as StreamHookContext, XP as DecisionSuccess, XR as Session, Xj as StreamOptions, YP as DecisionStartHookContext, Yi as InteractionToolOptions, Yj as StreamCallbacks, ZP as DecisionUsage, ZR as SessionData, _I as toolOutputBudgetByteLength, _j as AgentHookMap, _z as RemoteStoreOptions, aF as ChildRunStats, bF as McpServerConfig, cI as ToolResultDocumentContent, dI as ToolResultImageRefContent, eF as AgentRunOptions, eM as ToolSpec, fF as DEFAULT_AGENT_CLOCK, fI as ToolResultMetadata, gI as TurnUsage, gj as AgentHookHandlers, hI as TurnFinishReason, hj as AgentHookBus, iI as ToolOutcome, iz as SessionStore, jF as PromptImagePart, jI as ReadStateEntry, jP as DecisionAnswers, jR as ToolStateView, kF as PromptAudioPart, kP as DecisionAnswer, kR as ToolStateOp, lI as ToolResultDocumentRefContent, mI as ToolResultVideoContent, oI as ToolResultAudioContent, ox as SpawnToolOptions, pI as ToolResultTextContent, pM as OpenRouterParams, rI as ToolHookContext, sI as ToolResultContent, sx as SpawnToolState, tF as AgentStats, tM as TurnResult, tx as ChildAgent, tz as SessionRun, uI as ToolResultImageContent, vI as toolOutputByteLength, vj as AgentHooks, wI as ToolDef, x as flattenTurns, xF as McpToolHookContext, y as ModelUsage, yI as toolResultToText, yj as DecideHookContext, zF as RetryConfig, zP as DecisionOutcome, zo as Agent, zt as MutationValidationHooksOptions } from "./index-DqCio7Nd.js";
|
|
2
2
|
import { C as matchesContextExceeded, a as AgentContextExceededError, c as AgentToolNotAllowedError, f as CONTEXT_EXCEEDED_MESSAGE_PATTERNS, i as AgentBudgetExceededError, m as ClassifiedErrorKind, n as AgentAbortedError, p as ClassifiedError, s as AgentProviderError } from "./timeout-B5pO5I5a.js";
|
|
3
3
|
import { S as TaskStallInfo, _ as SpawnConfig, b as TaskExitInfo, d as ExecResult, f as ExecutionContext, i as ContextHardening, o as ContextType, p as ExecutionHandle, r as ContextCapabilities, s as DetachedTasksCapability, t as BackgroundTaskStatus, x as TaskHandle, y as TaskEntry } from "./types-2HrgolQz.js";
|
|
4
4
|
import { t as SandboxProvider } from "./sandbox-B4OW6oNx.js";
|
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
* retires it, so an upgrade can never leave windows silently executing on a
|
|
12
12
|
* process started from the previous release.
|
|
13
13
|
*/
|
|
14
|
-
const ZIDANE_VERSION = "9.1.
|
|
14
|
+
const ZIDANE_VERSION = "9.1.6";
|
|
15
15
|
/**
|
|
16
16
|
* Compare two dotted versions (`7.0.19`, `7.1.0-beta.1`): negative when `a`
|
|
17
17
|
* is older, positive when newer, 0 when equal. Pre-release tags are ignored
|
|
@@ -39,4 +39,4 @@ function parse(v) {
|
|
|
39
39
|
//#endregion
|
|
40
40
|
export { compareVersions as n, ZIDANE_VERSION as t };
|
|
41
41
|
|
|
42
|
-
//# sourceMappingURL=version-
|
|
42
|
+
//# sourceMappingURL=version-3w8QMAyl.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"version-
|
|
1
|
+
{"version":3,"file":"version-3w8QMAyl.js","names":["(pkg as { version?: string }).version"],"sources":["../package.json","../src/version.ts"],"sourcesContent":["","/**\n * The version of the zidane code this process is running — `package.json`\n * inlined at build time (Bun `--compile`, tsdown for `dist/`, and Vite for\n * the GUI main all fold JSON imports into the bundle, so this never reads\n * the filesystem at runtime and cannot report a NEIGHBOUR package's version\n * the way a `require('../package.json')` from a bundled chunk can).\n *\n * Used by the daemon handshake: a client running newer code than the daemon\n * retires it, so an upgrade can never leave windows silently executing on a\n * process started from the previous release.\n */\nimport pkg from '../package.json' with { type: 'json' }\n\nexport const ZIDANE_VERSION: string = (pkg as { version?: string }).version ?? '0.0.0'\n\n/**\n * Compare two dotted versions (`7.0.19`, `7.1.0-beta.1`): negative when `a`\n * is older, positive when newer, 0 when equal. Pre-release tags are ignored\n * — same release train, same code as far as the daemon fence is concerned.\n * Unparseable input compares equal (never fences on garbage).\n */\nexport function compareVersions(a: string, b: string): number {\n const pa = parse(a)\n const pb = parse(b)\n if (!pa || !pb)\n return 0\n for (let i = 0; i < 3; i++) {\n const d = (pa[i] ?? 0) - (pb[i] ?? 0)\n if (d !== 0)\n return d\n }\n return 0\n}\n\nfunction parse(v: string): number[] | null {\n const m = /^v?(\\d+)\\.(\\d+)\\.(\\d+)/.exec(v.trim())\n return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null\n}\n"],"mappings":";;;;;;;;;;;;;ACaA,MAAa,iBAAyBA;;;;;;;AAQtC,SAAgB,gBAAgB,GAAW,GAAmB;CAC5D,MAAM,KAAK,MAAM,CAAC;CAClB,MAAM,KAAK,MAAM,CAAC;CAClB,IAAI,CAAC,MAAM,CAAC,IACV,OAAO;CACT,KAAK,IAAI,IAAI,GAAG,IAAI,GAAG,KAAK;EAC1B,MAAM,KAAK,GAAG,MAAM,MAAM,GAAG,MAAM;EACnC,IAAI,MAAM,GACR,OAAO;CACX;CACA,OAAO;AACT;AAEA,SAAS,MAAM,GAA4B;CACzC,MAAM,IAAI,yBAAyB,KAAK,EAAE,KAAK,CAAC;CAChD,OAAO,IAAI;EAAC,OAAO,EAAE,EAAE;EAAG,OAAO,EAAE,EAAE;EAAG,OAAO,EAAE,EAAE;CAAC,IAAI;AAC1D"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Jt as normalizeSettingValue, Qt as DisposedError, Wt as checkSettingValue, Xt as settingScopes, Yt as settingDefault, Zt as settingsForDefinition, _t as toWireActionStatus, qt as isValueSetting, vt as toWireSettings, yt as toWireValue } from "./registry-
|
|
1
|
+
import { Jt as normalizeSettingValue, Qt as DisposedError, Wt as checkSettingValue, Xt as settingScopes, Yt as settingDefault, Zt as settingsForDefinition, _t as toWireActionStatus, qt as isValueSetting, vt as toWireSettings, yt as toWireValue } from "./registry-DWYR40B2.js";
|
|
2
2
|
import { Buffer } from "node:buffer";
|
|
3
3
|
//#region src/extensions/settings/domain.ts
|
|
4
4
|
/** A refused write. */
|
|
@@ -303,4 +303,4 @@ function jsonBytes(value) {
|
|
|
303
303
|
//#endregion
|
|
304
304
|
export { createSettingsDomain as a, SettingsWriteError as i, RpcErrorType as n, jsonBytes as r, RPC_MAX_PAYLOAD_BYTES as t };
|
|
305
305
|
|
|
306
|
-
//# sourceMappingURL=wire-
|
|
306
|
+
//# sourceMappingURL=wire-Ct6nuXL5.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"wire-DYBrjw6p.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,M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,OAAO,WAAW,MAAM,MAAM,IAAI;AACtE"}
|
|
1
|
+
{"version":3,"file":"wire-Ct6nuXL5.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;GACF,MAAM,OAAO,IAAI,MAAM,GAAG;GAC1B,IAAI,UAAU,MAAM,MAAM,IAAI,GAC5B;GACF,MAAM,OAAO;GACb,MAAM,SAAS,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K,QAAQ;IACtB;GACF;GACA,SAAS,KAAK,QAAQ;GACtB,IAAI,CAAC,SAAS,OAAO,GACnB,OAAO,YAAY,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,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-
|
|
4
|
+
import { a as createSignalListeners, o as openIpcClient } from "./settings-keys-Dmig23l3.js";
|
|
5
5
|
import { f as hostRefOf } from "./protocol-MxDL3YeM.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-
|
|
316
|
+
//# sourceMappingURL=ws-client-DAm6UPtq.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ws-client-iv10YsKH.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,GAA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M,IAAI;CAC/C,UACQ;EACN,QAAQ,oBAAoB,SAAS,OAAO;CAC9C;AACF"}
|
|
1
|
+
{"version":3,"file":"ws-client-DAm6UPtq.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,MAAM,KAAK,aAAa;CACxB,IAAI,CAAC,MAAM,CAAC,IAAI,4BAA4B,OAAQ,WAAiC,QAAQ,aAC3F,OAAO;CACT,IAAI,yBAAyB,EAAE;CAC/B,OAAO;AACT;;;;AC1CA,MAAa,iBAAiB;;AAE9B,MAAa,mBAAmB;;;;;;;AA4BhC,MAAa,oBAAoB;AACjC,MAAM,qBAAqB;CAAC;CAAU;CAAsB;CAA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,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"}
|
|
@@ -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-
|
|
3
|
+
import { i as IpcVersionMismatchError } from "./settings-keys-Dmig23l3.js";
|
|
4
4
|
import { f as hostRefOf } from "./protocol-MxDL3YeM.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-
|
|
8
|
-
import { a as hostCaBundle, r as connectWsClient, t as HostAuthError } from "./ws-client-
|
|
7
|
+
import { i as probeUnsavedHost, t as createHostRegistry } from "./registry-yhXC9O2x.js";
|
|
8
|
+
import { a as hostCaBundle, r as connectWsClient, t as HostAuthError } from "./ws-client-DAm6UPtq.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-
|
|
291
|
+
//# sourceMappingURL=ws-olbe6ZfF.js.map
|