@yandy0725/pi-subagents 0.7.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +29 -3
- package/README.zh.md +29 -3
- package/index.ts +1 -1
- package/package.json +4 -4
- package/src/config/custom-agents.ts +1 -0
- package/src/config/invocation-config.ts +3 -0
- package/src/index.ts +4 -4
- package/src/lifecycle/create-subagent-session.ts +46 -30
- package/src/lifecycle/parent-snapshot.ts +0 -3
- package/src/lifecycle/subagent-manager.ts +3 -29
- package/src/lifecycle/subagent-session.ts +28 -0
- package/src/lifecycle/subagent.ts +55 -46
- package/src/lifecycle/turn-limits.ts +9 -2
- package/src/observation/notification.ts +1 -1
- package/src/service/service-adapter.ts +4 -6
- package/src/service/service.ts +4 -26
- package/src/session/prompts.ts +53 -56
- package/src/session/session-config.ts +19 -17
- package/src/settings.ts +46 -1
- package/src/tools/agent-tool.ts +9 -0
- package/src/tools/background-spawner.ts +1 -0
- package/src/tools/foreground-runner.ts +1 -0
- package/src/tools/helpers.ts +1 -1
- package/src/tools/result-renderer.ts +1 -1
- package/src/tools/spawn-config.ts +6 -2
- package/src/types.ts +4 -1
- package/src/ui/display.ts +3 -2
- package/src/ui/subagents-settings.ts +17 -0
- package/src/lifecycle/workspace-bracket.ts +0 -59
- package/src/lifecycle/workspace.ts +0 -47
|
@@ -2,21 +2,18 @@
|
|
|
2
2
|
* subagent.ts — Subagent class: identity, lifecycle status, and per-subagent behavior.
|
|
3
3
|
*
|
|
4
4
|
* Status/stats are delegated to the SubagentState value object; listener
|
|
5
|
-
* lifecycle to RunListeners
|
|
5
|
+
* lifecycle to RunListeners.
|
|
6
6
|
* Behavior (abort, steer buffering) lives here rather than on SubagentManager.
|
|
7
7
|
*/
|
|
8
8
|
|
|
9
9
|
import type { Model } from "@earendil-works/pi-ai";
|
|
10
10
|
import type { AgentSessionEvent, ToolDefinition } from "@earendil-works/pi-coding-agent";
|
|
11
|
-
import { debugLog } from "../debug";
|
|
12
11
|
import type { CreateSubagentSessionParams } from "../lifecycle/create-subagent-session";
|
|
13
12
|
import type { ParentSnapshot } from "../lifecycle/parent-snapshot";
|
|
14
13
|
import { RunListeners } from "../lifecycle/run-listeners";
|
|
15
14
|
import type { SubagentSession, TurnLoopResult } from "../lifecycle/subagent-session";
|
|
16
15
|
import { SubagentState, type SubagentStatus } from "../lifecycle/subagent-state";
|
|
17
16
|
import type { LifetimeUsage } from "../lifecycle/usage";
|
|
18
|
-
import type { WorkspaceProvider } from "../lifecycle/workspace";
|
|
19
|
-
import { WorkspaceBracket } from "../lifecycle/workspace-bracket";
|
|
20
17
|
import { NotificationState } from "../observation/notification-state";
|
|
21
18
|
import { subscribeSubagentObserver } from "../observation/record-observer";
|
|
22
19
|
import type { RunConfig } from "../runtime";
|
|
@@ -56,14 +53,12 @@ export interface SubagentExecution {
|
|
|
56
53
|
snapshot: ParentSnapshot;
|
|
57
54
|
/** Initial prompt for the turn loop. */
|
|
58
55
|
prompt: string;
|
|
59
|
-
/** Parent working directory handed to a workspace provider's prepare(). */
|
|
60
|
-
baseCwd: string;
|
|
61
56
|
observer?: SubagentLifecycleObserver;
|
|
62
57
|
getRunConfig?: () => RunConfig;
|
|
63
|
-
/** Resolves the registered workspace provider (if any) at run-start. */
|
|
64
|
-
getWorkspaceProvider?: () => WorkspaceProvider | undefined;
|
|
65
58
|
model?: Model<any>;
|
|
66
59
|
maxTurns?: number;
|
|
60
|
+
/** Hard wall-clock timeout in seconds (already normalized; undefined = unlimited). */
|
|
61
|
+
timeoutSeconds?: number;
|
|
67
62
|
thinkingLevel?: ThinkingLevel;
|
|
68
63
|
parentSession?: ParentSessionInfo;
|
|
69
64
|
signal?: AbortSignal;
|
|
@@ -144,9 +139,12 @@ export class Subagent {
|
|
|
144
139
|
return this._promise;
|
|
145
140
|
}
|
|
146
141
|
|
|
142
|
+
// Timeout guard — started at run() after markRunning, cleared on every terminal path.
|
|
143
|
+
private _timeoutHandle: ReturnType<typeof setTimeout> | undefined;
|
|
144
|
+
private _timedOut = false;
|
|
145
|
+
|
|
147
146
|
private readonly execution: SubagentExecution;
|
|
148
147
|
private readonly listeners = new RunListeners();
|
|
149
|
-
private readonly workspaceBracket: WorkspaceBracket;
|
|
150
148
|
|
|
151
149
|
subagentSession?: SubagentSession;
|
|
152
150
|
private _notification?: NotificationState;
|
|
@@ -233,9 +231,6 @@ export class Subagent {
|
|
|
233
231
|
// Execution machinery — a single mandatory collaborator
|
|
234
232
|
this.execution = init.execution;
|
|
235
233
|
|
|
236
|
-
// Per-run lifecycle collaborators
|
|
237
|
-
this.workspaceBracket = new WorkspaceBracket(this.execution.getWorkspaceProvider ?? (() => undefined));
|
|
238
|
-
|
|
239
234
|
// Notification state — created from parentSession.toolCallId if present
|
|
240
235
|
const toolCallId = init.execution.parentSession?.toolCallId;
|
|
241
236
|
if (toolCallId) {
|
|
@@ -244,9 +239,8 @@ export class Subagent {
|
|
|
244
239
|
}
|
|
245
240
|
|
|
246
241
|
/**
|
|
247
|
-
* Execute the full agent lifecycle:
|
|
248
|
-
*
|
|
249
|
-
* status transitions.
|
|
242
|
+
* Execute the full agent lifecycle: session creation via the factory,
|
|
243
|
+
* observer wiring, the turn loop, and status transitions.
|
|
250
244
|
*
|
|
251
245
|
* Execution is supplied at construction (mandatory), so run() needs no
|
|
252
246
|
* "not configured" guards. The returned promise always resolves (errors are
|
|
@@ -256,32 +250,12 @@ export class Subagent {
|
|
|
256
250
|
this.markRunning(Date.now());
|
|
257
251
|
this.execution.observer?.onStarted?.(this);
|
|
258
252
|
this.listeners.wireSignal(this.execution.signal, () => this.abort());
|
|
259
|
-
|
|
260
|
-
// Guard the await so the no-provider path stays synchronous, preserving
|
|
261
|
-
// the original run() timing: the factory is called in the same turn as
|
|
262
|
-
// spawn() when no workspace provider is registered.
|
|
263
|
-
let cwd: string | undefined;
|
|
264
|
-
if (this.workspaceBracket.hasProvider()) {
|
|
265
|
-
try {
|
|
266
|
-
cwd = await this.workspaceBracket.prepare({
|
|
267
|
-
agentId: this.id,
|
|
268
|
-
agentType: this.type,
|
|
269
|
-
baseCwd: this.execution.baseCwd,
|
|
270
|
-
invocation: this.invocation,
|
|
271
|
-
});
|
|
272
|
-
} catch (err) {
|
|
273
|
-
this.markError(err);
|
|
274
|
-
this.listeners.release();
|
|
275
|
-
this.execution.observer?.onRunFinished?.(this);
|
|
276
|
-
return;
|
|
277
|
-
}
|
|
278
|
-
}
|
|
253
|
+
this.startTimeoutGuard();
|
|
279
254
|
|
|
280
255
|
try {
|
|
281
256
|
this.subagentSession = await this.execution.createSubagentSession({
|
|
282
257
|
snapshot: this.execution.snapshot,
|
|
283
258
|
type: this.type,
|
|
284
|
-
cwd,
|
|
285
259
|
parentSession: this.execution.parentSession,
|
|
286
260
|
model: this.execution.model,
|
|
287
261
|
thinkingLevel: this.execution.thinkingLevel,
|
|
@@ -292,6 +266,15 @@ export class Subagent {
|
|
|
292
266
|
return;
|
|
293
267
|
}
|
|
294
268
|
|
|
269
|
+
// Timeout fired before the session existed: the controller had no listener
|
|
270
|
+
// (forwardAbortSignal is wired inside runTurnLoop), so nothing was killed.
|
|
271
|
+
// Fail fast instead of running a turn loop the budget already exhausted.
|
|
272
|
+
if (this._timedOut) {
|
|
273
|
+
this.disposeSession();
|
|
274
|
+
this.failRun(new Error(`Timed out after ${this.execution.timeoutSeconds}s before the session started`));
|
|
275
|
+
return;
|
|
276
|
+
}
|
|
277
|
+
|
|
295
278
|
this.flushPendingSteers();
|
|
296
279
|
this.listeners.attachObserver(
|
|
297
280
|
subscribeSubagentObserver(this.subagentSession, this.state, {
|
|
@@ -440,11 +423,37 @@ export class Subagent {
|
|
|
440
423
|
*/
|
|
441
424
|
abort(): boolean {
|
|
442
425
|
if (this.status !== "running") return false;
|
|
426
|
+
// A stopped run has no use for a deadline: without this, a timer firing
|
|
427
|
+
// during the abort unwind would stamp a timeout note on a user-stopped run.
|
|
428
|
+
this.clearTimeoutGuard();
|
|
443
429
|
this.abortController.abort();
|
|
444
430
|
this.markStopped();
|
|
445
431
|
return true;
|
|
446
432
|
}
|
|
447
433
|
|
|
434
|
+
/** Start the wall-clock timeout guard (no-op when no timeout is configured). */
|
|
435
|
+
private startTimeoutGuard(): void {
|
|
436
|
+
// Guard on > 0 so an unnormalized 0/negative/NaN can never arm a timer.
|
|
437
|
+
const seconds = Number(this.execution.timeoutSeconds);
|
|
438
|
+
if (!(seconds > 0)) return;
|
|
439
|
+
this._timeoutHandle = setTimeout(() => {
|
|
440
|
+
// Fire the controller without markStopped(): the abort flows through
|
|
441
|
+
// forwardAbortSignal into session.abort(), and the turn loop settles
|
|
442
|
+
// through the aborted path (status "aborted", not "stopped").
|
|
443
|
+
this._timedOut = true;
|
|
444
|
+
this.abortController.abort();
|
|
445
|
+
}, seconds * 1000);
|
|
446
|
+
this._timeoutHandle.unref();
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
/** Clear the timeout guard (idempotent; safe after it already fired). */
|
|
450
|
+
private clearTimeoutGuard(): void {
|
|
451
|
+
if (this._timeoutHandle) {
|
|
452
|
+
clearTimeout(this._timeoutHandle);
|
|
453
|
+
this._timeoutHandle = undefined;
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
|
|
448
457
|
/**
|
|
449
458
|
* Buffer a steer message for delivery once the session is ready.
|
|
450
459
|
* Called internally from steer() before the session is ready.
|
|
@@ -470,13 +479,18 @@ export class Subagent {
|
|
|
470
479
|
this.listeners.release();
|
|
471
480
|
}
|
|
472
481
|
|
|
473
|
-
/** Complete a run: release listeners,
|
|
482
|
+
/** Complete a run: release listeners, status transition, notify observer. */
|
|
474
483
|
completeRun(result: TurnLoopResult): void {
|
|
484
|
+
this.clearTimeoutGuard();
|
|
475
485
|
this.listeners.release();
|
|
476
486
|
|
|
477
487
|
const finalStatus: SubagentStatus = result.aborted ? "aborted" : result.steered ? "steered" : "completed";
|
|
478
|
-
const
|
|
479
|
-
|
|
488
|
+
const responseText = result.responseText;
|
|
489
|
+
const timeoutNote =
|
|
490
|
+
this._timedOut && finalStatus === "aborted"
|
|
491
|
+
? `⏱ Timed out after ${this.execution.timeoutSeconds}s — output may be truncated.\n\n`
|
|
492
|
+
: "";
|
|
493
|
+
const finalResult = timeoutNote + responseText;
|
|
480
494
|
|
|
481
495
|
if (result.aborted) this.markAborted(finalResult);
|
|
482
496
|
else if (result.steered) this.markSteered(finalResult);
|
|
@@ -490,17 +504,12 @@ export class Subagent {
|
|
|
490
504
|
this.subagentSession?.dispose();
|
|
491
505
|
}
|
|
492
506
|
|
|
493
|
-
/** Fail a run: mark error, release listeners,
|
|
507
|
+
/** Fail a run: mark error, release listeners, notify observer. */
|
|
494
508
|
failRun(err: unknown): void {
|
|
509
|
+
this.clearTimeoutGuard();
|
|
495
510
|
this.markError(err);
|
|
496
511
|
this.listeners.release();
|
|
497
512
|
|
|
498
|
-
try {
|
|
499
|
-
this.workspaceBracket.dispose({ status: "error", description: this.description });
|
|
500
|
-
} catch (cleanupErr) {
|
|
501
|
-
debugLog("workspace dispose on agent error", cleanupErr);
|
|
502
|
-
}
|
|
503
|
-
|
|
504
513
|
this.execution.observer?.onRunFinished?.(this);
|
|
505
514
|
}
|
|
506
515
|
}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* turn-limits.ts — Pure
|
|
2
|
+
* turn-limits.ts — Pure run-limit normalization for subagent execution
|
|
3
|
+
* (max turns and wall-clock timeout).
|
|
3
4
|
*
|
|
4
|
-
* Extracted from agent-runner.ts (issue #265) so the
|
|
5
|
+
* Extracted from agent-runner.ts (issue #265) so the run-limit policy has a
|
|
5
6
|
* focused home independent of session assembly. Consumed by the subagent tool's
|
|
6
7
|
* spawn-config resolution and by the turn loop in SubagentSession.
|
|
7
8
|
*/
|
|
@@ -11,3 +12,9 @@ export function normalizeMaxTurns(n: number | undefined): number | undefined {
|
|
|
11
12
|
if (n == null || n === 0) return undefined;
|
|
12
13
|
return Math.max(1, n);
|
|
13
14
|
}
|
|
15
|
+
|
|
16
|
+
/** Normalize a wall-clock timeout in seconds. undefined or 0 = unlimited, otherwise minimum 1. Non-finite → unlimited. */
|
|
17
|
+
export function normalizeTimeoutSeconds(s: number | undefined): number | undefined {
|
|
18
|
+
if (s == null || !Number.isFinite(s) || s === 0) return undefined;
|
|
19
|
+
return Math.max(1, s);
|
|
20
|
+
}
|
|
@@ -32,7 +32,7 @@ export function getStatusLabel(status: string, error?: string): string {
|
|
|
32
32
|
case "error":
|
|
33
33
|
return `Error: ${error ?? "unknown"}`;
|
|
34
34
|
case "aborted":
|
|
35
|
-
return "Aborted (
|
|
35
|
+
return "Aborted (hard limit exceeded)";
|
|
36
36
|
case "steered":
|
|
37
37
|
return "Wrapped up (turn limit)";
|
|
38
38
|
case "stopped":
|
|
@@ -6,9 +6,9 @@
|
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
8
|
import type { ParentSnapshot } from "../lifecycle/parent-snapshot";
|
|
9
|
-
import type { WorkspaceProvider } from "../lifecycle/workspace";
|
|
10
9
|
import type { SpawnOptions, SubagentRecord, SubagentsService } from "../service/service";
|
|
11
10
|
import type { ModelRegistry } from "../session/model-resolver";
|
|
11
|
+
import { normalizeTimeoutSeconds } from "../lifecycle/turn-limits";
|
|
12
12
|
import { resolveModelName } from "../tools/spawn-config";
|
|
13
13
|
import type { SessionContext, Subagent, ThinkingLevel, AgentInvocation } from "../types";
|
|
14
14
|
|
|
@@ -20,7 +20,6 @@ export interface SubagentManagerLike {
|
|
|
20
20
|
abort(id: string): boolean;
|
|
21
21
|
waitForAll(): Promise<void>;
|
|
22
22
|
hasRunning(): boolean;
|
|
23
|
-
registerWorkspaceProvider(provider: WorkspaceProvider): () => void;
|
|
24
23
|
}
|
|
25
24
|
|
|
26
25
|
/**
|
|
@@ -76,6 +75,9 @@ export class SubagentsServiceAdapter implements SubagentsService {
|
|
|
76
75
|
description,
|
|
77
76
|
model,
|
|
78
77
|
maxTurns: options?.maxTurns,
|
|
78
|
+
// Normalize at the boundary: the documented 0/undefined = unlimited contract
|
|
79
|
+
// must hold for cross-extension callers that skip the tool path.
|
|
80
|
+
timeoutSeconds: normalizeTimeoutSeconds(options?.timeoutSeconds),
|
|
79
81
|
thinkingLevel: options?.thinkingLevel,
|
|
80
82
|
inheritContext: options?.inheritContext,
|
|
81
83
|
bypassQueue: options?.bypassQueue,
|
|
@@ -113,10 +115,6 @@ export class SubagentsServiceAdapter implements SubagentsService {
|
|
|
113
115
|
hasRunning(): boolean {
|
|
114
116
|
return this.manager.hasRunning();
|
|
115
117
|
}
|
|
116
|
-
|
|
117
|
-
registerWorkspaceProvider(provider: WorkspaceProvider): () => void {
|
|
118
|
-
return this.manager.registerWorkspaceProvider(provider);
|
|
119
|
-
}
|
|
120
118
|
}
|
|
121
119
|
|
|
122
120
|
/**
|
package/src/service/service.ts
CHANGED
|
@@ -11,29 +11,11 @@
|
|
|
11
11
|
|
|
12
12
|
import type { SubagentStatus } from "../lifecycle/subagent";
|
|
13
13
|
import type { LifetimeUsage } from "../lifecycle/usage";
|
|
14
|
-
import type {
|
|
15
|
-
Workspace,
|
|
16
|
-
WorkspaceDisposeOutcome,
|
|
17
|
-
WorkspaceDisposeResult,
|
|
18
|
-
WorkspacePrepareContext,
|
|
19
|
-
WorkspaceProvider,
|
|
20
|
-
} from "../lifecycle/workspace";
|
|
21
14
|
|
|
22
15
|
// SubagentStatus is defined in the lifecycle layer (single home) and re-exported
|
|
23
|
-
// here for the public API surface — mirrors the LifetimeUsage
|
|
16
|
+
// here for the public API surface — mirrors the LifetimeUsage pattern.
|
|
24
17
|
export type { SubagentStatus } from "../lifecycle/subagent";
|
|
25
|
-
|
|
26
|
-
// and all four collaborator types it references are re-exported by name so
|
|
27
|
-
// consumers can import them directly rather than recovering them via
|
|
28
|
-
// indexed-access inference (e.g. `Parameters<WorkspaceProvider["prepare"]>[0]`).
|
|
29
|
-
export type {
|
|
30
|
-
LifetimeUsage,
|
|
31
|
-
Workspace,
|
|
32
|
-
WorkspaceDisposeOutcome,
|
|
33
|
-
WorkspaceDisposeResult,
|
|
34
|
-
WorkspacePrepareContext,
|
|
35
|
-
WorkspaceProvider,
|
|
36
|
-
};
|
|
18
|
+
export type { LifetimeUsage };
|
|
37
19
|
|
|
38
20
|
/** Serializable snapshot of an agent's state — no live session objects. */
|
|
39
21
|
export interface SubagentRecord {
|
|
@@ -57,6 +39,8 @@ export interface SpawnOptions {
|
|
|
57
39
|
description?: string;
|
|
58
40
|
model?: string;
|
|
59
41
|
maxTurns?: number;
|
|
42
|
+
/** Hard wall-clock timeout in seconds (0/undefined = unlimited). Normalize before passing, or pass an already-normalized value. */
|
|
43
|
+
timeoutSeconds?: number;
|
|
60
44
|
thinkingLevel?: string;
|
|
61
45
|
inheritContext?: boolean;
|
|
62
46
|
foreground?: boolean;
|
|
@@ -86,12 +70,6 @@ export interface SubagentsService {
|
|
|
86
70
|
/** Whether any agents are running or queued. */
|
|
87
71
|
hasRunning(): boolean;
|
|
88
72
|
|
|
89
|
-
/**
|
|
90
|
-
* Register the single workspace provider that supplies a child's working
|
|
91
|
-
* directory plus bracketed setup/teardown. Throws if one is already
|
|
92
|
-
* registered. Returns a disposer that unregisters the provider.
|
|
93
|
-
*/
|
|
94
|
-
registerWorkspaceProvider(provider: WorkspaceProvider): () => void;
|
|
95
73
|
}
|
|
96
74
|
|
|
97
75
|
/** Event channel constants for pi.events subscriptions. */
|
package/src/session/prompts.ts
CHANGED
|
@@ -1,50 +1,65 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* prompts.ts — System prompt
|
|
2
|
+
* prompts.ts — System prompt assembly for agents.
|
|
3
|
+
*
|
|
4
|
+
* Two shapes, one per `prompt_mode`:
|
|
5
|
+
*
|
|
6
|
+
* - "append": the harness renders the base system prompt for the child's OWN
|
|
7
|
+
* tool set (tool list, guidelines, skills, AGENTS.md, SYSTEM.md, date/cwd)
|
|
8
|
+
* and this module only contributes a section appended to it.
|
|
9
|
+
* - "replace": this module owns the whole prompt. The caller's rendered prompt
|
|
10
|
+
* is deliberately NOT reused — it carries the caller's tool list and
|
|
11
|
+
* guidelines, its cwd/date, and project context the child suppresses.
|
|
12
|
+
*
|
|
13
|
+
* Both shapes emit an `<active_agent name="..."/>` tag so downstream extensions
|
|
14
|
+
* can resolve per-agent policy by parsing the child's system prompt.
|
|
3
15
|
*/
|
|
4
16
|
|
|
5
17
|
import type { EnvInfo } from "../session/env";
|
|
6
18
|
import type { AgentPromptConfig } from "../types";
|
|
7
19
|
|
|
8
20
|
/**
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
* - "replace" mode: parent/genericBase + active_agent tag + env header +
|
|
16
|
-
* config.systemPrompt. No `<sub_agent_context>` bridge and no
|
|
17
|
-
* `<agent_instructions>` wrapper — the custom prompt has full control and
|
|
18
|
-
* the final say.
|
|
19
|
-
* - "append" mode: parent/genericBase + sub-agent context bridge +
|
|
20
|
-
* active_agent tag + env header + config.systemPrompt (wrapped in
|
|
21
|
-
* `<agent_instructions>` when non-empty).
|
|
22
|
-
* - "append" with empty systemPrompt: pure parent clone.
|
|
23
|
-
*
|
|
24
|
-
* Both modes include an `<active_agent name="${config.name}"/>` tag so
|
|
25
|
-
* downstream extensions can resolve per-agent policy inside the child session
|
|
26
|
-
* by parsing the system prompt.
|
|
27
|
-
* The tag follows the cacheable parent prefix in both modes.
|
|
28
|
-
*
|
|
29
|
-
* @param parentSystemPrompt The parent agent's effective system prompt.
|
|
21
|
+
* Fallback prompt for a replace agent whose body is empty — nothing else uses
|
|
22
|
+
* it. It asserts no role and no capability: in replace mode the body IS the
|
|
23
|
+
* spec, and a generic persona prepended to it would mislabel read-only or
|
|
24
|
+
* non-coding agents (and is the only capability text the model would see, since
|
|
25
|
+
* replace mode renders no tool list). Only the `tools` allowlist grants abilities.
|
|
30
26
|
*/
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
parentSystemPrompt?: string,
|
|
36
|
-
): string {
|
|
37
|
-
const activeAgentTag = `<active_agent name="${config.name}"/>\n\n`;
|
|
27
|
+
const emptyBodyFallback = `# Role
|
|
28
|
+
Your role is defined by the instructions below.
|
|
29
|
+
Your available tools are the ones exposed to you in this session; respect any restrictions stated below.
|
|
30
|
+
Do what has been asked; nothing more, nothing less.`;
|
|
38
31
|
|
|
39
|
-
|
|
40
|
-
|
|
32
|
+
/** Environment header shared by both modes. cwd and date are rendered by the harness. */
|
|
33
|
+
function environmentBlock(env: EnvInfo): string {
|
|
34
|
+
return `# Environment
|
|
41
35
|
${env.isGitRepo ? `Git repository: yes\nBranch: ${env.branch}` : "Not a git repository"}
|
|
42
36
|
Platform: ${env.platform}`;
|
|
37
|
+
}
|
|
43
38
|
|
|
44
|
-
|
|
39
|
+
/**
|
|
40
|
+
* Build the complete system prompt for a "replace" agent:
|
|
41
|
+
* active_agent tag → env header → the agent body verbatim.
|
|
42
|
+
*
|
|
43
|
+
* Only an empty body gets `emptyBodyFallback` in front of it; a non-empty body is the
|
|
44
|
+
* agent's whole spec, so nothing generic is prepended. No `<sub_agent_context>`
|
|
45
|
+
* bridge and no `<agent_instructions>` wrapper either: this is not an addendum
|
|
46
|
+
* to someone else's prompt.
|
|
47
|
+
*/
|
|
48
|
+
export function buildReplacePrompt(config: AgentPromptConfig, env: EnvInfo): string {
|
|
49
|
+
const identity = config.systemPrompt.trim() ? "" : `${emptyBodyFallback}\n\n`;
|
|
50
|
+
return `${identity}<active_agent name="${config.name}"/>\n\n${environmentBlock(env)}\n\n${config.systemPrompt}`;
|
|
51
|
+
}
|
|
45
52
|
|
|
46
|
-
|
|
47
|
-
|
|
53
|
+
/**
|
|
54
|
+
* Build the section appended to the harness-rendered base prompt for an
|
|
55
|
+
* "append" agent: sub-agent bridge → active_agent tag → env header → the agent
|
|
56
|
+
* body wrapped in `<agent_instructions>` (omitted when the body is empty).
|
|
57
|
+
*
|
|
58
|
+
* Carries no leading separator: the harness joins it onto the base prompt with
|
|
59
|
+
* its own blank line, so adding one here would stack into extra empty lines.
|
|
60
|
+
*/
|
|
61
|
+
export function buildAppendSection(config: AgentPromptConfig, env: EnvInfo): string {
|
|
62
|
+
const bridge = `<sub_agent_context>
|
|
48
63
|
You are operating as a sub-agent invoked to handle a specific task.
|
|
49
64
|
- Make independent tool calls in parallel
|
|
50
65
|
- Use absolute file paths
|
|
@@ -52,27 +67,9 @@ You are operating as a sub-agent invoked to handle a specific task.
|
|
|
52
67
|
- Be concise but complete
|
|
53
68
|
</sub_agent_context>`;
|
|
54
69
|
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
// Place shared/stable content first so the LLM's KV cache can reuse the
|
|
60
|
-
// inherited prefix across all subagent invocations. The parent prompt is
|
|
61
|
-
// placed verbatim (no wrapper tag) so it forms an identical byte prefix
|
|
62
|
-
// with the parent session, maximising KV cache hits. The <active_agent>
|
|
63
|
-
// tag and env block vary per call and are placed after the cached prefix.
|
|
64
|
-
return `${identity}\n\n${bridge}\n\n${activeAgentTag}${envBlock}${customSection}`;
|
|
65
|
-
}
|
|
70
|
+
const customSection = config.systemPrompt.trim()
|
|
71
|
+
? `\n\n<agent_instructions>\n${config.systemPrompt}\n</agent_instructions>`
|
|
72
|
+
: "";
|
|
66
73
|
|
|
67
|
-
|
|
68
|
-
// the active_agent tag, env block, and the config's full system prompt.
|
|
69
|
-
// Unlike append mode, no <sub_agent_context> bridge or <agent_instructions>
|
|
70
|
-
// wrapper is injected — the custom prompt retains full control.
|
|
71
|
-
return `${identity}\n\n${activeAgentTag}${envBlock}\n\n${config.systemPrompt}`;
|
|
74
|
+
return `${bridge}\n\n<active_agent name="${config.name}"/>\n\n${environmentBlock(env)}${customSection}`;
|
|
72
75
|
}
|
|
73
|
-
|
|
74
|
-
/** Fallback base prompt when parent system prompt is unavailable (both modes). */
|
|
75
|
-
const genericBase = `# Role
|
|
76
|
-
You are a general-purpose coding agent for complex, multi-step tasks.
|
|
77
|
-
You have full access to read, write, edit files, and execute commands.
|
|
78
|
-
Do what has been asked; nothing more, nothing less.`;
|
|
@@ -25,7 +25,8 @@ import type { AgentPromptConfig, SubagentType, ThinkingLevel } from "../types";
|
|
|
25
25
|
* at the edge (`create-subagent-session.ts`) or stubs in tests.
|
|
26
26
|
*/
|
|
27
27
|
export interface AssemblerIO {
|
|
28
|
-
|
|
28
|
+
buildReplacePrompt: (config: AgentPromptConfig, env: EnvInfo) => string;
|
|
29
|
+
buildAppendSection: (config: AgentPromptConfig, env: EnvInfo) => string;
|
|
29
30
|
}
|
|
30
31
|
|
|
31
32
|
/**
|
|
@@ -38,10 +39,8 @@ export interface AssemblerIO {
|
|
|
38
39
|
* `resolveDefaultModel`.
|
|
39
40
|
*/
|
|
40
41
|
export interface AssemblerContext {
|
|
41
|
-
/** Parent working directory
|
|
42
|
+
/** Parent working directory — every child runs here. */
|
|
42
43
|
cwd: string;
|
|
43
|
-
/** Parent's effective system prompt (for append-mode agents). */
|
|
44
|
-
parentSystemPrompt: string;
|
|
45
44
|
/** Parent's current model instance (fallback when agent config has no model). */
|
|
46
45
|
parentModel?: unknown;
|
|
47
46
|
/** Model registry for resolving config.model strings. */
|
|
@@ -56,8 +55,6 @@ export interface AssemblerContext {
|
|
|
56
55
|
* All fields are optional — callers pass only what they have.
|
|
57
56
|
*/
|
|
58
57
|
export interface AssemblerOptions {
|
|
59
|
-
/** Override working directory (e.g. for worktree isolation). */
|
|
60
|
-
cwd?: string;
|
|
61
58
|
/** Explicit model override — wins over agentConfig.model and parent model. */
|
|
62
59
|
model?: unknown;
|
|
63
60
|
/** Explicit thinking level — wins over agentConfig.thinking. */
|
|
@@ -70,10 +67,12 @@ export interface AssemblerOptions {
|
|
|
70
67
|
* with no SDK object references.
|
|
71
68
|
*/
|
|
72
69
|
export interface SessionConfig {
|
|
73
|
-
/**
|
|
74
|
-
|
|
75
|
-
/**
|
|
76
|
-
|
|
70
|
+
/** Working directory for the child — the parent's cwd, the only source. */
|
|
71
|
+
cwd: string;
|
|
72
|
+
/** Prompt mode declared by the agent; decides how the caller wires the resource loader. */
|
|
73
|
+
promptMode: "replace" | "append";
|
|
74
|
+
/** Mode-specific text: the complete system prompt for "replace", the appended section for "append". */
|
|
75
|
+
promptSection: string;
|
|
77
76
|
/** Built-in tool name allowlist for this agent type. */
|
|
78
77
|
toolNames: string[];
|
|
79
78
|
/**
|
|
@@ -130,7 +129,7 @@ function resolveDefaultModel(
|
|
|
130
129
|
*
|
|
131
130
|
* @param type The subagent type name (case-insensitive registry lookup).
|
|
132
131
|
* @param ctx Narrow context from the parent session.
|
|
133
|
-
* @param options Per-call overrides (
|
|
132
|
+
* @param options Per-call overrides (model, thinkingLevel).
|
|
134
133
|
* @param env Pre-resolved environment info from `detectEnv()`.
|
|
135
134
|
* @param registry Agent config lookup — provides resolveAgentConfig and getToolNamesForType.
|
|
136
135
|
* @param io IO collaborators (skill loader, memory builder, prompt builder).
|
|
@@ -145,12 +144,14 @@ export function assembleSessionConfig(
|
|
|
145
144
|
): SessionConfig {
|
|
146
145
|
const agentConfig = registry.resolveAgentConfig(type);
|
|
147
146
|
|
|
148
|
-
const effectiveCwd = options.cwd ?? ctx.cwd;
|
|
149
|
-
|
|
150
147
|
const toolNames = registry.getToolNamesForType(type);
|
|
151
148
|
|
|
152
|
-
//
|
|
153
|
-
|
|
149
|
+
// Assemble the prompt text: "replace" owns the whole prompt, "append" only
|
|
150
|
+
// contributes a section on top of the harness-rendered base prompt.
|
|
151
|
+
const promptSection =
|
|
152
|
+
agentConfig.promptMode === "replace"
|
|
153
|
+
? io.buildReplacePrompt(agentConfig, env)
|
|
154
|
+
: io.buildAppendSection(agentConfig, env);
|
|
154
155
|
|
|
155
156
|
// Model resolution: explicit option > config model string > parent model
|
|
156
157
|
const model = options.model ?? resolveDefaultModel(ctx.parentModel, ctx.modelRegistry, agentConfig.model);
|
|
@@ -162,8 +163,9 @@ export function assembleSessionConfig(
|
|
|
162
163
|
const agentMaxTurns = agentConfig.maxTurns;
|
|
163
164
|
|
|
164
165
|
return {
|
|
165
|
-
|
|
166
|
-
|
|
166
|
+
cwd: ctx.cwd,
|
|
167
|
+
promptMode: agentConfig.promptMode,
|
|
168
|
+
promptSection,
|
|
167
169
|
toolNames,
|
|
168
170
|
model,
|
|
169
171
|
thinkingLevel,
|
package/src/settings.ts
CHANGED
|
@@ -14,6 +14,8 @@ export interface SubagentsSettings {
|
|
|
14
14
|
* `/agents` → Settings input prompt explicitly says "0 = unlimited".
|
|
15
15
|
*/
|
|
16
16
|
defaultMaxTurns?: number;
|
|
17
|
+
/** Default wall-clock timeout in seconds for spawned agents. 0 = unlimited. */
|
|
18
|
+
defaultTimeoutSeconds?: number;
|
|
17
19
|
graceTurns?: number;
|
|
18
20
|
/**
|
|
19
21
|
* Capability/cost tier → real model mapping. Used only to generate the
|
|
@@ -37,6 +39,7 @@ const DEFAULT_GRACE_TURNS = 5;
|
|
|
37
39
|
*/
|
|
38
40
|
export class SettingsManager {
|
|
39
41
|
private _defaultMaxTurns: number | undefined = undefined;
|
|
42
|
+
private _defaultTimeoutSeconds: number | undefined = undefined;
|
|
40
43
|
private _graceTurns: number = DEFAULT_GRACE_TURNS;
|
|
41
44
|
private _maxConcurrent: number = DEFAULT_MAX_CONCURRENT;
|
|
42
45
|
private _modelTiers: ModelTierMap = {};
|
|
@@ -67,6 +70,20 @@ export class SettingsManager {
|
|
|
67
70
|
}
|
|
68
71
|
}
|
|
69
72
|
|
|
73
|
+
// ── defaultTimeoutSeconds: 0 or undefined → unlimited (undefined); else max(1, n) ──
|
|
74
|
+
|
|
75
|
+
get defaultTimeoutSeconds(): number | undefined {
|
|
76
|
+
return this._defaultTimeoutSeconds;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
set defaultTimeoutSeconds(n: number | undefined) {
|
|
80
|
+
if (n == null || n === 0) {
|
|
81
|
+
this._defaultTimeoutSeconds = undefined;
|
|
82
|
+
} else {
|
|
83
|
+
this._defaultTimeoutSeconds = Math.max(1, n);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
70
87
|
// ── graceTurns: minimum 1 ──
|
|
71
88
|
|
|
72
89
|
get graceTurns(): number {
|
|
@@ -104,6 +121,9 @@ export class SettingsManager {
|
|
|
104
121
|
const settings = loadSettings(this.agentDir, this.cwd);
|
|
105
122
|
if (typeof settings.maxConcurrent === "number") this.maxConcurrent = settings.maxConcurrent;
|
|
106
123
|
if (typeof settings.defaultMaxTurns === "number") this.defaultMaxTurns = settings.defaultMaxTurns;
|
|
124
|
+
if (typeof settings.defaultTimeoutSeconds === "number") {
|
|
125
|
+
this.defaultTimeoutSeconds = settings.defaultTimeoutSeconds;
|
|
126
|
+
}
|
|
107
127
|
if (typeof settings.graceTurns === "number") this.graceTurns = settings.graceTurns;
|
|
108
128
|
this._modelTiers = settings.modelTiers ? { ...settings.modelTiers } : {};
|
|
109
129
|
this.emit("subagents:settings_loaded", { settings });
|
|
@@ -116,10 +136,17 @@ export class SettingsManager {
|
|
|
116
136
|
* `modelTiers` is omitted when empty so hand-edited tier maps are only
|
|
117
137
|
* rewritten (not replaced with an empty object) when they exist.
|
|
118
138
|
*/
|
|
119
|
-
snapshot(): {
|
|
139
|
+
snapshot(): {
|
|
140
|
+
maxConcurrent: number;
|
|
141
|
+
defaultMaxTurns: number;
|
|
142
|
+
defaultTimeoutSeconds: number;
|
|
143
|
+
graceTurns: number;
|
|
144
|
+
modelTiers?: ModelTierMap;
|
|
145
|
+
} {
|
|
120
146
|
return {
|
|
121
147
|
maxConcurrent: this._maxConcurrent,
|
|
122
148
|
defaultMaxTurns: this._defaultMaxTurns ?? 0,
|
|
149
|
+
defaultTimeoutSeconds: this._defaultTimeoutSeconds ?? 0,
|
|
123
150
|
graceTurns: this._graceTurns,
|
|
124
151
|
...(Object.keys(this._modelTiers).length > 0 ? { modelTiers: { ...this._modelTiers } } : {}),
|
|
125
152
|
};
|
|
@@ -145,6 +172,16 @@ export class SettingsManager {
|
|
|
145
172
|
return this.saveAndNotify(`Default max turns set to ${label}`);
|
|
146
173
|
}
|
|
147
174
|
|
|
175
|
+
/**
|
|
176
|
+
* Set defaultTimeoutSeconds, persist, and return the toast.
|
|
177
|
+
* Pass 0 for unlimited (maps to undefined internally).
|
|
178
|
+
*/
|
|
179
|
+
applyDefaultTimeoutSeconds(n: number): { message: string; level: "info" | "warning" } {
|
|
180
|
+
this.defaultTimeoutSeconds = n === 0 ? undefined : n; // setter normalizes further
|
|
181
|
+
const label = this.defaultTimeoutSeconds == null ? "unlimited" : `${this.defaultTimeoutSeconds}s`;
|
|
182
|
+
return this.saveAndNotify(`Default timeout set to ${label}`);
|
|
183
|
+
}
|
|
184
|
+
|
|
148
185
|
/**
|
|
149
186
|
* Set graceTurns, persist, and return the toast.
|
|
150
187
|
*/
|
|
@@ -170,6 +207,7 @@ export class SettingsManager {
|
|
|
170
207
|
// that any realistic power-user setting passes through.
|
|
171
208
|
const MAX_CONCURRENT_CEILING = 1024;
|
|
172
209
|
const MAX_TURNS_CEILING = 10_000;
|
|
210
|
+
const MAX_TIMEOUT_SECONDS_CEILING = 86_400;
|
|
173
211
|
const GRACE_TURNS_CEILING = 1_000;
|
|
174
212
|
|
|
175
213
|
/** Drop fields that don't match the expected shape. Silent — garbage becomes absent. */
|
|
@@ -191,6 +229,13 @@ function sanitize(raw: unknown): SubagentsSettings {
|
|
|
191
229
|
) {
|
|
192
230
|
out.defaultMaxTurns = r.defaultMaxTurns as number;
|
|
193
231
|
}
|
|
232
|
+
if (
|
|
233
|
+
Number.isInteger(r.defaultTimeoutSeconds) &&
|
|
234
|
+
(r.defaultTimeoutSeconds as number) >= 0 &&
|
|
235
|
+
(r.defaultTimeoutSeconds as number) <= MAX_TIMEOUT_SECONDS_CEILING
|
|
236
|
+
) {
|
|
237
|
+
out.defaultTimeoutSeconds = r.defaultTimeoutSeconds as number;
|
|
238
|
+
}
|
|
194
239
|
if (
|
|
195
240
|
Number.isInteger(r.graceTurns) &&
|
|
196
241
|
(r.graceTurns as number) >= 1 &&
|