@deepseek-ai/dsh-cordis-host-runner 0.2.2-alpha.3 → 0.2.2-rc.2

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/src/sandbox.ts ADDED
@@ -0,0 +1,237 @@
1
+ /**
2
+ * The `node:vm` sandbox a dynamic package's HOST half evaluates in: a fresh realm whose globals
3
+ * are a tagged write-through console, the `harness` registration helpers, the encoding primitives
4
+ * a bare vm context lacks, and callable traps over the Node APIs the sandbox deliberately
5
+ * withholds. Traps steer filesystem, network, process, and timer work to `ctx.fs`, `ctx.web`,
6
+ * `ctx.bash`, and Cordis timers. This keeps cooperative packages inspectable and disposable but
7
+ * is not containment: host-realm helper functions remain an escape route.
8
+ *
9
+ * The browser half never reaches this module — it is evaluated by the client-side runner in a
10
+ * closure, with its own facade.
11
+ * @module @deepseek-ai/dsh-cordis-host-runner/sandbox
12
+ */
13
+
14
+ import { createContext, runInContext, Script } from 'node:vm'
15
+ import { sandboxDefineTool, sandboxRegisterTool } from './guard.ts'
16
+
17
+ /**
18
+ * A write-through console for one package, tagging every line with the package
19
+ * id. Write-through (host stdout/stderr), NOT buffered into the tool result:
20
+ * a registered listener fires long after the run call returned, and its output
21
+ * must land somewhere the user can see — for a terminal entry point, the host terminal.
22
+ */
23
+ function taggedConsole(id: string): Record<'log' | 'info' | 'warn' | 'error' | 'debug', (...args: unknown[]) => void> {
24
+ const tag = `[cordis:${id}]`
25
+ const log = (...args: unknown[]): void => { console.log(tag, ...args) }
26
+ const error = (...args: unknown[]): void => { console.error(tag, ...args) }
27
+ return { log, info: log, warn: log, debug: log, error }
28
+ }
29
+
30
+ /**
31
+ * Patch only VM constructors so `instanceof` accepts both VM values and host values passed as
32
+ * arguments, events, or service results; host intrinsics remain untouched.
33
+ */
34
+ const DUAL_REALM_INSTANCEOF_PRELUDE = `
35
+ (hostIntrinsics) => {
36
+ 'use strict'
37
+ const ordinary = Function.prototype[Symbol.hasInstance]
38
+ for (const name of Object.keys(hostIntrinsics)) {
39
+ const VmCtor = globalThis[name]
40
+ const HostCtor = hostIntrinsics[name]
41
+ if (typeof VmCtor !== 'function' || typeof HostCtor !== 'function') continue
42
+ Object.defineProperty(VmCtor, Symbol.hasInstance, {
43
+ value: (instance) => ordinary.call(VmCtor, instance) || ordinary.call(HostCtor, instance),
44
+ configurable: true,
45
+ })
46
+ }
47
+ }
48
+ `
49
+
50
+ /** Run {@link DUAL_REALM_INSTANCEOF_PRELUDE} in a freshly created sandbox, handing it the host intrinsics to pair up. */
51
+ function patchDualRealmInstanceof(sandbox: object): void {
52
+ const patch = runInContext(DUAL_REALM_INSTANCEOF_PRELUDE, sandbox) as (intrinsics: Record<string, unknown>) => void
53
+ patch({ Object, Array, Function, Error, TypeError, RangeError, SyntaxError, Promise, RegExp, Date, Map, Set })
54
+ }
55
+
56
+ const TIMER_REDIRECT
57
+ = 'Node timers are unavailable. Use the cordis timer service instead: declare inject: [\'timer\'] on your plugin '
58
+ + 'and call ctx.timeout / ctx.interval after querying Host Service.listService for the exact overloads. '
59
+ + 'Those calls are fiber effects, cleaned up automatically when stopped.'
60
+
61
+ /**
62
+ * The callable Node APIs the sandbox deliberately disables, each mapped to the
63
+ * cordis alternative its trap error names. Only function-valued globals are
64
+ * trapped; a data-valued global such as `process` stays `undefined`, because a
65
+ * throwing accessor would detonate the common `typeof process` feature probe
66
+ * at resolution time.
67
+ */
68
+ const NODE_API_REDIRECTS: Record<string, string> = {
69
+ require:
70
+ 'Node modules are unavailable. Use the cordis services on ctx instead — e.g. inject: [\'fs\'] for files, '
71
+ + '[\'web\'] for HTTP, [\'bash\'] for processes; query Service.listService with cordis_inspect_query first.',
72
+ setTimeout: TIMER_REDIRECT,
73
+ setInterval: TIMER_REDIRECT,
74
+ setImmediate: TIMER_REDIRECT,
75
+ clearTimeout: TIMER_REDIRECT,
76
+ clearInterval: TIMER_REDIRECT,
77
+ fetch:
78
+ 'Network access goes through the cordis web service: declare inject: [\'web\'] and call ctx.web '
79
+ + '(query Host Service.listService with cordis_inspect_query for its methods).',
80
+ }
81
+
82
+ /** Build the trap functions for {@link NODE_API_REDIRECTS}: calling one throws the redirect. */
83
+ function nodeApiTraps(): Record<string, () => never> {
84
+ const traps: Record<string, () => never> = {}
85
+ for (const [name, redirect] of Object.entries(NODE_API_REDIRECTS)) {
86
+ traps[name] = () => {
87
+ throw new Error(`${name} is not available in the dynamic package sandbox — ${redirect}`)
88
+ }
89
+ }
90
+ return traps
91
+ }
92
+
93
+ /**
94
+ * Build the vm context one host half evaluates in: the tagged console, the
95
+ * `harness` registration helpers, the encoding primitives, the Node-API traps,
96
+ * and the dual-realm `instanceof` patch, already `createContext`-ed.
97
+ * @param id - the package id (`dyn-<n>`), used as the console tag and filename stem.
98
+ * @param harnessExtras - per-package `harness` verbs beyond the registration pair (`handle`).
99
+ * @returns the contextified sandbox object to pass to {@link evaluateHostCode}.
100
+ */
101
+ export function createSandbox(id: string, harnessExtras: Record<string, unknown> = {}): object {
102
+ const sandbox = {
103
+ ...nodeApiTraps(),
104
+ console: taggedConsole(id),
105
+ harness: { defineTool: sandboxDefineTool, registerTool: sandboxRegisterTool, ...harnessExtras },
106
+ // Web APIs absent from fresh vm contexts — made available so the model
107
+ // can encode/decode base64 without Buffer (which is also absent). Host
108
+ // closures over Buffer, never Buffer itself.
109
+ btoa: (s: string) => Buffer.from(s, 'utf-8').toString('base64'),
110
+ atob: (s: string) => Buffer.from(s, 'base64').toString('utf-8'),
111
+ TextEncoder,
112
+ TextDecoder,
113
+ }
114
+ createContext(sandbox)
115
+ patchDualRealmInstanceof(sandbox)
116
+ return sandbox
117
+ }
118
+
119
+ /**
120
+ * Cross-realm SyntaxError detection: a compile failure inside `runInContext`
121
+ * constructs its error in the SANDBOX realm, so a host `instanceof
122
+ * SyntaxError` is silently false — the `name` property is the realm-safe tag.
123
+ */
124
+ function isSyntaxError(error: unknown): error is Error {
125
+ return typeof error === 'object' && error !== null && (error as { name?: unknown }).name === 'SyntaxError'
126
+ }
127
+
128
+ /**
129
+ * The parse-failure context a vm `SyntaxError` carries: the vm prints the
130
+ * offending source line and a caret before the message, which is exactly what
131
+ * a model needs to self-correct — surface it instead of the bare message.
132
+ * Falls back to `String(error)` when the stack carries no such prelude.
133
+ * @param error - the `SyntaxError` (host- or sandbox-realm) thrown while compiling package code.
134
+ * @returns the stack prefix up to and including the `SyntaxError: …` line.
135
+ */
136
+ export function syntaxErrorContext(error: Error): string {
137
+ const lines = (error.stack ?? '').split('\n')
138
+ const messageIndex = lines.findIndex(line => line.startsWith('SyntaxError'))
139
+ if (messageIndex === -1) return String(error)
140
+ return lines.slice(0, messageIndex + 1).join('\n')
141
+ }
142
+
143
+ /**
144
+ * The teaching text one parse failure produces, shared by the define-time
145
+ * precheck and the run-time evaluation so a model reads the same diagnosis
146
+ * whichever verb caught it.
147
+ * @param half - which half failed to parse, named as the define argument that carried it.
148
+ * @param context - the {@link syntaxErrorContext} of the failure.
149
+ * @returns the model-facing error message.
150
+ */
151
+ export function parseErrorMessage(half: 'code.host' | 'code.client', context: string): string {
152
+ // Scope the TypeScript heuristic to the OFFENDING line, not the whole code:
153
+ // an ` as ` inside an ordinary description string must not turn a plain
154
+ // syntax error into a misleading remove-annotations message.
155
+ const offendingLine = context.split('\n')[1] ?? ''
156
+ if (/\bas\b/.test(offendingLine)) {
157
+ return `dynamic package \`${half}\` failed to parse:\n${context}\n`
158
+ + 'The sandbox runs plain JavaScript, not TypeScript. Remove type annotations:\n'
159
+ + ' ✗ { type: \'text\' as const, text: x }\n'
160
+ + ' ✓ { type: \'text\', text: x }'
161
+ }
162
+ return `dynamic package \`${half}\` failed to parse:\n${context}\n`
163
+ + 'Note: it runs as the BODY of an async function (line numbers are offset by the 1-line wrapper). '
164
+ + 'Check bracket balance — ending the returned plugin object with `});` closes a call that was never opened; '
165
+ + 'a plain `return { … }` ends with `}` (an optional `;`), never `)`.'
166
+ }
167
+
168
+ /**
169
+ * Parse one half's source without running it: the define-time precheck that
170
+ * keeps unparseable code out of the registry, so a model fixes it and defines
171
+ * again instead of discovering the failure at run time. `new Function` is the
172
+ * gate — hosts without a real `node:vm` (the browser worker) still refuse
173
+ * unparseable code — and `vm.Script` is only the best-effort prettifier: on a
174
+ * Node host its failure carries the source-line-and-caret prelude the
175
+ * teaching text builds on, and where the vm is a stub the message stays bare.
176
+ * The two parsers' syntax faces differ at the margin (`new.target` parses in
177
+ * a function body but not at the vm wrapper's top level), an accepted cost of
178
+ * a vm-free gate; and under a page CSP without `'unsafe-eval'`, `new Function`
179
+ * throws `EvalError`, which propagates unwrapped.
180
+ * @param code - the model-written function body.
181
+ * @param half - which define argument carried it, for the error text.
182
+ * @throws when the body does not parse, with the offending line and a teaching hint.
183
+ */
184
+ export function precheckCode(code: string, half: 'code.host' | 'code.client'): void {
185
+ const wrapped = `(async () => {\n${code}\n})()`
186
+ try {
187
+ // Compile-only: constructing the function parses the source and runs nothing.
188
+ // oxlint-disable-next-line typescript/no-implied-eval -- parse gate over model-written code; nothing is invoked
189
+ new Function(wrapped)
190
+ } catch (error) {
191
+ if (!isSyntaxError(error)) throw error
192
+ throw new Error(parseErrorMessage(half, prettyParseContext(wrapped, half, error)))
193
+ }
194
+ }
195
+
196
+ /**
197
+ * Best-effort vm recompile of a body `new Function` already refused, for the
198
+ * source-line-and-caret prelude only.
199
+ * @param wrapped - the wrapped source that failed to parse.
200
+ * @param half - which define argument carried it, for the vm filename.
201
+ * @param refusal - the gate's own `SyntaxError`, the fallback context source.
202
+ * @returns the vm prelude when a real vm produced one, else the bare refusal.
203
+ */
204
+ function prettyParseContext(wrapped: string, half: 'code.host' | 'code.client', refusal: Error): string {
205
+ try {
206
+ new Script(wrapped, { filename: `cordis-dyn-${half}.js` })
207
+ } catch (vmError) {
208
+ if (isSyntaxError(vmError)) return syntaxErrorContext(vmError)
209
+ // A stubbed vm (the browser worker) refuses Script itself; the gate's
210
+ // error is the only context there is.
211
+ }
212
+ return String(refusal)
213
+ }
214
+
215
+ /**
216
+ * Evaluate a host half as the body of an async function inside the sandbox. `vmTimeoutMs` only
217
+ * bounds the SYNCHRONOUS portion; an async body escapes it — acceptable under the module's
218
+ * trust stance. Parse errors include the offending line and a TypeScript-removal or bracket-
219
+ * balance hint.
220
+ * @param sandbox - the contextified object from {@link createSandbox}.
221
+ * @param code - the model-written function body; must `return` a plugin.
222
+ * @param id - the package id, used as the vm filename (`cordis-dyn-<id>.js`).
223
+ * @param vmTimeoutMs - the synchronous evaluation bound in milliseconds.
224
+ * @returns whatever the code returned, still un-narrowed (the run lifecycle checks plugin shape).
225
+ */
226
+ export async function evaluateHostCode(sandbox: object, code: string, id: string, vmTimeoutMs: number): Promise<unknown> {
227
+ try {
228
+ return await runInContext(
229
+ `(async () => {\n${code}\n})()`,
230
+ sandbox,
231
+ { filename: `cordis-dyn-${id}.js`, timeout: vmTimeoutMs },
232
+ )
233
+ } catch (error) {
234
+ if (!isSyntaxError(error)) throw error
235
+ throw new Error(parseErrorMessage('code.host', syntaxErrorContext(error)))
236
+ }
237
+ }
package/src/types.ts ADDED
@@ -0,0 +1,403 @@
1
+ /**
2
+ * Client-safe wire vocabulary of the dynamic Cordis plugin runner.
3
+ * @module @deepseek-ai/dsh-cordis-host-runner/types
4
+ */
5
+
6
+ import type { Branded } from '@deepseek-ai/dsh-brand'
7
+ import type { SessionId } from '@deepseek-ai/dsh-session/types'
8
+ import type { JsonValue } from '@deepseek-ai/dsh-util-values'
9
+
10
+ /** Stable identity of one dynamic plugin instance. */
11
+ export type CordisDynamicPluginId = Branded<'CordisDynamicPluginId'>
12
+
13
+ /** Identity of one immutable package version belonging to a dynamic plugin. */
14
+ export type CordisDynamicPackageId = Branded<'CordisDynamicPackageId'>
15
+
16
+ /** Identity of one successful activation attempt. */
17
+ export type CordisDynamicPluginRunId = Branded<'CordisDynamicPluginRunId'>
18
+
19
+ /** Identity of one human approval request. */
20
+ export type ApprovalRequestId = Branded<'ApprovalRequestId'>
21
+
22
+ /** Identity of one cross-page inspect query. */
23
+ export type CordisInspectRequestId = Branded<'CordisInspectRequestId'>
24
+
25
+ /** Runtime plane that owns an inspect provider. */
26
+ export type CordisInspectPlatform = 'host' | 'client'
27
+
28
+ /** One model-callable read-only query exposed by an inspect provider. */
29
+ export interface CordisInspectMethodManifest {
30
+ /** Method name, unique within its provider. */
31
+ name: string
32
+ /** What the query returns and when to use it. */
33
+ description: string
34
+ /** JSON Schema accepted by the query. */
35
+ inputSchema: JsonValue
36
+ /** JSON Schema produced by the query. */
37
+ outputSchema: JsonValue
38
+ }
39
+
40
+ /** Serializable directory entry for one inspect provider. */
41
+ export interface CordisInspectProviderManifest {
42
+ /** Provider identity, unique within one platform. */
43
+ id: string
44
+ /** Capability described by this provider. */
45
+ description: string
46
+ /** Explicit read-only queries. */
47
+ methods: readonly CordisInspectMethodManifest[]
48
+ }
49
+
50
+ /** Provider directory row returned by `cordis_inspect_list`. */
51
+ export interface CordisInspectProviderView extends CordisInspectProviderManifest {
52
+ /** Runtime plane that executes these methods. */
53
+ platform: CordisInspectPlatform
54
+ }
55
+
56
+ /** Host broadcast requesting one live Client inspect result. */
57
+ export interface CordisInspectQueryRequest {
58
+ /** Correlation identity. */
59
+ requestId: CordisInspectRequestId
60
+ /** Session whose model requested the query. */
61
+ agentId: SessionId
62
+ /** Provider selected from the Client manifest. */
63
+ provider: string
64
+ /** Method selected from the provider manifest. */
65
+ method: string
66
+ /** JSON query input, omitted when the method has no fields. */
67
+ input?: JsonValue
68
+ }
69
+
70
+ /** Result sent from a Client provider to the waiting Host query. */
71
+ export type CordisInspectQueryResolution =
72
+ | { ok: true; data: JsonValue }
73
+ | {
74
+ ok: false
75
+ reason: 'provider-missing' | 'method-missing' | 'invalid-input' | 'provider-error' | 'cancelled'
76
+ message: string
77
+ }
78
+
79
+ /** Notification that a Client inspect request can no longer be answered. */
80
+ export interface CordisInspectQueryResolved {
81
+ /** Query that left the pending state. */
82
+ requestId: CordisInspectRequestId
83
+ }
84
+
85
+ /** Whether a Client answer claimed the still-pending query. */
86
+ export interface CordisInspectResolveAck {
87
+ /**
88
+ * True only for a valid success that settles the query;
89
+ * false for retained failures and unknown, timed out, cancelled, or late answers.
90
+ */
91
+ accepted: boolean
92
+ }
93
+
94
+ /** Whether a package starts the current version or replaces it. */
95
+ export type CordisDynamicRunMode = 'run' | 'update'
96
+
97
+ /** How a model-driven Client activation request left the pending state. */
98
+ export type RequestRunOutcome = 'approved' | 'completed' | 'rejected' | 'cancelled' | 'failed'
99
+
100
+ /** Error fields preserved across the Host/Client transport. */
101
+ export interface CordisErrorDetails {
102
+ /** Original error message. */
103
+ message: string
104
+ /** Original stack when the thrown value supplied one. */
105
+ stack?: string
106
+ }
107
+
108
+ /** Persisted state of the latest activation attempt. */
109
+ export type CordisRunStatus =
110
+ | 'awaiting-approval'
111
+ | 'starting-host'
112
+ | 'client-pending'
113
+ | 'running'
114
+ | 'waiting'
115
+ | 'rejected'
116
+ | 'failed'
117
+ | 'cancelled'
118
+ | 'stopped'
119
+
120
+ /** One platform half within an activation attempt. */
121
+ export interface CordisHalfState {
122
+ /** Lifecycle state of this half. */
123
+ status: 'absent' | 'pending' | 'stopped' | 'running' | 'waiting' | 'failed'
124
+ /** Services still needed by a successfully created Fiber. */
125
+ waitingFor: readonly string[]
126
+ /** Failure text for this half. */
127
+ error?: string
128
+ }
129
+
130
+ /** Structured failure associated with an exact activation attempt. */
131
+ export interface CordisRunDiagnostic {
132
+ /** Stage that failed. */
133
+ phase: 'approval' | 'host-load' | 'host-apply' | 'client-load' | 'client-apply' | 'client-render'
134
+ /** Original failure text. */
135
+ message: string
136
+ /** Original failure stack when available. */
137
+ stack?: string
138
+ /** Stable Plugin identity. */
139
+ pluginId: CordisDynamicPluginId
140
+ /** Immutable Package identity. */
141
+ packageId: CordisDynamicPackageId
142
+ /** Exact attempt identity. */
143
+ pluginRunId: CordisDynamicPluginRunId
144
+ }
145
+
146
+ /** Latest activation attempt retained independently from the physical run. */
147
+ export interface DynamicCordisRunAttempt {
148
+ /** Exact attempt identity. */
149
+ pluginRunId: CordisDynamicPluginRunId
150
+ /** Target Package. */
151
+ packageId: CordisDynamicPackageId
152
+ /** Explicit run/update intent. */
153
+ mode: CordisDynamicRunMode
154
+ /** Current attempt state. */
155
+ status: CordisRunStatus
156
+ /** Pending Client activation request; it represents approval only when `requiresApproval` is true. */
157
+ approvalRequestId?: ApprovalRequestId
158
+ /** Whether the pending Client activation requires a user decision. */
159
+ requiresApproval?: boolean
160
+ /** Host-half state. */
161
+ host: CordisHalfState
162
+ /** Client-half state. */
163
+ client: CordisHalfState
164
+ /** Most recent failure. */
165
+ error?: CordisRunDiagnostic
166
+ }
167
+
168
+ /** One running package announced to browser pages. */
169
+ export interface DynamicCordisPackage {
170
+ /** Stable plugin instance. */
171
+ pluginId: CordisDynamicPluginId
172
+ /** Immutable package version currently active. */
173
+ packageId: CordisDynamicPackageId
174
+ /** This activation's identity. */
175
+ pluginRunId: CordisDynamicPluginRunId
176
+ /** Package label. */
177
+ name: string
178
+ }
179
+
180
+ /** One pending model-driven Client activation forwarded to browser pages. */
181
+ export interface DynamicCordisRunRequest {
182
+ /** Correlation identity of the activation request. */
183
+ requestId: ApprovalRequestId
184
+ /** Session whose plugin and tool call own the request. */
185
+ agentId: SessionId
186
+ /** Stable plugin instance being acted on. */
187
+ pluginId: CordisDynamicPluginId
188
+ /** Package version the request will activate. */
189
+ packageId: CordisDynamicPackageId
190
+ /** Explicit lifecycle intent. */
191
+ mode: CordisDynamicRunMode
192
+ /** Package label. */
193
+ name: string
194
+ /** User-facing reason supplied at define time. */
195
+ purpose: string
196
+ /** Whether a page must wait for an explicit user decision before activation. */
197
+ requiresApproval: boolean
198
+ }
199
+
200
+ /** One settled model-driven Client activation request broadcast to all pages. */
201
+ export interface DynamicCordisRequestResolved {
202
+ /** Request that left the pending state. */
203
+ requestId: ApprovalRequestId
204
+ /** How the request settled. */
205
+ outcome: RequestRunOutcome
206
+ }
207
+
208
+ /** One activation withdrawn from every page. */
209
+ export interface DynamicCordisRetracted {
210
+ /** Stable plugin instance. */
211
+ pluginId: CordisDynamicPluginId
212
+ /** Package version that was active. */
213
+ packageId: CordisDynamicPackageId
214
+ /** Exact activation being withdrawn. */
215
+ pluginRunId: CordisDynamicPluginRunId
216
+ }
217
+
218
+ /** Package metadata exposed by the inventory without source code. */
219
+ export interface DynamicCordisInventoryPackage {
220
+ /** Immutable package version. */
221
+ packageId: CordisDynamicPackageId
222
+ /** Package label. */
223
+ name: string
224
+ /** User-facing purpose. */
225
+ purpose: string
226
+ /** Whether this version contains Host code. */
227
+ hasHostHalf: boolean
228
+ /** Whether this version contains Client code. */
229
+ hasClientHalf: boolean
230
+ }
231
+
232
+ /** One stable plugin row in the frame-wide inventory. */
233
+ export interface DynamicCordisInventoryRow {
234
+ /** Stable plugin instance. */
235
+ pluginId: CordisDynamicPluginId
236
+ /** Session that owns this plugin. */
237
+ agentId: SessionId
238
+ /** Immutable versions in define order. */
239
+ packages: readonly DynamicCordisInventoryPackage[]
240
+ /** Last package that completed activation successfully. */
241
+ currentPackageId?: CordisDynamicPackageId
242
+ /** Package selected for a failed or in-progress transition. */
243
+ nextPackageId?: CordisDynamicPackageId
244
+ /** Current activation, absent while stopped. */
245
+ activeRun?: {
246
+ pluginRunId: CordisDynamicPluginRunId
247
+ packageId: CordisDynamicPackageId
248
+ }
249
+ /** Latest activation attempt, including pending approval and diagnostics. */
250
+ latestRun?: DynamicCordisRunAttempt
251
+ }
252
+
253
+ /** Answer to removing a plugin and all of its package versions. */
254
+ export type DynamicCordisUndefineReceipt =
255
+ | { ok: true; wasRunning: boolean }
256
+ | { ok: false; reason: 'plugin-missing'; message: string }
257
+
258
+ /** One render failure observed after a Client half loaded. */
259
+ export interface DynamicCordisRenderFailure {
260
+ /** Slot whose component failed. */
261
+ slot: string
262
+ /** Render failure text. */
263
+ message: string
264
+ /** Original render failure stack when available. */
265
+ stack?: string
266
+ /** Whether the failing contribution relinquished its slot. */
267
+ abdicated: boolean
268
+ }
269
+
270
+ /** Result shared by model-driven and panel-driven activation. */
271
+ export type DynamicCordisRunResponse =
272
+ | {
273
+ ok: true
274
+ /** Whether activation completed synchronously, is starting in a Client, or awaits user approval. */
275
+ status: 'awaiting-approval' | 'starting' | 'running'
276
+ pluginId: CordisDynamicPluginId
277
+ packageId: CordisDynamicPackageId
278
+ pluginRunId: CordisDynamicPluginRunId
279
+ /** Missing Host services; a parked Fiber is a successful activation. */
280
+ waitingFor: readonly string[]
281
+ /** Missing Client services reported by the approving page. */
282
+ clientWaitingFor?: readonly string[]
283
+ /** Last fully successful Package. */
284
+ currentPackageId?: CordisDynamicPackageId
285
+ /** Selected transition target. */
286
+ nextPackageId?: CordisDynamicPackageId
287
+ /** Explicit lifecycle intent. */
288
+ mode: CordisDynamicRunMode
289
+ }
290
+ | {
291
+ ok: false
292
+ reason:
293
+ | 'plugin-missing'
294
+ | 'package-missing'
295
+ | 'invalid-mode'
296
+ | 'transition-in-flight'
297
+ | 'host-half-failed'
298
+ | 'client-half-failed'
299
+ | 'rejected'
300
+ | 'cancelled'
301
+ | 'not-running'
302
+ message: string
303
+ /** Original failure stack when available. */
304
+ stack?: string
305
+ }
306
+
307
+ /** Result of stopping a Plugin without deleting its Packages. */
308
+ export type DynamicCordisStopResponse =
309
+ | { ok: true }
310
+ | { ok: false; reason: 'plugin-missing' | 'not-running'; message: string }
311
+
312
+ /** Result of bringing up the Host half before loading the Client half. */
313
+ export type DynamicCordisHostHalfResult =
314
+ | {
315
+ ok: true
316
+ pluginId: CordisDynamicPluginId
317
+ packageId: CordisDynamicPackageId
318
+ pluginRunId: CordisDynamicPluginRunId
319
+ waitingFor: readonly string[]
320
+ /** False when a panel merely attaches this page to an already active run. */
321
+ startedHere: boolean
322
+ }
323
+ | ({ ok: false } & CordisErrorDetails)
324
+
325
+ /** Client-half source for one exact activation. */
326
+ export interface DynamicCordisClientSource {
327
+ /** Browser JavaScript body. */
328
+ code: string
329
+ /** Package label. */
330
+ name: string
331
+ /** Stable plugin instance. */
332
+ pluginId: CordisDynamicPluginId
333
+ /** Immutable source version. */
334
+ packageId: CordisDynamicPackageId
335
+ /** Exact activation the source belongs to. */
336
+ pluginRunId: CordisDynamicPluginRunId
337
+ }
338
+
339
+ /** Browser verdict used for both approved tool runs and panel runs. */
340
+ export type DynamicCordisRunResolution =
341
+ | { ok: true; pluginRunId: CordisDynamicPluginRunId; waitingFor?: readonly string[] }
342
+ | {
343
+ ok: false
344
+ reason: 'rejected' | 'host-half-failed' | 'client-half-failed'
345
+ /** Activation that failed; absent for a refusal before activation. */
346
+ pluginRunId?: CordisDynamicPluginRunId
347
+ /** Whether this page created the failed activation instead of attaching to it. */
348
+ startedHere?: boolean
349
+ message?: string
350
+ stack?: string
351
+ }
352
+
353
+ /** Whether a Client activation resolution reached the still-pending request. */
354
+ export interface DynamicCordisResolveAck {
355
+ /** False for late, unknown, or stale answers. */
356
+ accepted: boolean
357
+ }
358
+
359
+ /** Result of routing one Client call to the active Host half. */
360
+ export type DynamicCordisInvokeResult =
361
+ | { ok: true; value: JsonValue }
362
+ | ({ ok: false; code: 'plugin-not-running' | 'stale-run' | 'method-not-found' | 'handler-error' } & CordisErrorDetails)
363
+
364
+ declare module '@deepseek-ai/cordis' {
365
+ interface Events {
366
+ /**
367
+ * A Client-bearing activation needs a browser page, and may require a user decision.
368
+ * @param request - correlation identity, owner, target version, mode, and approval requirement.
369
+ * @mode emit
370
+ */
371
+ 'cordis/request-run'(request: DynamicCordisRunRequest): void
372
+ /**
373
+ * A pending Client activation request left the answerable state.
374
+ * @param resolved - request identity and outcome.
375
+ * @mode emit
376
+ */
377
+ 'cordis/request-run-resolved'(resolved: DynamicCordisRequestResolved): void
378
+ /**
379
+ * One exact Plugin/Package activation is now live in the Host.
380
+ * @param pkg - stable plugin, immutable package, run identity, and label.
381
+ * @mode emit
382
+ */
383
+ 'cordis/dynamic-package'(pkg: DynamicCordisPackage): void
384
+ /**
385
+ * One exact activation was withdrawn.
386
+ * @param retracted - plugin, package, and run identity.
387
+ * @mode emit
388
+ */
389
+ 'cordis/dynamic-retract'(retracted: DynamicCordisRetracted): void
390
+ /**
391
+ * Request a live read-only query from the Client inspect registry.
392
+ * @param request - correlation, Session, provider, method, and JSON input.
393
+ * @mode emit
394
+ */
395
+ 'cordis/inspect-query'(request: CordisInspectQueryRequest): void
396
+ /**
397
+ * Notify every Client that an inspect query has settled or been cancelled.
398
+ * @param resolved - exact query identity that is no longer answerable.
399
+ * @mode emit
400
+ */
401
+ 'cordis/inspect-query-resolved'(resolved: CordisInspectQueryResolved): void
402
+ }
403
+ }