@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
package/README.en.md CHANGED
@@ -18,11 +18,11 @@ What you see is one assistant, but behind it can be a well-divided AI engineerin
18
18
 
19
19
  Pipiclaw supports two kinds of delegation at once: built-in sub-agents do lightweight work in-process such as retrieval and log triage; external agents launch real Claude Code, Codex CLI, or any script to handle heavy tasks that need long runs, many files, and repeated self-testing.
20
20
 
21
- In DingTalk daemon mode, external tasks keep running in the background after dispatch and automatically wake the originating channel on completion. You can use `/subagents` at any time to check run status, the actual command, and outputs, use `/subagents cancel` to terminate directly, and let the main agent keep asking follow-up questions on a finished Claude Code / Codex session. The repo ships explorer, builder, reviewer, verifier, and git-committer role templates that are ready to adapt.
21
+ In DingTalk daemon mode, external tasks keep running in the background after dispatch and automatically wake the originating channel on completion. You can use `/subagents` at any time to check run status, the actual command, and outputs, use `/subagents cancel` to terminate directly, and let the main agent keep asking follow-up questions on a finished Claude Code / Codex session. The repo ships recommended capability-and-cost entries plus earlier job-style role templates for reference.
22
22
 
23
23
  ### Work does not end when a conversation ends
24
24
 
25
- Every session has its own current state, long-term memory, and history summary. The task ledger persists goals, done criteria, progress, next steps, and verification records to Markdown files; the built-in task driver resumes work at the right time — continuing when there is progress, backing off when stalled, and stopping and telling you when a boundary is crossed.
25
+ Every session has its own current state, long-term memory, and history summary. The task ledger persists goals, done criteria, progress, next steps, and verification records to Markdown files; the built-in task driver resumes work from waiting tickets and schedules, and stops with a notice when a budget, idle-loop, or repeated-expiry boundary is reached.
26
26
 
27
27
  ### Natively at home in DingTalk
28
28
 
@@ -50,7 +50,7 @@ Pipiclaw today targets individuals and small teams, self-hosted, single-instance
50
50
 
51
51
  ## Quick start
52
52
 
53
- Below are three progressive paths: verify a model in the terminal first, then connect DingTalk, then enable external agents. If you already have a clear goal, jump straight to the relevant part.
53
+ The steps below cover local verification, DingTalk setup, and external-agent configuration in order. If you already have a clear goal, jump straight to the relevant part.
54
54
 
55
55
  ### 1. Install and confirm the CLI
56
56
 
@@ -95,10 +95,10 @@ pipiclaw tui
95
95
  It can also be used for scripted one-shot requests:
96
96
 
97
97
  ```bash
98
- pipiclaw tui --print "Review the current project and give me the three highest-priority risks"
98
+ pipiclaw tui --print "Reply with only: Pipiclaw model call succeeded"
99
99
  ```
100
100
 
101
- To connect an enterprise gateway, a local model, or set a default model, see [Configuration reference](https://github.com/oyasmi/pipiclaw/blob/main/docs/configuration.md).
101
+ Only an actual model reply proves that the request path works; `pipiclaw tui --help` and `/model` only prove that the CLI or model catalog is visible. Before real work, use `/project` to confirm the current project directory. To connect an enterprise gateway, a local model, or set a default model, see [Configuration reference](https://github.com/oyasmi/pipiclaw/blob/main/docs/configuration.md).
102
102
 
103
103
  ### 3. Connect DingTalk
104
104
 
@@ -134,7 +134,7 @@ Start the daemon:
134
134
  pipiclaw
135
135
  ```
136
136
 
137
- In DingTalk, send `/model` first to confirm the model is available, then send:
137
+ In DingTalk, send `/model` to inspect the model reference, then send a normal message to verify a real call:
138
138
 
139
139
  ```text
140
140
  Please introduce yourself and explain what you can do right now
@@ -144,12 +144,12 @@ If the first message does not succeed, start from [Deployment and operations](ht
144
144
 
145
145
  ### 4. Enable external agent delegation
146
146
 
147
- First install and log in to the target CLI under the same account that runs Pipiclaw, then copy the roles you need. The example below enables both a Claude Code builder and a Codex reviewer:
147
+ First install and log in to the target CLI under the same account that runs Pipiclaw, then copy the capability entries you need. This enables the main Claude Code and Codex entries:
148
148
 
149
149
  ```bash
150
150
  mkdir -p ~/.pipiclaw/workspace/sub-agents
151
151
  PIPICLAW_PACKAGE_DIR="$(npm root -g)/@oyasmi/pipiclaw"
152
- cp "$PIPICLAW_PACKAGE_DIR"/examples/sub-agents/{builder,reviewer}.md \
152
+ cp "$PIPICLAW_PACKAGE_DIR"/examples/sub-agents/agents/{claude-main,codex-main}.md \
153
153
  ~/.pipiclaw/workspace/sub-agents/
154
154
  ```
155
155
 
@@ -159,10 +159,10 @@ Role file changes are rediscovered at runtime. Send:
159
159
  /subagents roles
160
160
  ```
161
161
 
162
- Once the roles show as available, you can describe a goal and name a role directly:
162
+ Once the entries show as available, describe the goal and acceptance criteria and let the main agent select an executor:
163
163
 
164
164
  ```text
165
- Please hand this cross-module implementation to the builder, and once it's done have the reviewer check it independently.
165
+ Please hand this cross-module implementation to a suitable executor, then independently check the final changes.
166
166
  ```
167
167
 
168
168
  Common control entry points:
@@ -175,7 +175,7 @@ Common control entry points:
175
175
  /subagents roles [name] # view the role directory and a single role's config
176
176
  ```
177
177
 
178
- External agents do not go through Pipiclaw's command and path guards. Before using the example roles, read the authorization, security boundary, and sandbox notes in the [Agent delegation guide](https://github.com/oyasmi/pipiclaw/blob/main/docs/sub-agents.md).
178
+ External agents do not go through Pipiclaw's command and path guards. The recommended entries above use permissive CLI flags; before using them, read the authorization, security boundary, and sandbox notes in the [Agent delegation guide](https://github.com/oyasmi/pipiclaw/blob/main/docs/sub-agents.md).
179
179
 
180
180
  Long-running external delegations should run in the DingTalk daemon; the TUI currently does not provide completion notifications for external runs or re-adoption after exit.
181
181
 
@@ -243,7 +243,7 @@ npm run build
243
243
  npm run check # lint + typecheck + deadcode + test
244
244
  ```
245
245
 
246
- Minimal verification: `npm run typecheck` and `npm run test`. Real-model E2E uses `npm run test:e2e` and is not part of the daily unit tests.
246
+ Minimal verification: `npm run typecheck` and `npm run test`. `npm run test:e2e` is deterministic, offline, and credential-free; the small real-model smoke suite uses `npm run test:e2e:live`.
247
247
 
248
248
  ## License
249
249
 
package/README.md CHANGED
@@ -18,11 +18,11 @@ Pipiclaw 是一个面向个人和团队的 AI coding assistant runtime。它让
18
18
 
19
19
  Pipiclaw 同时支持两类委派:内置子智能体在进程内完成检索、日志筛查等轻量工作;外部智能体则启动真实的 Claude Code、Codex CLI 或任意脚本,处理需要长时间运行、跨多个文件和反复自测的重型任务。
20
20
 
21
- 在钉钉常驻模式中,外部任务派发后在后台继续执行,完成时自动唤醒原频道。你可以随时用 `/subagents` 查看运行状态、实际命令和产出,用 `/subagents cancel` 直接终止,也可以让主智能体在已结束的 Claude Code / Codex 会话上继续追问。仓库附带 explorer、builder、reviewer、verifier、git-committer 等可直接改造的角色模板。
21
+ 在钉钉常驻模式中,外部任务派发后在后台继续执行,完成时自动唤醒原频道。你可以随时用 `/subagents` 查看运行状态、实际命令和产出,用 `/subagents cancel` 直接终止,也可以让主智能体在已结束的 Claude Code / Codex 会话上继续追问。仓库附带按能力与成本组织的推荐条目,以及可参考的早期岗位角色模板。
22
22
 
23
23
  ### 工作不会随着一次对话结束
24
24
 
25
- 每个会话都有独立的当前状态、长期记忆和历史摘要。任务台账把目标、完成标准、进度、下一步和验收记录持久化到 Markdown 文件;内建 task driver 会在合适的时间恢复工作,有进展就继续,停滞则退避,超过边界就停止并告诉你。
25
+ 每个会话都有独立的当前状态、长期记忆和历史摘要。任务台账把目标、完成标准、进度、下一步和验收记录持久化到 Markdown 文件;内建 task driver 根据等待票和周期调度恢复工作,预算耗尽、空转或连续无法兑现等待时会停止并告诉你。
26
26
 
27
27
  ### 原生工作在钉钉里
28
28
 
@@ -50,7 +50,7 @@ Pipiclaw 当前定位是个人与小团队、自托管、单实例运行。它
50
50
 
51
51
  ## 快速开始
52
52
 
53
- 下面提供三条递进路径:先在终端验证模型,再接入钉钉,最后启用外部智能体。已经有明确目标时可以直接跳到对应部分。
53
+ 下面按顺序完成本地验证、钉钉接入和外部智能体配置;已经有明确目标时可以直接跳到对应部分。
54
54
 
55
55
  ### 1. 安装并确认 CLI
56
56
 
@@ -95,10 +95,10 @@ pipiclaw tui
95
95
  也可以用于脚本化的一次性请求:
96
96
 
97
97
  ```bash
98
- pipiclaw tui --print "检查当前项目并给出三个最高优先级风险"
98
+ pipiclaw tui --print "只回复:Pipiclaw 模型调用成功"
99
99
  ```
100
100
 
101
- 如需接入企业网关、本地模型或指定默认模型,请看[配置速查](https://github.com/oyasmi/pipiclaw/blob/main/docs/configuration.md)。
101
+ 看到模型实际回复才表示调用链路已经跑通;`pipiclaw tui --help` 或 `/model` 只能证明 CLI 或模型目录可见。正式工作前可用 `/project` 确认当前项目目录。如需接入企业网关、本地模型或指定默认模型,请看[配置速查](https://github.com/oyasmi/pipiclaw/blob/main/docs/configuration.md)。
102
102
 
103
103
  ### 3. 接入钉钉
104
104
 
@@ -134,7 +134,7 @@ pipiclaw tui --print "检查当前项目并给出三个最高优先级风险"
134
134
  pipiclaw
135
135
  ```
136
136
 
137
- 先在钉钉里发送 `/model`,确认模型可用,再发送:
137
+ 先在钉钉里发送 `/model` 检查模型引用,再发送一条普通消息验证真实调用:
138
138
 
139
139
  ```text
140
140
  请介绍一下你自己,并说明你现在能做什么
@@ -144,12 +144,12 @@ pipiclaw
144
144
 
145
145
  ### 4. 启用外部智能体委派
146
146
 
147
- 先在运行 Pipiclaw 的同一账号下安装并登录目标 CLI,然后复制需要的角色。下面的示例同时启用 Claude Code builder 和 Codex reviewer:
147
+ 先在运行 Pipiclaw 的同一账号下安装并登录目标 CLI,然后复制需要的能力条目。下面启用 Claude Code 与 Codex 的两个主力条目:
148
148
 
149
149
  ```bash
150
150
  mkdir -p ~/.pipiclaw/workspace/sub-agents
151
151
  PIPICLAW_PACKAGE_DIR="$(npm root -g)/@oyasmi/pipiclaw"
152
- cp "$PIPICLAW_PACKAGE_DIR"/examples/sub-agents/{builder,reviewer}.md \
152
+ cp "$PIPICLAW_PACKAGE_DIR"/examples/sub-agents/agents/{claude-main,codex-main}.md \
153
153
  ~/.pipiclaw/workspace/sub-agents/
154
154
  ```
155
155
 
@@ -159,10 +159,10 @@ cp "$PIPICLAW_PACKAGE_DIR"/examples/sub-agents/{builder,reviewer}.md \
159
159
  /subagents roles
160
160
  ```
161
161
 
162
- 确认角色显示为可用后,可以直接描述目标并指定角色:
162
+ 确认条目显示为可用后,直接描述目标和验收要求,由主智能体选择执行器:
163
163
 
164
164
  ```text
165
- 请把这个跨模块实现交给 builder 完成,完成后再让 reviewer 独立检查。
165
+ 请把这个跨模块实现交给合适的执行器,完成后独立检查最终改动。
166
166
  ```
167
167
 
168
168
  常用控制入口:
@@ -175,7 +175,7 @@ cp "$PIPICLAW_PACKAGE_DIR"/examples/sub-agents/{builder,reviewer}.md \
175
175
  /subagents roles [name] # 查看角色目录和单个角色配置
176
176
  ```
177
177
 
178
- 外部智能体不会经过 Pipiclaw 的命令和路径守卫。使用示例角色前,请阅读[智能体委派指南](https://github.com/oyasmi/pipiclaw/blob/main/docs/sub-agents.md)中的授权、安全边界和 sandbox 说明。
178
+ 外部智能体不会经过 Pipiclaw 的命令和路径守卫。上述推荐条目使用放开权限的 CLI 参数;使用前必须阅读[智能体委派指南](https://github.com/oyasmi/pipiclaw/blob/main/docs/sub-agents.md)中的授权、安全边界和 sandbox 说明。
179
179
 
180
180
  长时间外部委派应运行在钉钉 daemon 中;TUI 当前不提供外部 run 的完成通知和退出后的重新认领。
181
181
 
@@ -243,7 +243,7 @@ npm run build
243
243
  npm run check # lint + typecheck + deadcode + test
244
244
  ```
245
245
 
246
- 最小验证:`npm run typecheck` 和 `npm run test`。真实模型 E2E 使用 `npm run test:e2e`,不包含在日常单元测试中。
246
+ 最小验证:`npm run typecheck` 和 `npm run test`。`npm run test:e2e` 是离线、无凭据的确定性全栈测试;少量真实模型 smoke 使用 `npm run test:e2e:live`。
247
247
 
248
248
  ## 许可证
249
249
 
@@ -1,6 +1,3 @@
1
- import { Agent, type ThinkingLevel } from "@earendil-works/pi-agent-core";
2
- import type { Api, Model } from "@earendil-works/pi-ai";
3
- import { AgentSession, SettingsManager as SDKSettingsManager, SessionManager } from "@earendil-works/pi-coding-agent";
4
1
  import type { ChannelContext } from "../channel/channel-context.js";
5
2
  import { type InboundImage } from "../channel/channel-event.js";
6
3
  import type { ChannelStore } from "../channel/store.js";
@@ -10,13 +7,10 @@ import type { UsageTotals } from "../shared/types.js";
10
7
  import { type SubAgentDiscoveryResult } from "../subagents/discovery.js";
11
8
  import type { RunnerDeps, RunnerFactoryPaths } from "./runner-factory.js";
12
9
  import { type AgentRunner, type RunnerStatusSnapshot, type TurnStatus } from "./types.js";
13
- /** Apply the pi 0.83 source-model thinking compatibility branch to one real AgentSession. */
14
- export declare function setModelWithThinkingPreservation(session: AgentSession, manager: SDKSettingsManager, model: Model<Api>): Promise<void>;
15
- export declare function setThinkingLevelWithConditionalPersist(session: AgentSession, level: ThinkingLevel): void;
16
- export declare function cycleThinkingLevelWithConditionalPersist(session: AgentSession): ThinkingLevel | undefined;
17
- export declare function initializeThinkingLevelCompat(agent: Agent, model: Model<Api>, sessionManager: SessionManager, configuredDefault: ThinkingLevel | undefined): ThinkingLevel;
18
10
  export declare class ChannelRunner implements AgentRunner {
19
11
  private readonly executor;
12
+ private readonly jobManager;
13
+ private readonly runManager;
20
14
  private readonly fileStore;
21
15
  private readonly channelId;
22
16
  private readonly channelDir;
@@ -38,8 +32,8 @@ export declare class ChannelRunner implements AgentRunner {
38
32
  private session;
39
33
  /** Settings manager owned by the currently bound AgentSession. */
40
34
  private sessionSettingsManager;
41
- private agent;
42
- private sessionManager;
35
+ private get agent();
36
+ private get sessionManager();
43
37
  private readonly settingsManager;
44
38
  private modelRuntime;
45
39
  private modelRegistry;
@@ -296,14 +290,6 @@ export declare class ChannelRunner implements AgentRunner {
296
290
  } | undefined;
297
291
  private buildRuntimeTools;
298
292
  private rebuildSessionTools;
299
- /**
300
- * Overwrite the SDK session's `baseToolsOverride` map so a resource reload swaps in
301
- * freshly-built tools. The SDK exposes no public setter for this, so we reach into the
302
- * private `_baseToolsOverride` field. This is the single, isolated point of that coupling:
303
- * if a future SDK renames or removes the field, the guard below warns loudly instead of
304
- * silently leaving stale tools in place. Replace with a public setter once upstream adds one.
305
- */
306
- private setSessionBaseToolsOverride;
307
293
  private subscribeToSessionEvents;
308
294
  /** Gated by the same master autonomy switch as the task_* tools and the TaskDriver. */
309
295
  private buildTaskDigestForTurn;
@@ -1,6 +1,6 @@
1
1
  import { Agent } from "@earendil-works/pi-agent-core";
2
- import { clampThinkingLevel, streamSimple } from "@earendil-works/pi-ai/compat";
3
- import { AgentSession, AgentSessionRuntime, convertToLlm, DefaultResourceLoader, SettingsManager as SDKSettingsManager, SessionManager, } from "@earendil-works/pi-coding-agent";
2
+ import { streamSimple } from "@earendil-works/pi-ai/compat";
3
+ import { AgentSession, AgentSessionRuntime, convertToLlm, DefaultResourceLoader, SessionManager, } from "@earendil-works/pi-coding-agent";
4
4
  import { mkdir, readFile, writeFile } from "fs/promises";
5
5
  import { dirname, join, resolve } from "path";
6
6
  import { commitActiveSessionRef, resolveActiveSessionFile } from "../channel/active-session-store.js";
@@ -28,6 +28,7 @@ import { errorMessage } from "../shared/text-utils.js";
28
28
  import { isRecord } from "../shared/type-guards.js";
29
29
  import { withTimeout } from "../shared/with-timeout.js";
30
30
  import { discoverSubAgents } from "../subagents/discovery.js";
31
+ import { SubAgentRunManager } from "../subagents/runs.js";
31
32
  import { TASK_SESSIONS_DIRNAME, taskSessionPath } from "../tasks/session-path.js";
32
33
  import { loadToolsConfigWithDiagnostics } from "../tools/config.js";
33
34
  import { createPipiclawTools } from "../tools/index.js";
@@ -35,6 +36,7 @@ import { formatSize } from "../tools/truncate.js";
35
36
  import { getUsageLedger } from "../usage/ledger.js";
36
37
  import { createCommandExtension } from "./command-extension.js";
37
38
  import { estimateIncomingMessageTokens, getPreventiveCompactionDecision } from "./context-budget.js";
39
+ import { ChannelJobManager } from "./job-manager.js";
38
40
  import { PRIMARY_COOLDOWN_MS, runPromptWithFallback, shouldRestorePrimary, } from "./model-fallback.js";
39
41
  import { clipUserInput, formatProgressEntry } from "./progress-formatter.js";
40
42
  import { buildPipiclawSystemPrompt } from "./prompt/builder.js";
@@ -42,6 +44,7 @@ import { createPromptBoundaryExtension } from "./prompt/extension.js";
42
44
  import { buildPromptManifest, measureToolSchemas, renderContextReport, TOOL_SCHEMA_TARGET_UNITS, toolSchemaBudgetWarning, } from "./prompt/manifest.js";
43
45
  import { loadWorkspacePromptResources } from "./prompt/resources.js";
44
46
  import { createRunQueue } from "./run-queue.js";
47
+ import { asSdkSettingsManager, cycleThinkingLevelWithConditionalPersist, DEFAULT_MAIN_THINKING_LEVEL, initializeThinkingLevelCompat, setModelWithThinkingPreservation, setSessionBaseToolsOverride, setThinkingLevelWithConditionalPersist, } from "./session-adapter.js";
45
48
  import { handleSessionEvent } from "./session-events.js";
46
49
  import { SessionResourceGate } from "./session-resource-gate.js";
47
50
  import { assembleTurnPrompt } from "./turn-prompt.js";
@@ -59,66 +62,6 @@ function isFinalOutcome(outcome) {
59
62
  function getFinalOutcomeText(outcome) {
60
63
  return isFinalOutcome(outcome) ? outcome.text : null;
61
64
  }
62
- function asSdkSettingsManager(manager) {
63
- // The upstream session needs its broad interactive SettingsManager surface, while
64
- // Pipiclaw deliberately owns a small runtime-specific settings contract. Build a
65
- // real upstream manager from that contract instead of making PipiclawSettingsManager
66
- // pretend to implement dozens of unrelated no-op UI preferences.
67
- return SDKSettingsManager.inMemory({
68
- defaultProvider: manager.getDefaultProvider(),
69
- defaultModel: manager.getDefaultModel(),
70
- defaultThinkingLevel: manager.getDefaultThinkingLevel() ?? DEFAULT_MAIN_THINKING_LEVEL,
71
- compaction: manager.getCompactionSettings(),
72
- retry: manager.getRetrySettings(),
73
- });
74
- }
75
- const DEFAULT_MAIN_THINKING_LEVEL = "medium";
76
- /** Apply the pi 0.83 source-model thinking compatibility branch to one real AgentSession. */
77
- export async function setModelWithThinkingPreservation(session, manager, model) {
78
- const source = session.model;
79
- if (!source?.reasoning) {
80
- await session.setModel(model);
81
- return;
82
- }
83
- const previousDefault = manager.getDefaultThinkingLevel();
84
- manager.setDefaultThinkingLevel(session.thinkingLevel);
85
- try {
86
- await session.setModel(model);
87
- }
88
- finally {
89
- manager.setDefaultThinkingLevel(previousDefault ?? DEFAULT_MAIN_THINKING_LEVEL);
90
- }
91
- }
92
- export function setThinkingLevelWithConditionalPersist(session, level) {
93
- const before = session.thinkingLevel;
94
- session.setThinkingLevel(level);
95
- const effective = session.thinkingLevel;
96
- if (effective === before)
97
- return;
98
- if (!session.model?.reasoning && effective === "off")
99
- return;
100
- session.setThinkingLevel(effective, { persist: true });
101
- }
102
- export function cycleThinkingLevelWithConditionalPersist(session) {
103
- const before = session.thinkingLevel;
104
- const next = session.cycleThinkingLevel();
105
- const effective = session.thinkingLevel;
106
- if (next && effective !== before && (session.model?.reasoning || effective !== "off")) {
107
- session.setThinkingLevel(effective, { persist: true });
108
- }
109
- return next;
110
- }
111
- export function initializeThinkingLevelCompat(agent, model, sessionManager, configuredDefault) {
112
- const branch = sessionManager.getBranch();
113
- const hasThinkingEntry = branch.some((entry) => entry.type === "thinking_level_change");
114
- const historical = sessionManager.buildSessionContext().thinkingLevel;
115
- const requested = hasThinkingEntry ? historical : (configuredDefault ?? DEFAULT_MAIN_THINKING_LEVEL);
116
- const effective = clampThinkingLevel(model, requested);
117
- agent.state.thinkingLevel = effective;
118
- if (!hasThinkingEntry)
119
- sessionManager.appendThinkingLevelChange(effective);
120
- return effective;
121
- }
122
65
  /**
123
66
  * Ceilings for the two awaited steps of a session-resource reload. Both reach
124
67
  * the network (model/auth re-resolution; the SDK session's own reload) and
@@ -143,6 +86,12 @@ function isTaskSessionPath(sessionFile) {
143
86
  return sessionFile?.replace(/\\/g, "/").includes(`/${TASK_SESSIONS_DIRNAME}/`) === true;
144
87
  }
145
88
  export class ChannelRunner {
89
+ get agent() {
90
+ return this.session.agent;
91
+ }
92
+ get sessionManager() {
93
+ return this.session.sessionManager;
94
+ }
146
95
  constructor(channelId, channelDir, paths, deps) {
147
96
  this.ledger = getUsageLedger();
148
97
  /**
@@ -174,6 +123,8 @@ export class ChannelRunner {
174
123
  this.onSessionEvent = paths.onSessionEvent;
175
124
  this.mediaSender = paths.mediaSender;
176
125
  this.executor = deps.executor;
126
+ this.jobManager = paths.jobManager ?? new ChannelJobManager(channelId, deps.executor);
127
+ this.runManager = paths.runManager ?? new SubAgentRunManager(channelId, {});
177
128
  this.fileStore = deps.fileStore;
178
129
  this.loadSecurityConfig = deps.loadSecurityConfig;
179
130
  this.workspaceDir = resolve(dirname(channelDir));
@@ -197,14 +148,14 @@ export class ChannelRunner {
197
148
  // (or the context.jsonl default, for a channel that has never run a topology op) names
198
149
  // (spec 043, D1).
199
150
  const activeSessionFile = resolveActiveSessionFile(channelDir);
200
- this.sessionManager = SessionManager.open(join(channelDir, activeSessionFile), channelDir);
151
+ const sessionManager = SessionManager.open(join(channelDir, activeSessionFile), channelDir);
201
152
  // Per-runner recovery barrier (spec 043, D10 point 2): repairs must run against this exact
202
153
  // SessionManager instance, before anything else touches it — a second `open()` of the same
203
154
  // file would mutate a branch this instance never sees, silently desyncing the two. The
204
155
  // daemon's own startup scan (bootstrap.ts) covers channels with no live runner yet; this
205
156
  // covers lazy channels, the TUI, and a channel whose file was fixed by hand after the scan
206
157
  // already ran and reported it blocked.
207
- const recoveryOutcome = recoverInterruptedTurn(this.sessionManager, {
158
+ const recoveryOutcome = recoverInterruptedTurn(sessionManager, {
208
159
  api: defaultModel.api,
209
160
  provider: defaultModel.provider,
210
161
  model: defaultModel.id,
@@ -222,22 +173,7 @@ export class ChannelRunner {
222
173
  appHomeDir: this.appHomeDir,
223
174
  onError: (channelId, error) => log.logWarning(`[${channelId}] Failed to record memory maintenance state`, errorMessage(error)),
224
175
  });
225
- // The real model/auth runtime is built asynchronously in initializeSession
226
- // (ModelRuntime.create is async). Until then the agent runs on a placeholder
227
- // model; initializeSession corrects it before any turn (via sessionReady).
228
176
  this.activeModel = defaultModel;
229
- const initialTools = this.buildRuntimeTools();
230
- this.agent = new Agent({
231
- initialState: {
232
- systemPrompt: "",
233
- model: this.activeModel,
234
- thinkingLevel: DEFAULT_MAIN_THINKING_LEVEL,
235
- tools: initialTools,
236
- },
237
- convertToLlm,
238
- getApiKey: async () => getApiKeyForModel(this.modelRegistry, this.activeModel),
239
- streamFn: streamSimple,
240
- });
241
177
  this.memoryLifecycle = new MemoryLifecycle({
242
178
  channelId: this.channelId,
243
179
  channelDir: this.channelDir,
@@ -252,7 +188,7 @@ export class ChannelRunner {
252
188
  this.sessionResourceGate = new SessionResourceGate(async () => {
253
189
  await this.reloadSessionResources();
254
190
  });
255
- this.sessionReady = this.initializeSession();
191
+ this.sessionReady = this.initializeSession(sessionManager);
256
192
  }
257
193
  // === Public API ===
258
194
  beginTurn(taskText) {
@@ -526,7 +462,7 @@ export class ChannelRunner {
526
462
  else if (isSilentOutcome(finalOutcome)) {
527
463
  try {
528
464
  await ctx.deleteMessage();
529
- log.logInfo("Silent response - deleted message");
465
+ log.logInfo("Silent response - ended progress delivery");
530
466
  }
531
467
  catch (err) {
532
468
  const errMsg = errorMessage(err);
@@ -774,8 +710,8 @@ export class ChannelRunner {
774
710
  const build = this.lastPromptBuild ?? this.buildSystemPrompt();
775
711
  return renderContextReport({
776
712
  build,
777
- finalPrompt: this.lastFinalPrompt,
778
713
  skills: this.currentSkills.skills.map((skill) => ({ name: skill.name, description: skill.description })),
714
+ finalPrompt: this.lastFinalPrompt,
779
715
  toolNames: this.currentTools.map((tool) => tool.name),
780
716
  toolSchemas: measureToolSchemas(this.currentTools),
781
717
  soul: this.lastWorkspaceResources?.soul,
@@ -1056,7 +992,7 @@ export class ChannelRunner {
1056
992
  }
1057
993
  return match;
1058
994
  }
1059
- async initializeSession() {
995
+ async initializeSession(sessionManager) {
1060
996
  // Build the canonical async model/auth runtime and its synchronous read shell.
1061
997
  this.modelRuntime = await createModelRuntime({
1062
998
  authConfigPath: this.authConfigPath,
@@ -1065,23 +1001,11 @@ export class ChannelRunner {
1065
1001
  this.modelRegistry = wrapModelRegistry(this.modelRuntime);
1066
1002
  // Resolve model: prefer saved global default, fall back to first available model.
1067
1003
  this.activeModel = resolveInitialModel(this.modelRegistry, this.settingsManager);
1068
- this.agent.state.model = this.activeModel; // correct the placeholder default
1069
- this.initializeThinkingLevel(this.agent, this.activeModel, this.sessionManager);
1070
1004
  log.logInfo(`Using model: ${this.activeModel.provider}/${this.activeModel.id} (${this.activeModel.name})`);
1071
1005
  this.subAgentDiscovery = await this.refreshSubAgentDiscovery();
1072
- const initialResourceLoader = this.createResourceLoader();
1073
- const baseToolsOverride = Object.fromEntries(this.currentTools.map((tool) => [tool.name, tool]));
1074
- this.sessionSettingsManager = asSdkSettingsManager(this.settingsManager);
1075
- this.session = new AgentSession({
1076
- agent: this.agent,
1077
- sessionManager: this.sessionManager,
1078
- settingsManager: this.sessionSettingsManager,
1079
- cwd: this.projectScope.projectRoot,
1080
- modelRuntime: this.modelRuntime,
1081
- resourceLoader: initialResourceLoader,
1082
- baseToolsOverride,
1083
- });
1084
- this.sessionRuntime = new AgentSessionRuntime(this.session, this.createAgentSessionServices(initialResourceLoader), async ({ sessionManager, sessionStartEvent }) => {
1006
+ const initial = await this.createSessionRuntime(sessionManager);
1007
+ this.session = initial.session;
1008
+ this.sessionRuntime = new AgentSessionRuntime(this.session, this.createAgentSessionServices(initial.resourceLoader), async ({ sessionManager, sessionStartEvent }) => {
1085
1009
  // `/new`, fork, and switch already wrote the target session's durable header by
1086
1010
  // this point (the SDK does it synchronously before invoking this callback); commit
1087
1011
  // the pointer before we rebuild and rebind to it, so a crash between "SDK created
@@ -1103,14 +1027,11 @@ export class ChannelRunner {
1103
1027
  });
1104
1028
  this.sessionRuntime.setRebindSession(async (session) => {
1105
1029
  this.session = session;
1106
- this.agent = session.agent;
1107
- this.sessionManager = session.sessionManager;
1108
1030
  await this.bindSessionExtensions();
1109
1031
  this.subscribeToSessionEvents();
1110
1032
  });
1111
1033
  // Subscribe to session events
1112
1034
  this.subscribeToSessionEvents();
1113
- await this.reloadSessionResources();
1114
1035
  await this.bindSessionExtensions();
1115
1036
  // A restart resumes an existing transcript: if that session was already handed its
1116
1037
  // bootstrap before the daemon went down, the first turn after recovery must not inject a
@@ -1244,9 +1165,6 @@ export class ChannelRunner {
1244
1165
  const resources = loadWorkspacePromptResources(this.workspaceDir);
1245
1166
  this.lastWorkspaceResources = resources;
1246
1167
  const build = buildPipiclawSystemPrompt({
1247
- mode: "normal",
1248
- cwd: this.projectScope.projectRoot,
1249
- workspaceDir: this.workspaceDir,
1250
1168
  tools: this.currentTools.map((tool) => ({
1251
1169
  name: tool.name,
1252
1170
  description: tool.description,
@@ -1263,7 +1181,6 @@ export class ChannelRunner {
1263
1181
  mutates: agent.mutates,
1264
1182
  unavailable: agent.unavailable,
1265
1183
  })),
1266
- skills: this.currentSkills.skills.map((skill) => ({ name: skill.name, description: skill.description })),
1267
1184
  });
1268
1185
  for (const diagnostic of [...resources.diagnostics, ...build.diagnostics]) {
1269
1186
  if (diagnostic.level === "info")
@@ -1403,7 +1320,7 @@ export class ChannelRunner {
1403
1320
  sessionStartEvent,
1404
1321
  });
1405
1322
  this.sessionSettingsManager = sessionSettingsManager;
1406
- return { agent, session, resourceLoader };
1323
+ return { session, resourceLoader };
1407
1324
  }
1408
1325
  /**
1409
1326
  * Bind this runner to a task cycle's own session (spec 051, D3/INV-5).
@@ -1465,6 +1382,8 @@ export class ChannelRunner {
1465
1382
  this.reportConfigDiagnostics([...securityLoad.diagnostics, ...toolsLoad.diagnostics]);
1466
1383
  this.tasksEnabled = toolsLoad.config.tools.tasks.enabled;
1467
1384
  const tools = createPipiclawTools({
1385
+ jobManager: this.jobManager,
1386
+ runManager: this.runManager,
1468
1387
  executor: this.executor,
1469
1388
  fileStore: this.fileStore,
1470
1389
  getCurrentModel: () => this.activeModel,
@@ -1494,24 +1413,10 @@ export class ChannelRunner {
1494
1413
  }
1495
1414
  rebuildSessionTools() {
1496
1415
  const tools = this.buildRuntimeTools();
1497
- this.setSessionBaseToolsOverride(tools);
1416
+ setSessionBaseToolsOverride(this.session, tools, this.channelId);
1498
1417
  this.agent.state.tools = tools;
1499
1418
  this.session.setActiveToolsByName(tools.map((tool) => tool.name));
1500
1419
  }
1501
- /**
1502
- * Overwrite the SDK session's `baseToolsOverride` map so a resource reload swaps in
1503
- * freshly-built tools. The SDK exposes no public setter for this, so we reach into the
1504
- * private `_baseToolsOverride` field. This is the single, isolated point of that coupling:
1505
- * if a future SDK renames or removes the field, the guard below warns loudly instead of
1506
- * silently leaving stale tools in place. Replace with a public setter once upstream adds one.
1507
- */
1508
- setSessionBaseToolsOverride(tools) {
1509
- const target = this.session;
1510
- if (!("_baseToolsOverride" in target)) {
1511
- log.logWarning(`[${this.channelId}] AgentSession no longer exposes _baseToolsOverride; tool reloads may use stale tools (SDK change?)`);
1512
- }
1513
- target._baseToolsOverride = Object.fromEntries(tools.map((tool) => [tool.name, tool]));
1514
- }
1515
1420
  // === Session event subscription ===
1516
1421
  subscribeToSessionEvents() {
1517
1422
  this.sessionUnsubscribe?.();
@@ -1,4 +1,4 @@
1
- import { estimateTokens } from "../shared/token-estimate.js";
1
+ import { estimateTokens } from "../shared/format.js";
2
2
  export const PREVENTIVE_COMPACTION_THRESHOLD_RATIO = 0.75;
3
3
  /**
4
4
  * Rough per-image token cost (spec 049), used only to keep the preventive-compaction projection
@@ -115,6 +115,7 @@ export declare class ChannelJobManager {
115
115
  private sweepTimer?;
116
116
  private garbageCollectionTimer?;
117
117
  private sweeping;
118
+ private stopped;
118
119
  private readonly options;
119
120
  private readonly sweepIntervalMs;
120
121
  private readonly fileStore;
@@ -161,6 +162,8 @@ export declare class ChannelJobManager {
161
162
  * so their slots free up even when the model never polls, and stops itself once nothing is running.
162
163
  */
163
164
  private ensureSweeper;
165
+ /** Stop observation at application shutdown; detached jobs keep running. */
166
+ stop(): void;
164
167
  private stopSweeper;
165
168
  private sweep;
166
169
  /**
@@ -261,21 +264,12 @@ interface JobRuntimeConfig {
261
264
  /** Sweep cadence override for the lazily-built channel managers (tests). */
262
265
  sweepIntervalMs?: number;
263
266
  }
264
- /**
265
- * Give background jobs their persistence root and their way to wake a channel. Called once from
266
- * bootstrap, before any turn runs; the tool layer builds managers lazily and picks this up.
267
- */
268
- export declare function configureJobRuntime(config: JobRuntimeConfig): void;
269
- /**
270
- * Human-readable lines naming this channel's currently running background jobs, for the `/project
271
- * set|reset` blocker check (spec 043, D4.3) — mirrors `channelJobTaskIds`'s "no manager means no
272
- * jobs" reasoning, so it needs no `Executor` either.
273
- */
274
- export declare function channelRunningJobLines(channelId: string): string[];
275
- export declare function getChannelJobManager(channelId: string, executor: Executor): ChannelJobManager;
276
- /**
277
- * Re-adopt every channel's persisted jobs at startup. Channels are discovered from the state
278
- * directory itself, so a job survives even when its channel has had no traffic since the restart.
279
- */
280
- export declare function restoreChannelJobs(executor: Executor): Promise<number>;
267
+ /** One application's jobs; the executor and configuration cannot change after construction. */
268
+ export declare function createJobRuntime(executor: Executor, options?: JobRuntimeConfig): {
269
+ get: (channelId: string) => ChannelJobManager;
270
+ runningLines: (channelId: string) => string[];
271
+ restore: () => Promise<number>;
272
+ stop: () => void;
273
+ };
274
+ export type JobRuntime = ReturnType<typeof createJobRuntime>;
281
275
  export {};