@oyasmi/pipiclaw 0.9.3-beta.3 → 0.9.3-beta.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 (126) hide show
  1. package/README.en.md +12 -12
  2. package/README.md +12 -12
  3. package/dist/agent/channel-runner.d.ts +4 -18
  4. package/dist/agent/channel-runner.js +26 -121
  5. package/dist/agent/context-budget.js +1 -1
  6. package/dist/agent/job-manager.d.ts +11 -17
  7. package/dist/agent/job-manager.js +77 -67
  8. package/dist/agent/prompt/builder.js +1 -17
  9. package/dist/agent/prompt/manifest.d.ts +0 -1
  10. package/dist/agent/prompt/manifest.js +2 -2
  11. package/dist/agent/prompt/sections.js +0 -9
  12. package/dist/agent/prompt/types.d.ts +2 -18
  13. package/dist/agent/prompt/types.js +1 -1
  14. package/dist/agent/runner-factory.d.ts +4 -0
  15. package/dist/agent/session-adapter.d.ts +19 -0
  16. package/dist/agent/session-adapter.js +77 -0
  17. package/dist/app-services.d.ts +18 -0
  18. package/dist/app-services.js +43 -0
  19. package/dist/channel/channel-context.d.ts +2 -2
  20. package/dist/channel/channel-context.js +2 -2
  21. package/dist/channel/channel-event.d.ts +3 -3
  22. package/dist/{runtime → events}/events.d.ts +1 -1
  23. package/dist/memory/journal.js +1 -1
  24. package/dist/memory/maintenance-gates.d.ts +0 -3
  25. package/dist/memory/maintenance-gates.js +2 -2
  26. package/dist/memory/maintenance-migration.d.ts +5 -0
  27. package/dist/memory/maintenance-migration.js +91 -0
  28. package/dist/memory/maintenance-state.js +5 -44
  29. package/dist/memory/migrate.js +1 -1
  30. package/dist/memory/reflect-job.d.ts +1 -9
  31. package/dist/memory/reflect-job.js +1 -3
  32. package/dist/memory/reflect.js +1 -1
  33. package/dist/memory/session-corpus.js +1 -1
  34. package/dist/memory/store.js +1 -1
  35. package/dist/models/auth-cli.js +1 -1
  36. package/dist/playbooks/agent-delegation.md +15 -11
  37. package/dist/playbooks/background-jobs.md +1 -1
  38. package/dist/playbooks/runtime-orientation.md +2 -0
  39. package/dist/playbooks/task-loop.md +1 -1
  40. package/dist/runtime/bootstrap.d.ts +5 -15
  41. package/dist/runtime/bootstrap.js +44 -65
  42. package/dist/runtime/delivery.d.ts +1 -2
  43. package/dist/runtime/delivery.js +57 -62
  44. package/dist/runtime/dingtalk.d.ts +15 -8
  45. package/dist/runtime/dingtalk.js +101 -35
  46. package/dist/runtime/subagent-commands.d.ts +2 -1
  47. package/dist/runtime/subagent-commands.js +10 -12
  48. package/dist/runtime/task-wake.d.ts +4 -5
  49. package/dist/runtime/task-wake.js +2 -12
  50. package/dist/security/types.d.ts +7 -0
  51. package/dist/security/types.js +16 -1
  52. package/dist/settings.d.ts +8 -0
  53. package/dist/settings.js +24 -1
  54. package/dist/shared/exact-keys.d.ts +13 -0
  55. package/dist/shared/exact-keys.js +1 -0
  56. package/dist/shared/format.d.ts +20 -0
  57. package/dist/shared/format.js +64 -0
  58. package/dist/shared/{fs-utils.d.ts → os.d.ts} +6 -0
  59. package/dist/shared/{fs-utils.js → os.js} +8 -0
  60. package/dist/subagents/discovery.d.ts +16 -3
  61. package/dist/subagents/discovery.js +13 -9
  62. package/dist/subagents/external/claude-code.js +3 -1
  63. package/dist/subagents/external/harness.d.ts +4 -2
  64. package/dist/subagents/external/run.d.ts +2 -1
  65. package/dist/subagents/external/run.js +13 -5
  66. package/dist/subagents/external/settlement.js +10 -5
  67. package/dist/subagents/format.d.ts +1 -1
  68. package/dist/subagents/format.js +1 -1
  69. package/dist/subagents/runs.d.ts +13 -12
  70. package/dist/subagents/runs.js +109 -91
  71. package/dist/subagents/tool.d.ts +7 -7
  72. package/dist/subagents/tool.js +11 -11
  73. package/dist/tasks/brief.js +1 -0
  74. package/dist/tools/command-optimizer.js +1 -1
  75. package/dist/tools/config.d.ts +7 -0
  76. package/dist/tools/config.js +16 -1
  77. package/dist/tools/event-manage.d.ts +1 -1
  78. package/dist/tools/event-manage.js +3 -3
  79. package/dist/tools/grep.js +1 -1
  80. package/dist/tools/index.d.ts +4 -0
  81. package/dist/tools/index.js +4 -2
  82. package/dist/tools/job.js +1 -1
  83. package/dist/tools/read.js +1 -1
  84. package/dist/tools/registry.d.ts +3 -3
  85. package/dist/tools/registry.js +18 -56
  86. package/dist/tools/skill.js +1 -1
  87. package/dist/tools/subagent-manage.d.ts +2 -0
  88. package/dist/tools/subagent-manage.js +7 -7
  89. package/dist/tools/subagent-tool-names.d.ts +2 -2
  90. package/dist/tools/subagent-tool-names.js +2 -2
  91. package/dist/tools/task-manage/shared.js +4 -9
  92. package/dist/tools/task-manage/types.d.ts +4 -0
  93. package/dist/tui/app.js +22 -7
  94. package/dist/web/config.js +1 -1
  95. package/examples/sub-agents/README.md +65 -81
  96. package/examples/sub-agents/agents/claude-high.md +23 -0
  97. package/examples/sub-agents/agents/claude-main.md +23 -0
  98. package/examples/sub-agents/agents/codex-flash.md +23 -0
  99. package/examples/sub-agents/agents/codex-high.md +23 -0
  100. package/examples/sub-agents/agents/codex-main.md +23 -0
  101. package/examples/sub-agents/agents/glm-flash.md +23 -0
  102. package/examples/sub-agents/agents/glm-high.md +23 -0
  103. package/package.json +2 -1
  104. package/dist/shared/duration.d.ts +0 -2
  105. package/dist/shared/duration.js +0 -7
  106. package/dist/shared/file-stamp.d.ts +0 -10
  107. package/dist/shared/file-stamp.js +0 -19
  108. package/dist/shared/numeric.d.ts +0 -7
  109. package/dist/shared/numeric.js +0 -19
  110. package/dist/shared/shell-escape.d.ts +0 -5
  111. package/dist/shared/shell-escape.js +0 -7
  112. package/dist/shared/token-estimate.d.ts +0 -1
  113. package/dist/shared/token-estimate.js +0 -19
  114. /package/dist/{runtime → events}/event-commands.d.ts +0 -0
  115. /package/dist/{runtime → events}/event-commands.js +0 -0
  116. /package/dist/{runtime → events}/event-validation.d.ts +0 -0
  117. /package/dist/{runtime → events}/event-validation.js +0 -0
  118. /package/dist/{runtime → events}/events.js +0 -0
  119. /package/examples/sub-agents/{builder-hard.md → roles/builder-hard.md} +0 -0
  120. /package/examples/sub-agents/{builder.md → roles/builder.md} +0 -0
  121. /package/examples/sub-agents/{explorer.md → roles/explorer.md} +0 -0
  122. /package/examples/sub-agents/{git-committer.md → roles/git-committer.md} +0 -0
  123. /package/examples/sub-agents/{planner.md → roles/planner.md} +0 -0
  124. /package/examples/sub-agents/{reviewer.md → roles/reviewer.md} +0 -0
  125. /package/examples/sub-agents/{verifier.md → roles/verifier.md} +0 -0
  126. /package/examples/sub-agents/{worker.md → roles/worker.md} +0 -0
@@ -95,7 +95,7 @@ const SUPPORTED_FILE_TYPES = new Set(["xlsx", "pdf", "zip", "rar", "doc", "docx"
95
95
  // hung connection, and a stalled card-streaming request would wedge the delivery
96
96
  // sync loop (never resolving flush()), leaving the whole channel permanently busy.
97
97
  // A timeout turns "hang" into a normal failure that the existing fallback paths
98
- // (discardCard / replay / sendPlain) already handle.
98
+ // (bounded snapshot replay / sendPlain) already handle.
99
99
  const DINGTALK_HTTP_TIMEOUT_MS = 15_000;
100
100
  const http = axios.create({ timeout: DINGTALK_HTTP_TIMEOUT_MS });
101
101
  // Bounds enqueueStreamMessage (user messages + busy-message requeues), mirroring the
@@ -129,9 +129,9 @@ export class DingTalkBot {
129
129
  this.tokenRefreshPromise = null;
130
130
  // Active AI cards: channelId → AICard
131
131
  this.activeCards = new Map();
132
- // Singleflight for card creation: warmup and the first progress update can
133
- // race before activeCards is populated, which would create two cards. Sharing
134
- // the in-flight promise per channel guarantees at most one create call.
132
+ this.cardGenerations = new Map();
133
+ this.cardCreationAttempted = new Set();
134
+ // Share creation within a turn, but never let a late old turn own a new turn's card.
135
135
  this.cardCreationInFlight = new Map();
136
136
  // Conversation metadata cache: channelId → metadata
137
137
  this.convMeta = new Map();
@@ -607,28 +607,38 @@ export class DingTalkBot {
607
607
  // ==========================================================================
608
608
  // AI Card operations
609
609
  // ==========================================================================
610
- /**
611
- * Get or create an AI Card for a channel.
612
- */
613
- async ensureCard(channelId) {
614
- if (!this.config.cardTemplateId)
610
+ /** Capture the current turn's identity; close, /stop and /new invalidate it. */
611
+ getCardGeneration(channelId) {
612
+ let generation = this.cardGenerations.get(channelId);
613
+ if (!generation) {
614
+ generation = Symbol(channelId);
615
+ this.cardGenerations.set(channelId, generation);
616
+ }
617
+ return generation;
618
+ }
619
+ isCardGenerationCurrent(channelId, generation) {
620
+ return this.cardGenerations.get(channelId) === generation;
621
+ }
622
+ /** Get or create an AI card without joining an earlier turn's in-flight creation. */
623
+ async ensureCard(channelId, generation = this.getCardGeneration(channelId)) {
624
+ if (!this.config.cardTemplateId || !this.isCardGenerationCurrent(channelId, generation))
615
625
  return;
616
626
  const existing = this.activeCards.get(channelId);
617
627
  if (existing && !existing.finished)
618
628
  return;
619
- await this.createCard(channelId);
629
+ await this.createCard(channelId, generation);
620
630
  }
621
631
  /**
622
632
  * Replace the active card content with a full snapshot.
623
633
  */
624
- async replaceCard(channelId, content, finalize = false, failed = false) {
625
- return this.writeCard(channelId, content, { append: false, finalize, failed });
634
+ async replaceCard(channelId, content, finalize = false, failed = false, generation = this.getCardGeneration(channelId)) {
635
+ return this.writeCard(channelId, content, { append: false, finalize, failed }, generation);
626
636
  }
627
637
  /**
628
638
  * Append a delta to the active card transcript.
629
639
  */
630
- async appendToCard(channelId, content, finalize = false, failed = false) {
631
- return this.writeCard(channelId, content, { append: true, finalize, failed });
640
+ async appendToCard(channelId, content, finalize = false, failed = false, generation = this.getCardGeneration(channelId)) {
641
+ return this.writeCard(channelId, content, { append: true, finalize, failed }, generation);
632
642
  }
633
643
  /**
634
644
  * Shared body of `replaceCard`/`appendToCard`: whether to open a fresh card differs between the
@@ -637,7 +647,9 @@ export class DingTalkBot {
637
647
  * being collapsed away — everything after it (stream, then drop the card on finalize/failed/a
638
648
  * failed stream) is identical either way.
639
649
  */
640
- async writeCard(channelId, content, options) {
650
+ async writeCard(channelId, content, options, generation) {
651
+ if (!this.isCardGenerationCurrent(channelId, generation))
652
+ return false;
641
653
  const { append, finalize, failed } = options;
642
654
  if (append && !content && !finalize && !failed) {
643
655
  return true;
@@ -647,17 +659,18 @@ export class DingTalkBot {
647
659
  ? !finalize && !failed && content.trim().length > 0
648
660
  : content.trim().length > 0 || !finalize || failed;
649
661
  if ((!card || card.finished) && this.config.cardTemplateId && shouldEnsure) {
650
- await this.ensureCard(channelId);
662
+ await this.ensureCard(channelId, generation);
663
+ if (!this.isCardGenerationCurrent(channelId, generation))
664
+ return false;
651
665
  card = this.activeCards.get(channelId);
652
666
  }
653
667
  if (!card || card.finished) {
654
- if (finalize && content.trim()) {
655
- return this.sendPlain(channelId, content);
656
- }
657
668
  return false;
658
669
  }
659
- const streamed = await this.streamCard(card, content, { append, finalize, failed });
660
- if (!streamed || finalize || failed) {
670
+ // Never erase a visible card, including callers finishing with no new text.
671
+ const snapshot = !append && !content.trim() ? card.content || "处理已结束。" : content;
672
+ const streamed = await this.streamCard(card, snapshot, { append, finalize, failed });
673
+ if (streamed && (finalize || failed) && this.activeCards.get(channelId) === card) {
661
674
  this.activeCards.delete(channelId);
662
675
  }
663
676
  return streamed;
@@ -665,15 +678,37 @@ export class DingTalkBot {
665
678
  /**
666
679
  * Finalize and remove the active card for a channel.
667
680
  */
668
- async finalizeCard(channelId, content) {
669
- const finalized = await this.replaceCard(channelId, content, true, false);
670
- if (!finalized) {
681
+ async finalizeCard(channelId, content, generation = this.getCardGeneration(channelId)) {
682
+ if (!content.trim() || !this.isCardGenerationCurrent(channelId, generation))
683
+ return false;
684
+ const finalized = await this.replaceCard(channelId, content, true, false, generation);
685
+ if (!finalized && this.isCardGenerationCurrent(channelId, generation)) {
671
686
  return this.sendPlain(channelId, content);
672
687
  }
673
- return true;
688
+ return finalized;
674
689
  }
675
- discardCard(channelId) {
690
+ /** Finish progress only: never create a card or send a fallback chat message. */
691
+ async finalizeExistingCard(channelId, content, generation = this.getCardGeneration(channelId)) {
692
+ if (!this.isCardGenerationCurrent(channelId, generation) || !this.activeCards.has(channelId))
693
+ return false;
694
+ return this.replaceCard(channelId, content, true, false, generation);
695
+ }
696
+ /** Invalidate this turn's local state. This is not a remote message deletion. */
697
+ discardCard(channelId, generation = this.cardGenerations.get(channelId)) {
698
+ if (!generation || !this.isCardGenerationCurrent(channelId, generation))
699
+ return;
700
+ this.cardGenerations.delete(channelId);
701
+ this.cardCreationAttempted.delete(generation);
702
+ const card = this.activeCards.get(channelId);
676
703
  this.activeCards.delete(channelId);
704
+ // /stop and /new may invalidate a turn before its controller gets to finish.
705
+ if (card && !card.finished) {
706
+ void this.streamCard(card, `${card.content || "正在处理…"}\n\n处理已结束。`, {
707
+ append: false,
708
+ finalize: true,
709
+ failed: false,
710
+ });
711
+ }
677
712
  }
678
713
  /**
679
714
  * Send a normal message natively mapping DM and Group to correct endpoints (fallback when no card).
@@ -917,7 +952,7 @@ export class DingTalkBot {
917
952
  // ==========================================================================
918
953
  // Private - AI Card implementation
919
954
  // ==========================================================================
920
- async createCard(channelId) {
955
+ async createCard(channelId, generation) {
921
956
  // Re-check under the singleflight: a concurrent caller may have already
922
957
  // created the card while we awaited, so avoid a duplicate create.
923
958
  const existing = this.activeCards.get(channelId);
@@ -925,18 +960,24 @@ export class DingTalkBot {
925
960
  return existing;
926
961
  }
927
962
  const inFlight = this.cardCreationInFlight.get(channelId);
928
- if (inFlight) {
929
- return inFlight;
963
+ if (inFlight?.generation === generation) {
964
+ return inFlight.promise;
930
965
  }
931
- const creation = this.createCardUncached(channelId).finally(() => {
932
- this.cardCreationInFlight.delete(channelId);
966
+ // A failed create may already have reached DingTalk. Never mint another ID in this turn.
967
+ if (this.cardCreationAttempted.has(generation))
968
+ return null;
969
+ this.cardCreationAttempted.add(generation);
970
+ const creation = this.createCardUncached(channelId, generation).finally(() => {
971
+ if (this.cardCreationInFlight.get(channelId)?.generation === generation) {
972
+ this.cardCreationInFlight.delete(channelId);
973
+ }
933
974
  });
934
- this.cardCreationInFlight.set(channelId, creation);
975
+ this.cardCreationInFlight.set(channelId, { generation, promise: creation });
935
976
  return creation;
936
977
  }
937
- async createCardUncached(channelId) {
978
+ async createCardUncached(channelId, generation) {
938
979
  const token = await this.getAccessToken();
939
- if (!token)
980
+ if (!token || !this.isCardGenerationCurrent(channelId, generation))
940
981
  return null;
941
982
  const meta = this.getConversationMeta(channelId);
942
983
  if (!meta) {
@@ -957,6 +998,7 @@ export class DingTalkBot {
957
998
  outTrackId: instanceId,
958
999
  cardData: {
959
1000
  cardParamMap: {
1001
+ [this.config.cardTemplateKey || "content"]: "正在处理…",
960
1002
  sys_full_json_obj: JSON.stringify({
961
1003
  config: {
962
1004
  autoLayout: this.config.cardAutoLayout ?? true,
@@ -1000,13 +1042,33 @@ export class DingTalkBot {
1000
1042
  templateKey: this.config.cardTemplateKey || "content",
1001
1043
  createdAt: Date.now() / 1000,
1002
1044
  lastUpdated: Date.now() / 1000,
1003
- content: "",
1045
+ content: "正在处理…",
1004
1046
  finished: false,
1005
1047
  };
1048
+ if (!this.isCardGenerationCurrent(channelId, generation)) {
1049
+ await this.streamCard(card, "处理已结束。", { append: false, finalize: true, failed: false });
1050
+ return null;
1051
+ }
1006
1052
  this.activeCards.set(channelId, card);
1007
1053
  return card;
1008
1054
  }
1009
1055
  async streamCard(card, content, options) {
1056
+ // A stop/new-session close can arrive while the prior HTTP write is in flight.
1057
+ // Order writes by instance so that close remains the last update to the old card.
1058
+ const pending = (card.pendingWrite ?? Promise.resolve(true))
1059
+ .then(async () => {
1060
+ if (card.finished)
1061
+ return false;
1062
+ return this.streamCardRequest(card, content, options);
1063
+ })
1064
+ .catch((error) => {
1065
+ log.logWarning("DingTalk Card: streaming failed", errorMessage(error));
1066
+ return false;
1067
+ });
1068
+ card.pendingWrite = pending;
1069
+ return pending;
1070
+ }
1071
+ async streamCardRequest(card, content, options) {
1010
1072
  // Refresh token if needed
1011
1073
  const ageSecs = Date.now() / 1000 - card.createdAt;
1012
1074
  if (ageSecs > TOKEN_REFRESH_SECS) {
@@ -1342,6 +1404,10 @@ export class DingTalkBot {
1342
1404
  if (card && card.lastUpdated * 1000 > cutoff)
1343
1405
  continue;
1344
1406
  this.activeCards.delete(channelId);
1407
+ const generation = this.cardGenerations.get(channelId);
1408
+ if (generation)
1409
+ this.cardCreationAttempted.delete(generation);
1410
+ this.cardGenerations.delete(channelId);
1345
1411
  this.convMeta.delete(channelId);
1346
1412
  this.queues.delete(channelId);
1347
1413
  this.channelLastActiveAt.delete(channelId);
@@ -1,11 +1,12 @@
1
1
  import type { SubAgentDiscoveryResult } from "../subagents/discovery.js";
2
- import { type RunNotice } from "../subagents/runs.js";
2
+ import type { RunNotice, SubAgentRunManager } from "../subagents/runs.js";
3
3
  /**
4
4
  * `/subagents` — the human control path that does not depend on the model (spec 040 D6, polished
5
5
  * by spec 041). Mirrors `task-commands.ts`'s shape: pure functions returning markdown, no
6
6
  * bot/event coupling.
7
7
  */
8
8
  export interface HandleSubagentsCommandOptions {
9
+ runManager: SubAgentRunManager;
9
10
  args: string;
10
11
  channelId: string;
11
12
  /** Best-effort role-directory snapshot for `roles` / the overview tail; omitted when no runner
@@ -1,10 +1,9 @@
1
1
  import { readFile } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
3
  import { renderSubcommandUsage } from "../commands/catalog.js";
4
- import { formatDuration } from "../shared/duration.js";
4
+ import { formatDuration } from "../shared/format.js";
5
5
  import { errorMessage } from "../shared/text-utils.js";
6
6
  import { formatCost, formatRunDuration, harnessLabel } from "../subagents/format.js";
7
- import { getSubAgentRunManager } from "../subagents/runs.js";
8
7
  function usage() {
9
8
  return `${renderSubcommandUsage("subagents")}\n\n\`runId\` 支持不带 \`run_\` 前缀的简写,只要能唯一匹配即可,例如 \`show a1b2c3\`。`;
10
9
  }
@@ -113,7 +112,7 @@ function capListForDisplay(records) {
113
112
  };
114
113
  }
115
114
  async function listRuns(options, filter) {
116
- const records = getSubAgentRunManager(options.channelId).list();
115
+ const records = options.runManager.list();
117
116
  if (records.length === 0)
118
117
  return "**委派 Run**\n\n没有委派记录。";
119
118
  const running = records.filter((record) => record.status === "running").sort((a, b) => b.startedAt - a.startedAt);
@@ -170,8 +169,8 @@ function formatRunResolution(resolution, ref) {
170
169
  }
171
170
  return undefined;
172
171
  }
173
- async function showRun(channelId, ref) {
174
- const resolution = getSubAgentRunManager(channelId).resolveRef(ref);
172
+ async function showRun(manager, ref) {
173
+ const resolution = manager.resolveRef(ref);
175
174
  const error = formatRunResolution(resolution, ref);
176
175
  if (error || resolution.kind !== "found")
177
176
  return error ?? `未找到 run:\`${ref}\``;
@@ -225,8 +224,8 @@ async function showRun(channelId, ref) {
225
224
  }
226
225
  return lines.join("\n");
227
226
  }
228
- async function showOutput(channelId, ref) {
229
- const resolution = getSubAgentRunManager(channelId).resolveRef(ref);
227
+ async function showOutput(manager, ref) {
228
+ const resolution = manager.resolveRef(ref);
230
229
  const error = formatRunResolution(resolution, ref);
231
230
  if (error || resolution.kind !== "found")
232
231
  return error ?? `未找到 run:\`${ref}\``;
@@ -240,8 +239,7 @@ async function showOutput(channelId, ref) {
240
239
  const truncatedNote = outputText.length > tail.length ? `(只显示末尾 ${OUTPUT_TAIL_CHARS} 字符,完整内容见上方产物目录)\n\n` : "";
241
240
  return `**Run \`${record.runId}\` 的产出**\n\n${truncatedNote}\`\`\`\n${tail}\n\`\`\``;
242
241
  }
243
- async function cancelRun(channelId, ref) {
244
- const manager = getSubAgentRunManager(channelId);
242
+ async function cancelRun(manager, ref) {
245
243
  if (ref === "all") {
246
244
  const running = manager.list().filter((record) => record.status === "running");
247
245
  if (running.length === 0)
@@ -352,11 +350,11 @@ export async function handleSubagentsCommand(options) {
352
350
  case "list":
353
351
  return await listRuns(options, command.filter);
354
352
  case "show":
355
- return await showRun(options.channelId, command.ref);
353
+ return await showRun(options.runManager, command.ref);
356
354
  case "output":
357
- return await showOutput(options.channelId, command.ref);
355
+ return await showOutput(options.runManager, command.ref);
358
356
  case "cancel":
359
- return await cancelRun(options.channelId, command.ref);
357
+ return await cancelRun(options.runManager, command.ref);
360
358
  case "roles":
361
359
  return await showRoles(options, command.name);
362
360
  }
@@ -4,10 +4,9 @@
4
4
  * over an explicit `event`/`workspaceDir`/`executor`, with no dependency on
5
5
  * `createRuntimeContext`'s closures.
6
6
  */
7
- import { type JobSnapshot } from "../agent/job-manager.js";
7
+ import type { ChannelJobManager, JobSnapshot } from "../agent/job-manager.js";
8
8
  import type { ChannelEvent } from "../channel/channel-event.js";
9
- import type { Executor } from "../executor.js";
10
- import { type RunRecord } from "../subagents/runs.js";
9
+ import type { RunRecord, SubAgentRunManager } from "../subagents/runs.js";
11
10
  /**
12
11
  * Whether a `[JOB:<jobId>] ... belongs to task <taskId>.` wake actually names a job that: exists
13
12
  * on this channel, has actually finished (a still-`running` job cannot have produced this wake —
@@ -46,7 +45,7 @@ export interface WakeTaskTransitionHooks {
46
45
  /** Claim and activate a producer-created delegation wake without consuming it yet. Keeping the
47
46
  * final marker separate lets transports such as TUI mark it consumed only after they have accepted
48
47
  * the corresponding turn; a rejected submit remains replayable in the same or next process. */
49
- export declare function claimVerifiedDelegationWake(event: ChannelEvent, workspaceDir: string, hooks?: WakeTaskTransitionHooks): Promise<ClaimedDelegationWake | undefined>;
48
+ export declare function claimVerifiedDelegationWake(event: ChannelEvent, workspaceDir: string, runManager: SubAgentRunManager, hooks?: WakeTaskTransitionHooks): Promise<ClaimedDelegationWake | undefined>;
50
49
  export interface ClaimedJobWake {
51
50
  taskId: string;
52
51
  activated: boolean;
@@ -57,4 +56,4 @@ export interface ClaimedJobWake {
57
56
  /** Same shape as `claimVerifiedDelegationWake`, for a `[JOB:<jobId>] ... belongs to task
58
57
  * <taskId>.` completion wake. A background job has no rollback bookkeeping — its wake
59
58
  * activation is a single unconditional step — so `ClaimedJobWake` omits `rollback`. */
60
- export declare function claimVerifiedJobWake(event: ChannelEvent, workspaceDir: string, executor: Executor, hooks?: WakeTaskTransitionHooks): Promise<ClaimedJobWake | undefined>;
59
+ export declare function claimVerifiedJobWake(event: ChannelEvent, workspaceDir: string, jobManager: ChannelJobManager, hooks?: WakeTaskTransitionHooks): Promise<ClaimedJobWake | undefined>;
@@ -1,12 +1,4 @@
1
- /**
2
- * Verifying and claiming a background job's or delegation run's completion wake before it may
3
- * activate a parked task (spec 040, D7/T9). Split out of `bootstrap.ts`: these are pure functions
4
- * over an explicit `event`/`workspaceDir`/`executor`, with no dependency on
5
- * `createRuntimeContext`'s closures.
6
- */
7
- import { getChannelJobManager } from "../agent/job-manager.js";
8
1
  import { getChannelDir } from "../channel/channel-paths.js";
9
- import { getSubAgentRunManager } from "../subagents/runs.js";
10
2
  import { parkTask, readStoredTask, redeemTicket } from "../tasks/store.js";
11
3
  /**
12
4
  * True when `taskId` is already `open` and not paused — i.e. the driver already owns advancing
@@ -55,11 +47,10 @@ export function isTrustedInternalWake(event, kind, resourceId, taskId) {
55
47
  /** Claim and activate a producer-created delegation wake without consuming it yet. Keeping the
56
48
  * final marker separate lets transports such as TUI mark it consumed only after they have accepted
57
49
  * the corresponding turn; a rejected submit remains replayable in the same or next process. */
58
- export async function claimVerifiedDelegationWake(event, workspaceDir, hooks) {
50
+ export async function claimVerifiedDelegationWake(event, workspaceDir, runManager, hooks) {
59
51
  const wake = event.internalWake;
60
52
  if (wake?.kind !== "subagent")
61
53
  return undefined;
62
- const runManager = getSubAgentRunManager(event.channelId);
63
54
  const record = runManager.get(wake.resourceId);
64
55
  if (!isTrustedInternalWake(event, "subagent", wake.resourceId, wake.taskId) ||
65
56
  !isVerifiedDelegationWake(record, wake.taskId) ||
@@ -91,11 +82,10 @@ export async function claimVerifiedDelegationWake(event, workspaceDir, hooks) {
91
82
  /** Same shape as `claimVerifiedDelegationWake`, for a `[JOB:<jobId>] ... belongs to task
92
83
  * <taskId>.` completion wake. A background job has no rollback bookkeeping — its wake
93
84
  * activation is a single unconditional step — so `ClaimedJobWake` omits `rollback`. */
94
- export async function claimVerifiedJobWake(event, workspaceDir, executor, hooks) {
85
+ export async function claimVerifiedJobWake(event, workspaceDir, jobManager, hooks) {
95
86
  const wake = event.internalWake;
96
87
  if (wake?.kind !== "job")
97
88
  return undefined;
98
- const jobManager = getChannelJobManager(event.channelId, executor);
99
89
  const jobs = await jobManager.list();
100
90
  if (!isTrustedInternalWake(event, "job", wake.resourceId, wake.taskId) ||
101
91
  !isVerifiedJobWake(jobs, wake.resourceId, wake.taskId) ||
@@ -36,6 +36,13 @@ export interface SecurityConfig {
36
36
  allowedRoots?: string[];
37
37
  };
38
38
  }
39
+ /**
40
+ * Every top-level `security.json` key, read by `test/config-reference-coverage.test.ts` to check
41
+ * that `docs/security.md` still mentions each one. Kept in sync with `SecurityConfig` by
42
+ * `satisfies` (rejects an extra/misspelled entry) and `AssertNoMissingKeys` (rejects a field with
43
+ * no entry here) — both at `npm run typecheck`.
44
+ */
45
+ export declare const SECURITY_CONFIG_TOP_LEVEL_KEYS: readonly ["enabled", "commandGuard", "pathGuard", "networkGuard", "audit", "projectAccess"];
39
46
  export interface SecurityRuntimeContext {
40
47
  agentWorkspaceDir: string;
41
48
  projectRoot?: string;
@@ -1 +1,16 @@
1
- export {};
1
+ /**
2
+ * Every top-level `security.json` key, read by `test/config-reference-coverage.test.ts` to check
3
+ * that `docs/security.md` still mentions each one. Kept in sync with `SecurityConfig` by
4
+ * `satisfies` (rejects an extra/misspelled entry) and `AssertNoMissingKeys` (rejects a field with
5
+ * no entry here) — both at `npm run typecheck`.
6
+ */
7
+ export const SECURITY_CONFIG_TOP_LEVEL_KEYS = [
8
+ "enabled",
9
+ "commandGuard",
10
+ "pathGuard",
11
+ "networkGuard",
12
+ "audit",
13
+ "projectAccess",
14
+ ];
15
+ const _securityConfigKeysComplete = true;
16
+ void _securityConfigKeysComplete;
@@ -105,6 +105,14 @@ export interface PipiclawSettings {
105
105
  tui?: Partial<PipiclawTuiSettings>;
106
106
  delegation?: Partial<PipiclawDelegationSettings>;
107
107
  }
108
+ /**
109
+ * Every top-level `settings.json` key, read by `test/config-reference-coverage.test.ts` to check
110
+ * that `docs/configuration-reference.md` still mentions each one. The two lines below keep this
111
+ * list from drifting out of sync with `PipiclawSettings` itself: `satisfies` rejects an extra or
112
+ * misspelled entry, and the `AssertNoMissingKeys` check rejects an interface field with no entry
113
+ * here — both at `npm run typecheck`, not by trusting a human to update two places together.
114
+ */
115
+ export declare const SETTINGS_TOP_LEVEL_KEYS: readonly ["defaultProvider", "defaultModel", "defaultThinkingLevel", "fallbackModel", "subagentModel", "compaction", "retry", "memoryMaintenance", "sessionSearch", "logging", "tui", "delegation"];
108
116
  export interface PipiclawTuiSettings {
109
117
  /**
110
118
  * Output shape for the terminal TUI, reusing the DingTalk response-mode
package/dist/settings.js CHANGED
@@ -11,7 +11,30 @@ import { dirname, join } from "path";
11
11
  import * as log from "./log.js";
12
12
  import { getMemoryMaintenanceTuning } from "./memory/maintenance-tuning.js";
13
13
  import { writeFileAtomicallySync } from "./shared/atomic-file.js";
14
- import { fileStamp } from "./shared/file-stamp.js";
14
+ import { fileStamp } from "./shared/format.js";
15
+ /**
16
+ * Every top-level `settings.json` key, read by `test/config-reference-coverage.test.ts` to check
17
+ * that `docs/configuration-reference.md` still mentions each one. The two lines below keep this
18
+ * list from drifting out of sync with `PipiclawSettings` itself: `satisfies` rejects an extra or
19
+ * misspelled entry, and the `AssertNoMissingKeys` check rejects an interface field with no entry
20
+ * here — both at `npm run typecheck`, not by trusting a human to update two places together.
21
+ */
22
+ export const SETTINGS_TOP_LEVEL_KEYS = [
23
+ "defaultProvider",
24
+ "defaultModel",
25
+ "defaultThinkingLevel",
26
+ "fallbackModel",
27
+ "subagentModel",
28
+ "compaction",
29
+ "retry",
30
+ "memoryMaintenance",
31
+ "sessionSearch",
32
+ "logging",
33
+ "tui",
34
+ "delegation",
35
+ ];
36
+ const _settingsKeysComplete = true;
37
+ void _settingsKeysComplete;
15
38
  const DEFAULT_TUI = {
16
39
  responseMode: "full_progress_then_plain_final",
17
40
  };
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Compile-time completeness check for a runtime key list paired with a config interface. Assign
3
+ * the result to a `const` typed `true` (then `void` it to satisfy `noUnusedLocals`): if `K` is
4
+ * missing any key of `T`, the check's type becomes `never` and the assignment fails to
5
+ * typecheck. This is what keeps a documentation-coverage test's key list (e.g.
6
+ * `SETTINGS_TOP_LEVEL_KEYS` in `settings.ts`) from silently drifting out of sync with the
7
+ * interface it documents when a field is added — `npm run typecheck` catches it, not a human
8
+ * remembering to update two places.
9
+ *
10
+ * Only checks for *missing* keys. Pair the key list's own type with
11
+ * `satisfies readonly (keyof T)[]` to also reject an extra or misspelled key.
12
+ */
13
+ export type AssertNoMissingKeys<T, K extends readonly (keyof T)[]> = Exclude<keyof T, K[number]> extends never ? true : never;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,20 @@
1
+ /** Render a millisecond duration as compact human text (`"42s"`, `"3m7s"`). */
2
+ export declare function formatDuration(ms: number): string;
3
+ /**
4
+ * Coerce an untrusted numeric config/request value into an integer within `[minimum, maximum]`,
5
+ * falling back to `fallback` for anything not a finite number or out of range. Shared by the
6
+ * app-level config loaders (`tools.json`) and web request parameter resolution — both need the
7
+ * same "trust nothing, fail closed to a safe default" numeric parsing.
8
+ */
9
+ export declare function clampInteger(value: unknown, fallback: number, minimum: number, maximum?: number): number;
10
+ export declare function estimateTokens(text: string): number;
11
+ /**
12
+ * A cheap change token for a config file: `mtime:ctime:size`, or `""` when the file
13
+ * cannot be stat'ed (missing or unreadable — itself a stable state worth caching).
14
+ *
15
+ * Used by the hot re-read paths (`settings.json` on every driver/maintenance tick,
16
+ * `tools.json` on every driver tick) to skip a JSON parse when nothing changed. Same
17
+ * triple as the task-ledger parse cache: mtime alone misses an atomic-rename overwrite
18
+ * that preserves the timestamp, ctime catches the rename, size catches the rest.
19
+ */
20
+ export declare function fileStamp(path: string): string;
@@ -0,0 +1,64 @@
1
+ import { statSync } from "node:fs";
2
+ /** Render a millisecond duration as compact human text (`"42s"`, `"3m7s"`). */
3
+ export function formatDuration(ms) {
4
+ const seconds = Math.round(ms / 1000);
5
+ if (seconds < 60)
6
+ return `${seconds}s`;
7
+ return `${Math.floor(seconds / 60)}m${seconds % 60}s`;
8
+ }
9
+ /**
10
+ * Coerce an untrusted numeric config/request value into an integer within `[minimum, maximum]`,
11
+ * falling back to `fallback` for anything not a finite number or out of range. Shared by the
12
+ * app-level config loaders (`tools.json`) and web request parameter resolution — both need the
13
+ * same "trust nothing, fail closed to a safe default" numeric parsing.
14
+ */
15
+ export function clampInteger(value, fallback, minimum, maximum) {
16
+ if (typeof value !== "number" || !Number.isFinite(value)) {
17
+ return fallback;
18
+ }
19
+ const normalized = Math.floor(value);
20
+ if (normalized < minimum) {
21
+ return fallback;
22
+ }
23
+ if (maximum !== undefined && normalized > maximum) {
24
+ return fallback;
25
+ }
26
+ return normalized;
27
+ }
28
+ /**
29
+ * Rough token estimate, shared by everything that has to reason about context size without
30
+ * calling a tokenizer. CJK runs about one token per character, Latin text about four characters
31
+ * per token; the provider's real tokenizer is the authority, and the usage ledger records what
32
+ * it billed.
33
+ *
34
+ * The script split matters wherever the estimate gates behavior rather than just reporting: a
35
+ * flat characters-per-token ratio tuned for Latin text underestimates Chinese input roughly
36
+ * threefold, so a budget check would clear a message that in fact does not fit.
37
+ */
38
+ const CJK_REGEX = /\p{Script=Han}|\p{Script=Hiragana}|\p{Script=Katakana}|\p{Script=Hangul}/u;
39
+ export function estimateTokens(text) {
40
+ let cjk = 0;
41
+ for (const char of text) {
42
+ if (CJK_REGEX.test(char))
43
+ cjk++;
44
+ }
45
+ return Math.ceil(cjk + (text.length - cjk) / 4);
46
+ }
47
+ /**
48
+ * A cheap change token for a config file: `mtime:ctime:size`, or `""` when the file
49
+ * cannot be stat'ed (missing or unreadable — itself a stable state worth caching).
50
+ *
51
+ * Used by the hot re-read paths (`settings.json` on every driver/maintenance tick,
52
+ * `tools.json` on every driver tick) to skip a JSON parse when nothing changed. Same
53
+ * triple as the task-ledger parse cache: mtime alone misses an atomic-rename overwrite
54
+ * that preserves the timestamp, ctime catches the rename, size catches the rest.
55
+ */
56
+ export function fileStamp(path) {
57
+ try {
58
+ const stats = statSync(path);
59
+ return `${stats.mtimeMs}:${stats.ctimeMs}:${stats.size}`;
60
+ }
61
+ catch {
62
+ return "";
63
+ }
64
+ }
@@ -1,3 +1,4 @@
1
+ /** Small, dependency-free helpers for talking to the host filesystem and shell. */
1
2
  export declare function isNodeError(error: unknown): error is NodeJS.ErrnoException;
2
3
  /**
3
4
  * Read a UTF-8 text file, returning "" when it does not exist.
@@ -6,3 +7,8 @@ export declare function isNodeError(error: unknown): error is NodeJS.ErrnoExcept
6
7
  * silently treat a real read failure as an absent file.
7
8
  */
8
9
  export declare function readOptionalTextFile(path: string): Promise<string>;
10
+ /**
11
+ * Shell-escape a string for safe use in sh -c commands.
12
+ * Wraps in single quotes and escapes internal single quotes.
13
+ */
14
+ export declare function shellEscape(s: string): string;
@@ -1,4 +1,5 @@
1
1
  import { readFile } from "fs/promises";
2
+ /** Small, dependency-free helpers for talking to the host filesystem and shell. */
2
3
  export function isNodeError(error) {
3
4
  return error instanceof Error && "code" in error;
4
5
  }
@@ -19,3 +20,10 @@ export async function readOptionalTextFile(path) {
19
20
  throw error;
20
21
  }
21
22
  }
23
+ /**
24
+ * Shell-escape a string for safe use in sh -c commands.
25
+ * Wraps in single quotes and escapes internal single quotes.
26
+ */
27
+ export function shellEscape(s) {
28
+ return `'${s.replace(/'/g, "'\\''")}'`;
29
+ }