@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
@@ -2,11 +2,12 @@ import { randomBytes } from "node:crypto";
2
2
  import { chmod, mkdir, readdir, readFile, unlink } from "node:fs/promises";
3
3
  import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
+ import { getChannelDir } from "../channel/channel-paths.js";
5
6
  import { createFileStore } from "../file-store.js";
6
7
  import * as log from "../log.js";
7
8
  import { writeFileAtomically } from "../shared/atomic-file.js";
9
+ import { shellEscape } from "../shared/os.js";
8
10
  import { createSerialQueue } from "../shared/serial-queue.js";
9
- import { shellEscape } from "../shared/shell-escape.js";
10
11
  import { errorMessage } from "../shared/text-utils.js";
11
12
  import { isRecord } from "../shared/type-guards.js";
12
13
  import { beginWakeClaim, finishWakeClaim } from "../shared/wake-claim.js";
@@ -108,8 +109,8 @@ export const FINISHED_JOB_RETENTION_MS = 24 * 60 * 60_000;
108
109
  const WAKE_OUTPUT_TAIL_BYTES = 2_000;
109
110
  /** Upper bound on how much of a spill file's tail `readOutput` reads (spec 044, D8). */
110
111
  const JOB_OUTPUT_READ_MAX_BYTES = 512 * 1024;
111
- function jobSpillPath(id) {
112
- return join(tmpdir(), `pipiclaw-job-${id}.log`);
112
+ function jobSpillPath(id, spillDir) {
113
+ return join(spillDir ?? tmpdir(), `pipiclaw-job-${id}.log`);
113
114
  }
114
115
  function isTerminal(status) {
115
116
  return status !== "running";
@@ -210,6 +211,7 @@ export class ChannelJobManager {
210
211
  */
211
212
  this.reconcileQueue = createSerialQueue();
212
213
  this.sweeping = false;
214
+ this.stopped = false;
213
215
  // A bare number keeps the original `sweepIntervalMs` positional form working for tests.
214
216
  this.options = typeof options === "number" ? { sweepIntervalMs: options } : options;
215
217
  this.sweepIntervalMs = this.options.sweepIntervalMs ?? SWEEP_INTERVAL_MS;
@@ -272,6 +274,8 @@ export class ChannelJobManager {
272
274
  * to enforce the retention promise without keeping an idle channel awake every few seconds.
273
275
  */
274
276
  scheduleGarbageCollection() {
277
+ if (this.stopped)
278
+ return;
275
279
  if (this.garbageCollectionTimer) {
276
280
  clearTimeout(this.garbageCollectionTimer);
277
281
  this.garbageCollectionTimer = undefined;
@@ -321,7 +325,10 @@ export class ChannelJobManager {
321
325
  throw new Error(`Too many background jobs already running (>= ${MAX_RUNNING_JOBS}). Poll or cancel some with the job tool first.`);
322
326
  }
323
327
  const id = randomBytes(6).toString("hex");
324
- const spillFile = jobSpillPath(id);
328
+ if (this.options.spillDir) {
329
+ await mkdir(this.options.spillDir, { recursive: true }).catch(() => undefined);
330
+ }
331
+ const spillFile = jobSpillPath(id, this.options.spillDir);
325
332
  const art = jobArtifacts(spillFile);
326
333
  const launch = buildLaunchScript(command, art);
327
334
  let result;
@@ -458,7 +465,7 @@ export class ChannelJobManager {
458
465
  * so their slots free up even when the model never polls, and stops itself once nothing is running.
459
466
  */
460
467
  ensureSweeper() {
461
- if (this.sweepTimer || this.runningCount() === 0) {
468
+ if (this.stopped || this.sweepTimer || this.runningCount() === 0) {
462
469
  return;
463
470
  }
464
471
  this.sweepTimer = setInterval(() => {
@@ -472,6 +479,14 @@ export class ChannelJobManager {
472
479
  // Do not keep the process alive just for the sweeper.
473
480
  this.sweepTimer.unref?.();
474
481
  }
482
+ /** Stop observation at application shutdown; detached jobs keep running. */
483
+ stop() {
484
+ this.stopped = true;
485
+ this.stopSweeper();
486
+ if (this.garbageCollectionTimer)
487
+ clearTimeout(this.garbageCollectionTimer);
488
+ this.garbageCollectionTimer = undefined;
489
+ }
475
490
  stopSweeper() {
476
491
  if (this.sweepTimer) {
477
492
  clearInterval(this.sweepTimer);
@@ -479,7 +494,7 @@ export class ChannelJobManager {
479
494
  }
480
495
  }
481
496
  async sweep() {
482
- if (this.sweeping) {
497
+ if (this.stopped || this.sweeping) {
483
498
  return; // A prior sweep is still awaiting the executor; skip this tick.
484
499
  }
485
500
  this.sweeping = true;
@@ -493,7 +508,7 @@ export class ChannelJobManager {
493
508
  // per-job slot so it cannot race a concurrent list/poll/cancel.
494
509
  await this.reconcileQueue
495
510
  .run(record.id, async () => {
496
- if (record.status !== "running")
511
+ if (this.stopped || record.status !== "running")
497
512
  return;
498
513
  await this.applyProbe(record, probes.get(record.id) ?? "");
499
514
  })
@@ -862,13 +877,20 @@ export class ChannelJobManager {
862
877
  */
863
878
  async poll(ids, signal) {
864
879
  const deadline = Date.now() + POLL_WAIT_MS;
865
- const watchIds = () => ids && ids.length > 0
880
+ // Freeze the observation set once, up front. `refresh(..., announce=false)` marks a job's
881
+ // completion wake as consumed (the result is being returned inline), so if we re-derived the
882
+ // watch list each iteration a job that finished mid-poll would drop out of "running", never
883
+ // make it into the returned snapshot, and never wake the channel either — the closure lost
884
+ // entirely. With `ids` omitted this is a snapshot of the jobs running *now*; a job started
885
+ // after poll begins is not folded into this call (poll is snapshot semantics — see the tool
886
+ // description).
887
+ const watchedIds = ids && ids.length > 0
866
888
  ? ids.filter((id) => this.jobs.has(id))
867
889
  : Array.from(this.jobs.values())
868
890
  .filter((job) => job.status === "running")
869
891
  .map((job) => job.id);
870
892
  while (true) {
871
- for (const id of watchIds()) {
893
+ for (const id of watchedIds) {
872
894
  const record = this.jobs.get(id);
873
895
  if (record) {
874
896
  // poll returns the finished job's output to the model inline, so it must not
@@ -876,7 +898,7 @@ export class ChannelJobManager {
876
898
  await this.refresh(record, signal, false);
877
899
  }
878
900
  }
879
- const watched = watchIds()
901
+ const watched = watchedIds
880
902
  .map((id) => this.jobs.get(id))
881
903
  .filter((record) => record !== undefined);
882
904
  const anyDone = watched.some((record) => record.status !== "running");
@@ -953,65 +975,68 @@ export class ChannelJobManager {
953
975
  return { spillFile: record.spillFile, text };
954
976
  }
955
977
  }
956
- // One manager per channel, shared across tool rebuilds so job records survive a resource reload —
957
- // mirrors the shared singletons used elsewhere in the runtime (e.g. the channel memory queue).
958
- const managers = new Map();
959
- let runtimeConfig = {};
960
- /**
961
- * Give background jobs their persistence root and their way to wake a channel. Called once from
962
- * bootstrap, before any turn runs; the tool layer builds managers lazily and picks this up.
963
- */
964
- export function configureJobRuntime(config) {
965
- runtimeConfig = config;
966
- }
967
- /**
968
- * Human-readable lines naming this channel's currently running background jobs, for the `/project
969
- * set|reset` blocker check (spec 043, D4.3) — mirrors `channelJobTaskIds`'s "no manager means no
970
- * jobs" reasoning, so it needs no `Executor` either.
971
- */
972
- export function channelRunningJobLines(channelId) {
973
- const manager = managers.get(channelId);
974
- if (!manager)
975
- return [];
976
- return manager.listRunning().map((job) => `job \`${job.id}\`: ${job.command.slice(0, 80)}`);
977
- }
978
- export function getChannelJobManager(channelId, executor) {
979
- let manager = managers.get(channelId);
980
- if (!manager) {
981
- manager = new ChannelJobManager(channelId, executor, {
982
- ...(runtimeConfig.jobsStateDir ? { stateDir: join(runtimeConfig.jobsStateDir, channelId) } : {}),
983
- ...(runtimeConfig.dispatch ? { dispatch: runtimeConfig.dispatch } : {}),
984
- ...(runtimeConfig.sweepIntervalMs ? { sweepIntervalMs: runtimeConfig.sweepIntervalMs } : {}),
985
- });
986
- managers.set(channelId, manager);
978
+ /** One application's jobs; the executor and configuration cannot change after construction. */
979
+ export function createJobRuntime(executor, options = {}) {
980
+ const config = { ...options };
981
+ const managers = new Map();
982
+ let stopped = false;
983
+ function runningLines(channelId) {
984
+ const manager = managers.get(channelId);
985
+ if (!manager)
986
+ return [];
987
+ return manager.listRunning().map((job) => `job \`${job.id}\`: ${job.command.slice(0, 80)}`);
987
988
  }
988
- return manager;
989
- }
990
- /**
991
- * Re-adopt every channel's persisted jobs at startup. Channels are discovered from the state
992
- * directory itself, so a job survives even when its channel has had no traffic since the restart.
993
- */
994
- export async function restoreChannelJobs(executor) {
995
- const jobsStateDir = runtimeConfig.jobsStateDir;
996
- if (!jobsStateDir)
997
- return 0;
998
- let channelIds;
999
- try {
1000
- await mkdir(jobsStateDir, { recursive: true });
1001
- channelIds = (await readdir(jobsStateDir, { withFileTypes: true }))
1002
- .filter((entry) => entry.isDirectory())
1003
- .map((entry) => entry.name);
1004
- }
1005
- catch (error) {
1006
- log.logWarning("Failed to scan persisted background jobs", errorMessage(error));
1007
- return 0;
1008
- }
1009
- let restored = 0;
1010
- for (const channelId of channelIds) {
1011
- restored += await getChannelJobManager(channelId, executor).restore();
1012
- }
1013
- if (restored > 0) {
1014
- log.logInfo(`Restored ${restored} background job record(s)`);
1015
- }
1016
- return restored;
989
+ function get(channelId) {
990
+ let manager = managers.get(channelId);
991
+ if (!manager) {
992
+ manager = new ChannelJobManager(channelId, executor, {
993
+ ...(config.jobsStateDir ? { stateDir: join(config.jobsStateDir, channelId) } : {}),
994
+ ...(config.workspaceDir ? { spillDir: join(getChannelDir(config.workspaceDir, channelId), "logs") } : {}),
995
+ ...(config.dispatch ? { dispatch: config.dispatch } : {}),
996
+ ...(config.sweepIntervalMs ? { sweepIntervalMs: config.sweepIntervalMs } : {}),
997
+ });
998
+ managers.set(channelId, manager);
999
+ if (stopped)
1000
+ manager.stop();
1001
+ }
1002
+ return manager;
1003
+ }
1004
+ /**
1005
+ * Re-adopt every channel's persisted jobs at startup. Channels are discovered from the state
1006
+ * directory itself, so a job survives even when its channel has had no traffic since the restart.
1007
+ */
1008
+ async function restore() {
1009
+ const jobsStateDir = config.jobsStateDir;
1010
+ if (!jobsStateDir)
1011
+ return 0;
1012
+ let channelIds;
1013
+ try {
1014
+ await mkdir(jobsStateDir, { recursive: true });
1015
+ channelIds = (await readdir(jobsStateDir, { withFileTypes: true }))
1016
+ .filter((entry) => entry.isDirectory())
1017
+ .map((entry) => entry.name);
1018
+ }
1019
+ catch (error) {
1020
+ log.logWarning("Failed to scan persisted background jobs", errorMessage(error));
1021
+ return 0;
1022
+ }
1023
+ let restored = 0;
1024
+ for (const channelId of channelIds) {
1025
+ restored += await get(channelId).restore();
1026
+ }
1027
+ if (restored > 0) {
1028
+ log.logInfo(`Restored ${restored} background job record(s)`);
1029
+ }
1030
+ return restored;
1031
+ }
1032
+ return {
1033
+ get,
1034
+ runningLines,
1035
+ restore,
1036
+ stop: () => {
1037
+ stopped = true;
1038
+ for (const manager of managers.values())
1039
+ manager.stop();
1040
+ },
1041
+ };
1017
1042
  }
@@ -13,7 +13,7 @@
13
13
  */
14
14
  import type { PromptBuildContext, PromptBuildResult, PromptSectionDefinition } from "./types.js";
15
15
  /** Bumped whenever the runtime-authored prompt text changes in a way worth attributing in telemetry. */
16
- export declare const RUNTIME_PROMPT_VERSION = 3;
16
+ export declare const RUNTIME_PROMPT_VERSION = 4;
17
17
  /** Over this, the runtime-authored prompt still works but is worth a warning (spec 026 §5.2). */
18
18
  export declare const RUNTIME_PROMPT_TARGET_UNITS = 700;
19
19
  /** Over this it is a development error: runtime text has drifted well past its budget. */
@@ -12,11 +12,11 @@
12
12
  * budgeted independently in resources.ts, and skills are pi's to render.
13
13
  */
14
14
  import { createHash } from "node:crypto";
15
+ import { estimateTokens } from "../../shared/format.js";
15
16
  import { countPromptUnits } from "../../shared/prompt-units.js";
16
- import { estimateTokens } from "../../shared/token-estimate.js";
17
17
  import { FINAL_BOUNDARY_SECTION, MAIN_PROMPT_SECTIONS } from "./sections.js";
18
18
  /** Bumped whenever the runtime-authored prompt text changes in a way worth attributing in telemetry. */
19
- export const RUNTIME_PROMPT_VERSION = 3;
19
+ export const RUNTIME_PROMPT_VERSION = 4;
20
20
  /**
21
21
  * The sections Pipiclaw authors and must keep tight (spec 026 §10.3): identity,
22
22
  * execution, invariants, persistent-task rules, the runtime-guide catalog and the
@@ -68,13 +68,6 @@ function applyOverflow(definition, content, diagnostics) {
68
68
  return { content, truncated: false };
69
69
  }
70
70
  switch (definition.overflow) {
71
- case "omit":
72
- diagnostics.push({
73
- level: "warning",
74
- sectionId: definition.id,
75
- message: `${content.length} chars exceeds the ${definition.maxChars} char budget; section omitted.`,
76
- });
77
- return { content: "", truncated: true };
78
71
  case "truncate-items":
79
72
  diagnostics.push({
80
73
  level: "warning",
@@ -108,9 +101,6 @@ function applyOverflow(definition, content, diagnostics) {
108
101
  }
109
102
  }
110
103
  function resolve(definition, context, diagnostics) {
111
- if (definition.modes && !definition.modes.includes(context.mode)) {
112
- return undefined;
113
- }
114
104
  if (definition.requiresAllTools?.some((name) => !context.tools.some((tool) => tool.name === name))) {
115
105
  return undefined;
116
106
  }
@@ -124,7 +114,6 @@ function resolve(definition, context, diagnostics) {
124
114
  }
125
115
  return {
126
116
  id: definition.id,
127
- order: definition.order,
128
117
  source: definition.source,
129
118
  authority: definition.authority,
130
119
  cacheClass: definition.cacheClass,
@@ -140,17 +129,12 @@ function resolve(definition, context, diagnostics) {
140
129
  export function buildPipiclawSystemPrompt(context, definitions = MAIN_PROMPT_SECTIONS) {
141
130
  const diagnostics = [];
142
131
  const ids = new Set();
143
- const orders = new Set();
144
132
  for (const definition of [...definitions, FINAL_BOUNDARY_SECTION]) {
145
133
  if (ids.has(definition.id))
146
134
  throw new Error(`Duplicate prompt section id: ${definition.id}`);
147
- if (orders.has(definition.order))
148
- throw new Error(`Duplicate prompt section order: ${definition.order}`);
149
135
  ids.add(definition.id);
150
- orders.add(definition.order);
151
136
  }
152
137
  const sections = [...definitions]
153
- .sort((a, b) => a.order - b.order)
154
138
  .map((definition) => resolve(definition, context, diagnostics))
155
139
  .filter((section) => section !== undefined);
156
140
  const footerSection = resolve(FINAL_BOUNDARY_SECTION, context, diagnostics);
@@ -69,7 +69,6 @@ export interface PromptContextReportInput {
69
69
  }
70
70
  export interface PromptSectionManifestEntry {
71
71
  id: string;
72
- order: number;
73
72
  source: string;
74
73
  authority: string;
75
74
  cacheClass: string;
@@ -9,8 +9,8 @@
9
9
  * owns the same list that backs `/skill:name`, so `estimateSkillsPromptChars` lives
10
10
  * next to the report — not in the builder's budget path (spec 026 §9, §10.9).
11
11
  */
12
+ import { estimateTokens } from "../../shared/format.js";
12
13
  import { countPromptUnits } from "../../shared/prompt-units.js";
13
- import { estimateTokens } from "../../shared/token-estimate.js";
14
14
  import { RUNTIME_PROMPT_TARGET_UNITS, sha256 } from "./builder.js";
15
15
  /** The design ceiling for everything Pipiclaw auto-appends to a turn (spec 026 §5.3). */
16
16
  export const AUTOMATIC_TURN_CONTEXT_BUDGET_UNITS = 3_000;
@@ -144,7 +144,7 @@ export function renderContextReport(input) {
144
144
  lines.push("");
145
145
  lines.push("Detail:");
146
146
  for (const section of build.sections) {
147
- lines.push(`- ${section.id} (order ${section.order}, ${section.authority}) ← ${section.source} · sha256:${section.sha256.slice(0, 12)}`);
147
+ lines.push(`- ${section.id} (${section.authority}) ← ${section.source} · sha256:${section.sha256.slice(0, 12)}`);
148
148
  }
149
149
  if (input.toolNames.length > 0) {
150
150
  lines.push(`- tools: ${input.toolNames.join(", ")}`);
@@ -36,7 +36,6 @@ function sealContent(content, tag) {
36
36
  }
37
37
  export const IDENTITY_SECTION = {
38
38
  id: "runtime.identity",
39
- order: 100,
40
39
  source: "runtime/identity",
41
40
  authority: "runtime-fact",
42
41
  cacheClass: "runtime-stable",
@@ -49,7 +48,6 @@ export const IDENTITY_SECTION = {
49
48
  };
50
49
  export const EXECUTION_SECTION = {
51
50
  id: "runtime.execution",
52
- order: 200,
53
51
  source: "runtime/execution",
54
52
  authority: "runtime-fact",
55
53
  cacheClass: "runtime-stable",
@@ -59,13 +57,12 @@ export const EXECUTION_SECTION = {
59
57
  "## Working Contract",
60
58
  "- For actionable requests, continue until the requested outcome exists or you are genuinely blocked. Inspect before changing and verify material results.",
61
59
  "- State what remains unverified. Tool definitions are the source of truth for available capabilities and parameters.",
62
- "- Background jobs and delegations wake this channel when they finish: end the turn instead of polling, scheduling a check-in, or looping to wait.",
63
- "- Before non-trivial use of a Pipiclaw mechanism or workspace procedure, read the matching runtime guide or skill.",
60
+ "- Jobs and delegations wake this channel on completion. Finish independent work and dispatches; when only waiting remains, end the turn without polling or check-in events.",
61
+ "- Before non-trivial use of a runtime mechanism or workspace procedure, read its guide or skill; reuse it while it remains in context.",
64
62
  ].join("\n"),
65
63
  };
66
64
  export const INVARIANTS_SECTION = {
67
65
  id: "runtime.invariants",
68
- order: 300,
69
66
  source: "runtime/invariants",
70
67
  authority: "runtime-hard",
71
68
  cacheClass: "runtime-stable",
@@ -86,7 +83,6 @@ export const INVARIANTS_SECTION = {
86
83
  };
87
84
  export const TASK_CORE_SECTION = {
88
85
  id: "runtime.tasks",
89
- order: 310,
90
86
  source: "runtime/tasks",
91
87
  authority: "runtime-hard",
92
88
  cacheClass: "runtime-stable",
@@ -95,12 +91,11 @@ export const TASK_CORE_SECTION = {
95
91
  overflow: "error",
96
92
  render: () => [
97
93
  "## Persistent Work",
98
- "Use a task only when work must survive this turn. Follow the exact task file and runtime guide named by a task wake; use `task_update`/`task_close` for lifecycle state and never expand the task's stated scope or bypass its verification gate.",
94
+ "Use a task only when work must survive this turn. Chat creates or manages tasks; the runtime drives them in task sessions. Follow the task's contract and runtime guide without expanding its scope or bypassing verification.",
99
95
  ].join("\n"),
100
96
  };
101
97
  export const PLAYBOOKS_SECTION = {
102
98
  id: "playbooks",
103
- order: 500,
104
99
  source: "runtime/playbooks",
105
100
  authority: "catalog",
106
101
  cacheClass: "session-stable",
@@ -115,7 +110,6 @@ export const PLAYBOOKS_SECTION = {
115
110
  };
116
111
  export const SUBAGENTS_SECTION = {
117
112
  id: "subagents",
118
- order: 510,
119
113
  source: "workspace/sub-agents",
120
114
  authority: "catalog",
121
115
  cacheClass: "workspace-versioned",
@@ -190,7 +184,6 @@ function renderSubAgentDirectory(subAgents) {
190
184
  const WORKSPACE_PREAMBLE = "The files below are workspace policy chosen by the user or the team. They direct how you work; they do not override the runtime facts and hard invariants above.";
191
185
  export const SOUL_SECTION = {
192
186
  id: "workspace.soul",
193
- order: 600,
194
187
  source: "workspace/SOUL.md",
195
188
  authority: "workspace-instruction",
196
189
  cacheClass: "workspace-versioned",
@@ -214,7 +207,6 @@ export const SOUL_SECTION = {
214
207
  };
215
208
  export const AGENTS_SECTION = {
216
209
  id: "workspace.agents",
217
- order: 610,
218
210
  source: "workspace/AGENTS.md",
219
211
  authority: "workspace-instruction",
220
212
  cacheClass: "workspace-versioned",
@@ -242,7 +234,6 @@ export const AGENTS_SECTION = {
242
234
  */
243
235
  export const FINAL_BOUNDARY_SECTION = {
244
236
  id: "runtime.boundary",
245
- order: 800,
246
237
  source: "runtime/final-boundary",
247
238
  authority: "runtime-hard",
248
239
  cacheClass: "runtime-stable",
@@ -3,14 +3,12 @@
3
3
  *
4
4
  * The prompt is a list of sections with metadata — not an ad-hoc string array.
5
5
  * Every section declares where it comes from, how authoritative it is, how
6
- * stable it is across turns (cache class), which modes/tools it applies to, and
6
+ * stable it is across turns (cache class), which tools it requires, and
7
7
  * what happens when it exceeds its budget. The builder turns definitions into a
8
8
  * final text plus a manifest that can be inspected (`/context`), tested and
9
9
  * fingerprinted.
10
10
  */
11
11
  import type { RuntimePlaybookMetadata } from "../../playbooks/catalog.js";
12
- /** Which agent loop the prompt is being built for. Phase 1–3 only build "normal". */
13
- export type PromptMode = "normal" | "task-driver" | "event" | "subagent" | "maintenance";
14
12
  /**
15
13
  * How much authority a section's content carries.
16
14
  * - `runtime-hard`: boundaries workspace content may not redefine (still enforced by guards/state machines, not by prose).
@@ -26,7 +24,7 @@ export type PromptCacheClass = "runtime-stable" | "workspace-versioned" | "sessi
26
24
  * What to do when a section exceeds `maxChars`.
27
25
  * `error` is for runtime-authored text: overflowing it is a development error, not a user problem.
28
26
  */
29
- export type PromptOverflowPolicy = "error" | "truncate-head-tail" | "truncate-items" | "omit";
27
+ export type PromptOverflowPolicy = "error" | "truncate-head-tail" | "truncate-items";
30
28
  /**
31
29
  * A registered tool, as the prompt builder sees it. There is no per-tool prose here and no
32
30
  * section renders this list: spec 026 §3.2 removed `## Available Tools` because the model
@@ -67,31 +65,18 @@ export interface LoadedPromptResource {
67
65
  truncated: boolean;
68
66
  }
69
67
  export interface PromptBuildContext {
70
- mode: PromptMode;
71
- /** Bash working directory. Not the channel directory: channel facts are turn-dynamic and never enter the system prompt. */
72
- cwd: string;
73
- workspaceDir: string;
74
68
  tools: ToolDescriptor[];
75
69
  soul?: LoadedPromptResource;
76
70
  agents?: LoadedPromptResource;
77
71
  playbooks: RuntimePlaybookMetadata[];
78
72
  subAgents: SubAgentSummary[];
79
- /** Skills are rendered by pi (they drive `/skill:name` too); recorded here for the manifest only. */
80
- skills?: Array<{
81
- name: string;
82
- description: string;
83
- }>;
84
73
  }
85
74
  export interface PromptSectionDefinition {
86
75
  id: string;
87
- /** Sort key. Unique across sections; see the reserved ranges in sections.ts. */
88
- order: number;
89
76
  /** Code identifier or real file path. */
90
77
  source: string;
91
78
  authority: PromptAuthority;
92
79
  cacheClass: PromptCacheClass;
93
- /** Modes this section applies to. Omitted = all modes. */
94
- modes?: PromptMode[];
95
80
  /**
96
81
  * Section is dropped unless *every* listed tool is registered — all-of. A section
97
82
  * describes one mechanism, so a missing tool means the mechanism is unreachable.
@@ -104,7 +89,6 @@ export interface PromptSectionDefinition {
104
89
  }
105
90
  export interface ResolvedPromptSection {
106
91
  id: string;
107
- order: number;
108
92
  source: string;
109
93
  authority: PromptAuthority;
110
94
  cacheClass: PromptCacheClass;
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * The prompt is a list of sections with metadata — not an ad-hoc string array.
5
5
  * Every section declares where it comes from, how authoritative it is, how
6
- * stable it is across turns (cache class), which modes/tools it applies to, and
6
+ * stable it is across turns (cache class), which tools it requires, and
7
7
  * what happens when it exceeds its budget. The builder turns definitions into a
8
8
  * final text plus a manifest that can be inspected (`/context`), tested and
9
9
  * fingerprinted.
@@ -3,8 +3,12 @@ import { type Executor } from "../executor.js";
3
3
  import { type FileStore } from "../file-store.js";
4
4
  import { type LoadedSecurityConfig } from "../security/config.js";
5
5
  import type { PipiclawSettingsManager } from "../settings.js";
6
+ import type { SubAgentRunManager } from "../subagents/runs.js";
7
+ import type { ChannelJobManager } from "./job-manager.js";
6
8
  import type { AgentRunner } from "./types.js";
7
9
  export interface RunnerFactoryPaths {
10
+ jobManager?: ChannelJobManager;
11
+ runManager?: SubAgentRunManager;
8
12
  appHomeDir: string;
9
13
  authConfigPath: string;
10
14
  modelsConfigPath: string;
@@ -0,0 +1,19 @@
1
+ import type { Agent, AgentTool, ThinkingLevel } from "@earendil-works/pi-agent-core";
2
+ import type { Api, Model } from "@earendil-works/pi-ai";
3
+ import { type AgentSession, SettingsManager as SDKSettingsManager, type SessionManager } from "@earendil-works/pi-coding-agent";
4
+ import type { PipiclawSettingsManager } from "../settings.js";
5
+ export declare function asSdkSettingsManager(manager: PipiclawSettingsManager): SDKSettingsManager;
6
+ export declare const DEFAULT_MAIN_THINKING_LEVEL: ThinkingLevel;
7
+ /** Apply the pi 0.83 source-model thinking compatibility branch to one real AgentSession. */
8
+ export declare function setModelWithThinkingPreservation(session: AgentSession, manager: SDKSettingsManager, model: Model<Api>): Promise<void>;
9
+ export declare function setThinkingLevelWithConditionalPersist(session: AgentSession, level: ThinkingLevel): void;
10
+ export declare function cycleThinkingLevelWithConditionalPersist(session: AgentSession): ThinkingLevel | undefined;
11
+ export declare function initializeThinkingLevelCompat(agent: Agent, model: Model<Api>, sessionManager: SessionManager, configuredDefault: ThinkingLevel | undefined): ThinkingLevel;
12
+ /**
13
+ * Overwrite the SDK session's `baseToolsOverride` map so a resource reload swaps in
14
+ * freshly-built tools. The SDK exposes no public setter for this, so we reach into the
15
+ * private `_baseToolsOverride` field. This is the single, isolated point of that coupling:
16
+ * if a future SDK renames or removes the field, the guard below warns loudly instead of
17
+ * silently leaving stale tools in place. Replace with a public setter once upstream adds one.
18
+ */
19
+ export declare function setSessionBaseToolsOverride(session: AgentSession, tools: AgentTool<any>[], channelId: string): void;
@@ -0,0 +1,77 @@
1
+ import { clampThinkingLevel } from "@earendil-works/pi-ai/compat";
2
+ import { SettingsManager as SDKSettingsManager, } from "@earendil-works/pi-coding-agent";
3
+ import * as log from "../log.js";
4
+ export function asSdkSettingsManager(manager) {
5
+ // The upstream session needs its broad interactive SettingsManager surface, while
6
+ // Pipiclaw deliberately owns a small runtime-specific settings contract. Build a
7
+ // real upstream manager from that contract instead of making PipiclawSettingsManager
8
+ // pretend to implement dozens of unrelated no-op UI preferences.
9
+ return SDKSettingsManager.inMemory({
10
+ defaultProvider: manager.getDefaultProvider(),
11
+ defaultModel: manager.getDefaultModel(),
12
+ defaultThinkingLevel: manager.getDefaultThinkingLevel() ?? DEFAULT_MAIN_THINKING_LEVEL,
13
+ compaction: manager.getCompactionSettings(),
14
+ retry: manager.getRetrySettings(),
15
+ });
16
+ }
17
+ export const DEFAULT_MAIN_THINKING_LEVEL = "medium";
18
+ /** Apply the pi 0.83 source-model thinking compatibility branch to one real AgentSession. */
19
+ export async function setModelWithThinkingPreservation(session, manager, model) {
20
+ const source = session.model;
21
+ if (!source?.reasoning) {
22
+ await session.setModel(model);
23
+ return;
24
+ }
25
+ const previousDefault = manager.getDefaultThinkingLevel();
26
+ manager.setDefaultThinkingLevel(session.thinkingLevel);
27
+ try {
28
+ await session.setModel(model);
29
+ }
30
+ finally {
31
+ manager.setDefaultThinkingLevel(previousDefault ?? DEFAULT_MAIN_THINKING_LEVEL);
32
+ }
33
+ }
34
+ export function setThinkingLevelWithConditionalPersist(session, level) {
35
+ const before = session.thinkingLevel;
36
+ session.setThinkingLevel(level);
37
+ const effective = session.thinkingLevel;
38
+ if (effective === before)
39
+ return;
40
+ if (!session.model?.reasoning && effective === "off")
41
+ return;
42
+ session.setThinkingLevel(effective, { persist: true });
43
+ }
44
+ export function cycleThinkingLevelWithConditionalPersist(session) {
45
+ const before = session.thinkingLevel;
46
+ const next = session.cycleThinkingLevel();
47
+ const effective = session.thinkingLevel;
48
+ if (next && effective !== before && (session.model?.reasoning || effective !== "off")) {
49
+ session.setThinkingLevel(effective, { persist: true });
50
+ }
51
+ return next;
52
+ }
53
+ export function initializeThinkingLevelCompat(agent, model, sessionManager, configuredDefault) {
54
+ const branch = sessionManager.getBranch();
55
+ const hasThinkingEntry = branch.some((entry) => entry.type === "thinking_level_change");
56
+ const historical = sessionManager.buildSessionContext().thinkingLevel;
57
+ const requested = hasThinkingEntry ? historical : (configuredDefault ?? DEFAULT_MAIN_THINKING_LEVEL);
58
+ const effective = clampThinkingLevel(model, requested);
59
+ agent.state.thinkingLevel = effective;
60
+ if (!hasThinkingEntry)
61
+ sessionManager.appendThinkingLevelChange(effective);
62
+ return effective;
63
+ }
64
+ /**
65
+ * Overwrite the SDK session's `baseToolsOverride` map so a resource reload swaps in
66
+ * freshly-built tools. The SDK exposes no public setter for this, so we reach into the
67
+ * private `_baseToolsOverride` field. This is the single, isolated point of that coupling:
68
+ * if a future SDK renames or removes the field, the guard below warns loudly instead of
69
+ * silently leaving stale tools in place. Replace with a public setter once upstream adds one.
70
+ */
71
+ export function setSessionBaseToolsOverride(session, tools, channelId) {
72
+ const target = session;
73
+ if (!("_baseToolsOverride" in target)) {
74
+ log.logWarning(`[${channelId}] AgentSession no longer exposes _baseToolsOverride; tool reloads may use stale tools (SDK change?)`);
75
+ }
76
+ target._baseToolsOverride = Object.fromEntries(tools.map((tool) => [tool.name, tool]));
77
+ }
@@ -0,0 +1,18 @@
1
+ import { type BootstrapPaths } from "./runtime/app-home.js";
2
+ import { PipiclawSettingsManager } from "./settings.js";
3
+ /**
4
+ * Transport-neutral app services shared by the DingTalk runtime, the terminal TUI, and the
5
+ * `pipiclaw auth` CLI: loads settings (surfacing load errors) and reports tool/security config
6
+ * diagnostics. Does NOT touch DingTalk config, so non-DingTalk entrypoints can call it without
7
+ * any DingTalk credentials.
8
+ *
9
+ * Lives at the package root rather than in `runtime/` on purpose: `models/auth-cli.ts` needs it
10
+ * before a runner or channel exists, and `runtime/bootstrap.ts` separately depends on `models/`
11
+ * (for the default model reference) — parking this function inside `bootstrap.ts` made `models`
12
+ * and `runtime` depend on each other. Everything this function touches (`settings.ts`,
13
+ * `tools/config.ts`, `security/config.ts`, `runtime/app-home.ts`, `runtime/proxy.ts`) has no
14
+ * import back to `models/`, so this file doesn't reintroduce the cycle it was extracted to break.
15
+ */
16
+ export declare function prepareAppServices(paths?: BootstrapPaths): {
17
+ settingsManager: PipiclawSettingsManager;
18
+ };