@acrylblends/control 0.0.0-stage → 0.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/README.md +13 -2
  2. package/cordis.patch.yml +3 -0
  3. package/lib/index.js +1457 -0
  4. package/lib/index.js.map +1 -0
  5. package/lib/types/agent/agent-control.d.ts +104 -0
  6. package/lib/types/agent/providers/acp.d.ts +7 -0
  7. package/lib/types/agent/providers/capabilities.d.ts +13 -0
  8. package/lib/types/agent/providers/claude.d.ts +7 -0
  9. package/lib/types/agent/providers/codex.d.ts +7 -0
  10. package/lib/types/agent/providers/dsh-native.d.ts +7 -0
  11. package/lib/types/agent/providers/factory.d.ts +17 -0
  12. package/lib/types/agent/transports/claude-stream.d.ts +55 -0
  13. package/lib/types/architecture/projection.d.ts +43 -0
  14. package/lib/types/architecture/provider.d.ts +15 -0
  15. package/lib/types/authorization/attempts.d.ts +88 -0
  16. package/lib/types/authorization/service.d.ts +25 -0
  17. package/lib/types/authorization/types.d.ts +89 -0
  18. package/lib/types/contracts/operations.d.ts +20 -0
  19. package/lib/types/contracts/session.d.ts +42 -0
  20. package/lib/types/credential/default-model.d.ts +38 -0
  21. package/lib/types/credential/projection.d.ts +87 -0
  22. package/lib/types/credential/route-activation.d.ts +25 -0
  23. package/lib/types/credential/types.d.ts +38 -0
  24. package/lib/types/events.d.ts +14 -0
  25. package/lib/types/index.d.ts +28 -0
  26. package/lib/types/platform/tools.d.ts +113 -0
  27. package/lib/types/platform/web.d.ts +19 -0
  28. package/lib/types/plugin/controller.d.ts +145 -0
  29. package/lib/types/plugin/host.d.ts +84 -0
  30. package/lib/types/plugin/provider.d.ts +41 -0
  31. package/lib/types/plugin/types.d.ts +43 -0
  32. package/lib/types/protocol/client.d.ts +7 -0
  33. package/package.json +60 -4
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["Service","nodeSpawn","FIBER_PHASE","phaseOf","Service","Service"],"sources":["../src/agent/agent-control.ts","../src/agent/transports/claude-stream.ts","../src/agent/providers/capabilities.ts","../src/agent/providers/factory.ts","../src/agent/providers/dsh-native.ts","../src/agent/providers/codex.ts","../src/agent/providers/claude.ts","../src/agent/providers/acp.ts","../src/architecture/projection.ts","../src/architecture/provider.ts","../src/contracts/session.ts","../src/credential/projection.ts","../src/credential/route-activation.ts","../src/credential/default-model.ts","../src/authorization/types.ts","../src/authorization/service.ts","../src/authorization/attempts.ts","../src/platform/tools.ts","../src/plugin/host.ts","../src/plugin/controller.ts","../src/plugin/provider.ts","../src/protocol/client.ts"],"sourcesContent":["/** Provider-neutral agent-control service definition for ACRYL. */\n\nimport type { Context } from '@deepseek-ai/cordis'\nimport { Service } from '@deepseek-ai/cordis'\n\nexport type AgentFidelity = 'native' | 'structured' | 'derived' | 'opaque-terminal'\nexport type AgentStatus = 'idle' | 'running' | 'waiting' | 'stopping' | 'stopped' | 'failed'\n\n/** Canonical logical worker identity in the ACRYL room. */\nexport type AcrWorkerId = string\n/** Identity for one live in-process agent, protocol connection, SDK run, or CLI process. */\nexport type AgentRuntimeId = string\n/** Adapter-scoped opaque vendor session reference. */\nexport type ProviderSessionRef = string\n\n/** Generation-scoped truthful provider capabilities. */\nexport type AgentCapability =\n | 'agent.start'\n | 'agent.stop'\n | 'agent.send'\n | 'agent.cancel'\n | 'agent.resume'\n | 'agent.snapshot'\n | 'output.structured'\n | 'output.terminal'\n | 'tool.calls'\n | 'approval.respond'\n\nexport interface AgentWorkspace {\n readonly identity: string\n readonly cwd: string\n}\n\n/** One bound worker as projected by the control service. */\nexport interface AgentSnapshot {\n readonly workerId: AcrWorkerId\n readonly runtimeId: AgentRuntimeId | null\n readonly providerId: string\n readonly providerSessionRef: ProviderSessionRef | null\n readonly harnessSessionId: string | null\n readonly workspace: AgentWorkspace | null\n readonly capabilities: readonly AgentCapability[]\n readonly fidelity: AgentFidelity\n readonly status: AgentStatus\n}\n\nexport type AgentCommandKind = 'start' | 'send' | 'cancel' | 'stop' | 'resume'\n\nexport interface AgentCommand {\n readonly kind: AgentCommandKind\n readonly payload: unknown\n}\n\nexport interface CommandReceipt {\n readonly accepted: true\n readonly workerId: AcrWorkerId\n readonly runtimeId: AgentRuntimeId\n readonly kind: AgentCommandKind\n readonly result: unknown\n}\n\nexport interface AttachAgentRequest {\n readonly workerId: AcrWorkerId\n readonly providerId: string\n readonly workspace: AgentWorkspace | null\n readonly capabilities: readonly AgentCapability[]\n readonly fidelity: AgentFidelity\n readonly providerSessionRef?: ProviderSessionRef\n readonly harnessSessionId?: string\n}\n\nexport interface AgentScope {\n readonly workerId?: AcrWorkerId\n readonly providerId?: string\n}\n\n/** The live runtime a transport opened for one worker: what makes a bound worker dispatchable. */\nexport interface AgentTransportRuntime {\n readonly runtimeId: AgentRuntimeId\n readonly providerSessionRef?: ProviderSessionRef\n}\n\n/** Transport seam a provider delegates to; vendor SDKs, protocols and CLIs plug in here. */\nexport interface AgentTransport {\n /**\n * Bring up the vendor runtime for one worker (a process, a connection) and name it. Without `open` a provider binds no runtime, and\n * every dispatch is refused until something else does.\n */\n open?(request: AttachAgentRequest, signal?: AbortSignal): Promise<AgentTransportRuntime>\n execute(binding: AgentSnapshot, command: AgentCommand, signal?: AbortSignal): Promise<unknown>\n /** Release every runtime this transport opened (the provider's owner is unloading). */\n dispose?(): Promise<void>\n}\n\n/** One registered adapter. Registration is a reversible effect. */\nexport interface AgentProvider {\n readonly id: string\n readonly fidelity: AgentFidelity\n readonly capabilities: readonly AgentCapability[]\n attach(request: AttachAgentRequest): Promise<AgentSnapshot>\n execute(binding: AgentSnapshot, command: AgentCommand, signal?: AbortSignal): Promise<unknown>\n}\n\nexport interface AcrAgentControl {\n registerProvider(owner: Context, provider: AgentProvider): void\n attach(request: AttachAgentRequest): Promise<AgentSnapshot>\n dispatch(workerId: AcrWorkerId, command: AgentCommand, signal?: AbortSignal): Promise<CommandReceipt>\n snapshot(scope?: AgentScope): Promise<readonly AgentSnapshot[]>\n}\n\nexport type AcrAgentControlErrorCode =\n | 'unknown-provider'\n | 'unknown-worker'\n | 'capability-rejected'\n | 'runtime-collision'\n | 'session-collision'\n | 'cancelled'\n | 'transport-unavailable'\n | 'worker-busy'\n\nexport class AcrAgentControlError extends Error {\n constructor(readonly code: AcrAgentControlErrorCode, message: string) {\n super(message)\n this.name = 'AcrAgentControlError'\n }\n}\n\ndeclare module '@deepseek-ai/cordis' {\n interface Context {\n acrAgentControl: AcrAgentControl\n }\n}\n\nconst COMMAND_CAPABILITY: Readonly<Record<AgentCommandKind, AgentCapability>> = {\n start: 'agent.start',\n send: 'agent.send',\n cancel: 'agent.cancel',\n stop: 'agent.stop',\n resume: 'agent.resume',\n}\n\nexport class AcrAgentControlService extends Service implements AcrAgentControl {\n private readonly providers = new Map<string, AgentProvider>()\n private readonly bindings = new Map<AcrWorkerId, AgentSnapshot>()\n\n constructor(ctx: Context) {\n super(ctx, 'acrAgentControl')\n }\n\n registerProvider(owner: Context, provider: AgentProvider): void {\n if (provider.id.trim() === '') throw new Error('agent provider id must not be empty')\n owner.effect(() => {\n if (this.providers.has(provider.id)) {\n throw new Error(`duplicate agent provider id: ${provider.id}`)\n }\n this.providers.set(provider.id, provider)\n return () => {\n if (this.providers.get(provider.id) === provider) this.providers.delete(provider.id)\n }\n }, `acryl-control: agent provider ${provider.id}`)\n }\n\n async attach(request: AttachAgentRequest): Promise<AgentSnapshot> {\n const provider = this.providers.get(request.providerId)\n if (provider === undefined) {\n throw new AcrAgentControlError('unknown-provider', `Unknown agent provider ${request.providerId}.`)\n }\n const declared = new Set(provider.capabilities)\n for (const capability of request.capabilities) {\n if (!declared.has(capability)) {\n throw new AcrAgentControlError(\n 'capability-rejected',\n `Provider ${request.providerId} does not declare capability ${capability}.`,\n )\n }\n }\n const binding = await provider.attach(request)\n for (const existing of this.bindings.values()) {\n if (binding.runtimeId !== null && binding.runtimeId === existing.runtimeId) {\n throw new AcrAgentControlError('runtime-collision', `Runtime ${binding.runtimeId} is already bound.`)\n }\n if (\n binding.providerSessionRef !== null\n && binding.providerSessionRef === existing.providerSessionRef\n && binding.providerId !== existing.providerId\n ) {\n throw new AcrAgentControlError(\n 'session-collision',\n `Provider session ${binding.providerSessionRef} is claimed by another provider.`,\n )\n }\n }\n this.bindings.set(binding.workerId, binding)\n return binding\n }\n\n async dispatch(\n workerId: AcrWorkerId,\n command: AgentCommand,\n signal?: AbortSignal,\n ): Promise<CommandReceipt> {\n const binding = this.bindings.get(workerId)\n if (binding === undefined) {\n throw new AcrAgentControlError('unknown-worker', `Unknown agent worker ${workerId}.`)\n }\n const required = COMMAND_CAPABILITY[command.kind]\n if (!binding.capabilities.includes(required)) {\n throw new AcrAgentControlError(\n 'capability-rejected',\n `Worker ${workerId} does not declare capability ${required}.`,\n )\n }\n if (signal?.aborted) {\n throw new AcrAgentControlError('cancelled', `Command ${command.kind} was cancelled.`)\n }\n const provider = this.providers.get(binding.providerId)\n if (provider === undefined) {\n throw new AcrAgentControlError('unknown-provider', `Unknown agent provider ${binding.providerId}.`)\n }\n if (binding.runtimeId === null) {\n throw new AcrAgentControlError('unknown-worker', `Worker ${workerId} has no live runtime.`)\n }\n const result = await provider.execute(binding, command, signal)\n return Object.freeze({\n accepted: true,\n workerId,\n runtimeId: binding.runtimeId,\n kind: command.kind,\n result,\n })\n }\n\n async snapshot(scope?: AgentScope): Promise<readonly AgentSnapshot[]> {\n const bindings = [...this.bindings.values()]\n if (scope === undefined) return Object.freeze(bindings)\n return Object.freeze(bindings.filter((binding) => {\n if (scope.workerId !== undefined && binding.workerId !== scope.workerId) return false\n if (scope.providerId !== undefined && binding.providerId !== scope.providerId) return false\n return true\n }))\n }\n}\n\nexport default AcrAgentControlService\n","/**\n * Claude Code over its own `stream-json` protocol: one long-lived `claude -p` process per worker, one JSON object per line each way.\n * This is the structured transport behind the `claude` provider (fidelity `structured`): a user message in, assistant text and a final\n * `result` out, a control request to interrupt, stdin closed to stop. No vendor SDK and no other ACRYL dependency; the process is the\n * runtime, so the transport owns its whole life (`dispose` ends every child).\n *\n * Observed on Claude Code 2.1.288: the process stays silent until the first user message (the `system` `init` event, which carries\n * the session id, arrives with the first turn, not at spawn); hook and rate-limit events are interleaved and ignored here.\n */\n\nimport { spawn as nodeSpawn, type ChildProcessWithoutNullStreams, type SpawnOptionsWithoutStdio } from 'node:child_process'\nimport { AcrAgentControlError, type AgentCommand, type AgentSnapshot, type AgentTransport, type AgentTransportRuntime, type AttachAgentRequest } from '../agent-control.ts'\n\nexport interface ClaudeStreamTransportOptions {\n /** The executable. Defaults to `claude` on the PATH. */\n readonly command?: string\n /**\n * Extra arguments for every process, after the protocol flags. Defaults to read-only work: Claude Code asks for approval before it edits or\n * runs anything, and a headless process cannot answer, so such calls are refused. Pass `--permission-mode` or `--allowedTools` to widen it.\n * A function is asked at each attach, for arguments that only exist once the host is up (an MCP config naming this host's own address).\n */\n readonly args?: readonly string[] | (() => readonly string[] | Promise<readonly string[]>)\n readonly env?: NodeJS.ProcessEnv\n /** Spawn seam for tests. */\n readonly spawn?: (command: string, args: readonly string[], options: SpawnOptionsWithoutStdio) => ChildProcessWithoutNullStreams\n /** How long a stopped process may take to exit before it is killed. Default 3000. */\n readonly stopGraceMs?: number\n /** How long an interrupted turn may take to end before the process is killed. Default 5000. */\n readonly interruptGraceMs?: number\n}\n\nexport interface ClaudeTurnResult {\n /** The final answer, as Claude Code reports it. */\n readonly text: string\n readonly isError: boolean\n readonly sessionId: string | null\n readonly stopReason: string | null\n /** Every assistant text block of the turn, in order. */\n readonly assistantText: readonly string[]\n}\n\ninterface Turn {\n readonly assistantText: string[]\n readonly resolve: (result: ClaudeTurnResult) => void\n readonly reject: (cause: Error) => void\n}\n\ninterface Run {\n readonly child: ChildProcessWithoutNullStreams\n buffer: string\n sessionId: string | null\n turn: Turn | null\n closed: boolean\n readonly exited: Promise<void>\n}\n\nconst PROTOCOL_ARGS = ['-p', '--input-format', 'stream-json', '--output-format', 'stream-json', '--verbose'] as const\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nexport class ClaudeStreamTransport implements AgentTransport {\n private readonly runs = new Map<string, Run>()\n private requestCounter = 0\n\n constructor(private readonly options: ClaudeStreamTransportOptions = {}) {}\n\n async open(request: AttachAgentRequest): Promise<AgentTransportRuntime> {\n const args = [\n ...PROTOCOL_ARGS,\n ...(typeof this.options.args === 'function' ? await this.options.args() : this.options.args ?? []),\n ...(request.providerSessionRef === undefined ? [] : ['--resume', request.providerSessionRef]),\n ]\n const spawnProcess = this.options.spawn ?? nodeSpawn\n let child: ChildProcessWithoutNullStreams\n try {\n child = spawnProcess(this.options.command ?? 'claude', args, {\n ...(request.workspace === null ? {} : { cwd: request.workspace.cwd }),\n ...(this.options.env === undefined ? {} : { env: this.options.env }),\n stdio: 'pipe',\n })\n } catch (cause) {\n throw new AcrAgentControlError('transport-unavailable', `Could not start Claude Code: ${cause instanceof Error ? cause.message : String(cause)}`)\n }\n // A missing executable is reported on the 'error' event, not thrown by spawn.\n const started = await new Promise<Error | undefined>((resolve) => {\n child.once('error', resolve)\n child.once('spawn', () => { resolve(undefined) })\n })\n if (started !== undefined) throw new AcrAgentControlError('transport-unavailable', `Could not start Claude Code: ${started.message}`)\n\n const runtimeId = `claude-${String(child.pid)}`\n const run: Run = {\n child,\n buffer: '',\n sessionId: request.providerSessionRef ?? null,\n turn: null,\n closed: false,\n exited: new Promise<void>((resolve) => { child.once('close', () => { resolve() }) }),\n }\n child.stdout.setEncoding('utf8')\n child.stdout.on('data', (chunk: string) => { this.onData(run, chunk) })\n child.stderr.resume()\n child.stdin.on('error', () => {})\n child.once('error', (cause) => { this.fail(run, cause) })\n child.once('close', (code, signal) => {\n run.closed = true\n this.runs.delete(runtimeId)\n this.fail(run, new AcrAgentControlError('transport-unavailable', `Claude Code exited (${signal ?? String(code)}) before the turn ended.`))\n })\n this.runs.set(runtimeId, run)\n return { runtimeId, ...(request.providerSessionRef === undefined ? {} : { providerSessionRef: request.providerSessionRef }) }\n }\n\n async execute(binding: AgentSnapshot, command: AgentCommand, signal?: AbortSignal): Promise<unknown> {\n const run = binding.runtimeId === null ? undefined : this.runs.get(binding.runtimeId)\n if (run === undefined || run.closed) throw new AcrAgentControlError('transport-unavailable', `Claude Code runtime ${String(binding.runtimeId)} is not running.`)\n switch (command.kind) {\n case 'start':\n // The process is already up (`open`); starting names what is running.\n return { runtimeId: binding.runtimeId, sessionId: run.sessionId }\n case 'send':\n return this.send(run, command.payload, signal)\n case 'cancel':\n this.interrupt(run)\n return { interrupted: run.turn !== null }\n case 'stop':\n await this.stop(run)\n return { stopped: true }\n case 'resume':\n throw new AcrAgentControlError('capability-rejected', 'Resume is done by attaching with the session id (providerSessionRef).')\n }\n }\n\n async dispose(): Promise<void> {\n await Promise.all([...this.runs.values()].map(run => this.stop(run)))\n }\n\n private send(run: Run, payload: unknown, signal?: AbortSignal): Promise<ClaudeTurnResult> {\n const text = typeof payload === 'string' ? payload : isRecord(payload) && typeof payload.text === 'string' ? payload.text : undefined\n if (text === undefined || text === '') throw new AcrAgentControlError('capability-rejected', 'A send needs a text: a string or { text }.')\n if (run.turn !== null) throw new AcrAgentControlError('worker-busy', 'Claude Code is still answering the previous message.')\n return new Promise<ClaudeTurnResult>((resolve, reject) => {\n const onAbort = (): void => { this.interrupt(run) }\n const turn: Turn = {\n assistantText: [],\n resolve: (result) => { signal?.removeEventListener('abort', onAbort); resolve(result) },\n reject: (cause) => { signal?.removeEventListener('abort', onAbort); reject(cause) },\n }\n run.turn = turn\n if (signal !== undefined) {\n if (signal.aborted) { run.turn = null; reject(new AcrAgentControlError('cancelled', 'The send was cancelled.')); return }\n signal.addEventListener('abort', onAbort, { once: true })\n }\n this.write(run, { type: 'user', message: { role: 'user', content: [{ type: 'text', text }] } })\n }).then((result) => {\n if (signal?.aborted === true) throw new AcrAgentControlError('cancelled', 'The send was cancelled.')\n return result\n })\n }\n\n private interrupt(run: Run): void {\n if (run.turn === null || run.closed) return\n this.write(run, { type: 'control_request', request_id: `acryl-${String(++this.requestCounter)}`, request: { subtype: 'interrupt' } })\n // A turn that does not end after an interrupt is not coming back: kill the process rather than hang the caller.\n const turn = run.turn\n setTimeout(() => {\n if (run.turn === turn && !run.closed) run.child.kill('SIGKILL')\n }, this.options.interruptGraceMs ?? 5000).unref()\n }\n\n private async stop(run: Run): Promise<void> {\n if (run.closed) return\n run.child.stdin.end()\n const timer = setTimeout(() => { if (!run.closed) run.child.kill('SIGTERM') }, this.options.stopGraceMs ?? 3000)\n timer.unref()\n await run.exited\n clearTimeout(timer)\n }\n\n private write(run: Run, message: Record<string, unknown>): void {\n run.child.stdin.write(`${JSON.stringify(message)}\\n`)\n }\n\n private onData(run: Run, chunk: string): void {\n run.buffer += chunk\n let newline = run.buffer.indexOf('\\n')\n while (newline >= 0) {\n const line = run.buffer.slice(0, newline).trim()\n run.buffer = run.buffer.slice(newline + 1)\n if (line !== '') this.onLine(run, line)\n newline = run.buffer.indexOf('\\n')\n }\n }\n\n private onLine(run: Run, line: string): void {\n let event: unknown\n try { event = JSON.parse(line) } catch { return } // diagnostics other than protocol lines are not events\n if (!isRecord(event)) return\n if (typeof event.session_id === 'string') run.sessionId = event.session_id\n const turn = run.turn\n if (turn === null) return\n if (event.type === 'assistant' && isRecord(event.message) && Array.isArray(event.message.content)) {\n for (const block of event.message.content) {\n if (isRecord(block) && block.type === 'text' && typeof block.text === 'string') turn.assistantText.push(block.text)\n }\n } else if (event.type === 'result') {\n run.turn = null\n turn.resolve({\n text: typeof event.result === 'string' ? event.result : turn.assistantText.join('\\n'),\n isError: event.is_error === true,\n sessionId: run.sessionId,\n stopReason: typeof event.stop_reason === 'string' ? event.stop_reason : null,\n assistantText: Object.freeze([...turn.assistantText]),\n })\n }\n }\n\n private fail(run: Run, cause: Error): void {\n const turn = run.turn\n if (turn === null) return\n run.turn = null\n turn.reject(cause)\n }\n}\n\n/** Convenience for the common case: the transport with its options. */\nexport function createClaudeStreamTransport(options: ClaudeStreamTransportOptions = {}): ClaudeStreamTransport {\n return new ClaudeStreamTransport(options)\n}\n","/** Truthful generation-scoped capability declarations per provider kind. */\n\nimport type { AgentCapability, AgentFidelity } from '../agent-control.ts'\n\nexport type AgentProviderKind = 'dsh-native' | 'codex' | 'claude' | 'acp'\n\nexport interface ProviderCapabilityProfile {\n readonly kind: AgentProviderKind\n readonly fidelity: AgentFidelity\n readonly capabilities: readonly AgentCapability[]\n}\n\nfunction capabilities(...items: AgentCapability[]): readonly AgentCapability[] {\n return Object.freeze(items)\n}\n\n/**\n * Declared capability sets. A provider must only claim what its transport can\n * truthfully support; unsupported commands are rejected before dispatch.\n */\nexport const PROVIDER_CAPABILITIES: Readonly<Record<AgentProviderKind, ProviderCapabilityProfile>> = {\n 'dsh-native': Object.freeze({\n kind: 'dsh-native',\n fidelity: 'native',\n capabilities: capabilities(\n 'agent.start',\n 'agent.stop',\n 'agent.send',\n 'agent.cancel',\n 'agent.resume',\n 'agent.snapshot',\n 'output.structured',\n 'tool.calls',\n 'approval.respond',\n ),\n }),\n codex: Object.freeze({\n kind: 'codex',\n fidelity: 'structured',\n capabilities: capabilities(\n 'agent.start',\n 'agent.stop',\n 'agent.send',\n 'agent.cancel',\n 'agent.snapshot',\n 'output.structured',\n 'tool.calls',\n ),\n }),\n claude: Object.freeze({\n kind: 'claude',\n fidelity: 'structured',\n capabilities: capabilities(\n 'agent.start',\n 'agent.stop',\n 'agent.send',\n 'agent.cancel',\n 'agent.snapshot',\n 'output.structured',\n 'tool.calls',\n ),\n }),\n acp: Object.freeze({\n kind: 'acp',\n fidelity: 'structured',\n capabilities: capabilities(\n 'agent.start',\n 'agent.stop',\n 'agent.send',\n 'agent.cancel',\n 'agent.resume',\n 'agent.snapshot',\n 'output.structured',\n 'tool.calls',\n ),\n }),\n}\n","/** Shared provider plugin factory: registers a capability-declaring adapter. */\n\nimport type { Context } from '@deepseek-ai/cordis'\nimport {\n AcrAgentControlError,\n type AgentCommand,\n type AgentProvider,\n type AgentSnapshot,\n type AgentTransport,\n type AgentTransportRuntime,\n type AttachAgentRequest,\n} from '../agent-control.ts'\nimport { PROVIDER_CAPABILITIES, type AgentProviderKind } from './capabilities.ts'\n\nexport interface ProviderPluginOptions {\n readonly kind: AgentProviderKind\n readonly transport?: AgentTransport\n}\n\nfunction snapshotOf(request: AttachAgentRequest, runtime?: AgentTransportRuntime): AgentSnapshot {\n return Object.freeze({\n workerId: request.workerId,\n runtimeId: runtime?.runtimeId ?? null,\n providerId: request.providerId,\n providerSessionRef: runtime?.providerSessionRef ?? request.providerSessionRef ?? null,\n harnessSessionId: request.harnessSessionId ?? null,\n workspace: request.workspace,\n capabilities: Object.freeze([...request.capabilities]),\n fidelity: request.fidelity,\n status: 'idle',\n })\n}\n\n/**\n * Create a provider plugin for one vendor. The transport is the Phase 8 seam;\n * until one is supplied, `execute` rejects honestly with `transport-unavailable`.\n */\nexport function createProviderPlugin(options: ProviderPluginOptions) {\n const profile = PROVIDER_CAPABILITIES[options.kind]\n return {\n name: `acryl-agent-${profile.kind}`,\n inject: ['acrAgentControl'] as const,\n apply(ctx: Context) {\n const provider: AgentProvider = {\n id: profile.kind,\n fidelity: profile.fidelity,\n capabilities: profile.capabilities,\n async attach(request: AttachAgentRequest): Promise<AgentSnapshot> {\n // A transport that can open its runtime does so here, so the bound worker is dispatchable; otherwise it stays unbound.\n return snapshotOf(request, await options.transport?.open?.(request))\n },\n async execute(binding: AgentSnapshot, command: AgentCommand, signal?: AbortSignal) {\n if (options.transport === undefined) {\n throw new AcrAgentControlError(\n 'transport-unavailable',\n `Provider ${profile.kind} has no transport wired.`,\n )\n }\n return options.transport.execute(binding, command, signal)\n },\n }\n // Whatever the transport opened ends with the plugin that owns it (a child process must not outlive its Fiber).\n if (options.transport?.dispose !== undefined) {\n const transport = options.transport\n ctx.effect(() => () => { void transport.dispose?.() }, `acryl-control: ${profile.kind} transport`)\n }\n ctx.acrAgentControl.registerProvider(ctx, provider)\n },\n }\n}\n","/** Harness-native agent provider (full capability profile, native fidelity). */\n\nimport type { AgentTransport } from '../agent-control.ts'\nimport { createProviderPlugin } from './factory.ts'\n\nexport function dshNativeProvider(transport?: AgentTransport) {\n return createProviderPlugin({ kind: 'dsh-native', ...(transport === undefined ? {} : { transport }) })\n}\n","/** Codex CLI provider (structured fidelity). */\n\nimport type { AgentTransport } from '../agent-control.ts'\nimport { createProviderPlugin } from './factory.ts'\n\nexport function codexProvider(transport?: AgentTransport) {\n return createProviderPlugin({ kind: 'codex', ...(transport === undefined ? {} : { transport }) })\n}\n","/** Claude provider (structured fidelity). */\n\nimport type { AgentTransport } from '../agent-control.ts'\nimport { createProviderPlugin } from './factory.ts'\n\nexport function claudeProvider(transport?: AgentTransport) {\n return createProviderPlugin({ kind: 'claude', ...(transport === undefined ? {} : { transport }) })\n}\n","/** ACP protocol provider (structured fidelity). */\n\nimport type { AgentTransport } from '../agent-control.ts'\nimport { createProviderPlugin } from './factory.ts'\n\nexport function acpProvider(transport?: AgentTransport) {\n return createProviderPlugin({ kind: 'acp', ...(transport === undefined ? {} : { transport }) })\n}\n","/** Bounded, host-neutral projection of native Cordis runtime state. */\n\nimport type { Context, EffectMeta, Fiber } from '@deepseek-ai/cordis'\n\nconst MAX_FIBERS = 2_048\nconst MAX_SERVICES = 4_096\nconst MAX_EFFECTS_PER_FIBER = 512\nconst MAX_EFFECT_DEPTH = 12\nconst MAX_LABEL_LENGTH = 512\n\nexport type ArchitecturePlane = 'host' | 'client' | 'tui'\n\nexport type ArchitectureFiberPhase =\n | 'pending'\n | 'loading'\n | 'active'\n | 'failed'\n | 'unloading'\n\nexport type ArchitectureDependencyStatus = 'resolved' | 'available' | 'missing'\n\n/** One currently owned, labeled Cordis effect and its nested ownership. */\nexport interface ArchitectureEffectView {\n readonly label: string\n readonly children: readonly ArchitectureEffectView[]\n}\n\n/** One native `inject` declaration and its current resolution state. */\nexport interface ArchitectureDependencyView {\n readonly name: string\n readonly status: ArchitectureDependencyStatus\n readonly providerFiberUid: number | null\n}\n\n/** One live Cordis Fiber. Repeated mounts remain distinct by UID. */\nexport interface ArchitectureFiberView {\n readonly uid: number\n readonly name: string\n readonly phase: ArchitectureFiberPhase\n readonly parentUid: number | null\n readonly loaderEntryId: string | null\n readonly moduleName: string | null\n readonly dependencies: readonly ArchitectureDependencyView[]\n readonly providedServices: readonly string[]\n readonly effects: readonly ArchitectureEffectView[]\n}\n\n/** One live service implementation and its owning Fiber. */\nexport interface ArchitectureServiceView {\n readonly name: string\n readonly providerFiberUid: number\n readonly providerName: string\n readonly providerPhase: ArchitectureFiberPhase\n}\n\n/** Point-in-time native graph for one independent Cordis context. */\nexport interface RuntimeArchitectureSnapshot {\n readonly plane: ArchitecturePlane\n readonly fibers: readonly ArchitectureFiberView[]\n readonly services: readonly ArchitectureServiceView[]\n}\n\nconst FIBER_PHASE: Record<number, ArchitectureFiberPhase | null> = {\n 0: 'pending',\n 1: 'loading',\n 2: 'active',\n 3: 'failed',\n 4: null,\n 5: 'unloading',\n}\n\ninterface LoaderInspection {\n locate(fiber?: Fiber): string | undefined\n}\n\ninterface StoreImpl {\n readonly name: string\n readonly fiber: Fiber\n}\n\ninterface FiberEntry {\n readonly options?: { readonly name?: unknown }\n}\n\nfunction phaseOf(fiber: Fiber): ArchitectureFiberPhase {\n return FIBER_PHASE[fiber.state as number] ?? 'pending'\n}\n\nfunction effectView(\n meta: EffectMeta,\n depth: number,\n budget: { remaining: number },\n): ArchitectureEffectView {\n if (depth > MAX_EFFECT_DEPTH) throw new Error('Cordis effect tree exceeds the inspection depth limit')\n if (--budget.remaining < 0) throw new Error('Cordis Fiber exceeds the inspection effect limit')\n if (typeof meta.label !== 'string' || meta.label.length > MAX_LABEL_LENGTH) {\n throw new Error('Cordis effect label exceeds the inspection limit')\n }\n return Object.freeze({\n label: meta.label,\n children: Object.freeze(meta.children.map(child => effectView(child, depth + 1, budget))),\n })\n}\n\nfunction liveServices(ctx: Context): StoreImpl[] {\n const store = ctx.root.reflect.store as unknown as Record<symbol, StoreImpl | undefined>\n const services: StoreImpl[] = []\n for (const key of Object.getOwnPropertySymbols(store)) {\n const impl = store[key]\n if (impl !== undefined && impl.fiber.uid !== null) services.push(impl)\n }\n return services\n}\n\nfunction fibers(ctx: Context): Fiber[] {\n const found = new Set<Fiber>([ctx.root.fiber])\n for (const runtime of ctx.root.registry.values()) {\n for (const fiber of runtime.fibers) {\n if (fiber.uid !== null) found.add(fiber)\n }\n }\n const result = [...found].sort((left, right) => (left.uid ?? 0) - (right.uid ?? 0))\n if (result.length > MAX_FIBERS) throw new Error('Cordis context exceeds the inspection Fiber limit')\n return result\n}\n\nfunction dependencyView(fiber: Fiber, name: string): ArchitectureDependencyView {\n const resolved = fiber.store?.[name]\n if (resolved !== undefined && resolved.fiber.uid !== null) {\n return Object.freeze({\n name,\n status: 'resolved' as const,\n providerFiberUid: resolved.fiber.uid,\n })\n }\n const status: ArchitectureDependencyStatus = fiber.ctx.get(name) === undefined ? 'missing' : 'available'\n return Object.freeze({ name, status, providerFiberUid: null })\n}\n\nfunction moduleNameOf(fiber: Fiber): string | null {\n const entry = (fiber as Fiber & { entry?: FiberEntry }).entry\n const name = entry?.options?.name\n return typeof name === 'string' && name.length > 0 && name.length <= MAX_LABEL_LENGTH ? name : null\n}\n\n/** Inspect one Cordis context without caching or inventing cross-plane identity. */\nexport function projectRuntimeArchitecture(\n ctx: Context,\n plane: ArchitecturePlane,\n): RuntimeArchitectureSnapshot {\n const allFibers = fibers(ctx)\n const services = liveServices(ctx)\n if (services.length > MAX_SERVICES) throw new Error('Cordis context exceeds the inspection service limit')\n\n const servicesByFiber = new Map<Fiber, string[]>()\n for (const impl of services) {\n const names = servicesByFiber.get(impl.fiber) ?? []\n names.push(impl.name)\n servicesByFiber.set(impl.fiber, names)\n }\n\n const loader = ctx.get('loader') as LoaderInspection | undefined\n const fiberViews: ArchitectureFiberView[] = allFibers.map((fiber) => {\n const parent = fiber.parent.fiber\n const budget = { remaining: MAX_EFFECTS_PER_FIBER }\n return Object.freeze({\n uid: fiber.uid ?? 0,\n name: fiber.name,\n phase: phaseOf(fiber),\n parentUid: parent === fiber ? null : parent.uid,\n loaderEntryId: loader?.locate(fiber) ?? null,\n moduleName: moduleNameOf(fiber),\n dependencies: Object.freeze(\n Object.keys(fiber.inject).sort().map(name => dependencyView(fiber, name)),\n ),\n providedServices: Object.freeze([...(servicesByFiber.get(fiber) ?? [])].sort()),\n effects: Object.freeze(fiber.getEffects().map(meta => effectView(meta, 0, budget))),\n })\n })\n\n const serviceViews: ArchitectureServiceView[] = services\n .map(impl => Object.freeze({\n name: impl.name,\n providerFiberUid: impl.fiber.uid ?? 0,\n providerName: impl.fiber.name,\n providerPhase: phaseOf(impl.fiber),\n }))\n .sort((left, right) => left.name.localeCompare(right.name)\n || left.providerFiberUid - right.providerFiberUid)\n\n return Object.freeze({\n plane,\n fibers: Object.freeze(fiberViews),\n services: Object.freeze(serviceViews),\n })\n}\n","import { type Context, Service } from '@deepseek-ai/cordis'\nimport {\n projectRuntimeArchitecture,\n type ArchitecturePlane,\n type RuntimeArchitectureSnapshot,\n} from './projection.ts'\n\nexport interface AcrRuntimeArchitecture {\n snapshot(plane: ArchitecturePlane): RuntimeArchitectureSnapshot\n}\n\ndeclare module '@deepseek-ai/cordis' {\n interface Context {\n acrRuntimeArchitecture: AcrRuntimeArchitecture\n }\n}\n\nexport class AcrRuntimeArchitectureService extends Service implements AcrRuntimeArchitecture {\n constructor(ctx: Context) {\n super(ctx, 'acrRuntimeArchitecture')\n }\n\n snapshot(plane: ArchitecturePlane): RuntimeArchitectureSnapshot {\n return projectRuntimeArchitecture(this.ctx, plane)\n }\n}\n\nexport default AcrRuntimeArchitectureService\n","export type AcrylSessionAttachment = 'owner' | 'attached'\nexport type AcrylSessionAgentStatus = 'idle' | 'running' | 'waiting' | 'failed'\nexport type AcrylTranscriptAuthor = 'user' | 'assistant'\nexport type AcrylToolStatus = 'pending' | 'running' | 'succeeded' | 'failed'\n\nexport interface AcrylTranscriptItem {\n readonly id: string\n readonly author: AcrylTranscriptAuthor\n readonly text: string\n}\n\nexport interface AcrylToolProjection {\n readonly callId: string\n readonly name: string\n readonly status: AcrylToolStatus\n}\n\nexport interface AcrylSessionSnapshot {\n readonly profile: string\n readonly generationId: string\n readonly attachment: AcrylSessionAttachment\n readonly sessionId: string\n readonly agentStatus: AcrylSessionAgentStatus\n readonly transcript: readonly AcrylTranscriptItem[]\n readonly tools: readonly AcrylToolProjection[]\n}\n\nexport interface AcrylSessionSubscription {\n dispose(): Promise<void>\n /** Resolves with the terminal endpoint-subscription failure, if one occurs. */\n whenError(): Promise<Error>\n}\n\nexport interface AcrylSessionClient {\n snapshot(sessionId: string): Promise<AcrylSessionSnapshot>\n subscribe(\n sessionId: string,\n listener: (snapshot: AcrylSessionSnapshot) => void,\n onError?: (error: Error) => void,\n ): Promise<AcrylSessionSubscription>\n submitPrompt(input: {\n readonly sessionId: string\n readonly text: string\n readonly clientCommandId: string\n }): Promise<void>\n cancel(input: { readonly sessionId: string }): Promise<void>\n}\n\nfunction record(value: unknown): Record<string, unknown> | undefined {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? value as Record<string, unknown>\n : undefined\n}\n\nfunction nonEmpty(value: unknown, message: string): string {\n if (typeof value !== 'string' || value.trim() === '') throw new Error(message)\n return value\n}\n\nfunction oneOf<T extends string>(\n value: unknown,\n values: readonly T[],\n message: string,\n): T {\n if (typeof value !== 'string' || !values.includes(value as T)) throw new Error(message)\n return value as T\n}\n\nfunction parseTranscript(value: unknown): readonly AcrylTranscriptItem[] {\n if (!Array.isArray(value)) throw new Error('invalid ACRYL transcript')\n return Object.freeze(value.map((item) => {\n const source = record(item)\n if (source === undefined) throw new Error('invalid ACRYL transcript item')\n return Object.freeze({\n id: nonEmpty(source.id, 'invalid ACRYL transcript id'),\n author: oneOf(source.author, ['user', 'assistant'], 'invalid ACRYL transcript author'),\n text: nonEmpty(source.text, 'invalid ACRYL transcript text'),\n })\n }))\n}\n\nfunction parseTools(value: unknown): readonly AcrylToolProjection[] {\n if (!Array.isArray(value)) throw new Error('invalid ACRYL tool projections')\n return Object.freeze(value.map((item) => {\n const source = record(item)\n if (source === undefined) throw new Error('invalid ACRYL tool projection')\n return Object.freeze({\n callId: nonEmpty(source.callId, 'invalid ACRYL tool call id'),\n name: nonEmpty(source.name, 'invalid ACRYL tool name'),\n status: oneOf(source.status, ['pending', 'running', 'succeeded', 'failed'], 'invalid ACRYL tool status'),\n })\n }))\n}\n\n/** Validate an untrusted control-plane session projection at the boundary. */\nexport function parseAcrylSessionSnapshot(value: unknown): AcrylSessionSnapshot {\n const source = record(value)\n if (source === undefined) throw new Error('invalid ACRYL session snapshot')\n return Object.freeze({\n profile: nonEmpty(source.profile, 'invalid ACRYL profile'),\n generationId: nonEmpty(source.generationId, 'invalid ACRYL generation id'),\n attachment: oneOf(source.attachment, ['owner', 'attached'], 'invalid ACRYL attachment mode'),\n sessionId: nonEmpty(source.sessionId, 'invalid ACRYL session id'),\n agentStatus: oneOf(source.agentStatus, ['idle', 'running', 'waiting', 'failed'], 'invalid ACRYL agent status'),\n transcript: parseTranscript(source.transcript),\n tools: parseTools(source.tools),\n })\n}\n","/**\n * `CredentialProjection`: the one join of `ctx.llm` + `ctx.settings` +\n * `ctx.credentials` into provider rows. Replaces the surface's own\n * `computeProviderRows`/`loadAuthorizationFlows` duplicate joins (finding R1)\n * so `/login` and `/model` read the same projection instead of two\n * independently-fetched pictures of the same state.\n *\n * Framework-free: takes plain service ports (not a Cordis `Context`), so it\n * is directly unit-testable with stubs — no Cordis boot required. The\n * surface wires these ports from `host.ctx.get(...)`.\n */\nimport type { AuthMethod, CredentialModelEntry, CredentialProjectionRow } from './types.ts'\n\nexport interface CredentialProjectionConfigurableProvider {\n readonly provider: string\n readonly displayName: string\n readonly settingsNs: string\n readonly settingsPath: readonly string[]\n}\n\nexport interface CredentialProjectionLlmPort {\n listConfigurableProviders(): readonly CredentialProjectionConfigurableProvider[]\n listProviders(): readonly { readonly id: string }[]\n listModels(provider: string): Promise<readonly CredentialModelEntry[]>\n}\n\nexport interface CredentialProjectionSettingsDescriptor {\n readonly ns: string\n readonly value: unknown\n readonly user?: unknown\n readonly revision?: number\n}\n\nexport interface CredentialProjectionSettingsPort {\n describe(options: { readonly redactSecrets: boolean }): readonly CredentialProjectionSettingsDescriptor[]\n}\n\nexport interface CredentialProjectionRecord {\n readonly kind: string\n}\n\nexport interface CredentialProjectionCredentialsPort {\n describe(ref: string): Promise<{ readonly configured: boolean }>\n readRecord?(key: string): Promise<CredentialProjectionRecord | undefined>\n}\n\nexport interface CredentialProjectionServices {\n readonly llm: CredentialProjectionLlmPort\n readonly settings: CredentialProjectionSettingsPort\n readonly credentials: CredentialProjectionCredentialsPort\n}\n\n/**\n * The `apiKeyEnv` reference a provider route falls back to when its settings\n * profile names none, e.g. `my-proxy` -> `MY_PROXY_API_KEY`. One rule for every\n * surface (the terminal's `/model` and the Desktop sign-in read the same name).\n */\nexport function deriveApiKeyRef(route: string): string {\n const upper = route.toUpperCase().replace(/[^A-Z0-9]+/g, '_')\n const identifier = /^[A-Z_]/.test(upper) ? upper : `P_${upper}`\n return `${identifier}_API_KEY`\n}\n\nexport interface CredentialProjectionOptions {\n /** Derive the settings-fallback `apiKeyEnv` reference for a route with no stored profile. Defaults to {@link deriveApiKeyRef}. */\n readonly deriveApiKeyRef?: (route: string) => string\n /**\n * The scope a `/login` sign-in's own credential record lives under\n * (`dsh-llm-pi-ai`'s `credentialKey(scope, providerId)`), separate from the\n * `apiKeyEnv` reference a manually configured provider's settings profile\n * points at. Defaults to `'llm-pi-ai'`.\n */\n readonly loginRecordScope?: string\n}\n\n/** Read a nested value out of an untyped resolved/raw settings section. */\nfunction getAtPath(value: unknown, path: readonly string[]): unknown {\n let current = value\n for (const key of path) {\n if (current === null || typeof current !== 'object') return undefined\n current = (current as Record<string, unknown>)[key]\n }\n return current\n}\n\ninterface StoredProviderProfileLike {\n readonly displayName?: string\n readonly api?: string\n readonly baseURL?: string\n readonly apiKeyEnv?: string\n readonly models?: readonly CredentialModelEntry[]\n}\n\nexport interface RouteUsabilityServices {\n readonly llm: Pick<CredentialProjectionLlmPort, 'listConfigurableProviders' | 'listProviders'>\n readonly settings: CredentialProjectionSettingsPort\n readonly credentials: {\n describe(ref: string): Promise<{ readonly configured: boolean }>\n describeRecord(key: string): Promise<{ readonly configured: boolean }>\n }\n}\n\n/**\n * Whether one route can answer a request now: live in `ctx.llm` and holding a credential (the settings profile's\n * `apiKeyEnv` secret, or a sign-in's own record). The same credential rule as {@link computeCredentialProjection}, for\n * one route and without reading any secret or model list.\n */\nexport async function isRouteUsable(services: RouteUsabilityServices, provider: string, options: CredentialProjectionOptions = {}): Promise<boolean> {\n if (!services.llm.listProviders().some(entry => entry.id === provider)) return false\n const entry = services.llm.listConfigurableProviders().find(candidate => candidate.provider === provider)\n if (entry === undefined) return true\n const descriptor = services.settings.describe({ redactSecrets: true }).find(candidate => candidate.ns === entry.settingsNs)\n const value = (descriptor === undefined ? undefined : getAtPath(descriptor.value, entry.settingsPath)) as StoredProviderProfileLike | undefined\n const apiKeyRef = value?.apiKeyEnv ?? (options.deriveApiKeyRef ?? deriveApiKeyRef)(provider)\n if ((await services.credentials.describe(apiKeyRef)).configured) return true\n return (await services.credentials.describeRecord(`${options.loginRecordScope ?? 'llm-pi-ai'}/${provider}`)).configured\n}\n\n/** Compute every provider route's joined credential/settings/live-registration row. */\nexport async function computeCredentialProjection(\n services: CredentialProjectionServices,\n options: CredentialProjectionOptions,\n): Promise<readonly CredentialProjectionRow[]> {\n const scope = options.loginRecordScope ?? 'llm-pi-ai'\n const configurable = services.llm.listConfigurableProviders()\n const live = new Set(services.llm.listProviders().map(provider => provider.id))\n const descriptors = services.settings.describe({ redactSecrets: true })\n const byNs = new Map(descriptors.map(descriptor => [descriptor.ns, descriptor]))\n\n const rows: CredentialProjectionRow[] = []\n for (const entry of configurable) {\n const descriptor = byNs.get(entry.settingsNs)\n const value = (descriptor === undefined ? undefined : getAtPath(descriptor.value, entry.settingsPath)) as StoredProviderProfileLike | undefined\n const userValue = descriptor === undefined ? undefined : getAtPath(descriptor.user, entry.settingsPath)\n const apiKeyRef = value?.apiKeyEnv ?? (options.deriveApiKeyRef ?? deriveApiKeyRef)(entry.provider)\n const info = await services.credentials.describe(apiKeyRef)\n // A `/login` sign-in never sets `apiKeyEnv` — it writes the login scope's\n // own record instead — so `info.configured` alone reads \"no key\" for a\n // route the user just signed into via OAuth or a catalog API key. Check\n // that record too before reporting \"no credential\".\n const loginRecord = await services.credentials.readRecord?.(`${scope}/${entry.provider}`)\n // A login record's `kind` names the actual method used ('grant' is an\n // OAuth token, anything else is catalog-flow-typed key); the ref-based\n // path (`apiKeyEnv`) only ever comes from typing a key into `/model`\n // directly, so it's unambiguously 'api-key' too. A row is one or the\n // other in practice — `/login` and `/model` write to different storage.\n const authMethod: AuthMethod | undefined = loginRecord !== undefined\n ? (loginRecord.kind === 'grant' ? 'oauth' : 'api-key')\n : info.configured ? 'api-key' : undefined\n const isLive = live.has(entry.provider)\n // `value?.models` only reflects a settings-document override; omitting it\n // (the normal case) means \"use the installed catalog's own models\",\n // which only a live registration can actually answer.\n const models = isLive\n ? await services.llm.listModels(entry.provider).catch(() => value?.models ?? [])\n : value?.models ?? []\n rows.push({\n route: entry.provider,\n displayName: value?.displayName ?? entry.displayName,\n settingsNs: entry.settingsNs,\n settingsPath: entry.settingsPath,\n hasSettingsProfile: userValue !== undefined,\n hasCredential: info.configured || loginRecord !== undefined,\n isLive,\n authMethod,\n api: value?.api,\n baseURL: value?.baseURL,\n apiKeyRef,\n models,\n revision: descriptor?.revision,\n })\n }\n return rows\n}\n","/**\n * `createRouteActivation`: make a provider usable right after a sign-in.\n *\n * A sign-in only ever writes a credential (the OAuth grant or the typed API key); it never touches `ctx.settings`.\n * `dsh-llm-pi-ai` registers a route as live only once its settings section names it (an empty profile, which means \"use\n * the installed catalog's defaults\", counts), so without this a successful sign-in leaves the provider credentialed but\n * absent from `ctx.llm`'s live directory and unusable. It writes only when the route has no settings profile yet, so it\n * never replaces one the user configured (custom base URL, model overrides), and never touches the display name.\n *\n * Framework-free like the rest of this folder: plain ports, no Cordis `Context`.\n */\nimport type { CredentialProjectionConfigurableProvider, CredentialProjectionSettingsPort } from './projection.ts'\nimport type { RouteActivationPort } from '../authorization/types.ts'\n\nexport interface RouteActivationSettingsPort extends CredentialProjectionSettingsPort {\n update(ns: string, patch: Record<string, unknown>, expectedRevision?: number): Promise<unknown>\n}\n\nexport interface RouteActivationPorts {\n readonly settings: RouteActivationSettingsPort\n readonly llm: { listConfigurableProviders(): readonly CredentialProjectionConfigurableProvider[] }\n /** Wait out the settings watcher queue after a write, so the route is live when this resolves. */\n readonly settled?: () => Promise<void>\n}\n\nfunction valueAt(value: unknown, path: readonly string[]): unknown {\n let current = value\n for (const key of path) {\n if (current === null || typeof current !== 'object') return undefined\n current = (current as Record<string, unknown>)[key]\n }\n return current\n}\n\n/** Nest a provider section at its settings path, e.g. `['providers','deepseek']` gives `{ providers: { deepseek: section } }`. */\nfunction nestAt(path: readonly string[], section: Record<string, unknown>): Record<string, unknown> {\n let patch = section\n for (let index = path.length - 1; index >= 0; index--) patch = { [path[index]!]: patch }\n return patch\n}\n\nexport function createRouteActivation(ports: RouteActivationPorts): RouteActivationPort {\n return {\n async ensureRouteActivated(providerId) {\n const entry = ports.llm.listConfigurableProviders().find(candidate => candidate.provider === providerId)\n if (entry === undefined) return\n const descriptor = ports.settings.describe({ redactSecrets: true }).find(candidate => candidate.ns === entry.settingsNs)\n if (valueAt(descriptor?.user, entry.settingsPath) !== undefined) return\n await ports.settings.update(entry.settingsNs, nestAt(entry.settingsPath, {}), descriptor?.revision)\n await ports.settled?.()\n },\n }\n}\n","/**\n * `createDefaultModelAdoption`: after a sign-in, make the signed-in provider the default for new sessions when the\n * current default cannot answer (its provider has no credential or is not live).\n *\n * Without this, a first-run user who signs into Claude still gets new sessions on the composition's default (DeepSeek),\n * and the first message fails. A default whose provider works is never replaced: the user's own choice wins.\n *\n * Framework-free like the rest of this folder: plain ports, no Cordis `Context`.\n */\nimport type { DefaultModelAdoptionPort } from '../authorization/types.ts'\n\nexport interface DefaultModelSelection {\n readonly provider: string\n readonly model: string\n}\n\nexport interface DefaultModelAdoptionPorts {\n /** `ctx.agentDefaultModel` (`dsh-agent-default-model`). */\n readonly defaultModel: {\n currentSelection(): DefaultModelSelection\n saveSelection(next: DefaultModelSelection): Promise<void>\n }\n /** Whether a provider route can answer a request now: live in `ctx.llm` and holding a credential. */\n readonly isUsable: (provider: string) => Promise<boolean>\n /** The route's models in adapter order (`ctx.llm.listModels`). */\n readonly listModels: (provider: string) => Promise<readonly { readonly id: string }[]>\n}\n\n/**\n * The model a new session starts on for a provider ACRYL features on its sign-in screen, most preferred first. The\n * installed catalog lists models alphabetically, so its first entry is no recommendation; a provider absent here (or\n * whose preferred ids a catalog update removed) starts on that first entry instead.\n */\nexport const STARTING_MODELS: Readonly<Record<string, readonly string[]>> = {\n anthropic: ['claude-sonnet-5-5', 'claude-sonnet-5', 'claude-sonnet-4-6'],\n openai: ['gpt-5.5', 'gpt-5.4'],\n 'openai-codex': ['gpt-5.5'],\n deepseek: ['deepseek-v4-pro', 'deepseek-flash'],\n}\n\n/** The model to start on from a route's catalog, or `undefined` when the route lists none. */\nexport function startingModel(provider: string, models: readonly { readonly id: string }[]): string | undefined {\n const offered = new Set(models.map(model => model.id))\n return (STARTING_MODELS[provider] ?? []).find(id => offered.has(id)) ?? models[0]?.id\n}\n\nexport function createDefaultModelAdoption(ports: DefaultModelAdoptionPorts): DefaultModelAdoptionPort {\n return {\n async adoptIfDefaultUnusable(provider) {\n const current = ports.defaultModel.currentSelection()\n if (current.provider === provider) return\n if (await ports.isUsable(current.provider)) return\n const model = startingModel(provider, await ports.listModels(provider))\n if (model === undefined) return\n await ports.defaultModel.saveSelection({ provider, model })\n },\n }\n}\n","/** Typed authorization use-case contract: `/login`'s `beginAuthorization` action. */\n\n/** A question the running flow needs answered before it can continue (opaque pass-through). */\nexport interface AuthorizationInteraction {\n notify(notice: { readonly message: string; readonly url?: string; readonly code?: string }): void\n prompt(prompt: {\n readonly kind: 'text' | 'secret' | 'select'\n readonly message: string\n readonly options?: readonly { readonly id: string; readonly label: string; readonly description?: string }[]\n readonly placeholder?: string\n readonly signal?: AbortSignal\n }): Promise<string>\n}\n\nexport interface AuthorizationBeginRequest {\n /** The credential record key this flow writes (`<scope>/<id>`). */\n readonly key: string\n readonly method: string | undefined\n readonly interaction: AuthorizationInteraction\n /** Withdraws the attempt (a Cancel button on a surface that is not the one holding the flow). */\n readonly signal?: AbortSignal\n}\n\nexport interface AuthorizationOutcome {\n readonly status: string\n readonly [extra: string]: unknown\n}\n\n/** The underlying pi-ai (or equivalent) authorization flow runner. */\nexport interface AuthorizationPort {\n begin(request: AuthorizationBeginRequest): Promise<AuthorizationOutcome>\n}\n\n/**\n * Make a route usable from `/model` after a successful sign-in: `dsh-llm-pi-ai`\n * only registers a route as live once its settings section names it (even an\n * empty profile — \"use the installed catalog's defaults\" — counts), so a\n * signed-in-but-never-configured route stays credentialed but absent from\n * `ctx.llm`'s live directory otherwise. A no-op when the route already has a\n * settings profile, so it never clobbers one the user already configured.\n */\nexport interface RouteActivationPort {\n ensureRouteActivated(providerId: string, method: string | undefined): Promise<void>\n}\n\n/**\n * Point new sessions at a just-signed-in provider when the current default\n * cannot answer, so a first sign-in with anything but the composition's default\n * provider does not leave the first message failing. A no-op when the current\n * default works.\n */\nexport interface DefaultModelAdoptionPort {\n adoptIfDefaultUnusable(providerId: string): Promise<void>\n}\n\nexport type CredentialChangedListener = (key: string) => void\n\n/** The service name of {@link AccountSignInPort}. */\nexport const ACCOUNT_SIGN_IN_SERVICE = 'acrylAccountSignIn'\n\n/**\n * The key DeepSeek's account flow registers on `ctx.authorization` (`dsh-deepseek-account-platform`). It runs only once\n * DeepSeek's account service has opened an attempt, so a surface never starts it through `begin`.\n */\nexport const DEEPSEEK_ACCOUNT_FLOW_KEY = 'deepseek-account-platform/default'\n\nexport type AccountSignInOutcome =\n | { readonly status: 'authorized' }\n | { readonly status: 'cancelled' }\n | { readonly status: 'failed', readonly error: string }\n\n/**\n * `acrylAccountSignIn`: DeepSeek account sign-in on a surface without a web server of its own (the terminal), provided by\n * `acryl-sign-in/account-callback`. DeepSeek's account flow is registered on `ctx.authorization` as `key`, but it can only\n * be started here; a surface lists it under that key and signs in through this port instead of `begin`.\n */\nexport interface AccountSignInPort {\n /** The authorization flow key the sign-in writes ({@link DEEPSEEK_ACCOUNT_FLOW_KEY}). */\n readonly key: string\n /** The model route a successful sign-in makes usable (`deepseek-account`). */\n readonly route: string\n /** Start a sign-in and settle when it ends; `notify` receives the page to open in a browser. Aborting cancels it. */\n signIn(request: {\n readonly locale?: string\n readonly signal?: AbortSignal\n notify(url: string): void\n }): Promise<AccountSignInOutcome>\n}\n","/**\n * `AuthorizationService`: the `beginAuthorization` use-case, owned outside\n * the terminal surface (finding R1). Forwards to the underlying\n * `AuthorizationPort`, activates the route on success (no display-name\n * encoding — the `-oauth` suffix hack is deleted, not moved; see finding R2),\n * and emits `credential.changed` so subscribers can invalidate a targeted\n * projection instead of a shotgun dual reload (finding R4).\n *\n * Framework-free: every dependency is a plain port, so this is directly\n * unit-testable with stubs — no Cordis boot required.\n */\nimport type {\n AuthorizationBeginRequest,\n AuthorizationOutcome,\n AuthorizationPort,\n CredentialChangedListener,\n DefaultModelAdoptionPort,\n RouteActivationPort,\n} from './types.ts'\n\nexport interface AuthorizationServiceDeps {\n readonly authorization: AuthorizationPort\n /** Optional: absent profiles degrade to \"not available\" (matches the surface's own optional-service pattern). */\n readonly routeActivation?: RouteActivationPort\n /** Optional: runs after the route is active, so the route's models can be listed. */\n readonly defaultModel?: DefaultModelAdoptionPort\n readonly onCredentialChanged: CredentialChangedListener\n}\n\nexport class AuthorizationService {\n constructor(private readonly deps: AuthorizationServiceDeps) {}\n\n async begin(request: AuthorizationBeginRequest): Promise<AuthorizationOutcome> {\n const outcome = await this.deps.authorization.begin(request)\n if (outcome.status === 'authorized') {\n const slash = request.key.indexOf('/')\n const providerId = slash === -1 ? request.key : request.key.slice(slash + 1)\n if (this.deps.routeActivation !== undefined) {\n await this.deps.routeActivation.ensureRouteActivated(providerId, request.method)\n }\n await this.deps.defaultModel?.adoptIfDefaultUnusable(providerId)\n this.deps.onCredentialChanged(request.key)\n }\n return outcome\n }\n}\n","/**\n * `SignInAttempts`: the one sign-in conversation a surface shows at a time, as a plain read model.\n *\n * `AuthorizationService.begin` runs a flow to its end and talks to the human through callbacks (notices, prompts). A\n * request/response surface (a native window, a page) cannot hold a callback open, so this owns the conversation in\n * between: it starts the flow, records what the flow said (`notices`) and asked (`prompt`), lets the surface answer or\n * cancel by id, and reports how it ended. The terminal keeps its own copy of this logic inline; this is the shared one.\n *\n * Framework-free: the only dependency is a `begin` function, so it is unit-testable without Cordis. A secret typed into a\n * prompt travels from `answer` to the flow and is never stored here.\n */\nimport type { AuthorizationBeginRequest, AuthorizationOutcome } from './types.ts'\n\n/** What the running flow said: where to go, or what to do next. */\nexport interface SignInNotice {\n readonly message: string\n readonly url?: string\n readonly code?: string\n}\n\n/** A question the running flow waits on. */\nexport interface SignInPrompt {\n /** Echoed back by `answer`, so a late answer to a withdrawn question is refused. */\n readonly id: string\n readonly kind: 'text' | 'secret' | 'select'\n readonly message: string\n readonly placeholder?: string\n readonly options?: readonly { readonly id: string; readonly label: string; readonly description?: string }[]\n}\n\nexport type SignInPhase = 'running' | 'authorized' | 'cancelled' | 'failed'\n\n/** One attempt as a surface sees it. */\nexport interface SignInAttemptView {\n readonly id: string\n readonly key: string\n readonly method: string | undefined\n readonly phase: SignInPhase\n /** The most recent notices, oldest first. */\n readonly notices: readonly SignInNotice[]\n /** The question the flow is waiting on, while `phase` is `running`. */\n readonly prompt?: SignInPrompt\n /** Why a `failed` attempt failed, in words safe to show. */\n readonly error?: string\n}\n\nexport interface SignInAttemptsDeps {\n readonly begin: (request: AuthorizationBeginRequest) => Promise<AuthorizationOutcome>\n /** A fresh id for an attempt or a prompt. */\n readonly newId: () => string\n}\n\n/** A refused request (unknown attempt, stale prompt): the caller learns what to fix. */\nexport class SignInAttemptError extends Error {\n constructor(readonly code: 'unknown-attempt' | 'unknown-prompt' | 'invalid-answer', message: string) {\n super(message)\n this.name = 'SignInAttemptError'\n }\n}\n\nconst MAX_NOTICES = 8\n\ninterface Live {\n view: SignInAttemptView\n readonly controller: AbortController\n pending: { readonly prompt: SignInPrompt; readonly resolve: (value: string) => void; readonly reject: (cause: Error) => void } | undefined\n}\n\n/**\n * A flow's failure as a person reads it. Provider token endpoints answer with a JSON body that the flows quote whole\n * (\"... token exchange failed (401): { \"error\": { \"message\": \"Could not validate your token. ...\" } }\"); keep the flow's\n * own lead-in and the provider's sentence, drop the JSON around it.\n */\nexport function readableFailure(cause: unknown): string {\n const message = cause instanceof Error ? cause.message.trim() : ''\n if (message === '') return 'Sign-in failed.'\n const start = message.indexOf('{')\n if (start === -1) return message\n let body: unknown\n try {\n body = JSON.parse(message.slice(start))\n } catch {\n return message\n }\n const record = (value: unknown): Record<string, unknown> | undefined => typeof value === 'object' && value !== null ? value as Record<string, unknown> : undefined\n const nested = record(record(body)?.error)\n const said = [nested?.message, record(body)?.error_description, record(body)?.message, record(body)?.error].find(value => typeof value === 'string' && value.trim() !== '')\n if (typeof said !== 'string') return message\n const lead = message.slice(0, start).trim().replace(/:$/u, '')\n return lead === '' ? said.trim() : `${lead}: ${said.trim()}`\n}\n\nexport class SignInAttempts {\n private live: Live | undefined\n\n constructor(private readonly deps: SignInAttemptsDeps) {}\n\n /** The latest attempt (running or settled), or undefined before any. */\n current(): SignInAttemptView | undefined {\n return this.live?.view\n }\n\n /**\n * Start an attempt, withdrawing a running one first (a surface that restarts has abandoned the old conversation).\n * @returns the new attempt, already `running`.\n */\n begin(key: string, method: string | undefined): SignInAttemptView {\n if (this.live?.view.phase === 'running') this.withdraw(this.live)\n const live: Live = {\n view: { id: this.deps.newId(), key, method, phase: 'running', notices: [] },\n controller: new AbortController(),\n pending: undefined,\n }\n this.live = live\n void this.run(live)\n return live.view\n }\n\n /**\n * Answer the question the flow is waiting on.\n * @param promptId - the id of the prompt being answered, as the view showed it.\n * @param value - the typed text or the chosen option id.\n */\n answer(attemptId: string, promptId: string, value: string): SignInAttemptView {\n const live = this.require(attemptId)\n const pending = live.pending\n if (pending === undefined || pending.prompt.id !== promptId) throw new SignInAttemptError('unknown-prompt', 'That question is no longer being asked.')\n if (pending.prompt.kind === 'select' && !(pending.prompt.options ?? []).some(option => option.id === value)) {\n throw new SignInAttemptError('invalid-answer', 'That is not one of the choices.')\n }\n live.pending = undefined\n this.show(live, undefined)\n pending.resolve(value)\n return live.view\n }\n\n /** Withdraw the attempt; a settled attempt is left as it ended. */\n cancel(attemptId: string): SignInAttemptView {\n const live = this.require(attemptId)\n if (live.view.phase === 'running') this.withdraw(live)\n return live.view\n }\n\n private require(attemptId: string): Live {\n if (this.live === undefined || this.live.view.id !== attemptId) throw new SignInAttemptError('unknown-attempt', 'That sign-in is no longer current.')\n return this.live\n }\n\n private update(live: Live, patch: { readonly phase?: SignInPhase; readonly notices?: readonly SignInNotice[]; readonly error?: string }): void {\n live.view = { ...live.view, ...patch }\n }\n\n /** Show (or clear) the question the flow waits on. */\n private show(live: Live, prompt: SignInPrompt | undefined): void {\n const { prompt: _previous, ...rest } = live.view\n live.view = prompt === undefined ? rest : { ...rest, prompt }\n }\n\n /** Stop a running attempt: the flow's pending question is refused, which ends it as cancelled. */\n private withdraw(live: Live): void {\n live.controller.abort()\n live.pending?.reject(new Error('sign-in withdrawn'))\n live.pending = undefined\n this.show(live, undefined)\n this.update(live, { phase: 'cancelled' })\n }\n\n private async run(live: Live): Promise<void> {\n const interaction: AuthorizationBeginRequest['interaction'] = {\n notify: notice => {\n this.update(live, { notices: [...live.view.notices, notice].slice(-MAX_NOTICES) })\n },\n prompt: prompt => new Promise<string>((resolve, reject) => {\n if (live.controller.signal.aborted || prompt.signal?.aborted === true) { reject(new Error('sign-in withdrawn')); return }\n const shown: SignInPrompt = {\n id: this.deps.newId(),\n kind: prompt.kind,\n message: prompt.message,\n ...prompt.placeholder === undefined ? {} : { placeholder: prompt.placeholder },\n ...prompt.options === undefined ? {} : { options: prompt.options.map(option => ({ id: option.id, label: option.label, ...option.description === undefined ? {} : { description: option.description } })) },\n }\n live.pending = { prompt: shown, resolve, reject }\n this.show(live, shown)\n // A flow that races a typed code against a browser callback withdraws the losing question itself.\n prompt.signal?.addEventListener('abort', () => {\n if (live.pending?.prompt.id !== shown.id) return\n live.pending = undefined\n this.show(live, undefined)\n reject(new Error('sign-in question withdrawn'))\n }, { once: true })\n }),\n }\n try {\n const outcome = await this.deps.begin({ key: live.view.key, method: live.view.method, interaction, signal: live.controller.signal })\n // A cancel that raced the end of the flow wins: the surface already showed the attempt as cancelled.\n if (live.view.phase !== 'running') return\n this.show(live, undefined)\n this.update(live, { phase: outcome.status === 'authorized' ? 'authorized' : 'cancelled' })\n } catch (cause) {\n if (live.view.phase !== 'running') return\n this.show(live, undefined)\n this.update(live, { phase: 'failed', error: readableFailure(cause) })\n }\n }\n}\n","/**\n * The tools port of the ACRYL platform: what ACRYL's own Host plugins need to give an agent a tool, and to have a say in whether a call runs, without\n * importing a DeepSeek Harness package. A plugin injects `acrylTools` (optional where a chat may not exist), defines tools with {@link defineAcrylTool}\n * and registers them; a policy decides allow, deny or ask before a call runs. The provider is an adapter in the engine seam (`acryl-harness-runtime`),\n * so the registry behind it can change without touching a plugin.\n *\n * @module acryl-control/platform/tools\n */\n\n/** A parameter of a tool: a JSON Schema type, whether it must be given, and a description for the model. */\nexport interface AcrylToolParam {\n readonly type: 'string' | 'integer' | 'number' | 'boolean' | 'array' | 'object'\n readonly required?: boolean\n readonly description?: string\n readonly [extra: string]: unknown\n}\n\ntype ValueOf<P extends AcrylToolParam> =\n P['type'] extends 'string' ? string\n : P['type'] extends 'integer' | 'number' ? number\n : P['type'] extends 'boolean' ? boolean\n : unknown\n\n/** The arguments object a tool receives, inferred from its parameter specs: required ones always present, the others optional. */\nexport type AcrylToolArgs<P extends Readonly<Record<string, AcrylToolParam>>> =\n { readonly [K in keyof P as P[K]['required'] extends true ? K : never]: ValueOf<P[K]> }\n & { readonly [K in keyof P as P[K]['required'] extends true ? never : K]?: ValueOf<P[K]> }\n\n/** One block of what the model reads back. */\nexport interface AcrylToolBlock {\n readonly type: 'text'\n readonly text: string\n}\n\n/** What a running tool is given besides its arguments. */\nexport interface AcrylToolExecution {\n /** Aborted when the call is cancelled; a tool honours it. */\n readonly signal: AbortSignal\n}\n\nexport interface AcrylToolDefinition {\n readonly name: string\n readonly description: string\n readonly parameters: Readonly<Record<string, AcrylToolParam>>\n readonly output: {\n /** JSON Schema of the value `execute` returns. */\n readonly schema: Readonly<Record<string, unknown>>\n /** What the model reads, separately from the typed value. */\n readonly render?: (args: never, value: never) => readonly AcrylToolBlock[]\n }\n readonly execute: (args: never, exec: AcrylToolExecution) => unknown\n}\n\n/**\n * Describe a tool with its arguments inferred from `parameters` and its value typed by `execute`. Plain data in, the same data out: the typing is the\n * whole job.\n */\nexport function defineAcrylTool<const P extends Readonly<Record<string, AcrylToolParam>>, V>(definition: {\n readonly name: string\n readonly description: string\n readonly parameters: P\n readonly output: {\n readonly schema: Readonly<Record<string, unknown>>\n readonly render?: (args: AcrylToolArgs<P>, value: V) => readonly AcrylToolBlock[]\n }\n readonly execute: (args: AcrylToolArgs<P>, exec: AcrylToolExecution) => V | Promise<V>\n}): AcrylToolDefinition {\n return definition as unknown as AcrylToolDefinition\n}\n\n/** The call a policy is asked about. */\nexport interface AcrylToolCall {\n readonly name: string\n readonly arguments: unknown\n /** The agent session that made the call, when there is one (an outside caller has none). */\n readonly agent?: { readonly session: unknown }\n}\n\nexport type AcrylToolDecision =\n | { readonly kind: 'allow' }\n | { readonly kind: 'deny'; readonly reason: string }\n | { readonly kind: 'ask'; readonly reason?: string }\n\n/** A policy: ask `next()` for what the rest of the chain would decide, and return it unchanged unless this policy has something to say. */\nexport type AcrylToolPolicy = (call: AcrylToolCall, next: () => Promise<AcrylToolDecision>) => Promise<AcrylToolDecision>\n\n/** A tool as the registry knows it. */\nexport interface AcrylToolInfo {\n readonly name: string\n readonly description: string\n /** JSON Schema of the arguments. */\n readonly parameters: Readonly<Record<string, unknown>>\n}\n\nexport interface AcrylToolResult {\n readonly isError?: boolean\n readonly content?: ReadonlyArray<{ readonly type: string; readonly text?: string }>\n}\n\nexport interface AcrylTools {\n /** @returns the disposer that removes exactly this tool. */\n register(definition: AcrylToolDefinition): () => void\n /** @returns the tool, or `undefined` when none by that name is registered. */\n get(name: string): AcrylToolInfo | undefined\n /** Run a tool through the registry's whole pipeline: every policy applies. */\n execute(input: { readonly callId: string; readonly name: string; readonly arguments: unknown; readonly signal: AbortSignal }): Promise<AcrylToolResult>\n /** @returns the disposer that removes exactly this policy. */\n policy(handler: AcrylToolPolicy): () => void\n}\n\ndeclare module '@deepseek-ai/cordis' {\n interface Context {\n acrylTools: AcrylTools\n }\n}\n","/**\n * Everything the plugin lifecycle controller needs from the host it runs in.\n *\n * The controller owns the lifecycle mechanics - resolution, dependent cascade,\n * transaction ordering, rollback, Fiber restart - and this port supplies the\n * three things that differ per surface: which entries are user-mutable, how\n * enablement is persisted, and what a just-installed bundle inserts.\n *\n * @module acryl-control/plugin/host\n */\n\nimport type { EntryGroup } from '@deepseek-ai/cordis-plugin-loader'\n\n/** The Loader identity of one entry, as a policy sees it. */\nexport interface PluginLifecycleEntryRef {\n /** Runtime Loader entry id, including its owning Include path when composed from one. */\n readonly entryId: string\n /** Exact module specifier the entry loads. */\n readonly moduleName: string\n /** Whether the entry is a Loader group rather than a plugin. */\n readonly group: boolean\n}\n\n/** The Loader row a profile-bundle package inserts, read from its own cordis patch. */\nexport interface PluginLifecycleBundleRow {\n readonly id: string\n readonly name: string\n}\n\n/** Shown for a non-mutable entry whose host supplies no wording of its own. */\nexport const PROTECTED_PLUGIN_ENTRY_REASON =\n 'This entry is part of the runtime or is dependency-managed and is not user-toggleable. Plugins you add through a profile bundle or a plugin market can be enabled, disabled, and reloaded here.'\n\n/**\n * Host policy and side effects behind the lifecycle controller.\n *\n * Implementations are host-neutral by contract: they may read a profile, a\n * state file, or a remote registry, but they never decide lifecycle order.\n */\nexport interface PluginLifecycleHost {\n /** Whether this host admits the entry to user lifecycle control. */\n isMutable(entry: PluginLifecycleEntryRef): boolean\n\n /**\n * Why an entry is not mutable, in the host's own words. Defaults to\n * {@link PROTECTED_PLUGIN_ENTRY_REASON}; a surface with its own explanation\n * (e.g. a Desktop runtime) overrides it.\n */\n protectedReason?(entry: PluginLifecycleEntryRef): string | null\n\n /**\n * Re-read any externally derived mutation state (a bundle list a package\n * manager just rewrote, for example). Called before every mutation, so a host\n * does not have to keep its own view fresh.\n */\n refresh?(): void\n\n /** Persist one entry's desired enablement. Rejects when the write fails. */\n setEnabled(entryId: string, enabled: boolean): Promise<void>\n\n /**\n * The Loader row a profile-bundle package inserts, for live activation of a\n * just-installed plugin. Consulted before the already-mounted shortcut, so it\n * is also the host's answer to \"may this package be activated at all\".\n *\n * Throws `PluginLifecycleError` with `protected-entry` when the package is\n * not an installed profile bundle, and with `lifecycle-failed` when it is a\n * bundle whose patch declares no usable insert row: only the host can tell a\n * package that was never installed from one that is installed but broken.\n * Optional - a host without a profile-bundle concept simply does not support\n * live activation.\n */\n bundleRow?(packageName: string): PluginLifecycleBundleRow\n\n /**\n * The Loader group a bundle row joins. Defaults to the Loader root; a\n * host that composes its profile through an include file returns that\n * include's group so a live install lands among the profile's own rows.\n */\n bundleGroup?(): EntryGroup\n\n /**\n * Host bookkeeping after a package leaves the Loader tree (pruning a stale\n * disable record, for example). Best effort: a rejection is reported through\n * {@link PluginLifecycleHost.warn} and never fails the uninstall.\n */\n afterDeactivate?(packageName: string): Promise<void>\n\n /**\n * Entries \"reload all\" sweeps, when the host's own reload is deliberately\n * narrower than every mutable entry. Optional - without it, reload-all\n * restarts every enabled mutable entry.\n */\n reloadAllEntryIds?(): ReadonlySet<string>\n\n /** Reports a best-effort failure (bookkeeping cleanup) that must not throw. */\n warn?(message: string): void\n}\n","/**\n * Host-neutral lifecycle authority over explicitly managed Loader entries.\n *\n * Every surface runs this one controller: the TUI drives it for `plugin\n * enable|disable`, the Web surface mounts it through the runtime, and Desktop\n * wraps it with its own projection and market bridge. The controller decides\n * resolution, cascade, order, and rollback; the host port\n * (`host.ts`) decides policy and persistence.\n *\n * @module acryl-control/plugin/controller\n */\n\nimport { type Context, type Fiber, type FiberState } from '@deepseek-ai/cordis'\nimport type { Entry, EntryOptions } from '@deepseek-ai/cordis-plugin-loader'\nimport {\n PROTECTED_PLUGIN_ENTRY_REASON,\n type PluginLifecycleEntryRef,\n type PluginLifecycleHost,\n} from './host.ts'\nimport type {\n PluginLifecycleAction,\n PluginLifecycleEntryView,\n PluginLifecycleFiberPhase,\n PluginLifecycleMountedStatus,\n PluginLifecycleReceipt,\n PluginLifecycleSnapshot,\n} from './types.ts'\n\nconst FIBER_STATE = {\n PENDING: 0 as FiberState.PENDING,\n LOADING: 1 as FiberState.LOADING,\n ACTIVE: 2 as FiberState.ACTIVE,\n FAILED: 3 as FiberState.FAILED,\n DISPOSED: 4 as FiberState.DISPOSED,\n UNLOADING: 5 as FiberState.UNLOADING,\n} as const\n\nconst FIBER_PHASE = {\n [FIBER_STATE.PENDING]: 'pending',\n [FIBER_STATE.LOADING]: 'loading',\n [FIBER_STATE.ACTIVE]: 'active',\n [FIBER_STATE.FAILED]: 'failed',\n [FIBER_STATE.DISPOSED]: null,\n [FIBER_STATE.UNLOADING]: 'unloading',\n} as const satisfies Record<FiberState, PluginLifecycleFiberPhase>\n\n/** Stable failures that a route, a command, or a panel may present. */\nexport type PluginLifecycleErrorCode =\n | 'unknown-entry'\n | 'protected-entry'\n | 'already-enabled'\n | 'already-disabled'\n | 'not-mounted'\n | 'persistence-failed'\n | 'lifecycle-failed'\n\nexport class PluginLifecycleError extends Error {\n constructor(readonly code: PluginLifecycleErrorCode, message: string) {\n super(message)\n this.name = 'PluginLifecycleError'\n }\n}\n\n/** The error a FAILED entry's Fiber recorded, when it recorded one (Cordis keeps it on the Fiber's private `_error`). */\nfunction fiberFailure(entry: Entry): Error | undefined {\n const failure: unknown = entry.fiber === undefined ? undefined : Reflect.get(entry.fiber, '_error')\n return failure instanceof Error ? failure : undefined\n}\n\nfunction phaseOf(entry: Entry): PluginLifecycleFiberPhase {\n return entry.fiber === undefined ? null : FIBER_PHASE[entry.fiber.state as FiberState]\n}\n\n/**\n * The bare Fiber behind the thenable wrapper the registry hands out.\n *\n * `ctx.plugin()` returns `Object.create(fiber)` with an own `then`, and the\n * Loader keeps that wrapper as `entry.fiber`, while plugin code sees the bare\n * fiber as `ctx.fiber` and service implementations record that one. Any\n * comparison between an entry's fiber and a service's providing fiber has to\n * unwrap the entry side first, or it never matches.\n */\nfunction bareFiber(fiber: Fiber): Fiber {\n return Object.hasOwn(fiber, 'then') ? (Object.getPrototypeOf(fiber) as Fiber) : fiber\n}\n\nfunction refOf(entry: Entry): PluginLifecycleEntryRef {\n return { entryId: entry.id, moduleName: entry.options.name, group: entry.options.group === true }\n}\n\n/** Deep module hiding Loader mutation, ordering, rollback, and cascade policy. */\nexport class AcrPluginLifecycleController {\n private operation = Promise.resolve()\n /**\n * Entry ids this controller mounted, keyed by the package that asked for\n * them. A bundle's insert row names a module specifier that need not equal\n * the package name (`acryl-desktop` inserts `acryl-desktop/terminal`), and\n * after an uninstall the package can no longer be asked - so what an\n * activation actually created is the only authority that outlives it.\n */\n private readonly activatedEntries = new Map<string, string>()\n /**\n * Module rows this controller inserted for {@link requireModules}, each with the plugin packages that need it. A row is removed when\n * its last owner leaves; a row that was already mounted when a plugin asked for it is never in here, so this path never removes it.\n */\n private readonly moduleOwners = new Map<string, Set<string>>()\n\n constructor(\n private readonly ctx: Context,\n private readonly host: PluginLifecycleHost,\n ) {}\n\n /** Project every non-group Loader entry and the host's mutation policy. */\n snapshot(): PluginLifecycleSnapshot {\n const entries: PluginLifecycleEntryView[] = []\n for (const entry of this.ctx.loader.entries()) {\n if (entry.options.group) continue\n const mutable = this.isMutable(entry)\n entries.push(Object.freeze({\n entryId: entry.id,\n moduleName: entry.options.name,\n enabled: !entry.disabled,\n hostPhase: phaseOf(entry),\n mutable,\n protectedReason: mutable ? null : this.protectedReason(entry),\n dependents: mutable && !entry.disabled\n ? Object.freeze(this.mutableDependents(entry).map(dependent => dependent.id))\n : Object.freeze([]),\n }))\n }\n return Object.freeze({ entries: Object.freeze(entries) })\n }\n\n /**\n * Apply one entry's enablement and wait until it has settled. Loader 1.0.5 (DSH 0.2) starts disposing a disabled entry's Fiber\n * without waiting, and logs - rather than throws - an activation failure; a receipt must not be returned for a Fiber that is still\n * unloading, and a failed activation must reach the caller so the transaction rolls back.\n */\n private async applyEnabled(target: Entry, enabled: boolean): Promise<void> {\n const previous = target.fiber\n await target.update({ disabled: !enabled })\n if (!enabled) await previous?.dispose()\n await this.ctx.loader.await?.()\n if (enabled && (target.fiber === undefined || phaseOf(target) === 'failed')) {\n throw new Error(`Plugin ${target.id} did not activate`)\n }\n }\n\n /**\n * Persist and apply one managed entry's enablement transactionally. Disabling\n * an entry that mutable plugins depend on disables those dependents in the\n * same transaction (dependents first, so a consumer unmounts before its\n * provider); the receipt lists every id changed.\n */\n setEnabled(entryId: string, enabled: boolean): Promise<PluginLifecycleReceipt> {\n return this.exclusive(async () => {\n const entry = this.resolveMutable(entryId)\n if ((!entry.disabled) === enabled) {\n throw new PluginLifecycleError(\n enabled ? 'already-enabled' : 'already-disabled',\n `Plugin ${entryId} is already ${enabled ? 'enabled' : 'disabled'}.`,\n )\n }\n const targets = enabled\n ? [entry]\n : [...this.mutableDependents(entry).filter(dependent => !dependent.disabled), entry]\n\n // A target joins `persisted` as soon as its override is written, before\n // the Loader applies it: an update that throws still left the persisted\n // state changed, and skipping that one in the rollback would hand the\n // next boot a disable the user was told had failed.\n const persisted: Entry[] = []\n try {\n for (const target of targets) {\n await this.host.setEnabled(target.id, enabled)\n persisted.push(target)\n await this.applyEnabled(target, enabled)\n }\n } catch (cause) {\n const rollbackErrors: string[] = []\n for (const target of persisted.reverse()) {\n try {\n await this.host.setEnabled(target.id, !enabled)\n await this.applyEnabled(target, !enabled)\n } catch (rollbackCause) {\n rollbackErrors.push(describe(rollbackCause))\n }\n }\n const detail = describe(cause)\n throw new PluginLifecycleError(\n rollbackErrors.length > 0 ? 'persistence-failed' : 'lifecycle-failed',\n rollbackErrors.length > 0\n ? `Plugin lifecycle change failed and rollback also failed: ${detail}; ${rollbackErrors.join('; ')}`\n : `Plugin lifecycle change failed: ${detail}`,\n )\n }\n return this.receipt(enabled ? 'enable' : 'disable', persisted.map(target => target.id))\n })\n }\n\n /**\n * Restart one entry, or - with no argument - the host's reload-all set:\n * {@link PluginLifecycleHost.reloadAllEntryIds} when the host narrows it\n * (Desktop deliberately avoids churning every market plugin's client fiber at\n * once), otherwise every enabled mutable entry.\n */\n reload(entryId?: string): Promise<PluginLifecycleReceipt> {\n return this.exclusive(async () => {\n const entries = entryId === undefined ? this.reloadAllEntries() : [this.resolveMutable(entryId)]\n if (entries.length === 0) {\n throw new PluginLifecycleError('not-mounted', 'No managed plugin is currently mounted.')\n }\n for (const entry of entries) {\n if (entry.disabled || entry.fiber === undefined) {\n throw new PluginLifecycleError('not-mounted', `Plugin ${entry.id} is not mounted.`)\n }\n try {\n await entry.fiber.restart()\n } catch (cause) {\n throw new PluginLifecycleError(\n 'lifecycle-failed',\n `Plugin ${entry.id} failed to reload: ${describe(cause)}`,\n )\n }\n }\n return this.receipt('reload', entries.map(entry => entry.id))\n })\n }\n\n /**\n * Mount a just-installed profile-bundle package into the running Loader tree,\n * so an install takes effect without a process restart. The bundle's row comes\n * from its own cordis patch, via {@link PluginLifecycleHost.bundleRow}.\n * Idempotent: a package already mounted returns its current snapshot.\n *\n * The host is asked for the row before the mounted-entry shortcut, so it\n * stays the single authority on what may be activated at all: only it can\n * tell an installed profile bundle from a package the market never managed.\n */\n activate(packageName: string): Promise<PluginLifecycleReceipt> {\n return this.exclusive(async () => {\n const row = this.host.bundleRow?.(packageName)\n if (row === undefined) {\n throw new PluginLifecycleError(\n 'protected-entry',\n `Package ${packageName} cannot be activated by this host.`,\n )\n }\n const already = this.findLiveEntry(packageName)\n if (already !== undefined) {\n this.activatedEntries.set(packageName, already.id)\n return this.receipt('enable', [already.id])\n }\n\n let entry: Entry | undefined\n try {\n entry = await this.mountRow(row)\n } catch (cause) {\n throw new PluginLifecycleError(\n 'lifecycle-failed',\n `Plugin ${packageName} failed to activate: ${describe(cause)}`,\n )\n }\n if (entry !== undefined) this.activatedEntries.set(packageName, entry.id)\n return this.receipt('enable', [entry?.id ?? `include:${row.id}`])\n })\n }\n\n /**\n * Make the modules `owner` needs mounted (a module inside a package, such as `acrylblends/cordis/state`, which is not a profile bundle of\n * its own), and release the ones it needed before and no longer names. `modules` is the owner's whole list, so an install, an update and\n * an uninstall (`[]`) are the same call. A module already mounted is used as it is and never removed by this path; a missing one gets\n * the row `{ id: module, name: module }`, owned by every plugin that asks for it, and removed when its last owner leaves.\n *\n * All or nothing: when a module cannot be mounted, the rows this call inserted are removed and the owners it added dropped before the\n * error is thrown, and nothing is released; releases run only after every module is mounted. A row of the module that exists but is\n * turned off is left alone and refused, because turning it off was a choice.\n * @param owner - the plugin package that needs the modules.\n * @param modules - every module it needs now.\n */\n requireModules(owner: string, modules: readonly string[]): Promise<void> {\n return this.exclusive(async () => {\n const wanted = new Set(modules)\n const inserted: string[] = []\n const joined: string[] = []\n try {\n for (const module of wanted) {\n const owners = this.moduleOwners.get(module)\n if (owners !== undefined) {\n if (!owners.has(owner)) { owners.add(owner); joined.push(module) }\n continue\n }\n const existing = [...this.ctx.loader.entries()].find(entry => !entry.options.group && entry.options.name === module)\n if (existing !== undefined) {\n if (existing.disabled) {\n throw new PluginLifecycleError('lifecycle-failed', `${module} is turned off in this app (row ${existing.id}); turn it on, then install ${owner} again.`)\n }\n continue\n }\n try {\n await this.mountRow({ id: module, name: module })\n } catch (cause) {\n throw new PluginLifecycleError('lifecycle-failed', `${module}, which ${owner} needs, failed to start: ${describe(cause)}`)\n }\n this.moduleOwners.set(module, new Set([owner]))\n inserted.push(module)\n }\n } catch (cause) {\n for (const module of joined) this.moduleOwners.get(module)?.delete(owner)\n for (const module of inserted.reverse()) {\n this.moduleOwners.delete(module)\n await this.unmountRow(module).catch((error: unknown) => { this.host.warn?.(`could not remove ${module} after a failed start: ${describe(error)}`) })\n }\n throw cause\n }\n for (const [module, owners] of this.moduleOwners) {\n if (wanted.has(module) || !owners.delete(owner) || owners.size > 0) continue\n this.moduleOwners.delete(module)\n try {\n await this.unmountRow(module)\n } catch (cause) {\n throw new PluginLifecycleError('lifecycle-failed', `${module}, which only ${owner} needed, failed to stop: ${describe(cause)}`)\n }\n }\n })\n }\n\n /**\n * Unmount an uninstalled package from the running Loader tree, then let the\n * host prune any bookkeeping the package left behind. No-op when it is\n * already gone; the host's cleanup still runs, because a package that has left\n * the profile has nothing left to be disabled.\n */\n deactivate(packageName: string): Promise<PluginLifecycleReceipt> {\n return this.exclusive(async () => {\n const entry = this.findLiveEntry(packageName)\n if (entry === undefined) {\n await this.afterDeactivate(packageName)\n return this.receipt('disable', [])\n }\n const rowId = entry.options.id\n try {\n await entry.parent.remove(rowId)\n await this.ctx.loader.await?.()\n } catch (cause) {\n throw new PluginLifecycleError(\n 'lifecycle-failed',\n `Plugin ${packageName} failed to deactivate: ${describe(cause)}`,\n )\n }\n await this.afterDeactivate(packageName)\n return this.receipt('disable', [entry.id])\n })\n }\n\n /**\n * Restart the fiber of a mounted plugin identified by package name. Used by a\n * local-development file watcher. No-op when the package is not mounted.\n */\n reloadByPackage(packageName: string): Promise<PluginLifecycleReceipt> {\n return this.exclusive(async () => {\n const entry = this.findLiveEntry(packageName)\n if (entry === undefined || entry.disabled || entry.fiber === undefined) {\n return this.receipt('reload', [])\n }\n try {\n await entry.fiber.restart()\n } catch (cause) {\n throw new PluginLifecycleError(\n 'lifecycle-failed',\n `Plugin ${packageName} failed to reload: ${describe(cause)}`,\n )\n }\n return this.receipt('reload', [entry.id])\n })\n }\n\n /**\n * Toggle a live entry by package name for a caller that knows only package\n * names, not Loader ids. Resolves `false` when no live entry exists (an import\n * failure, or not mounted yet), so the caller falls back to its own persisted\n * state - the only mechanism that still works when a bundle's module cannot\n * even be imported. Idempotent against a state that already matches, since the\n * caller's own view of \"current status\" may be the exact stale read this\n * method exists to correct.\n */\n async setEnabledByPackageName(packageName: string, enabled: boolean): Promise<boolean> {\n const entry = this.findLiveEntry(packageName)\n if (entry === undefined) return false\n try {\n await this.setEnabled(entry.id, enabled)\n } catch (cause) {\n if (cause instanceof PluginLifecycleError\n && (cause.code === 'already-enabled' || cause.code === 'already-disabled')) return true\n throw cause\n }\n return true\n }\n\n /**\n * Read a live entry's current enabled/disabled state by package name, or\n * `undefined` when it is not mounted (the caller's own persisted status is\n * authoritative in that case).\n */\n statusOfPackage(packageName: string): PluginLifecycleMountedStatus | undefined {\n const entry = this.findLiveEntry(packageName)\n if (entry === undefined) return undefined\n return entry.disabled ? 'disabled' : 'active'\n }\n\n private isMutable(entry: Entry): boolean {\n if (entry.options.group) return false\n return this.host.isMutable(refOf(entry))\n }\n\n private protectedReason(entry: Entry): string {\n return this.host.protectedReason?.(refOf(entry)) ?? PROTECTED_PLUGIN_ENTRY_REASON\n }\n\n private reloadAllEntries(): Entry[] {\n const narrowed = this.host.reloadAllEntryIds?.()\n return [...this.ctx.loader.entries()].filter((entry) => {\n if (entry.options.group || entry.disabled) return false\n return narrowed === undefined ? this.isMutable(entry) : narrowed.has(entry.id)\n })\n }\n\n /** Service names whose live provider is `fiber`. */\n private servicesProvidedBy(fiber: Fiber): ReadonlySet<string> {\n const store = (this.ctx.root as {\n reflect?: { store?: Record<symbol, { name: string, fiber: Fiber } | undefined> }\n }).reflect?.store\n const names = new Set<string>()\n if (store === undefined) return names\n const target = bareFiber(fiber)\n for (const key of Object.getOwnPropertySymbols(store)) {\n const impl = store[key]\n if (impl !== undefined && bareFiber(impl.fiber) === target) names.add(impl.name)\n }\n return names\n }\n\n /**\n * Mutable, currently-mounted entries that hard-`inject` a service `entry`\n * provides and resolve it to `entry`'s fiber - transitively.\n */\n private mutableDependents(entry: Entry): Entry[] {\n const byId = new Map([...this.ctx.loader.entries()].map(candidate => [candidate.id, candidate]))\n const found = new Map<string, Entry>()\n const queue: Entry[] = [entry]\n while (queue.length > 0) {\n const current = queue.shift()!\n const currentFiber = current.fiber\n if (currentFiber === undefined) continue\n const provided = this.servicesProvidedBy(currentFiber)\n if (provided.size === 0) continue\n for (const other of byId.values()) {\n if (other === entry || found.has(other.id) || other.options.group) continue\n if (other.fiber === undefined || !this.isMutable(other)) continue\n const inject = (other.fiber as { inject?: Record<string, unknown> }).inject ?? {}\n const store = (other.fiber as { store?: Record<string, { fiber?: Fiber } | undefined> }).store ?? {}\n const target = bareFiber(currentFiber)\n const dependsOnCurrent = Object.keys(inject).some((name) => {\n const impl = store[name]\n return provided.has(name) && impl?.fiber !== undefined && bareFiber(impl.fiber) === target\n })\n if (dependsOnCurrent) {\n found.set(other.id, other)\n queue.push(other)\n }\n }\n }\n return [...found.values()]\n }\n\n private async afterDeactivate(packageName: string): Promise<void> {\n this.host.refresh?.()\n if (this.host.afterDeactivate === undefined) return\n try {\n await this.host.afterDeactivate(packageName)\n } catch (cause) {\n // Best effort: cleanup must never fail the uninstall itself.\n this.host.warn?.(`could not complete plugin cleanup for ${packageName}: ${describe(cause)}`)\n }\n }\n\n /**\n * The live entry a package occupies: the row whose module specifier is the\n * package name (how a bundle row mounted by the boot Loader is identified),\n * else the row this controller mounted for it. A package whose row was\n * mounted at boot under a different specifier - an insert row pointing at a\n * subpath - is only resolvable while the host still calls it a profile\n * bundle; the activation record only covers this process.\n */\n private findLiveEntry(packageName: string): Entry | undefined {\n const entries = [...this.ctx.loader.entries()].filter(candidate => !candidate.options.group)\n const byName = entries.find(candidate => candidate.options.name === packageName)\n if (byName !== undefined) return byName\n const mountedId = this.activatedEntries.get(packageName)\n if (mountedId === undefined) return undefined\n return entries.find(candidate => candidate.id === mountedId)\n }\n\n private resolveMutable(entryId: string): Entry {\n const entry = [...this.ctx.loader.entries()].find(candidate => candidate.id === entryId)\n if (entry === undefined) {\n throw new PluginLifecycleError('unknown-entry', `Unknown plugin ${entryId}.`)\n }\n if (!this.isMutable(entry)) {\n throw new PluginLifecycleError(\n 'protected-entry',\n `Plugin ${entryId} is a core capability and cannot be toggled.`,\n )\n }\n return entry\n }\n\n private receipt(\n action: PluginLifecycleAction,\n entryIds: readonly string[],\n ): PluginLifecycleReceipt {\n return Object.freeze({\n accepted: true as const,\n action,\n entryIds: Object.freeze([...entryIds]),\n snapshot: this.snapshot(),\n })\n }\n\n /**\n * Insert one row into the profile's include group and wait until it settled; a row that did not reach ACTIVE (or PENDING) is removed\n * again and its error thrown. Returns the mounted entry.\n */\n private async mountRow(row: { readonly id: string; readonly name: string }): Promise<Entry | undefined> {\n const group = this.host.bundleGroup?.() ?? this.ctx.loader.root\n // The Loader's create() keeps a provided id (ensureId only generates one\n // when absent); its type omits `id` to steer callers toward generated\n // ids, but a bundle row's id must stay stable so the reboot patch (by id)\n // and a lifecycle toggle target the same entry.\n const rowOptions: EntryOptions & { id: string } = { id: row.id, name: row.name }\n try {\n await group.create(rowOptions)\n group.data.push(rowOptions)\n await this.ctx.loader.await?.()\n // Loader 1.0.5 (DSH 0.2) logs a throwing `apply` as a FAILED Fiber instead of rejecting `create()`: surface it here so the\n // caller rolls the install back with the plugin's own error.\n const created = [...this.ctx.loader.entries()].find(candidate => candidate.options.id === row.id)\n if (created !== undefined && (created.fiber === undefined || phaseOf(created) === 'failed')) {\n throw fiberFailure(created) ?? new Error(`plugin ${row.id} did not activate`)\n }\n return created\n } catch (cause) {\n try { await group.remove(row.id) } catch { /* best effort */ }\n throw cause\n }\n }\n\n /** Remove a row this controller inserted, wherever it sits, and wait until its Fiber has unloaded. */\n private async unmountRow(rowId: string): Promise<void> {\n const entry = [...this.ctx.loader.entries()].find(candidate => candidate.options.id === rowId)\n if (entry === undefined) return\n await entry.parent.remove(rowId)\n await this.ctx.loader.await?.()\n }\n\n /** Serialize mutations: one lifecycle transition settles before the next starts. */\n private exclusive<T>(operation: () => Promise<T>): Promise<T> {\n this.host.refresh?.()\n const next = this.operation.then(operation, operation)\n this.operation = next.then(() => undefined, () => undefined)\n return next\n }\n}\n\nfunction describe(cause: unknown): string {\n return cause instanceof Error ? cause.message : String(cause)\n}\n","/**\n * The Cordis service every surface injects to inspect and steer plugins.\n *\n * The service publishes an existing {@link AcrPluginLifecycleController} on\n * `ctx.acrPluginLifecycle` for the fiber's lifetime. It takes the controller\n * rather than a host because publishing a capability and building the domain\n * object are different acts: a surface that also owns package-keyed\n * operations (Desktop's market bridge) needs the controller itself, and both\n * views must be the same object or their transitions stop sharing one queue.\n *\n * @module acryl-control/plugin/provider\n */\n\nimport { type Context, Service } from '@deepseek-ai/cordis'\nimport type { AcrPluginLifecycleController } from './controller.ts'\nimport type { PluginLifecycleHost } from './host.ts'\nimport type { PluginLifecycleReceipt, PluginLifecycleSnapshot } from './types.ts'\n\nexport type { PluginLifecycleHost }\n\n/** The resolver-facing lifecycle API: list, enable or disable, reload. */\nexport interface AcrPluginLifecycle {\n snapshot(): PluginLifecycleSnapshot\n setEnabled(entryId: string, enabled: boolean): Promise<PluginLifecycleReceipt>\n reload(entryId?: string): Promise<PluginLifecycleReceipt>\n}\n\ndeclare module '@deepseek-ai/cordis' {\n interface Context {\n acrPluginLifecycle: AcrPluginLifecycle\n }\n}\n\nexport class AcrPluginLifecycleService extends Service implements AcrPluginLifecycle {\n /**\n * The full controller, for a host that also owns package-keyed operations\n * (activating a just-installed bundle, a market's install/uninstall bridge).\n * Same instance the service delegates to, so both views never drift.\n */\n readonly controller: AcrPluginLifecycleController\n\n constructor(ctx: Context, controller: AcrPluginLifecycleController) {\n super(ctx, 'acrPluginLifecycle')\n this.controller = controller\n }\n\n snapshot(): PluginLifecycleSnapshot {\n return this.controller.snapshot()\n }\n\n setEnabled(entryId: string, enabled: boolean): Promise<PluginLifecycleReceipt> {\n return this.controller.setEnabled(entryId, enabled)\n }\n\n reload(entryId?: string): Promise<PluginLifecycleReceipt> {\n return this.controller.reload(entryId)\n }\n}\n\nexport default AcrPluginLifecycleService\n","import {\n parseAcrylSessionSnapshot,\n type AcrylSessionClient,\n type AcrylSessionSnapshot,\n type AcrylSessionSubscription,\n} from '../contracts/session.ts'\n\nexport interface AcrylSessionTransport {\n request(operation: string, payload: unknown): Promise<unknown>\n subscribe(\n operation: string,\n payload: unknown,\n listener: (value: unknown) => void,\n onError?: (error: Error) => void,\n ): Promise<AcrylSessionSubscription>\n}\n\nfunction sessionId(value: string): string {\n if (value.trim() === '') throw new Error('ACRYL session id must not be empty')\n return value\n}\n\nfunction prompt(input: { readonly text: string }): string {\n if (input.text.trim() === '') throw new Error('ACRYL prompt must not be empty')\n return input.text\n}\n\n/** Create the presentation-safe session client over an owner or attached transport. */\nexport function createAcrylSessionClient(transport: AcrylSessionTransport): AcrylSessionClient {\n return Object.freeze({\n async snapshot(value: string): Promise<AcrylSessionSnapshot> {\n return parseAcrylSessionSnapshot(await transport.request('session.snapshot', {\n sessionId: sessionId(value),\n }))\n },\n async subscribe(\n value: string,\n listener: (snapshot: AcrylSessionSnapshot) => void,\n onError?: (error: Error) => void,\n ): Promise<AcrylSessionSubscription> {\n const selectedSessionId = sessionId(value)\n return transport.subscribe('session.subscribe', { sessionId: selectedSessionId }, (snapshot) => {\n try {\n const parsed = parseAcrylSessionSnapshot(snapshot)\n if (parsed.sessionId !== selectedSessionId) {\n throw new Error('ACRYL subscription returned a different session')\n }\n listener(parsed)\n } catch {\n // Presentation listeners cannot break a live transport subscription.\n }\n }, onError)\n },\n async submitPrompt(input: {\n readonly sessionId: string\n readonly text: string\n readonly clientCommandId: string\n }): Promise<void> {\n await transport.request('session.prompt.submit', {\n sessionId: sessionId(input.sessionId),\n text: prompt(input),\n clientCommandId: nonEmptyCommandId(input.clientCommandId),\n })\n },\n async cancel(input: { readonly sessionId: string }): Promise<void> {\n await transport.request('session.cancel', { sessionId: sessionId(input.sessionId) })\n },\n })\n}\n\nfunction nonEmptyCommandId(value: string): string {\n if (value.trim() === '') throw new Error('ACRYL client command id must not be empty')\n return value\n}\n"],"mappings":";;;AAwHA,IAAa,uBAAb,cAA0C,MAAM;CACzB;CAArB,YAAY,MAAyC,SAAiB;EACpE,MAAM,OAAO;EADM,KAAA,OAAA;EAEnB,KAAK,OAAO;CACd;AACF;AAQA,MAAM,qBAA0E;CAC9E,OAAO;CACP,MAAM;CACN,QAAQ;CACR,MAAM;CACN,QAAQ;AACV;AAEA,IAAa,yBAAb,cAA4CA,UAAmC;CAC7E,4BAA6B,IAAI,IAA2B;CAC5D,2BAA4B,IAAI,IAAgC;CAEhE,YAAY,KAAc;EACxB,MAAM,KAAK,iBAAiB;CAC9B;CAEA,iBAAiB,OAAgB,UAA+B;EAC9D,IAAI,SAAS,GAAG,KAAK,MAAM,IAAI,MAAM,IAAI,MAAM,qCAAqC;EACpF,MAAM,aAAa;GACjB,IAAI,KAAK,UAAU,IAAI,SAAS,EAAE,GAChC,MAAM,IAAI,MAAM,gCAAgC,SAAS,IAAI;GAE/D,KAAK,UAAU,IAAI,SAAS,IAAI,QAAQ;GACxC,aAAa;IACX,IAAI,KAAK,UAAU,IAAI,SAAS,EAAE,MAAM,UAAU,KAAK,UAAU,OAAO,SAAS,EAAE;GACrF;EACF,GAAG,iCAAiC,SAAS,IAAI;CACnD;CAEA,MAAM,OAAO,SAAqD;EAChE,MAAM,WAAW,KAAK,UAAU,IAAI,QAAQ,UAAU;EACtD,IAAI,aAAa,KAAA,GACf,MAAM,IAAI,qBAAqB,oBAAoB,0BAA0B,QAAQ,WAAW,EAAE;EAEpG,MAAM,WAAW,IAAI,IAAI,SAAS,YAAY;EAC9C,KAAK,MAAM,cAAc,QAAQ,cAC/B,IAAI,CAAC,SAAS,IAAI,UAAU,GAC1B,MAAM,IAAI,qBACR,uBACA,YAAY,QAAQ,WAAW,+BAA+B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,MAAM,OAAO,KAAK;IAClB,iBAAiB,kBAAkB,MAAM,eAAe;GAC1D,CAAC;EACH;EACA,MAAM,OAAO,OAAsD;GACjE,MAAM,UAAU,QAAQ,kBAAkB,EAAE,WAAW,UAAU,MAAM,SAAS,EAAE,CAAC;EACrF;CACF,CAAC;AACH;AAEA,SAAS,kBAAkB,OAAuB;CAChD,IAAI,MAAM,KAAK,MAAM,IAAI,MAAM,IAAI,MAAM,2CAA2C;CACpF,OAAO;AACT"}
@@ -0,0 +1,104 @@
1
+ /** Provider-neutral agent-control service definition for ACRYL. */
2
+ import type { Context } from '@deepseek-ai/cordis';
3
+ import { Service } from '@deepseek-ai/cordis';
4
+ export type AgentFidelity = 'native' | 'structured' | 'derived' | 'opaque-terminal';
5
+ export type AgentStatus = 'idle' | 'running' | 'waiting' | 'stopping' | 'stopped' | 'failed';
6
+ /** Canonical logical worker identity in the ACRYL room. */
7
+ export type AcrWorkerId = string;
8
+ /** Identity for one live in-process agent, protocol connection, SDK run, or CLI process. */
9
+ export type AgentRuntimeId = string;
10
+ /** Adapter-scoped opaque vendor session reference. */
11
+ export type ProviderSessionRef = string;
12
+ /** Generation-scoped truthful provider capabilities. */
13
+ export type AgentCapability = 'agent.start' | 'agent.stop' | 'agent.send' | 'agent.cancel' | 'agent.resume' | 'agent.snapshot' | 'output.structured' | 'output.terminal' | 'tool.calls' | 'approval.respond';
14
+ export interface AgentWorkspace {
15
+ readonly identity: string;
16
+ readonly cwd: string;
17
+ }
18
+ /** One bound worker as projected by the control service. */
19
+ export interface AgentSnapshot {
20
+ readonly workerId: AcrWorkerId;
21
+ readonly runtimeId: AgentRuntimeId | null;
22
+ readonly providerId: string;
23
+ readonly providerSessionRef: ProviderSessionRef | null;
24
+ readonly harnessSessionId: string | null;
25
+ readonly workspace: AgentWorkspace | null;
26
+ readonly capabilities: readonly AgentCapability[];
27
+ readonly fidelity: AgentFidelity;
28
+ readonly status: AgentStatus;
29
+ }
30
+ export type AgentCommandKind = 'start' | 'send' | 'cancel' | 'stop' | 'resume';
31
+ export interface AgentCommand {
32
+ readonly kind: AgentCommandKind;
33
+ readonly payload: unknown;
34
+ }
35
+ export interface CommandReceipt {
36
+ readonly accepted: true;
37
+ readonly workerId: AcrWorkerId;
38
+ readonly runtimeId: AgentRuntimeId;
39
+ readonly kind: AgentCommandKind;
40
+ readonly result: unknown;
41
+ }
42
+ export interface AttachAgentRequest {
43
+ readonly workerId: AcrWorkerId;
44
+ readonly providerId: string;
45
+ readonly workspace: AgentWorkspace | null;
46
+ readonly capabilities: readonly AgentCapability[];
47
+ readonly fidelity: AgentFidelity;
48
+ readonly providerSessionRef?: ProviderSessionRef;
49
+ readonly harnessSessionId?: string;
50
+ }
51
+ export interface AgentScope {
52
+ readonly workerId?: AcrWorkerId;
53
+ readonly providerId?: string;
54
+ }
55
+ /** The live runtime a transport opened for one worker: what makes a bound worker dispatchable. */
56
+ export interface AgentTransportRuntime {
57
+ readonly runtimeId: AgentRuntimeId;
58
+ readonly providerSessionRef?: ProviderSessionRef;
59
+ }
60
+ /** Transport seam a provider delegates to; vendor SDKs, protocols and CLIs plug in here. */
61
+ export interface AgentTransport {
62
+ /**
63
+ * Bring up the vendor runtime for one worker (a process, a connection) and name it. Without `open` a provider binds no runtime, and
64
+ * every dispatch is refused until something else does.
65
+ */
66
+ open?(request: AttachAgentRequest, signal?: AbortSignal): Promise<AgentTransportRuntime>;
67
+ execute(binding: AgentSnapshot, command: AgentCommand, signal?: AbortSignal): Promise<unknown>;
68
+ /** Release every runtime this transport opened (the provider's owner is unloading). */
69
+ dispose?(): Promise<void>;
70
+ }
71
+ /** One registered adapter. Registration is a reversible effect. */
72
+ export interface AgentProvider {
73
+ readonly id: string;
74
+ readonly fidelity: AgentFidelity;
75
+ readonly capabilities: readonly AgentCapability[];
76
+ attach(request: AttachAgentRequest): Promise<AgentSnapshot>;
77
+ execute(binding: AgentSnapshot, command: AgentCommand, signal?: AbortSignal): Promise<unknown>;
78
+ }
79
+ export interface AcrAgentControl {
80
+ registerProvider(owner: Context, provider: AgentProvider): void;
81
+ attach(request: AttachAgentRequest): Promise<AgentSnapshot>;
82
+ dispatch(workerId: AcrWorkerId, command: AgentCommand, signal?: AbortSignal): Promise<CommandReceipt>;
83
+ snapshot(scope?: AgentScope): Promise<readonly AgentSnapshot[]>;
84
+ }
85
+ export type AcrAgentControlErrorCode = 'unknown-provider' | 'unknown-worker' | 'capability-rejected' | 'runtime-collision' | 'session-collision' | 'cancelled' | 'transport-unavailable' | 'worker-busy';
86
+ export declare class AcrAgentControlError extends Error {
87
+ readonly code: AcrAgentControlErrorCode;
88
+ constructor(code: AcrAgentControlErrorCode, message: string);
89
+ }
90
+ declare module '@deepseek-ai/cordis' {
91
+ interface Context {
92
+ acrAgentControl: AcrAgentControl;
93
+ }
94
+ }
95
+ export declare class AcrAgentControlService extends Service implements AcrAgentControl {
96
+ private readonly providers;
97
+ private readonly bindings;
98
+ constructor(ctx: Context);
99
+ registerProvider(owner: Context, provider: AgentProvider): void;
100
+ attach(request: AttachAgentRequest): Promise<AgentSnapshot>;
101
+ dispatch(workerId: AcrWorkerId, command: AgentCommand, signal?: AbortSignal): Promise<CommandReceipt>;
102
+ snapshot(scope?: AgentScope): Promise<readonly AgentSnapshot[]>;
103
+ }
104
+ export default AcrAgentControlService;
@@ -0,0 +1,7 @@
1
+ /** ACP protocol provider (structured fidelity). */
2
+ import type { AgentTransport } from '../agent-control.ts';
3
+ export declare function acpProvider(transport?: AgentTransport): {
4
+ name: string;
5
+ inject: readonly ["acrAgentControl"];
6
+ apply(ctx: import("@deepseek-ai/cordis").Context): void;
7
+ };
@@ -0,0 +1,13 @@
1
+ /** Truthful generation-scoped capability declarations per provider kind. */
2
+ import type { AgentCapability, AgentFidelity } from '../agent-control.ts';
3
+ export type AgentProviderKind = 'dsh-native' | 'codex' | 'claude' | 'acp';
4
+ export interface ProviderCapabilityProfile {
5
+ readonly kind: AgentProviderKind;
6
+ readonly fidelity: AgentFidelity;
7
+ readonly capabilities: readonly AgentCapability[];
8
+ }
9
+ /**
10
+ * Declared capability sets. A provider must only claim what its transport can
11
+ * truthfully support; unsupported commands are rejected before dispatch.
12
+ */
13
+ export declare const PROVIDER_CAPABILITIES: Readonly<Record<AgentProviderKind, ProviderCapabilityProfile>>;
@@ -0,0 +1,7 @@
1
+ /** Claude provider (structured fidelity). */
2
+ import type { AgentTransport } from '../agent-control.ts';
3
+ export declare function claudeProvider(transport?: AgentTransport): {
4
+ name: string;
5
+ inject: readonly ["acrAgentControl"];
6
+ apply(ctx: import("@deepseek-ai/cordis").Context): void;
7
+ };
@@ -0,0 +1,7 @@
1
+ /** Codex CLI provider (structured fidelity). */
2
+ import type { AgentTransport } from '../agent-control.ts';
3
+ export declare function codexProvider(transport?: AgentTransport): {
4
+ name: string;
5
+ inject: readonly ["acrAgentControl"];
6
+ apply(ctx: import("@deepseek-ai/cordis").Context): void;
7
+ };
@@ -0,0 +1,7 @@
1
+ /** Harness-native agent provider (full capability profile, native fidelity). */
2
+ import type { AgentTransport } from '../agent-control.ts';
3
+ export declare function dshNativeProvider(transport?: AgentTransport): {
4
+ name: string;
5
+ inject: readonly ["acrAgentControl"];
6
+ apply(ctx: import("@deepseek-ai/cordis").Context): void;
7
+ };
@@ -0,0 +1,17 @@
1
+ /** Shared provider plugin factory: registers a capability-declaring adapter. */
2
+ import type { Context } from '@deepseek-ai/cordis';
3
+ import { type AgentTransport } from '../agent-control.ts';
4
+ import { type AgentProviderKind } from './capabilities.ts';
5
+ export interface ProviderPluginOptions {
6
+ readonly kind: AgentProviderKind;
7
+ readonly transport?: AgentTransport;
8
+ }
9
+ /**
10
+ * Create a provider plugin for one vendor. The transport is the Phase 8 seam;
11
+ * until one is supplied, `execute` rejects honestly with `transport-unavailable`.
12
+ */
13
+ export declare function createProviderPlugin(options: ProviderPluginOptions): {
14
+ name: string;
15
+ inject: readonly ["acrAgentControl"];
16
+ apply(ctx: Context): void;
17
+ };
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Claude Code over its own `stream-json` protocol: one long-lived `claude -p` process per worker, one JSON object per line each way.
3
+ * This is the structured transport behind the `claude` provider (fidelity `structured`): a user message in, assistant text and a final
4
+ * `result` out, a control request to interrupt, stdin closed to stop. No vendor SDK and no other ACRYL dependency; the process is the
5
+ * runtime, so the transport owns its whole life (`dispose` ends every child).
6
+ *
7
+ * Observed on Claude Code 2.1.288: the process stays silent until the first user message (the `system` `init` event, which carries
8
+ * the session id, arrives with the first turn, not at spawn); hook and rate-limit events are interleaved and ignored here.
9
+ */
10
+ import { type ChildProcessWithoutNullStreams, type SpawnOptionsWithoutStdio } from 'node:child_process';
11
+ import { type AgentCommand, type AgentSnapshot, type AgentTransport, type AgentTransportRuntime, type AttachAgentRequest } from '../agent-control.ts';
12
+ export interface ClaudeStreamTransportOptions {
13
+ /** The executable. Defaults to `claude` on the PATH. */
14
+ readonly command?: string;
15
+ /**
16
+ * Extra arguments for every process, after the protocol flags. Defaults to read-only work: Claude Code asks for approval before it edits or
17
+ * runs anything, and a headless process cannot answer, so such calls are refused. Pass `--permission-mode` or `--allowedTools` to widen it.
18
+ * A function is asked at each attach, for arguments that only exist once the host is up (an MCP config naming this host's own address).
19
+ */
20
+ readonly args?: readonly string[] | (() => readonly string[] | Promise<readonly string[]>);
21
+ readonly env?: NodeJS.ProcessEnv;
22
+ /** Spawn seam for tests. */
23
+ readonly spawn?: (command: string, args: readonly string[], options: SpawnOptionsWithoutStdio) => ChildProcessWithoutNullStreams;
24
+ /** How long a stopped process may take to exit before it is killed. Default 3000. */
25
+ readonly stopGraceMs?: number;
26
+ /** How long an interrupted turn may take to end before the process is killed. Default 5000. */
27
+ readonly interruptGraceMs?: number;
28
+ }
29
+ export interface ClaudeTurnResult {
30
+ /** The final answer, as Claude Code reports it. */
31
+ readonly text: string;
32
+ readonly isError: boolean;
33
+ readonly sessionId: string | null;
34
+ readonly stopReason: string | null;
35
+ /** Every assistant text block of the turn, in order. */
36
+ readonly assistantText: readonly string[];
37
+ }
38
+ export declare class ClaudeStreamTransport implements AgentTransport {
39
+ private readonly options;
40
+ private readonly runs;
41
+ private requestCounter;
42
+ constructor(options?: ClaudeStreamTransportOptions);
43
+ open(request: AttachAgentRequest): Promise<AgentTransportRuntime>;
44
+ execute(binding: AgentSnapshot, command: AgentCommand, signal?: AbortSignal): Promise<unknown>;
45
+ dispose(): Promise<void>;
46
+ private send;
47
+ private interrupt;
48
+ private stop;
49
+ private write;
50
+ private onData;
51
+ private onLine;
52
+ private fail;
53
+ }
54
+ /** Convenience for the common case: the transport with its options. */
55
+ export declare function createClaudeStreamTransport(options?: ClaudeStreamTransportOptions): ClaudeStreamTransport;
@@ -0,0 +1,43 @@
1
+ /** Bounded, host-neutral projection of native Cordis runtime state. */
2
+ import type { Context } from '@deepseek-ai/cordis';
3
+ export type ArchitecturePlane = 'host' | 'client' | 'tui';
4
+ export type ArchitectureFiberPhase = 'pending' | 'loading' | 'active' | 'failed' | 'unloading';
5
+ export type ArchitectureDependencyStatus = 'resolved' | 'available' | 'missing';
6
+ /** One currently owned, labeled Cordis effect and its nested ownership. */
7
+ export interface ArchitectureEffectView {
8
+ readonly label: string;
9
+ readonly children: readonly ArchitectureEffectView[];
10
+ }
11
+ /** One native `inject` declaration and its current resolution state. */
12
+ export interface ArchitectureDependencyView {
13
+ readonly name: string;
14
+ readonly status: ArchitectureDependencyStatus;
15
+ readonly providerFiberUid: number | null;
16
+ }
17
+ /** One live Cordis Fiber. Repeated mounts remain distinct by UID. */
18
+ export interface ArchitectureFiberView {
19
+ readonly uid: number;
20
+ readonly name: string;
21
+ readonly phase: ArchitectureFiberPhase;
22
+ readonly parentUid: number | null;
23
+ readonly loaderEntryId: string | null;
24
+ readonly moduleName: string | null;
25
+ readonly dependencies: readonly ArchitectureDependencyView[];
26
+ readonly providedServices: readonly string[];
27
+ readonly effects: readonly ArchitectureEffectView[];
28
+ }
29
+ /** One live service implementation and its owning Fiber. */
30
+ export interface ArchitectureServiceView {
31
+ readonly name: string;
32
+ readonly providerFiberUid: number;
33
+ readonly providerName: string;
34
+ readonly providerPhase: ArchitectureFiberPhase;
35
+ }
36
+ /** Point-in-time native graph for one independent Cordis context. */
37
+ export interface RuntimeArchitectureSnapshot {
38
+ readonly plane: ArchitecturePlane;
39
+ readonly fibers: readonly ArchitectureFiberView[];
40
+ readonly services: readonly ArchitectureServiceView[];
41
+ }
42
+ /** Inspect one Cordis context without caching or inventing cross-plane identity. */
43
+ export declare function projectRuntimeArchitecture(ctx: Context, plane: ArchitecturePlane): RuntimeArchitectureSnapshot;