@oyasmi/pipiclaw 0.9.3-beta.2 → 0.9.3-beta.4

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 (148) hide show
  1. package/dist/agent/channel-runner.d.ts +4 -18
  2. package/dist/agent/channel-runner.js +25 -120
  3. package/dist/agent/context-budget.js +1 -1
  4. package/dist/agent/job-manager.d.ts +20 -17
  5. package/dist/agent/job-manager.js +95 -70
  6. package/dist/agent/prompt/builder.d.ts +1 -1
  7. package/dist/agent/prompt/builder.js +2 -18
  8. package/dist/agent/prompt/manifest.d.ts +0 -1
  9. package/dist/agent/prompt/manifest.js +2 -2
  10. package/dist/agent/prompt/sections.js +3 -12
  11. package/dist/agent/prompt/types.d.ts +2 -18
  12. package/dist/agent/prompt/types.js +1 -1
  13. package/dist/agent/runner-factory.d.ts +4 -0
  14. package/dist/agent/session-adapter.d.ts +19 -0
  15. package/dist/agent/session-adapter.js +77 -0
  16. package/dist/app-services.d.ts +18 -0
  17. package/dist/app-services.js +43 -0
  18. package/dist/{runtime → events}/events.d.ts +1 -1
  19. package/dist/executor.d.ts +5 -1
  20. package/dist/executor.js +35 -5
  21. package/dist/file-store.d.ts +4 -1
  22. package/dist/file-store.js +5 -0
  23. package/dist/memory/journal.d.ts +13 -0
  24. package/dist/memory/journal.js +47 -4
  25. package/dist/memory/maintenance-gates.d.ts +0 -3
  26. package/dist/memory/maintenance-gates.js +2 -2
  27. package/dist/memory/maintenance-migration.d.ts +5 -0
  28. package/dist/memory/maintenance-migration.js +91 -0
  29. package/dist/memory/maintenance-state.js +5 -44
  30. package/dist/memory/migrate.js +1 -1
  31. package/dist/memory/reflect-job.d.ts +1 -9
  32. package/dist/memory/reflect-job.js +1 -3
  33. package/dist/memory/reflect.js +1 -1
  34. package/dist/memory/search.js +13 -6
  35. package/dist/memory/session-corpus.d.ts +11 -0
  36. package/dist/memory/session-corpus.js +16 -5
  37. package/dist/memory/session-search.d.ts +3 -0
  38. package/dist/memory/session-search.js +45 -8
  39. package/dist/memory/store.d.ts +9 -0
  40. package/dist/memory/store.js +26 -3
  41. package/dist/models/auth-cli.js +1 -1
  42. package/dist/playbooks/agent-delegation.md +35 -76
  43. package/dist/playbooks/background-jobs.md +14 -16
  44. package/dist/playbooks/event-scheduling.md +20 -25
  45. package/dist/playbooks/memory-and-learning.md +28 -61
  46. package/dist/playbooks/outbound-media.md +10 -12
  47. package/dist/playbooks/runtime-orientation.md +34 -53
  48. package/dist/playbooks/task-loop.md +49 -69
  49. package/dist/runtime/bootstrap.d.ts +5 -15
  50. package/dist/runtime/bootstrap.js +57 -67
  51. package/dist/runtime/subagent-commands.d.ts +2 -1
  52. package/dist/runtime/subagent-commands.js +10 -12
  53. package/dist/runtime/task-wake.d.ts +4 -5
  54. package/dist/runtime/task-wake.js +2 -12
  55. package/dist/security/path-guard-filter.d.ts +22 -0
  56. package/dist/security/path-guard-filter.js +35 -0
  57. package/dist/security/types.d.ts +7 -0
  58. package/dist/security/types.js +16 -1
  59. package/dist/settings.d.ts +8 -0
  60. package/dist/settings.js +24 -1
  61. package/dist/shared/exact-keys.d.ts +13 -0
  62. package/dist/shared/exact-keys.js +1 -0
  63. package/dist/shared/format.d.ts +20 -0
  64. package/dist/shared/format.js +64 -0
  65. package/dist/shared/{fs-utils.d.ts → os.d.ts} +6 -0
  66. package/dist/shared/{fs-utils.js → os.js} +8 -0
  67. package/dist/subagents/discovery.d.ts +18 -6
  68. package/dist/subagents/discovery.js +12 -8
  69. package/dist/subagents/external/run.d.ts +2 -1
  70. package/dist/subagents/external/run.js +1 -2
  71. package/dist/subagents/external/settlement.js +10 -5
  72. package/dist/subagents/format.d.ts +1 -1
  73. package/dist/subagents/format.js +1 -1
  74. package/dist/subagents/runs.d.ts +13 -12
  75. package/dist/subagents/runs.js +108 -89
  76. package/dist/subagents/tool.d.ts +13 -7
  77. package/dist/subagents/tool.js +21 -13
  78. package/dist/tasks/brief.d.ts +1 -1
  79. package/dist/tasks/brief.js +12 -2
  80. package/dist/tasks/log.d.ts +4 -0
  81. package/dist/tasks/log.js +13 -1
  82. package/dist/tools/bash.d.ts +13 -0
  83. package/dist/tools/bash.js +123 -20
  84. package/dist/tools/command-optimizer.js +1 -1
  85. package/dist/tools/config.d.ts +7 -0
  86. package/dist/tools/config.js +16 -1
  87. package/dist/tools/edit.js +36 -5
  88. package/dist/tools/event-manage.d.ts +26 -5
  89. package/dist/tools/event-manage.js +84 -36
  90. package/dist/tools/glob.js +57 -4
  91. package/dist/tools/grep.d.ts +2 -0
  92. package/dist/tools/grep.js +188 -15
  93. package/dist/tools/index.d.ts +4 -0
  94. package/dist/tools/index.js +4 -2
  95. package/dist/tools/job.js +17 -5
  96. package/dist/tools/memory-manage.js +80 -41
  97. package/dist/tools/read.js +43 -6
  98. package/dist/tools/registry.d.ts +9 -3
  99. package/dist/tools/registry.js +22 -57
  100. package/dist/tools/send-media.js +6 -4
  101. package/dist/tools/session-search.js +4 -1
  102. package/dist/tools/skill.d.ts +2 -0
  103. package/dist/tools/skill.js +13 -1
  104. package/dist/tools/subagent-manage.d.ts +2 -0
  105. package/dist/tools/subagent-manage.js +8 -8
  106. package/dist/tools/subagent-tool-names.d.ts +11 -0
  107. package/dist/tools/subagent-tool-names.js +19 -0
  108. package/dist/tools/task-manage/log-view.js +6 -3
  109. package/dist/tools/task-manage/schema.d.ts +6 -6
  110. package/dist/tools/task-manage/schema.js +5 -12
  111. package/dist/tools/task-manage/shared.js +20 -11
  112. package/dist/tools/task-manage/step-end.js +22 -5
  113. package/dist/tools/task-manage/types.d.ts +4 -0
  114. package/dist/tools/task-manage.js +9 -1
  115. package/dist/tools/web-cache.d.ts +11 -3
  116. package/dist/tools/web-cache.js +26 -8
  117. package/dist/tools/web-fetch.d.ts +1 -0
  118. package/dist/tools/web-fetch.js +68 -15
  119. package/dist/tools/write.js +3 -0
  120. package/dist/tui/app.js +22 -7
  121. package/dist/web/config.js +1 -1
  122. package/dist/web/fetch.d.ts +5 -0
  123. package/dist/web/fetch.js +36 -1
  124. package/examples/sub-agents/README.md +14 -4
  125. package/examples/sub-agents/builder-hard.md +12 -34
  126. package/examples/sub-agents/builder.md +11 -31
  127. package/examples/sub-agents/explorer.md +10 -16
  128. package/examples/sub-agents/git-committer.md +15 -20
  129. package/examples/sub-agents/planner.md +11 -21
  130. package/examples/sub-agents/reviewer.md +10 -31
  131. package/examples/sub-agents/verifier.md +12 -27
  132. package/examples/sub-agents/worker.md +11 -35
  133. package/package.json +8 -3
  134. package/dist/shared/duration.d.ts +0 -2
  135. package/dist/shared/duration.js +0 -7
  136. package/dist/shared/file-stamp.d.ts +0 -10
  137. package/dist/shared/file-stamp.js +0 -19
  138. package/dist/shared/numeric.d.ts +0 -7
  139. package/dist/shared/numeric.js +0 -19
  140. package/dist/shared/shell-escape.d.ts +0 -5
  141. package/dist/shared/shell-escape.js +0 -7
  142. package/dist/shared/token-estimate.d.ts +0 -1
  143. package/dist/shared/token-estimate.js +0 -19
  144. /package/dist/{runtime → events}/event-commands.d.ts +0 -0
  145. /package/dist/{runtime → events}/event-commands.js +0 -0
  146. /package/dist/{runtime → events}/event-validation.d.ts +0 -0
  147. /package/dist/{runtime → events}/event-validation.js +0 -0
  148. /package/dist/{runtime → events}/events.js +0 -0
@@ -1,10 +1,11 @@
1
1
  import { mkdir, writeFile } from "fs/promises";
2
2
  import { join, relative } from "path";
3
- import { channelRunningJobLines, configureJobRuntime, restoreChannelJobs } from "../agent/job-manager.js";
3
+ import { createJobRuntime } from "../agent/job-manager.js";
4
4
  import { loadDetachedMaintenanceContext } from "../agent/maintenance-context.js";
5
5
  import { createRunner } from "../agent/runner-factory.js";
6
6
  import { renderStatus } from "../agent/status-render.js";
7
7
  import { scanWorkspaceForInterruptedTurns } from "../agent/turn-recovery.js";
8
+ import { prepareAppServices } from "../app-services.js";
8
9
  import { createFreshActiveSession } from "../channel/active-session-store.js";
9
10
  import { muteChannelContext } from "../channel/channel-context.js";
10
11
  import { createChannelIndex } from "../channel/channel-index.js";
@@ -12,37 +13,36 @@ import { ensureChannelDir, getChannelDir } from "../channel/channel-paths.js";
12
13
  import { resolveProjectScope } from "../channel/project-scope-store.js";
13
14
  import { ChannelStore } from "../channel/store.js";
14
15
  import { BUILT_IN_COMMANDS, formatUnknownCommandMessage, isRunnerBuiltInCommand, parseBuiltInCommand, slashCommandName, } from "../commands/catalog.js";
16
+ import { handleEventsCommand as runEventsCommand } from "../events/event-commands.js";
17
+ import { createEventsWatcher } from "../events/events.js";
15
18
  import { createExecutor } from "../executor.js";
16
19
  import * as log from "../log.js";
20
+ import { migrateMemoryMaintenanceStates } from "../memory/maintenance-migration.js";
17
21
  import { MemoryMaintenanceScheduler } from "../memory/scheduler.js";
18
22
  import { defaultModel } from "../models/utils.js";
19
23
  import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
20
24
  import { flushSecurityLogs } from "../security/logger.js";
21
25
  import { resolveProjectAccessPolicy } from "../security/project-scope.js";
22
26
  import { PipiclawSettingsManager, TASK_DRIVER_SETTINGS } from "../settings.js";
23
- import { formatConfigDiagnostic } from "../shared/config-diagnostic.js";
24
- import { fileStamp } from "../shared/file-stamp.js";
27
+ import { fileStamp } from "../shared/format.js";
25
28
  import { localStampForFilename } from "../shared/local-time.js";
26
29
  import { errorMessage } from "../shared/text-utils.js";
27
30
  import { sleepUnref } from "../shared/with-timeout.js";
28
31
  import { loadDetachedSubAgentDiscovery } from "../subagents/detached-discovery.js";
29
- import { configureSubAgentRuntime, getSubAgentRunManager, restoreAllSubAgentRuns, stopSubAgentGarbageCollector, } from "../subagents/runs.js";
32
+ import { createSubAgentRuntime } from "../subagents/runs.js";
30
33
  import { buildTaskStepBrief } from "../tasks/brief.js";
31
34
  import { readActiveTasks } from "../tasks/ledger.js";
32
35
  import { consumeTaskNotice } from "../tasks/steer.js";
33
36
  import { readStoredTask } from "../tasks/store.js";
34
- import { getToolsConfigPath, loadToolsConfig, loadToolsConfigWithDiagnostics } from "../tools/config.js";
37
+ import { getToolsConfigPath, loadToolsConfig } from "../tools/config.js";
35
38
  import { getUsageLedger } from "../usage/ledger.js";
36
39
  import { parseUsageMode, renderUsageReport } from "../usage/render.js";
37
40
  import { BootstrapExitError, bootstrapAppHome, DEFAULT_BOOTSTRAP_PATHS, loadConfig, parseArgs, printBootstrapSummary, readCliVersion, } from "./app-home.js";
38
41
  import { createDingTalkContext } from "./delivery.js";
39
42
  import { DingTalkBot, } from "./dingtalk.js";
40
43
  import { DurableDispatchService } from "./durable-dispatch.js";
41
- import { handleEventsCommand as runEventsCommand } from "./event-commands.js";
42
- import { createEventsWatcher } from "./events.js";
43
44
  import { extensionForMimeType } from "./inbound-media.js";
44
45
  import { handleProjectCommand as runProjectCommand } from "./project-commands.js";
45
- import { installLlmProxy } from "./proxy.js";
46
46
  import { handleSkillsCommand as runSkillsCommand } from "./skill-commands.js";
47
47
  import { renderRunNotice, handleSubagentsCommand as runSubagentsCommand } from "./subagent-commands.js";
48
48
  import { pauseTask, handleTasksCommand as runTasksCommand } from "./task-commands.js";
@@ -149,7 +149,7 @@ export async function forceEndStuckTurnAfterStop(input) {
149
149
  return true;
150
150
  }
151
151
  function createDingTalkHandler(deps) {
152
- const { options, store, channelRunners, sessionResetChains, activeTasks, stopWatchdogs, channelIndex, archiveIncomingMessage, getRunner, cliVersion, startedAt, isShuttingDown, getDurableDispatch, getExecutor, getTaskDriver, } = deps;
152
+ const { options, store, channelRunners, sessionResetChains, activeTasks, stopWatchdogs, channelIndex, archiveIncomingMessage, getRunner, cliVersion, startedAt, isShuttingDown, getDurableDispatch, getJobs, getRuns, getTaskDriver, } = deps;
153
153
  /**
154
154
  * Turn a `[TASK_DRIVER:<id>]` dispatch into a task loop step: bind the runner to the task
155
155
  * cycle's own session and replace the wake text with the step brief. Returns `undefined` for
@@ -160,9 +160,9 @@ function createDingTalkHandler(deps) {
160
160
  */
161
161
  const prepareTaskStep = async (event, runner) => {
162
162
  const match = /^\[TASK_DRIVER:([A-Za-z0-9._-]+)\]/.exec(event.text);
163
- if (!match?.[1] || !runner.bindTaskSession)
163
+ const taskId = match?.[1] ?? event.internalWake?.taskId;
164
+ if (!taskId || !runner.bindTaskSession)
164
165
  return undefined;
165
- const taskId = match[1];
166
166
  const channelDir = ensureChannelDir(options.paths.workspaceDir, event.channelId);
167
167
  try {
168
168
  const document = await readStoredTask(channelDir, taskId);
@@ -180,12 +180,19 @@ function createDingTalkHandler(deps) {
180
180
  }
181
181
  };
182
182
  /** Deliver whatever the step asked to say, then hand the runner back to the chat session. */
183
- const finishTaskStep = async (channelId, taskId, ctx) => {
183
+ const finishTaskStep = async (channelId, taskId, bot) => {
184
184
  const channelDir = ensureChannelDir(options.paths.workspaceDir, channelId);
185
185
  try {
186
186
  const notice = await consumeTaskNotice(channelDir, taskId);
187
- if (notice)
188
- await ctx.respond(notice, true);
187
+ if (notice) {
188
+ // runner.run closes its per-turn delivery context before returning. Sending through that
189
+ // closed context silently dropped successful task_step_end notifications (T-run-01).
190
+ const delivered = await bot.sendPlain(channelId, notice);
191
+ if (delivered)
192
+ await store.logBotResponse(channelId, notice, Date.now().toString());
193
+ else
194
+ log.logWarning(`[${channelId}] Failed to deliver task notice for ${taskId}`);
195
+ }
189
196
  }
190
197
  catch (error) {
191
198
  log.logWarning(`[${channelId}] Could not deliver task notice for ${taskId}`, errorMessage(error));
@@ -362,6 +369,7 @@ function createDingTalkHandler(deps) {
362
369
  case "subagents":
363
370
  return runSubagentsCommand({
364
371
  args,
372
+ runManager: getRuns().get(event.channelId),
365
373
  channelId: event.channelId,
366
374
  discovery: channelRunners.get(event.channelId)?.getSubAgentDiscoverySnapshot(),
367
375
  // `roles` needs a role directory even for a channel that has never spoken this boot —
@@ -381,11 +389,12 @@ function createDingTalkHandler(deps) {
381
389
  actor: "dingtalk-command",
382
390
  isBusy: () => channelRunners.get(event.channelId)?.isBusy() ?? false,
383
391
  listActiveBlockers: () => [
384
- ...getSubAgentRunManager(event.channelId)
392
+ ...getRuns()
393
+ .get(event.channelId)
385
394
  .list()
386
395
  .filter((record) => record.status === "running")
387
396
  .map((record) => `subagent run \`${record.runId}\` (${record.agent})`),
388
- ...channelRunningJobLines(event.channelId),
397
+ ...getJobs().runningLines(event.channelId),
389
398
  ],
390
399
  // D4.2: dispose the cached runner so the next access rebuilds it under the new scope.
391
400
  // The active-session ref is untouched — same session, new project root.
@@ -525,15 +534,13 @@ function createDingTalkHandler(deps) {
525
534
  // wake (a delegation or job finishing) is the opposite — a human is actually waiting
526
535
  // on it — so it renders progress the same way a normal message does (P0-2).
527
536
  const backgroundOnly = Boolean(_isEvent) && event.presentation !== "awaited";
528
- const baseCtx = createDingTalkContext(event, bot, store, backgroundOnly ? "none" : undefined);
529
537
  // Spec 051, D3: a task-driver dispatch runs as a *task step* — in the task cycle's
530
538
  // own session, with a brief instead of the wake text, and silent unless the step
531
539
  // asked for a notify. Everything below (busy state, /stop, delivery) is unchanged;
532
540
  // only which session the turn is bound to, and what reaches the channel, differ.
533
- const taskStep = await prepareTaskStep(event, runner);
534
- const ctx = taskStep ? muteChannelContext(baseCtx) : baseCtx;
535
- if (taskStep)
536
- event = { ...event, text: taskStep.brief };
541
+ let taskStep;
542
+ let baseCtx = createDingTalkContext(event, bot, store, backgroundOnly ? "none" : undefined);
543
+ let ctx = baseCtx;
537
544
  if (builtInCommand) {
538
545
  const commandStartedAt = Date.now();
539
546
  const logCtx = { channelId: event.channelId, userName: event.userName };
@@ -603,7 +610,7 @@ function createDingTalkHandler(deps) {
603
610
  : jobTextMatch;
604
611
  if (jobMatch) {
605
612
  const [, jobId, jobTaskId] = jobMatch;
606
- const claimed = await claimVerifiedJobWake(event, options.paths.workspaceDir, getExecutor(), options.wakeTransitionHooks?.job);
613
+ const claimed = await claimVerifiedJobWake(event, options.paths.workspaceDir, getJobs().get(event.channelId), options.wakeTransitionHooks?.job);
607
614
  if (claimed) {
608
615
  await claimed.finish();
609
616
  structuredWakeFinalized = true;
@@ -631,7 +638,7 @@ function createDingTalkHandler(deps) {
631
638
  : delegationTextMatch;
632
639
  if (delegationMatch) {
633
640
  const [, runId, delegationTaskId] = delegationMatch;
634
- const claimed = await claimVerifiedDelegationWake(event, options.paths.workspaceDir, options.wakeTransitionHooks?.subagent);
641
+ const claimed = await claimVerifiedDelegationWake(event, options.paths.workspaceDir, getRuns().get(event.channelId), options.wakeTransitionHooks?.subagent);
635
642
  if (claimed) {
636
643
  await claimed.finish();
637
644
  structuredWakeFinalized = true;
@@ -648,9 +655,17 @@ function createDingTalkHandler(deps) {
648
655
  }
649
656
  }
650
657
  }
658
+ // Verified job/run wakes that activate a task are task steps too. Verification must happen
659
+ // first: routing directly from user-controlled wake text would grant task-only tools.
660
+ taskStep = await prepareTaskStep(event, runner);
661
+ if (taskStep) {
662
+ event = { ...event, text: taskStep.brief };
663
+ baseCtx = createDingTalkContext(event, bot, store, backgroundOnly ? "none" : undefined);
664
+ ctx = muteChannelContext(baseCtx);
665
+ }
651
666
  const result = await runner.run(ctx, store);
652
667
  if (taskStep)
653
- await finishTaskStep(event.channelId, taskStep.taskId, baseCtx);
668
+ await finishTaskStep(event.channelId, taskStep.taskId, bot);
654
669
  if (result.stopReason === "aborted" && runner.getTurnStatus().stopRequested) {
655
670
  log.logInfo(`[${event.channelId}] Stopped`);
656
671
  }
@@ -684,6 +699,7 @@ function createDingTalkHandler(deps) {
684
699
  return handler;
685
700
  }
686
701
  export async function createRuntimeContext(options) {
702
+ await migrateMemoryMaintenanceStates(options.paths.appHomeDir);
687
703
  const startServices = options.startServices ?? true;
688
704
  const registerSignalHandlers = options.registerSignalHandlers ?? true;
689
705
  const store = new ChannelStore({ workingDir: options.paths.workspaceDir });
@@ -721,6 +737,8 @@ export async function createRuntimeContext(options) {
721
737
  }
722
738
  const channelDir = ensureChannelDir(options.paths.workspaceDir, channelId);
723
739
  const runner = createRunner(channelId, channelDir, {
740
+ jobManager: jobs.get(channelId),
741
+ runManager: runs.get(channelId),
724
742
  appHomeDir: options.paths.appHomeDir,
725
743
  authConfigPath: options.paths.authConfigPath,
726
744
  modelsConfigPath: options.paths.modelsConfigPath,
@@ -741,7 +759,8 @@ export async function createRuntimeContext(options) {
741
759
  // task driver's own `notify` needs) — these two closures resolve them lazily, the same way
742
760
  // `getRunner` above already resolves `bot` before its own declaration: nothing here calls
743
761
  // through them until long after the whole function has finished setting up.
744
- const getExecutor = () => executor;
762
+ const getJobs = () => jobs;
763
+ const getRuns = () => runs;
745
764
  const getTaskDriver = () => taskDriver;
746
765
  const handler = createDingTalkHandler({
747
766
  options,
@@ -757,7 +776,8 @@ export async function createRuntimeContext(options) {
757
776
  startedAt,
758
777
  isShuttingDown,
759
778
  getDurableDispatch,
760
- getExecutor,
779
+ getJobs,
780
+ getRuns,
761
781
  getTaskDriver,
762
782
  });
763
783
  const bot = options.createBot
@@ -777,17 +797,18 @@ export async function createRuntimeContext(options) {
777
797
  `记录文件:state/dispatch/${record.id}.json(已保留,供排查)。`);
778
798
  },
779
799
  });
780
- const executor = createExecutor();
800
+ const executor = options.executor ?? createExecutor();
781
801
  // Background jobs get their persistence root and their way to wake a channel before any turn
782
802
  // can start one, then re-adopt whatever survived the last shutdown (spec 031, D6).
783
- configureJobRuntime({
803
+ const jobs = createJobRuntime(executor, {
784
804
  jobsStateDir: join(options.paths.appHomeDir, "state", "jobs"),
805
+ workspaceDir: options.paths.workspaceDir,
785
806
  dispatch: (event) => durableDispatch?.dispatch(event) ?? false,
786
807
  ...(options.jobSweepIntervalMs ? { sweepIntervalMs: options.jobSweepIntervalMs } : {}),
787
808
  });
788
809
  // Delegation runs get the same treatment (spec 040, D1/D7): persistence root, wake delivery,
789
810
  // and the usage/archive authority, wired before any turn can start a run.
790
- configureSubAgentRuntime({
811
+ const runs = createSubAgentRuntime({
791
812
  stateDir: join(options.paths.appHomeDir, "state", "subagent-runs"),
792
813
  dispatch: (event) => durableDispatch?.dispatch(event) ?? false,
793
814
  // P0-1/P1a: a best-effort out-of-band notice, independent of the completion wake — it reaches
@@ -812,8 +833,9 @@ export async function createRuntimeContext(options) {
812
833
  // Spec 042 D11: `restoreChannelJobs` used to be a bare `void` while `restoreAllSubAgentRuns`
813
834
  // was already awaited — the same admission race P0-1 closed for delegation runs was still open
814
835
  // for background jobs.
815
- await restoreChannelJobs(executor);
816
- await restoreAllSubAgentRuns();
836
+ await jobs.restore();
837
+ await runs.restore();
838
+ runs.start();
817
839
  // Spec 043, D10 point 1: repair any turn interrupted by the last shutdown/crash before opening
818
840
  // admission — a message routed to a still-dangling session would 400 against the provider on
819
841
  // every attempt (F3) until a human ran /new. Runs before bot.start() for the same reason as
@@ -903,7 +925,8 @@ export async function createRuntimeContext(options) {
903
925
  durableDispatch?.stop();
904
926
  memoryMaintenanceScheduler.stop();
905
927
  eventsWatcher.stop();
906
- stopSubAgentGarbageCollector();
928
+ runs.stop();
929
+ jobs.stop();
907
930
  await bot.stop();
908
931
  const runningTasks = Array.from(activeTasks);
909
932
  if (runningTasks.length > 0) {
@@ -990,6 +1013,8 @@ export async function createRuntimeContext(options) {
990
1013
  }
991
1014
  return {
992
1015
  handler,
1016
+ jobs,
1017
+ runs,
993
1018
  store,
994
1019
  bot,
995
1020
  taskDriver,
@@ -997,41 +1022,6 @@ export async function createRuntimeContext(options) {
997
1022
  shutdown: shutdownWithReason,
998
1023
  };
999
1024
  }
1000
- /**
1001
- * Transport-neutral app services shared by the DingTalk runtime and the terminal
1002
- * TUI: loads settings (surfacing load errors) and reports tool/security config
1003
- * diagnostics. Does NOT touch DingTalk config, so the TUI can call it without any
1004
- * DingTalk credentials.
1005
- *
1006
- * Extracted verbatim from `bootstrap()`; the DingTalk path calls it in the same
1007
- * position (after `loadConfig`, before `logStartup`) so its behavior is
1008
- * unchanged. Logging configuration is intentionally left to each caller
1009
- * (DingTalk: `createRuntimeContext`; TUI: right after this) to preserve the
1010
- * existing "diagnostics logged with default logging config" ordering.
1011
- */
1012
- export function prepareAppServices(paths = DEFAULT_BOOTSTRAP_PATHS) {
1013
- // Shared by the DingTalk daemon and the TUI (both call prepareAppServices), so this
1014
- // covers every entrypoint that talks to an LLM provider.
1015
- installLlmProxy();
1016
- const settingsManager = new PipiclawSettingsManager(paths.appHomeDir);
1017
- for (const { scope, error } of settingsManager.drainErrors()) {
1018
- log.logWarning(`Failed to load ${scope} settings`, `${error.message}\n${paths.settingsConfigPath}`);
1019
- }
1020
- // Errors already went out above with a richer message; this pass exists for the
1021
- // warnings, chiefly retired settings keys (spec 035 D3).
1022
- for (const diagnostic of settingsManager.getDiagnostics()) {
1023
- if (diagnostic.severity === "error")
1024
- continue;
1025
- log.logWarning(formatConfigDiagnostic(diagnostic), diagnostic.path);
1026
- }
1027
- for (const diagnostic of loadToolsConfigWithDiagnostics(paths.appHomeDir).diagnostics) {
1028
- log.logWarning(formatConfigDiagnostic(diagnostic), diagnostic.path);
1029
- }
1030
- for (const diagnostic of loadSecurityConfigWithDiagnostics(paths.appHomeDir).diagnostics) {
1031
- log.logWarning(formatConfigDiagnostic(diagnostic), diagnostic.path);
1032
- }
1033
- return { settingsManager };
1034
- }
1035
1025
  export async function bootstrap(argv, options = {}) {
1036
1026
  const io = options.io ?? console;
1037
1027
  const paths = options.paths ?? DEFAULT_BOOTSTRAP_PATHS;
@@ -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) ||
@@ -0,0 +1,22 @@
1
+ import type { SecurityConfig, SecurityRuntimeContext } from "./types.js";
2
+ /**
3
+ * Backstop read-guard filter for the recursive discovery tools (`grep`, `glob`, `skill list`).
4
+ *
5
+ * A direct `read`/`grep` on a denied path is refused by the per-path guard, but a *recursive*
6
+ * walk rooted at an allowed directory descends straight into denied subtrees — so `grep` would
7
+ * return the contents of a `readDeny`'d file and `glob` would leak its path. Every candidate hit
8
+ * is re-checked here against the read guard and denied entries are dropped before anything is
9
+ * rendered or counted.
10
+ *
11
+ * Residual risk, recorded honestly: for `grep` the child process has already read those files'
12
+ * bytes by the time this JS filter runs. The boundary this actually enforces is "no denied
13
+ * content reaches the model or the tool result". The push-down `--exclude`/`--exclude-dir` flags
14
+ * are what additionally keep `grep` from opening the file at all; this filter is the guarantee,
15
+ * those flags are the optimization. Do not claim the `grep` process never touches a denied file.
16
+ */
17
+ export declare function partitionByReadGuard(absolutePaths: string[], securityConfig: SecurityConfig, securityContext: SecurityRuntimeContext): {
18
+ allowed: string[];
19
+ deniedCount: number;
20
+ };
21
+ /** True when the read guard would allow this single absolute path. */
22
+ export declare function readGuardAllows(absolutePath: string, securityConfig: SecurityConfig, securityContext: SecurityRuntimeContext): boolean;
@@ -0,0 +1,35 @@
1
+ import { guardPath } from "./path-guard.js";
2
+ /**
3
+ * Backstop read-guard filter for the recursive discovery tools (`grep`, `glob`, `skill list`).
4
+ *
5
+ * A direct `read`/`grep` on a denied path is refused by the per-path guard, but a *recursive*
6
+ * walk rooted at an allowed directory descends straight into denied subtrees — so `grep` would
7
+ * return the contents of a `readDeny`'d file and `glob` would leak its path. Every candidate hit
8
+ * is re-checked here against the read guard and denied entries are dropped before anything is
9
+ * rendered or counted.
10
+ *
11
+ * Residual risk, recorded honestly: for `grep` the child process has already read those files'
12
+ * bytes by the time this JS filter runs. The boundary this actually enforces is "no denied
13
+ * content reaches the model or the tool result". The push-down `--exclude`/`--exclude-dir` flags
14
+ * are what additionally keep `grep` from opening the file at all; this filter is the guarantee,
15
+ * those flags are the optimization. Do not claim the `grep` process never touches a denied file.
16
+ */
17
+ export function partitionByReadGuard(absolutePaths, securityConfig, securityContext) {
18
+ const config = securityConfig.enabled ? securityConfig.pathGuard : { ...securityConfig.pathGuard, enabled: false };
19
+ const allowed = [];
20
+ let deniedCount = 0;
21
+ for (const path of absolutePaths) {
22
+ if (guardPath(path, "read", { ...securityContext, config }).allowed) {
23
+ allowed.push(path);
24
+ }
25
+ else {
26
+ deniedCount++;
27
+ }
28
+ }
29
+ return { allowed, deniedCount };
30
+ }
31
+ /** True when the read guard would allow this single absolute path. */
32
+ export function readGuardAllows(absolutePath, securityConfig, securityContext) {
33
+ const config = securityConfig.enabled ? securityConfig.pathGuard : { ...securityConfig.pathGuard, enabled: false };
34
+ return guardPath(absolutePath, "read", { ...securityContext, config }).allowed;
35
+ }
@@ -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;