@oyasmi/pipiclaw 0.9.0-beta.7 → 0.9.0-beta.9
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 +1 -0
- package/dist/agent/channel-runner.js +21 -2
- package/dist/agent/index.d.ts +1 -1
- package/dist/agent/index.js +1 -1
- package/dist/agent/job-manager.d.ts +3 -3
- package/dist/agent/job-manager.js +0 -1
- package/dist/agent/runner-factory.d.ts +16 -4
- package/dist/agent/runner-factory.js +9 -23
- package/dist/agent/types.d.ts +9 -1
- package/dist/agent/types.js +3 -16
- package/dist/memory/review-log.js +0 -0
- package/dist/memory/scheduler.d.ts +1 -0
- package/dist/memory/scheduler.js +64 -6
- package/dist/playbooks/agent-delegation.md +2 -2
- package/dist/runtime/bootstrap.d.ts +10 -2
- package/dist/runtime/bootstrap.js +83 -55
- package/dist/runtime/channel-event.d.ts +41 -0
- package/dist/runtime/channel-event.js +1 -0
- package/dist/runtime/delivery.d.ts +3 -2
- package/dist/runtime/dingtalk.d.ts +9 -31
- package/dist/runtime/durable-dispatch.d.ts +4 -2
- package/dist/runtime/durable-dispatch.js +36 -25
- package/dist/runtime/events.d.ts +3 -2
- package/dist/runtime/events.js +2 -3
- package/dist/runtime/subagent-commands.js +48 -10
- package/dist/runtime/task-commands.js +2 -2
- package/dist/runtime/task-driver.d.ts +7 -7
- package/dist/runtime/task-driver.js +1 -4
- package/dist/runtime/task-migration.js +1 -1
- package/dist/runtime/task-wake.d.ts +4 -4
- package/dist/settings.d.ts +0 -106
- package/dist/settings.js +0 -224
- package/dist/shared/host-process.d.ts +25 -9
- package/dist/shared/host-process.js +59 -10
- package/dist/shared/types.d.ts +1 -0
- package/dist/shared/types.js +10 -1
- package/dist/subagents/discovery.d.ts +24 -0
- package/dist/subagents/discovery.js +103 -17
- package/dist/subagents/external/claude-code.js +10 -3
- package/dist/subagents/external/codex-cli.js +9 -3
- package/dist/subagents/external/exec.js +1 -0
- package/dist/subagents/external/harness.d.ts +22 -0
- package/dist/subagents/external/harness.js +22 -4
- package/dist/subagents/external/run.d.ts +23 -3
- package/dist/subagents/external/run.js +112 -131
- package/dist/subagents/external/settlement.d.ts +50 -0
- package/dist/subagents/external/settlement.js +123 -0
- package/dist/subagents/format.d.ts +4 -0
- package/dist/subagents/format.js +7 -0
- package/dist/subagents/runs.d.ts +73 -16
- package/dist/subagents/runs.js +197 -120
- package/dist/subagents/tool.d.ts +38 -6
- package/dist/subagents/tool.js +93 -61
- package/dist/subagents/verification-outcome.d.ts +26 -0
- package/dist/subagents/verification-outcome.js +16 -0
- package/dist/subagents/workspace-lease.d.ts +10 -1
- package/dist/subagents/workspace-lease.js +15 -2
- package/dist/tasks/ledger.js +1 -1
- package/dist/{shared → tasks}/task-schedule.js +1 -1
- package/dist/tools/bash.js +1 -1
- package/dist/tools/event-manage.js +1 -4
- package/dist/tools/grep.js +2 -3
- package/dist/tools/index.js +6 -0
- package/dist/tools/job.js +5 -5
- package/dist/tools/memory-manage.js +3 -6
- package/dist/tools/session-search.js +0 -1
- package/dist/tools/skill-manage.js +3 -3
- package/dist/tools/subagent-manage.d.ts +20 -6
- package/dist/tools/subagent-manage.js +88 -18
- package/dist/tools/task-manage/shared.js +2 -2
- package/dist/tools/task-manage.js +1 -4
- package/dist/tools/web-fetch.js +0 -1
- package/dist/tui/app.js +4 -4
- package/package.json +1 -1
- /package/dist/{shared → tasks}/task-events.d.ts +0 -0
- /package/dist/{shared → tasks}/task-events.js +0 -0
- /package/dist/{shared → tasks}/task-schedule.d.ts +0 -0
|
@@ -92,6 +92,7 @@ export declare class ChannelRunner implements AgentRunner {
|
|
|
92
92
|
isKnownSlashCommand(text: string): boolean;
|
|
93
93
|
queueSteer(text: string, userName?: string): Promise<void>;
|
|
94
94
|
flushMemoryForShutdown(): Promise<void>;
|
|
95
|
+
dispose(): Promise<void>;
|
|
95
96
|
getMemoryMaintenanceContext(): Promise<MemoryMaintenanceRuntimeContext>;
|
|
96
97
|
getStatusSnapshot(): RunnerStatusSnapshot;
|
|
97
98
|
abort(): Promise<void>;
|
|
@@ -17,7 +17,6 @@ import { getApiKeyForModel } from "../models/api-keys.js";
|
|
|
17
17
|
import { createModelRuntime, defaultModel, findExactModelReferenceMatch, formatModelReference, hasKnownModelPricing, resolveInitialModel, wrapModelRegistry, } from "../models/utils.js";
|
|
18
18
|
import { loadRuntimePlaybookCatalog, selectRuntimePlaybooks } from "../playbooks/catalog.js";
|
|
19
19
|
import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
|
|
20
|
-
import { PipiclawSettingsManager } from "../settings.js";
|
|
21
20
|
import { formatConfigDiagnostic } from "../shared/config-diagnostic.js";
|
|
22
21
|
import { formatLocalTime, localStampForFilename } from "../shared/local-time.js";
|
|
23
22
|
import { countPromptUnits } from "../shared/prompt-units.js";
|
|
@@ -114,7 +113,7 @@ export class ChannelRunner {
|
|
|
114
113
|
// Create session manager
|
|
115
114
|
const contextFile = join(channelDir, "context.jsonl");
|
|
116
115
|
this.sessionManager = SessionManager.open(contextFile, channelDir);
|
|
117
|
-
this.settingsManager =
|
|
116
|
+
this.settingsManager = paths.settingsManager;
|
|
118
117
|
this.reportSettingsDiagnostics();
|
|
119
118
|
this.memoryCandidateStore = createMemoryCandidateStore();
|
|
120
119
|
this.memoryActivityRecorder = createMemoryActivityRecorder({
|
|
@@ -606,6 +605,26 @@ export class ChannelRunner {
|
|
|
606
605
|
await this.flushMemoryActivity();
|
|
607
606
|
await this.memoryLifecycle.flushForShutdown();
|
|
608
607
|
}
|
|
608
|
+
async dispose() {
|
|
609
|
+
await this.flushMemoryForShutdown();
|
|
610
|
+
if (this.isBusy()) {
|
|
611
|
+
// `session.dispose()` aborts in-flight work; a busy runner keeps its session and
|
|
612
|
+
// subscription until whoever holds it calls dispose() again once idle.
|
|
613
|
+
log.logWarning(`[${this.channelId}] dispose() called while busy; session left intact`, "");
|
|
614
|
+
return;
|
|
615
|
+
}
|
|
616
|
+
// Guards a dispose() racing construction: initializeSession assigns `this.session`
|
|
617
|
+
// asynchronously, so a runner disposed the instant after creation may not have one yet.
|
|
618
|
+
await this.sessionReady;
|
|
619
|
+
this.sessionUnsubscribe?.();
|
|
620
|
+
this.sessionUnsubscribe = undefined;
|
|
621
|
+
try {
|
|
622
|
+
this.session.dispose();
|
|
623
|
+
}
|
|
624
|
+
catch (error) {
|
|
625
|
+
log.logWarning(`[${this.channelId}] Session dispose failed`, errorMessage(error));
|
|
626
|
+
}
|
|
627
|
+
}
|
|
609
628
|
async getMemoryMaintenanceContext() {
|
|
610
629
|
await this.ensureSessionReady();
|
|
611
630
|
this.settingsManager.reload();
|
package/dist/agent/index.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export { createRunner } from "./runner-factory.js";
|
|
2
2
|
export type { AgentRunner } from "./types.js";
|
package/dist/agent/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export { createRunner } from "./runner-factory.js";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Executor } from "../executor.js";
|
|
2
|
-
import type {
|
|
2
|
+
import type { ChannelEvent } from "../runtime/channel-event.js";
|
|
3
3
|
/**
|
|
4
4
|
* Per-channel manager for background bash jobs. A long command that ran synchronously would hold
|
|
5
5
|
* the channel's run queue for its whole duration, blocking `/steer`, `/followup`, and every other
|
|
@@ -44,7 +44,7 @@ export interface JobManagerOptions {
|
|
|
44
44
|
/** Directory for this channel's persisted job records. Omit to run without persistence. */
|
|
45
45
|
stateDir?: string;
|
|
46
46
|
/** Delivers the completion wake. Omit to disable waking (sub-agent and test paths). */
|
|
47
|
-
dispatch?: (event:
|
|
47
|
+
dispatch?: (event: ChannelEvent) => boolean | Promise<boolean>;
|
|
48
48
|
sweepIntervalMs?: number;
|
|
49
49
|
}
|
|
50
50
|
/** Cap on concurrently running jobs per channel, so a runaway model can't spawn unbounded processes. */
|
|
@@ -166,7 +166,7 @@ export declare class ChannelJobManager {
|
|
|
166
166
|
interface JobRuntimeConfig {
|
|
167
167
|
/** Root of the per-channel record directories (`<jobsStateDir>/<channelId>/`). */
|
|
168
168
|
jobsStateDir?: string;
|
|
169
|
-
dispatch?: (event:
|
|
169
|
+
dispatch?: (event: ChannelEvent) => boolean | Promise<boolean>;
|
|
170
170
|
}
|
|
171
171
|
/**
|
|
172
172
|
* Give background jobs their persistence root and their way to wake a channel. Called once from
|
|
@@ -356,7 +356,6 @@ export class ChannelJobManager {
|
|
|
356
356
|
`Full output: ${record.spillFile}\n` +
|
|
357
357
|
"Continue whatever was waiting on this job. If it needs no follow-up, respond with exactly [SILENT].",
|
|
358
358
|
ts: String(Date.now()),
|
|
359
|
-
conversationId: "",
|
|
360
359
|
conversationType: this.channelId.startsWith("group_") ? "2" : "1",
|
|
361
360
|
dispatchId: `job:${this.channelId}:${record.id}:done`,
|
|
362
361
|
...(record.contract.taskId
|
|
@@ -1,19 +1,31 @@
|
|
|
1
1
|
import type { MediaSender } from "../runtime/channel-context.js";
|
|
2
|
+
import type { PipiclawSettingsManager } from "../settings.js";
|
|
2
3
|
import type { AgentRunner } from "./types.js";
|
|
3
4
|
export interface RunnerFactoryPaths {
|
|
4
5
|
appHomeDir: string;
|
|
5
6
|
authConfigPath: string;
|
|
6
7
|
modelsConfigPath: string;
|
|
8
|
+
/**
|
|
9
|
+
* The single app-level settings manager (from `prepareAppServices`), shared across every
|
|
10
|
+
* channel's runner rather than each constructing its own. Keeps `drainErrors()`/diagnostics
|
|
11
|
+
* ordering and `reload()`'s file-stamp guard meaningful instead of racing N independent copies.
|
|
12
|
+
*/
|
|
13
|
+
settingsManager: PipiclawSettingsManager;
|
|
7
14
|
/** Optional, side-effect-free observer used by the behavior-eval harness. */
|
|
8
15
|
onSessionEvent?: (event: unknown, channelId: string) => void;
|
|
9
16
|
/**
|
|
10
17
|
* Transport that can deliver file attachments (the DingTalk bot, or the terminal).
|
|
11
|
-
* Present enables the `send_media` tool; absent, the tool is not built.
|
|
12
|
-
* of the runner cache key — it is a stable per-process transport handle.
|
|
18
|
+
* Present enables the `send_media` tool; absent, the tool is not built.
|
|
13
19
|
*/
|
|
14
20
|
mediaSender?: MediaSender;
|
|
15
21
|
/** Runtime callback that durably enqueues an independent task verifier. */
|
|
16
22
|
dispatchVerification?: (taskId: string) => Promise<boolean>;
|
|
17
23
|
}
|
|
18
|
-
|
|
19
|
-
|
|
24
|
+
/**
|
|
25
|
+
* Stateless: always constructs a fresh runner. The daemon (`runtime/bootstrap.ts`) and the TUI
|
|
26
|
+
* (`tui/app.ts`) are the only two callers, and each already owns exactly one cache appropriate to
|
|
27
|
+
* its own lifecycle (the daemon's runtime channel map with LRU eviction; the TUI's single local
|
|
28
|
+
* `const`, one channel per process) — a second cache here just duplicated that ownership and
|
|
29
|
+
* could hold a stale entry the real owner had already disposed.
|
|
30
|
+
*/
|
|
31
|
+
export declare function createRunner(channelId: string, channelDir: string, paths: RunnerFactoryPaths): AgentRunner;
|
|
@@ -1,25 +1,11 @@
|
|
|
1
1
|
import { ChannelRunner } from "./channel-runner.js";
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
const runner = new ChannelRunner(channelId, channelDir, paths);
|
|
12
|
-
channelRunners.set(key, runner);
|
|
13
|
-
return runner;
|
|
14
|
-
}
|
|
15
|
-
export function resetRunner(channelId, paths, channelDir) {
|
|
16
|
-
if (paths && channelDir) {
|
|
17
|
-
channelRunners.delete(runnerKey(paths, channelId, channelDir));
|
|
18
|
-
return;
|
|
19
|
-
}
|
|
20
|
-
for (const key of channelRunners.keys()) {
|
|
21
|
-
if (key.endsWith(`\0${channelId}`)) {
|
|
22
|
-
channelRunners.delete(key);
|
|
23
|
-
}
|
|
24
|
-
}
|
|
2
|
+
/**
|
|
3
|
+
* Stateless: always constructs a fresh runner. The daemon (`runtime/bootstrap.ts`) and the TUI
|
|
4
|
+
* (`tui/app.ts`) are the only two callers, and each already owns exactly one cache appropriate to
|
|
5
|
+
* its own lifecycle (the daemon's runtime channel map with LRU eviction; the TUI's single local
|
|
6
|
+
* `const`, one channel per process) — a second cache here just duplicated that ownership and
|
|
7
|
+
* could hold a stale entry the real owner had already disposed.
|
|
8
|
+
*/
|
|
9
|
+
export function createRunner(channelId, channelDir, paths) {
|
|
10
|
+
return new ChannelRunner(channelId, channelDir, paths);
|
|
25
11
|
}
|
package/dist/agent/types.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { MemoryMaintenanceRuntimeContext } from "../memory/scheduler.js";
|
|
2
2
|
import type { ChannelContext } from "../runtime/channel-context.js";
|
|
3
3
|
import type { ChannelStore } from "../runtime/store.js";
|
|
4
|
-
import type
|
|
4
|
+
import { type UsageTotals } from "../shared/types.js";
|
|
5
5
|
import type { SubAgentDiscoveryResult } from "../subagents/discovery.js";
|
|
6
6
|
import type { RunnerBuiltInCommand } from "./commands.js";
|
|
7
7
|
export interface RunnerStatusSnapshot {
|
|
@@ -77,6 +77,14 @@ export interface AgentRunner {
|
|
|
77
77
|
/** Mark the current turn as user-stopped (no-op when idle). */
|
|
78
78
|
requestStop(): void;
|
|
79
79
|
getTurnStatus(): TurnStatus;
|
|
80
|
+
/**
|
|
81
|
+
* Release this runner's resources: flush pending memory, unsubscribe from session events, and
|
|
82
|
+
* dispose the underlying SDK session. A no-op (memory still flushed) while `isBusy()` — disposing
|
|
83
|
+
* the SDK session aborts in-flight work, so a caller must never call this on a busy runner and
|
|
84
|
+
* expect the turn to survive. The owning cache (daemon runtime map, TUI's single runner) must
|
|
85
|
+
* drop its own reference after calling this; a disposed runner is not reusable.
|
|
86
|
+
*/
|
|
87
|
+
dispose(): Promise<void>;
|
|
80
88
|
}
|
|
81
89
|
export type FinalOutcome = {
|
|
82
90
|
kind: "none";
|
package/dist/agent/types.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { createEmptyUsageTotals } from "../shared/types.js";
|
|
1
2
|
export function createEmptyRunState() {
|
|
2
3
|
return {
|
|
3
4
|
ctx: null,
|
|
@@ -5,22 +6,8 @@ export function createEmptyRunState() {
|
|
|
5
6
|
store: null,
|
|
6
7
|
queue: null,
|
|
7
8
|
pendingTools: new Map(),
|
|
8
|
-
totalUsage:
|
|
9
|
-
|
|
10
|
-
output: 0,
|
|
11
|
-
cacheRead: 0,
|
|
12
|
-
cacheWrite: 0,
|
|
13
|
-
total: 0,
|
|
14
|
-
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
15
|
-
},
|
|
16
|
-
assistantUsage: {
|
|
17
|
-
input: 0,
|
|
18
|
-
output: 0,
|
|
19
|
-
cacheRead: 0,
|
|
20
|
-
cacheWrite: 0,
|
|
21
|
-
total: 0,
|
|
22
|
-
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
23
|
-
},
|
|
9
|
+
totalUsage: createEmptyUsageTotals(),
|
|
10
|
+
assistantUsage: createEmptyUsageTotals(),
|
|
24
11
|
costKnown: true,
|
|
25
12
|
usageSources: 0,
|
|
26
13
|
stopReason: "stop",
|
|
Binary file
|
|
@@ -27,6 +27,7 @@ export interface MemoryMaintenanceSchedulerOptions {
|
|
|
27
27
|
isChannelActive: (channelId: string) => boolean;
|
|
28
28
|
getSettings: () => {
|
|
29
29
|
memoryMaintenance: PipiclawMemoryMaintenanceSettings;
|
|
30
|
+
sessionMemory: PipiclawSessionMemorySettings;
|
|
30
31
|
};
|
|
31
32
|
intervalMs?: number;
|
|
32
33
|
}
|
package/dist/memory/scheduler.js
CHANGED
|
@@ -6,9 +6,57 @@ import * as log from "../log.js";
|
|
|
6
6
|
import { discoverWorkspaceChannelIds } from "../runtime/channel-index.js";
|
|
7
7
|
import { isChannelId } from "../runtime/channel-paths.js";
|
|
8
8
|
import { errorMessage } from "../shared/text-utils.js";
|
|
9
|
+
import { shouldRunMemoryCheckpoint, shouldRunSessionRefresh, shouldRunStructuralMaintenance, } from "./maintenance-gates.js";
|
|
9
10
|
import { runMemoryCheckpointJob, runSessionRefreshJob, runStructuralMaintenanceJob } from "./maintenance-jobs.js";
|
|
10
|
-
import { getMemoryMaintenanceStateDir } from "./maintenance-state.js";
|
|
11
|
+
import { getMemoryMaintenanceStateDir, readMemoryMaintenanceState } from "./maintenance-state.js";
|
|
11
12
|
const DEFAULT_TICK_INTERVAL_MS = 60_000;
|
|
13
|
+
/**
|
|
14
|
+
* Cheap due-time predicate, evaluated before `getRuntimeContext` (transcript access, model
|
|
15
|
+
* resolution, settings reload) is paid for.
|
|
16
|
+
*
|
|
17
|
+
* Reuses the real gates with optimistic material (transcript-derived checks always pass), so the
|
|
18
|
+
* only work here is one state-file read plus timestamp arithmetic. A gate's material checks are
|
|
19
|
+
* purely additive restrictions on top of the cheap checks (interval/backoff/idle/dirty), so
|
|
20
|
+
* optimistic material can only ever make this predicate *more* permissive than the real job would
|
|
21
|
+
* be — it never wrongly skips a channel that a job would actually run for.
|
|
22
|
+
*/
|
|
23
|
+
async function mightAnyMaintenanceJobBeDue(input) {
|
|
24
|
+
const state = await readMemoryMaintenanceState(input.appHomeDir, input.channelId);
|
|
25
|
+
const sessionRefresh = shouldRunSessionRefresh({
|
|
26
|
+
now: input.now,
|
|
27
|
+
state,
|
|
28
|
+
sessionMemory: input.settings.sessionMemory,
|
|
29
|
+
maintenance: input.settings.memoryMaintenance,
|
|
30
|
+
channelActive: false,
|
|
31
|
+
hasNewSessionEntry: () => true,
|
|
32
|
+
hasMeaningfulMaterial: () => true,
|
|
33
|
+
});
|
|
34
|
+
if (sessionRefresh.allowed)
|
|
35
|
+
return true;
|
|
36
|
+
const checkpoint = shouldRunMemoryCheckpoint({
|
|
37
|
+
now: input.now,
|
|
38
|
+
state,
|
|
39
|
+
maintenance: input.settings.memoryMaintenance,
|
|
40
|
+
channelActive: false,
|
|
41
|
+
material: () => ({ hasNewEntry: true, hasMeaningfulExchange: true, batchSize: Number.MAX_SAFE_INTEGER }),
|
|
42
|
+
});
|
|
43
|
+
if (checkpoint.allowed)
|
|
44
|
+
return true;
|
|
45
|
+
const structural = await shouldRunStructuralMaintenance({
|
|
46
|
+
now: input.now,
|
|
47
|
+
state,
|
|
48
|
+
maintenance: input.settings.memoryMaintenance,
|
|
49
|
+
channelActive: false,
|
|
50
|
+
material: async () => ({
|
|
51
|
+
memoryCleanupNeeded: true,
|
|
52
|
+
historyFoldingNeeded: true,
|
|
53
|
+
hasMemoryContent: true,
|
|
54
|
+
hasHistoryContent: true,
|
|
55
|
+
expiredEntryCount: 1,
|
|
56
|
+
}),
|
|
57
|
+
});
|
|
58
|
+
return structural.allowed;
|
|
59
|
+
}
|
|
12
60
|
async function listStateChannels(appHomeDir) {
|
|
13
61
|
try {
|
|
14
62
|
const entries = await readdir(getMemoryMaintenanceStateDir(appHomeDir), { withFileTypes: true });
|
|
@@ -47,9 +95,12 @@ export class MemoryMaintenanceScheduler {
|
|
|
47
95
|
this.nextChannelIndex = 0;
|
|
48
96
|
}
|
|
49
97
|
start() {
|
|
50
|
-
if (this.timer
|
|
98
|
+
if (this.timer) {
|
|
51
99
|
return;
|
|
52
100
|
}
|
|
101
|
+
// `enabled` is re-checked on every tick inside `runOnce`, which is nearly free when
|
|
102
|
+
// disabled (one cached settings read, no channel scan). Gating `start()` on it too would
|
|
103
|
+
// mean flipping `memoryMaintenance.enabled` on at runtime never actually starts the timer.
|
|
53
104
|
this.timer = setInterval(() => {
|
|
54
105
|
void this.runOnce().catch((error) => {
|
|
55
106
|
log.logWarning("Memory maintenance scheduler tick failed", errorMessage(error));
|
|
@@ -65,8 +116,8 @@ export class MemoryMaintenanceScheduler {
|
|
|
65
116
|
this.timer = null;
|
|
66
117
|
}
|
|
67
118
|
async runOnce(now = new Date()) {
|
|
68
|
-
const settings = this.options.getSettings()
|
|
69
|
-
if (!settings.enabled || this.running) {
|
|
119
|
+
const settings = this.options.getSettings();
|
|
120
|
+
if (!settings.memoryMaintenance.enabled || this.running) {
|
|
70
121
|
return;
|
|
71
122
|
}
|
|
72
123
|
this.running = true;
|
|
@@ -76,7 +127,7 @@ export class MemoryMaintenanceScheduler {
|
|
|
76
127
|
workspaceDir: this.options.workspaceDir,
|
|
77
128
|
knownChannelIds: this.options.getKnownChannelIds?.(),
|
|
78
129
|
});
|
|
79
|
-
const maxConcurrent = normalizeMaxConcurrentChannels(settings.maxConcurrentChannels);
|
|
130
|
+
const maxConcurrent = normalizeMaxConcurrentChannels(settings.memoryMaintenance.maxConcurrentChannels);
|
|
80
131
|
if (channelIds.length === 0) {
|
|
81
132
|
return;
|
|
82
133
|
}
|
|
@@ -85,7 +136,14 @@ export class MemoryMaintenanceScheduler {
|
|
|
85
136
|
let index = this.nextChannelIndex % channelIds.length;
|
|
86
137
|
while (scanned < channelIds.length && selected.length < maxConcurrent) {
|
|
87
138
|
const channelId = channelIds[index];
|
|
88
|
-
if (channelId &&
|
|
139
|
+
if (channelId &&
|
|
140
|
+
!this.options.isChannelActive(channelId) &&
|
|
141
|
+
(await mightAnyMaintenanceJobBeDue({
|
|
142
|
+
appHomeDir: this.options.appHomeDir,
|
|
143
|
+
channelId,
|
|
144
|
+
settings,
|
|
145
|
+
now,
|
|
146
|
+
}))) {
|
|
89
147
|
selected.push(channelId);
|
|
90
148
|
}
|
|
91
149
|
index = (index + 1) % channelIds.length;
|
|
@@ -40,7 +40,7 @@ order: 36
|
|
|
40
40
|
|
|
41
41
|
- **每次委派都显式传 `workingDirectory`**,不要依赖默认值。
|
|
42
42
|
- **并行的写入分片各自 `git worktree add` 后指向不同 checkout**,绝不让两个写入者共享一棵树。
|
|
43
|
-
- runtime 只在**委派之间**保证排他写锁:`mutates: write` 的 run 会占住目标目录,第二个写入者被拒时错误会点名持有者 runId
|
|
43
|
+
- runtime 只在**委派之间**保证排他写锁:`mutates: write` 的 run 会占住目标目录,第二个写入者被拒时错误会点名持有者 runId。锁触发说明分片设计已经出错,它是兜底而不是免于思考的理由。**这把锁只保护声明了 `mutates: write` 的委派**——内置角色的 `mutates` 是按 `tools` 推定(只看 `write`/`edit`,不看 `bash`),外部角色是自述,两者都可能与角色实际行为不符,写清楚 `mutates` 是你的责任,不是 runtime 能替你核实的事。
|
|
44
44
|
- **你自己的 `write` / `edit` / `bash` 不受这把锁保护。** 一个目录上有活跃写委派时,不要同时自己去改它——先等它结束,或者换一棵 worktree。
|
|
45
45
|
- **创建的 worktree 在使用结束后要记得关闭**
|
|
46
46
|
|
|
@@ -57,7 +57,7 @@ order: 36
|
|
|
57
57
|
## 五、纠偏与续接
|
|
58
58
|
|
|
59
59
|
- `subagent_manage op=cancel <runId>`:提前终止。**`/stop` 不会连带停止已派发的委派**,这是有意的——停止一个正在写工作区的进程永远需要一次显式决定。取消不产生唤醒,因为那是你自己的决定。
|
|
60
|
-
- `subagent_manage op=follow_up <runId>`:在一个**已结束**的可续接外部 run(claude-code / codex-cli)上追加一轮,省掉重新交代上下文。它产生新的 `runId
|
|
60
|
+
- `subagent_manage op=follow_up <runId>`:在一个**已结束**的可续接外部 run(claude-code / codex-cli)上追加一轮,省掉重新交代上下文。它产生新的 `runId`,同样异步唤醒,走与首次派发相同的信封(运行时上下文、上下文块、verify 协议)。内置 run 和 `exec` 不支持续接(内置的隔离上下文本就不持久化),改为带着上一轮产出开一个新委派。角色的 `command`/`model`/`shell` 若在两次派发之间变过,续接会被拒绝——把变化当作"开新任务"而不是想办法绕过去。
|
|
61
61
|
- 不要仅因为耗时长就中断在跑的委派。只在明确阻塞、循环、崩溃、需要纠偏或用户要求时才取消。
|
|
62
62
|
|
|
63
63
|
## 六、产物与验收
|
|
@@ -3,7 +3,8 @@ import { type Executor } from "../executor.js";
|
|
|
3
3
|
import { PipiclawSettingsManager } from "../settings.js";
|
|
4
4
|
import { type WakeTaskTransitionHooks } from "../tasks/store.js";
|
|
5
5
|
import { type BootstrapIO, type BootstrapPaths } from "./app-home.js";
|
|
6
|
-
import
|
|
6
|
+
import type { ChannelEvent } from "./channel-event.js";
|
|
7
|
+
import { DingTalkBot, type DingTalkConfig, type DingTalkHandler } from "./dingtalk.js";
|
|
7
8
|
import { ChannelStore } from "./store.js";
|
|
8
9
|
export interface BootstrapOptions {
|
|
9
10
|
env?: NodeJS.ProcessEnv;
|
|
@@ -76,13 +77,20 @@ interface RuntimeContextOptions {
|
|
|
76
77
|
/** Receives raw SDK session events after subscription, without changing runtime handling. */
|
|
77
78
|
observer?: (event: unknown, channelId: string) => void;
|
|
78
79
|
/** Receives TaskDriver dispatch outcomes; used only by isolated evaluation workers. */
|
|
79
|
-
onTaskDriverDispatch?: (event:
|
|
80
|
+
onTaskDriverDispatch?: (event: ChannelEvent, accepted: boolean) => void;
|
|
80
81
|
startServices?: boolean;
|
|
81
82
|
registerSignalHandlers?: boolean;
|
|
82
83
|
/** Test-only fault seams for the atomic structured-wake task transition. */
|
|
83
84
|
wakeTransitionHooks?: Partial<Record<"job" | "subagent", WakeTaskTransitionHooks>>;
|
|
84
85
|
/** Override the `/stop` watchdog's grace window (tests use a short one). */
|
|
85
86
|
stopForceEndGraceMs?: number;
|
|
87
|
+
/**
|
|
88
|
+
* The app-level settings manager, shared by every channel's runner (see
|
|
89
|
+
* `agent/runner-factory.ts`'s `RunnerFactoryPaths.settingsManager`). `bootstrap()` passes the
|
|
90
|
+
* same instance `prepareAppServices()` already constructed and diagnosed; a caller that skips
|
|
91
|
+
* `prepareAppServices()` (tests) gets one built here instead.
|
|
92
|
+
*/
|
|
93
|
+
settingsManager?: PipiclawSettingsManager;
|
|
86
94
|
}
|
|
87
95
|
export declare function createRuntimeContext(options: RuntimeContextOptions): Promise<RuntimeContext & {
|
|
88
96
|
bot: DingTalkBot;
|
|
@@ -2,10 +2,9 @@ import { existsSync, mkdirSync, writeFileSync } from "fs";
|
|
|
2
2
|
import { join } from "path";
|
|
3
3
|
import { formatUnknownCommandMessage, isRunnerBuiltInCommand, parseBuiltInCommand, slashCommandName, } from "../agent/commands.js";
|
|
4
4
|
import { channelEffectCount, noteTaskEffects, taskEffectCount } from "../agent/effect-ledger.js";
|
|
5
|
-
import {
|
|
5
|
+
import { createRunner } from "../agent/index.js";
|
|
6
6
|
import { configureJobRuntime, restoreChannelJobs } from "../agent/job-manager.js";
|
|
7
7
|
import { loadDetachedMaintenanceContext } from "../agent/maintenance-context.js";
|
|
8
|
-
import { resetRunner } from "../agent/runner-factory.js";
|
|
9
8
|
import { renderStatus } from "../agent/status-render.js";
|
|
10
9
|
import { createExecutor } from "../executor.js";
|
|
11
10
|
import * as log from "../log.js";
|
|
@@ -18,7 +17,7 @@ import { formatConfigDiagnostic } from "../shared/config-diagnostic.js";
|
|
|
18
17
|
import { fileStamp } from "../shared/file-stamp.js";
|
|
19
18
|
import { errorMessage } from "../shared/text-utils.js";
|
|
20
19
|
import { loadDetachedSubAgentDiscovery } from "../subagents/detached-discovery.js";
|
|
21
|
-
import { configureSubAgentRuntime, restoreAllSubAgentRuns,
|
|
20
|
+
import { configureSubAgentRuntime, restoreAllSubAgentRuns, stopSubAgentGarbageCollector } from "../subagents/runs.js";
|
|
22
21
|
import { readActiveTasks } from "../tasks/ledger.js";
|
|
23
22
|
import { finishTaskAttempt } from "../tasks/store.js";
|
|
24
23
|
import { getToolsConfigPath, loadToolsConfig, loadToolsConfigWithDiagnostics } from "../tools/config.js";
|
|
@@ -56,17 +55,32 @@ function waitForTasks(tasks, timeoutMs) {
|
|
|
56
55
|
});
|
|
57
56
|
});
|
|
58
57
|
}
|
|
59
|
-
|
|
60
|
-
|
|
58
|
+
/**
|
|
59
|
+
* Ceiling on cached runners per daemon process. A long-lived daemon otherwise accumulates one
|
|
60
|
+
* `ChannelRunner` (session, subscriptions, memory state) per distinct channel it has ever heard
|
|
61
|
+
* from, unbounded, for the life of the process. Eviction below only ever touches idle runners —
|
|
62
|
+
* a busy one is left cached past the cap rather than mid-turn disposed.
|
|
63
|
+
*/
|
|
64
|
+
const MAX_CACHED_RUNNERS = 50;
|
|
65
|
+
/**
|
|
66
|
+
* Drop the least-recently-used *idle* runners until the cache is back at the cap, disposing each
|
|
67
|
+
* one (flush memory, unsubscribe, release the SDK session) before dropping it. `channelRunners`
|
|
68
|
+
* is a `Map`, so insertion order is iteration order; `getRunner` below re-inserts on every cache
|
|
69
|
+
* hit to keep that order equal to recency of use — the standard "LRU via Map" idiom.
|
|
70
|
+
*/
|
|
71
|
+
async function evictIdleRunnersOverCap(channelRunners) {
|
|
72
|
+
if (channelRunners.size <= MAX_CACHED_RUNNERS)
|
|
73
|
+
return;
|
|
61
74
|
for (const [channelId, runner] of channelRunners) {
|
|
62
|
-
if (
|
|
75
|
+
if (channelRunners.size <= MAX_CACHED_RUNNERS)
|
|
76
|
+
break;
|
|
77
|
+
if (runner.isBusy())
|
|
63
78
|
continue;
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
log.logWarning(`[${channelId}] Failed to
|
|
67
|
-
})
|
|
79
|
+
channelRunners.delete(channelId);
|
|
80
|
+
await runner.dispose().catch((err) => {
|
|
81
|
+
log.logWarning(`[${channelId}] Failed to dispose evicted runner`, errorMessage(err));
|
|
82
|
+
});
|
|
68
83
|
}
|
|
69
|
-
return flushes;
|
|
70
84
|
}
|
|
71
85
|
function isNoRunningTaskQueueError(err) {
|
|
72
86
|
return err instanceof Error && err.message === "No task is currently running.";
|
|
@@ -117,7 +131,7 @@ export async function createRuntimeContext(options) {
|
|
|
117
131
|
const startServices = options.startServices ?? true;
|
|
118
132
|
const registerSignalHandlers = options.registerSignalHandlers ?? true;
|
|
119
133
|
const store = new ChannelStore({ workingDir: options.paths.workspaceDir });
|
|
120
|
-
const runtimeSettingsManager = new PipiclawSettingsManager(options.paths.appHomeDir);
|
|
134
|
+
const runtimeSettingsManager = options.settingsManager ?? new PipiclawSettingsManager(options.paths.appHomeDir);
|
|
121
135
|
log.configureLogging(runtimeSettingsManager.getLoggingSettings());
|
|
122
136
|
const startedAt = Date.now();
|
|
123
137
|
const cliVersion = readCliVersion();
|
|
@@ -140,30 +154,37 @@ export async function createRuntimeContext(options) {
|
|
|
140
154
|
}
|
|
141
155
|
};
|
|
142
156
|
const getRunner = (channelId) => {
|
|
143
|
-
|
|
144
|
-
if (
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
modelsConfigPath: options.paths.modelsConfigPath,
|
|
151
|
-
onSessionEvent: options.observer,
|
|
152
|
-
// The DingTalk bot is the media sender for this transport; enables `send_media`.
|
|
153
|
-
// `bot` is defined below in this same scope and initialized before any message
|
|
154
|
-
// (and thus any getRunner call) can arrive.
|
|
155
|
-
mediaSender: bot,
|
|
156
|
-
dispatchVerification: async (taskId) => {
|
|
157
|
-
const entries = await readActiveTasks(join(channelDir, "tasks"));
|
|
158
|
-
const entry = entries.find((candidate) => candidate.id === taskId);
|
|
159
|
-
if (!entry)
|
|
160
|
-
return false;
|
|
161
|
-
const verificationEvent = createTaskVerificationEvent(channelId, entry, Date.now());
|
|
162
|
-
return (await durableDispatch?.dispatch(verificationEvent)) ?? false;
|
|
163
|
-
},
|
|
164
|
-
});
|
|
165
|
-
channelRunners.set(channelId, runner);
|
|
157
|
+
const existing = channelRunners.get(channelId);
|
|
158
|
+
if (existing) {
|
|
159
|
+
// Re-insert to move this channel to the end (most-recently-used) of the Map's
|
|
160
|
+
// iteration order, which evictIdleRunnersOverCap relies on.
|
|
161
|
+
channelRunners.delete(channelId);
|
|
162
|
+
channelRunners.set(channelId, existing);
|
|
163
|
+
return existing;
|
|
166
164
|
}
|
|
165
|
+
const channelDir = ensureChannelDir(options.paths.workspaceDir, channelId);
|
|
166
|
+
ensureChannelMemoryFilesSync(channelDir);
|
|
167
|
+
const runner = createRunner(channelId, channelDir, {
|
|
168
|
+
appHomeDir: options.paths.appHomeDir,
|
|
169
|
+
authConfigPath: options.paths.authConfigPath,
|
|
170
|
+
modelsConfigPath: options.paths.modelsConfigPath,
|
|
171
|
+
settingsManager: runtimeSettingsManager,
|
|
172
|
+
onSessionEvent: options.observer,
|
|
173
|
+
// The DingTalk bot is the media sender for this transport; enables `send_media`.
|
|
174
|
+
// `bot` is defined below in this same scope and initialized before any message
|
|
175
|
+
// (and thus any getRunner call) can arrive.
|
|
176
|
+
mediaSender: bot,
|
|
177
|
+
dispatchVerification: async (taskId) => {
|
|
178
|
+
const entries = await readActiveTasks(join(channelDir, "tasks"));
|
|
179
|
+
const entry = entries.find((candidate) => candidate.id === taskId);
|
|
180
|
+
if (!entry)
|
|
181
|
+
return false;
|
|
182
|
+
const verificationEvent = createTaskVerificationEvent(channelId, entry, Date.now());
|
|
183
|
+
return (await durableDispatch?.dispatch(verificationEvent)) ?? false;
|
|
184
|
+
},
|
|
185
|
+
});
|
|
186
|
+
channelRunners.set(channelId, runner);
|
|
187
|
+
void evictIdleRunnersOverCap(channelRunners);
|
|
167
188
|
return runner;
|
|
168
189
|
};
|
|
169
190
|
const handler = {
|
|
@@ -526,7 +547,6 @@ export async function createRuntimeContext(options) {
|
|
|
526
547
|
jobsStateDir: join(options.paths.appHomeDir, "state", "jobs"),
|
|
527
548
|
dispatch: (event) => durableDispatch?.dispatch(event) ?? false,
|
|
528
549
|
});
|
|
529
|
-
void restoreChannelJobs(executor);
|
|
530
550
|
// Delegation runs get the same treatment (spec 040, D1/D7): persistence root, wake delivery,
|
|
531
551
|
// and the usage/archive authority, wired before any turn can start a run.
|
|
532
552
|
configureSubAgentRuntime({
|
|
@@ -535,9 +555,13 @@ export async function createRuntimeContext(options) {
|
|
|
535
555
|
ledger: getUsageLedger(),
|
|
536
556
|
store,
|
|
537
557
|
});
|
|
538
|
-
// Admission (bot.start() below) must not open until every persisted run is back in
|
|
539
|
-
//
|
|
558
|
+
// Admission (bot.start() below) must not open until every persisted job and run is back in
|
|
559
|
+
// memory: a message arriving mid-restore would see partial running-count/short-id/lease state,
|
|
540
560
|
// and durableDispatch's redelivery of a pending completion wake would find no record to claim.
|
|
561
|
+
// Spec 042 D11: `restoreChannelJobs` used to be a bare `void` while `restoreAllSubAgentRuns`
|
|
562
|
+
// was already awaited — the same admission race P0-1 closed for delegation runs was still open
|
|
563
|
+
// for background jobs.
|
|
564
|
+
await restoreChannelJobs(executor);
|
|
541
565
|
await restoreAllSubAgentRuns();
|
|
542
566
|
const eventsWatcher = options.createEventsWatcher
|
|
543
567
|
? options.createEventsWatcher(options.paths.workspaceDir, bot, executor, options.paths.eventHistoryPath)
|
|
@@ -570,6 +594,7 @@ export async function createRuntimeContext(options) {
|
|
|
570
594
|
runtimeSettingsManager.reload();
|
|
571
595
|
return {
|
|
572
596
|
memoryMaintenance: runtimeSettingsManager.getMemoryMaintenanceSettings(),
|
|
597
|
+
sessionMemory: runtimeSettingsManager.getSessionMemorySettings(),
|
|
573
598
|
};
|
|
574
599
|
},
|
|
575
600
|
intervalMs: options.memoryMaintenanceSchedulerIntervalMs,
|
|
@@ -614,7 +639,7 @@ export async function createRuntimeContext(options) {
|
|
|
614
639
|
durableDispatch?.stop();
|
|
615
640
|
memoryMaintenanceScheduler.stop();
|
|
616
641
|
eventsWatcher.stop();
|
|
617
|
-
|
|
642
|
+
stopSubAgentGarbageCollector();
|
|
618
643
|
await bot.stop();
|
|
619
644
|
const runningTasks = Array.from(activeTasks);
|
|
620
645
|
if (runningTasks.length > 0) {
|
|
@@ -642,23 +667,25 @@ export async function createRuntimeContext(options) {
|
|
|
642
667
|
}
|
|
643
668
|
}
|
|
644
669
|
}
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
670
|
+
// Idle runners are disposed (flush memory, unsubscribe, release the SDK session); a
|
|
671
|
+
// still-busy one — its turn already aborted above — is just dropped from the cache and
|
|
672
|
+
// left to unwind on its own as the process exits.
|
|
673
|
+
const disposals = [];
|
|
674
|
+
for (const [channelId, runner] of channelRunners) {
|
|
675
|
+
if (runner.isBusy())
|
|
676
|
+
continue;
|
|
677
|
+
disposals.push(runner.dispose().catch((err) => {
|
|
678
|
+
log.logWarning(`[${channelId}] Failed to dispose runner during shutdown`, errorMessage(err));
|
|
679
|
+
}));
|
|
652
680
|
}
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
onSessionEvent: options.observer,
|
|
660
|
-
}, channelDir);
|
|
681
|
+
if (disposals.length > 0) {
|
|
682
|
+
log.logInfo(`Disposing ${disposals.length} idle channel runner(s) before shutdown`);
|
|
683
|
+
const disposed = await waitForTasks(disposals, SHUTDOWN_FLUSH_WAIT_MS);
|
|
684
|
+
if (!disposed) {
|
|
685
|
+
log.logWarning(`Shutdown runner disposal exceeded ${SHUTDOWN_FLUSH_WAIT_MS}ms`);
|
|
686
|
+
}
|
|
661
687
|
}
|
|
688
|
+
channelRunners.clear();
|
|
662
689
|
const storageFlushes = [
|
|
663
690
|
store.close(),
|
|
664
691
|
// Cancels the debounce timer and lands the last activity times.
|
|
@@ -771,13 +798,14 @@ export async function bootstrap(argv, options = {}) {
|
|
|
771
798
|
}
|
|
772
799
|
const dingtalkConfig = loadConfig(paths, io);
|
|
773
800
|
dingtalkConfig.stateDir = paths.workspaceDir;
|
|
774
|
-
prepareAppServices(paths);
|
|
801
|
+
const { settingsManager } = prepareAppServices(paths);
|
|
775
802
|
log.logStartup(paths.workspaceDir);
|
|
776
803
|
const runtime = await createRuntimeContext({
|
|
777
804
|
paths,
|
|
778
805
|
dingtalkConfig,
|
|
779
806
|
registerSignalHandlers,
|
|
780
807
|
startServices,
|
|
808
|
+
settingsManager,
|
|
781
809
|
});
|
|
782
810
|
return {
|
|
783
811
|
bot: runtime.bot,
|