@lmzhen/dsh-evolution-core 0.49.0 → 0.51.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 (110) hide show
  1. package/lib/authority-plugin.js +2 -1
  2. package/lib/citations-CZKTUGQF.js +198 -0
  3. package/lib/composition/index.js +3 -3
  4. package/lib/{composition-Cqjbho0t.js → composition-CtNbVHq3.js} +1 -1
  5. package/lib/connection-DAJy7Xjm.js +28 -0
  6. package/lib/{ensure-CAjLGd9f.js → ensure-BLmEW0Ju.js} +25 -7
  7. package/lib/errors.js +2 -0
  8. package/lib/extract-plan-D6o__2Kf.js +271 -0
  9. package/lib/extract.js +240 -0
  10. package/lib/http-routes.js +27 -7
  11. package/lib/index.js +100 -811
  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-DpAS0rd9.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-BQCM4N8z.js +1419 -0
  24. package/lib/{skill-history-CxrDE3Rb.js → skill-history-CZp8vhyL.js} +46 -2
  25. package/lib/skills.js +140 -20
  26. package/lib/state-store-Jpa-iYIZ.js +54 -0
  27. package/lib/subagent/index.js +214 -176
  28. package/lib/{tools-DzcNFex2.js → tools-BrUswg8v.js} +3 -1
  29. package/lib/types/composition/ensure.js +21 -7
  30. package/lib/types/composition/preset-ids.d.ts +2 -1
  31. package/lib/types/composition/preset-ids.js +7 -1
  32. package/lib/types/events.d.ts +3 -0
  33. package/lib/types/extract-plan.d.ts +2 -0
  34. package/lib/types/extract.d.ts +12 -0
  35. package/lib/types/extract.js +12 -0
  36. package/lib/types/http-routes.js +32 -9
  37. package/lib/types/index.d.ts +0 -3
  38. package/lib/types/index.js +0 -3
  39. package/lib/types/opt-in.js +4 -3
  40. package/lib/types/params.js +2 -1
  41. package/lib/types/platform/agents.d.ts +32 -0
  42. package/lib/types/platform/agents.js +26 -0
  43. package/lib/types/platform/commands.d.ts +14 -0
  44. package/lib/types/platform/commands.js +9 -0
  45. package/lib/types/platform/connection.d.ts +26 -0
  46. package/lib/types/platform/connection.js +27 -0
  47. package/lib/types/platform/index.d.ts +26 -0
  48. package/lib/types/platform/index.js +13 -0
  49. package/lib/types/platform/llm.d.ts +3 -1
  50. package/lib/types/platform/llm.js +1 -0
  51. package/lib/types/platform/platformView.d.ts +21 -0
  52. package/lib/types/platform/platformView.js +29 -0
  53. package/lib/types/platform/profileContext.d.ts +16 -0
  54. package/lib/types/platform/profileContext.js +14 -0
  55. package/lib/types/platform/sessionQuery.d.ts +14 -0
  56. package/lib/types/platform/sessionQuery.js +9 -0
  57. package/lib/types/platform/settings.d.ts +22 -0
  58. package/lib/types/platform/settings.js +14 -0
  59. package/lib/types/platform/skills.d.ts +16 -0
  60. package/lib/types/platform/skills.js +9 -0
  61. package/lib/types/platform/storageDomain.d.ts +13 -0
  62. package/lib/types/platform/storageDomain.js +9 -0
  63. package/lib/types/platform/subagents.d.ts +25 -0
  64. package/lib/types/platform/subagents.js +17 -0
  65. package/lib/types/platform/systemPrompt.d.ts +16 -0
  66. package/lib/types/platform/systemPrompt.js +13 -0
  67. package/lib/types/platform/tools.d.ts +4 -0
  68. package/lib/types/platform/tools.js +2 -0
  69. package/lib/types/platform/userQuestions.d.ts +33 -0
  70. package/lib/types/platform/userQuestions.js +9 -0
  71. package/lib/types/platform/workingDirectory.d.ts +14 -0
  72. package/lib/types/platform/workingDirectory.js +9 -0
  73. package/lib/types/platform-line.generated.d.ts +5 -5
  74. package/lib/types/platform-line.generated.js +5 -5
  75. package/lib/types/platform-services.js +4 -0
  76. package/lib/types/prompts.d.ts +9 -8
  77. package/lib/types/prompts.js +20 -1
  78. package/lib/types/result.d.ts +35 -0
  79. package/lib/types/result.js +25 -0
  80. package/lib/types/review-context.d.ts +8 -0
  81. package/lib/types/review-context.js +11 -0
  82. package/lib/types/run-registry.d.ts +2 -1
  83. package/lib/types/run-registry.js +37 -7
  84. package/lib/types/runtime/llm.d.ts +2 -2
  85. package/lib/types/runtime/llm.js +5 -8
  86. package/lib/types/runtime/platform.d.ts +37 -4
  87. package/lib/types/runtime/platform.js +40 -5
  88. package/lib/types/runtime/projections.d.ts +9 -4
  89. package/lib/types/runtime/projections.js +64 -28
  90. package/lib/types/section-selection.js +5 -0
  91. package/lib/types/skill-history.d.ts +29 -3
  92. package/lib/types/skill-history.js +30 -0
  93. package/lib/types/skill-store.d.ts +32 -4
  94. package/lib/types/skill-store.js +109 -15
  95. package/lib/types/subagent/channel.d.ts +1 -3
  96. package/lib/types/subagent/channel.js +2 -332
  97. package/lib/types/subagent/index.d.ts +2 -0
  98. package/lib/types/subagent/index.js +2 -0
  99. package/lib/types/subagent/kernel.d.ts +4 -0
  100. package/lib/types/subagent/kernel.js +234 -0
  101. package/lib/types/subagent/readiness.js +5 -7
  102. package/lib/types/subagent/run.d.ts +53 -0
  103. package/lib/types/subagent/run.js +125 -0
  104. package/lib/types/subagent/types.d.ts +3 -3
  105. package/lib/types/write-gates.js +11 -1
  106. package/lib/usage-B5a90TKv.js +1257 -0
  107. package/lib/write.js +1 -1
  108. package/package.json +37 -25
  109. package/lib/platform-Cc9cNt5j.js +0 -111
  110. package/lib/skill-health-DP8z9TPf.js +0 -2923
@@ -57,7 +57,7 @@ import { projectExtractBodies } from "./extract-plan.js";
57
57
  import { diffFindings } from "./skill-lint.js";
58
58
  import { contentHash, loadMutations, recordMutation } from "./mutations.js";
59
59
  import { revisionFingerprint, revisionSupportDigest } from "./skill-revision.js";
60
- import { contentRetentionFeedback, HISTORY_DIR, loadVersionContent, loadVersions, recordVersions } from "./skill-history.js";
60
+ import { clipChangeSummary, contentRetentionFeedback, DEFAULT_SKILL_WRITE_SUMMARY_CHARS, HISTORY_DIR, loadVersionContent, loadVersions, normalizeChangeSummary, recordVersions } from "./skill-history.js";
61
61
  import { getRecord, loadUsage, mutateUsage, suppressedFile, usageFile } from "./usage.js";
62
62
  import { assessStructureHealth, DEFAULT_HEALTH_THRESHOLDS, lintBody } from "./skill-health.js";
63
63
  import { CONTENT_SPLIT_HINT, DEFAULT_SKILL_VERSION_KEEP, PROTECTED_BUILTIN_SKILLS, SKILL_NAME_RE, SUPPORT_DIRS } from "./constants.js";
@@ -398,7 +398,11 @@ function planRestructureSections(body, moves) {
398
398
  // One scan (h2Sections) and one selection rule; extract reuses the same
399
399
  // selector for start/end sub-blocks, so restructure and extract cannot drift
400
400
  // on heading ambiguity, empty sections or duplicate moves.
401
- const selection = selectSections(body, moves.map(move => ({ heading: move.heading })));
401
+ const selection = selectSections(body, moves.map(move => ({
402
+ heading: move.heading,
403
+ ...(move.start === undefined ? {} : { start: move.start }),
404
+ ...(move.end === undefined ? {} : { end: move.end }),
405
+ })));
402
406
  if (!selection.ok)
403
407
  return { error: selection.message };
404
408
  const lines = body.split('\n');
@@ -535,7 +539,8 @@ export class SkillLibrary {
535
539
  ...(provenance.get(op.target) === undefined ? {} : { provenance: provenance.get(op.target) }),
536
540
  });
537
541
  }
538
- return { moves, sources: roots.map(skill => ({ skill })) };
542
+ const runId = currentReviewContext()?.runId;
543
+ return { ...(runId === undefined ? {} : { runId }), moves, sources: roots.map(skill => ({ skill })) };
539
544
  }
540
545
  async withMutationLock(task) {
541
546
  // Fail closed: a missing authority/lock is an assembly error, not a reason to run
@@ -1218,6 +1223,18 @@ export class SkillLibrary {
1218
1223
  console.warn('skill-store: hard-cap event not recorded for "' + name + '": ' + (error instanceof Error ? error.message : String(error)));
1219
1224
  }
1220
1225
  }
1226
+ /** Host fallback for the user-facing change summary when the writer did not supply one. */
1227
+ hostChangeSummary(action, before, after, path, machine) {
1228
+ const target = path ?? 'SKILL.md';
1229
+ let text = machine;
1230
+ if (action === 'update' || action === 'edit')
1231
+ text = `updated ${target} (${before?.length ?? 0} → ${after?.length ?? 0})`;
1232
+ else if (action === 'create')
1233
+ text = `created ${target} (${after?.length ?? 0})`;
1234
+ else if (action === 'patch')
1235
+ text = machine.trim() === '' || machine === 'patched' ? `patched ${target}` : machine;
1236
+ return { text: clipChangeSummary(text, DEFAULT_SKILL_WRITE_SUMMARY_CHARS), source: 'host' };
1237
+ }
1221
1238
  /** Best-effort audit trail entry; never blocks the mutation.
1222
1239
  *
1223
1240
  * Two independent best-effort writes run here, because either one failing must not cost the
@@ -1233,11 +1250,17 @@ export class SkillLibrary {
1233
1250
  // migration step). Optional so existing callers keep their behaviour; the ledger stores it when
1234
1251
  // given, and old records without it stay readable.
1235
1252
  // G3a: one tree change writes N paths under ONE unit id; the entries it writes share it.
1236
- unitId, unitHead, origin, fenceHeld = false) {
1253
+ unitId, unitHead, origin, fenceHeld = false, change) {
1237
1254
  // A committed hook or outer tree operation already holds the home fence.
1238
1255
  // Keep per-file transactions, but do not queue behind our own lease.
1239
1256
  const fence = fenceHeld ? undefined : this.fence;
1240
1257
  const at = new Date().toISOString();
1258
+ const finalSummary = change === undefined
1259
+ ? this.hostChangeSummary(action, before, after, path, summary)
1260
+ : (() => {
1261
+ const normalized = normalizeChangeSummary(change.text, DEFAULT_SKILL_WRITE_SUMMARY_CHARS);
1262
+ return normalized.ok ? { text: normalized.text, source: change.source } : this.hostChangeSummary(action, before, after, path, summary);
1263
+ })();
1241
1264
  let versions = null;
1242
1265
  try {
1243
1266
  const keep = this.limits.versionKeep ?? DEFAULT_SKILL_VERSION_KEEP;
@@ -1251,6 +1274,8 @@ export class SkillLibrary {
1251
1274
  ...path === undefined ? {} : { path },
1252
1275
  ...unitId === undefined ? {} : { unitId },
1253
1276
  ...unitHead === undefined ? {} : { unitHead },
1277
+ summary: finalSummary.text,
1278
+ summarySource: finalSummary.source,
1254
1279
  };
1255
1280
  versions = await recordVersions(this.root, this.io, input, keep, fence);
1256
1281
  }
@@ -1732,6 +1757,69 @@ export class SkillLibrary {
1732
1757
  // queue so two concurrent patches on one skill never interleave.
1733
1758
  return await this.serial(() => this.patchCore(name, oldString, newString, filePath, replaceAll, origin));
1734
1759
  }
1760
+ /**
1761
+ * Replace ONE section's content (or one exact sub-block) in place. Keeps the
1762
+ * H2 heading line for whole-section edits, so a model can compress one
1763
+ * section at a time without re-sending the body. No content-conservation
1764
+ * gate: the version history is the rollback, and existing structural
1765
+ * validation still applies through {@link update}.
1766
+ * @param rawName - skill name.
1767
+ * @param edit - section selector plus replacement text.
1768
+ * @param origin - write face.
1769
+ * @returns the normalized result, with before/after body sizes.
1770
+ */
1771
+ async patchSection(rawName, edit, origin = this.authority.origin) {
1772
+ await this.ensureRecovered();
1773
+ return await this.patchSectionCore(rawName.trim(), edit, origin);
1774
+ }
1775
+ async patchSectionCore(name, edit, origin) {
1776
+ const badName = this.badName(name);
1777
+ if (badName)
1778
+ return { ok: false, message: badName };
1779
+ if (typeof edit.heading !== 'string' || edit.heading.trim() === '')
1780
+ return { ok: false, message: '章节改写需要非空 heading。' };
1781
+ const dir = this.dirOf(name);
1782
+ const path = join(dir, 'SKILL.md');
1783
+ let md;
1784
+ try {
1785
+ md = await this.io.readText(path);
1786
+ }
1787
+ catch (error) {
1788
+ return unreadableTarget(name, error);
1789
+ }
1790
+ if (md === null)
1791
+ return { ok: false, message: `技能「${name}」不存在。` };
1792
+ const block = frontmatterBlock(md);
1793
+ if (!block)
1794
+ return { ok: false, message: 'SKILL.md 没有有效的 frontmatter;拒绝章节改写。' };
1795
+ const header = block.lines.slice(0, block.end + 1).join('\n');
1796
+ const body = md.slice(header.length).replace(/\r\n/g, '\n');
1797
+ const selection = selectSections(body, [{
1798
+ heading: edit.heading,
1799
+ ...edit.start === undefined ? {} : { start: edit.start },
1800
+ ...edit.end === undefined ? {} : { end: edit.end },
1801
+ }]);
1802
+ if (!selection.ok)
1803
+ return { ok: false, message: `章节改写被拒绝:${selection.message}` };
1804
+ const section = selection.sections[0];
1805
+ if (section === undefined)
1806
+ return { ok: false, message: '章节改写被拒绝:没有匹配的章节。' };
1807
+ const lines = body.split('\n');
1808
+ // Whole-section: keep the heading itself and replace only the content
1809
+ // after it. Sub-block: replace the selected inclusive lines.
1810
+ const start = section.anchorStart === undefined ? section.start + 1 : section.start;
1811
+ const end = section.end;
1812
+ const replacement = edit.content === '' ? [] : edit.content.replace(/\r\n/g, '\n').split('\n');
1813
+ const nextBody = [...lines.slice(0, start), ...replacement, ...lines.slice(end)].join('\n');
1814
+ const next = `${header}${nextBody}`;
1815
+ const finalMd = block.nl === '\r\n' ? next.replace(/\n/g, '\r\n') : next;
1816
+ if (finalMd.trimEnd() === md.trimEnd())
1817
+ return { ok: true, message: `技能「${name}」未变更:章节内容一致,未写入。`, noop: true, path: dir };
1818
+ const result = await this.update(name, finalMd, origin, { sha256: contentHash(md) });
1819
+ if (!result.ok)
1820
+ return result;
1821
+ return { ok: true, message: `已更新「${name}」的「${edit.heading}」章节(正文 ${md.length} → ${finalMd.length} 字符)。`, path: dir };
1822
+ }
1735
1823
  async patchCore(name, oldString, newString, filePath, replaceAll, origin) {
1736
1824
  // P1-1 (v14): patch was the ONE path-building mutator without the name
1737
1825
  // guard — `name = '../outside'` plus a `file_path` escaped the skills root
@@ -1987,10 +2075,10 @@ export class SkillLibrary {
1987
2075
  }
1988
2076
  catch { /* lifecycle telemetry is best-effort; the archive already landed */ }
1989
2077
  }
1990
- async archive(rawName, options = {}, origin = this.authority.origin) {
1991
- return await this.archiveCore(rawName, options, origin, false);
2078
+ async archive(rawName, options = {}, origin = this.authority.origin, change) {
2079
+ return await this.archiveCore(rawName, options, origin, false, change);
1992
2080
  }
1993
- async archiveCore(rawName, options, origin, fenceHeld) {
2081
+ async archiveCore(rawName, options, origin, fenceHeld, change) {
1994
2082
  // One trim per entry: paths (dirOf), validation and messages all see the same name.
1995
2083
  const name = rawName.trim();
1996
2084
  const badName = this.badName(name, { allowReserved: true });
@@ -2104,7 +2192,7 @@ export class SkillLibrary {
2104
2192
  catch {
2105
2193
  // Same posture as .archive-reason: metadata only, never abort the archive.
2106
2194
  }
2107
- await this.audit(name, 'archive', md, null, reason, undefined, options.unitId, options.unitHead, origin, fenceHeld);
2195
+ await this.audit(name, 'archive', md, null, reason, undefined, options.unitId, options.unitHead, origin, fenceHeld, change);
2108
2196
  this.notifyMutation({ action: 'archive', name, archivedPath: dest });
2109
2197
  return { ok: true, message: `技能「${name}」已归档到 .archive。`, path: dest };
2110
2198
  }
@@ -2788,14 +2876,14 @@ export class SkillLibrary {
2788
2876
  * support-directory links is refused (those links' files stay behind in the
2789
2877
  * same package; the moved text belongs in references/ beside them).
2790
2878
  */
2791
- async restructure(rawName, moves, origin = this.authority.origin) {
2879
+ async restructure(rawName, moves, origin = this.authority.origin, change) {
2792
2880
  const name = rawName.trim();
2793
2881
  await this.ensureRecovered();
2794
2882
  // F-208: the whole read→plan→write runs under the in-process serialize
2795
2883
  // queue so two concurrent restructures on one skill never interleave.
2796
- return await this.restructureCore(name, moves, origin);
2884
+ return await this.restructureCore(name, moves, origin, change);
2797
2885
  }
2798
- async restructureCore(name, moves, origin) {
2886
+ async restructureCore(name, moves, origin, change) {
2799
2887
  const badName = this.badName(name);
2800
2888
  if (badName)
2801
2889
  return { ok: false, message: badName };
@@ -2816,6 +2904,12 @@ export class SkillLibrary {
2816
2904
  if (typeof move.heading !== 'string' || !move.heading.trim()) {
2817
2905
  return { ok: false, message: '每次重构搬移都需要非空的 heading。' };
2818
2906
  }
2907
+ if ((move.start === undefined) !== (move.end === undefined)) {
2908
+ return { ok: false, message: '子块搬移必须同时提供 start 和 end。' };
2909
+ }
2910
+ if (move.start !== undefined && (typeof move.start !== 'string' || typeof move.end !== 'string' || !move.start.trim() || !move.end.trim())) {
2911
+ return { ok: false, message: '子块搬移的 start/end 必须是匹配行的非空文本。' };
2912
+ }
2819
2913
  // A1-6 (v18): reuse the single validator (regex + Windows device stems)
2820
2914
  // so restructure cannot mint a target the support-file layer refuses.
2821
2915
  const targetIssue = validateRestructureTarget(move.toFile);
@@ -2914,7 +3008,7 @@ export class SkillLibrary {
2914
3008
  let headPlaced = false;
2915
3009
  for (const op of event.ops) {
2916
3010
  const rel = relative(dir, op.target).split(String.fromCharCode(92)).join('/');
2917
- await this.audit(name, 'restructure', op.before, op.after, summary, rel === 'SKILL.md' ? undefined : rel, event.unitId, headPlaced ? undefined : this.unitHeadForOps(event.ops, [name]), origin, true);
3011
+ await this.audit(name, 'restructure', op.before, op.after, summary, rel === 'SKILL.md' ? undefined : rel, event.unitId, headPlaced ? undefined : this.unitHeadForOps(event.ops, [name]), origin, true, change);
2918
3012
  headPlaced = true;
2919
3013
  }
2920
3014
  this.notifyMutation({ action: 'restructure', name, skillDir: dir });
@@ -2939,7 +3033,7 @@ export class SkillLibrary {
2939
3033
  });
2940
3034
  if (!result.ok)
2941
3035
  return { ok: false, message: result.errors.map(error => error.message).join(';') };
2942
- return { ok: true, message: `已重构「${name}」:把 ${plan.sections.length} 个章节搬到 references/。`, path: dir };
3036
+ return { ok: true, message: `已重构「${name}」:把 ${plan.sections.length} 个章节搬到 references/(正文 ${md.length} → ${finalMd.length} 字符)。`, path: dir };
2943
3037
  }
2944
3038
  /**
2945
3039
  * Unified tree-change commit point (009 kernel): owns validation order,
@@ -2956,7 +3050,7 @@ export class SkillLibrary {
2956
3050
  * @param origin - write face recorded in the audit ledger.
2957
3051
  * @returns the kernel result; a refusal writes nothing.
2958
3052
  */
2959
- async extract(plan, origin = this.authority.origin) {
3053
+ async extract(plan, origin = this.authority.origin, change) {
2960
3054
  await this.ensureRecovered();
2961
3055
  if (plan.outcome === 'owner-gap' || plan.owner.mode !== 'covered')
2962
3056
  return { ok: false, message: '提取被拒绝:owner-gap 不是写操作。' };
@@ -3042,7 +3136,7 @@ export class SkillLibrary {
3042
3136
  if (op.skill === undefined)
3043
3137
  continue;
3044
3138
  const rel = relative(this.dirOf(op.skill), op.target).split(String.fromCharCode(92)).join('/');
3045
- await this.audit(op.skill, 'extract', op.before, op.after, summary, rel === 'SKILL.md' ? undefined : rel, event.unitId, headPlaced ? undefined : head, origin, true);
3139
+ await this.audit(op.skill, 'extract', op.before, op.after, summary, rel === 'SKILL.md' ? undefined : rel, event.unitId, headPlaced ? undefined : head, origin, true, change);
3046
3140
  headPlaced = true;
3047
3141
  }
3048
3142
  for (const name of roots)
@@ -1,4 +1,2 @@
1
- import type { Context } from '@deepseek-ai/cordis';
2
- import type { SubagentChannel } from './types.ts';
3
- export declare function createSubagentChannel(ctx: Context): SubagentChannel;
1
+ export { createSubagentKernel as createSubagentChannel } from './kernel.ts';
4
2
  //# sourceMappingURL=channel.d.ts.map
@@ -1,333 +1,3 @@
1
- import { ensureRestrictedPreset } from "../composition/ensure.js";
2
- import { probeChannelState } from "./readiness.js";
3
- function serviceOf(ctx, name) {
4
- return ctx.get(name);
5
- }
6
- function messageOf(error) {
7
- return error instanceof Error ? error.message : String(error);
8
- }
9
- function textOfValue(value) {
10
- if (typeof value === 'string')
11
- return value;
12
- if (!Array.isArray(value))
13
- return '';
14
- return value
15
- .filter(block => typeof block === 'object' && block !== null && block.type === 'text')
16
- .map((block) => {
17
- const text = block.text;
18
- return typeof text === 'string' ? text : '';
19
- })
20
- .join('');
21
- }
22
- function abortLink(signal, timeoutMs) {
23
- const controller = new AbortController();
24
- const timer = setTimeout(() => { controller.abort(new Error('subagent turn timeout')); }, timeoutMs);
25
- const onAbort = () => { controller.abort(signal?.reason); };
26
- signal?.addEventListener('abort', onAbort, { once: true });
27
- return {
28
- controller,
29
- cleanup: () => {
30
- clearTimeout(timer);
31
- signal?.removeEventListener('abort', onAbort);
32
- },
33
- };
34
- }
35
- function waitForSubagentEnd(ctx, childId, signal, timeoutMs) {
36
- return new Promise((resolve, reject) => {
37
- let settled = false;
38
- const finish = (fn) => {
39
- if (settled)
40
- return;
41
- settled = true;
42
- cleanup();
43
- fn();
44
- };
45
- const eventCtx = ctx;
46
- const off = typeof eventCtx.on === 'function'
47
- ? eventCtx.on('subagent/end', (info) => {
48
- if (info.id !== childId)
49
- return;
50
- finish(() => { resolve(info); });
51
- })
52
- : () => { };
53
- const timer = setTimeout(() => {
54
- finish(() => { reject(new Error('timed out waiting for subagent/end: ' + childId)); });
55
- }, timeoutMs);
56
- const onAbort = () => {
57
- finish(() => { reject(signal.reason instanceof Error ? signal.reason : new Error('conversation turn aborted')); });
58
- };
59
- signal.addEventListener('abort', onAbort, { once: true });
60
- function cleanup() {
61
- clearTimeout(timer);
62
- signal.removeEventListener('abort', onAbort);
63
- off();
64
- }
65
- if (signal.aborted)
66
- onAbort();
67
- });
68
- }
69
- export function createSubagentChannel(ctx) {
70
- let lastKind = 'reviewer';
71
- const active = new Map();
72
- const disposed = new Set();
73
- const channel = {
74
- get state() {
75
- return probeChannelState(ctx, lastKind);
76
- },
77
- prepare(spec) {
78
- lastKind = spec.kind;
79
- const state = probeChannelState(ctx, spec.kind);
80
- if (state.kind === 'unavailable')
81
- return Promise.resolve(state);
82
- if (spec.allow.length === 0)
83
- return Promise.resolve({ kind: 'unavailable', code: 'E-324', reason: 'allow set is empty' });
84
- return Promise.resolve(state);
85
- },
86
- async run(spec) {
87
- lastKind = spec.kind;
88
- const probe = probeChannelState(ctx, spec.kind);
89
- if (probe.kind === 'unavailable')
90
- return probe;
91
- const subagents = serviceOf(ctx, 'subagents');
92
- const presets = serviceOf(ctx, 'agentPresets');
93
- if (subagents === undefined || presets === undefined) {
94
- return { kind: 'unavailable', code: 'E-323', reason: 'subagents/agentPresets service unavailable' };
95
- }
96
- const parentPresetId = presets.composedPreset(spec.parent.ctx);
97
- if (parentPresetId === undefined) {
98
- return { kind: 'unavailable', code: 'E-323', reason: 'parent preset could not be resolved' };
99
- }
100
- const ensured = await ensureRestrictedPreset(ctx, { kind: spec.kind, parentPresetId, allow: spec.allow });
101
- if (ensured.kind === 'failed') {
102
- return { kind: 'unavailable', code: 'E-324', reason: ensured.reason };
103
- }
104
- const controller = new AbortController();
105
- const timer = setTimeout(() => { controller.abort(new Error('subagent timeout')); }, spec.timeoutMs);
106
- const onAbort = () => { controller.abort(spec.signal?.reason); };
107
- spec.signal?.addEventListener('abort', onAbort, { once: true });
108
- let activation;
109
- try {
110
- activation = await subagents.startActivation({
111
- provider: 'spawn',
112
- label: spec.label,
113
- delivery: 'caller',
114
- request: {
115
- parent: spec.parent,
116
- prompt: [{ type: 'text', text: spec.promptText }],
117
- agentPreset: ensured.presetId,
118
- ...(spec.outputSchema !== undefined ? { outputSchema: spec.outputSchema } : {}),
119
- ...(spec.maxDepth !== undefined ? { maxDepth: spec.maxDepth } : {}),
120
- ...(spec.agentOptions !== undefined ? { agentOptions: spec.agentOptions } : {}),
121
- },
122
- signal: controller.signal,
123
- });
124
- let result;
125
- try {
126
- result = await activation.result;
127
- }
128
- catch (error) {
129
- if (controller.signal.aborted)
130
- return { kind: 'aborted' };
131
- return { kind: 'unavailable', code: 'E-323', reason: messageOf(error) };
132
- }
133
- let evidence;
134
- if (spec.afterResult !== undefined) {
135
- try {
136
- const agents = serviceOf(ctx, 'agents');
137
- const child = agents?.get(activation.childId);
138
- if (child !== undefined)
139
- evidence = spec.afterResult(child);
140
- }
141
- catch {
142
- evidence = undefined;
143
- }
144
- }
145
- const stopReason = result.stopReason;
146
- // W5 §3: OK requires BOTH a completed stop and a structured payload; a completed run that
147
- // produced nothing must stay a no-structured outcome so the business layer cannot treat an
148
- // empty result as a plan.
149
- if (stopReason === 'completed' && result.structured !== undefined && result.structured !== null) {
150
- return {
151
- kind: 'ok',
152
- structured: result.structured,
153
- childId: activation.childId,
154
- stopReason: 'completed',
155
- ...(evidence !== undefined ? { evidence } : {}),
156
- };
157
- }
158
- if (stopReason === 'aborted')
159
- return { kind: 'aborted' };
160
- return {
161
- kind: 'no-structured',
162
- childId: activation.childId,
163
- stopReason,
164
- ...(result.diagnostic !== undefined ? { diagnostic: result.diagnostic } : {}),
165
- ...(evidence !== undefined ? { evidence } : {}),
166
- };
167
- }
168
- catch (error) {
169
- if (controller.signal.aborted)
170
- return { kind: 'aborted' };
171
- return { kind: 'unavailable', code: 'E-323', reason: messageOf(error) };
172
- }
173
- finally {
174
- clearTimeout(timer);
175
- spec.signal?.removeEventListener('abort', onAbort);
176
- if (activation !== undefined) {
177
- try {
178
- await activation.dispose();
179
- }
180
- catch (error) {
181
- // W5 §6: teardown failures are observable but must NOT replace the captured outcome.
182
- try {
183
- ctx.logger.warn('subagent channel: activation dispose failed: ' + messageOf(error));
184
- }
185
- catch { /* logging must not mask teardown */ }
186
- }
187
- }
188
- }
189
- },
190
- async open(spec) {
191
- lastKind = spec.kind;
192
- const probe = probeChannelState(ctx, spec.kind);
193
- if (probe.kind === 'unavailable')
194
- return probe;
195
- if (spec.allow.length === 0)
196
- return { kind: 'unavailable', code: 'E-324', reason: 'allow set is empty' };
197
- const subagents = serviceOf(ctx, 'subagents');
198
- const presets = serviceOf(ctx, 'agentPresets');
199
- if (subagents === undefined || presets === undefined) {
200
- return { kind: 'unavailable', code: 'E-323', reason: 'subagents/agentPresets service unavailable' };
201
- }
202
- const parentPresetId = presets.composedPreset(spec.parent.ctx);
203
- if (parentPresetId === undefined) {
204
- return { kind: 'unavailable', code: 'E-323', reason: 'parent preset could not be resolved' };
205
- }
206
- const ensured = await ensureRestrictedPreset(ctx, { kind: spec.kind, parentPresetId, allow: spec.allow });
207
- if (ensured.kind === 'failed')
208
- return { kind: 'unavailable', code: 'E-324', reason: ensured.reason };
209
- const link = abortLink(spec.signal, spec.timeoutMs);
210
- let activation;
211
- try {
212
- activation = await subagents.startActivation({
213
- provider: 'spawn',
214
- label: spec.label,
215
- delivery: 'caller',
216
- request: {
217
- parent: spec.parent,
218
- prompt: [{ type: 'text', text: spec.promptText }],
219
- agentPreset: ensured.presetId,
220
- ...(spec.cwd !== undefined ? { cwd: spec.cwd } : {}),
221
- ...(spec.maxDepth !== undefined ? { maxDepth: spec.maxDepth } : {}),
222
- ...(spec.agentOptions !== undefined ? { agentOptions: spec.agentOptions } : {}),
223
- },
224
- signal: link.controller.signal,
225
- });
226
- const result = await activation.result;
227
- if (result.stopReason === 'aborted') {
228
- try {
229
- await activation.dispose();
230
- }
231
- catch { /* teardown must not replace the outcome */ }
232
- return { kind: 'aborted' };
233
- }
234
- if (result.stopReason !== 'completed') {
235
- try {
236
- await activation.dispose();
237
- }
238
- catch { /* teardown must not replace the outcome */ }
239
- return { kind: 'unavailable', code: 'E-323', reason: 'round 1 did not complete: ' + result.stopReason };
240
- }
241
- const turn = {
242
- childId: activation.childId,
243
- stopReason: result.stopReason,
244
- text: textOfValue(result.output),
245
- ...(result.structured !== undefined ? { structured: result.structured } : {}),
246
- ...(result.diagnostic !== undefined ? { diagnostic: result.diagnostic } : {}),
247
- };
248
- active.set(activation.childId, { childId: activation.childId, parent: spec.parent, activation, disposed: false });
249
- disposed.delete(activation.childId);
250
- return { kind: 'ok', childId: activation.childId, turn };
251
- }
252
- catch (error) {
253
- if (activation !== undefined) {
254
- try {
255
- await activation.dispose();
256
- }
257
- catch { /* teardown must not replace the outcome */ }
258
- }
259
- if (link.controller.signal.aborted)
260
- return { kind: 'aborted' };
261
- return { kind: 'unavailable', code: 'E-323', reason: messageOf(error) };
262
- }
263
- finally {
264
- link.cleanup();
265
- }
266
- },
267
- async continueTurn(childId, promptText, options) {
268
- if (disposed.has(childId))
269
- return { kind: 'unavailable', code: 'E-324', reason: 'conversation is disposed' };
270
- const current = active.get(childId);
271
- if (current === undefined || current.disposed) {
272
- return { kind: 'unavailable', code: 'E-323', reason: 'no open conversation for ' + childId };
273
- }
274
- const subagents = serviceOf(ctx, 'subagents');
275
- if (subagents?.sendMessage === undefined) {
276
- return { kind: 'unavailable', code: 'E-323', reason: 'subagents.sendMessage unavailable' };
277
- }
278
- const link = abortLink(options?.signal, options?.timeoutMs ?? 120_000);
279
- let pending;
280
- try {
281
- pending = waitForSubagentEnd(ctx, childId, link.controller.signal, options?.timeoutMs ?? 120_000);
282
- await subagents.sendMessage(current.parent, childId, [{ type: 'text', text: promptText }], { signal: link.controller.signal });
283
- }
284
- catch (error) {
285
- link.cleanup();
286
- if (options?.signal?.aborted === true)
287
- return { kind: 'aborted' };
288
- return { kind: 'unavailable', code: 'E-323', reason: messageOf(error) };
289
- }
290
- try {
291
- const info = await pending;
292
- if (info.stopReason === 'aborted')
293
- return { kind: 'aborted' };
294
- const turn = {
295
- childId,
296
- stopReason: info.stopReason ?? 'completed',
297
- text: textOfValue(info.lastAssistantMessage),
298
- ...(info.diagnostic !== undefined ? { diagnostic: info.diagnostic } : {}),
299
- };
300
- return { kind: 'ok', childId, turn };
301
- }
302
- catch (error) {
303
- if (options?.signal?.aborted === true)
304
- return { kind: 'aborted' };
305
- return { kind: 'unavailable', code: 'E-323', reason: messageOf(error) };
306
- }
307
- finally {
308
- link.cleanup();
309
- }
310
- },
311
- async dispose(childId) {
312
- const current = active.get(childId);
313
- if (current === undefined || current.disposed) {
314
- disposed.add(childId);
315
- return;
316
- }
317
- current.disposed = true;
318
- active.delete(childId);
319
- disposed.add(childId);
320
- try {
321
- await current.activation.dispose();
322
- }
323
- catch (error) {
324
- try {
325
- ctx.logger.warn('subagent conversation: dispose failed: ' + messageOf(error));
326
- }
327
- catch { /* logging must not mask teardown */ }
328
- }
329
- },
330
- };
331
- return channel;
332
- }
1
+ // Thin compatibility adapter: the execution kernel owns one implementation.
2
+ export { createSubagentKernel as createSubagentChannel } from "./kernel.js";
333
3
  //# sourceMappingURL=channel.js.map
@@ -1,4 +1,6 @@
1
1
  export * from './types.ts';
2
2
  export * from './readiness.ts';
3
+ export * from './run.ts';
4
+ export * from './kernel.ts';
3
5
  export * from './channel.ts';
4
6
  //# sourceMappingURL=index.d.ts.map
@@ -1,5 +1,7 @@
1
1
  // Subagent channel contract + implementation (types/readiness/channel split for one owner each).
2
2
  export * from "./types.js";
3
3
  export * from "./readiness.js";
4
+ export * from "./run.js";
5
+ export * from "./kernel.js";
4
6
  export * from "./channel.js";
5
7
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,4 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import type { SubagentChannel } from './types.ts';
3
+ export declare function createSubagentKernel(ctx: Context): SubagentChannel;
4
+ //# sourceMappingURL=kernel.d.ts.map