@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
@@ -6,8 +6,8 @@ import { getChannelDir } from "../channel/channel-paths.js";
6
6
  import { createFileStore } from "../file-store.js";
7
7
  import * as log from "../log.js";
8
8
  import { writeFileAtomically } from "../shared/atomic-file.js";
9
+ import { shellEscape } from "../shared/os.js";
9
10
  import { createSerialQueue } from "../shared/serial-queue.js";
10
- import { shellEscape } from "../shared/shell-escape.js";
11
11
  import { errorMessage } from "../shared/text-utils.js";
12
12
  import { isRecord } from "../shared/type-guards.js";
13
13
  import { beginWakeClaim, finishWakeClaim } from "../shared/wake-claim.js";
@@ -211,6 +211,7 @@ export class ChannelJobManager {
211
211
  */
212
212
  this.reconcileQueue = createSerialQueue();
213
213
  this.sweeping = false;
214
+ this.stopped = false;
214
215
  // A bare number keeps the original `sweepIntervalMs` positional form working for tests.
215
216
  this.options = typeof options === "number" ? { sweepIntervalMs: options } : options;
216
217
  this.sweepIntervalMs = this.options.sweepIntervalMs ?? SWEEP_INTERVAL_MS;
@@ -273,6 +274,8 @@ export class ChannelJobManager {
273
274
  * to enforce the retention promise without keeping an idle channel awake every few seconds.
274
275
  */
275
276
  scheduleGarbageCollection() {
277
+ if (this.stopped)
278
+ return;
276
279
  if (this.garbageCollectionTimer) {
277
280
  clearTimeout(this.garbageCollectionTimer);
278
281
  this.garbageCollectionTimer = undefined;
@@ -462,7 +465,7 @@ export class ChannelJobManager {
462
465
  * so their slots free up even when the model never polls, and stops itself once nothing is running.
463
466
  */
464
467
  ensureSweeper() {
465
- if (this.sweepTimer || this.runningCount() === 0) {
468
+ if (this.stopped || this.sweepTimer || this.runningCount() === 0) {
466
469
  return;
467
470
  }
468
471
  this.sweepTimer = setInterval(() => {
@@ -476,6 +479,14 @@ export class ChannelJobManager {
476
479
  // Do not keep the process alive just for the sweeper.
477
480
  this.sweepTimer.unref?.();
478
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
+ }
479
490
  stopSweeper() {
480
491
  if (this.sweepTimer) {
481
492
  clearInterval(this.sweepTimer);
@@ -483,7 +494,7 @@ export class ChannelJobManager {
483
494
  }
484
495
  }
485
496
  async sweep() {
486
- if (this.sweeping) {
497
+ if (this.stopped || this.sweeping) {
487
498
  return; // A prior sweep is still awaiting the executor; skip this tick.
488
499
  }
489
500
  this.sweeping = true;
@@ -497,7 +508,7 @@ export class ChannelJobManager {
497
508
  // per-job slot so it cannot race a concurrent list/poll/cancel.
498
509
  await this.reconcileQueue
499
510
  .run(record.id, async () => {
500
- if (record.status !== "running")
511
+ if (this.stopped || record.status !== "running")
501
512
  return;
502
513
  await this.applyProbe(record, probes.get(record.id) ?? "");
503
514
  })
@@ -699,8 +710,7 @@ export class ChannelJobManager {
699
710
  ts: String(Date.now()),
700
711
  conversationType: this.channelId.startsWith("group_") ? "2" : "1",
701
712
  dispatchId: `job:${this.channelId}:${record.id}:done`,
702
- // P0-2: a user is waiting on this job's result — render the resulting turn's progress
703
- // instead of the "none" style autonomous check-ins get.
713
+ // The result is awaited; the wake itself still runs without a progress card.
704
714
  presentation: "awaited",
705
715
  ...(record.contract.taskId
706
716
  ? {
@@ -964,68 +974,68 @@ export class ChannelJobManager {
964
974
  return { spillFile: record.spillFile, text };
965
975
  }
966
976
  }
967
- // One manager per channel, shared across tool rebuilds so job records survive a resource reload —
968
- // mirrors the shared singletons used elsewhere in the runtime (e.g. the channel memory queue).
969
- const managers = new Map();
970
- let runtimeConfig = {};
971
- /**
972
- * Give background jobs their persistence root and their way to wake a channel. Called once from
973
- * bootstrap, before any turn runs; the tool layer builds managers lazily and picks this up.
974
- */
975
- export function configureJobRuntime(config) {
976
- runtimeConfig = config;
977
- }
978
- /**
979
- * Human-readable lines naming this channel's currently running background jobs, for the `/project
980
- * set|reset` blocker check (spec 043, D4.3) — mirrors `channelJobTaskIds`'s "no manager means no
981
- * jobs" reasoning, so it needs no `Executor` either.
982
- */
983
- export function channelRunningJobLines(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)}`);
988
- }
989
- export function getChannelJobManager(channelId, executor) {
990
- let manager = managers.get(channelId);
991
- if (!manager) {
992
- manager = new ChannelJobManager(channelId, executor, {
993
- ...(runtimeConfig.jobsStateDir ? { stateDir: join(runtimeConfig.jobsStateDir, channelId) } : {}),
994
- ...(runtimeConfig.workspaceDir
995
- ? { spillDir: join(getChannelDir(runtimeConfig.workspaceDir, channelId), "logs") }
996
- : {}),
997
- ...(runtimeConfig.dispatch ? { dispatch: runtimeConfig.dispatch } : {}),
998
- ...(runtimeConfig.sweepIntervalMs ? { sweepIntervalMs: runtimeConfig.sweepIntervalMs } : {}),
999
- });
1000
- managers.set(channelId, manager);
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
- export async function restoreChannelJobs(executor) {
1009
- const jobsStateDir = runtimeConfig.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;
977
+ /** One application's jobs; the executor and configuration cannot change after construction. */
978
+ export function createJobRuntime(executor, options = {}) {
979
+ const config = { ...options };
980
+ const managers = new Map();
981
+ let stopped = false;
982
+ function runningLines(channelId) {
983
+ const manager = managers.get(channelId);
984
+ if (!manager)
985
+ return [];
986
+ return manager.listRunning().map((job) => `job \`${job.id}\`: ${job.command.slice(0, 80)}`);
1022
987
  }
1023
- let restored = 0;
1024
- for (const channelId of channelIds) {
1025
- restored += await getChannelJobManager(channelId, executor).restore();
988
+ function get(channelId) {
989
+ let manager = managers.get(channelId);
990
+ if (!manager) {
991
+ manager = new ChannelJobManager(channelId, executor, {
992
+ ...(config.jobsStateDir ? { stateDir: join(config.jobsStateDir, channelId) } : {}),
993
+ ...(config.workspaceDir ? { spillDir: join(getChannelDir(config.workspaceDir, channelId), "logs") } : {}),
994
+ ...(config.dispatch ? { dispatch: config.dispatch } : {}),
995
+ ...(config.sweepIntervalMs ? { sweepIntervalMs: config.sweepIntervalMs } : {}),
996
+ });
997
+ managers.set(channelId, manager);
998
+ if (stopped)
999
+ manager.stop();
1000
+ }
1001
+ return manager;
1026
1002
  }
1027
- if (restored > 0) {
1028
- log.logInfo(`Restored ${restored} background job record(s)`);
1003
+ /**
1004
+ * Re-adopt every channel's persisted jobs at startup. Channels are discovered from the state
1005
+ * directory itself, so a job survives even when its channel has had no traffic since the restart.
1006
+ */
1007
+ async function restore() {
1008
+ const jobsStateDir = config.jobsStateDir;
1009
+ if (!jobsStateDir)
1010
+ return 0;
1011
+ let channelIds;
1012
+ try {
1013
+ await mkdir(jobsStateDir, { recursive: true });
1014
+ channelIds = (await readdir(jobsStateDir, { withFileTypes: true }))
1015
+ .filter((entry) => entry.isDirectory())
1016
+ .map((entry) => entry.name);
1017
+ }
1018
+ catch (error) {
1019
+ log.logWarning("Failed to scan persisted background jobs", errorMessage(error));
1020
+ return 0;
1021
+ }
1022
+ let restored = 0;
1023
+ for (const channelId of channelIds) {
1024
+ restored += await get(channelId).restore();
1025
+ }
1026
+ if (restored > 0) {
1027
+ log.logInfo(`Restored ${restored} background job record(s)`);
1028
+ }
1029
+ return restored;
1029
1030
  }
1030
- return restored;
1031
+ return {
1032
+ get,
1033
+ runningLines,
1034
+ restore,
1035
+ stop: () => {
1036
+ stopped = true;
1037
+ for (const manager of managers.values())
1038
+ manager.stop();
1039
+ },
1040
+ };
1031
1041
  }
@@ -12,8 +12,8 @@
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
19
  export const RUNTIME_PROMPT_VERSION = 4;
@@ -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",
@@ -65,7 +63,6 @@ export const EXECUTION_SECTION = {
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",
@@ -100,7 +96,6 @@ export const TASK_CORE_SECTION = {
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
+ };
@@ -0,0 +1,43 @@
1
+ import * as log from "./log.js";
2
+ import { DEFAULT_BOOTSTRAP_PATHS } from "./runtime/app-home.js";
3
+ import { installLlmProxy } from "./runtime/proxy.js";
4
+ import { loadSecurityConfigWithDiagnostics } from "./security/config.js";
5
+ import { PipiclawSettingsManager } from "./settings.js";
6
+ import { formatConfigDiagnostic } from "./shared/config-diagnostic.js";
7
+ import { loadToolsConfigWithDiagnostics } from "./tools/config.js";
8
+ /**
9
+ * Transport-neutral app services shared by the DingTalk runtime, the terminal TUI, and the
10
+ * `pipiclaw auth` CLI: loads settings (surfacing load errors) and reports tool/security config
11
+ * diagnostics. Does NOT touch DingTalk config, so non-DingTalk entrypoints can call it without
12
+ * any DingTalk credentials.
13
+ *
14
+ * Lives at the package root rather than in `runtime/` on purpose: `models/auth-cli.ts` needs it
15
+ * before a runner or channel exists, and `runtime/bootstrap.ts` separately depends on `models/`
16
+ * (for the default model reference) — parking this function inside `bootstrap.ts` made `models`
17
+ * and `runtime` depend on each other. Everything this function touches (`settings.ts`,
18
+ * `tools/config.ts`, `security/config.ts`, `runtime/app-home.ts`, `runtime/proxy.ts`) has no
19
+ * import back to `models/`, so this file doesn't reintroduce the cycle it was extracted to break.
20
+ */
21
+ export function prepareAppServices(paths = DEFAULT_BOOTSTRAP_PATHS) {
22
+ // Shared by the DingTalk daemon, the TUI, and the auth CLI (all call prepareAppServices), so
23
+ // this covers every entrypoint that talks to an LLM provider.
24
+ installLlmProxy();
25
+ const settingsManager = new PipiclawSettingsManager(paths.appHomeDir);
26
+ for (const { scope, error } of settingsManager.drainErrors()) {
27
+ log.logWarning(`Failed to load ${scope} settings`, `${error.message}\n${paths.settingsConfigPath}`);
28
+ }
29
+ // Errors already went out above with a richer message; this pass exists for the
30
+ // warnings, chiefly retired settings keys (spec 035 D3).
31
+ for (const diagnostic of settingsManager.getDiagnostics()) {
32
+ if (diagnostic.severity === "error")
33
+ continue;
34
+ log.logWarning(formatConfigDiagnostic(diagnostic), diagnostic.path);
35
+ }
36
+ for (const diagnostic of loadToolsConfigWithDiagnostics(paths.appHomeDir).diagnostics) {
37
+ log.logWarning(formatConfigDiagnostic(diagnostic), diagnostic.path);
38
+ }
39
+ for (const diagnostic of loadSecurityConfigWithDiagnostics(paths.appHomeDir).diagnostics) {
40
+ log.logWarning(formatConfigDiagnostic(diagnostic), diagnostic.path);
41
+ }
42
+ return { settingsManager };
43
+ }
@@ -77,6 +77,7 @@ export interface ChannelContext {
77
77
  respondInThread: (text: string) => Promise<void>;
78
78
  setTyping: (isTyping: boolean) => Promise<void>;
79
79
  setWorking: (working: boolean) => Promise<void>;
80
+ /** End without a final answer. Transports may preserve already-visible progress. */
80
81
  deleteMessage: () => Promise<void>;
81
82
  primeCard: (delayMs: number) => void;
82
83
  flush: () => Promise<void>;
@@ -93,7 +94,6 @@ export interface ChannelContext {
93
94
  * something to say routes it through `task_step_end`'s `notify` — which the runtime delivers on
94
95
  * the real context after the step ends.
95
96
  *
96
- * Card/typing/lifecycle calls pass through: they affect no transcript and keep the transport's
97
- * own state machine consistent.
97
+ * Lifecycle calls pass through for cleanup; card priming is a visible write and is muted too.
98
98
  */
99
99
  export declare function muteChannelContext(ctx: ChannelContext): ChannelContext;
@@ -25,8 +25,7 @@
25
25
  * something to say routes it through `task_step_end`'s `notify` — which the runtime delivers on
26
26
  * the real context after the step ends.
27
27
  *
28
- * Card/typing/lifecycle calls pass through: they affect no transcript and keep the transport's
29
- * own state machine consistent.
28
+ * Lifecycle calls pass through for cleanup; card priming is a visible write and is muted too.
30
29
  */
31
30
  export function muteChannelContext(ctx) {
32
31
  return {
@@ -35,5 +34,6 @@ export function muteChannelContext(ctx) {
35
34
  respondPlain: async () => true,
36
35
  replaceMessage: async () => undefined,
37
36
  respondInThread: async () => undefined,
37
+ primeCard: () => undefined,
38
38
  };
39
39
  }