@lmzhen/dsh-evolution-core 0.49.0 → 0.50.0

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 (93) hide show
  1. package/lib/authority-plugin.js +2 -1
  2. package/lib/citations-CZKTUGQF.js +198 -0
  3. package/lib/composition/index.js +2 -2
  4. package/lib/{composition-Cqjbho0t.js → composition-DA8XPfMc.js} +1 -1
  5. package/lib/connection-DAJy7Xjm.js +28 -0
  6. package/lib/{ensure-CAjLGd9f.js → ensure-Bx4ksgJk.js} +15 -5
  7. package/lib/errors.js +2 -0
  8. package/lib/extract-plan-Bru3c9ec.js +271 -0
  9. package/lib/extract.js +240 -0
  10. package/lib/http-routes.js +27 -7
  11. package/lib/index.js +41 -800
  12. package/lib/{numeric-D8js3sqC.js → limits-C9jfvxBl.js} +1 -43
  13. package/lib/{mutation-authority-l57R626O.js → mutation-authority-DQfpXs1O.js} +2 -54
  14. package/lib/numeric-Dc53KQoe.js +43 -0
  15. package/lib/platform/index.js +4 -3
  16. package/lib/platform-DyHnHUmQ.js +251 -0
  17. package/lib/policy.js +3 -2
  18. package/lib/quality-WAU6YatF.js +554 -0
  19. package/lib/restrictor.js +1 -1
  20. package/lib/result.js +33 -0
  21. package/lib/runtime/plugin.js +97 -43
  22. package/lib/{session-projection-DSXnUNZG.js → session-projection-ByNxQi9O.js} +2 -198
  23. package/lib/skill-health-Bl-MdXZ4.js +1409 -0
  24. package/lib/skills.js +7 -4
  25. package/lib/state-store-Jpa-iYIZ.js +54 -0
  26. package/lib/subagent/index.js +214 -176
  27. package/lib/{tools-DzcNFex2.js → tools-BrUswg8v.js} +3 -1
  28. package/lib/types/composition/ensure.js +21 -7
  29. package/lib/types/extract-plan.d.ts +2 -0
  30. package/lib/types/extract.d.ts +12 -0
  31. package/lib/types/extract.js +12 -0
  32. package/lib/types/http-routes.js +32 -9
  33. package/lib/types/index.d.ts +0 -3
  34. package/lib/types/index.js +0 -3
  35. package/lib/types/opt-in.js +4 -3
  36. package/lib/types/params.js +2 -1
  37. package/lib/types/platform/agents.d.ts +32 -0
  38. package/lib/types/platform/agents.js +26 -0
  39. package/lib/types/platform/commands.d.ts +14 -0
  40. package/lib/types/platform/commands.js +9 -0
  41. package/lib/types/platform/connection.d.ts +26 -0
  42. package/lib/types/platform/connection.js +27 -0
  43. package/lib/types/platform/index.d.ts +26 -0
  44. package/lib/types/platform/index.js +13 -0
  45. package/lib/types/platform/llm.d.ts +3 -1
  46. package/lib/types/platform/llm.js +1 -0
  47. package/lib/types/platform/platformView.d.ts +21 -0
  48. package/lib/types/platform/platformView.js +29 -0
  49. package/lib/types/platform/profileContext.d.ts +16 -0
  50. package/lib/types/platform/profileContext.js +14 -0
  51. package/lib/types/platform/sessionQuery.d.ts +14 -0
  52. package/lib/types/platform/sessionQuery.js +9 -0
  53. package/lib/types/platform/settings.d.ts +22 -0
  54. package/lib/types/platform/settings.js +14 -0
  55. package/lib/types/platform/skills.d.ts +16 -0
  56. package/lib/types/platform/skills.js +9 -0
  57. package/lib/types/platform/storageDomain.d.ts +13 -0
  58. package/lib/types/platform/storageDomain.js +9 -0
  59. package/lib/types/platform/subagents.d.ts +25 -0
  60. package/lib/types/platform/subagents.js +17 -0
  61. package/lib/types/platform/systemPrompt.d.ts +16 -0
  62. package/lib/types/platform/systemPrompt.js +13 -0
  63. package/lib/types/platform/tools.d.ts +4 -0
  64. package/lib/types/platform/tools.js +2 -0
  65. package/lib/types/platform/userQuestions.d.ts +33 -0
  66. package/lib/types/platform/userQuestions.js +9 -0
  67. package/lib/types/platform/workingDirectory.d.ts +14 -0
  68. package/lib/types/platform/workingDirectory.js +9 -0
  69. package/lib/types/platform-line.generated.d.ts +5 -5
  70. package/lib/types/platform-line.generated.js +5 -5
  71. package/lib/types/platform-services.js +3 -0
  72. package/lib/types/result.d.ts +35 -0
  73. package/lib/types/result.js +25 -0
  74. package/lib/types/runtime/llm.d.ts +2 -2
  75. package/lib/types/runtime/llm.js +5 -8
  76. package/lib/types/runtime/platform.d.ts +37 -4
  77. package/lib/types/runtime/platform.js +40 -5
  78. package/lib/types/runtime/projections.d.ts +9 -4
  79. package/lib/types/runtime/projections.js +64 -28
  80. package/lib/types/subagent/channel.d.ts +1 -3
  81. package/lib/types/subagent/channel.js +2 -332
  82. package/lib/types/subagent/index.d.ts +2 -0
  83. package/lib/types/subagent/index.js +2 -0
  84. package/lib/types/subagent/kernel.d.ts +4 -0
  85. package/lib/types/subagent/kernel.js +234 -0
  86. package/lib/types/subagent/readiness.js +5 -7
  87. package/lib/types/subagent/run.d.ts +53 -0
  88. package/lib/types/subagent/run.js +125 -0
  89. package/lib/types/subagent/types.d.ts +2 -2
  90. package/lib/usage-DdjIBAkm.js +1252 -0
  91. package/package.json +37 -25
  92. package/lib/platform-Cc9cNt5j.js +0 -111
  93. package/lib/skill-health-DP8z9TPf.js +0 -2923
package/lib/skills.js CHANGED
@@ -1,10 +1,13 @@
1
1
  import { _ as probeMtime, b as probeText, c as transactIo, d as isAbsent, g as probeList, h as probeAbsent, i as isCommittedWarning, m as isUnknown, o as nodeEvolutionIo, p as isPresent, t as TransactionNotInvokedError, v as probePresent, x as probeUnknown, y as probeReason } from "./io-GxghO3Ip.js";
2
- import { l as evolutionRoot, n as mutationLockFrom } from "./mutation-authority-l57R626O.js";
3
- import { G as resolveCitations } from "./session-projection-DSXnUNZG.js";
4
- import { K as SKILL_NAME_RE, U as PROTECTED_BUILTIN_SKILLS, a as DEFAULT_SKILL_LIMITS, c as policyStageLimits, d as CONTENT_SPLIT_HINT, i as DEFAULT_REFERENCE_REWRITE_POLICY, n as DEFAULT_ARCHIVE_RETENTION_POLICY, o as DEFAULT_SUPPORT_FILE_CHAR_POLICY, q as SUPPORT_DIRS, r as DEFAULT_CITATION_POLICY, s as POLICY_STAGE_DEFAULTS } from "./numeric-D8js3sqC.js";
5
- import { At as relatedSkillNames, Bt as planRehoming, Ct as authoringFeedback, D as appendEvolutionEvent, Dt as frontmatterCatalogInvalid, Et as frontmatterBlock, F as RULES, Gt as sessionReadSupportFiles, Ht as filterUnreadSkillOps, I as diffFindings, It as supportRefs, Jt as authorityFrom, L as lintSkill, Lt as applyReferenceRewrite, Mt as skillMdOnDisk, Nt as validateFrontmatter, O as eventsFile, Ot as normalizeFrontmatter, Pt as yamlPlainScalarNeedsQuotes, Rt as describeReferenceRewrite, S as trimPatternBoundaries, Tt as exceedsContentLimit, Ut as isUnreadWrite, Vt as READ_REQUIRED_ACTIONS, Wt as sessionReadSkillNames, a as lintBody, h as scanContentThreats, ht as usageFile, i as assessStructureHealth, jt as shrinksOverLimit, kt as parseFrontmatter, l as isReviewChannelSession, lt as mutateUsage, n as HEALTH_STAMP_RE, o as currentReviewContext, pt as suppressedFile, r as MIN_STAMP_BODY_CHARS, rt as getRecord, st as loadUsage, t as DEFAULT_HEALTH_THRESHOLDS, v as makeSerialQueue, vt as projectExtractBodies, wt as ensureSkillFrontmatter, x as fuzzyPatch, yt as selectSections, zt as planReferenceRewrite } from "./skill-health-DP8z9TPf.js";
2
+ import { n as mutationLockFrom } from "./mutation-authority-DQfpXs1O.js";
3
+ import { o as resolveCitations } from "./citations-CZKTUGQF.js";
4
+ import { G as SKILL_NAME_RE, H as PROTECTED_BUILTIN_SKILLS, K as SUPPORT_DIRS, a as DEFAULT_SUPPORT_FILE_CHAR_POLICY, i as DEFAULT_SKILL_LIMITS, n as DEFAULT_CITATION_POLICY, o as POLICY_STAGE_DEFAULTS, r as DEFAULT_REFERENCE_REWRITE_POLICY, s as policyStageLimits, t as DEFAULT_ARCHIVE_RETENTION_POLICY, u as CONTENT_SPLIT_HINT } from "./limits-C9jfvxBl.js";
5
+ import { $ as authorityFrom, D as appendEvolutionEvent, F as RULES, I as diffFindings, J as isUnreadWrite, K as READ_REQUIRED_ACTIONS, L as lintSkill, O as eventsFile, S as trimPatternBoundaries, X as sessionReadSupportFiles, Y as sessionReadSkillNames, a as lintBody, h as scanContentThreats, i as assessStructureHealth, l as isReviewChannelSession, n as HEALTH_STAMP_RE, o as currentReviewContext, q as filterUnreadSkillOps, r as MIN_STAMP_BODY_CHARS, t as DEFAULT_HEALTH_THRESHOLDS, v as makeSerialQueue, x as fuzzyPatch } from "./skill-health-Bl-MdXZ4.js";
6
+ import { A as authoringFeedback, B as validateFrontmatter, E as selectSections, F as normalizeFrontmatter, G as describeReferenceRewrite, I as parseFrontmatter, K as planReferenceRewrite, L as relatedSkillNames, M as exceedsContentLimit, N as frontmatterBlock, P as frontmatterCatalogInvalid, R as shrinksOverLimit, S as suppressedFile, U as supportRefs, V as yamlPlainScalarNeedsQuotes, W as applyReferenceRewrite, f as getRecord, g as loadUsage, j as ensureSkillFrontmatter, q as planRehoming, v as mutateUsage, w as usageFile, z as skillMdOnDisk } from "./usage-DdjIBAkm.js";
7
+ import { n as evolutionRoot } from "./state-store-Jpa-iYIZ.js";
6
8
  import { i as loadMutations, o as recordMutation, r as contentHash } from "./mutations-DQXddSJd.js";
7
9
  import { C as textDiffFacts, D as unitJournalPort, E as pruneTreeChangeUnits, O as unitSnapshotPort, Q as fileMutationLock, S as recordVersions, T as versionTarget, Z as MutationUnit, _ as nextHistoryIndex, a as RETENTION_FEEDBACK_MIN_CHARS, b as partitionVersions, c as blobPath, d as entryTarget, f as historyIndexFile, g as loadVersions, h as loadVersionContent, i as RETENTION_FEEDBACK_KEEP_RATIO, l as contentRetentionFeedback, m as latestVersionAt, n as HISTORY_DIR, o as TEXT_DIFF_MAX_CHARS, p as historyRoot, r as HISTORY_INDEX_VERSION, s as TEXT_DIFF_MAX_LINES, t as BASELINE_ACTION, u as elapsedSince, v as orderVersions, w as versionActionKind, x as readHistoryIndex, y as parseHistoryIndex } from "./skill-history-CxrDE3Rb.js";
10
+ import { n as projectExtractBodies } from "./extract-plan-Bru3c9ec.js";
8
11
  import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
9
12
  //#region lib/types/skill-row-cells.js
10
13
  /**
@@ -0,0 +1,54 @@
1
+ import { join, resolve } from "node:path";
2
+ import { homedir } from "node:os";
3
+ //#region lib/types/state-store.js
4
+ /**
5
+ * Evolution home path helpers: the DSH root and `$DSH_HOME/evolution` for
6
+ * plugin-owned sidecar state (reports, activity store, feedback file,
7
+ * state-domain data).
8
+ *
9
+ * C-10: PATH HELPERS ONLY — despite the file name there is no store
10
+ * here. Durable evolution state lives in the state stack (evolution-state over
11
+ * evolution-state-domain); skills and memories live in skill-store.ts
12
+ * / memory-store.ts. The file name is kept deliberately: renaming it would
13
+ * touch every family import for zero behavior change, and the audit records
14
+ * the mismatch as known naming debt.
15
+ */
16
+ /**
17
+ * DSH home root: `$DSH_HOME` or `~/.dsh`. Single source of the empty-string
18
+ * fallback — an EMPTY or WHITESPACE-ONLY DSH_HOME resolves to the default
19
+ * home, never to a CWD-relative path (0.3.19 W1.3, 0.3.22 F-207);
20
+ * V8-06 (0.3.47) extends the guard to whitespace.
21
+ * C-11 correction (S2.2, PLAN 2026-09-16): upstream `resolveDshHome`
22
+ * (util/home-paths) uses `trim()` ONLY as the ADOPTION test and then uses the
23
+ * RAW env value — the earlier "same trimmed source" form returned the trimmed
24
+ * text, so `DSH_HOME=" /x "` produced `/x` where upstream produced the literal
25
+ * padded path. The value semantics now match upstream line for line:
26
+ * `const selected = configured ?? (fromEnv !== undefined &&
27
+ * fromEnv.trim().length > 0 ? fromEnv : defaultDshHome())`.
28
+ * OPT-27 (2026-09, plan D5 — accepted): the v10-era "no `~` expansion, no
29
+ * resolve" divergence from upstream `resolveDshHome` is RETIRED. It became
30
+ * load-bearing when the skill-catalog shadow made "same tree as the upstream
31
+ * `USER_DSH_RANK` provider" a hard contract: upstream watches the EXPANDED
32
+ * absolute `<home>/skills` while this value fed a literal `~/x` (a directory
33
+ * named `~` under the host CWD) or a CWD-relative path — split-brain skill
34
+ * trees, preset installs the platform never reads, doctor probes of a
35
+ * directory nothing serves.
36
+ * S2.2 (PLAN 2026-09-16), final correction: the result is ALWAYS
37
+ * `resolve(expandHomePath(selected))` — the earlier form returned an
38
+ * already-absolute value VERBATIM, so a trailing slash or `..` segment
39
+ * landed unnormalized while upstream normalizes every value. Relative
40
+ * `DSH_HOME` values change landing spot; a CLEAN absolute home stays
41
+ * byte-identical (resolve is a no-op on it).
42
+ */
43
+ function evolutionRoot(env = process.env) {
44
+ const fromEnv = env.DSH_HOME;
45
+ const selected = fromEnv !== void 0 && fromEnv.trim().length > 0 ? fromEnv : join(homedir(), ".dsh");
46
+ return resolve(selected === "~" ? homedir() : selected.startsWith("~/") || selected.startsWith("~\\") ? join(homedir(), selected.slice(2)) : selected);
47
+ }
48
+ /** Evolution home path helper: `$DSH_HOME/evolution` for plugin-owned sidecar
49
+ * state (reports, activity store, feedback file, state-domain data). */
50
+ function evolutionHome(env = process.env) {
51
+ return join(evolutionRoot(env), "evolution");
52
+ }
53
+ //#endregion
54
+ export { evolutionRoot as n, evolutionHome as t };
@@ -1,12 +1,10 @@
1
- import { m as restrictedPresetId, n as ensureRestrictedPreset, r as restrictedPresetState } from "../ensure-CAjLGd9f.js";
1
+ import { m as restrictedPresetId, n as ensureRestrictedPreset, r as restrictedPresetState } from "../ensure-Bx4ksgJk.js";
2
2
  //#region lib/types/subagent/readiness.js
3
- function serviceOf$1(ctx, name) {
4
- return ctx.get(name);
5
- }
6
3
  /** Pure derivation (no side effects): the doctor reads this, the channel re-probes on every run. */
7
4
  function probeChannelState(ctx, kind) {
8
- const subagents = serviceOf$1(ctx, "subagents");
9
- if (subagents === void 0 || typeof subagents.getProvider !== "function") return {
5
+ const platform = ctx.get("evolutionPlatform");
6
+ const subagents = platform?.ports.subagents;
7
+ if (subagents === void 0) return {
10
8
  kind: "unavailable",
11
9
  code: "E-323",
12
10
  reason: "subagents service unavailable"
@@ -27,8 +25,7 @@ function probeChannelState(ctx, kind) {
27
25
  code: "E-323",
28
26
  reason: "spawn provider inherits the parent context (independent preset required)"
29
27
  };
30
- const agentPresets = serviceOf$1(ctx, "agentPresets");
31
- if (agentPresets === void 0 || typeof agentPresets.readDocument !== "function" || typeof agentPresets.register !== "function") return {
28
+ if (platform?.ports.presets === void 0) return {
32
29
  kind: "unavailable",
33
30
  code: "E-323",
34
31
  reason: "agentPresets service unavailable or incomplete"
@@ -43,13 +40,7 @@ function probeChannelState(ctx, kind) {
43
40
  };
44
41
  }
45
42
  //#endregion
46
- //#region lib/types/subagent/channel.js
47
- function serviceOf(ctx, name) {
48
- return ctx.get(name);
49
- }
50
- function messageOf(error) {
51
- return error instanceof Error ? error.message : String(error);
52
- }
43
+ //#region lib/types/subagent/run.js
53
44
  function textOfValue(value) {
54
45
  if (typeof value === "string") return value;
55
46
  if (!Array.isArray(value)) return "";
@@ -110,10 +101,180 @@ function waitForSubagentEnd(ctx, childId, signal, timeoutMs) {
110
101
  if (signal.aborted) onAbort();
111
102
  });
112
103
  }
113
- function createSubagentChannel(ctx) {
104
+ /** Wrap one started activation in the single continuation handle. */
105
+ function createSubagentRun(ctx, parent, name, activation) {
106
+ let disposed = false;
107
+ let pending;
108
+ const map = (value) => {
109
+ const output = value.output ?? value.lastAssistantMessage;
110
+ return {
111
+ childId: activation.childId,
112
+ stopReason: value.stopReason,
113
+ ...output === void 0 ? {} : { output },
114
+ ...value.structured === void 0 ? {} : { structured: value.structured },
115
+ ...value.diagnostic === void 0 ? {} : { diagnostic: value.diagnostic }
116
+ };
117
+ };
118
+ const openTurn = (options) => {
119
+ const link = abortLink(options?.signal, options?.timeoutMs ?? 12e4);
120
+ return {
121
+ promise: waitForSubagentEnd(ctx, activation.childId, link.controller.signal, options?.timeoutMs ?? 12e4),
122
+ cleanup: link.cleanup,
123
+ controller: link.controller
124
+ };
125
+ };
126
+ return {
127
+ id: activation.childId,
128
+ name,
129
+ result: activation.result.then(map),
130
+ async send(prompt, options) {
131
+ if (disposed) throw new Error("subagent run is disposed");
132
+ const send = ctx.get("evolutionPlatform")?.ports.subagents?.sendMessage;
133
+ if (send === void 0) throw new Error("subagents.sendMessage unavailable");
134
+ pending?.cleanup();
135
+ const turn = openTurn(options);
136
+ pending = turn;
137
+ try {
138
+ await send(parent, activation.childId, prompt, { signal: turn.controller.signal });
139
+ } catch (error) {
140
+ pending = void 0;
141
+ turn.cleanup();
142
+ throw error;
143
+ }
144
+ },
145
+ async next(options) {
146
+ if (disposed) throw new Error("subagent run is disposed");
147
+ const turn = pending ?? openTurn(options);
148
+ pending = void 0;
149
+ try {
150
+ const info = await turn.promise;
151
+ return map({
152
+ ...info,
153
+ stopReason: info.stopReason ?? "completed"
154
+ });
155
+ } finally {
156
+ turn.cleanup();
157
+ }
158
+ },
159
+ async dispose() {
160
+ if (disposed) return;
161
+ disposed = true;
162
+ pending?.cleanup();
163
+ pending = void 0;
164
+ await activation.dispose();
165
+ }
166
+ };
167
+ }
168
+ //#endregion
169
+ //#region lib/types/subagent/kernel.js
170
+ function platformOf(ctx) {
171
+ return ctx.get("evolutionPlatform");
172
+ }
173
+ function messageOf(error) {
174
+ return error instanceof Error ? error.message : String(error);
175
+ }
176
+ function createSubagentKernel(ctx) {
114
177
  let lastKind = "reviewer";
115
178
  const active = /* @__PURE__ */ new Map();
116
179
  const disposed = /* @__PURE__ */ new Set();
180
+ /**
181
+ * The one policy/probe/preset preparation shared by run and open. Starting the
182
+ * activation stays separate because run disposes and open keeps the handle.
183
+ */
184
+ async function prepare(spec) {
185
+ lastKind = spec.kind;
186
+ const probe = probeChannelState(ctx, spec.kind);
187
+ if (probe.kind === "unavailable") return {
188
+ ok: false,
189
+ outcome: probe
190
+ };
191
+ const platform = platformOf(ctx);
192
+ const subagents = platform?.ports.subagents;
193
+ const presets = platform?.ports.presets;
194
+ if (platform === void 0 || subagents === void 0 || presets === void 0) return {
195
+ ok: false,
196
+ outcome: {
197
+ kind: "unavailable",
198
+ code: "E-323",
199
+ reason: "subagents/agentPresets service unavailable"
200
+ }
201
+ };
202
+ const parentPresetId = presets.composedPreset(spec.parent.ctx);
203
+ if (parentPresetId === void 0) return {
204
+ ok: false,
205
+ outcome: {
206
+ kind: "unavailable",
207
+ code: "E-323",
208
+ reason: "parent preset could not be resolved"
209
+ }
210
+ };
211
+ const ensured = await ensureRestrictedPreset(ctx, {
212
+ kind: spec.kind,
213
+ parentPresetId,
214
+ allow: spec.allow
215
+ });
216
+ if (ensured.kind === "failed") return {
217
+ ok: false,
218
+ outcome: {
219
+ kind: "unavailable",
220
+ code: "E-324",
221
+ reason: ensured.reason
222
+ }
223
+ };
224
+ return {
225
+ ok: true,
226
+ platform,
227
+ subagents,
228
+ ensured
229
+ };
230
+ }
231
+ /** Start one activation after the shared policy/prepare step; the caller owns its link/run. */
232
+ async function startRun(spec, options) {
233
+ const prepared = await prepare(spec);
234
+ if (!prepared.ok) return {
235
+ ok: false,
236
+ outcome: prepared.outcome
237
+ };
238
+ const link = abortLink(spec.signal, spec.timeoutMs);
239
+ try {
240
+ const activation = await prepared.subagents.start({
241
+ provider: "spawn",
242
+ label: spec.label,
243
+ delivery: "caller",
244
+ parent: spec.parent,
245
+ prompt: [{
246
+ type: "text",
247
+ text: spec.promptText
248
+ }],
249
+ agentPreset: prepared.ensured.presetId,
250
+ ...options.outputSchema !== void 0 ? { outputSchema: options.outputSchema } : {},
251
+ ...options.cwd !== void 0 ? { cwd: options.cwd } : {},
252
+ ...spec.maxDepth !== void 0 ? { maxDepth: spec.maxDepth } : {},
253
+ ...spec.agentOptions !== void 0 ? { agentOptions: spec.agentOptions } : {},
254
+ signal: link.controller.signal
255
+ });
256
+ return {
257
+ ok: true,
258
+ run: createSubagentRun(ctx, spec.parent, spec.label, activation),
259
+ link,
260
+ platform: prepared.platform
261
+ };
262
+ } catch (error) {
263
+ link.cleanup();
264
+ if (link.controller.signal.aborted) return {
265
+ ok: false,
266
+ outcome: { kind: "aborted" }
267
+ };
268
+ return {
269
+ ok: false,
270
+ outcome: {
271
+ kind: "unavailable",
272
+ code: "E-323",
273
+ reason: messageOf(error)
274
+ }
275
+ };
276
+ }
277
+ }
117
278
  return {
118
279
  get state() {
119
280
  return probeChannelState(ctx, lastKind);
@@ -130,73 +291,14 @@ function createSubagentChannel(ctx) {
130
291
  return Promise.resolve(state);
131
292
  },
132
293
  async run(spec) {
133
- lastKind = spec.kind;
134
- const probe = probeChannelState(ctx, spec.kind);
135
- if (probe.kind === "unavailable") return probe;
136
- const subagents = serviceOf(ctx, "subagents");
137
- const presets = serviceOf(ctx, "agentPresets");
138
- if (subagents === void 0 || presets === void 0) return {
139
- kind: "unavailable",
140
- code: "E-323",
141
- reason: "subagents/agentPresets service unavailable"
142
- };
143
- const parentPresetId = presets.composedPreset(spec.parent.ctx);
144
- if (parentPresetId === void 0) return {
145
- kind: "unavailable",
146
- code: "E-323",
147
- reason: "parent preset could not be resolved"
148
- };
149
- const ensured = await ensureRestrictedPreset(ctx, {
150
- kind: spec.kind,
151
- parentPresetId,
152
- allow: spec.allow
153
- });
154
- if (ensured.kind === "failed") return {
155
- kind: "unavailable",
156
- code: "E-324",
157
- reason: ensured.reason
158
- };
159
- const controller = new AbortController();
160
- const timer = setTimeout(() => {
161
- controller.abort(/* @__PURE__ */ new Error("subagent timeout"));
162
- }, spec.timeoutMs);
163
- const onAbort = () => {
164
- controller.abort(spec.signal?.reason);
165
- };
166
- spec.signal?.addEventListener("abort", onAbort, { once: true });
167
- let activation;
294
+ const started = await startRun(spec, spec.outputSchema === void 0 ? {} : { outputSchema: spec.outputSchema });
295
+ if (!started.ok) return started.outcome;
296
+ const { run, link, platform } = started;
168
297
  try {
169
- activation = await subagents.startActivation({
170
- provider: "spawn",
171
- label: spec.label,
172
- delivery: "caller",
173
- request: {
174
- parent: spec.parent,
175
- prompt: [{
176
- type: "text",
177
- text: spec.promptText
178
- }],
179
- agentPreset: ensured.presetId,
180
- ...spec.outputSchema !== void 0 ? { outputSchema: spec.outputSchema } : {},
181
- ...spec.maxDepth !== void 0 ? { maxDepth: spec.maxDepth } : {},
182
- ...spec.agentOptions !== void 0 ? { agentOptions: spec.agentOptions } : {}
183
- },
184
- signal: controller.signal
185
- });
186
- let result;
187
- try {
188
- result = await activation.result;
189
- } catch (error) {
190
- if (controller.signal.aborted) return { kind: "aborted" };
191
- return {
192
- kind: "unavailable",
193
- code: "E-323",
194
- reason: messageOf(error)
195
- };
196
- }
298
+ const result = await run.result;
197
299
  let evidence;
198
300
  if (spec.afterResult !== void 0) try {
199
- const child = serviceOf(ctx, "agents")?.get(activation.childId);
301
+ const child = platform.ports.agents?.get(run.id);
200
302
  if (child !== void 0) evidence = spec.afterResult(child);
201
303
  } catch {
202
304
  evidence = void 0;
@@ -205,30 +307,29 @@ function createSubagentChannel(ctx) {
205
307
  if (stopReason === "completed" && result.structured !== void 0 && result.structured !== null) return {
206
308
  kind: "ok",
207
309
  structured: result.structured,
208
- childId: activation.childId,
310
+ childId: run.id,
209
311
  stopReason: "completed",
210
312
  ...evidence !== void 0 ? { evidence } : {}
211
313
  };
212
314
  if (stopReason === "aborted") return { kind: "aborted" };
213
315
  return {
214
316
  kind: "no-structured",
215
- childId: activation.childId,
317
+ childId: run.id,
216
318
  stopReason,
217
319
  ...result.diagnostic !== void 0 ? { diagnostic: result.diagnostic } : {},
218
320
  ...evidence !== void 0 ? { evidence } : {}
219
321
  };
220
322
  } catch (error) {
221
- if (controller.signal.aborted) return { kind: "aborted" };
323
+ if (link.controller.signal.aborted) return { kind: "aborted" };
222
324
  return {
223
325
  kind: "unavailable",
224
326
  code: "E-323",
225
327
  reason: messageOf(error)
226
328
  };
227
329
  } finally {
228
- clearTimeout(timer);
229
- spec.signal?.removeEventListener("abort", onAbort);
230
- if (activation !== void 0) try {
231
- await activation.dispose();
330
+ link.cleanup();
331
+ try {
332
+ await run.dispose();
232
333
  } catch (error) {
233
334
  try {
234
335
  ctx.logger.warn("subagent channel: activation dispose failed: " + messageOf(error));
@@ -237,67 +338,20 @@ function createSubagentChannel(ctx) {
237
338
  }
238
339
  },
239
340
  async open(spec) {
240
- lastKind = spec.kind;
241
- const probe = probeChannelState(ctx, spec.kind);
242
- if (probe.kind === "unavailable") return probe;
243
- if (spec.allow.length === 0) return {
244
- kind: "unavailable",
245
- code: "E-324",
246
- reason: "allow set is empty"
247
- };
248
- const subagents = serviceOf(ctx, "subagents");
249
- const presets = serviceOf(ctx, "agentPresets");
250
- if (subagents === void 0 || presets === void 0) return {
251
- kind: "unavailable",
252
- code: "E-323",
253
- reason: "subagents/agentPresets service unavailable"
254
- };
255
- const parentPresetId = presets.composedPreset(spec.parent.ctx);
256
- if (parentPresetId === void 0) return {
257
- kind: "unavailable",
258
- code: "E-323",
259
- reason: "parent preset could not be resolved"
260
- };
261
- const ensured = await ensureRestrictedPreset(ctx, {
262
- kind: spec.kind,
263
- parentPresetId,
264
- allow: spec.allow
265
- });
266
- if (ensured.kind === "failed") return {
267
- kind: "unavailable",
268
- code: "E-324",
269
- reason: ensured.reason
270
- };
271
- const link = abortLink(spec.signal, spec.timeoutMs);
272
- let activation;
341
+ const started = await startRun(spec, spec.cwd === void 0 ? {} : { cwd: spec.cwd });
342
+ if (!started.ok) return started.outcome;
343
+ const { run, link } = started;
273
344
  try {
274
- activation = await subagents.startActivation({
275
- provider: "spawn",
276
- label: spec.label,
277
- delivery: "caller",
278
- request: {
279
- parent: spec.parent,
280
- prompt: [{
281
- type: "text",
282
- text: spec.promptText
283
- }],
284
- agentPreset: ensured.presetId,
285
- ...spec.cwd !== void 0 ? { cwd: spec.cwd } : {},
286
- ...spec.maxDepth !== void 0 ? { maxDepth: spec.maxDepth } : {},
287
- ...spec.agentOptions !== void 0 ? { agentOptions: spec.agentOptions } : {}
288
- },
289
- signal: link.controller.signal
290
- });
291
- const result = await activation.result;
345
+ const result = await run.result;
292
346
  if (result.stopReason === "aborted") {
293
347
  try {
294
- await activation.dispose();
348
+ await run.dispose();
295
349
  } catch {}
296
350
  return { kind: "aborted" };
297
351
  }
298
352
  if (result.stopReason !== "completed") {
299
353
  try {
300
- await activation.dispose();
354
+ await run.dispose();
301
355
  } catch {}
302
356
  return {
303
357
  kind: "unavailable",
@@ -306,27 +360,26 @@ function createSubagentChannel(ctx) {
306
360
  };
307
361
  }
308
362
  const turn = {
309
- childId: activation.childId,
363
+ childId: run.id,
310
364
  stopReason: result.stopReason,
311
365
  text: textOfValue(result.output),
312
366
  ...result.structured !== void 0 ? { structured: result.structured } : {},
313
367
  ...result.diagnostic !== void 0 ? { diagnostic: result.diagnostic } : {}
314
368
  };
315
- active.set(activation.childId, {
316
- childId: activation.childId,
317
- parent: spec.parent,
318
- activation,
369
+ active.set(run.id, {
370
+ childId: run.id,
371
+ run,
319
372
  disposed: false
320
373
  });
321
- disposed.delete(activation.childId);
374
+ disposed.delete(run.id);
322
375
  return {
323
376
  kind: "ok",
324
- childId: activation.childId,
377
+ childId: run.id,
325
378
  turn
326
379
  };
327
380
  } catch (error) {
328
- if (activation !== void 0) try {
329
- await activation.dispose();
381
+ try {
382
+ await run.dispose();
330
383
  } catch {}
331
384
  if (link.controller.signal.aborted) return { kind: "aborted" };
332
385
  return {
@@ -350,40 +403,27 @@ function createSubagentChannel(ctx) {
350
403
  code: "E-323",
351
404
  reason: "no open conversation for " + childId
352
405
  };
353
- const subagents = serviceOf(ctx, "subagents");
354
- if (subagents?.sendMessage === void 0) return {
355
- kind: "unavailable",
356
- code: "E-323",
357
- reason: "subagents.sendMessage unavailable"
358
- };
359
- const link = abortLink(options?.signal, options?.timeoutMs ?? 12e4);
360
- let pending;
361
406
  try {
362
- pending = waitForSubagentEnd(ctx, childId, link.controller.signal, options?.timeoutMs ?? 12e4);
363
- await subagents.sendMessage(current.parent, childId, [{
407
+ await current.run.send([{
364
408
  type: "text",
365
409
  text: promptText
366
- }], { signal: link.controller.signal });
367
- } catch (error) {
368
- link.cleanup();
369
- if (options?.signal?.aborted === true) return { kind: "aborted" };
370
- return {
410
+ }], options);
411
+ const result = await current.run.next(options);
412
+ if (result.stopReason === "aborted") return { kind: "aborted" };
413
+ if (result.stopReason !== "completed") return {
371
414
  kind: "unavailable",
372
415
  code: "E-323",
373
- reason: messageOf(error)
416
+ reason: "round 2 did not complete: " + result.stopReason
374
417
  };
375
- }
376
- try {
377
- const info = await pending;
378
- if (info.stopReason === "aborted") return { kind: "aborted" };
379
418
  return {
380
419
  kind: "ok",
381
420
  childId,
382
421
  turn: {
383
422
  childId,
384
- stopReason: info.stopReason ?? "completed",
385
- text: textOfValue(info.lastAssistantMessage),
386
- ...info.diagnostic !== void 0 ? { diagnostic: info.diagnostic } : {}
423
+ stopReason: "completed",
424
+ text: textOfValue(result.output),
425
+ ...result.structured !== void 0 ? { structured: result.structured } : {},
426
+ ...result.diagnostic !== void 0 ? { diagnostic: result.diagnostic } : {}
387
427
  }
388
428
  };
389
429
  } catch (error) {
@@ -393,8 +433,6 @@ function createSubagentChannel(ctx) {
393
433
  code: "E-323",
394
434
  reason: messageOf(error)
395
435
  };
396
- } finally {
397
- link.cleanup();
398
436
  }
399
437
  },
400
438
  async dispose(childId) {
@@ -407,7 +445,7 @@ function createSubagentChannel(ctx) {
407
445
  active.delete(childId);
408
446
  disposed.add(childId);
409
447
  try {
410
- await current.activation.dispose();
448
+ await current.run.dispose();
411
449
  } catch (error) {
412
450
  try {
413
451
  ctx.logger.warn("subagent conversation: dispose failed: " + messageOf(error));
@@ -417,4 +455,4 @@ function createSubagentChannel(ctx) {
417
455
  };
418
456
  }
419
457
  //#endregion
420
- export { createSubagentChannel, probeChannelState };
458
+ export { abortLink, createSubagentKernel as createSubagentChannel, createSubagentKernel, createSubagentRun, probeChannelState, textOfValue, waitForSubagentEnd };
@@ -9,7 +9,9 @@ function toolsPort(ctx) {
9
9
  return {
10
10
  register: (definition) => tools.register(definition),
11
11
  guard: (guard) => tools.guard(guard),
12
- restrict: (filter) => tools.restrict(filter)
12
+ restrict: (filter) => tools.restrict(filter),
13
+ get: (name, scope) => tools.get(name, scope),
14
+ ...typeof tools.execute === "function" ? { execute: (input) => tools.execute(input) } : {}
13
15
  };
14
16
  }
15
17
  /** Register one family tool through the port; a missing service yields a no-op disposer. */
@@ -36,11 +36,20 @@ export async function ensureRestrictedPreset(ctx, req) {
36
36
  const allow = normalizeAllow(req.allow);
37
37
  const key = req.parentPresetId + '\n' + allow.join('\n');
38
38
  const slot = slotFor(ctx, req.kind);
39
- if (slot.readyKey === key && slot.state !== undefined && slot.state.kind === 'ready')
40
- return slot.state;
41
- if (slot.inflight !== undefined)
42
- return slot.inflight;
43
- slot.inflight = (async () => {
39
+ // One registration per kind is the invariant. A same-key caller joins the
40
+ // in-flight promise; a different-key caller must NOT join it (that was the
41
+ // cross-allow race), so it waits for the current attempt and re-evaluates.
42
+ for (;;) {
43
+ if (slot.readyKey === key && slot.state !== undefined && slot.state.kind === 'ready')
44
+ return slot.state;
45
+ const inflight = slot.inflight;
46
+ if (inflight === undefined)
47
+ break;
48
+ if (slot.inflightKey === key)
49
+ return inflight;
50
+ await inflight.catch(() => undefined);
51
+ }
52
+ const pending = (async () => {
44
53
  await releaseRestrictedPreset(ctx, req.kind, slot);
45
54
  if (allow.length === 0) {
46
55
  slot.state = { kind: 'failed', code: 'E-324', reason: 'allow set is empty' };
@@ -67,11 +76,16 @@ export async function ensureRestrictedPreset(ctx, req) {
67
76
  return slot.state;
68
77
  }
69
78
  })();
79
+ slot.inflight = pending;
80
+ slot.inflightKey = key;
70
81
  try {
71
- return await slot.inflight;
82
+ return await pending;
72
83
  }
73
84
  finally {
74
- slot.inflight = undefined;
85
+ if (slot.inflight === pending) {
86
+ slot.inflight = undefined;
87
+ slot.inflightKey = undefined;
88
+ }
75
89
  }
76
90
  }
77
91
  /** Read-only view of the current registration (doctor runtime row). */
@@ -56,6 +56,8 @@ export interface ExtractAnchors {
56
56
  sourceMdSha256: string;
57
57
  targetMdSha256: string;
58
58
  }
59
+ /** The stable plan shape a preview/approval serializes and an apply re-executes. */
60
+ export type SkillPlan = ExtractPlanDraft;
59
61
  export interface ExtractPlanDraft {
60
62
  source: string;
61
63
  target: {