@oyasmi/pipiclaw 0.9.3-beta.3 → 0.9.3-beta.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent/channel-runner.d.ts +4 -18
- package/dist/agent/channel-runner.js +25 -120
- package/dist/agent/context-budget.js +1 -1
- package/dist/agent/job-manager.d.ts +11 -17
- package/dist/agent/job-manager.js +76 -65
- package/dist/agent/prompt/builder.js +1 -17
- package/dist/agent/prompt/manifest.d.ts +0 -1
- package/dist/agent/prompt/manifest.js +2 -2
- package/dist/agent/prompt/sections.js +0 -9
- package/dist/agent/prompt/types.d.ts +2 -18
- package/dist/agent/prompt/types.js +1 -1
- package/dist/agent/runner-factory.d.ts +4 -0
- package/dist/agent/session-adapter.d.ts +19 -0
- package/dist/agent/session-adapter.js +77 -0
- package/dist/app-services.d.ts +18 -0
- package/dist/app-services.js +43 -0
- package/dist/{runtime → events}/events.d.ts +1 -1
- package/dist/memory/journal.js +1 -1
- package/dist/memory/maintenance-gates.d.ts +0 -3
- package/dist/memory/maintenance-gates.js +2 -2
- package/dist/memory/maintenance-migration.d.ts +5 -0
- package/dist/memory/maintenance-migration.js +91 -0
- package/dist/memory/maintenance-state.js +5 -44
- package/dist/memory/migrate.js +1 -1
- package/dist/memory/reflect-job.d.ts +1 -9
- package/dist/memory/reflect-job.js +1 -3
- package/dist/memory/reflect.js +1 -1
- package/dist/memory/session-corpus.js +1 -1
- package/dist/memory/store.js +1 -1
- package/dist/models/auth-cli.js +1 -1
- package/dist/runtime/bootstrap.d.ts +5 -15
- package/dist/runtime/bootstrap.js +32 -56
- package/dist/runtime/subagent-commands.d.ts +2 -1
- package/dist/runtime/subagent-commands.js +10 -12
- package/dist/runtime/task-wake.d.ts +4 -5
- package/dist/runtime/task-wake.js +2 -12
- package/dist/security/types.d.ts +7 -0
- package/dist/security/types.js +16 -1
- package/dist/settings.d.ts +8 -0
- package/dist/settings.js +24 -1
- package/dist/shared/exact-keys.d.ts +13 -0
- package/dist/shared/exact-keys.js +1 -0
- package/dist/shared/format.d.ts +20 -0
- package/dist/shared/format.js +64 -0
- package/dist/shared/{fs-utils.d.ts → os.d.ts} +6 -0
- package/dist/shared/{fs-utils.js → os.js} +8 -0
- package/dist/subagents/discovery.d.ts +16 -3
- package/dist/subagents/discovery.js +9 -7
- package/dist/subagents/external/run.d.ts +2 -1
- package/dist/subagents/external/run.js +1 -2
- package/dist/subagents/external/settlement.js +10 -5
- package/dist/subagents/format.d.ts +1 -1
- package/dist/subagents/format.js +1 -1
- package/dist/subagents/runs.d.ts +13 -12
- package/dist/subagents/runs.js +108 -89
- package/dist/subagents/tool.d.ts +7 -7
- package/dist/subagents/tool.js +11 -11
- package/dist/tasks/brief.js +1 -0
- package/dist/tools/command-optimizer.js +1 -1
- package/dist/tools/config.d.ts +7 -0
- package/dist/tools/config.js +16 -1
- package/dist/tools/event-manage.d.ts +1 -1
- package/dist/tools/event-manage.js +3 -3
- package/dist/tools/grep.js +1 -1
- package/dist/tools/index.d.ts +4 -0
- package/dist/tools/index.js +4 -2
- package/dist/tools/job.js +1 -1
- package/dist/tools/read.js +1 -1
- package/dist/tools/registry.d.ts +3 -3
- package/dist/tools/registry.js +18 -56
- package/dist/tools/skill.js +1 -1
- package/dist/tools/subagent-manage.d.ts +2 -0
- package/dist/tools/subagent-manage.js +7 -7
- package/dist/tools/subagent-tool-names.d.ts +2 -2
- package/dist/tools/subagent-tool-names.js +2 -2
- package/dist/tools/task-manage/shared.js +4 -9
- package/dist/tools/task-manage/types.d.ts +4 -0
- package/dist/tui/app.js +22 -7
- package/dist/web/config.js +1 -1
- package/package.json +2 -1
- package/dist/shared/duration.d.ts +0 -2
- package/dist/shared/duration.js +0 -7
- package/dist/shared/file-stamp.d.ts +0 -10
- package/dist/shared/file-stamp.js +0 -19
- package/dist/shared/numeric.d.ts +0 -7
- package/dist/shared/numeric.js +0 -19
- package/dist/shared/shell-escape.d.ts +0 -5
- package/dist/shared/shell-escape.js +0 -7
- package/dist/shared/token-estimate.d.ts +0 -1
- package/dist/shared/token-estimate.js +0 -19
- /package/dist/{runtime → events}/event-commands.d.ts +0 -0
- /package/dist/{runtime → events}/event-commands.js +0 -0
- /package/dist/{runtime → events}/event-validation.d.ts +0 -0
- /package/dist/{runtime → events}/event-validation.js +0 -0
- /package/dist/{runtime → events}/events.js +0 -0
|
@@ -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 {
|
|
3
|
-
import { AgentSession, AgentSessionRuntime, convertToLlm, DefaultResourceLoader,
|
|
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
|
-
|
|
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(
|
|
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) {
|
|
@@ -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
|
|
1073
|
-
|
|
1074
|
-
this.
|
|
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 {
|
|
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.
|
|
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/
|
|
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
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
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 {};
|
|
@@ -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
|
})
|
|
@@ -964,68 +975,68 @@ export class ChannelJobManager {
|
|
|
964
975
|
return { spillFile: record.spillFile, text };
|
|
965
976
|
}
|
|
966
977
|
}
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
const
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
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;
|
|
978
|
+
/** One application's jobs; the executor and configuration cannot change after construction. */
|
|
979
|
+
export function createJobRuntime(executor, options = {}) {
|
|
980
|
+
const config = { ...options };
|
|
981
|
+
const managers = new Map();
|
|
982
|
+
let stopped = false;
|
|
983
|
+
function runningLines(channelId) {
|
|
984
|
+
const manager = managers.get(channelId);
|
|
985
|
+
if (!manager)
|
|
986
|
+
return [];
|
|
987
|
+
return manager.listRunning().map((job) => `job \`${job.id}\`: ${job.command.slice(0, 80)}`);
|
|
1022
988
|
}
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
989
|
+
function get(channelId) {
|
|
990
|
+
let manager = managers.get(channelId);
|
|
991
|
+
if (!manager) {
|
|
992
|
+
manager = new ChannelJobManager(channelId, executor, {
|
|
993
|
+
...(config.jobsStateDir ? { stateDir: join(config.jobsStateDir, channelId) } : {}),
|
|
994
|
+
...(config.workspaceDir ? { spillDir: join(getChannelDir(config.workspaceDir, channelId), "logs") } : {}),
|
|
995
|
+
...(config.dispatch ? { dispatch: config.dispatch } : {}),
|
|
996
|
+
...(config.sweepIntervalMs ? { sweepIntervalMs: config.sweepIntervalMs } : {}),
|
|
997
|
+
});
|
|
998
|
+
managers.set(channelId, manager);
|
|
999
|
+
if (stopped)
|
|
1000
|
+
manager.stop();
|
|
1001
|
+
}
|
|
1002
|
+
return manager;
|
|
1026
1003
|
}
|
|
1027
|
-
|
|
1028
|
-
|
|
1004
|
+
/**
|
|
1005
|
+
* Re-adopt every channel's persisted jobs at startup. Channels are discovered from the state
|
|
1006
|
+
* directory itself, so a job survives even when its channel has had no traffic since the restart.
|
|
1007
|
+
*/
|
|
1008
|
+
async function restore() {
|
|
1009
|
+
const jobsStateDir = config.jobsStateDir;
|
|
1010
|
+
if (!jobsStateDir)
|
|
1011
|
+
return 0;
|
|
1012
|
+
let channelIds;
|
|
1013
|
+
try {
|
|
1014
|
+
await mkdir(jobsStateDir, { recursive: true });
|
|
1015
|
+
channelIds = (await readdir(jobsStateDir, { withFileTypes: true }))
|
|
1016
|
+
.filter((entry) => entry.isDirectory())
|
|
1017
|
+
.map((entry) => entry.name);
|
|
1018
|
+
}
|
|
1019
|
+
catch (error) {
|
|
1020
|
+
log.logWarning("Failed to scan persisted background jobs", errorMessage(error));
|
|
1021
|
+
return 0;
|
|
1022
|
+
}
|
|
1023
|
+
let restored = 0;
|
|
1024
|
+
for (const channelId of channelIds) {
|
|
1025
|
+
restored += await get(channelId).restore();
|
|
1026
|
+
}
|
|
1027
|
+
if (restored > 0) {
|
|
1028
|
+
log.logInfo(`Restored ${restored} background job record(s)`);
|
|
1029
|
+
}
|
|
1030
|
+
return restored;
|
|
1029
1031
|
}
|
|
1030
|
-
return
|
|
1032
|
+
return {
|
|
1033
|
+
get,
|
|
1034
|
+
runningLines,
|
|
1035
|
+
restore,
|
|
1036
|
+
stop: () => {
|
|
1037
|
+
stopped = true;
|
|
1038
|
+
for (const manager of managers.values())
|
|
1039
|
+
manager.stop();
|
|
1040
|
+
},
|
|
1041
|
+
};
|
|
1031
1042
|
}
|
|
@@ -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);
|