@oyasmi/pipiclaw 0.9.2 → 0.9.3-beta.2
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.en.md +250 -0
- package/README.md +3 -1
- package/dist/agent/channel-runner.d.ts +59 -2
- package/dist/agent/channel-runner.js +177 -76
- package/dist/agent/job-manager.d.ts +76 -21
- package/dist/agent/job-manager.js +447 -63
- package/dist/agent/maintenance-context.js +4 -5
- package/dist/agent/prompt/manifest.d.ts +0 -2
- package/dist/agent/prompt/manifest.js +2 -3
- package/dist/agent/prompt/sections.js +3 -3
- package/dist/agent/session-events.js +4 -8
- package/dist/agent/turn-prompt.d.ts +7 -7
- package/dist/agent/turn-prompt.js +6 -9
- package/dist/agent/types.d.ts +12 -0
- package/dist/agent/types.js +1 -0
- package/dist/channel/channel-context.d.ts +13 -0
- package/dist/channel/channel-context.js +21 -1
- package/dist/commands/catalog.js +47 -20
- package/dist/memory/commands.d.ts +8 -0
- package/dist/memory/commands.js +113 -148
- package/dist/memory/index-budget.d.ts +27 -0
- package/dist/memory/index-budget.js +99 -0
- package/dist/memory/journal.d.ts +20 -0
- package/dist/memory/journal.js +78 -0
- package/dist/memory/lifecycle.d.ts +9 -15
- package/dist/memory/lifecycle.js +55 -145
- package/dist/memory/maintenance-gates.d.ts +13 -47
- package/dist/memory/maintenance-gates.js +13 -92
- package/dist/memory/maintenance-state.d.ts +10 -16
- package/dist/memory/maintenance-state.js +12 -59
- package/dist/memory/maintenance-tuning.d.ts +7 -27
- package/dist/memory/maintenance-tuning.js +11 -28
- package/dist/memory/migrate.d.ts +15 -0
- package/dist/memory/migrate.js +364 -0
- package/dist/memory/reflect-job.d.ts +43 -0
- package/dist/memory/reflect-job.js +117 -0
- package/dist/memory/reflect.d.ts +52 -0
- package/dist/memory/reflect.js +313 -0
- package/dist/memory/render.d.ts +19 -0
- package/dist/memory/render.js +35 -0
- package/dist/memory/review-log.d.ts +2 -1
- package/dist/memory/scheduler.d.ts +2 -3
- package/dist/memory/scheduler.js +14 -49
- package/dist/memory/search.d.ts +35 -0
- package/dist/memory/search.js +297 -0
- package/dist/memory/session-search.js +1 -1
- package/dist/memory/store.d.ts +108 -0
- package/dist/memory/store.js +418 -0
- package/dist/memory/task-digest.d.ts +2 -2
- package/dist/memory/task-digest.js +29 -36
- package/dist/memory/tombstones.d.ts +0 -11
- package/dist/memory/tombstones.js +6 -37
- package/dist/memory/transcript.js +12 -5
- package/dist/playbooks/agent-delegation.md +37 -9
- package/dist/playbooks/background-jobs.md +1 -1
- package/dist/playbooks/event-scheduling.md +6 -2
- package/dist/playbooks/memory-and-learning.md +36 -12
- package/dist/playbooks/outbound-media.md +1 -1
- package/dist/playbooks/runtime-orientation.md +9 -8
- package/dist/playbooks/task-loop.md +110 -0
- package/dist/runtime/bootstrap.d.ts +3 -3
- package/dist/runtime/bootstrap.js +66 -41
- package/dist/runtime/events.d.ts +9 -0
- package/dist/runtime/events.js +43 -4
- package/dist/runtime/task-commands.d.ts +14 -15
- package/dist/runtime/task-commands.js +249 -485
- package/dist/runtime/task-driver.d.ts +41 -29
- package/dist/runtime/task-driver.js +170 -317
- package/dist/runtime/task-migration.d.ts +34 -30
- package/dist/runtime/task-migration.js +229 -183
- package/dist/runtime/task-wake.d.ts +6 -3
- package/dist/runtime/task-wake.js +26 -19
- package/dist/settings.d.ts +0 -29
- package/dist/settings.js +12 -35
- package/dist/shared/markdown-sections.d.ts +0 -1
- package/dist/shared/markdown-sections.js +0 -3
- package/dist/subagents/discovery.d.ts +2 -2
- package/dist/subagents/discovery.js +21 -10
- package/dist/subagents/external/progress-tail.js +6 -1
- package/dist/subagents/external/run.js +1 -0
- package/dist/subagents/runs.d.ts +19 -2
- package/dist/subagents/runs.js +73 -4
- package/dist/subagents/tool.d.ts +10 -8
- package/dist/subagents/tool.js +55 -94
- package/dist/tasks/brief.d.ts +17 -0
- package/dist/tasks/brief.js +57 -0
- package/dist/tasks/budget.d.ts +26 -0
- package/dist/tasks/budget.js +59 -0
- package/dist/tasks/cycle.d.ts +48 -0
- package/dist/tasks/cycle.js +94 -0
- package/dist/tasks/frontmatter.d.ts +73 -0
- package/dist/tasks/frontmatter.js +175 -0
- package/dist/tasks/ledger.d.ts +66 -106
- package/dist/tasks/ledger.js +90 -546
- package/dist/tasks/log.d.ts +88 -0
- package/dist/tasks/log.js +97 -0
- package/dist/tasks/rounds.d.ts +41 -0
- package/dist/tasks/rounds.js +53 -0
- package/dist/tasks/session-path.d.ts +9 -0
- package/dist/tasks/session-path.js +16 -0
- package/dist/tasks/steer.d.ts +8 -0
- package/dist/tasks/steer.js +79 -0
- package/dist/tasks/store.d.ts +60 -35
- package/dist/tasks/store.js +166 -107
- package/dist/tasks/ticket.d.ts +102 -0
- package/dist/tasks/ticket.js +209 -0
- package/dist/tasks/verification.d.ts +47 -0
- package/dist/tasks/verification.js +60 -1
- package/dist/tools/index.d.ts +13 -4
- package/dist/tools/index.js +5 -10
- package/dist/tools/memory-manage.d.ts +6 -16
- package/dist/tools/memory-manage.js +108 -129
- package/dist/tools/presentation.js +2 -1
- package/dist/tools/registry.d.ts +11 -2
- package/dist/tools/registry.js +17 -6
- package/dist/tools/subagent-manage.d.ts +0 -9
- package/dist/tools/subagent-manage.js +8 -17
- package/dist/tools/task-manage/create.js +2 -2
- package/dist/tools/task-manage/lifecycle.d.ts +9 -4
- package/dist/tools/task-manage/lifecycle.js +136 -188
- package/dist/tools/task-manage/log-view.d.ts +8 -0
- package/dist/tools/task-manage/log-view.js +24 -0
- package/dist/tools/task-manage/schema.d.ts +38 -14
- package/dist/tools/task-manage/schema.js +46 -27
- package/dist/tools/task-manage/shared.d.ts +35 -31
- package/dist/tools/task-manage/shared.js +130 -141
- package/dist/tools/task-manage/step-end.d.ts +11 -0
- package/dist/tools/task-manage/step-end.js +134 -0
- package/dist/tools/task-manage/types.d.ts +23 -32
- package/dist/tools/task-manage.d.ts +4 -3
- package/dist/tools/task-manage.js +30 -15
- package/dist/tools/tool-details.d.ts +1 -1
- package/dist/tui/app.js +0 -2
- package/examples/sub-agents/README.md +54 -38
- package/examples/sub-agents/builder-hard.md +21 -12
- package/examples/sub-agents/builder.md +24 -16
- package/examples/sub-agents/explorer.md +17 -15
- package/examples/sub-agents/git-committer.md +8 -6
- package/examples/sub-agents/planner.md +17 -16
- package/examples/sub-agents/reviewer.md +11 -9
- package/examples/sub-agents/verifier.md +22 -16
- package/examples/sub-agents/worker.md +22 -6
- package/package.json +1 -1
- package/dist/agent/effect-ledger.d.ts +0 -32
- package/dist/agent/effect-ledger.js +0 -89
- package/dist/memory/bootstrap.d.ts +0 -17
- package/dist/memory/bootstrap.js +0 -120
- package/dist/memory/candidates.d.ts +0 -26
- package/dist/memory/candidates.js +0 -202
- package/dist/memory/consolidation.d.ts +0 -54
- package/dist/memory/consolidation.js +0 -292
- package/dist/memory/extraction.d.ts +0 -54
- package/dist/memory/extraction.js +0 -240
- package/dist/memory/files.d.ts +0 -71
- package/dist/memory/files.js +0 -419
- package/dist/memory/maintenance-jobs.d.ts +0 -41
- package/dist/memory/maintenance-jobs.js +0 -265
- package/dist/memory/metadata.d.ts +0 -57
- package/dist/memory/metadata.js +0 -142
- package/dist/memory/probation.d.ts +0 -17
- package/dist/memory/probation.js +0 -44
- package/dist/memory/promotion.d.ts +0 -38
- package/dist/memory/promotion.js +0 -36
- package/dist/memory/recall.d.ts +0 -59
- package/dist/memory/recall.js +0 -746
- package/dist/memory/session.d.ts +0 -24
- package/dist/memory/session.js +0 -273
- package/dist/playbooks/task-driving.md +0 -92
- package/dist/playbooks/task-planning.md +0 -58
- package/dist/tasks/control.d.ts +0 -56
- package/dist/tasks/control.js +0 -169
- package/dist/tasks/transitions.d.ts +0 -16
- package/dist/tasks/transitions.js +0 -48
- package/dist/tools/task-manage/verification.d.ts +0 -19
- package/dist/tools/task-manage/verification.js +0 -91
- package/examples/sub-agents/documenter.md +0 -50
- package/examples/sub-agents/log-sifter.md +0 -47
- package/examples/sub-agents/scout.md +0 -34
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Agent } from "@earendil-works/pi-agent-core";
|
|
2
2
|
import { clampThinkingLevel, streamSimple } from "@earendil-works/pi-ai/compat";
|
|
3
|
-
import { AgentSession, AgentSessionRuntime, convertToLlm,
|
|
3
|
+
import { AgentSession, AgentSessionRuntime, convertToLlm, DefaultResourceLoader, SettingsManager as SDKSettingsManager, 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";
|
|
@@ -8,13 +8,14 @@ import { MAX_INBOUND_IMAGE_BYTES } from "../channel/channel-event.js";
|
|
|
8
8
|
import { resolveProjectScope } from "../channel/project-scope-store.js";
|
|
9
9
|
import { isKnownCommandName, renderBuiltInHelp, slashCommandName, } from "../commands/catalog.js";
|
|
10
10
|
import * as log from "../log.js";
|
|
11
|
-
import { buildFirstTurnMemoryBootstrapResult, FIRST_TURN_BOOTSTRAP_MAX_UNITS, } from "../memory/bootstrap.js";
|
|
12
|
-
import { createMemoryCandidateStore } from "../memory/candidates.js";
|
|
13
11
|
import { handleMemoryCommand } from "../memory/commands.js";
|
|
14
|
-
import {
|
|
12
|
+
import { buildChannelIndexForBootstrap, clipJournalTailForBootstrap, clipWorkspaceMemoryForBootstrap, } from "../memory/index-budget.js";
|
|
13
|
+
import { readJournalDay } from "../memory/journal.js";
|
|
15
14
|
import { MemoryLifecycle } from "../memory/lifecycle.js";
|
|
16
15
|
import { createMemoryActivityRecorder, } from "../memory/maintenance-state.js";
|
|
17
|
-
import {
|
|
16
|
+
import { isChannelMigratedToV2, migrateChannelMemoryToV2 } from "../memory/migrate.js";
|
|
17
|
+
import { hasMemoryBootstrapBlock, renderMemoryBootstrap } from "../memory/render.js";
|
|
18
|
+
import { listMemoryEntries } from "../memory/store.js";
|
|
18
19
|
import { buildTaskDigest, TASK_AGENDA_MAX_UNITS } from "../memory/task-digest.js";
|
|
19
20
|
import { getApiKeyForModel } from "../models/api-keys.js";
|
|
20
21
|
import { createModelRuntime, defaultModel, findExactModelReferenceMatch, formatModelReference, hasKnownModelPricing, resolveInitialModel, wrapModelRegistry, } from "../models/utils.js";
|
|
@@ -22,11 +23,12 @@ import { loadRuntimePlaybookCatalog, selectRuntimePlaybooks } from "../playbooks
|
|
|
22
23
|
import { resolveProjectAccessPolicy } from "../security/project-scope.js";
|
|
23
24
|
import { TASK_DIGEST_SETTINGS } from "../settings.js";
|
|
24
25
|
import { formatConfigDiagnostic } from "../shared/config-diagnostic.js";
|
|
25
|
-
import { formatLocalTime, localStampForFilename, parseLocalTime } from "../shared/local-time.js";
|
|
26
|
+
import { formatLocalTime, localDayKey, localStampForFilename, parseLocalTime } from "../shared/local-time.js";
|
|
26
27
|
import { errorMessage } from "../shared/text-utils.js";
|
|
27
28
|
import { isRecord } from "../shared/type-guards.js";
|
|
28
29
|
import { withTimeout } from "../shared/with-timeout.js";
|
|
29
30
|
import { discoverSubAgents } from "../subagents/discovery.js";
|
|
31
|
+
import { TASK_SESSIONS_DIRNAME, taskSessionPath } from "../tasks/session-path.js";
|
|
30
32
|
import { loadToolsConfigWithDiagnostics } from "../tools/config.js";
|
|
31
33
|
import { createPipiclawTools } from "../tools/index.js";
|
|
32
34
|
import { formatSize } from "../tools/truncate.js";
|
|
@@ -45,7 +47,7 @@ import { SessionResourceGate } from "./session-resource-gate.js";
|
|
|
45
47
|
import { assembleTurnPrompt } from "./turn-prompt.js";
|
|
46
48
|
import { recoverInterruptedTurn } from "./turn-recovery.js";
|
|
47
49
|
import { TurnStateMachine } from "./turn-state.js";
|
|
48
|
-
import { getLastAssistantUsage } from "./type-guards.js";
|
|
50
|
+
import { getLastAssistantUsage, isAutoCompactionEndEvent } from "./type-guards.js";
|
|
49
51
|
import { createEmptyRunState, MAX_USER_MESSAGE_CHARS, } from "./types.js";
|
|
50
52
|
import { loadPipiclawSkills, resolvePipiclawSkills } from "./workspace-resources.js";
|
|
51
53
|
function isSilentOutcome(outcome) {
|
|
@@ -126,6 +128,20 @@ export function initializeThinkingLevelCompat(agent, model, sessionManager, conf
|
|
|
126
128
|
*/
|
|
127
129
|
const MODEL_REGISTRY_REFRESH_TIMEOUT_MS = 15_000;
|
|
128
130
|
const SESSION_RELOAD_TIMEOUT_MS = 30_000;
|
|
131
|
+
/** The text of a message's `content`, whether it is a bare string or a multimodal part array. */
|
|
132
|
+
function plainTextOf(content) {
|
|
133
|
+
if (typeof content === "string")
|
|
134
|
+
return content;
|
|
135
|
+
if (!Array.isArray(content))
|
|
136
|
+
return "";
|
|
137
|
+
return content
|
|
138
|
+
.map((part) => (isRecord(part) && part.type === "text" && typeof part.text === "string" ? part.text : ""))
|
|
139
|
+
.join("\n");
|
|
140
|
+
}
|
|
141
|
+
/** Task sessions live under `<channelDir>/tasks/.sessions/`; nothing else may be mistaken for one. */
|
|
142
|
+
function isTaskSessionPath(sessionFile) {
|
|
143
|
+
return sessionFile?.replace(/\\/g, "/").includes(`/${TASK_SESSIONS_DIRNAME}/`) === true;
|
|
144
|
+
}
|
|
129
145
|
export class ChannelRunner {
|
|
130
146
|
constructor(channelId, channelDir, paths, deps) {
|
|
131
147
|
this.ledger = getUsageLedger();
|
|
@@ -148,6 +164,8 @@ export class ChannelRunner {
|
|
|
148
164
|
this.primaryFailedAt = null;
|
|
149
165
|
// --- Per run ---
|
|
150
166
|
this.runState = createEmptyRunState();
|
|
167
|
+
/** Spec 050 §5: migrate this channel's memory to v2 on first use, before any turn reads it. */
|
|
168
|
+
this.memoryMigrationChecked = false;
|
|
151
169
|
this.channelId = channelId;
|
|
152
170
|
this.channelDir = channelDir;
|
|
153
171
|
this.appHomeDir = paths.appHomeDir;
|
|
@@ -200,7 +218,6 @@ export class ChannelRunner {
|
|
|
200
218
|
}
|
|
201
219
|
this.settingsManager = paths.settingsManager;
|
|
202
220
|
this.reportSettingsDiagnostics();
|
|
203
|
-
this.memoryCandidateStore = createMemoryCandidateStore();
|
|
204
221
|
this.memoryActivityRecorder = createMemoryActivityRecorder({
|
|
205
222
|
appHomeDir: this.appHomeDir,
|
|
206
223
|
onError: (channelId, error) => log.logWarning(`[${channelId}] Failed to record memory maintenance state`, errorMessage(error)),
|
|
@@ -224,12 +241,12 @@ export class ChannelRunner {
|
|
|
224
241
|
this.memoryLifecycle = new MemoryLifecycle({
|
|
225
242
|
channelId: this.channelId,
|
|
226
243
|
channelDir: this.channelDir,
|
|
244
|
+
workspaceDir: this.workspaceDir,
|
|
227
245
|
appHomeDir: this.appHomeDir,
|
|
228
246
|
getMessages: () => this.session.messages,
|
|
229
247
|
getSessionEntries: () => this.sessionManager.getBranch(),
|
|
230
248
|
getModel: () => this.session.model ?? this.activeModel,
|
|
231
249
|
resolveApiKey: async (model) => getApiKeyForModel(this.modelRegistry, model),
|
|
232
|
-
getSessionMemorySettings: () => this.settingsManager.getSessionMemorySettings(),
|
|
233
250
|
recordMemoryActivity: (event) => this.recordMemoryActivity(event),
|
|
234
251
|
});
|
|
235
252
|
this.sessionResourceGate = new SessionResourceGate(async () => {
|
|
@@ -276,14 +293,13 @@ export class ChannelRunner {
|
|
|
276
293
|
let fallbackTargetRef;
|
|
277
294
|
// Hoisted so the debug dump in `finally` can report the turn as it was actually sent.
|
|
278
295
|
let promptText = "";
|
|
279
|
-
let recalledContextText = "";
|
|
280
296
|
let taskDigestText = "";
|
|
281
297
|
let durableMemoryBootstrapText = "";
|
|
282
298
|
let channelCapsuleText = "";
|
|
283
|
-
let bootstrapCandidateIds = [];
|
|
284
299
|
let bootstrapPrepared = false;
|
|
285
300
|
try {
|
|
286
301
|
await this.ensureSessionReady();
|
|
302
|
+
await this.ensureMemoryMigrated();
|
|
287
303
|
await this.maybeRestorePrimaryModel();
|
|
288
304
|
this.memoryLifecycle.noteUserTurnStarted();
|
|
289
305
|
const normalizedInputLength = ctx.message.text.replace(/\r/g, "").trim().length;
|
|
@@ -304,47 +320,19 @@ export class ChannelRunner {
|
|
|
304
320
|
// system prompt is what lets every channel in a workspace share one cached prefix.
|
|
305
321
|
channelCapsuleText = this.renderChannelTurnContext();
|
|
306
322
|
// The task digest reads the whole tasks/ directory and depends on nothing the memory
|
|
307
|
-
//
|
|
308
|
-
//
|
|
309
|
-
//
|
|
310
|
-
//
|
|
311
|
-
//
|
|
323
|
+
// bootstrap below produces, so it runs alongside it rather than queuing behind it.
|
|
324
|
+
// Settled into a result object rather than left as a bare promise: if the bootstrap
|
|
325
|
+
// throws first we would otherwise leave a rejection unobserved, which Node's default
|
|
326
|
+
// policy turns into a process exit. Rethrown at the await, so a digest failure still
|
|
327
|
+
// fails the turn exactly as it did when this ran inline.
|
|
312
328
|
const taskDigestPromise = (this.tasksEnabled ? this.buildTaskDigestForTurn() : Promise.resolve("")).then((text) => ({ text }), (error) => ({ error }));
|
|
329
|
+
// Spec 050, D1: the memory index is injected in full on the first turn of a session
|
|
330
|
+
// (and the first turn after compaction — see `subscribeToSessionEvents`), never per
|
|
331
|
+
// turn. Mid-session, the model uses `memory_search` to look things up.
|
|
313
332
|
if (this.firstTurnMemoryBootstrapPending) {
|
|
314
|
-
|
|
315
|
-
durableMemoryBootstrapText = bootstrap.renderedText;
|
|
316
|
-
bootstrapCandidateIds = bootstrap.includedCandidateIds;
|
|
333
|
+
durableMemoryBootstrapText = await this.buildFirstTurnMemoryBootstrap();
|
|
317
334
|
bootstrapPrepared = true;
|
|
318
335
|
}
|
|
319
|
-
const recallSettings = this.settingsManager.getMemoryRecallSettings();
|
|
320
|
-
if (recallSettings.enabled) {
|
|
321
|
-
const recall = await recallRelevantMemory({
|
|
322
|
-
query: clippedInput,
|
|
323
|
-
contextQuery: findPreviousUserText(this.session.messages),
|
|
324
|
-
channelId: this.channelId,
|
|
325
|
-
workspaceDir: this.workspaceDir,
|
|
326
|
-
channelDir: this.channelDir,
|
|
327
|
-
maxCandidates: recallSettings.maxCandidates,
|
|
328
|
-
maxInjected: recallSettings.maxInjected,
|
|
329
|
-
maxChars: recallSettings.maxChars,
|
|
330
|
-
// The configured char cap and the runtime unit cap both apply; first to bind clips.
|
|
331
|
-
maxUnits: MEMORY_RECALL_MAX_UNITS,
|
|
332
|
-
rerankWithModel: recallSettings.rerankWithModel,
|
|
333
|
-
excludedCandidateIds: bootstrapCandidateIds,
|
|
334
|
-
// `rerankWithModel` is passed through as configured; `shouldUseModelRerank`
|
|
335
|
-
// owns the decision. Under "auto" it reranks whenever the shortlist is
|
|
336
|
-
// over-full *and* the local ranking has no clear winner — script-independent,
|
|
337
|
-
// so a Chinese turn is treated exactly like an English one. That rerank is an
|
|
338
|
-
// LLM call on the critical path of the turn, capped at
|
|
339
|
-
// MEMORY_RECALL_RERANK_TIMEOUT_MS and failing open to the local ranking.
|
|
340
|
-
model: this.session.model ?? this.activeModel,
|
|
341
|
-
resolveApiKey: async (model) => getApiKeyForModel(this.modelRegistry, model),
|
|
342
|
-
candidateStore: this.memoryCandidateStore,
|
|
343
|
-
});
|
|
344
|
-
if (recall.renderedText) {
|
|
345
|
-
recalledContextText = recall.renderedText;
|
|
346
|
-
}
|
|
347
|
-
}
|
|
348
336
|
const taskDigestResult = await taskDigestPromise;
|
|
349
337
|
if (taskDigestResult.error !== undefined) {
|
|
350
338
|
throw taskDigestResult.error;
|
|
@@ -358,7 +346,6 @@ export class ChannelRunner {
|
|
|
358
346
|
channelCapsule: channelCapsuleText,
|
|
359
347
|
durableMemoryBootstrap: durableMemoryBootstrapText,
|
|
360
348
|
taskDigest: taskDigestText,
|
|
361
|
-
recalledMemory: recalledContextText,
|
|
362
349
|
});
|
|
363
350
|
promptText = assembled.text;
|
|
364
351
|
// Resolved before the compaction estimate below (which needs the image count) and
|
|
@@ -462,7 +449,6 @@ export class ChannelRunner {
|
|
|
462
449
|
promptText,
|
|
463
450
|
durableMemoryBootstrapText,
|
|
464
451
|
taskDigestText,
|
|
465
|
-
recalledContextText,
|
|
466
452
|
});
|
|
467
453
|
}
|
|
468
454
|
return {
|
|
@@ -496,7 +482,6 @@ export class ChannelRunner {
|
|
|
496
482
|
messages: this.session.messages,
|
|
497
483
|
durableMemoryBootstrap: input.durableMemoryBootstrapText || undefined,
|
|
498
484
|
taskDigest: input.taskDigestText || undefined,
|
|
499
|
-
recalledContext: input.recalledContextText || undefined,
|
|
500
485
|
newUserMessage: input.promptText,
|
|
501
486
|
};
|
|
502
487
|
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)));
|
|
@@ -716,16 +701,14 @@ export class ChannelRunner {
|
|
|
716
701
|
return {
|
|
717
702
|
channelId: this.channelId,
|
|
718
703
|
channelDir: this.channelDir,
|
|
704
|
+
workspaceDir: this.workspaceDir,
|
|
719
705
|
// Snapshot only when a maintenance job actually needs the transcript; most ticks
|
|
720
706
|
// stop at a schedule gate and never call these.
|
|
721
707
|
messages: () => [...this.session.messages],
|
|
722
708
|
sessionEntries: () => [...this.sessionManager.getBranch()],
|
|
723
709
|
model: this.session.model ?? this.activeModel,
|
|
724
710
|
resolveApiKey: async (model) => getApiKeyForModel(this.modelRegistry, model),
|
|
725
|
-
settings: {
|
|
726
|
-
sessionMemory: this.settingsManager.getSessionMemorySettings(),
|
|
727
|
-
memoryMaintenance: this.settingsManager.getMemoryMaintenanceSettings(),
|
|
728
|
-
},
|
|
711
|
+
settings: { memoryMaintenance: this.settingsManager.getMemoryMaintenanceSettings() },
|
|
729
712
|
};
|
|
730
713
|
}
|
|
731
714
|
getStatusSnapshot() {
|
|
@@ -835,7 +818,7 @@ export class ChannelRunner {
|
|
|
835
818
|
return [
|
|
836
819
|
"<runtime_turn_context>",
|
|
837
820
|
`Channel directory: ${this.channelDir}`,
|
|
838
|
-
"
|
|
821
|
+
"The channel `MEMORY.md` index, `memory/`, `journal/` and `tasks/` live there. 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.",
|
|
839
822
|
"</runtime_turn_context>",
|
|
840
823
|
].join("\n");
|
|
841
824
|
}
|
|
@@ -1104,11 +1087,16 @@ export class ChannelRunner {
|
|
|
1104
1087
|
// the pointer before we rebuild and rebind to it, so a crash between "SDK created
|
|
1105
1088
|
// session" and "we finished rebinding" leaves the old ref (and old session)
|
|
1106
1089
|
// authoritative rather than an orphaned new file (spec 043, D1.3).
|
|
1107
|
-
|
|
1108
|
-
|
|
1090
|
+
// A task session is not the channel's chat session: never repoint the active-session
|
|
1091
|
+
// ref at it, or `/new` and restart recovery would adopt a task's transcript as the
|
|
1092
|
+
// conversation (spec 051, D3).
|
|
1093
|
+
if (!isTaskSessionPath(sessionManager.getSessionFile())) {
|
|
1094
|
+
await commitActiveSessionRef(this.channelDir, sessionManager);
|
|
1095
|
+
}
|
|
1096
|
+
const next = await this.createSessionRuntime(sessionManager, sessionStartEvent);
|
|
1109
1097
|
return {
|
|
1110
1098
|
session: next.session,
|
|
1111
|
-
extensionsResult:
|
|
1099
|
+
extensionsResult: next.resourceLoader.getExtensions(),
|
|
1112
1100
|
services: this.createAgentSessionServices(next.resourceLoader),
|
|
1113
1101
|
diagnostics: [],
|
|
1114
1102
|
};
|
|
@@ -1124,6 +1112,10 @@ export class ChannelRunner {
|
|
|
1124
1112
|
this.subscribeToSessionEvents();
|
|
1125
1113
|
await this.reloadSessionResources();
|
|
1126
1114
|
await this.bindSessionExtensions();
|
|
1115
|
+
// A restart resumes an existing transcript: if that session was already handed its
|
|
1116
|
+
// bootstrap before the daemon went down, the first turn after recovery must not inject a
|
|
1117
|
+
// second copy just because a process-local field starts out `true`.
|
|
1118
|
+
this.syncMemoryBootstrapPendingFromSession();
|
|
1127
1119
|
this.sessionInitialized = true;
|
|
1128
1120
|
}
|
|
1129
1121
|
async reloadSessionResources() {
|
|
@@ -1149,14 +1141,18 @@ export class ChannelRunner {
|
|
|
1149
1141
|
},
|
|
1150
1142
|
fork: async (entryId, options) => {
|
|
1151
1143
|
const result = await this.sessionRuntime.fork(entryId, options);
|
|
1144
|
+
this.syncMemoryBootstrapPendingFromSession();
|
|
1152
1145
|
return { cancelled: result.cancelled };
|
|
1153
1146
|
},
|
|
1154
1147
|
navigateTree: async (targetId, options) => {
|
|
1155
1148
|
const result = await this.session.navigateTree(targetId, options);
|
|
1149
|
+
this.syncMemoryBootstrapPendingFromSession();
|
|
1156
1150
|
return { cancelled: result.cancelled };
|
|
1157
1151
|
},
|
|
1158
1152
|
switchSession: async (sessionPath, options) => {
|
|
1159
|
-
|
|
1153
|
+
const result = await this.sessionRuntime.switchSession(sessionPath, options);
|
|
1154
|
+
this.syncMemoryBootstrapPendingFromSession();
|
|
1155
|
+
return result;
|
|
1160
1156
|
},
|
|
1161
1157
|
reload: async () => {
|
|
1162
1158
|
await this.refreshSessionResources();
|
|
@@ -1167,6 +1163,24 @@ export class ChannelRunner {
|
|
|
1167
1163
|
async ensureSessionReady() {
|
|
1168
1164
|
await this.sessionReady;
|
|
1169
1165
|
}
|
|
1166
|
+
async ensureMemoryMigrated() {
|
|
1167
|
+
if (this.memoryMigrationChecked) {
|
|
1168
|
+
return;
|
|
1169
|
+
}
|
|
1170
|
+
this.memoryMigrationChecked = true;
|
|
1171
|
+
if (isChannelMigratedToV2(this.channelDir)) {
|
|
1172
|
+
return;
|
|
1173
|
+
}
|
|
1174
|
+
try {
|
|
1175
|
+
const result = await migrateChannelMemoryToV2(this.channelDir);
|
|
1176
|
+
if (result.migrated) {
|
|
1177
|
+
log.logInfo(`[${this.channelId}] Migrated channel memory to v2 (${result.entries} entries, ${result.journalDays} journal days)`);
|
|
1178
|
+
}
|
|
1179
|
+
}
|
|
1180
|
+
catch (error) {
|
|
1181
|
+
log.logWarning(`[${this.channelId}] Channel memory v2 migration failed`, errorMessage(error));
|
|
1182
|
+
}
|
|
1183
|
+
}
|
|
1170
1184
|
async maybeRunPreventiveCompactionForIncomingText(incomingText, imageCount = 0) {
|
|
1171
1185
|
const currentModel = this.session.model ?? this.activeModel;
|
|
1172
1186
|
const contextUsage = this.session.getContextUsage();
|
|
@@ -1297,7 +1311,12 @@ export class ChannelRunner {
|
|
|
1297
1311
|
refreshSessionResources: async () => {
|
|
1298
1312
|
await this.refreshSessionResources();
|
|
1299
1313
|
},
|
|
1300
|
-
runMemoryCommand: async (args) => handleMemoryCommand({
|
|
1314
|
+
runMemoryCommand: async (args) => handleMemoryCommand({
|
|
1315
|
+
channelId: this.channelId,
|
|
1316
|
+
channelDir: this.channelDir,
|
|
1317
|
+
appHomeDir: this.appHomeDir,
|
|
1318
|
+
args,
|
|
1319
|
+
}),
|
|
1301
1320
|
}),
|
|
1302
1321
|
],
|
|
1303
1322
|
// Pipiclaw owns the base prompt: with a custom prompt present, pi emits no
|
|
@@ -1328,12 +1347,23 @@ export class ChannelRunner {
|
|
|
1328
1347
|
diagnostics: [],
|
|
1329
1348
|
};
|
|
1330
1349
|
}
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1350
|
+
/**
|
|
1351
|
+
* Load a freshly constructed ResourceLoader before an `AgentSession` is built on top of it.
|
|
1352
|
+
*
|
|
1353
|
+
* `AgentSession` reads `resourceLoader.getExtensions()` in its constructor, and a loader that
|
|
1354
|
+
* has never been loaded answers with an *empty* set. Skipping this leaves a replacement session
|
|
1355
|
+
* with no extensions at all — no command extension (so `/model`, `/thinking`, `/session`,
|
|
1356
|
+
* `/compact` and `/memory` fall through to the model as plain text), no memory lifecycle, no
|
|
1357
|
+
* prompt-boundary footer, and no prompt templates. Tolerated on failure the same way
|
|
1358
|
+
* `reloadSessionResources` tolerates a stuck reload: a degraded session still answers chat.
|
|
1359
|
+
*/
|
|
1360
|
+
async loadSessionResources(resourceLoader) {
|
|
1361
|
+
try {
|
|
1362
|
+
await withTimeout(`[${this.channelId}] session resource load`, SESSION_RELOAD_TIMEOUT_MS, () => resourceLoader.reload());
|
|
1363
|
+
}
|
|
1364
|
+
catch (error) {
|
|
1365
|
+
log.logWarning(`[${this.channelId}] Session resources did not load`, errorMessage(error));
|
|
1366
|
+
}
|
|
1337
1367
|
}
|
|
1338
1368
|
/**
|
|
1339
1369
|
* Resolve the initial thinking level using the same precedence as pi's SDK:
|
|
@@ -1343,7 +1373,7 @@ export class ChannelRunner {
|
|
|
1343
1373
|
initializeThinkingLevel(agent, model, sessionManager) {
|
|
1344
1374
|
initializeThinkingLevelCompat(agent, model, sessionManager, this.settingsManager.getDefaultThinkingLevel());
|
|
1345
1375
|
}
|
|
1346
|
-
createSessionRuntime(sessionManager, sessionStartEvent) {
|
|
1376
|
+
async createSessionRuntime(sessionManager, sessionStartEvent) {
|
|
1347
1377
|
const tools = this.buildRuntimeTools();
|
|
1348
1378
|
const agent = new Agent({
|
|
1349
1379
|
initialState: {
|
|
@@ -1358,6 +1388,9 @@ export class ChannelRunner {
|
|
|
1358
1388
|
});
|
|
1359
1389
|
this.initializeThinkingLevel(agent, this.activeModel, sessionManager);
|
|
1360
1390
|
const resourceLoader = this.createResourceLoader();
|
|
1391
|
+
// Must precede `new AgentSession`: the session snapshots the loader's extensions in its
|
|
1392
|
+
// constructor (see `loadSessionResources`).
|
|
1393
|
+
await this.loadSessionResources(resourceLoader);
|
|
1361
1394
|
const sessionSettingsManager = asSdkSettingsManager(this.settingsManager);
|
|
1362
1395
|
const session = new AgentSession({
|
|
1363
1396
|
agent,
|
|
@@ -1372,6 +1405,60 @@ export class ChannelRunner {
|
|
|
1372
1405
|
this.sessionSettingsManager = sessionSettingsManager;
|
|
1373
1406
|
return { agent, session, resourceLoader };
|
|
1374
1407
|
}
|
|
1408
|
+
/**
|
|
1409
|
+
* Bind this runner to a task cycle's own session (spec 051, D3/INV-5).
|
|
1410
|
+
*
|
|
1411
|
+
* Task work must not accumulate in the channel's chat transcript: the one real channel on the
|
|
1412
|
+
* author's machine had grown to 7.4 MB and been compacted six times because chat and two daily
|
|
1413
|
+
* tasks shared it, so every compaction damaged all three at once. Swapping the bound session
|
|
1414
|
+
* per turn gives each cycle its own bounded context while leaving turn state, `/stop`, and
|
|
1415
|
+
* delivery exactly where they already are.
|
|
1416
|
+
*/
|
|
1417
|
+
async bindTaskSession(taskId, cycleId) {
|
|
1418
|
+
await this.sessionReady;
|
|
1419
|
+
const path = taskSessionPath(this.channelDir, taskId, cycleId);
|
|
1420
|
+
await mkdir(dirname(path), { recursive: true });
|
|
1421
|
+
this.taskLoop = { taskId, cycleId };
|
|
1422
|
+
await this.sessionRuntime.switchSession(path);
|
|
1423
|
+
this.syncMemoryBootstrapPendingFromSession();
|
|
1424
|
+
}
|
|
1425
|
+
/** Return to the channel's chat session after a task step. Safe to call when already bound. */
|
|
1426
|
+
async bindChatSession() {
|
|
1427
|
+
if (!this.taskLoop)
|
|
1428
|
+
return;
|
|
1429
|
+
this.taskLoop = undefined;
|
|
1430
|
+
await this.sessionRuntime.switchSession(join(this.channelDir, resolveActiveSessionFile(this.channelDir)));
|
|
1431
|
+
this.syncMemoryBootstrapPendingFromSession();
|
|
1432
|
+
}
|
|
1433
|
+
/**
|
|
1434
|
+
* Re-derive "does this session still owe a memory bootstrap" from the session now bound.
|
|
1435
|
+
*
|
|
1436
|
+
* The pending flag used to be set to `true` on every bind, which is right for a fresh task
|
|
1437
|
+
* session and wrong for the return trip: a chat session that already carries the block would
|
|
1438
|
+
* be handed a second copy on its next turn, and one interleaved task step could therefore cost
|
|
1439
|
+
* the whole index again. It was also wrong across a restart, where the field simply starts
|
|
1440
|
+
* `true` and the resumed session's own history says otherwise.
|
|
1441
|
+
*
|
|
1442
|
+
* So the answer comes from the transcript that will actually be sent, not from a boolean that
|
|
1443
|
+
* has to be kept in step with every binding. The `/new` and post-compaction resets in
|
|
1444
|
+
* `subscribeToSessionEvents` stay as they are: those are the SDK telling us the context
|
|
1445
|
+
* generation changed, which is a fact about the session that its message list alone —
|
|
1446
|
+
* compaction having rewritten it into a summary — cannot be scanned for reliably.
|
|
1447
|
+
*/
|
|
1448
|
+
syncMemoryBootstrapPendingFromSession() {
|
|
1449
|
+
// `session.messages` is empty until the session actually runs a turn, so the answer comes
|
|
1450
|
+
// from the persisted branch — which is also what makes this correct across a restart.
|
|
1451
|
+
const injected = this.sessionManager.getBranch().some((entry) => {
|
|
1452
|
+
if (!isRecord(entry) || entry.type !== "message" || !isRecord(entry.message))
|
|
1453
|
+
return false;
|
|
1454
|
+
return entry.message.role === "user" && hasMemoryBootstrapBlock(plainTextOf(entry.message.content));
|
|
1455
|
+
});
|
|
1456
|
+
this.firstTurnMemoryBootstrapPending = !injected;
|
|
1457
|
+
}
|
|
1458
|
+
/** Which task loop this runner is currently bound to, if any. */
|
|
1459
|
+
getTaskLoop() {
|
|
1460
|
+
return this.taskLoop;
|
|
1461
|
+
}
|
|
1375
1462
|
buildRuntimeTools() {
|
|
1376
1463
|
const securityLoad = this.loadSecurityConfig();
|
|
1377
1464
|
const toolsLoad = loadToolsConfigWithDiagnostics(this.appHomeDir);
|
|
@@ -1388,13 +1475,13 @@ export class ChannelRunner {
|
|
|
1388
1475
|
channelDir: this.channelDir,
|
|
1389
1476
|
channelId: this.channelId,
|
|
1390
1477
|
getSubAgentDiscovery: () => this.subAgentDiscovery,
|
|
1391
|
-
getMemoryRecallSettings: () => this.settingsManager.getMemoryRecallSettings(),
|
|
1392
1478
|
getSubAgentModelReference: () => this.settingsManager.getSubAgentModelReference(),
|
|
1393
1479
|
getSessionSearchSettings: () => this.settingsManager.getSessionSearchSettings(),
|
|
1394
|
-
memoryCandidateStore: this.memoryCandidateStore,
|
|
1395
1480
|
securityConfig: securityLoad.config,
|
|
1396
1481
|
toolsConfig: toolsLoad.config,
|
|
1397
1482
|
mediaSender: this.mediaSender,
|
|
1483
|
+
taskLoop: this.taskLoop,
|
|
1484
|
+
getToolsUsed: () => this.runState.toolsUsed,
|
|
1398
1485
|
});
|
|
1399
1486
|
this.currentTools = tools;
|
|
1400
1487
|
// Tool schemas are billed with the system prompt and, unlike it, nothing trims them.
|
|
@@ -1442,6 +1529,11 @@ export class ChannelRunner {
|
|
|
1442
1529
|
if (isRecord(event) && "reason" in event && event.reason === "new") {
|
|
1443
1530
|
this.firstTurnMemoryBootstrapPending = true;
|
|
1444
1531
|
}
|
|
1532
|
+
// Spec 050, D1: compaction rewrites the first-turn bootstrap into a summary; re-inject
|
|
1533
|
+
// the authoritative index on the next turn so memory does not decay with the transcript.
|
|
1534
|
+
if (isAutoCompactionEndEvent(event) && !event.aborted && !event.errorMessage) {
|
|
1535
|
+
this.firstTurnMemoryBootstrapPending = true;
|
|
1536
|
+
}
|
|
1445
1537
|
if (!this.runState.ctx || !this.runState.logCtx || !this.runState.queue)
|
|
1446
1538
|
return;
|
|
1447
1539
|
// The SDK listener signature is `(event) => void`, so the promise below is fire-and-forget.
|
|
@@ -1478,6 +1570,11 @@ export class ChannelRunner {
|
|
|
1478
1570
|
maxUnits: TASK_AGENDA_MAX_UNITS,
|
|
1479
1571
|
});
|
|
1480
1572
|
}
|
|
1573
|
+
/**
|
|
1574
|
+
* Spec 050, D1: assemble `<memory_bootstrap>` for the first turn of a session — workspace
|
|
1575
|
+
* MEMORY.md (whole H2 sections, budgeted) + the channel index (full, or budget-tiered). The
|
|
1576
|
+
* journal subsection is added in P2.
|
|
1577
|
+
*/
|
|
1481
1578
|
async buildFirstTurnMemoryBootstrap() {
|
|
1482
1579
|
const readOptionalFile = async (path) => {
|
|
1483
1580
|
try {
|
|
@@ -1487,14 +1584,18 @@ export class ChannelRunner {
|
|
|
1487
1584
|
return "";
|
|
1488
1585
|
}
|
|
1489
1586
|
};
|
|
1490
|
-
const
|
|
1491
|
-
|
|
1587
|
+
const today = localDayKey();
|
|
1588
|
+
const [entries, workspaceMemory, journalToday] = await Promise.all([
|
|
1589
|
+
listMemoryEntries(this.channelDir).catch(() => []),
|
|
1492
1590
|
readOptionalFile(join(this.workspaceDir, "MEMORY.md")),
|
|
1591
|
+
readJournalDay(this.channelDir, today).catch(() => ""),
|
|
1493
1592
|
]);
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1593
|
+
const index = buildChannelIndexForBootstrap(entries);
|
|
1594
|
+
const journalTail = clipJournalTailForBootstrap(journalToday);
|
|
1595
|
+
return renderMemoryBootstrap({
|
|
1596
|
+
workspaceMemory: clipWorkspaceMemoryForBootstrap(workspaceMemory),
|
|
1597
|
+
channelIndex: entries.length > 0 ? index.text : "",
|
|
1598
|
+
journal: journalTail ? { date: today, text: journalTail } : undefined,
|
|
1498
1599
|
});
|
|
1499
1600
|
}
|
|
1500
1601
|
}
|
|
@@ -6,11 +6,12 @@ import { type FileStore } from "../file-store.js";
|
|
|
6
6
|
* the channel's run queue for its whole duration, blocking `/steer`, `/followup`, and every other
|
|
7
7
|
* message. A background job instead returns immediately and the model can end its turn.
|
|
8
8
|
*
|
|
9
|
-
* Jobs live on the host, managed through shell commands (`
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
* and
|
|
9
|
+
* Jobs live on the host, managed through shell commands (`setsid` to launch as its own process
|
|
10
|
+
* group with a startup handshake, a three-state identity probe, a confirmed kill) with no
|
|
11
|
+
* in-process child handles. Records
|
|
12
|
+
* are mirrored to `state/jobs/<channelId>/<id>.json` so they survive a restart: a detached
|
|
13
|
+
* process outlives the daemon, and losing the record while the process kept running meant orphaned
|
|
14
|
+
* work, leaked slots, and unreachable output (spec 031, D6).
|
|
14
15
|
*
|
|
15
16
|
* A finished job wakes its channel by itself. Making the model predict a completion time and
|
|
16
17
|
* arrange its own callback was a judgement call it could not make correctly, so completion is a
|
|
@@ -38,6 +39,14 @@ export interface JobWakeContract {
|
|
|
38
39
|
}
|
|
39
40
|
interface JobRecord extends JobSnapshot {
|
|
40
41
|
pid: number;
|
|
42
|
+
/** Process-group id of the launched job, as `ps` reported it right after spawn. `setsid` makes
|
|
43
|
+
* the job its own session/group leader, so this normally equals `pid` — the precondition for a
|
|
44
|
+
* safe negative-PGID kill. Absent on records written before this was captured. */
|
|
45
|
+
pgid?: number;
|
|
46
|
+
/** `ps -o lstart=` for `pid` at launch: the only OS-verifiable way to tell the still-running
|
|
47
|
+
* job apart from an unrelated process that later reused its pid. Absent on older records and
|
|
48
|
+
* whenever `ps` was unavailable at launch — callers must then treat identity as unprovable. */
|
|
49
|
+
pidStartedAt?: string;
|
|
41
50
|
spillFile: string;
|
|
42
51
|
exitFile: string;
|
|
43
52
|
timeoutSeconds: number;
|
|
@@ -46,6 +55,12 @@ interface JobRecord extends JobSnapshot {
|
|
|
46
55
|
finishedAt?: number;
|
|
47
56
|
/** Set once the completion wake has been dispatched, so a restart cannot re-announce it. */
|
|
48
57
|
notified?: boolean;
|
|
58
|
+
/**
|
|
59
|
+
* A cancel or timeout whose kill could not be *confirmed* yet: the job stays `running` and
|
|
60
|
+
* manageable, and every sweep re-attempts the kill until the process is proven gone, at which
|
|
61
|
+
* point this terminal status is applied. Internal only — never surfaced in a `JobSnapshot`.
|
|
62
|
+
*/
|
|
63
|
+
pendingKill?: "cancelled" | "failed";
|
|
49
64
|
wakeClaimDispatchId?: string;
|
|
50
65
|
wakeConsumedAt?: number;
|
|
51
66
|
}
|
|
@@ -86,6 +101,14 @@ export declare class ChannelJobManager {
|
|
|
86
101
|
private readonly executor;
|
|
87
102
|
private readonly jobs;
|
|
88
103
|
private readonly wakeQueue;
|
|
104
|
+
/**
|
|
105
|
+
* Serializes every probe → decide → terminal-transition sequence for a single job. The sweeper,
|
|
106
|
+
* `list`/`poll`/`restore` (via `refresh`), `cancel`, and the persist-failure rollback all pass
|
|
107
|
+
* through it, so two callers can never race the same job to two terminal states (e.g. both see
|
|
108
|
+
* `pendingKill`, both `finish`, the second reading a now-cleared `pendingKill` and writing a
|
|
109
|
+
* bogus status). Inside the slot each op re-checks `record.status`.
|
|
110
|
+
*/
|
|
111
|
+
private readonly reconcileQueue;
|
|
89
112
|
private sweepTimer?;
|
|
90
113
|
private garbageCollectionTimer?;
|
|
91
114
|
private sweeping;
|
|
@@ -97,6 +120,8 @@ export declare class ChannelJobManager {
|
|
|
97
120
|
/** Mirror a record to disk. Persistence is best-effort: it must never fail a job operation. */
|
|
98
121
|
private persist;
|
|
99
122
|
private forget;
|
|
123
|
+
/** Remove a job's scratch files (and optionally its persisted record). Every unlink is best-effort. */
|
|
124
|
+
private unlinkArtifacts;
|
|
100
125
|
/**
|
|
101
126
|
* Drop finished jobs whose retention window has passed, together with their spill files.
|
|
102
127
|
* Called from the sweeper and from restore, so leftovers never outlive a daemon restart.
|
|
@@ -114,11 +139,20 @@ export declare class ChannelJobManager {
|
|
|
114
139
|
/** Task ids that a still-running job on this channel promises to wake. See `channelJobTaskIds`. */
|
|
115
140
|
runningTaskIds(): Set<string>;
|
|
116
141
|
/**
|
|
117
|
-
* Launch a command in the background and return its
|
|
118
|
-
*
|
|
119
|
-
* `
|
|
142
|
+
* Launch a command in the background and return its snapshot. The wrapper (`buildLaunchScript`)
|
|
143
|
+
* runs a readiness handshake before the command executes: only after the inner shell proves it
|
|
144
|
+
* started — spill writable, `setsid`/`sh` execed — does the parent print `MODE`/`PID` and exit
|
|
145
|
+
* 0. A failed handshake, a non-zero launch, or an interrupted launch never creates a `running`
|
|
146
|
+
* record; a persist failure right after a successful launch terminates the process (see below).
|
|
120
147
|
*/
|
|
121
148
|
start(command: string, label: string, timeoutSeconds: number, options?: JobStartOptions): Promise<JobSnapshot>;
|
|
149
|
+
/**
|
|
150
|
+
* Recover from a launch that rejected (an abort landed after the wrapper had already spawned the
|
|
151
|
+
* detached child, or the executor failed outright). The wrapper writes a metadata file *before*
|
|
152
|
+
* its readiness handshake, so even an interrupted launch usually leaves a recoverable pid;
|
|
153
|
+
* clean it up with no caller signal and return an error that is honest about what is known.
|
|
154
|
+
*/
|
|
155
|
+
private recoverInterruptedLaunch;
|
|
122
156
|
/**
|
|
123
157
|
* Start the low-frequency sweeper if it is not already running. It reaps finished/timed-out jobs
|
|
124
158
|
* so their slots free up even when the model never polls, and stops itself once nothing is running.
|
|
@@ -127,10 +161,11 @@ export declare class ChannelJobManager {
|
|
|
127
161
|
private stopSweeper;
|
|
128
162
|
private sweep;
|
|
129
163
|
/**
|
|
130
|
-
* Probe every given job in one shell invocation, returning
|
|
164
|
+
* Probe every given job in one shell invocation, returning
|
|
165
|
+
* `id → EXIT:<code> | ALIVE | GONE | DIFFERENT | UNKNOWN`.
|
|
131
166
|
*
|
|
132
167
|
* Each job contributes one branch that reads its exit-code file if present and otherwise checks
|
|
133
|
-
*
|
|
168
|
+
* liveness (three-state when a start time was captured — see the inline comment).
|
|
134
169
|
*/
|
|
135
170
|
private probeAll;
|
|
136
171
|
/**
|
|
@@ -141,7 +176,19 @@ export declare class ChannelJobManager {
|
|
|
141
176
|
* to say nothing.
|
|
142
177
|
*/
|
|
143
178
|
private refresh;
|
|
144
|
-
/**
|
|
179
|
+
/**
|
|
180
|
+
* Probe one job and apply the result. The unlocked core of `refresh` — every caller must already
|
|
181
|
+
* hold the job's `reconcileQueue` slot (`refresh`, or `cancel`'s combined critical section).
|
|
182
|
+
*/
|
|
183
|
+
private reconcileLocked;
|
|
184
|
+
/**
|
|
185
|
+
* The terminal status for a job a probe just showed as finished/gone. A cancel or timeout kill
|
|
186
|
+
* already in flight (`pendingKill`) wins over the raw probe result — a job the model asked to
|
|
187
|
+
* cancel lands `cancelled`, a timed-out one `failed`/124 — even if the process happened to exit
|
|
188
|
+
* on its own first. Clears `pendingKill`; call only immediately before `finish`.
|
|
189
|
+
*/
|
|
190
|
+
private takePendingTerminal;
|
|
191
|
+
/** Turn one probe result into a status transition; an inconclusive result only ages the job. */
|
|
145
192
|
private applyProbe;
|
|
146
193
|
/** Move a job to a terminal status: record it, persist it, and wake the channel once. */
|
|
147
194
|
private finish;
|
|
@@ -153,7 +200,24 @@ export declare class ChannelJobManager {
|
|
|
153
200
|
* version that persisted `notified` first, which could crash-lose the wake entirely).
|
|
154
201
|
*/
|
|
155
202
|
private announce;
|
|
156
|
-
|
|
203
|
+
/**
|
|
204
|
+
* The shell command that terminates `record`'s process and prints one token describing what
|
|
205
|
+
* happened (`TERMINATED` / `GONE` / `IDENTITY_MISMATCH` / `UNCONFIRMED`), or `undefined` when
|
|
206
|
+
* there is no pid we can safely signal.
|
|
207
|
+
*
|
|
208
|
+
* A negative-PGID target is used only when `setsid` gave the job pgid == pid (spec: everything
|
|
209
|
+
* the command spawned dies with it). When a start time was captured it is checked first: a
|
|
210
|
+
* recycled pid reads as `IDENTITY_MISMATCH` and is never signalled; a pid `ps` cannot see but
|
|
211
|
+
* that `kill -0` says is alive reads as `UNCONFIRMED` (do not signal what we cannot prove is
|
|
212
|
+
* ours). Legacy / nohup records have only `kill -0` liveness and a plain pid kill.
|
|
213
|
+
*/
|
|
214
|
+
private killCommand;
|
|
215
|
+
/**
|
|
216
|
+
* Run one kill attempt and classify it from the printed token plus the executor result — never
|
|
217
|
+
* from "the shell exited 0". Used by cancel, timeout, the persist-failure rollback and the
|
|
218
|
+
* interrupted-launch recovery; the last two pass no signal so an aborted caller cannot skip it.
|
|
219
|
+
*/
|
|
220
|
+
private runKill;
|
|
157
221
|
list(signal?: AbortSignal): Promise<JobSnapshot[]>;
|
|
158
222
|
beginWakeConsumption(id: string, taskId: string, dispatchId: string): Promise<boolean>;
|
|
159
223
|
finishWakeConsumption(id: string, dispatchId: string): Promise<void>;
|
|
@@ -193,15 +257,6 @@ interface JobRuntimeConfig {
|
|
|
193
257
|
* bootstrap, before any turn runs; the tool layer builds managers lazily and picks this up.
|
|
194
258
|
*/
|
|
195
259
|
export declare function configureJobRuntime(config: JobRuntimeConfig): void;
|
|
196
|
-
/**
|
|
197
|
-
* Which of this channel's tasks a running background job will wake, without needing an `Executor`.
|
|
198
|
-
*
|
|
199
|
-
* Read-only view for `/tasks doctor`: a parked task (`waiting`, no `wake`) is healthy exactly when
|
|
200
|
-
* something is going to call it. Managers are created lazily by the tool layer *and* eagerly at
|
|
201
|
-
* startup by `restoreChannelJobs`, so a channel with live jobs always has one; a channel with no
|
|
202
|
-
* manager simply has no jobs, and the empty set is the right answer.
|
|
203
|
-
*/
|
|
204
|
-
export declare function channelJobTaskIds(channelId: string): Set<string>;
|
|
205
260
|
/**
|
|
206
261
|
* Human-readable lines naming this channel's currently running background jobs, for the `/project
|
|
207
262
|
* set|reset` blocker check (spec 043, D4.3) — mirrors `channelJobTaskIds`'s "no manager means no
|