| 1 | import { ReviewedLoader, installCompositionLoader } from './dsh/composition.ts' |
| 2 | import { REVIEWED_AGENT_PRESETS_BRAND } from './dsh/agent-presets.ts' |
| 3 | import { BUILTIN_DSH_ADAPTERS, DSH_ADAPTERS, type AdapterHost, type DshAdapter } from './dsh/adapters.ts' |
| 4 | import { createBundledSubagentsView } from './dsh/agents.ts' |
| 5 | import { createBundledSystemPromptView } from './dsh/session-prompt.ts' |
| 6 | /** |
| 7 | * The Cordis root that plugin fibers run under. |
| 8 | * |
| 9 | * The host has no turn loop, store, prompt authority or approval. Plugins |
| 10 | * reach the core only through the shim services here, and every one of them |
| 11 | * becomes a `registry/*` request that Rust admits or refuses. Service names |
| 12 | * that belong to the core cannot be provided by a plugin at all. |
| 13 | */ |
| 14 | import { createHash } from 'node:crypto' |
| 15 | import { readFile } from 'node:fs/promises' |
| 16 | import { AsyncLocalStorage } from 'node:async_hooks' |
| 17 | import { pathToFileURL } from 'node:url' |
| 18 | import { Context, Inject, Service } from '@deepseek-ai/cordis' |
| 19 | import { |
| 20 | ErrorCode, |
| 21 | type ActivateParams, |
| 22 | type ActivateResult, |
| 23 | type CommandResultWire, |
| 24 | type ContentBlockWire, |
| 25 | type DeactivateResult, |
| 26 | type HookEvaluateParams, |
| 27 | type HookVerdictWire, |
| 28 | type Json, |
| 29 | type OwnerRef, |
| 30 | type EntryRef, |
| 31 | type HarnessRunParams, |
| 32 | type McpOpenParams, |
| 33 | type McpRequestParams, |
| 34 | type McpCloseParams, |
| 35 | type ToolResultWire, |
| 36 | } from './protocol.ts' |
| 37 | import { RpcError, type RpcPeer } from './rpc.ts' |
| 38 | import { UserQuestionError } from './dsh/dsh-message-compat.js' |
| 39 | import { explainImportError } from './dsh/resolve-hooks.ts' |
| 40 | import { PROVIDED_SERVICES, REFUSED_SERVICES, describeMissingServices } from './dsh/missing-services.ts' |
| 41 | import compatibility from './dsh/compatibility.json' with { type: 'json' } |
| 42 | import { assertSupportedJsonSchema, validateJsonSchemaValue, ToolOutputError } from './dsh/dsh-tools-compat.js' |
| 43 | import { isJson } from './json.ts' |
| 44 | import { makeCoreApi } from './shims/core.ts' |
| 45 | import { gitInvocations, installGitAdapter } from './shims/git.ts' |
| 46 | import { OwnedRegistrations } from './shims/owned.ts' |
| 47 | import { defineShellHooksService,type LocalShellHook } from './shims/shell-hooks.ts' |
| 48 | import { hookExecution, hookVerdict, type LocalHook } from './shims/hooks.ts' |
| 49 | import { PromptSections, definePromptService, normalizePromptSection, type LocalPromptSection } from './shims/prompt.ts' |
| 50 | import { createStorage, type PluginStorage } from './shims/storage.ts' |
| 51 | import {McpDefinitions,defineMcpService,type LocalMcp} from './shims/mcp.ts' |
| 52 | import { AvatarPacks, defineAvatarsService, type LocalAvatarPack } from './shims/avatars.ts' |
| 53 | import { SkillRoots, defineSkillsService, type LocalSkillRoot } from './shims/skills.ts' |
| 54 | import { ownerTier, type HostTier } from './tier.ts' |
| 55 | import { |
| 56 | commandSpec, |
| 57 | defineCommandsService, |
| 58 | makeInvocation, |
| 59 | type LocalCommand, |
| 60 | type NormalizedCommand, |
| 61 | } from './shims/commands.ts' |
| 62 | |
| 63 | /** Context key carrying the owner record; inherited by every nested fiber. */ |
| 64 | export const OWNER = Symbol.for('codewhale.extension-host.owner') |
| 65 | |
| 66 | const CORDIS_SERVICES = new Set(compatibility.provided_services.cordis) |
| 67 | const CREATOR_SERVICES = new Set(['pluginManager', 'sandboxPolicy', 'approval']) |
| 68 | |
| 69 | const ACTIVATE_DEADLINE_MS = 5_000 |
| 70 | const DISPOSE_DEADLINE_MS = 2_000 |
| 71 | |
| 72 | interface HarnessBuiltin { run(params: HarnessRunParams, signal: AbortSignal): Promise<unknown>; dispose(): Promise<void> } |
| 73 | |
| 74 | interface McpBuiltin { |
| 75 | open(params: McpOpenParams, signal: AbortSignal): Promise<unknown> |
| 76 | request(params: McpRequestParams, signal: AbortSignal): Promise<unknown> |
| 77 | close(owner: OwnerRef, sessionId: string): Promise<void> |
| 78 | dispose(): Promise<void> |
| 79 | } |
| 80 | |
| 81 | export interface OwnerRecord { |
| 82 | mcp?: McpBuiltin; |
| 83 | harness?: HarnessBuiltin; |
| 84 | ref: OwnerRef |
| 85 | scope?: EntryRef |
| 86 | views?: Map<string, OwnerRecord> |
| 87 | pluginName: string |
| 88 | fibers: any[] |
| 89 | /** In-flight `registry/register` requests, awaited before activation acks. */ |
| 90 | pendingRegistrations: Set<Promise<void>> |
| 91 | refusals: string[] |
| 92 | tools: Map<number, LocalTool> |
| 93 | commands: Map<number, LocalCommand<OwnerRecord>> |
| 94 | shellHooks:Map<number,LocalShellHook<OwnerRecord>> |
| 95 | hooks: Map<number, LocalHook<OwnerRecord>> |
| 96 | promptSections: Map<number, LocalPromptSection<OwnerRecord>> |
| 97 | skillRoots: Map<number, LocalSkillRoot<OwnerRecord>> |
| 98 | avatarPacks: Map<number, LocalAvatarPack<OwnerRecord>> |
| 99 | mcpDefinitions:Map<number,LocalMcp<OwnerRecord>> |
| 100 | storage?: PluginStorage |
| 101 | warnedAllow?: boolean |
| 102 | /** Entry modules activated under this owner so far (a plugin may declare several). */ |
| 103 | entries: Set<string> |
| 104 | /** The plugin's own writable directory, as the core named it at activation. */ |
| 105 | dataDir?: string |
| 106 | bundledFirstParty?: boolean |
| 107 | subagentsView?: Record<PropertyKey, unknown> |
| 108 | systemPromptView?: Record<PropertyKey, unknown> |
| 109 | disposing?: Promise<void> |
| 110 | state: 'activating' | 'active' | 'failed' | 'disposed' |
| 111 | } |
| 112 | |
| 113 | interface LocalTool { |
| 114 | owner: OwnerRecord |
| 115 | name: string |
| 116 | handle?: number |
| 117 | definition: any |
| 118 | disposed: boolean |
| 119 | } |
| 120 | |
| 121 | export const ownerStorage = new AsyncLocalStorage<OwnerRecord>() |
| 122 | |
| 123 | function describeError(error: unknown): string { |
| 124 | if (error instanceof Error) return `${error.name}: ${error.message}` |
| 125 | return String(error) |
| 126 | } |
| 127 | |
| 128 | function withDeadline<T>(promise: Promise<T>, ms: number, label: string): Promise<T> { |
| 129 | let timer: NodeJS.Timeout |
| 130 | const deadline = new Promise<never>((_, reject) => { |
| 131 | timer = setTimeout(() => reject(new Error(`${label} exceeded ${ms} ms`)), ms) |
| 132 | timer.unref() |
| 133 | }) |
| 134 | return Promise.race([promise, deadline]).finally(() => clearTimeout(timer)) |
| 135 | } |
| 136 | |
| 137 | export interface ToolInvocation { |
| 138 | owner: OwnerRecord |
| 139 | callId: string |
| 140 | session: object | undefined |
| 141 | agent: object | undefined |
| 142 | questionTicket: string | undefined |
| 143 | subagentTicket: string | undefined |
| 144 | brokerTickets: ReadonlyMap<string, string> |
| 145 | callerTools: readonly string[] |
| 146 | delegated: boolean |
| 147 | ticket: string | undefined |
| 148 | signal: AbortSignal |
| 149 | active: boolean |
| 150 | pending: Promise<void> |
| 151 | } |
| 152 | |
| 153 | export class HostRoot { |
| 154 | readonly root: any |
| 155 | private readonly toolInvocations = new AsyncLocalStorage<ToolInvocation>() |
| 156 | readonly owners = new Map<string, OwnerRecord>() |
| 157 | private readonly toolRegistrations: OwnedRegistrations<OwnerRecord, LocalTool> |
| 158 | private readonly commandRegistrations: OwnedRegistrations<OwnerRecord, LocalCommand<OwnerRecord>> |
| 159 | private readonly shellRegistrations:OwnedRegistrations<OwnerRecord,LocalShellHook<OwnerRecord>> |
| 160 | private readonly hookRegistrations: OwnedRegistrations<OwnerRecord, LocalHook<OwnerRecord>> |
| 161 | private readonly promptSections: PromptSections<OwnerRecord> |
| 162 | private readonly skillRoots: SkillRoots<OwnerRecord> |
| 163 | private readonly avatarPacks: AvatarPacks<OwnerRecord> |
| 164 | private readonly mcpDefinitions:McpDefinitions<OwnerRecord> |
| 165 | private readonly adapterHost: AdapterHost |
| 166 | |
| 167 | constructor( |
| 168 | private readonly rpc: RpcPeer, |
| 169 | /** The trust tier this process serves; it activates only owners of that tier. */ |
| 170 | readonly tier: HostTier, |
| 171 | adapters: readonly DshAdapter[] = DSH_ADAPTERS, |
| 172 | ) { |
| 173 | const root: any = new Context() |
| 174 | this.root = root |
| 175 | const host = this |
| 176 | if (tier === 'plugin') installGitAdapter(() => ownerStorage.getStore() !== undefined) |
| 177 | this.toolRegistrations = new OwnedRegistrations( |
| 178 | rpc, |
| 179 | 'tool', |
| 180 | (owner) => owner.tools, |
| 181 | (message, owner) => this.log('warn', message, owner), |
| 182 | ) |
| 183 | this.commandRegistrations = new OwnedRegistrations( |
| 184 | rpc, |
| 185 | 'command', |
| 186 | (owner) => owner.commands, |
| 187 | (message, owner) => this.log('warn', message, owner), |
| 188 | ) |
| 189 | this.shellRegistrations=new OwnedRegistrations(rpc,'shell_hook',(owner)=>owner.shellHooks,(message,owner)=>this.log('warn',message,owner)) |
| 190 | this.hookRegistrations = new OwnedRegistrations(rpc, 'hook', (owner) => owner.hooks, |
| 191 | (message, owner) => this.log('warn', message, owner)) |
| 192 | this.promptSections = new PromptSections(rpc, (owner) => owner.promptSections, |
| 193 | (message, owner) => this.log('warn', message, owner)) |
| 194 | this.mcpDefinitions=new McpDefinitions(rpc,(owner)=>owner.mcpDefinitions,(message,owner)=>this.log('warn',message,owner)) |
| 195 | this.avatarPacks = new AvatarPacks(rpc, owner => owner.avatarPacks, (message, owner) => this.log('warn', message, owner)) |
| 196 | this.skillRoots = new SkillRoots(rpc, (owner) => owner.skillRoots, |
| 197 | (message, owner) => this.log('warn', message, owner)) |
| 198 | |
| 199 | // Cordis already owns listener effects and teardown. Intercept this one |
| 200 | // event using its supported extension point instead of replacing ctx.on. |
| 201 | // Actual upstream bridge seams for which this checkpoint has no core |
| 202 | // projection. Refuse instead of accepting listeners that never fire. |
| 203 | const unsupportedDshLifecycle = new Set([ |
| 204 | 'agent/pre-step', 'agent/turn-stopping', |
| 205 | 'subagent/start', 'subagent/end', |
| 206 | 'approval/request', |
| 207 | ]) |
| 208 | root.on('internal/listener', function (this: any, name: string, callback: any, options: any) { |
| 209 | const owner: OwnerRecord | undefined = this[OWNER] |
| 210 | if (owner && unsupportedDshLifecycle.has(name)) { |
| 211 | if (!(owner.bundledFirstParty && name === 'agent/pre-step')) { |
| 212 | throw new Error(`DSH lifecycle ${name} is not projected by this host checkpoint`) |
| 213 | } |
| 214 | } |
| 215 | if (name === 'agent/created' && options?.global) throw new Error('agent/created listeners are owner-scoped; global is unsupported') |
| 216 | if (name !== 'tools/pre-execute' && name !== 'tools/post-execute' && name !== 'tools/result' && !(owner?.bundledFirstParty && name === 'agent/pre-step')) return |
| 217 | if (!owner) throw new Error(`${name} listener registered outside a plugin owner`) |
| 218 | if (options?.prepend || options?.global) throw new Error(`${name} listeners use core registration order; prepend/global are unsupported`) |
| 219 | const hookEvent = name === 'tools/result' ? 'tools/post-execute' : name |
| 220 | const description = hookEvent === 'tools/pre-execute' |
| 221 | ? 'Programmable tool admission listener' |
| 222 | : hookEvent === 'agent/pre-step' |
| 223 | ? 'Bundled agent pre-step admission listener' |
| 224 | : 'Read-only tool outcome observer' |
| 225 | return this.effect(() => host.hookRegistrations.add( |
| 226 | { owner, name: hookEvent, callback, disposed: false }, |
| 227 | { name: hookEvent, description }, |
| 228 | ), `ctx.on("${name}")`) |
| 229 | }) |
| 230 | |
| 231 | // Refuse core service names before any plugin can run. The refusal does |
| 232 | // not depend on who calls: `ctx.root.provide(...)` runs with the root as |
| 233 | // its context, so an owner check alone could be sidestepped. The one |
| 234 | // exception is each host shim of its own name, provided once, below. |
| 235 | const shimClasses = new Map<string, Function>() |
| 236 | const shimsProvided = new Set<string>() |
| 237 | const reflect = root.reflect |
| 238 | const originalProvide = reflect.provide |
| 239 | reflect.provide = function (this: any, name: string, value: unknown, ...rest: unknown[]) { |
| 240 | if (REFUSED_SERVICES.has(name)) { |
| 241 | const shim = shimClasses.get(name) |
| 242 | const hostShim = shim !== undefined && !shimsProvided.has(name) && value instanceof (shim as any) |
| 243 | const reviewedPreset = name === 'agentPresets' && value !== null && typeof value === 'object' && (value as any)[REVIEWED_AGENT_PRESETS_BRAND] === true |
| 244 | if (!hostShim && !reviewedPreset) { |
| 245 | throw new Error(`plugin may not provide core service \`${name}\`: the Codewhale core owns it`) |
| 246 | } |
| 247 | if (hostShim) shimsProvided.add(name) |
| 248 | } |
| 249 | return originalProvide.call(this, name, value, ...rest) |
| 250 | } |
| 251 | |
| 252 | // Logger shim: every Cordis log line becomes a `log` notification. |
| 253 | root.logger.exporter({ |
| 254 | colors: false, |
| 255 | export: (message: any) => { |
| 256 | const fiber = message.fiber?.deref?.() |
| 257 | const owner: OwnerRecord | undefined = fiber?.ctx?.[OWNER] |
| 258 | const text = (message.args ?? []).map((arg: unknown) => (arg instanceof Error ? describeError(arg) : typeof arg === 'string' ? arg : safeStringify(arg))).join(' ') |
| 259 | host.log(message.type === 'error' ? 'error' : message.type === 'warn' ? 'warn' : 'info', `[${message.name}] ${text}`, owner) |
| 260 | }, |
| 261 | }) |
| 262 | |
| 263 | class ToolsShim extends Service { |
| 264 | constructor(ctx: any) { |
| 265 | super(ctx, 'tools') |
| 266 | } |
| 267 | |
| 268 | get(name: unknown, agent?: unknown) { |
| 269 | const invocation = host.toolInvocations.getStore() |
| 270 | if (typeof name !== 'string' || !invocation || !invocation.active || invocation.agent === undefined || agent !== invocation.agent) return undefined |
| 271 | return invocation.callerTools.includes(name) ? Object.freeze({ name }) : undefined |
| 272 | } |
| 273 | |
| 274 | /** DSH `ctx.tools.guard(fn)`: deny-only guard registered on tools/pre-execute; never auto-approves. */ |
| 275 | guard(guardFn: unknown): () => void { |
| 276 | const ctx: any = this.ctx |
| 277 | const owner: OwnerRecord | undefined = ctx[OWNER] |
| 278 | if (!owner) throw new Error('tools.guard called outside a plugin owner') |
| 279 | if (typeof guardFn !== 'function') throw new TypeError('tools.guard requires a guard function') |
| 280 | const wrapped = async (exec: unknown) => { |
| 281 | const verdict = await (guardFn as (exec: unknown) => unknown)(exec) |
| 282 | if (typeof verdict === 'string' && verdict.trim().length > 0) { |
| 283 | return { kind: 'deny', reason: verdict.trim() } |
| 284 | } |
| 285 | if (verdict && typeof verdict === 'object') { |
| 286 | const kind = (verdict as { kind?: unknown }).kind |
| 287 | const reason = (verdict as { reason?: unknown }).reason |
| 288 | if ((kind === undefined || kind === 'deny') && typeof reason === 'string' && reason.trim().length > 0) { |
| 289 | return { kind: 'deny', reason: reason.trim() } |
| 290 | } |
| 291 | } |
| 292 | return { kind: 'abstain' } |
| 293 | } |
| 294 | return ctx.effect(() => host.hookRegistrations.add( |
| 295 | { owner, name: 'tools/pre-execute', callback: wrapped, disposed: false }, |
| 296 | { name: 'tools/pre-execute', description: 'Read-only deny-only tool guard' }, |
| 297 | ), 'tools.guard()') |
| 298 | } |
| 299 | |
| 300 | /** DSH `ctx.tools.register(defineTool(...))`: returns an idempotent disposer. */ |
| 301 | register(definition: any, options?: unknown) { |
| 302 | const ctx: any = this.ctx |
| 303 | const owner: OwnerRecord | undefined = ctx[OWNER] |
| 304 | if (!owner) throw new Error('tools.register called outside a plugin owner') |
| 305 | if (options !== undefined && (!options || typeof options !== 'object' || Array.isArray(options) || Reflect.ownKeys(options).length !== 0)) { |
| 306 | throw new TypeError(`tools.register options are unsupported by the Codewhale DSH ${compatibility.target_dsh_version} definition adapter`) |
| 307 | } |
| 308 | validateDefinition(definition) |
| 309 | return ctx.effect(() => host.addTool(owner, definition), `tools.register(${JSON.stringify(definition.name)})`) |
| 310 | } |
| 311 | } |
| 312 | // Plugins share one process, so the owner token is not a boundary |
| 313 | // between them (design §4.4, threat 3). Freezing a shim at least stops |
| 314 | // the direct route of one plugin rewriting `register` for every other |
| 315 | // plugin; shared globals remain, and the approval card says so. |
| 316 | Object.freeze(ToolsShim.prototype) |
| 317 | const CommandsShim = defineCommandsService<OwnerRecord>({ |
| 318 | ownerOf: (ctx) => ctx[OWNER], |
| 319 | addCommand: (owner, command) => host.addCommand(owner, command), |
| 320 | }) |
| 321 | const PromptShim = definePromptService<OwnerRecord>({ |
| 322 | ownerOf: (ctx) => ctx[OWNER], |
| 323 | promptSections: this.promptSections, |
| 324 | }) |
| 325 | const ShellHooksShim=defineShellHooksService<OwnerRecord>({ownerOf:(ctx)=>ctx[OWNER],registrations:this.shellRegistrations}) |
| 326 | const McpShim=defineMcpService<OwnerRecord>({ownerOf:(ctx)=>(ctx as Context & { [OWNER]?: OwnerRecord })[OWNER],definitions:this.mcpDefinitions}) |
| 327 | const AvatarsShim = defineAvatarsService<OwnerRecord>({ ownerOf: (ctx) => ctx[OWNER], avatarPacks: this.avatarPacks }) |
| 328 | const SkillsShim = defineSkillsService<OwnerRecord>({ ownerOf: (ctx) => ctx[OWNER], skillRoots: this.skillRoots }) |
| 329 | class StorageShim extends Service { |
| 330 | constructor(ctx: any) { super(ctx, 'storage') } |
| 331 | private api(): PluginStorage { |
| 332 | const owner: OwnerRecord | undefined = (this.ctx as any)[OWNER] |
| 333 | if (!owner || !owner.dataDir) throw new Error('storage requires an active plugin owner and data directory') |
| 334 | owner.storage ??= createStorage({ |
| 335 | dataDir: owner.dataDir, |
| 336 | isActive: () => (owner.state === 'activating' || owner.state === 'active') && !owner.disposing, |
| 337 | }) |
| 338 | return owner.storage |
| 339 | } |
| 340 | get(key: string) { return this.api().get(key) } |
| 341 | set(key: string, value: Json) { return this.api().set(key, value) } |
| 342 | delete(key: string) { return this.api().delete(key) } |
| 343 | } |
| 344 | class UserQuestionsShim extends Service { |
| 345 | constructor(ctx: any) { super(ctx, 'userQuestions') } |
| 346 | async ask(request: { agent?: unknown; questions: unknown; signal?: AbortSignal; wait?: unknown }) { |
| 347 | const invocation = host.toolInvocations.getStore() |
| 348 | const owner: OwnerRecord | undefined = (this.ctx as any)[OWNER] |
| 349 | const data = (value: unknown, allowed: string[]): Record<string, unknown> => { |
| 350 | if (value === null || typeof value !== 'object' || Array.isArray(value) |
| 351 | || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) throw new RpcError(ErrorCode.InvalidParams, 'expected a plain question object') |
| 352 | const result: Record<string, unknown> = Object.create(null) |
| 353 | for (const key of Reflect.ownKeys(value)) { |
| 354 | const descriptor = Object.getOwnPropertyDescriptor(value, key)! |
| 355 | if (typeof key !== 'string' || !allowed.includes(key) || !descriptor.enumerable || !('value' in descriptor)) throw new RpcError(ErrorCode.InvalidParams, 'unsupported question property') |
| 356 | if (descriptor.value !== undefined) result[key] = descriptor.value |
| 357 | } |
| 358 | return result |
| 359 | } |
| 360 | const list = (value: unknown, maximum: number): unknown[] => { |
| 361 | if (!Array.isArray(value) || value.length > maximum || Reflect.ownKeys(value).length !== value.length + 1) throw new RpcError(ErrorCode.InvalidParams, 'invalid question array') |
| 362 | return Array.from({ length: value.length }, (_, index) => { |
| 363 | const descriptor = Object.getOwnPropertyDescriptor(value, String(index)) |
| 364 | if (!descriptor || !descriptor.enumerable || !('value' in descriptor)) throw new RpcError(ErrorCode.InvalidParams, 'invalid question array item') |
| 365 | return descriptor.value |
| 366 | }) |
| 367 | } |
| 368 | const input = data(request, ['agent', 'questions', 'signal', 'wait']) |
| 369 | if (input.wait !== undefined) throw new RpcError(ErrorCode.NotAvailable, 'timed or continued questions are not yet supported') |
| 370 | request = input as typeof request |
| 371 | if (request.signal !== undefined && !(request.signal instanceof AbortSignal)) { |
| 372 | throw new RpcError(ErrorCode.InvalidParams, 'question signal must be an AbortSignal') |
| 373 | } |
| 374 | if (request.signal?.aborted) throw new UserQuestionError('ask_user_question was aborted before the user answered', 'ASK_ABORTED') |
| 375 | const items = list(request.questions, 10) |
| 376 | if (items.length === 0) throw new UserQuestionError('ask_user_question requires at least one question', 'EMPTY_QUESTIONS') |
| 377 | if (request.agent === undefined) throw new RpcError(ErrorCode.NotAvailable, 'userQuestions.ask requires this live tool invocation’s agent') |
| 378 | if (!invocation || !invocation.active || invocation.signal.aborted || invocation.agent === undefined || request.agent !== invocation.agent) { |
| 379 | throw new UserQuestionError('human interaction requires the exact live calling agent when an agent is supplied', 'CALLER_NOT_LIVE') |
| 380 | } |
| 381 | if (invocation.owner !== owner || owner?.state !== 'active' || owner.disposing) throw new RpcError(ErrorCode.NotAvailable, 'userQuestions.ask service owner is no longer current') |
| 382 | if (invocation.delegated) throw new UserQuestionError("human interaction is unavailable while the calling agent is owned by another live agent; include the unresolved question or decision in the child agent's final result", 'DELEGATED_CALLER') |
| 383 | const live = () => invocation.active && !invocation.signal.aborted |
| 384 | && invocation.owner === owner && owner?.state === 'active' && !owner.disposing |
| 385 | && invocation.questionTicket !== undefined && request.agent === invocation.agent |
| 386 | if (!live()) throw new RpcError(ErrorCode.NotAvailable, 'userQuestions.ask requires this live tool invocation’s question ticket') |
| 387 | const signal = request.signal === undefined ? invocation.signal : AbortSignal.any([invocation.signal, request.signal]) |
| 388 | const questions = items.map(value => { |
| 389 | const question = data(value, ['id', 'question', 'header', 'detail', 'options', 'multiSelect', 'intent']) |
| 390 | const options = list(question.options === undefined ? [] : question.options, 1000) |
| 391 | const intent = question.intent === undefined ? undefined : data(question.intent, ['kind', 'approve', 'callId']) |
| 392 | if (intent !== undefined && intent.kind !== 'plan-review') throw new RpcError(ErrorCode.InvalidParams, 'unsupported question intent') |
| 393 | return { |
| 394 | id: question.id, question: question.question, header: question.header === undefined ? '' : question.header, |
| 395 | ...(question.detail === undefined ? {} : { detail: question.detail }), |
| 396 | ...(intent === undefined ? {} : { intent: { kind: 'plan-review', approve: intent.approve, |
| 397 | ...(intent.callId === undefined ? {} : { call_id: intent.callId }) } }), |
| 398 | options: options.map(option => { |
| 399 | const item = data(option, ['label', 'description']) |
| 400 | return { label: item.label, description: item.description === undefined ? '' : item.description } |
| 401 | }), |
| 402 | allow_free_text: true, multi_select: question.multiSelect === undefined ? false : question.multiSelect, |
| 403 | } |
| 404 | }) |
| 405 | if (!isJson(questions)) throw new RpcError(ErrorCode.InvalidParams, 'question data must be lossless JSON') |
| 406 | for (const question of questions) { |
| 407 | if (question.intent === undefined) continue |
| 408 | if (!question.options.some(option => option.label === question.intent!.approve)) throw new UserQuestionError('question ' + question.id + ' declares an intent whose approve label names none of its options', 'BAD_INTENT') |
| 409 | if (question.detail === undefined) throw new UserQuestionError('question ' + question.id + ' declares an intent without the detail it reviews', 'BAD_INTENT') |
| 410 | } |
| 411 | if (Buffer.byteLength(JSON.stringify(questions)) > 1024 * 1024) throw new RpcError(ErrorCode.InvalidParams, 'question payload exceeds 1 MiB') |
| 412 | const call = invocation! |
| 413 | const run = async () => { |
| 414 | if (!live() || signal.aborted) throw new RpcError(ErrorCode.Cancelled, 'question invocation ended') |
| 415 | const result = await host.rpc.request<unknown>('user-questions/ask', { owner: call.owner.ref, ticket: call.questionTicket, questions }, signal).catch(error => { |
| 416 | if (error instanceof RpcError && isJson(error.data) |
| 417 | && error.data !== null && typeof error.data === 'object' && !Array.isArray(error.data)) { |
| 418 | const code = error.data.user_question_error |
| 419 | if ((error.code === ErrorCode.NotAvailable && code === 'NO_PROVIDER') |
| 420 | || (error.code === ErrorCode.Cancelled && code === 'ASK_CANCELLED')) { |
| 421 | throw new UserQuestionError(error.message, code, { cause: error }) |
| 422 | } |
| 423 | } |
| 424 | if (signal.aborted) throw new UserQuestionError('ask_user_question was aborted before the user answered', 'ASK_ABORTED', { cause: error }) |
| 425 | throw error |
| 426 | }) |
| 427 | if (!live() || signal.aborted) throw new RpcError(ErrorCode.Cancelled, 'question invocation ended') |
| 428 | if (!isJson(result) || result === null || typeof result !== 'object' || Array.isArray(result) || !Array.isArray(result.answers)) { |
| 429 | throw new RpcError(ErrorCode.Internal, 'invalid question answer receipt') |
| 430 | } |
| 431 | const answers = questions.map(question => ({ id: question.id, selected: [] as string[], custom: undefined as string | undefined, skipped: false, rows: 0 })) |
| 432 | for (const row of result.answers) { |
| 433 | if (row === null || typeof row !== 'object' || Array.isArray(row) || typeof row.label !== 'string' || typeof row.value !== 'string') throw new RpcError(ErrorCode.Internal, 'invalid question answer row') |
| 434 | const answer = answers.find(answer => answer.id === row.id) |
| 435 | const question = questions.find(question => question.id === row.id) |
| 436 | if (!answer || !question || answer.skipped) throw new RpcError(ErrorCode.Internal, 'question answer identity mismatch') |
| 437 | if (row.kind === 'choice' && row.label === row.value && question.options.some(option => option.label === row.value) && !answer.selected.includes(row.value)) answer.selected.push(row.value) |
| 438 | else if (row.kind === 'custom' && row.label === '' && row.value.trim() !== '' && answer.custom === undefined) answer.custom = row.value |
| 439 | else if (row.kind === 'skipped' && row.label === '' && row.value === '' && answer.rows === 0) answer.skipped = true |
| 440 | else throw new RpcError(ErrorCode.Internal, 'ambiguous question answer receipt') |
| 441 | answer.rows += 1 |
| 442 | if (!question.multi_select && answer.selected.length + (answer.custom === undefined ? 0 : 1) > 1) throw new RpcError(ErrorCode.Internal, 'invalid single-select answer') |
| 443 | } |
| 444 | if (answers.some(answer => answer.rows === 0)) throw new RpcError(ErrorCode.Internal, 'missing question answer') |
| 445 | return { answers: answers.map(({ id, selected, custom }) => ({ id, selected, ...(custom === undefined ? {} : { custom }) })) } |
| 446 | } |
| 447 | const result = call.pending.then(run) |
| 448 | call.pending = result.then(() => undefined, () => undefined) |
| 449 | let cancel: () => void = () => {} |
| 450 | const cancelled = new Promise<never>((_, reject) => { |
| 451 | cancel = () => reject(new UserQuestionError('ask_user_question was aborted before the user answered', 'ASK_ABORTED')) |
| 452 | signal.addEventListener('abort', cancel, { once: true }) |
| 453 | if (signal.aborted) cancel() |
| 454 | }) |
| 455 | return Promise.race([result, cancelled]).finally(() => signal.removeEventListener('abort', cancel)) |
| 456 | } |
| 457 | } |
| 458 | Object.freeze(UserQuestionsShim.prototype) |
| 459 | Object.freeze(StorageShim.prototype) |
| 460 | const adapterHost: AdapterHost = { |
| 461 | tier, |
| 462 | rpc, |
| 463 | ownerOf: (ctx) => (ctx as { [OWNER]?: OwnerRecord })[OWNER], |
| 464 | liveInvocation: (ctx) => { |
| 465 | const invocation = host.toolInvocations.getStore() |
| 466 | const owner: OwnerRecord | undefined = (ctx as { [OWNER]?: OwnerRecord })[OWNER] |
| 467 | return invocation && invocation.active && !invocation.signal.aborted && owner !== undefined |
| 468 | && invocation.owner === owner && owner.state === 'active' && !owner.disposing |
| 469 | ? invocation |
| 470 | : undefined |
| 471 | }, |
| 472 | log: (level, message, owner) => host.log(level, message, owner), |
| 473 | brokerTicket: (ctx, service) => { |
| 474 | const invocation = adapterHost.liveInvocation(ctx) |
| 475 | const ticket = invocation?.brokerTickets.get(service) |
| 476 | if (invocation === undefined || ticket === undefined) throw new RpcError(ErrorCode.NotAvailable, `the ${String(service).slice(0, 64)} broker is only available to a live tool invocation the core gave a ticket for it`) |
| 477 | return { invocation, ticket } |
| 478 | }, |
| 479 | broker: async (ctx, service, method, input, signal?: AbortSignal) => { |
| 480 | if (signal !== undefined && !(signal instanceof AbortSignal)) { |
| 481 | throw new RpcError(ErrorCode.InvalidParams, 'signal must be an AbortSignal') |
| 482 | } |
| 483 | const { invocation, ticket } = adapterHost.brokerTicket(ctx, service) |
| 484 | const combined = signal === undefined ? invocation.signal : AbortSignal.any([invocation.signal, signal]) |
| 485 | return rpc.request<unknown>('dsh/broker', { owner: invocation.owner.ref, ticket, service, method, input }, combined) |
| 486 | }, |
| 487 | registerPromptSection: (ctx, definition) => { |
| 488 | const owner = (ctx as { [OWNER]?: OwnerRecord })[OWNER] |
| 489 | if (!owner) throw new Error('systemPrompt.section called outside a plugin owner') |
| 490 | const section = normalizePromptSection(definition) |
| 491 | return (ctx as any).effect(() => host.promptSections.register(owner, section), `systemPrompt.section(${JSON.stringify(section.id)})`) |
| 492 | }, |
| 493 | } |
| 494 | this.adapterHost = adapterHost |
| 495 | const shims = new Map<string, new (ctx: any) => Service>([ |
| 496 | ['tools', ToolsShim], |
| 497 | ['commands', CommandsShim], |
| 498 | ['prompt', PromptShim], |
| 499 | ['storage', StorageShim], |
| 500 | ['userQuestions', UserQuestionsShim], |
| 501 | ['skills', SkillsShim], |
| 502 | ['avatars', AvatarsShim], |
| 503 | ['mcp', McpShim], |
| 504 | ['shellHooks', ShellHooksShim], |
| 505 | ]) |
| 506 | for (const adapter of adapters) { |
| 507 | if (shims.has(adapter.service)) throw new Error(`DSH adapter for \`${adapter.service}\` duplicates a service the host root already provides`) |
| 508 | shims.set(adapter.service, adapter.define(adapterHost)) |
| 509 | } |
| 510 | const mismatched = [ |
| 511 | ...[...shims.keys()].filter((name) => !PROVIDED_SERVICES.has(name)).map((name) => `${name} is installed but not declared in compatibility.json`), |
| 512 | ...[...PROVIDED_SERVICES].filter((name) => !CORDIS_SERVICES.has(name) && !shims.has(name)).map((name) => `${name} is declared in compatibility.json but has no installed service`), |
| 513 | ] |
| 514 | if (mismatched.length > 0) throw new Error(`DSH provided services disagree with the installed services: ${mismatched.join('; ')}`) |
| 515 | const builtinExtras: Array<[string, new (ctx: any) => Service]> = [] |
| 516 | if (tier === 'builtin') { |
| 517 | for (const adapter of BUILTIN_DSH_ADAPTERS) { |
| 518 | const shim = adapter.define(adapterHost) |
| 519 | if (shims.has(adapter.service)) { |
| 520 | shims.set(adapter.service, shim) |
| 521 | } else { |
| 522 | builtinExtras.push([adapter.service, shim]) |
| 523 | } |
| 524 | } |
| 525 | } |
| 526 | for (const [name, shim] of [...shims, ...builtinExtras]) { |
| 527 | shimClasses.set(name, shim) |
| 528 | root.plugin(shim) |
| 529 | } |
| 530 | shimClasses.set('loader', ReviewedLoader) |
| 531 | installCompositionLoader(root) |
| 532 | } |
| 533 | |
| 534 | log(level: string, msg: string, owner?: OwnerRecord) { |
| 535 | const params: Record<string, string> = { level, msg: msg.slice(0, 8192) } |
| 536 | if (owner) params.plugin_id = owner.ref.plugin_id |
| 537 | this.rpc.notify('log', params) |
| 538 | } |
| 539 | |
| 540 | /** Called inside the owner's effect; returns the effect's cleanup. */ |
| 541 | private addTool(owner: OwnerRecord, definition: any): () => void { |
| 542 | const local: LocalTool = { owner, name: definition.name, definition, disposed: false } |
| 543 | return this.toolRegistrations.add(local, { |
| 544 | name: definition.name, |
| 545 | description: String(definition.description ?? ''), |
| 546 | input_schema: definition.parameters ?? { type: 'object', properties: {} }, |
| 547 | }) |
| 548 | } |
| 549 | |
| 550 | private addCommand(owner: OwnerRecord, definition: NormalizedCommand): () => void { |
| 551 | const local: LocalCommand<OwnerRecord> = { owner, name: definition.name, definition, disposed: false } |
| 552 | return this.commandRegistrations.add(local, commandSpec(definition)) |
| 553 | } |
| 554 | |
| 555 | /** |
| 556 | * `ext/activate`: load one `native` entry of a plugin under its owner. A |
| 557 | * manifest may declare several entries; the core sends one `ext/activate` |
| 558 | * per entry, in order, under the same owner token, and every entry becomes a |
| 559 | * fiber of that one owner. A further entry is accepted only after the |
| 560 | * previous one finished activating, for the same plugin, and only once per |
| 561 | * path. Core-selected Native scopes have independent fibers; failure withdraws |
| 562 | * that entry while siblings remain active. An unscoped owner stays atomic. |
| 563 | */ |
| 564 | async activate(params: ActivateParams): Promise<ActivateResult> { |
| 565 | // This process serves one tier. An owner of the other tier is refused |
| 566 | // outright, before anything of it is read or loaded. |
| 567 | const wanted = ownerTier(params.owner.plugin_id) |
| 568 | if (wanted !== this.tier) { |
| 569 | throw new RpcError( |
| 570 | ErrorCode.InvalidParams, |
| 571 | `owner ${JSON.stringify(params.owner.plugin_id)} belongs to the ${wanted} tier, but this host serves the ${this.tier} tier`, |
| 572 | ) |
| 573 | } |
| 574 | const key = params.owner.owner_token |
| 575 | let parent=this.owners.get(key) |
| 576 | const scopeKey=params.scope===undefined ? undefined : `${params.scope.path}\0${params.scope.sha256}` |
| 577 | if (scopeKey!==undefined) { |
| 578 | if (params.scope?.path!==params.entry.path || params.scope?.sha256!==params.entry.sha256) return {status:'failed',diagnostic:'scope does not match the core-selected entry'} |
| 579 | parent ??= {ref:params.owner,pluginName:params.plugin_name,fibers:[],pendingRegistrations:new Set(),refusals:[],tools:new Map(),commands:new Map(),hooks:new Map(),shellHooks:new Map(),promptSections:new Map(),skillRoots:new Map(),avatarPacks:new Map(),mcpDefinitions:new Map(),entries:new Set(),views:new Map(),state:'active',...(params.data_dir===undefined?{}:{dataDir:params.data_dir})} |
| 580 | if (parent.state!=='active' || parent.ref.plugin_id!==params.owner.plugin_id || parent.ref.generation!==params.owner.generation || parent.pluginName!==params.plugin_name) return {status:'failed',diagnostic:'scope owner was withdrawn'} |
| 581 | parent.views ??=new Map() |
| 582 | this.owners.set(key,parent) |
| 583 | } |
| 584 | const existing = scopeKey===undefined ? this.owners.get(key) : parent!.views!.get(scopeKey) |
| 585 | if (existing) { |
| 586 | if (existing.state !== 'active') return { status: 'failed', diagnostic: 'owner token already active' } |
| 587 | if (existing.ref.plugin_id !== params.owner.plugin_id || existing.pluginName !== params.plugin_name) { |
| 588 | return { status: 'failed', diagnostic: 'owner token already active for another plugin' } |
| 589 | } |
| 590 | if (existing.entries.has(params.entry.path)) { |
| 591 | return { status: 'failed', diagnostic: `entry ${params.entry.path} is already activated under this owner` } |
| 592 | } |
| 593 | existing.state = 'activating' |
| 594 | } |
| 595 | const owner: OwnerRecord = existing ?? { |
| 596 | ref: params.owner, |
| 597 | ...(params.scope===undefined ? {} : {scope:params.scope}), |
| 598 | pluginName: params.plugin_name, |
| 599 | fibers: [], |
| 600 | pendingRegistrations: new Set(), |
| 601 | refusals: [], |
| 602 | tools: new Map(), |
| 603 | commands: new Map(), |
| 604 | hooks: new Map(), |
| 605 | shellHooks:new Map(), |
| 606 | promptSections: new Map(), |
| 607 | skillRoots: new Map(), |
| 608 | avatarPacks: new Map(), |
| 609 | mcpDefinitions:new Map(), |
| 610 | entries: new Set(), |
| 611 | ...(params.data_dir === undefined ? {} : { dataDir: params.data_dir }), |
| 612 | state: 'activating', |
| 613 | } |
| 614 | if (!existing) {if(scopeKey===undefined)this.owners.set(key,owner);else parent!.views!.set(scopeKey,owner)} |
| 615 | owner.entries.add(params.entry.path) |
| 616 | try { |
| 617 | const bytes = await readFile(params.entry.path) |
| 618 | const digest = createHash('sha256').update(bytes).digest('hex') |
| 619 | if (digest !== params.entry.sha256) { |
| 620 | throw new Error(`entry ${params.entry.path} changed after review (sha256 ${digest.slice(0, 12)}…)`) |
| 621 | } |
| 622 | const module = await ownerStorage.run(owner, () => import(pathToFileURL(params.entry.path).href)).catch((error) => { |
| 623 | throw explainImportError(error) |
| 624 | }) |
| 625 | if (this.tier === 'builtin' && owner.ref.plugin_id === 'host:harness') { |
| 626 | if (existing || typeof module.createHarnessModule !== 'function') throw new Error('invalid harness builtin module') |
| 627 | owner.harness = module.createHarnessModule(this.rpc, Object.freeze(structuredClone(owner.ref))) as HarnessBuiltin |
| 628 | owner.state = 'active' |
| 629 | return { status: 'ok', tools: [], commands: [] } |
| 630 | } |
| 631 | if (this.tier === 'builtin' && owner.ref.plugin_id === 'host:mcp') { |
| 632 | if (existing || typeof module.createMcpModule !== 'function') throw new Error('invalid MCP builtin module') |
| 633 | owner.mcp = module.createMcpModule(this.rpc, Object.freeze(structuredClone(owner.ref))) as McpBuiltin |
| 634 | owner.state = 'active' |
| 635 | return { status: 'ok', tools: [], commands: [] } |
| 636 | } |
| 637 | const plugin = pickPlugin(module) |
| 638 | const creatorAllowed = this.tier === 'builtin' && owner.ref.plugin_id === 'host:creator' |
| 639 | const creatorRestricted = this.tier === 'builtin' && !creatorAllowed |
| 640 | const missing = Object.keys(Inject.resolve(plugin.inject)).filter((name) => (!PROVIDED_SERVICES.has(name) || (creatorRestricted && CREATOR_SERVICES.has(name))) && !(creatorAllowed && CREATOR_SERVICES.has(name))) |
| 641 | if (missing.length > 0) throw new Error(`requires ${describeMissingServices(missing, { scoped: false })}`) |
| 642 | if (params.bundled_first_party) owner.bundledFirstParty = true |
| 643 | const ownerCtx = this.root.extend({ [OWNER]: owner }) |
| 644 | if (owner.bundledFirstParty) { |
| 645 | Object.defineProperty(ownerCtx, 'subagents', { |
| 646 | configurable: true, |
| 647 | get: () => { |
| 648 | owner.subagentsView ??= createBundledSubagentsView(this.adapterHost, this.root.subagents, ownerCtx) |
| 649 | return owner.subagentsView |
| 650 | }, |
| 651 | }) |
| 652 | Object.defineProperty(ownerCtx, 'systemPrompt', { |
| 653 | configurable: true, |
| 654 | get: () => { |
| 655 | owner.systemPromptView ??= createBundledSystemPromptView(this.adapterHost, ownerCtx) |
| 656 | return owner.systemPromptView |
| 657 | }, |
| 658 | }) |
| 659 | } |
| 660 | const fiber = ownerStorage.run(owner, () => ownerCtx.plugin(plugin, params.config ?? {})) |
| 661 | owner.fibers.push(fiber) |
| 662 | await withDeadline(Promise.resolve(fiber.await()), ACTIVATE_DEADLINE_MS, 'activation') |
| 663 | const pending = pendingFibers(fiber) |
| 664 | if (pending.length > 0) { |
| 665 | throw new Error(`plugin fibers are waiting on services the host does not provide: ${pending.join(', ')}`) |
| 666 | } |
| 667 | while (owner.pendingRegistrations.size > 0) { |
| 668 | await Promise.allSettled([...owner.pendingRegistrations]) |
| 669 | } |
| 670 | if (owner.refusals.length > 0) throw new Error(owner.refusals.join('; ')) |
| 671 | if (owner.state !== 'activating' || owner.disposing || (scopeKey !== undefined && parent?.state !== 'active')) throw new Error('entry was withdrawn while activating') |
| 672 | owner.state = 'active' |
| 673 | return { |
| 674 | status: 'ok', |
| 675 | tools: [...owner.tools.values()].map((tool) => tool.name).sort(), |
| 676 | commands: [...owner.commands.values()].map((command) => command.name).sort(), |
| 677 | } |
| 678 | } catch (error) { |
| 679 | owner.state = 'failed' |
| 680 | // Return the activation cause promptly, while retaining a dirty owner |
| 681 | // for Rust's bounded ext/deactivate receipt. Never hide an unfinished |
| 682 | // disposer by deleting the record before Core can observe it. |
| 683 | const cleanup = this.disposeOwner(owner) |
| 684 | void cleanup.then(() => { |
| 685 | this.toolRegistrations.forget(owner) |
| 686 | this.commandRegistrations.forget(owner) |
| 687 | this.hookRegistrations.forget(owner);this.shellRegistrations.forget(owner) |
| 688 | this.promptSections.forget(owner) |
| 689 | this.skillRoots.forget(owner);this.avatarPacks.forget(owner);this.mcpDefinitions.forget(owner) |
| 690 | if (scopeKey === undefined) { |
| 691 | if (this.owners.get(key) === owner) this.owners.delete(key) |
| 692 | } else if (parent?.views?.get(scopeKey) === owner) parent.views.delete(scopeKey) |
| 693 | }, () => undefined) |
| 694 | return { status: 'failed', diagnostic: describeError(error) } |
| 695 | } |
| 696 | } |
| 697 | |
| 698 | async harnessRun(params: HarnessRunParams, signal: AbortSignal): Promise<unknown> { |
| 699 | const owner = this.owners.get(params.owner.owner_token) |
| 700 | if (this.tier !== 'builtin' || params.owner.plugin_id !== 'host:harness' || owner?.state !== 'active' || owner.ref.generation !== params.owner.generation || !owner.harness || owner.disposing) throw new RpcError(ErrorCode.NotAvailable, 'harness builtin owner is no longer live') |
| 701 | return owner.harness.run(params, signal) |
| 702 | } |
| 703 | |
| 704 | private mcpOwner(ref: OwnerRef): McpBuiltin { |
| 705 | const owner = this.owners.get(ref.owner_token) |
| 706 | if (this.tier !== 'builtin' || ref.plugin_id !== 'host:mcp' || owner?.state !== 'active' || owner.ref.generation !== ref.generation || !owner.mcp || owner.disposing) { |
| 707 | throw new RpcError(ErrorCode.NotAvailable, 'MCP builtin owner is no longer live') |
| 708 | } |
| 709 | return owner.mcp |
| 710 | } |
| 711 | async mcpOpen(params: McpOpenParams, signal: AbortSignal): Promise<unknown> { return this.mcpOwner(params.owner).open(params, signal) } |
| 712 | async mcpRequest(params: McpRequestParams, signal: AbortSignal): Promise<unknown> { return this.mcpOwner(params.owner).request(params, signal) } |
| 713 | async mcpClose(params: McpCloseParams): Promise<unknown> { await this.mcpOwner(params.owner).close(params.owner, params.session_id); return {} } |
| 714 | |
| 715 | /** Dispose one owner's fibers (reverse order, async disposers awaited). Memoised. */ |
| 716 | disposeOwner(owner: OwnerRecord): Promise<void> { |
| 717 | owner.state = 'disposed' |
| 718 | owner.disposing ??= (async () => { |
| 719 | for (const view of owner.views?.values() ?? []) await this.disposeOwner(view) |
| 720 | await owner.mcp?.dispose() |
| 721 | await owner.harness?.dispose() |
| 722 | for (const fiber of [...owner.fibers].reverse()) { |
| 723 | await fiber.dispose() |
| 724 | } |
| 725 | // Admission may have answered after a failed fiber's disposer ran. |
| 726 | // OwnedRegistrations compensates that admission and tracks its cleanup; |
| 727 | // acknowledge withdrawal only once both phases have settled. |
| 728 | while (owner.pendingRegistrations.size > 0) { |
| 729 | await Promise.allSettled([...owner.pendingRegistrations]) |
| 730 | } |
| 731 | owner.state = 'disposed' |
| 732 | })() |
| 733 | return owner.disposing |
| 734 | } |
| 735 | |
| 736 | async deactivate(ref: OwnerRef, entry?: EntryRef): Promise<DeactivateResult> { |
| 737 | const parent=this.owners.get(ref.owner_token) |
| 738 | if (parent && (parent.ref.plugin_id!==ref.plugin_id || parent.ref.generation!==ref.generation)) throw new Error('deactivation owner differs') |
| 739 | if (entry===undefined && parent?.views) { |
| 740 | parent.state = 'disposed' |
| 741 | const results=await Promise.all([...parent.views.values()].map(view=>this.deactivate(ref,view.scope))) |
| 742 | parent.views.clear() |
| 743 | this.owners.delete(ref.owner_token) |
| 744 | return {disposed:results.every(result=>result.disposed),leaked:results.flatMap(result=>result.leaked)} |
| 745 | } |
| 746 | const scopeKey=entry===undefined?undefined:`${entry.path}\0${entry.sha256}` |
| 747 | const owner = scopeKey===undefined?parent:parent?.views?.get(scopeKey) |
| 748 | if (!owner) return { disposed: true, leaked: [] } |
| 749 | let disposed = true |
| 750 | try { |
| 751 | await withDeadline(this.disposeOwner(owner), DISPOSE_DEADLINE_MS, 'dispose') |
| 752 | } catch { |
| 753 | disposed = false |
| 754 | } |
| 755 | const leaked = [ |
| 756 | ...[...owner.tools.values()].map((tool) => `tool:${tool.name}`), |
| 757 | ...[...owner.commands.values()].map((command) => `command:${command.name}`), |
| 758 | ...[...owner.shellHooks.values()].map((hook)=>`shell_hook:${hook.name}`), |
| 759 | ...[...owner.hooks.values()].map((hook) => `hook:${hook.name}`), |
| 760 | ...[...owner.promptSections.values()].map((section) => `prompt_section:${section.name}`), |
| 761 | ...[...owner.mcpDefinitions.values()].map(server=>`mcp_server:${server.name}`), |
| 762 | ...[...owner.avatarPacks.values()].map((pack) => `avatar_pack:${pack.name}`), |
| 763 | ...[...owner.skillRoots.values()].map((root) => `skill_root:${root.name}`), |
| 764 | ] |
| 765 | for (const fiber of owner.fibers) { |
| 766 | for (const effect of fiber.getEffects?.() ?? []) leaked.push(`effect:${effect.label}`) |
| 767 | } |
| 768 | this.toolRegistrations.forget(owner) |
| 769 | this.commandRegistrations.forget(owner) |
| 770 | this.hookRegistrations.forget(owner);this.shellRegistrations.forget(owner) |
| 771 | this.promptSections.forget(owner) |
| 772 | this.skillRoots.forget(owner);this.avatarPacks.forget(owner);this.mcpDefinitions.forget(owner) |
| 773 | if(scopeKey===undefined)this.owners.delete(ref.owner_token);else parent?.views?.delete(scopeKey) |
| 774 | return { disposed, leaked } |
| 775 | } |
| 776 | |
| 777 | async deactivateAll(deadlineMs: number) { |
| 778 | await withDeadline( |
| 779 | Promise.allSettled([...this.owners.values()].map((owner) => this.deactivate(owner.ref))), |
| 780 | deadlineMs, |
| 781 | 'shutdown', |
| 782 | ).catch(() => undefined) |
| 783 | } |
| 784 | |
| 785 | async callTool( |
| 786 | handle: number, |
| 787 | input: unknown, |
| 788 | callId: string, |
| 789 | signal: AbortSignal, |
| 790 | workspace?: string, |
| 791 | /** The core's invocation ticket: present only when this call runs under the turn loop's permission gate. */ |
| 792 | ticket?: string, |
| 793 | identity?: InvocationIdentityWire, |
| 794 | ): Promise<ToolResultWire> { |
| 795 | const local = this.toolRegistrations.byHandle.get(handle) |
| 796 | if (!local || local.disposed || local.owner.state !== 'active') { |
| 797 | throw new RpcError(ErrorCode.NotAvailable, `tool handle ${handle} is not live`) |
| 798 | } |
| 799 | const definition = local.definition |
| 800 | // `workspace` is the calling session's workspace, per call; `dataDir` is |
| 801 | // this plugin's own directory. Both are read-only strings. |
| 802 | // `core` exists only when the core gave this call a ticket (`exec.core` in shims/core.ts). |
| 803 | const core = ticket === undefined ? {} : { core: makeCoreApi(this.rpc, local.owner.ref, ticket, signal) } |
| 804 | const agent = workspace && identity?.session_id ? Object.freeze({ |
| 805 | id: identity.agent_id ?? identity.session_id, |
| 806 | session: Object.freeze({ header: Object.freeze({ cwd: workspace }) }), |
| 807 | }) : undefined |
| 808 | const exec = Object.freeze({ signal, callId, args: input, ...callContext(local.owner, workspace, identity), ...core, ...(agent === undefined ? {} : { agent }) }) |
| 809 | const closed = new AbortController() |
| 810 | const invocation: ToolInvocation = { |
| 811 | owner: local.owner, |
| 812 | callId, |
| 813 | session: agent?.session, |
| 814 | agent, |
| 815 | questionTicket: identity?.question_ticket, |
| 816 | subagentTicket: identity?.subagent_ticket, |
| 817 | brokerTickets: new Map((identity?.broker_tickets ?? []).map(({ service, ticket }) => [service, ticket])), |
| 818 | callerTools: Object.freeze([...(identity?.caller_tools ?? [])]), |
| 819 | delegated: identity?.agent_id !== undefined, |
| 820 | ticket: identity?.checkpoint_ticket, |
| 821 | signal: AbortSignal.any([signal, closed.signal]), |
| 822 | active: true, |
| 823 | pending: Promise.resolve(), |
| 824 | } |
| 825 | const gitInvocation = workspace && ticket ? { |
| 826 | workspace, |
| 827 | core: makeCoreApi(this.rpc, local.owner.ref, ticket, invocation.signal), |
| 828 | signal: invocation.signal, |
| 829 | live: () => invocation.active && local.owner.state === 'active' && !local.owner.disposing, |
| 830 | } : undefined |
| 831 | const run = ownerStorage.run(local.owner, () => this.toolInvocations.run(invocation, () => gitInvocations.run(gitInvocation, async () => { |
| 832 | const value = await definition.execute(input, exec) |
| 833 | return renderResult(definition, input, value) |
| 834 | }))) |
| 835 | try { |
| 836 | return await Promise.race([run, abortedBy(signal)]) |
| 837 | } finally { |
| 838 | invocation.active = false |
| 839 | closed.abort() |
| 840 | } |
| 841 | } |
| 842 | |
| 843 | /** `command/run`: only for a handle the core admitted, and only on a user's own invocation. */ |
| 844 | async callCommand(handle: number, rawInput: string, commandId: string, signal: AbortSignal, workspace?: string, identity?: InvocationIdentityWire): Promise<CommandResultWire> { |
| 845 | const local = this.commandRegistrations.byHandle.get(handle) |
| 846 | if (!local || local.disposed || local.owner.state !== 'active') { |
| 847 | throw new RpcError(ErrorCode.NotAvailable, `command handle ${handle} is not live`) |
| 848 | } |
| 849 | const { definition } = local |
| 850 | const call = makeInvocation(definition.name, rawInput, commandId, signal, callContext(local.owner, workspace, identity)) |
| 851 | const run = ownerStorage.run(local.owner, async () => { |
| 852 | try { |
| 853 | const value = await definition.handler(call.invocation) |
| 854 | return call.complete(value) |
| 855 | } finally { |
| 856 | call.close() |
| 857 | } |
| 858 | }) |
| 859 | try { |
| 860 | return await Promise.race([run, abortedBy(signal)]) |
| 861 | } finally { |
| 862 | call.close() |
| 863 | } |
| 864 | } |
| 865 | |
| 866 | async evaluateHook(params: HookEvaluateParams, signal: AbortSignal): Promise<HookVerdictWire> { |
| 867 | const local = this.hookRegistrations.byHandle.get(params.handle) |
| 868 | if (!local || local.disposed || local.owner.state !== 'active' || params.event !== local.name) { |
| 869 | throw new RpcError(ErrorCode.NotAvailable, 'hook handle is not live for this event') |
| 870 | } |
| 871 | if (params.event === 'agent/pre-step') { |
| 872 | const rawMessages = Array.isArray((params.payload.input as any)?.messages) |
| 873 | ? (params.payload.input as any).messages |
| 874 | : [] |
| 875 | const stepPayload = { |
| 876 | agent: { |
| 877 | id: params.payload.name, |
| 878 | session: { |
| 879 | header: { |
| 880 | id: params.payload.name, |
| 881 | cwd: params.payload.workspace, |
| 882 | version: 4, |
| 883 | }, |
| 884 | }, |
| 885 | }, |
| 886 | } |
| 887 | const run = ownerStorage.run(local.owner, async () => { |
| 888 | const decision: any = await (local.callback as any)(stepPayload, async () => ({ |
| 889 | kind: 'enter', |
| 890 | messages: rawMessages, |
| 891 | })) |
| 892 | if (decision && typeof decision === 'object' && decision.kind === 'skip') { |
| 893 | return { kind: 'deny', reason: 'agent/pre-step skipped' } as HookVerdictWire |
| 894 | } |
| 895 | return { kind: 'abstain' } as HookVerdictWire |
| 896 | }) |
| 897 | return Promise.race([run, abortedBy(signal)]) |
| 898 | } |
| 899 | const exec = hookExecution(params.payload, signal) |
| 900 | if (params.event === 'tools/post-execute') { |
| 901 | const run = ownerStorage.run(local.owner, async () => { |
| 902 | try { |
| 903 | await local.callback(exec, async () => ({ kind: 'abstain' })) |
| 904 | } catch (error) { |
| 905 | this.log('warn', `tools/post-execute listener threw: ${describeError(error)}`, local.owner) |
| 906 | } |
| 907 | return { kind: 'abstain' } as HookVerdictWire |
| 908 | }) |
| 909 | return Promise.race([run, abortedBy(signal)]) |
| 910 | } |
| 911 | const run = ownerStorage.run(local.owner, async () => hookVerdict( |
| 912 | await local.callback(exec, async () => ({ kind: 'abstain' })), |
| 913 | () => { |
| 914 | if (local.owner.warnedAllow) return |
| 915 | local.owner.warnedAllow = true |
| 916 | this.log('warn', 'pre-execute allow is an abstention; Rust still evaluates all admission gates', local.owner) |
| 917 | }, |
| 918 | )) |
| 919 | return Promise.race([run, abortedBy(signal)]) |
| 920 | } |
| 921 | } |
| 922 | |
| 923 | /** The read-only context a call carries beyond its input; a field the core did not send is absent. */ |
| 924 | interface InvocationIdentityWire { |
| 925 | question_ticket?: string |
| 926 | subagent_ticket?: string |
| 927 | broker_tickets?: { service: string, ticket: string }[] |
| 928 | caller_tools?: string[] |
| 929 | checkpoint_ticket?: string |
| 930 | session_id?: string |
| 931 | agent_id?: string |
| 932 | origin_turn_id?: string |
| 933 | } |
| 934 | |
| 935 | function callContext(owner: OwnerRecord, workspace: string | undefined, identity?: InvocationIdentityWire) { |
| 936 | return { |
| 937 | ...(workspace === undefined ? {} : { workspace }), |
| 938 | ...(owner.dataDir === undefined ? {} : { dataDir: owner.dataDir }), |
| 939 | ...(identity?.session_id === undefined ? {} : { sessionId: identity.session_id }), |
| 940 | ...(identity?.agent_id === undefined ? {} : { agentId: identity.agent_id }), |
| 941 | ...(identity?.origin_turn_id === undefined ? {} : { originTurnId: identity.origin_turn_id }), |
| 942 | } |
| 943 | } |
| 944 | |
| 945 | /** Rejects as cancelled when `signal` aborts. */ |
| 946 | function abortedBy(signal: AbortSignal): Promise<never> { |
| 947 | return new Promise<never>((_, reject) => { |
| 948 | const onAbort = () => reject(new RpcError(ErrorCode.Cancelled, 'cancelled')) |
| 949 | if (signal.aborted) onAbort() |
| 950 | else signal.addEventListener('abort', onAbort, { once: true }) |
| 951 | }) |
| 952 | } |
| 953 | |
| 954 | function renderResult(definition: any, input: unknown, value: unknown): ToolResultWire { |
| 955 | let blocks: unknown = undefined |
| 956 | if (definition.output !== undefined) { |
| 957 | if (!isJson(value)) throw new ToolOutputError(definition.name, ['value must be lossless JSON']) |
| 958 | const violations = validateJsonSchemaValue(definition.output.schema, value) |
| 959 | if (violations.length > 0) throw new ToolOutputError(definition.name, violations) |
| 960 | blocks = definition.output.render(input, value) |
| 961 | if (!Array.isArray(blocks)) throw new ToolOutputError(definition.name, ['output.render must return an array of content blocks']) |
| 962 | } |
| 963 | const content: ContentBlockWire[] = [] |
| 964 | if (Array.isArray(blocks)) { |
| 965 | for (const block of blocks) { |
| 966 | if (!block || typeof block !== 'object' || Array.isArray(block)) { |
| 967 | throw new ToolOutputError(definition.name, ['output.render returned an unsupported content block; this host accepts text or saved image blocks only']) |
| 968 | } |
| 969 | const kind = (block as any).type |
| 970 | if (kind === 'text') { |
| 971 | if (typeof (block as any).text !== 'string') { |
| 972 | throw new ToolOutputError(definition.name, ['output.render returned an unsupported content block; this host accepts text or saved image blocks only']) |
| 973 | } |
| 974 | if (Reflect.ownKeys(block).some(key => key !== 'type' && key !== 'text')) throw new ToolOutputError(definition.name, ['output.render returned unsupported text-block fields']) |
| 975 | content.push({ type: 'text', text: (block as any).text }) |
| 976 | } else if (kind === 'image') { |
| 977 | const attachment = (block as any).attachment |
| 978 | if (!attachment || typeof attachment !== 'object' || Array.isArray(attachment)) { |
| 979 | throw new ToolOutputError(definition.name, ['output.render returned an unsupported content block; image blocks require a saved attachment reference']) |
| 980 | } |
| 981 | if (Reflect.ownKeys(block).some(key => key !== 'type' && key !== 'attachment')) throw new ToolOutputError(definition.name, ['output.render returned unsupported image-block fields']) |
| 982 | const attachmentId = (attachment as any).attachmentId |
| 983 | if (typeof attachmentId !== 'string' || attachmentId.length === 0 || attachmentId.length > 256) { |
| 984 | throw new ToolOutputError(definition.name, ['output.render returned an image block without a valid attachmentId']) |
| 985 | } |
| 986 | content.push({ type: 'image_ref', attachment_id: attachmentId }) |
| 987 | } else { |
| 988 | throw new ToolOutputError(definition.name, ['output.render returned an unsupported content block; this host accepts text or saved image blocks only']) |
| 989 | } |
| 990 | } |
| 991 | } else { |
| 992 | content.push({ type: 'text', text: typeof value === 'string' ? value : safeStringify(value) }) |
| 993 | } |
| 994 | const result: ToolResultWire = { content, is_error: false } |
| 995 | if (value !== undefined && isJson(value)) result.structured = value |
| 996 | return result |
| 997 | } |
| 998 | |
| 999 | function safeStringify(value: unknown): string { |
| 1000 | try { |
| 1001 | return JSON.stringify(value) ?? String(value) |
| 1002 | } catch { |
| 1003 | return String(value) |
| 1004 | } |
| 1005 | } |
| 1006 | |
| 1007 | function validateDefinition(definition: any) { |
| 1008 | if (!definition || typeof definition !== 'object') throw new TypeError('tool definition must be an object') |
| 1009 | if (typeof definition.name !== 'string' || definition.name.length === 0) throw new TypeError('tool definition needs a name') |
| 1010 | if (typeof definition.execute !== 'function') throw new TypeError(`tool \`${definition.name}\` needs an execute function`) |
| 1011 | if (definition.parameters !== undefined && (typeof definition.parameters !== 'object' || definition.parameters === null)) { |
| 1012 | throw new TypeError(`tool \`${definition.name}\` parameters must be a JSON schema object`) |
| 1013 | } |
| 1014 | if (definition.output !== undefined) { |
| 1015 | if (!definition.output || typeof definition.output !== 'object' || typeof definition.output.render !== 'function') { |
| 1016 | throw new TypeError(`tool \`${definition.name}\` output must declare a schema and render function`) |
| 1017 | } |
| 1018 | assertSupportedJsonSchema(definition.output.schema) |
| 1019 | } |
| 1020 | for (const field of ['when', 'projectContent', 'finalizeContent']) { |
| 1021 | if (definition[field] !== undefined) throw new TypeError(`tool \`${definition.name}\` requires unsupported DSH execution field \`${field}\``) |
| 1022 | } |
| 1023 | if (definition.timeoutMs !== undefined && (typeof definition.timeoutMs !== 'number' || !Number.isFinite(definition.timeoutMs) || definition.timeoutMs <= 0)) { |
| 1024 | throw new TypeError(`tool \`${definition.name}\` timeoutMs must be a finite positive number`) |
| 1025 | } |
| 1026 | if (definition.deferLoading !== undefined && typeof definition.deferLoading !== 'boolean') throw new TypeError(`tool \`${definition.name}\` deferLoading must be boolean`) |
| 1027 | } |
| 1028 | |
| 1029 | function pickPlugin(module: any): any { |
| 1030 | const candidate = module?.default ?? module |
| 1031 | if (typeof candidate === 'function') return candidate |
| 1032 | if (candidate && typeof candidate.apply === 'function') return candidate |
| 1033 | if (module && typeof module.apply === 'function') return module |
| 1034 | throw new Error('entry module exports no Cordis plugin (a function, or an object with `apply`)') |
| 1035 | } |
| 1036 | |
| 1037 | /** Names of services that nested fibers under `fiber` are still waiting on. */ |
| 1038 | function pendingFibers(fiber: any): string[] { |
| 1039 | const out: string[] = [] |
| 1040 | const seen = new Set<any>() |
| 1041 | const visit = (current: any) => { |
| 1042 | if (!current || seen.has(current)) return |
| 1043 | seen.add(current) |
| 1044 | if (current.state === 0 /* PENDING */) { |
| 1045 | const names = Object.keys(current.inject ?? {}) |
| 1046 | const unresolved = names.filter((name) => current.ctx?.get?.(name) === undefined) |
| 1047 | out.push(`${current.name ?? 'plugin'} waits on ${describeMissingServices(unresolved.length > 0 ? unresolved : names)}`) |
| 1048 | } |
| 1049 | } |
| 1050 | visit(fiber) |
| 1051 | for (const runtime of fiber.ctx?.registry?.values?.() ?? []) { |
| 1052 | for (const child of runtime.fibers ?? []) { |
| 1053 | if (child.parent?.[OWNER] === fiber.ctx?.[OWNER]) visit(child) |
| 1054 | } |
| 1055 | } |
| 1056 | return out |
| 1057 | } |
| 1058 |