@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
package/lib/index.js ADDED
@@ -0,0 +1,1457 @@
1
+ import { Context, Service, Service as Service$1 } from "@deepseek-ai/cordis";
2
+ import { spawn } from "node:child_process";
3
+ //#region src/agent/agent-control.ts
4
+ var AcrAgentControlError = class extends Error {
5
+ code;
6
+ constructor(code, message) {
7
+ super(message);
8
+ this.code = code;
9
+ this.name = "AcrAgentControlError";
10
+ }
11
+ };
12
+ const COMMAND_CAPABILITY = {
13
+ start: "agent.start",
14
+ send: "agent.send",
15
+ cancel: "agent.cancel",
16
+ stop: "agent.stop",
17
+ resume: "agent.resume"
18
+ };
19
+ var AcrAgentControlService = class extends Service$1 {
20
+ providers = /* @__PURE__ */ new Map();
21
+ bindings = /* @__PURE__ */ new Map();
22
+ constructor(ctx) {
23
+ super(ctx, "acrAgentControl");
24
+ }
25
+ registerProvider(owner, provider) {
26
+ if (provider.id.trim() === "") throw new Error("agent provider id must not be empty");
27
+ owner.effect(() => {
28
+ if (this.providers.has(provider.id)) throw new Error(`duplicate agent provider id: ${provider.id}`);
29
+ this.providers.set(provider.id, provider);
30
+ return () => {
31
+ if (this.providers.get(provider.id) === provider) this.providers.delete(provider.id);
32
+ };
33
+ }, `acryl-control: agent provider ${provider.id}`);
34
+ }
35
+ async attach(request) {
36
+ const provider = this.providers.get(request.providerId);
37
+ if (provider === void 0) throw new AcrAgentControlError("unknown-provider", `Unknown agent provider ${request.providerId}.`);
38
+ const declared = new Set(provider.capabilities);
39
+ for (const capability of request.capabilities) if (!declared.has(capability)) throw new AcrAgentControlError("capability-rejected", `Provider ${request.providerId} does not declare capability ${capability}.`);
40
+ const binding = await provider.attach(request);
41
+ for (const existing of this.bindings.values()) {
42
+ if (binding.runtimeId !== null && binding.runtimeId === existing.runtimeId) throw new AcrAgentControlError("runtime-collision", `Runtime ${binding.runtimeId} is already bound.`);
43
+ if (binding.providerSessionRef !== null && binding.providerSessionRef === existing.providerSessionRef && binding.providerId !== existing.providerId) throw new AcrAgentControlError("session-collision", `Provider session ${binding.providerSessionRef} is claimed by another provider.`);
44
+ }
45
+ this.bindings.set(binding.workerId, binding);
46
+ return binding;
47
+ }
48
+ async dispatch(workerId, command, signal) {
49
+ const binding = this.bindings.get(workerId);
50
+ if (binding === void 0) throw new AcrAgentControlError("unknown-worker", `Unknown agent worker ${workerId}.`);
51
+ const required = COMMAND_CAPABILITY[command.kind];
52
+ if (!binding.capabilities.includes(required)) throw new AcrAgentControlError("capability-rejected", `Worker ${workerId} does not declare capability ${required}.`);
53
+ if (signal?.aborted) throw new AcrAgentControlError("cancelled", `Command ${command.kind} was cancelled.`);
54
+ const provider = this.providers.get(binding.providerId);
55
+ if (provider === void 0) throw new AcrAgentControlError("unknown-provider", `Unknown agent provider ${binding.providerId}.`);
56
+ if (binding.runtimeId === null) throw new AcrAgentControlError("unknown-worker", `Worker ${workerId} has no live runtime.`);
57
+ const result = await provider.execute(binding, command, signal);
58
+ return Object.freeze({
59
+ accepted: true,
60
+ workerId,
61
+ runtimeId: binding.runtimeId,
62
+ kind: command.kind,
63
+ result
64
+ });
65
+ }
66
+ async snapshot(scope) {
67
+ const bindings = [...this.bindings.values()];
68
+ if (scope === void 0) return Object.freeze(bindings);
69
+ return Object.freeze(bindings.filter((binding) => {
70
+ if (scope.workerId !== void 0 && binding.workerId !== scope.workerId) return false;
71
+ if (scope.providerId !== void 0 && binding.providerId !== scope.providerId) return false;
72
+ return true;
73
+ }));
74
+ }
75
+ };
76
+ //#endregion
77
+ //#region src/agent/transports/claude-stream.ts
78
+ /**
79
+ * Claude Code over its own `stream-json` protocol: one long-lived `claude -p` process per worker, one JSON object per line each way.
80
+ * This is the structured transport behind the `claude` provider (fidelity `structured`): a user message in, assistant text and a final
81
+ * `result` out, a control request to interrupt, stdin closed to stop. No vendor SDK and no other ACRYL dependency; the process is the
82
+ * runtime, so the transport owns its whole life (`dispose` ends every child).
83
+ *
84
+ * Observed on Claude Code 2.1.288: the process stays silent until the first user message (the `system` `init` event, which carries
85
+ * the session id, arrives with the first turn, not at spawn); hook and rate-limit events are interleaved and ignored here.
86
+ */
87
+ const PROTOCOL_ARGS = [
88
+ "-p",
89
+ "--input-format",
90
+ "stream-json",
91
+ "--output-format",
92
+ "stream-json",
93
+ "--verbose"
94
+ ];
95
+ function isRecord(value) {
96
+ return typeof value === "object" && value !== null && !Array.isArray(value);
97
+ }
98
+ var ClaudeStreamTransport = class {
99
+ options;
100
+ runs = /* @__PURE__ */ new Map();
101
+ requestCounter = 0;
102
+ constructor(options = {}) {
103
+ this.options = options;
104
+ }
105
+ async open(request) {
106
+ const args = [
107
+ ...PROTOCOL_ARGS,
108
+ ...typeof this.options.args === "function" ? await this.options.args() : this.options.args ?? [],
109
+ ...request.providerSessionRef === void 0 ? [] : ["--resume", request.providerSessionRef]
110
+ ];
111
+ const spawnProcess = this.options.spawn ?? spawn;
112
+ let child;
113
+ try {
114
+ child = spawnProcess(this.options.command ?? "claude", args, {
115
+ ...request.workspace === null ? {} : { cwd: request.workspace.cwd },
116
+ ...this.options.env === void 0 ? {} : { env: this.options.env },
117
+ stdio: "pipe"
118
+ });
119
+ } catch (cause) {
120
+ throw new AcrAgentControlError("transport-unavailable", `Could not start Claude Code: ${cause instanceof Error ? cause.message : String(cause)}`);
121
+ }
122
+ const started = await new Promise((resolve) => {
123
+ child.once("error", resolve);
124
+ child.once("spawn", () => {
125
+ resolve(void 0);
126
+ });
127
+ });
128
+ if (started !== void 0) throw new AcrAgentControlError("transport-unavailable", `Could not start Claude Code: ${started.message}`);
129
+ const runtimeId = `claude-${String(child.pid)}`;
130
+ const run = {
131
+ child,
132
+ buffer: "",
133
+ sessionId: request.providerSessionRef ?? null,
134
+ turn: null,
135
+ closed: false,
136
+ exited: new Promise((resolve) => {
137
+ child.once("close", () => {
138
+ resolve();
139
+ });
140
+ })
141
+ };
142
+ child.stdout.setEncoding("utf8");
143
+ child.stdout.on("data", (chunk) => {
144
+ this.onData(run, chunk);
145
+ });
146
+ child.stderr.resume();
147
+ child.stdin.on("error", () => {});
148
+ child.once("error", (cause) => {
149
+ this.fail(run, cause);
150
+ });
151
+ child.once("close", (code, signal) => {
152
+ run.closed = true;
153
+ this.runs.delete(runtimeId);
154
+ this.fail(run, new AcrAgentControlError("transport-unavailable", `Claude Code exited (${signal ?? String(code)}) before the turn ended.`));
155
+ });
156
+ this.runs.set(runtimeId, run);
157
+ return {
158
+ runtimeId,
159
+ ...request.providerSessionRef === void 0 ? {} : { providerSessionRef: request.providerSessionRef }
160
+ };
161
+ }
162
+ async execute(binding, command, signal) {
163
+ const run = binding.runtimeId === null ? void 0 : this.runs.get(binding.runtimeId);
164
+ if (run === void 0 || run.closed) throw new AcrAgentControlError("transport-unavailable", `Claude Code runtime ${String(binding.runtimeId)} is not running.`);
165
+ switch (command.kind) {
166
+ case "start": return {
167
+ runtimeId: binding.runtimeId,
168
+ sessionId: run.sessionId
169
+ };
170
+ case "send": return this.send(run, command.payload, signal);
171
+ case "cancel":
172
+ this.interrupt(run);
173
+ return { interrupted: run.turn !== null };
174
+ case "stop":
175
+ await this.stop(run);
176
+ return { stopped: true };
177
+ case "resume": throw new AcrAgentControlError("capability-rejected", "Resume is done by attaching with the session id (providerSessionRef).");
178
+ }
179
+ }
180
+ async dispose() {
181
+ await Promise.all([...this.runs.values()].map((run) => this.stop(run)));
182
+ }
183
+ send(run, payload, signal) {
184
+ const text = typeof payload === "string" ? payload : isRecord(payload) && typeof payload.text === "string" ? payload.text : void 0;
185
+ if (text === void 0 || text === "") throw new AcrAgentControlError("capability-rejected", "A send needs a text: a string or { text }.");
186
+ if (run.turn !== null) throw new AcrAgentControlError("worker-busy", "Claude Code is still answering the previous message.");
187
+ return new Promise((resolve, reject) => {
188
+ const onAbort = () => {
189
+ this.interrupt(run);
190
+ };
191
+ run.turn = {
192
+ assistantText: [],
193
+ resolve: (result) => {
194
+ signal?.removeEventListener("abort", onAbort);
195
+ resolve(result);
196
+ },
197
+ reject: (cause) => {
198
+ signal?.removeEventListener("abort", onAbort);
199
+ reject(cause);
200
+ }
201
+ };
202
+ if (signal !== void 0) {
203
+ if (signal.aborted) {
204
+ run.turn = null;
205
+ reject(new AcrAgentControlError("cancelled", "The send was cancelled."));
206
+ return;
207
+ }
208
+ signal.addEventListener("abort", onAbort, { once: true });
209
+ }
210
+ this.write(run, {
211
+ type: "user",
212
+ message: {
213
+ role: "user",
214
+ content: [{
215
+ type: "text",
216
+ text
217
+ }]
218
+ }
219
+ });
220
+ }).then((result) => {
221
+ if (signal?.aborted === true) throw new AcrAgentControlError("cancelled", "The send was cancelled.");
222
+ return result;
223
+ });
224
+ }
225
+ interrupt(run) {
226
+ if (run.turn === null || run.closed) return;
227
+ this.write(run, {
228
+ type: "control_request",
229
+ request_id: `acryl-${String(++this.requestCounter)}`,
230
+ request: { subtype: "interrupt" }
231
+ });
232
+ const turn = run.turn;
233
+ setTimeout(() => {
234
+ if (run.turn === turn && !run.closed) run.child.kill("SIGKILL");
235
+ }, this.options.interruptGraceMs ?? 5e3).unref();
236
+ }
237
+ async stop(run) {
238
+ if (run.closed) return;
239
+ run.child.stdin.end();
240
+ const timer = setTimeout(() => {
241
+ if (!run.closed) run.child.kill("SIGTERM");
242
+ }, this.options.stopGraceMs ?? 3e3);
243
+ timer.unref();
244
+ await run.exited;
245
+ clearTimeout(timer);
246
+ }
247
+ write(run, message) {
248
+ run.child.stdin.write(`${JSON.stringify(message)}\n`);
249
+ }
250
+ onData(run, chunk) {
251
+ run.buffer += chunk;
252
+ let newline = run.buffer.indexOf("\n");
253
+ while (newline >= 0) {
254
+ const line = run.buffer.slice(0, newline).trim();
255
+ run.buffer = run.buffer.slice(newline + 1);
256
+ if (line !== "") this.onLine(run, line);
257
+ newline = run.buffer.indexOf("\n");
258
+ }
259
+ }
260
+ onLine(run, line) {
261
+ let event;
262
+ try {
263
+ event = JSON.parse(line);
264
+ } catch {
265
+ return;
266
+ }
267
+ if (!isRecord(event)) return;
268
+ if (typeof event.session_id === "string") run.sessionId = event.session_id;
269
+ const turn = run.turn;
270
+ if (turn === null) return;
271
+ if (event.type === "assistant" && isRecord(event.message) && Array.isArray(event.message.content)) {
272
+ for (const block of event.message.content) if (isRecord(block) && block.type === "text" && typeof block.text === "string") turn.assistantText.push(block.text);
273
+ } else if (event.type === "result") {
274
+ run.turn = null;
275
+ turn.resolve({
276
+ text: typeof event.result === "string" ? event.result : turn.assistantText.join("\n"),
277
+ isError: event.is_error === true,
278
+ sessionId: run.sessionId,
279
+ stopReason: typeof event.stop_reason === "string" ? event.stop_reason : null,
280
+ assistantText: Object.freeze([...turn.assistantText])
281
+ });
282
+ }
283
+ }
284
+ fail(run, cause) {
285
+ const turn = run.turn;
286
+ if (turn === null) return;
287
+ run.turn = null;
288
+ turn.reject(cause);
289
+ }
290
+ };
291
+ /** Convenience for the common case: the transport with its options. */
292
+ function createClaudeStreamTransport(options = {}) {
293
+ return new ClaudeStreamTransport(options);
294
+ }
295
+ //#endregion
296
+ //#region src/agent/providers/capabilities.ts
297
+ function capabilities(...items) {
298
+ return Object.freeze(items);
299
+ }
300
+ /**
301
+ * Declared capability sets. A provider must only claim what its transport can
302
+ * truthfully support; unsupported commands are rejected before dispatch.
303
+ */
304
+ const PROVIDER_CAPABILITIES = {
305
+ "dsh-native": Object.freeze({
306
+ kind: "dsh-native",
307
+ fidelity: "native",
308
+ capabilities: capabilities("agent.start", "agent.stop", "agent.send", "agent.cancel", "agent.resume", "agent.snapshot", "output.structured", "tool.calls", "approval.respond")
309
+ }),
310
+ codex: Object.freeze({
311
+ kind: "codex",
312
+ fidelity: "structured",
313
+ capabilities: capabilities("agent.start", "agent.stop", "agent.send", "agent.cancel", "agent.snapshot", "output.structured", "tool.calls")
314
+ }),
315
+ claude: Object.freeze({
316
+ kind: "claude",
317
+ fidelity: "structured",
318
+ capabilities: capabilities("agent.start", "agent.stop", "agent.send", "agent.cancel", "agent.snapshot", "output.structured", "tool.calls")
319
+ }),
320
+ acp: Object.freeze({
321
+ kind: "acp",
322
+ fidelity: "structured",
323
+ capabilities: capabilities("agent.start", "agent.stop", "agent.send", "agent.cancel", "agent.resume", "agent.snapshot", "output.structured", "tool.calls")
324
+ })
325
+ };
326
+ //#endregion
327
+ //#region src/agent/providers/factory.ts
328
+ function snapshotOf(request, runtime) {
329
+ return Object.freeze({
330
+ workerId: request.workerId,
331
+ runtimeId: runtime?.runtimeId ?? null,
332
+ providerId: request.providerId,
333
+ providerSessionRef: runtime?.providerSessionRef ?? request.providerSessionRef ?? null,
334
+ harnessSessionId: request.harnessSessionId ?? null,
335
+ workspace: request.workspace,
336
+ capabilities: Object.freeze([...request.capabilities]),
337
+ fidelity: request.fidelity,
338
+ status: "idle"
339
+ });
340
+ }
341
+ /**
342
+ * Create a provider plugin for one vendor. The transport is the Phase 8 seam;
343
+ * until one is supplied, `execute` rejects honestly with `transport-unavailable`.
344
+ */
345
+ function createProviderPlugin(options) {
346
+ const profile = PROVIDER_CAPABILITIES[options.kind];
347
+ return {
348
+ name: `acryl-agent-${profile.kind}`,
349
+ inject: ["acrAgentControl"],
350
+ apply(ctx) {
351
+ const provider = {
352
+ id: profile.kind,
353
+ fidelity: profile.fidelity,
354
+ capabilities: profile.capabilities,
355
+ async attach(request) {
356
+ return snapshotOf(request, await options.transport?.open?.(request));
357
+ },
358
+ async execute(binding, command, signal) {
359
+ if (options.transport === void 0) throw new AcrAgentControlError("transport-unavailable", `Provider ${profile.kind} has no transport wired.`);
360
+ return options.transport.execute(binding, command, signal);
361
+ }
362
+ };
363
+ if (options.transport?.dispose !== void 0) {
364
+ const transport = options.transport;
365
+ ctx.effect(() => () => {
366
+ transport.dispose?.();
367
+ }, `acryl-control: ${profile.kind} transport`);
368
+ }
369
+ ctx.acrAgentControl.registerProvider(ctx, provider);
370
+ }
371
+ };
372
+ }
373
+ //#endregion
374
+ //#region src/agent/providers/dsh-native.ts
375
+ function dshNativeProvider(transport) {
376
+ return createProviderPlugin({
377
+ kind: "dsh-native",
378
+ ...transport === void 0 ? {} : { transport }
379
+ });
380
+ }
381
+ //#endregion
382
+ //#region src/agent/providers/codex.ts
383
+ function codexProvider(transport) {
384
+ return createProviderPlugin({
385
+ kind: "codex",
386
+ ...transport === void 0 ? {} : { transport }
387
+ });
388
+ }
389
+ //#endregion
390
+ //#region src/agent/providers/claude.ts
391
+ function claudeProvider(transport) {
392
+ return createProviderPlugin({
393
+ kind: "claude",
394
+ ...transport === void 0 ? {} : { transport }
395
+ });
396
+ }
397
+ //#endregion
398
+ //#region src/agent/providers/acp.ts
399
+ function acpProvider(transport) {
400
+ return createProviderPlugin({
401
+ kind: "acp",
402
+ ...transport === void 0 ? {} : { transport }
403
+ });
404
+ }
405
+ //#endregion
406
+ //#region src/architecture/projection.ts
407
+ const MAX_FIBERS = 2048;
408
+ const MAX_SERVICES = 4096;
409
+ const MAX_EFFECTS_PER_FIBER = 512;
410
+ const MAX_EFFECT_DEPTH = 12;
411
+ const MAX_LABEL_LENGTH = 512;
412
+ const FIBER_PHASE$1 = {
413
+ 0: "pending",
414
+ 1: "loading",
415
+ 2: "active",
416
+ 3: "failed",
417
+ 4: null,
418
+ 5: "unloading"
419
+ };
420
+ function phaseOf$1(fiber) {
421
+ return FIBER_PHASE$1[fiber.state] ?? "pending";
422
+ }
423
+ function effectView(meta, depth, budget) {
424
+ if (depth > MAX_EFFECT_DEPTH) throw new Error("Cordis effect tree exceeds the inspection depth limit");
425
+ if (--budget.remaining < 0) throw new Error("Cordis Fiber exceeds the inspection effect limit");
426
+ if (typeof meta.label !== "string" || meta.label.length > MAX_LABEL_LENGTH) throw new Error("Cordis effect label exceeds the inspection limit");
427
+ return Object.freeze({
428
+ label: meta.label,
429
+ children: Object.freeze(meta.children.map((child) => effectView(child, depth + 1, budget)))
430
+ });
431
+ }
432
+ function liveServices(ctx) {
433
+ const store = ctx.root.reflect.store;
434
+ const services = [];
435
+ for (const key of Object.getOwnPropertySymbols(store)) {
436
+ const impl = store[key];
437
+ if (impl !== void 0 && impl.fiber.uid !== null) services.push(impl);
438
+ }
439
+ return services;
440
+ }
441
+ function fibers(ctx) {
442
+ const found = /* @__PURE__ */ new Set([ctx.root.fiber]);
443
+ for (const runtime of ctx.root.registry.values()) for (const fiber of runtime.fibers) if (fiber.uid !== null) found.add(fiber);
444
+ const result = [...found].sort((left, right) => (left.uid ?? 0) - (right.uid ?? 0));
445
+ if (result.length > MAX_FIBERS) throw new Error("Cordis context exceeds the inspection Fiber limit");
446
+ return result;
447
+ }
448
+ function dependencyView(fiber, name) {
449
+ const resolved = fiber.store?.[name];
450
+ if (resolved !== void 0 && resolved.fiber.uid !== null) return Object.freeze({
451
+ name,
452
+ status: "resolved",
453
+ providerFiberUid: resolved.fiber.uid
454
+ });
455
+ const status = fiber.ctx.get(name) === void 0 ? "missing" : "available";
456
+ return Object.freeze({
457
+ name,
458
+ status,
459
+ providerFiberUid: null
460
+ });
461
+ }
462
+ function moduleNameOf(fiber) {
463
+ const name = fiber.entry?.options?.name;
464
+ return typeof name === "string" && name.length > 0 && name.length <= MAX_LABEL_LENGTH ? name : null;
465
+ }
466
+ /** Inspect one Cordis context without caching or inventing cross-plane identity. */
467
+ function projectRuntimeArchitecture(ctx, plane) {
468
+ const allFibers = fibers(ctx);
469
+ const services = liveServices(ctx);
470
+ if (services.length > MAX_SERVICES) throw new Error("Cordis context exceeds the inspection service limit");
471
+ const servicesByFiber = /* @__PURE__ */ new Map();
472
+ for (const impl of services) {
473
+ const names = servicesByFiber.get(impl.fiber) ?? [];
474
+ names.push(impl.name);
475
+ servicesByFiber.set(impl.fiber, names);
476
+ }
477
+ const loader = ctx.get("loader");
478
+ const fiberViews = allFibers.map((fiber) => {
479
+ const parent = fiber.parent.fiber;
480
+ const budget = { remaining: MAX_EFFECTS_PER_FIBER };
481
+ return Object.freeze({
482
+ uid: fiber.uid ?? 0,
483
+ name: fiber.name,
484
+ phase: phaseOf$1(fiber),
485
+ parentUid: parent === fiber ? null : parent.uid,
486
+ loaderEntryId: loader?.locate(fiber) ?? null,
487
+ moduleName: moduleNameOf(fiber),
488
+ dependencies: Object.freeze(Object.keys(fiber.inject).sort().map((name) => dependencyView(fiber, name))),
489
+ providedServices: Object.freeze([...servicesByFiber.get(fiber) ?? []].sort()),
490
+ effects: Object.freeze(fiber.getEffects().map((meta) => effectView(meta, 0, budget)))
491
+ });
492
+ });
493
+ const serviceViews = services.map((impl) => Object.freeze({
494
+ name: impl.name,
495
+ providerFiberUid: impl.fiber.uid ?? 0,
496
+ providerName: impl.fiber.name,
497
+ providerPhase: phaseOf$1(impl.fiber)
498
+ })).sort((left, right) => left.name.localeCompare(right.name) || left.providerFiberUid - right.providerFiberUid);
499
+ return Object.freeze({
500
+ plane,
501
+ fibers: Object.freeze(fiberViews),
502
+ services: Object.freeze(serviceViews)
503
+ });
504
+ }
505
+ //#endregion
506
+ //#region src/architecture/provider.ts
507
+ var AcrRuntimeArchitectureService = class extends Service$1 {
508
+ constructor(ctx) {
509
+ super(ctx, "acrRuntimeArchitecture");
510
+ }
511
+ snapshot(plane) {
512
+ return projectRuntimeArchitecture(this.ctx, plane);
513
+ }
514
+ };
515
+ //#endregion
516
+ //#region src/contracts/session.ts
517
+ function record(value) {
518
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
519
+ }
520
+ function nonEmpty(value, message) {
521
+ if (typeof value !== "string" || value.trim() === "") throw new Error(message);
522
+ return value;
523
+ }
524
+ function oneOf(value, values, message) {
525
+ if (typeof value !== "string" || !values.includes(value)) throw new Error(message);
526
+ return value;
527
+ }
528
+ function parseTranscript(value) {
529
+ if (!Array.isArray(value)) throw new Error("invalid ACRYL transcript");
530
+ return Object.freeze(value.map((item) => {
531
+ const source = record(item);
532
+ if (source === void 0) throw new Error("invalid ACRYL transcript item");
533
+ return Object.freeze({
534
+ id: nonEmpty(source.id, "invalid ACRYL transcript id"),
535
+ author: oneOf(source.author, ["user", "assistant"], "invalid ACRYL transcript author"),
536
+ text: nonEmpty(source.text, "invalid ACRYL transcript text")
537
+ });
538
+ }));
539
+ }
540
+ function parseTools(value) {
541
+ if (!Array.isArray(value)) throw new Error("invalid ACRYL tool projections");
542
+ return Object.freeze(value.map((item) => {
543
+ const source = record(item);
544
+ if (source === void 0) throw new Error("invalid ACRYL tool projection");
545
+ return Object.freeze({
546
+ callId: nonEmpty(source.callId, "invalid ACRYL tool call id"),
547
+ name: nonEmpty(source.name, "invalid ACRYL tool name"),
548
+ status: oneOf(source.status, [
549
+ "pending",
550
+ "running",
551
+ "succeeded",
552
+ "failed"
553
+ ], "invalid ACRYL tool status")
554
+ });
555
+ }));
556
+ }
557
+ /** Validate an untrusted control-plane session projection at the boundary. */
558
+ function parseAcrylSessionSnapshot(value) {
559
+ const source = record(value);
560
+ if (source === void 0) throw new Error("invalid ACRYL session snapshot");
561
+ return Object.freeze({
562
+ profile: nonEmpty(source.profile, "invalid ACRYL profile"),
563
+ generationId: nonEmpty(source.generationId, "invalid ACRYL generation id"),
564
+ attachment: oneOf(source.attachment, ["owner", "attached"], "invalid ACRYL attachment mode"),
565
+ sessionId: nonEmpty(source.sessionId, "invalid ACRYL session id"),
566
+ agentStatus: oneOf(source.agentStatus, [
567
+ "idle",
568
+ "running",
569
+ "waiting",
570
+ "failed"
571
+ ], "invalid ACRYL agent status"),
572
+ transcript: parseTranscript(source.transcript),
573
+ tools: parseTools(source.tools)
574
+ });
575
+ }
576
+ //#endregion
577
+ //#region src/credential/projection.ts
578
+ /**
579
+ * The `apiKeyEnv` reference a provider route falls back to when its settings
580
+ * profile names none, e.g. `my-proxy` -> `MY_PROXY_API_KEY`. One rule for every
581
+ * surface (the terminal's `/model` and the Desktop sign-in read the same name).
582
+ */
583
+ function deriveApiKeyRef(route) {
584
+ const upper = route.toUpperCase().replace(/[^A-Z0-9]+/g, "_");
585
+ return `${/^[A-Z_]/.test(upper) ? upper : `P_${upper}`}_API_KEY`;
586
+ }
587
+ /** Read a nested value out of an untyped resolved/raw settings section. */
588
+ function getAtPath(value, path) {
589
+ let current = value;
590
+ for (const key of path) {
591
+ if (current === null || typeof current !== "object") return void 0;
592
+ current = current[key];
593
+ }
594
+ return current;
595
+ }
596
+ /**
597
+ * Whether one route can answer a request now: live in `ctx.llm` and holding a credential (the settings profile's
598
+ * `apiKeyEnv` secret, or a sign-in's own record). The same credential rule as {@link computeCredentialProjection}, for
599
+ * one route and without reading any secret or model list.
600
+ */
601
+ async function isRouteUsable(services, provider, options = {}) {
602
+ if (!services.llm.listProviders().some((entry) => entry.id === provider)) return false;
603
+ const entry = services.llm.listConfigurableProviders().find((candidate) => candidate.provider === provider);
604
+ if (entry === void 0) return true;
605
+ const descriptor = services.settings.describe({ redactSecrets: true }).find((candidate) => candidate.ns === entry.settingsNs);
606
+ const apiKeyRef = (descriptor === void 0 ? void 0 : getAtPath(descriptor.value, entry.settingsPath))?.apiKeyEnv ?? (options.deriveApiKeyRef ?? deriveApiKeyRef)(provider);
607
+ if ((await services.credentials.describe(apiKeyRef)).configured) return true;
608
+ return (await services.credentials.describeRecord(`${options.loginRecordScope ?? "llm-pi-ai"}/${provider}`)).configured;
609
+ }
610
+ /** Compute every provider route's joined credential/settings/live-registration row. */
611
+ async function computeCredentialProjection(services, options) {
612
+ const scope = options.loginRecordScope ?? "llm-pi-ai";
613
+ const configurable = services.llm.listConfigurableProviders();
614
+ const live = new Set(services.llm.listProviders().map((provider) => provider.id));
615
+ const descriptors = services.settings.describe({ redactSecrets: true });
616
+ const byNs = new Map(descriptors.map((descriptor) => [descriptor.ns, descriptor]));
617
+ const rows = [];
618
+ for (const entry of configurable) {
619
+ const descriptor = byNs.get(entry.settingsNs);
620
+ const value = descriptor === void 0 ? void 0 : getAtPath(descriptor.value, entry.settingsPath);
621
+ const userValue = descriptor === void 0 ? void 0 : getAtPath(descriptor.user, entry.settingsPath);
622
+ const apiKeyRef = value?.apiKeyEnv ?? (options.deriveApiKeyRef ?? deriveApiKeyRef)(entry.provider);
623
+ const info = await services.credentials.describe(apiKeyRef);
624
+ const loginRecord = await services.credentials.readRecord?.(`${scope}/${entry.provider}`);
625
+ const authMethod = loginRecord !== void 0 ? loginRecord.kind === "grant" ? "oauth" : "api-key" : info.configured ? "api-key" : void 0;
626
+ const isLive = live.has(entry.provider);
627
+ const models = isLive ? await services.llm.listModels(entry.provider).catch(() => value?.models ?? []) : value?.models ?? [];
628
+ rows.push({
629
+ route: entry.provider,
630
+ displayName: value?.displayName ?? entry.displayName,
631
+ settingsNs: entry.settingsNs,
632
+ settingsPath: entry.settingsPath,
633
+ hasSettingsProfile: userValue !== void 0,
634
+ hasCredential: info.configured || loginRecord !== void 0,
635
+ isLive,
636
+ authMethod,
637
+ api: value?.api,
638
+ baseURL: value?.baseURL,
639
+ apiKeyRef,
640
+ models,
641
+ revision: descriptor?.revision
642
+ });
643
+ }
644
+ return rows;
645
+ }
646
+ //#endregion
647
+ //#region src/credential/route-activation.ts
648
+ function valueAt(value, path) {
649
+ let current = value;
650
+ for (const key of path) {
651
+ if (current === null || typeof current !== "object") return void 0;
652
+ current = current[key];
653
+ }
654
+ return current;
655
+ }
656
+ /** Nest a provider section at its settings path, e.g. `['providers','deepseek']` gives `{ providers: { deepseek: section } }`. */
657
+ function nestAt(path, section) {
658
+ let patch = section;
659
+ for (let index = path.length - 1; index >= 0; index--) patch = { [path[index]]: patch };
660
+ return patch;
661
+ }
662
+ function createRouteActivation(ports) {
663
+ return { async ensureRouteActivated(providerId) {
664
+ const entry = ports.llm.listConfigurableProviders().find((candidate) => candidate.provider === providerId);
665
+ if (entry === void 0) return;
666
+ const descriptor = ports.settings.describe({ redactSecrets: true }).find((candidate) => candidate.ns === entry.settingsNs);
667
+ if (valueAt(descriptor?.user, entry.settingsPath) !== void 0) return;
668
+ await ports.settings.update(entry.settingsNs, nestAt(entry.settingsPath, {}), descriptor?.revision);
669
+ await ports.settled?.();
670
+ } };
671
+ }
672
+ //#endregion
673
+ //#region src/credential/default-model.ts
674
+ /**
675
+ * The model a new session starts on for a provider ACRYL features on its sign-in screen, most preferred first. The
676
+ * installed catalog lists models alphabetically, so its first entry is no recommendation; a provider absent here (or
677
+ * whose preferred ids a catalog update removed) starts on that first entry instead.
678
+ */
679
+ const STARTING_MODELS = {
680
+ anthropic: [
681
+ "claude-sonnet-5-5",
682
+ "claude-sonnet-5",
683
+ "claude-sonnet-4-6"
684
+ ],
685
+ openai: ["gpt-5.5", "gpt-5.4"],
686
+ "openai-codex": ["gpt-5.5"],
687
+ deepseek: ["deepseek-v4-pro", "deepseek-flash"]
688
+ };
689
+ /** The model to start on from a route's catalog, or `undefined` when the route lists none. */
690
+ function startingModel(provider, models) {
691
+ const offered = new Set(models.map((model) => model.id));
692
+ return (STARTING_MODELS[provider] ?? []).find((id) => offered.has(id)) ?? models[0]?.id;
693
+ }
694
+ function createDefaultModelAdoption(ports) {
695
+ return { async adoptIfDefaultUnusable(provider) {
696
+ const current = ports.defaultModel.currentSelection();
697
+ if (current.provider === provider) return;
698
+ if (await ports.isUsable(current.provider)) return;
699
+ const model = startingModel(provider, await ports.listModels(provider));
700
+ if (model === void 0) return;
701
+ await ports.defaultModel.saveSelection({
702
+ provider,
703
+ model
704
+ });
705
+ } };
706
+ }
707
+ //#endregion
708
+ //#region src/authorization/types.ts
709
+ /** The service name of {@link AccountSignInPort}. */
710
+ const ACCOUNT_SIGN_IN_SERVICE = "acrylAccountSignIn";
711
+ /**
712
+ * The key DeepSeek's account flow registers on `ctx.authorization` (`dsh-deepseek-account-platform`). It runs only once
713
+ * DeepSeek's account service has opened an attempt, so a surface never starts it through `begin`.
714
+ */
715
+ const DEEPSEEK_ACCOUNT_FLOW_KEY = "deepseek-account-platform/default";
716
+ //#endregion
717
+ //#region src/authorization/service.ts
718
+ var AuthorizationService = class {
719
+ deps;
720
+ constructor(deps) {
721
+ this.deps = deps;
722
+ }
723
+ async begin(request) {
724
+ const outcome = await this.deps.authorization.begin(request);
725
+ if (outcome.status === "authorized") {
726
+ const slash = request.key.indexOf("/");
727
+ const providerId = slash === -1 ? request.key : request.key.slice(slash + 1);
728
+ if (this.deps.routeActivation !== void 0) await this.deps.routeActivation.ensureRouteActivated(providerId, request.method);
729
+ await this.deps.defaultModel?.adoptIfDefaultUnusable(providerId);
730
+ this.deps.onCredentialChanged(request.key);
731
+ }
732
+ return outcome;
733
+ }
734
+ };
735
+ //#endregion
736
+ //#region src/authorization/attempts.ts
737
+ /** A refused request (unknown attempt, stale prompt): the caller learns what to fix. */
738
+ var SignInAttemptError = class extends Error {
739
+ code;
740
+ constructor(code, message) {
741
+ super(message);
742
+ this.code = code;
743
+ this.name = "SignInAttemptError";
744
+ }
745
+ };
746
+ /**
747
+ * A flow's failure as a person reads it. Provider token endpoints answer with a JSON body that the flows quote whole
748
+ * ("... token exchange failed (401): { "error": { "message": "Could not validate your token. ..." } }"); keep the flow's
749
+ * own lead-in and the provider's sentence, drop the JSON around it.
750
+ */
751
+ function readableFailure(cause) {
752
+ const message = cause instanceof Error ? cause.message.trim() : "";
753
+ if (message === "") return "Sign-in failed.";
754
+ const start = message.indexOf("{");
755
+ if (start === -1) return message;
756
+ let body;
757
+ try {
758
+ body = JSON.parse(message.slice(start));
759
+ } catch {
760
+ return message;
761
+ }
762
+ const record = (value) => typeof value === "object" && value !== null ? value : void 0;
763
+ const said = [
764
+ record(record(body)?.error)?.message,
765
+ record(body)?.error_description,
766
+ record(body)?.message,
767
+ record(body)?.error
768
+ ].find((value) => typeof value === "string" && value.trim() !== "");
769
+ if (typeof said !== "string") return message;
770
+ const lead = message.slice(0, start).trim().replace(/:$/u, "");
771
+ return lead === "" ? said.trim() : `${lead}: ${said.trim()}`;
772
+ }
773
+ var SignInAttempts = class {
774
+ deps;
775
+ live;
776
+ constructor(deps) {
777
+ this.deps = deps;
778
+ }
779
+ /** The latest attempt (running or settled), or undefined before any. */
780
+ current() {
781
+ return this.live?.view;
782
+ }
783
+ /**
784
+ * Start an attempt, withdrawing a running one first (a surface that restarts has abandoned the old conversation).
785
+ * @returns the new attempt, already `running`.
786
+ */
787
+ begin(key, method) {
788
+ if (this.live?.view.phase === "running") this.withdraw(this.live);
789
+ const live = {
790
+ view: {
791
+ id: this.deps.newId(),
792
+ key,
793
+ method,
794
+ phase: "running",
795
+ notices: []
796
+ },
797
+ controller: new AbortController(),
798
+ pending: void 0
799
+ };
800
+ this.live = live;
801
+ this.run(live);
802
+ return live.view;
803
+ }
804
+ /**
805
+ * Answer the question the flow is waiting on.
806
+ * @param promptId - the id of the prompt being answered, as the view showed it.
807
+ * @param value - the typed text or the chosen option id.
808
+ */
809
+ answer(attemptId, promptId, value) {
810
+ const live = this.require(attemptId);
811
+ const pending = live.pending;
812
+ if (pending === void 0 || pending.prompt.id !== promptId) throw new SignInAttemptError("unknown-prompt", "That question is no longer being asked.");
813
+ if (pending.prompt.kind === "select" && !(pending.prompt.options ?? []).some((option) => option.id === value)) throw new SignInAttemptError("invalid-answer", "That is not one of the choices.");
814
+ live.pending = void 0;
815
+ this.show(live, void 0);
816
+ pending.resolve(value);
817
+ return live.view;
818
+ }
819
+ /** Withdraw the attempt; a settled attempt is left as it ended. */
820
+ cancel(attemptId) {
821
+ const live = this.require(attemptId);
822
+ if (live.view.phase === "running") this.withdraw(live);
823
+ return live.view;
824
+ }
825
+ require(attemptId) {
826
+ if (this.live === void 0 || this.live.view.id !== attemptId) throw new SignInAttemptError("unknown-attempt", "That sign-in is no longer current.");
827
+ return this.live;
828
+ }
829
+ update(live, patch) {
830
+ live.view = {
831
+ ...live.view,
832
+ ...patch
833
+ };
834
+ }
835
+ /** Show (or clear) the question the flow waits on. */
836
+ show(live, prompt) {
837
+ const { prompt: _previous, ...rest } = live.view;
838
+ live.view = prompt === void 0 ? rest : {
839
+ ...rest,
840
+ prompt
841
+ };
842
+ }
843
+ /** Stop a running attempt: the flow's pending question is refused, which ends it as cancelled. */
844
+ withdraw(live) {
845
+ live.controller.abort();
846
+ live.pending?.reject(/* @__PURE__ */ new Error("sign-in withdrawn"));
847
+ live.pending = void 0;
848
+ this.show(live, void 0);
849
+ this.update(live, { phase: "cancelled" });
850
+ }
851
+ async run(live) {
852
+ const interaction = {
853
+ notify: (notice) => {
854
+ this.update(live, { notices: [...live.view.notices, notice].slice(-8) });
855
+ },
856
+ prompt: (prompt) => new Promise((resolve, reject) => {
857
+ if (live.controller.signal.aborted || prompt.signal?.aborted === true) {
858
+ reject(/* @__PURE__ */ new Error("sign-in withdrawn"));
859
+ return;
860
+ }
861
+ const shown = {
862
+ id: this.deps.newId(),
863
+ kind: prompt.kind,
864
+ message: prompt.message,
865
+ ...prompt.placeholder === void 0 ? {} : { placeholder: prompt.placeholder },
866
+ ...prompt.options === void 0 ? {} : { options: prompt.options.map((option) => ({
867
+ id: option.id,
868
+ label: option.label,
869
+ ...option.description === void 0 ? {} : { description: option.description }
870
+ })) }
871
+ };
872
+ live.pending = {
873
+ prompt: shown,
874
+ resolve,
875
+ reject
876
+ };
877
+ this.show(live, shown);
878
+ prompt.signal?.addEventListener("abort", () => {
879
+ if (live.pending?.prompt.id !== shown.id) return;
880
+ live.pending = void 0;
881
+ this.show(live, void 0);
882
+ reject(/* @__PURE__ */ new Error("sign-in question withdrawn"));
883
+ }, { once: true });
884
+ })
885
+ };
886
+ try {
887
+ const outcome = await this.deps.begin({
888
+ key: live.view.key,
889
+ method: live.view.method,
890
+ interaction,
891
+ signal: live.controller.signal
892
+ });
893
+ if (live.view.phase !== "running") return;
894
+ this.show(live, void 0);
895
+ this.update(live, { phase: outcome.status === "authorized" ? "authorized" : "cancelled" });
896
+ } catch (cause) {
897
+ if (live.view.phase !== "running") return;
898
+ this.show(live, void 0);
899
+ this.update(live, {
900
+ phase: "failed",
901
+ error: readableFailure(cause)
902
+ });
903
+ }
904
+ }
905
+ };
906
+ //#endregion
907
+ //#region src/platform/tools.ts
908
+ /**
909
+ * 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
910
+ * whole job.
911
+ */
912
+ function defineAcrylTool(definition) {
913
+ return definition;
914
+ }
915
+ //#endregion
916
+ //#region src/plugin/host.ts
917
+ /** Shown for a non-mutable entry whose host supplies no wording of its own. */
918
+ const PROTECTED_PLUGIN_ENTRY_REASON = "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.";
919
+ //#endregion
920
+ //#region src/plugin/controller.ts
921
+ const FIBER_STATE = {
922
+ PENDING: 0,
923
+ LOADING: 1,
924
+ ACTIVE: 2,
925
+ FAILED: 3,
926
+ DISPOSED: 4,
927
+ UNLOADING: 5
928
+ };
929
+ const FIBER_PHASE = {
930
+ [FIBER_STATE.PENDING]: "pending",
931
+ [FIBER_STATE.LOADING]: "loading",
932
+ [FIBER_STATE.ACTIVE]: "active",
933
+ [FIBER_STATE.FAILED]: "failed",
934
+ [FIBER_STATE.DISPOSED]: null,
935
+ [FIBER_STATE.UNLOADING]: "unloading"
936
+ };
937
+ var PluginLifecycleError = class extends Error {
938
+ code;
939
+ constructor(code, message) {
940
+ super(message);
941
+ this.code = code;
942
+ this.name = "PluginLifecycleError";
943
+ }
944
+ };
945
+ /** The error a FAILED entry's Fiber recorded, when it recorded one (Cordis keeps it on the Fiber's private `_error`). */
946
+ function fiberFailure(entry) {
947
+ const failure = entry.fiber === void 0 ? void 0 : Reflect.get(entry.fiber, "_error");
948
+ return failure instanceof Error ? failure : void 0;
949
+ }
950
+ function phaseOf(entry) {
951
+ return entry.fiber === void 0 ? null : FIBER_PHASE[entry.fiber.state];
952
+ }
953
+ /**
954
+ * The bare Fiber behind the thenable wrapper the registry hands out.
955
+ *
956
+ * `ctx.plugin()` returns `Object.create(fiber)` with an own `then`, and the
957
+ * Loader keeps that wrapper as `entry.fiber`, while plugin code sees the bare
958
+ * fiber as `ctx.fiber` and service implementations record that one. Any
959
+ * comparison between an entry's fiber and a service's providing fiber has to
960
+ * unwrap the entry side first, or it never matches.
961
+ */
962
+ function bareFiber(fiber) {
963
+ return Object.hasOwn(fiber, "then") ? Object.getPrototypeOf(fiber) : fiber;
964
+ }
965
+ function refOf(entry) {
966
+ return {
967
+ entryId: entry.id,
968
+ moduleName: entry.options.name,
969
+ group: entry.options.group === true
970
+ };
971
+ }
972
+ /** Deep module hiding Loader mutation, ordering, rollback, and cascade policy. */
973
+ var AcrPluginLifecycleController = class {
974
+ ctx;
975
+ host;
976
+ operation = Promise.resolve();
977
+ /**
978
+ * Entry ids this controller mounted, keyed by the package that asked for
979
+ * them. A bundle's insert row names a module specifier that need not equal
980
+ * the package name (`acryl-desktop` inserts `acryl-desktop/terminal`), and
981
+ * after an uninstall the package can no longer be asked - so what an
982
+ * activation actually created is the only authority that outlives it.
983
+ */
984
+ activatedEntries = /* @__PURE__ */ new Map();
985
+ /**
986
+ * Module rows this controller inserted for {@link requireModules}, each with the plugin packages that need it. A row is removed when
987
+ * 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.
988
+ */
989
+ moduleOwners = /* @__PURE__ */ new Map();
990
+ constructor(ctx, host) {
991
+ this.ctx = ctx;
992
+ this.host = host;
993
+ }
994
+ /** Project every non-group Loader entry and the host's mutation policy. */
995
+ snapshot() {
996
+ const entries = [];
997
+ for (const entry of this.ctx.loader.entries()) {
998
+ if (entry.options.group) continue;
999
+ const mutable = this.isMutable(entry);
1000
+ entries.push(Object.freeze({
1001
+ entryId: entry.id,
1002
+ moduleName: entry.options.name,
1003
+ enabled: !entry.disabled,
1004
+ hostPhase: phaseOf(entry),
1005
+ mutable,
1006
+ protectedReason: mutable ? null : this.protectedReason(entry),
1007
+ dependents: mutable && !entry.disabled ? Object.freeze(this.mutableDependents(entry).map((dependent) => dependent.id)) : Object.freeze([])
1008
+ }));
1009
+ }
1010
+ return Object.freeze({ entries: Object.freeze(entries) });
1011
+ }
1012
+ /**
1013
+ * 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
1014
+ * without waiting, and logs - rather than throws - an activation failure; a receipt must not be returned for a Fiber that is still
1015
+ * unloading, and a failed activation must reach the caller so the transaction rolls back.
1016
+ */
1017
+ async applyEnabled(target, enabled) {
1018
+ const previous = target.fiber;
1019
+ await target.update({ disabled: !enabled });
1020
+ if (!enabled) await previous?.dispose();
1021
+ await this.ctx.loader.await?.();
1022
+ if (enabled && (target.fiber === void 0 || phaseOf(target) === "failed")) throw new Error(`Plugin ${target.id} did not activate`);
1023
+ }
1024
+ /**
1025
+ * Persist and apply one managed entry's enablement transactionally. Disabling
1026
+ * an entry that mutable plugins depend on disables those dependents in the
1027
+ * same transaction (dependents first, so a consumer unmounts before its
1028
+ * provider); the receipt lists every id changed.
1029
+ */
1030
+ setEnabled(entryId, enabled) {
1031
+ return this.exclusive(async () => {
1032
+ const entry = this.resolveMutable(entryId);
1033
+ if (!entry.disabled === enabled) throw new PluginLifecycleError(enabled ? "already-enabled" : "already-disabled", `Plugin ${entryId} is already ${enabled ? "enabled" : "disabled"}.`);
1034
+ const targets = enabled ? [entry] : [...this.mutableDependents(entry).filter((dependent) => !dependent.disabled), entry];
1035
+ const persisted = [];
1036
+ try {
1037
+ for (const target of targets) {
1038
+ await this.host.setEnabled(target.id, enabled);
1039
+ persisted.push(target);
1040
+ await this.applyEnabled(target, enabled);
1041
+ }
1042
+ } catch (cause) {
1043
+ const rollbackErrors = [];
1044
+ for (const target of persisted.reverse()) try {
1045
+ await this.host.setEnabled(target.id, !enabled);
1046
+ await this.applyEnabled(target, !enabled);
1047
+ } catch (rollbackCause) {
1048
+ rollbackErrors.push(describe(rollbackCause));
1049
+ }
1050
+ const detail = describe(cause);
1051
+ throw new PluginLifecycleError(rollbackErrors.length > 0 ? "persistence-failed" : "lifecycle-failed", rollbackErrors.length > 0 ? `Plugin lifecycle change failed and rollback also failed: ${detail}; ${rollbackErrors.join("; ")}` : `Plugin lifecycle change failed: ${detail}`);
1052
+ }
1053
+ return this.receipt(enabled ? "enable" : "disable", persisted.map((target) => target.id));
1054
+ });
1055
+ }
1056
+ /**
1057
+ * Restart one entry, or - with no argument - the host's reload-all set:
1058
+ * {@link PluginLifecycleHost.reloadAllEntryIds} when the host narrows it
1059
+ * (Desktop deliberately avoids churning every market plugin's client fiber at
1060
+ * once), otherwise every enabled mutable entry.
1061
+ */
1062
+ reload(entryId) {
1063
+ return this.exclusive(async () => {
1064
+ const entries = entryId === void 0 ? this.reloadAllEntries() : [this.resolveMutable(entryId)];
1065
+ if (entries.length === 0) throw new PluginLifecycleError("not-mounted", "No managed plugin is currently mounted.");
1066
+ for (const entry of entries) {
1067
+ if (entry.disabled || entry.fiber === void 0) throw new PluginLifecycleError("not-mounted", `Plugin ${entry.id} is not mounted.`);
1068
+ try {
1069
+ await entry.fiber.restart();
1070
+ } catch (cause) {
1071
+ throw new PluginLifecycleError("lifecycle-failed", `Plugin ${entry.id} failed to reload: ${describe(cause)}`);
1072
+ }
1073
+ }
1074
+ return this.receipt("reload", entries.map((entry) => entry.id));
1075
+ });
1076
+ }
1077
+ /**
1078
+ * Mount a just-installed profile-bundle package into the running Loader tree,
1079
+ * so an install takes effect without a process restart. The bundle's row comes
1080
+ * from its own cordis patch, via {@link PluginLifecycleHost.bundleRow}.
1081
+ * Idempotent: a package already mounted returns its current snapshot.
1082
+ *
1083
+ * The host is asked for the row before the mounted-entry shortcut, so it
1084
+ * stays the single authority on what may be activated at all: only it can
1085
+ * tell an installed profile bundle from a package the market never managed.
1086
+ */
1087
+ activate(packageName) {
1088
+ return this.exclusive(async () => {
1089
+ const row = this.host.bundleRow?.(packageName);
1090
+ if (row === void 0) throw new PluginLifecycleError("protected-entry", `Package ${packageName} cannot be activated by this host.`);
1091
+ const already = this.findLiveEntry(packageName);
1092
+ if (already !== void 0) {
1093
+ this.activatedEntries.set(packageName, already.id);
1094
+ return this.receipt("enable", [already.id]);
1095
+ }
1096
+ let entry;
1097
+ try {
1098
+ entry = await this.mountRow(row);
1099
+ } catch (cause) {
1100
+ throw new PluginLifecycleError("lifecycle-failed", `Plugin ${packageName} failed to activate: ${describe(cause)}`);
1101
+ }
1102
+ if (entry !== void 0) this.activatedEntries.set(packageName, entry.id);
1103
+ return this.receipt("enable", [entry?.id ?? `include:${row.id}`]);
1104
+ });
1105
+ }
1106
+ /**
1107
+ * Make the modules `owner` needs mounted (a module inside a package, such as `acrylblends/cordis/state`, which is not a profile bundle of
1108
+ * 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
1109
+ * 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
1110
+ * the row `{ id: module, name: module }`, owned by every plugin that asks for it, and removed when its last owner leaves.
1111
+ *
1112
+ * All or nothing: when a module cannot be mounted, the rows this call inserted are removed and the owners it added dropped before the
1113
+ * error is thrown, and nothing is released; releases run only after every module is mounted. A row of the module that exists but is
1114
+ * turned off is left alone and refused, because turning it off was a choice.
1115
+ * @param owner - the plugin package that needs the modules.
1116
+ * @param modules - every module it needs now.
1117
+ */
1118
+ requireModules(owner, modules) {
1119
+ return this.exclusive(async () => {
1120
+ const wanted = new Set(modules);
1121
+ const inserted = [];
1122
+ const joined = [];
1123
+ try {
1124
+ for (const module of wanted) {
1125
+ const owners = this.moduleOwners.get(module);
1126
+ if (owners !== void 0) {
1127
+ if (!owners.has(owner)) {
1128
+ owners.add(owner);
1129
+ joined.push(module);
1130
+ }
1131
+ continue;
1132
+ }
1133
+ const existing = [...this.ctx.loader.entries()].find((entry) => !entry.options.group && entry.options.name === module);
1134
+ if (existing !== void 0) {
1135
+ if (existing.disabled) throw new PluginLifecycleError("lifecycle-failed", `${module} is turned off in this app (row ${existing.id}); turn it on, then install ${owner} again.`);
1136
+ continue;
1137
+ }
1138
+ try {
1139
+ await this.mountRow({
1140
+ id: module,
1141
+ name: module
1142
+ });
1143
+ } catch (cause) {
1144
+ throw new PluginLifecycleError("lifecycle-failed", `${module}, which ${owner} needs, failed to start: ${describe(cause)}`);
1145
+ }
1146
+ this.moduleOwners.set(module, /* @__PURE__ */ new Set([owner]));
1147
+ inserted.push(module);
1148
+ }
1149
+ } catch (cause) {
1150
+ for (const module of joined) this.moduleOwners.get(module)?.delete(owner);
1151
+ for (const module of inserted.reverse()) {
1152
+ this.moduleOwners.delete(module);
1153
+ await this.unmountRow(module).catch((error) => {
1154
+ this.host.warn?.(`could not remove ${module} after a failed start: ${describe(error)}`);
1155
+ });
1156
+ }
1157
+ throw cause;
1158
+ }
1159
+ for (const [module, owners] of this.moduleOwners) {
1160
+ if (wanted.has(module) || !owners.delete(owner) || owners.size > 0) continue;
1161
+ this.moduleOwners.delete(module);
1162
+ try {
1163
+ await this.unmountRow(module);
1164
+ } catch (cause) {
1165
+ throw new PluginLifecycleError("lifecycle-failed", `${module}, which only ${owner} needed, failed to stop: ${describe(cause)}`);
1166
+ }
1167
+ }
1168
+ });
1169
+ }
1170
+ /**
1171
+ * Unmount an uninstalled package from the running Loader tree, then let the
1172
+ * host prune any bookkeeping the package left behind. No-op when it is
1173
+ * already gone; the host's cleanup still runs, because a package that has left
1174
+ * the profile has nothing left to be disabled.
1175
+ */
1176
+ deactivate(packageName) {
1177
+ return this.exclusive(async () => {
1178
+ const entry = this.findLiveEntry(packageName);
1179
+ if (entry === void 0) {
1180
+ await this.afterDeactivate(packageName);
1181
+ return this.receipt("disable", []);
1182
+ }
1183
+ const rowId = entry.options.id;
1184
+ try {
1185
+ await entry.parent.remove(rowId);
1186
+ await this.ctx.loader.await?.();
1187
+ } catch (cause) {
1188
+ throw new PluginLifecycleError("lifecycle-failed", `Plugin ${packageName} failed to deactivate: ${describe(cause)}`);
1189
+ }
1190
+ await this.afterDeactivate(packageName);
1191
+ return this.receipt("disable", [entry.id]);
1192
+ });
1193
+ }
1194
+ /**
1195
+ * Restart the fiber of a mounted plugin identified by package name. Used by a
1196
+ * local-development file watcher. No-op when the package is not mounted.
1197
+ */
1198
+ reloadByPackage(packageName) {
1199
+ return this.exclusive(async () => {
1200
+ const entry = this.findLiveEntry(packageName);
1201
+ if (entry === void 0 || entry.disabled || entry.fiber === void 0) return this.receipt("reload", []);
1202
+ try {
1203
+ await entry.fiber.restart();
1204
+ } catch (cause) {
1205
+ throw new PluginLifecycleError("lifecycle-failed", `Plugin ${packageName} failed to reload: ${describe(cause)}`);
1206
+ }
1207
+ return this.receipt("reload", [entry.id]);
1208
+ });
1209
+ }
1210
+ /**
1211
+ * Toggle a live entry by package name for a caller that knows only package
1212
+ * names, not Loader ids. Resolves `false` when no live entry exists (an import
1213
+ * failure, or not mounted yet), so the caller falls back to its own persisted
1214
+ * state - the only mechanism that still works when a bundle's module cannot
1215
+ * even be imported. Idempotent against a state that already matches, since the
1216
+ * caller's own view of "current status" may be the exact stale read this
1217
+ * method exists to correct.
1218
+ */
1219
+ async setEnabledByPackageName(packageName, enabled) {
1220
+ const entry = this.findLiveEntry(packageName);
1221
+ if (entry === void 0) return false;
1222
+ try {
1223
+ await this.setEnabled(entry.id, enabled);
1224
+ } catch (cause) {
1225
+ if (cause instanceof PluginLifecycleError && (cause.code === "already-enabled" || cause.code === "already-disabled")) return true;
1226
+ throw cause;
1227
+ }
1228
+ return true;
1229
+ }
1230
+ /**
1231
+ * Read a live entry's current enabled/disabled state by package name, or
1232
+ * `undefined` when it is not mounted (the caller's own persisted status is
1233
+ * authoritative in that case).
1234
+ */
1235
+ statusOfPackage(packageName) {
1236
+ const entry = this.findLiveEntry(packageName);
1237
+ if (entry === void 0) return void 0;
1238
+ return entry.disabled ? "disabled" : "active";
1239
+ }
1240
+ isMutable(entry) {
1241
+ if (entry.options.group) return false;
1242
+ return this.host.isMutable(refOf(entry));
1243
+ }
1244
+ protectedReason(entry) {
1245
+ return this.host.protectedReason?.(refOf(entry)) ?? "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.";
1246
+ }
1247
+ reloadAllEntries() {
1248
+ const narrowed = this.host.reloadAllEntryIds?.();
1249
+ return [...this.ctx.loader.entries()].filter((entry) => {
1250
+ if (entry.options.group || entry.disabled) return false;
1251
+ return narrowed === void 0 ? this.isMutable(entry) : narrowed.has(entry.id);
1252
+ });
1253
+ }
1254
+ /** Service names whose live provider is `fiber`. */
1255
+ servicesProvidedBy(fiber) {
1256
+ const store = this.ctx.root.reflect?.store;
1257
+ const names = /* @__PURE__ */ new Set();
1258
+ if (store === void 0) return names;
1259
+ const target = bareFiber(fiber);
1260
+ for (const key of Object.getOwnPropertySymbols(store)) {
1261
+ const impl = store[key];
1262
+ if (impl !== void 0 && bareFiber(impl.fiber) === target) names.add(impl.name);
1263
+ }
1264
+ return names;
1265
+ }
1266
+ /**
1267
+ * Mutable, currently-mounted entries that hard-`inject` a service `entry`
1268
+ * provides and resolve it to `entry`'s fiber - transitively.
1269
+ */
1270
+ mutableDependents(entry) {
1271
+ const byId = new Map([...this.ctx.loader.entries()].map((candidate) => [candidate.id, candidate]));
1272
+ const found = /* @__PURE__ */ new Map();
1273
+ const queue = [entry];
1274
+ while (queue.length > 0) {
1275
+ const currentFiber = queue.shift().fiber;
1276
+ if (currentFiber === void 0) continue;
1277
+ const provided = this.servicesProvidedBy(currentFiber);
1278
+ if (provided.size === 0) continue;
1279
+ for (const other of byId.values()) {
1280
+ if (other === entry || found.has(other.id) || other.options.group) continue;
1281
+ if (other.fiber === void 0 || !this.isMutable(other)) continue;
1282
+ const inject = other.fiber.inject ?? {};
1283
+ const store = other.fiber.store ?? {};
1284
+ const target = bareFiber(currentFiber);
1285
+ if (Object.keys(inject).some((name) => {
1286
+ const impl = store[name];
1287
+ return provided.has(name) && impl?.fiber !== void 0 && bareFiber(impl.fiber) === target;
1288
+ })) {
1289
+ found.set(other.id, other);
1290
+ queue.push(other);
1291
+ }
1292
+ }
1293
+ }
1294
+ return [...found.values()];
1295
+ }
1296
+ async afterDeactivate(packageName) {
1297
+ this.host.refresh?.();
1298
+ if (this.host.afterDeactivate === void 0) return;
1299
+ try {
1300
+ await this.host.afterDeactivate(packageName);
1301
+ } catch (cause) {
1302
+ this.host.warn?.(`could not complete plugin cleanup for ${packageName}: ${describe(cause)}`);
1303
+ }
1304
+ }
1305
+ /**
1306
+ * The live entry a package occupies: the row whose module specifier is the
1307
+ * package name (how a bundle row mounted by the boot Loader is identified),
1308
+ * else the row this controller mounted for it. A package whose row was
1309
+ * mounted at boot under a different specifier - an insert row pointing at a
1310
+ * subpath - is only resolvable while the host still calls it a profile
1311
+ * bundle; the activation record only covers this process.
1312
+ */
1313
+ findLiveEntry(packageName) {
1314
+ const entries = [...this.ctx.loader.entries()].filter((candidate) => !candidate.options.group);
1315
+ const byName = entries.find((candidate) => candidate.options.name === packageName);
1316
+ if (byName !== void 0) return byName;
1317
+ const mountedId = this.activatedEntries.get(packageName);
1318
+ if (mountedId === void 0) return void 0;
1319
+ return entries.find((candidate) => candidate.id === mountedId);
1320
+ }
1321
+ resolveMutable(entryId) {
1322
+ const entry = [...this.ctx.loader.entries()].find((candidate) => candidate.id === entryId);
1323
+ if (entry === void 0) throw new PluginLifecycleError("unknown-entry", `Unknown plugin ${entryId}.`);
1324
+ if (!this.isMutable(entry)) throw new PluginLifecycleError("protected-entry", `Plugin ${entryId} is a core capability and cannot be toggled.`);
1325
+ return entry;
1326
+ }
1327
+ receipt(action, entryIds) {
1328
+ return Object.freeze({
1329
+ accepted: true,
1330
+ action,
1331
+ entryIds: Object.freeze([...entryIds]),
1332
+ snapshot: this.snapshot()
1333
+ });
1334
+ }
1335
+ /**
1336
+ * 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
1337
+ * again and its error thrown. Returns the mounted entry.
1338
+ */
1339
+ async mountRow(row) {
1340
+ const group = this.host.bundleGroup?.() ?? this.ctx.loader.root;
1341
+ const rowOptions = {
1342
+ id: row.id,
1343
+ name: row.name
1344
+ };
1345
+ try {
1346
+ await group.create(rowOptions);
1347
+ group.data.push(rowOptions);
1348
+ await this.ctx.loader.await?.();
1349
+ const created = [...this.ctx.loader.entries()].find((candidate) => candidate.options.id === row.id);
1350
+ if (created !== void 0 && (created.fiber === void 0 || phaseOf(created) === "failed")) throw fiberFailure(created) ?? /* @__PURE__ */ new Error(`plugin ${row.id} did not activate`);
1351
+ return created;
1352
+ } catch (cause) {
1353
+ try {
1354
+ await group.remove(row.id);
1355
+ } catch {}
1356
+ throw cause;
1357
+ }
1358
+ }
1359
+ /** Remove a row this controller inserted, wherever it sits, and wait until its Fiber has unloaded. */
1360
+ async unmountRow(rowId) {
1361
+ const entry = [...this.ctx.loader.entries()].find((candidate) => candidate.options.id === rowId);
1362
+ if (entry === void 0) return;
1363
+ await entry.parent.remove(rowId);
1364
+ await this.ctx.loader.await?.();
1365
+ }
1366
+ /** Serialize mutations: one lifecycle transition settles before the next starts. */
1367
+ exclusive(operation) {
1368
+ this.host.refresh?.();
1369
+ const next = this.operation.then(operation, operation);
1370
+ this.operation = next.then(() => void 0, () => void 0);
1371
+ return next;
1372
+ }
1373
+ };
1374
+ function describe(cause) {
1375
+ return cause instanceof Error ? cause.message : String(cause);
1376
+ }
1377
+ //#endregion
1378
+ //#region src/plugin/provider.ts
1379
+ /**
1380
+ * The Cordis service every surface injects to inspect and steer plugins.
1381
+ *
1382
+ * The service publishes an existing {@link AcrPluginLifecycleController} on
1383
+ * `ctx.acrPluginLifecycle` for the fiber's lifetime. It takes the controller
1384
+ * rather than a host because publishing a capability and building the domain
1385
+ * object are different acts: a surface that also owns package-keyed
1386
+ * operations (Desktop's market bridge) needs the controller itself, and both
1387
+ * views must be the same object or their transitions stop sharing one queue.
1388
+ *
1389
+ * @module acryl-control/plugin/provider
1390
+ */
1391
+ var AcrPluginLifecycleService = class extends Service$1 {
1392
+ /**
1393
+ * The full controller, for a host that also owns package-keyed operations
1394
+ * (activating a just-installed bundle, a market's install/uninstall bridge).
1395
+ * Same instance the service delegates to, so both views never drift.
1396
+ */
1397
+ controller;
1398
+ constructor(ctx, controller) {
1399
+ super(ctx, "acrPluginLifecycle");
1400
+ this.controller = controller;
1401
+ }
1402
+ snapshot() {
1403
+ return this.controller.snapshot();
1404
+ }
1405
+ setEnabled(entryId, enabled) {
1406
+ return this.controller.setEnabled(entryId, enabled);
1407
+ }
1408
+ reload(entryId) {
1409
+ return this.controller.reload(entryId);
1410
+ }
1411
+ };
1412
+ //#endregion
1413
+ //#region src/protocol/client.ts
1414
+ function sessionId(value) {
1415
+ if (value.trim() === "") throw new Error("ACRYL session id must not be empty");
1416
+ return value;
1417
+ }
1418
+ function prompt(input) {
1419
+ if (input.text.trim() === "") throw new Error("ACRYL prompt must not be empty");
1420
+ return input.text;
1421
+ }
1422
+ /** Create the presentation-safe session client over an owner or attached transport. */
1423
+ function createAcrylSessionClient(transport) {
1424
+ return Object.freeze({
1425
+ async snapshot(value) {
1426
+ return parseAcrylSessionSnapshot(await transport.request("session.snapshot", { sessionId: sessionId(value) }));
1427
+ },
1428
+ async subscribe(value, listener, onError) {
1429
+ const selectedSessionId = sessionId(value);
1430
+ return transport.subscribe("session.subscribe", { sessionId: selectedSessionId }, (snapshot) => {
1431
+ try {
1432
+ const parsed = parseAcrylSessionSnapshot(snapshot);
1433
+ if (parsed.sessionId !== selectedSessionId) throw new Error("ACRYL subscription returned a different session");
1434
+ listener(parsed);
1435
+ } catch {}
1436
+ }, onError);
1437
+ },
1438
+ async submitPrompt(input) {
1439
+ await transport.request("session.prompt.submit", {
1440
+ sessionId: sessionId(input.sessionId),
1441
+ text: prompt(input),
1442
+ clientCommandId: nonEmptyCommandId(input.clientCommandId)
1443
+ });
1444
+ },
1445
+ async cancel(input) {
1446
+ await transport.request("session.cancel", { sessionId: sessionId(input.sessionId) });
1447
+ }
1448
+ });
1449
+ }
1450
+ function nonEmptyCommandId(value) {
1451
+ if (value.trim() === "") throw new Error("ACRYL client command id must not be empty");
1452
+ return value;
1453
+ }
1454
+ //#endregion
1455
+ export { ACCOUNT_SIGN_IN_SERVICE, AcrAgentControlError, AcrAgentControlService, AcrPluginLifecycleController, AcrPluginLifecycleService, AcrRuntimeArchitectureService, AuthorizationService, ClaudeStreamTransport, Context, DEEPSEEK_ACCOUNT_FLOW_KEY, PROTECTED_PLUGIN_ENTRY_REASON, PROVIDER_CAPABILITIES, PluginLifecycleError, STARTING_MODELS, Service, SignInAttemptError, SignInAttempts, acpProvider, claudeProvider, codexProvider, computeCredentialProjection, createAcrylSessionClient, createClaudeStreamTransport, createDefaultModelAdoption, createProviderPlugin, createRouteActivation, defineAcrylTool, deriveApiKeyRef, dshNativeProvider, isRouteUsable, parseAcrylSessionSnapshot, projectRuntimeArchitecture, readableFailure, startingModel };
1456
+
1457
+ //# sourceMappingURL=index.js.map