@oyasmi/pipiclaw 0.8.3 → 0.8.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.
- package/README.md +2 -1
- package/dist/agent/channel-runner.d.ts +45 -3
- package/dist/agent/channel-runner.js +200 -77
- package/dist/agent/commands.d.ts +2 -2
- package/dist/agent/commands.js +10 -1
- package/dist/agent/maintenance-context.d.ts +23 -0
- package/dist/agent/maintenance-context.js +72 -0
- package/dist/agent/prompt/builder.d.ts +32 -0
- package/dist/agent/prompt/builder.js +252 -0
- package/dist/agent/prompt/extension.d.ts +22 -0
- package/dist/agent/prompt/extension.js +24 -0
- package/dist/agent/prompt/manifest.d.ts +51 -0
- package/dist/agent/prompt/manifest.js +84 -0
- package/dist/agent/prompt/resources.d.ts +18 -0
- package/dist/agent/prompt/resources.js +61 -0
- package/dist/agent/prompt/sections.d.ts +39 -0
- package/dist/agent/prompt/sections.js +267 -0
- package/dist/agent/prompt/types.d.ts +110 -0
- package/dist/agent/prompt/types.js +11 -0
- package/dist/agent/status-render.d.ts +3 -7
- package/dist/agent/status-render.js +5 -5
- package/dist/agent/types.d.ts +33 -0
- package/dist/agent/workspace-resources.d.ts +25 -13
- package/dist/agent/workspace-resources.js +28 -41
- package/dist/index.d.ts +7 -2
- package/dist/index.js +6 -2
- package/dist/memory/transcript.js +7 -6
- package/dist/models/utils.d.ts +3 -1
- package/dist/models/utils.js +8 -0
- package/dist/playbooks/catalog.d.ts +22 -1
- package/dist/playbooks/catalog.js +57 -4
- package/dist/playbooks/event-scheduling.md +2 -0
- package/dist/playbooks/memory-and-learning.md +2 -0
- package/dist/playbooks/runtime-orientation.md +1 -0
- package/dist/playbooks/task-closeout.md +3 -1
- package/dist/playbooks/task-delegation.md +3 -1
- package/dist/playbooks/task-driving.md +2 -0
- package/dist/playbooks/task-planning.md +2 -0
- package/dist/playbooks/task-recurring.md +2 -0
- package/dist/playbooks/task-repair.md +3 -1
- package/dist/runtime/bootstrap.js +77 -93
- package/dist/runtime/channel-queue.d.ts +17 -0
- package/dist/runtime/channel-queue.js +50 -0
- package/dist/runtime/dingtalk.d.ts +1 -0
- package/dist/runtime/dingtalk.js +6 -42
- package/dist/runtime/task-driver.d.ts +2 -0
- package/dist/runtime/task-driver.js +3 -26
- package/dist/runtime/workspace-templates.d.ts +11 -0
- package/dist/runtime/workspace-templates.js +51 -0
- package/dist/settings.d.ts +0 -3
- package/dist/settings.js +0 -3
- package/dist/tools/config.d.ts +6 -22
- package/dist/tools/config.js +0 -58
- package/dist/tools/index.js +1 -4
- package/dist/tools/registry.d.ts +3 -3
- package/dist/tools/registry.js +4 -6
- package/dist/tui/commands.d.ts +1 -0
- package/dist/tui/commands.js +2 -0
- package/dist/tui/turn-controller.d.ts +1 -3
- package/dist/tui/turn-controller.js +17 -18
- package/package.json +1 -1
- package/dist/agent/prompt-builder.d.ts +0 -12
- package/dist/agent/prompt-builder.js +0 -71
package/README.md
CHANGED
|
@@ -217,6 +217,7 @@ pipiclaw
|
|
|
217
217
|
| `/tasks [show\|archive\|approve\|pause\|resume\|run\|stats\|doctor]` | 查看与治理任务台账,`approve` 是外部副作用的唯一授权入口 |
|
|
218
218
|
| `/status` | 运行时状态:执行状态、当前模型、上下文用量、运行时长、版本 |
|
|
219
219
|
| `/usage [7d\|month]` | 本通道与全局的 LLM 成本,按类型和 Top 模型拆分 |
|
|
220
|
+
| `/context [detail]` | 当前发给模型的上下文构成:system prompt 各 section 体量与 fingerprint、工具 schema 开销、上一轮动态上下文 |
|
|
220
221
|
| `/new` | 开启新会话 |
|
|
221
222
|
| `/compact [instructions]` | 手动压缩当前会话上下文 |
|
|
222
223
|
| `/session` | 当前会话状态、消息统计、token 使用量 |
|
|
@@ -224,7 +225,7 @@ pipiclaw
|
|
|
224
225
|
|
|
225
226
|
说明:
|
|
226
227
|
|
|
227
|
-
-
|
|
228
|
+
- 前九条由传输层直接处理,**忙碌时也可用**(`/context` 是只读统计,零 LLM 成本);后四条会话命令仅空闲时可用(忙碌时会收到提示)。
|
|
228
229
|
- 忙碌时的普通消息默认等价于 `/steer`,可通过 `channel.json` 的 `busyMessageDefault` 改为排队(`followUp`)。
|
|
229
230
|
- 未知的斜杠命令会被直接拒绝并提示 `/help`,不会作为普通消息发给模型(避免 `/modle` 这类笔误变成一整轮 LLM 调用)。workspace skill 也可作为命令调用(`/skill:<名称>`)。
|
|
230
231
|
- `/model` 依次尝试精确 `provider/modelId`、精确 `modelId`、对完整引用的子串匹配,只有唯一命中时才切换,例如 `/model turbo`。
|
|
@@ -4,7 +4,7 @@ import type { ChannelStore } from "../runtime/store.js";
|
|
|
4
4
|
import type { UsageTotals } from "../shared/types.js";
|
|
5
5
|
import { type RunnerBuiltInCommand } from "./commands.js";
|
|
6
6
|
import type { RunnerFactoryPaths } from "./runner-factory.js";
|
|
7
|
-
import { type AgentRunner, type RunnerStatusSnapshot } from "./types.js";
|
|
7
|
+
import { type AgentRunner, type RunnerStatusSnapshot, type TurnStatus } from "./types.js";
|
|
8
8
|
export declare class ChannelRunner implements AgentRunner {
|
|
9
9
|
private readonly executor;
|
|
10
10
|
private readonly channelId;
|
|
@@ -28,14 +28,26 @@ export declare class ChannelRunner implements AgentRunner {
|
|
|
28
28
|
private subAgentDiscovery;
|
|
29
29
|
private activeModel;
|
|
30
30
|
private currentSkills;
|
|
31
|
+
/** Last built system prompt (spec 025): feeds the boundary footer, /context and the debug manifest. */
|
|
32
|
+
private lastPromptBuild?;
|
|
33
|
+
/** The exact system prompt the provider last received (our prompt + pi's tail + footer). */
|
|
34
|
+
private lastFinalPrompt?;
|
|
35
|
+
private lastTurnContextStats?;
|
|
31
36
|
private currentTools;
|
|
32
37
|
private firstTurnMemoryBootstrapPending;
|
|
33
|
-
|
|
34
|
-
private
|
|
38
|
+
/** Mirror of `tools.tasks.enabled` from the last tools-config load (see buildRuntimeTools). */
|
|
39
|
+
private tasksEnabled;
|
|
40
|
+
/** Single owner of turn state; see TurnPhase in types.ts. */
|
|
41
|
+
private turn;
|
|
35
42
|
/** When the primary model last failed and we switched to the backup. null = on primary. */
|
|
36
43
|
private primaryFailedAt;
|
|
37
44
|
private runState;
|
|
38
45
|
constructor(channelId: string, channelDir: string, paths: RunnerFactoryPaths);
|
|
46
|
+
beginTurn(taskText: string): void;
|
|
47
|
+
endTurn(): void;
|
|
48
|
+
isBusy(): boolean;
|
|
49
|
+
requestStop(): void;
|
|
50
|
+
getTurnStatus(): TurnStatus;
|
|
39
51
|
run(ctx: ChannelContext, store: ChannelStore): Promise<{
|
|
40
52
|
stopReason: string;
|
|
41
53
|
errorMessage?: string;
|
|
@@ -56,11 +68,30 @@ export declare class ChannelRunner implements AgentRunner {
|
|
|
56
68
|
getMemoryMaintenanceContext(): Promise<MemoryMaintenanceRuntimeContext>;
|
|
57
69
|
getStatusSnapshot(): RunnerStatusSnapshot;
|
|
58
70
|
abort(): Promise<void>;
|
|
71
|
+
/**
|
|
72
|
+
* `/context` — read-only prompt accounting, no LLM cost. Reports the section
|
|
73
|
+
* breakdown of the system prompt, the tool schemas (billed on top of it, and
|
|
74
|
+
* often the larger half), and the last turn's dynamic context.
|
|
75
|
+
*/
|
|
76
|
+
renderContextReport(args?: string): string;
|
|
77
|
+
/**
|
|
78
|
+
* The per-turn channel capsule. It replaces the channel paths that used to sit in
|
|
79
|
+
* the system prompt: memory/task/event tools are already bound to this channel, so
|
|
80
|
+
* the model only needs the directory when it wants to read a file directly.
|
|
81
|
+
*/
|
|
82
|
+
private renderChannelTurnContext;
|
|
59
83
|
private sendCommandReply;
|
|
60
84
|
private recordMemoryActivity;
|
|
61
85
|
private requireQueuedMessage;
|
|
62
86
|
private shouldPreserveRawInput;
|
|
63
87
|
private formatUserMessage;
|
|
88
|
+
/**
|
|
89
|
+
* Single source of truth for the busy-message window: steer is accepted while
|
|
90
|
+
* the prompt is being assembled ("preparing") or while the agent loop is
|
|
91
|
+
* actually streaming. Re-asserted after every await because the turn can end
|
|
92
|
+
* while this call was suspended.
|
|
93
|
+
*/
|
|
94
|
+
private assertBusyWindowOpen;
|
|
64
95
|
private queueBusyMessage;
|
|
65
96
|
private resetRunState;
|
|
66
97
|
private refreshSessionResources;
|
|
@@ -83,6 +114,17 @@ export declare class ChannelRunner implements AgentRunner {
|
|
|
83
114
|
private refreshSubAgentDiscovery;
|
|
84
115
|
private reportSettingsDiagnostics;
|
|
85
116
|
private reportConfigDiagnostics;
|
|
117
|
+
/**
|
|
118
|
+
* Build the Pipiclaw-owned system prompt (spec 025). This replaces pi's default
|
|
119
|
+
* base prompt entirely: identity, execution contract, hard invariants, the tool
|
|
120
|
+
* catalog and the workspace files are ours. pi still appends its tail (skills,
|
|
121
|
+
* date, cwd), and the boundary footer is appended after that by the prompt
|
|
122
|
+
* extension.
|
|
123
|
+
*
|
|
124
|
+
* Nothing channel-specific enters this text — that is what lets two channels in
|
|
125
|
+
* one workspace share a cached prompt prefix. Channel facts ride the turn.
|
|
126
|
+
*/
|
|
127
|
+
private buildSystemPrompt;
|
|
86
128
|
private createResourceLoader;
|
|
87
129
|
private createAgentSessionServices;
|
|
88
130
|
private createEmptyExtensionsResult;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Agent } from "@earendil-works/pi-agent-core";
|
|
2
|
-
import { AgentSession, AgentSessionRuntime, AuthStorage, convertToLlm, createExtensionRuntime, DefaultResourceLoader,
|
|
2
|
+
import { AgentSession, AgentSessionRuntime, AuthStorage, convertToLlm, createExtensionRuntime, DefaultResourceLoader, SessionManager, } from "@earendil-works/pi-coding-agent";
|
|
3
3
|
import { mkdir, readFile, writeFile } from "fs/promises";
|
|
4
4
|
import { dirname, join, resolve } from "path";
|
|
5
5
|
import { createExecutor } from "../executor.js";
|
|
@@ -12,13 +12,14 @@ import { applyMemoryActivityToState, updateMemoryMaintenanceState, } from "../me
|
|
|
12
12
|
import { recallRelevantMemory } from "../memory/recall.js";
|
|
13
13
|
import { buildTaskDigest } from "../memory/task-digest.js";
|
|
14
14
|
import { getApiKeyForModel } from "../models/api-keys.js";
|
|
15
|
-
import { findExactModelReferenceMatch, formatModelReference, resolveInitialModel } from "../models/utils.js";
|
|
15
|
+
import { createModelRegistry, findExactModelReferenceMatch, formatModelReference, resolveInitialModel, } from "../models/utils.js";
|
|
16
|
+
import { loadRuntimePlaybookCatalog, selectRuntimePlaybooks } from "../playbooks/catalog.js";
|
|
16
17
|
import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
|
|
17
18
|
import { PipiclawSettingsManager } from "../settings.js";
|
|
18
19
|
import { formatConfigDiagnostic } from "../shared/config-diagnostics.js";
|
|
19
20
|
import { errorMessage } from "../shared/text-utils.js";
|
|
20
21
|
import { isRecord } from "../shared/type-guards.js";
|
|
21
|
-
import { discoverSubAgents
|
|
22
|
+
import { discoverSubAgents } from "../subagents/discovery.js";
|
|
22
23
|
import { loadToolsConfigWithDiagnostics } from "../tools/config.js";
|
|
23
24
|
import { createPipiclawTools } from "../tools/index.js";
|
|
24
25
|
import { TOOL_PROMPT_HINTS } from "../tools/registry.js";
|
|
@@ -28,13 +29,16 @@ import { isKnownCommandName, renderBuiltInHelp, slashCommandName } from "./comma
|
|
|
28
29
|
import { estimateIncomingMessageTokens, getPreventiveCompactionDecision } from "./context-budget.js";
|
|
29
30
|
import { PRIMARY_COOLDOWN_MS, runPromptWithFallback, shouldRestorePrimary, } from "./model-fallback.js";
|
|
30
31
|
import { clipUserInput, formatProgressEntry } from "./progress-formatter.js";
|
|
31
|
-
import {
|
|
32
|
+
import { buildPipiclawSystemPrompt } from "./prompt/builder.js";
|
|
33
|
+
import { createPromptBoundaryExtension } from "./prompt/extension.js";
|
|
34
|
+
import { buildPromptManifest, renderContextReport } from "./prompt/manifest.js";
|
|
35
|
+
import { loadWorkspacePromptResources } from "./prompt/resources.js";
|
|
32
36
|
import { createRunQueue } from "./run-queue.js";
|
|
33
37
|
import { handleSessionEvent } from "./session-events.js";
|
|
34
38
|
import { SessionResourceGate } from "./session-resource-gate.js";
|
|
35
39
|
import { getLastAssistantUsage } from "./type-guards.js";
|
|
36
40
|
import { createEmptyRunState, MAX_USER_MESSAGE_CHARS, } from "./types.js";
|
|
37
|
-
import {
|
|
41
|
+
import { loadPipiclawSkills, resolvePipiclawSkills } from "./workspace-resources.js";
|
|
38
42
|
function isSilentOutcome(outcome) {
|
|
39
43
|
return outcome.kind === "silent";
|
|
40
44
|
}
|
|
@@ -44,12 +48,6 @@ function isFinalOutcome(outcome) {
|
|
|
44
48
|
function getFinalOutcomeText(outcome) {
|
|
45
49
|
return isFinalOutcome(outcome) ? outcome.text : null;
|
|
46
50
|
}
|
|
47
|
-
function createModelRegistry(authStorage, modelsJsonPath) {
|
|
48
|
-
const registryClass = ModelRegistry;
|
|
49
|
-
return typeof registryClass.create === "function"
|
|
50
|
-
? registryClass.create(authStorage, modelsJsonPath)
|
|
51
|
-
: new registryClass(authStorage, modelsJsonPath);
|
|
52
|
-
}
|
|
53
51
|
function asSdkSettingsManager(manager) {
|
|
54
52
|
return manager;
|
|
55
53
|
}
|
|
@@ -58,8 +56,13 @@ export class ChannelRunner {
|
|
|
58
56
|
this.ledger = getUsageLedger();
|
|
59
57
|
this.currentTools = [];
|
|
60
58
|
this.firstTurnMemoryBootstrapPending = true;
|
|
61
|
-
|
|
62
|
-
this.
|
|
59
|
+
/** Mirror of `tools.tasks.enabled` from the last tools-config load (see buildRuntimeTools). */
|
|
60
|
+
this.tasksEnabled = true;
|
|
61
|
+
/** Single owner of turn state; see TurnPhase in types.ts. */
|
|
62
|
+
this.turn = {
|
|
63
|
+
phase: "idle",
|
|
64
|
+
stopRequested: false,
|
|
65
|
+
};
|
|
63
66
|
/** When the primary model last failed and we switched to the backup. null = on primary. */
|
|
64
67
|
this.primaryFailedAt = null;
|
|
65
68
|
// --- Per run ---
|
|
@@ -147,16 +150,46 @@ export class ChannelRunner {
|
|
|
147
150
|
this.sessionReady = this.initializeSession();
|
|
148
151
|
}
|
|
149
152
|
// === Public API ===
|
|
153
|
+
beginTurn(taskText) {
|
|
154
|
+
if (this.turn.phase !== "idle") {
|
|
155
|
+
log.logWarning(`[${this.channelId}] beginTurn while phase=${this.turn.phase}; turns must be serialized`);
|
|
156
|
+
}
|
|
157
|
+
this.turn = { phase: "dispatching", stopRequested: false, taskText };
|
|
158
|
+
}
|
|
159
|
+
endTurn() {
|
|
160
|
+
this.turn = { phase: "idle", stopRequested: false };
|
|
161
|
+
}
|
|
162
|
+
isBusy() {
|
|
163
|
+
return this.turn.phase !== "idle";
|
|
164
|
+
}
|
|
165
|
+
requestStop() {
|
|
166
|
+
if (this.turn.phase !== "idle") {
|
|
167
|
+
this.turn.stopRequested = true;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
getTurnStatus() {
|
|
171
|
+
return { ...this.turn };
|
|
172
|
+
}
|
|
150
173
|
async run(ctx, store) {
|
|
151
174
|
const startedAt = Date.now();
|
|
152
175
|
this.resetRunState(ctx, store);
|
|
153
|
-
|
|
154
|
-
|
|
176
|
+
// Direct callers (tests) may skip the transport's beginTurn/endTurn wrapper;
|
|
177
|
+
// then run() owns the whole turn itself.
|
|
178
|
+
const implicitTurn = this.turn.phase === "idle";
|
|
179
|
+
if (implicitTurn) {
|
|
180
|
+
this.beginTurn(ctx.message.text);
|
|
181
|
+
}
|
|
182
|
+
this.turn.phase = "preparing";
|
|
155
183
|
const runQueue = createRunQueue();
|
|
156
184
|
this.runState.queue = runQueue.queue;
|
|
157
185
|
let promptSubmitted = false;
|
|
158
186
|
let fallbackAttempted = false;
|
|
159
187
|
let fallbackTargetRef;
|
|
188
|
+
// Hoisted so the debug dump in `finally` can report the turn as it was actually sent.
|
|
189
|
+
let promptText = "";
|
|
190
|
+
let recalledContextText = "";
|
|
191
|
+
let taskDigestText = "";
|
|
192
|
+
let durableMemoryBootstrapText = "";
|
|
160
193
|
try {
|
|
161
194
|
await this.ensureSessionReady();
|
|
162
195
|
await this.maybeRestorePrimaryModel();
|
|
@@ -170,11 +203,11 @@ export class ChannelRunner {
|
|
|
170
203
|
const preserveRawInput = this.shouldPreserveRawInput(ctx.message.text);
|
|
171
204
|
// Ensure channel directory exists
|
|
172
205
|
await mkdir(this.channelDir, { recursive: true });
|
|
173
|
-
|
|
174
|
-
let recalledContextText = "";
|
|
175
|
-
let taskDigestText = "";
|
|
176
|
-
let durableMemoryBootstrapText = "";
|
|
206
|
+
promptText = preserveRawInput ? clippedInput : userMessage;
|
|
177
207
|
if (!preserveRawInput) {
|
|
208
|
+
// Channel facts are turn-dynamic by design (spec 025 §7.3): keeping them out of the
|
|
209
|
+
// system prompt is what lets every channel in a workspace share one cached prefix.
|
|
210
|
+
promptText = `${this.renderChannelTurnContext()}\n\n<user_message>\n${promptText}\n</user_message>`;
|
|
178
211
|
const recallSettings = this.settingsManager.getMemoryRecallSettings();
|
|
179
212
|
if (recallSettings.enabled) {
|
|
180
213
|
const recall = await recallRelevantMemory({
|
|
@@ -195,11 +228,12 @@ export class ChannelRunner {
|
|
|
195
228
|
});
|
|
196
229
|
if (recall.renderedText) {
|
|
197
230
|
recalledContextText = recall.renderedText;
|
|
198
|
-
promptText = `${recall.renderedText}\n\n
|
|
231
|
+
promptText = `${recall.renderedText}\n\n${promptText}`;
|
|
199
232
|
}
|
|
200
233
|
}
|
|
201
|
-
|
|
202
|
-
if (
|
|
234
|
+
// Gated by the same master autonomy switch as task_manage and the TaskDriver.
|
|
235
|
+
if (this.tasksEnabled) {
|
|
236
|
+
const taskDigestSettings = this.settingsManager.getTaskDigestSettings();
|
|
203
237
|
taskDigestText = await buildTaskDigest({
|
|
204
238
|
channelDir: this.channelDir,
|
|
205
239
|
maxTasks: taskDigestSettings.maxTasks,
|
|
@@ -221,18 +255,12 @@ export class ChannelRunner {
|
|
|
221
255
|
// prepended above), not just the bare user message — those pieces can add thousands of
|
|
222
256
|
// characters and must count against the projected context usage this guard is checking.
|
|
223
257
|
await this.maybeRunPreventiveCompactionForIncomingText(promptText);
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
taskDigest: taskDigestText || undefined,
|
|
231
|
-
recalledContext: recalledContextText || undefined,
|
|
232
|
-
newUserMessage: promptText,
|
|
233
|
-
};
|
|
234
|
-
await writeFile(join(this.channelDir, "last_prompt.json"), JSON.stringify(debugContext, null, 2));
|
|
235
|
-
}
|
|
258
|
+
this.lastTurnContextStats = {
|
|
259
|
+
durableMemoryChars: durableMemoryBootstrapText.length,
|
|
260
|
+
taskDigestChars: taskDigestText.length,
|
|
261
|
+
recalledMemoryChars: recalledContextText.length,
|
|
262
|
+
userMessageChars: clippedInput.length,
|
|
263
|
+
};
|
|
236
264
|
const fallbackDeps = {
|
|
237
265
|
prompt: async (text) => {
|
|
238
266
|
try {
|
|
@@ -292,8 +320,24 @@ export class ChannelRunner {
|
|
|
292
320
|
log.logWarning(`[${this.channelId}] Runner failed`, this.runState.errorMessage);
|
|
293
321
|
}
|
|
294
322
|
finally {
|
|
295
|
-
this.
|
|
296
|
-
|
|
323
|
+
this.turn.phase = "finishing";
|
|
324
|
+
// Debug dump (PIPICLAW_DEBUG=1). Written after the run so `systemPrompt` is the
|
|
325
|
+
// string the provider actually received — base sections, pi's tail, and the boundary
|
|
326
|
+
// footer the prompt extension appends at before_agent_start.
|
|
327
|
+
if (process.env.PIPICLAW_DEBUG) {
|
|
328
|
+
const debugContext = {
|
|
329
|
+
systemPrompt: this.lastFinalPrompt ?? this.agent.state.systemPrompt,
|
|
330
|
+
promptManifest: this.lastPromptBuild
|
|
331
|
+
? buildPromptManifest(this.lastPromptBuild, this.lastFinalPrompt)
|
|
332
|
+
: undefined,
|
|
333
|
+
messages: this.session.messages,
|
|
334
|
+
durableMemoryBootstrap: durableMemoryBootstrapText || undefined,
|
|
335
|
+
taskDigest: taskDigestText || undefined,
|
|
336
|
+
recalledContext: recalledContextText || undefined,
|
|
337
|
+
newUserMessage: promptText,
|
|
338
|
+
};
|
|
339
|
+
await writeFile(join(this.channelDir, "last_prompt.json"), JSON.stringify(debugContext, null, 2)).catch((error) => log.logWarning(`[${this.channelId}] Failed to write last_prompt.json`, errorMessage(error)));
|
|
340
|
+
}
|
|
297
341
|
if (!promptSubmitted) {
|
|
298
342
|
const discarded = this.session.clearQueue();
|
|
299
343
|
const discardedCount = discarded.steering.length + discarded.followUp.length;
|
|
@@ -404,6 +448,9 @@ export class ChannelRunner {
|
|
|
404
448
|
this.runState.ctx = null;
|
|
405
449
|
this.runState.logCtx = null;
|
|
406
450
|
this.runState.queue = null;
|
|
451
|
+
if (implicitTurn) {
|
|
452
|
+
this.endTurn();
|
|
453
|
+
}
|
|
407
454
|
}
|
|
408
455
|
return {
|
|
409
456
|
stopReason: this.runState.stopReason,
|
|
@@ -418,6 +465,9 @@ export class ChannelRunner {
|
|
|
418
465
|
case "help":
|
|
419
466
|
await this.sendCommandReply(ctx, renderBuiltInHelp());
|
|
420
467
|
return;
|
|
468
|
+
case "context":
|
|
469
|
+
await this.sendCommandReply(ctx, this.renderContextReport(command.args));
|
|
470
|
+
return;
|
|
421
471
|
case "stop":
|
|
422
472
|
await this.sendCommandReply(ctx, "No task is running. Use `/stop` only while a task is running.");
|
|
423
473
|
return;
|
|
@@ -483,7 +533,7 @@ export class ChannelRunner {
|
|
|
483
533
|
memoryGrowth: this.settingsManager.getMemoryGrowthSettings(),
|
|
484
534
|
memoryMaintenance: this.settingsManager.getMemoryMaintenanceSettings(),
|
|
485
535
|
},
|
|
486
|
-
loadedSkills: this.currentSkills.map((skill) => ({
|
|
536
|
+
loadedSkills: this.currentSkills.skills.map((skill) => ({
|
|
487
537
|
name: skill.name,
|
|
488
538
|
description: skill.description,
|
|
489
539
|
})),
|
|
@@ -512,7 +562,37 @@ export class ChannelRunner {
|
|
|
512
562
|
async abort() {
|
|
513
563
|
await this.session.abort();
|
|
514
564
|
}
|
|
565
|
+
/**
|
|
566
|
+
* `/context` — read-only prompt accounting, no LLM cost. Reports the section
|
|
567
|
+
* breakdown of the system prompt, the tool schemas (billed on top of it, and
|
|
568
|
+
* often the larger half), and the last turn's dynamic context.
|
|
569
|
+
*/
|
|
570
|
+
renderContextReport(args = "") {
|
|
571
|
+
const build = this.lastPromptBuild ?? this.buildSystemPrompt();
|
|
572
|
+
return renderContextReport({
|
|
573
|
+
build,
|
|
574
|
+
finalPrompt: this.lastFinalPrompt,
|
|
575
|
+
skills: this.currentSkills.skills.map((skill) => ({ name: skill.name, description: skill.description })),
|
|
576
|
+
toolNames: this.currentTools.map((tool) => tool.name),
|
|
577
|
+
toolSchemaChars: this.currentTools.reduce((sum, tool) => sum + tool.name.length + tool.description.length + JSON.stringify(tool.parameters ?? {}).length, 0),
|
|
578
|
+
lastTurn: this.lastTurnContextStats,
|
|
579
|
+
detail: args.trim().toLowerCase() === "detail",
|
|
580
|
+
});
|
|
581
|
+
}
|
|
515
582
|
// === Private helpers ===
|
|
583
|
+
/**
|
|
584
|
+
* The per-turn channel capsule. It replaces the channel paths that used to sit in
|
|
585
|
+
* the system prompt: memory/task/event tools are already bound to this channel, so
|
|
586
|
+
* the model only needs the directory when it wants to read a file directly.
|
|
587
|
+
*/
|
|
588
|
+
renderChannelTurnContext() {
|
|
589
|
+
return [
|
|
590
|
+
"<runtime_turn_context>",
|
|
591
|
+
`Channel directory: ${this.channelDir}`,
|
|
592
|
+
"SESSION.md, MEMORY.md, HISTORY.md and tasks/ live there and are runtime-maintained. Prefer the context supplied with this turn and the channel-bound tools; read those files directly only when you need detail they did not provide.",
|
|
593
|
+
"</runtime_turn_context>",
|
|
594
|
+
].join("\n");
|
|
595
|
+
}
|
|
516
596
|
async sendCommandReply(ctx, text) {
|
|
517
597
|
const delivered = await ctx.respondPlain(text);
|
|
518
598
|
if (!delivered) {
|
|
@@ -556,13 +636,23 @@ export class ChannelRunner {
|
|
|
556
636
|
const timestamp = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}${offsetSign}${offsetHours}:${offsetMins}`;
|
|
557
637
|
return `[${timestamp}] [${userName || "unknown"}]: ${text}`;
|
|
558
638
|
}
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
639
|
+
/**
|
|
640
|
+
* Single source of truth for the busy-message window: steer is accepted while
|
|
641
|
+
* the prompt is being assembled ("preparing") or while the agent loop is
|
|
642
|
+
* actually streaming. Re-asserted after every await because the turn can end
|
|
643
|
+
* while this call was suspended.
|
|
644
|
+
*/
|
|
645
|
+
assertBusyWindowOpen() {
|
|
646
|
+
if (this.turn.phase === "preparing") {
|
|
647
|
+
return;
|
|
562
648
|
}
|
|
563
|
-
if (this.
|
|
564
|
-
|
|
649
|
+
if (this.turn.phase === "streaming" && this.session.isStreaming) {
|
|
650
|
+
return;
|
|
565
651
|
}
|
|
652
|
+
throw new Error("No task is currently running.");
|
|
653
|
+
}
|
|
654
|
+
async queueBusyMessage(text, userName) {
|
|
655
|
+
this.assertBusyWindowOpen();
|
|
566
656
|
await this.ensureSessionReady();
|
|
567
657
|
const clippedText = clipUserInput(text, MAX_USER_MESSAGE_CHARS);
|
|
568
658
|
if (clippedText !== text.trim()) {
|
|
@@ -570,16 +660,9 @@ export class ChannelRunner {
|
|
|
570
660
|
}
|
|
571
661
|
const queuedMessage = this.formatUserMessage(clippedText, userName);
|
|
572
662
|
await this.maybeRunPreventiveCompactionForIncomingText(queuedMessage);
|
|
573
|
-
|
|
574
|
-
throw new Error("No task is currently running.");
|
|
575
|
-
}
|
|
576
|
-
if (this.agentLoopStarted && !this.session.isStreaming) {
|
|
577
|
-
throw new Error("No task is currently running.");
|
|
578
|
-
}
|
|
663
|
+
this.assertBusyWindowOpen();
|
|
579
664
|
const queueMessage = async () => {
|
|
580
|
-
|
|
581
|
-
throw new Error("No task is currently running.");
|
|
582
|
-
}
|
|
665
|
+
this.assertBusyWindowOpen();
|
|
583
666
|
await this.session.steer(queuedMessage);
|
|
584
667
|
};
|
|
585
668
|
await this.sessionResourceGate.runPrompt(queueMessage);
|
|
@@ -725,6 +808,49 @@ export class ChannelRunner {
|
|
|
725
808
|
log.logWarning(`[${this.channelId}] ${formatConfigDiagnostic(diagnostic)}`, diagnostic.path);
|
|
726
809
|
}
|
|
727
810
|
}
|
|
811
|
+
/**
|
|
812
|
+
* Build the Pipiclaw-owned system prompt (spec 025). This replaces pi's default
|
|
813
|
+
* base prompt entirely: identity, execution contract, hard invariants, the tool
|
|
814
|
+
* catalog and the workspace files are ours. pi still appends its tail (skills,
|
|
815
|
+
* date, cwd), and the boundary footer is appended after that by the prompt
|
|
816
|
+
* extension.
|
|
817
|
+
*
|
|
818
|
+
* Nothing channel-specific enters this text — that is what lets two channels in
|
|
819
|
+
* one workspace share a cached prompt prefix. Channel facts ride the turn.
|
|
820
|
+
*/
|
|
821
|
+
buildSystemPrompt() {
|
|
822
|
+
const toolNames = this.currentTools.map((tool) => tool.name);
|
|
823
|
+
const resources = loadWorkspacePromptResources(this.workspaceDir);
|
|
824
|
+
const build = buildPipiclawSystemPrompt({
|
|
825
|
+
mode: "normal",
|
|
826
|
+
cwd: process.cwd(),
|
|
827
|
+
workspaceDir: this.workspaceDir,
|
|
828
|
+
tools: this.currentTools.map((tool) => ({
|
|
829
|
+
name: tool.name,
|
|
830
|
+
description: tool.description,
|
|
831
|
+
hint: TOOL_PROMPT_HINTS[tool.name],
|
|
832
|
+
})),
|
|
833
|
+
soul: resources.soul,
|
|
834
|
+
agents: resources.agents,
|
|
835
|
+
playbooks: selectRuntimePlaybooks(loadRuntimePlaybookCatalog(), toolNames),
|
|
836
|
+
subAgents: this.subAgentDiscovery.agents.map((agent) => ({
|
|
837
|
+
name: agent.name,
|
|
838
|
+
description: agent.description,
|
|
839
|
+
})),
|
|
840
|
+
skills: this.currentSkills.skills.map((skill) => ({ name: skill.name, description: skill.description })),
|
|
841
|
+
});
|
|
842
|
+
for (const diagnostic of [...resources.diagnostics, ...build.diagnostics]) {
|
|
843
|
+
if (diagnostic.level === "info")
|
|
844
|
+
continue;
|
|
845
|
+
log.logWarning(`[${this.channelId}] Prompt ${diagnostic.level} (${diagnostic.sectionId})`, diagnostic.message);
|
|
846
|
+
}
|
|
847
|
+
// Only a real change is worth a line: a reload that produced the same bytes is noise.
|
|
848
|
+
if (this.lastPromptBuild?.fingerprint !== build.fingerprint) {
|
|
849
|
+
log.logInfo(`[${this.channelId}] System prompt rebuilt: ${build.totalChars} chars, ~${build.estimatedTokens} tokens, sha256:${build.fingerprint.slice(0, 12)} (was ${this.lastPromptBuild ? `sha256:${this.lastPromptBuild.fingerprint.slice(0, 12)}` : "none"})`);
|
|
850
|
+
}
|
|
851
|
+
this.lastPromptBuild = build;
|
|
852
|
+
return build;
|
|
853
|
+
}
|
|
728
854
|
createResourceLoader() {
|
|
729
855
|
return new DefaultResourceLoader({
|
|
730
856
|
cwd: process.cwd(),
|
|
@@ -732,6 +858,12 @@ export class ChannelRunner {
|
|
|
732
858
|
settingsManager: asSdkSettingsManager(this.settingsManager),
|
|
733
859
|
extensionFactories: [
|
|
734
860
|
this.memoryLifecycle.createExtensionFactory(),
|
|
861
|
+
createPromptBoundaryExtension({
|
|
862
|
+
getFooter: () => this.lastPromptBuild?.footer ?? "",
|
|
863
|
+
onFinalPrompt: (systemPrompt) => {
|
|
864
|
+
this.lastFinalPrompt = systemPrompt;
|
|
865
|
+
},
|
|
866
|
+
}),
|
|
735
867
|
createCommandExtension({
|
|
736
868
|
getCurrentModel: () => this.session.model ?? this.activeModel,
|
|
737
869
|
getAvailableModels: async () => {
|
|
@@ -752,32 +884,22 @@ export class ChannelRunner {
|
|
|
752
884
|
},
|
|
753
885
|
}),
|
|
754
886
|
],
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
887
|
+
// Pipiclaw owns the base prompt: with a custom prompt present, pi emits no
|
|
888
|
+
// default identity, no pi docs index and no `Available tools: (none)` block.
|
|
889
|
+
systemPromptOverride: () => this.buildSystemPrompt().text,
|
|
890
|
+
// Nothing may slip in behind the section pipeline — not pi's app-level
|
|
891
|
+
// APPEND_SYSTEM.md, not a base append. SOUL/AGENTS are rendered as sections.
|
|
892
|
+
appendSystemPromptOverride: () => [],
|
|
893
|
+
agentsFilesOverride: () => ({ agentsFiles: [] }),
|
|
894
|
+
// Skills stay in the ResourceLoader: they drive `/skill:name` and pi's
|
|
895
|
+
// `<available_skills>` index together. Only the merge policy is ours.
|
|
896
|
+
skillsOverride: (base) => {
|
|
897
|
+
const merged = resolvePipiclawSkills(base, this.currentSkills);
|
|
898
|
+
for (const diagnostic of merged.diagnostics) {
|
|
899
|
+
log.logWarning(`[${this.channelId}] Skill ${diagnostic.type}`, `${diagnostic.message}${diagnostic.path ? ` (${diagnostic.path})` : ""}`);
|
|
760
900
|
}
|
|
761
|
-
|
|
762
|
-
subAgentList: formatSubAgentList(this.subAgentDiscovery.agents),
|
|
763
|
-
tools: this.currentTools.map((tool) => ({
|
|
764
|
-
name: tool.name,
|
|
765
|
-
description: tool.description,
|
|
766
|
-
hint: TOOL_PROMPT_HINTS[tool.name],
|
|
767
|
-
})),
|
|
768
|
-
}));
|
|
769
|
-
return sections;
|
|
770
|
-
},
|
|
771
|
-
agentsFilesOverride: () => {
|
|
772
|
-
const agentConfig = getAgentConfig(this.channelDir);
|
|
773
|
-
return {
|
|
774
|
-
agentsFiles: agentConfig ? [{ path: `${this.workspaceDir}/AGENTS.md`, content: agentConfig }] : [],
|
|
775
|
-
};
|
|
901
|
+
return merged;
|
|
776
902
|
},
|
|
777
|
-
skillsOverride: (base) => ({
|
|
778
|
-
skills: [...base.skills, ...this.currentSkills],
|
|
779
|
-
diagnostics: base.diagnostics,
|
|
780
|
-
}),
|
|
781
903
|
});
|
|
782
904
|
}
|
|
783
905
|
createAgentSessionServices(resourceLoader) {
|
|
@@ -827,6 +949,7 @@ export class ChannelRunner {
|
|
|
827
949
|
const securityLoad = loadSecurityConfigWithDiagnostics(this.appHomeDir);
|
|
828
950
|
const toolsLoad = loadToolsConfigWithDiagnostics(this.appHomeDir);
|
|
829
951
|
this.reportConfigDiagnostics([...securityLoad.diagnostics, ...toolsLoad.diagnostics]);
|
|
952
|
+
this.tasksEnabled = toolsLoad.config.tools.tasks.enabled;
|
|
830
953
|
const tools = createPipiclawTools({
|
|
831
954
|
executor: this.executor,
|
|
832
955
|
getCurrentModel: () => this.activeModel,
|
|
@@ -869,8 +992,8 @@ export class ChannelRunner {
|
|
|
869
992
|
subscribeToSessionEvents() {
|
|
870
993
|
this.sessionUnsubscribe?.();
|
|
871
994
|
this.sessionUnsubscribe = this.session.subscribe(async (event) => {
|
|
872
|
-
if (isRecord(event) && event.type === "message_start") {
|
|
873
|
-
this.
|
|
995
|
+
if (isRecord(event) && event.type === "message_start" && this.turn.phase === "preparing") {
|
|
996
|
+
this.turn.phase = "streaming";
|
|
874
997
|
}
|
|
875
998
|
if (isRecord(event) && "reason" in event && event.reason === "new") {
|
|
876
999
|
this.firstTurnMemoryBootstrapPending = true;
|
package/dist/agent/commands.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
export type BuiltInCommandName = "help" | "steer" | "followup" | "stop" | "events" | "tasks" | "status" | "usage";
|
|
1
|
+
export type BuiltInCommandName = "help" | "steer" | "followup" | "stop" | "events" | "tasks" | "status" | "usage" | "context";
|
|
2
2
|
/** The four transport commands handled by `ChannelRunner.handleBuiltinCommand`. */
|
|
3
|
-
export type RunnerBuiltInCommandName = "help" | "stop" | "steer" | "followup";
|
|
3
|
+
export type RunnerBuiltInCommandName = "help" | "stop" | "steer" | "followup" | "context";
|
|
4
4
|
export interface BuiltInCommand {
|
|
5
5
|
name: BuiltInCommandName;
|
|
6
6
|
args: string;
|
package/dist/agent/commands.js
CHANGED
|
@@ -71,6 +71,15 @@ export const BUILT_IN_COMMANDS = [
|
|
|
71
71
|
examples: ["/usage", "/usage 7d", "/usage month"],
|
|
72
72
|
availableWhileBusy: true,
|
|
73
73
|
},
|
|
74
|
+
{
|
|
75
|
+
name: "context",
|
|
76
|
+
argumentHint: "[detail]",
|
|
77
|
+
description: "Show what the model is being sent: system prompt sections, tool schemas, and last-turn context",
|
|
78
|
+
examples: ["/context", "/context detail"],
|
|
79
|
+
// Read-only accounting of state the runner already holds: no LLM call, no session
|
|
80
|
+
// access, so it answers mid-turn like /status and /usage do.
|
|
81
|
+
availableWhileBusy: true,
|
|
82
|
+
},
|
|
74
83
|
];
|
|
75
84
|
/**
|
|
76
85
|
* Session commands: handled inside the Pipiclaw session layer (SDK command
|
|
@@ -114,7 +123,7 @@ export function sessionCommandDescription(name) {
|
|
|
114
123
|
export function isBuiltInCommandName(name) {
|
|
115
124
|
return BUILT_IN_NAMES.has(name);
|
|
116
125
|
}
|
|
117
|
-
const RUNNER_BUILT_IN_NAMES = new Set(["help", "stop", "steer", "followup"]);
|
|
126
|
+
const RUNNER_BUILT_IN_NAMES = new Set(["help", "stop", "steer", "followup", "context"]);
|
|
118
127
|
/** Narrow a parsed built-in to one `ChannelRunner.handleBuiltinCommand` accepts. */
|
|
119
128
|
export function isRunnerBuiltInCommand(command) {
|
|
120
129
|
return RUNNER_BUILT_IN_NAMES.has(command.name);
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { MemoryMaintenanceRuntimeContext } from "../memory/scheduler.js";
|
|
2
|
+
import type { PipiclawSettingsManager } from "../settings.js";
|
|
3
|
+
export interface DetachedMaintenanceContextOptions {
|
|
4
|
+
channelId: string;
|
|
5
|
+
channelDir: string;
|
|
6
|
+
workspaceDir: string;
|
|
7
|
+
authConfigPath: string;
|
|
8
|
+
modelsConfigPath: string;
|
|
9
|
+
settingsManager: PipiclawSettingsManager;
|
|
10
|
+
}
|
|
11
|
+
/** Test hook: drop cached transcripts so a fresh read is forced. */
|
|
12
|
+
export declare function clearDetachedMaintenanceCache(): void;
|
|
13
|
+
/**
|
|
14
|
+
* Build a MemoryMaintenanceRuntimeContext for a channel with no live runner,
|
|
15
|
+
* straight from disk. This is deliberately much lighter than a ChannelRunner:
|
|
16
|
+
* no Agent, no AgentSession, no tool set, no sub-agent discovery — just the
|
|
17
|
+
* persisted transcript, the resolved model, and current settings. Channels
|
|
18
|
+
* that spoke this boot keep using their runner's in-memory context instead.
|
|
19
|
+
*
|
|
20
|
+
* Returns null when the channel has no persisted transcript (nothing for the
|
|
21
|
+
* memory pipeline to work with) or the transcript cannot be read.
|
|
22
|
+
*/
|
|
23
|
+
export declare function loadDetachedMaintenanceContext(options: DetachedMaintenanceContextOptions): Promise<MemoryMaintenanceRuntimeContext | null>;
|