pi-suite 0.0.0-stage → 0.3.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/LICENSE +21 -0
- package/README.md +100 -2
- package/README.zh-CN.md +101 -0
- package/package.json +63 -4
- package/skills/pi-suite-jobs/SKILL.md +76 -0
- package/skills/pi-suite-workflow/SKILL.md +114 -0
- package/src/agents/catalog.ts +80 -0
- package/src/agents/child.ts +79 -0
- package/src/agents/commands.ts +17 -0
- package/src/agents/defaults.ts +78 -0
- package/src/agents/history.ts +112 -0
- package/src/agents/index.ts +211 -0
- package/src/agents/manager.ts +438 -0
- package/src/agents/mentions/clone.ts +51 -0
- package/src/agents/mentions/grammar.ts +64 -0
- package/src/agents/mentions/index.ts +76 -0
- package/src/agents/mentions/provider.ts +79 -0
- package/src/agents/model-editor.ts +95 -0
- package/src/agents/models.ts +43 -0
- package/src/agents/output/schema.ts +101 -0
- package/src/agents/output/tool.ts +98 -0
- package/src/agents/parent.ts +13 -0
- package/src/agents/questions.ts +63 -0
- package/src/agents/records.ts +90 -0
- package/src/agents/registry.ts +20 -0
- package/src/agents/render.ts +85 -0
- package/src/agents/resources/context.ts +48 -0
- package/src/agents/resources/loader.ts +86 -0
- package/src/agents/resources/memory.ts +67 -0
- package/src/agents/resources/packages.ts +96 -0
- package/src/agents/resources/paths.ts +8 -0
- package/src/agents/resources/prompts.ts +11 -0
- package/src/agents/resources/scope.ts +147 -0
- package/src/agents/resources/selectors.ts +186 -0
- package/src/agents/retry.ts +20 -0
- package/src/agents/rpc/handlers.ts +62 -0
- package/src/agents/rpc/index.ts +73 -0
- package/src/agents/rpc/options.ts +44 -0
- package/src/agents/run-groups.ts +16 -0
- package/src/agents/runner.ts +131 -0
- package/src/agents/runtime.ts +40 -0
- package/src/agents/schedules/index.ts +136 -0
- package/src/agents/schedules/menu.ts +38 -0
- package/src/agents/schedules/parse.ts +42 -0
- package/src/agents/schedules/store.ts +78 -0
- package/src/agents/schema.ts +5 -0
- package/src/agents/session.ts +29 -0
- package/src/agents/tools.ts +177 -0
- package/src/agents/types.ts +87 -0
- package/src/agents/ui/index.ts +42 -0
- package/src/agents/ui/runs.ts +122 -0
- package/src/agents/ui/types.ts +91 -0
- package/src/agents/viewer-info.ts +36 -0
- package/src/agents/viewer.ts +160 -0
- package/src/agents/workflow/collisions.ts +124 -0
- package/src/agents/workflow/entry.ts +93 -0
- package/src/agents/workflow/host.ts +119 -0
- package/src/agents/workflow/index.ts +100 -0
- package/src/agents/workflow/journal.ts +147 -0
- package/src/agents/workflow/literal.ts +57 -0
- package/src/agents/workflow/manager.ts +169 -0
- package/src/agents/workflow/meta.ts +323 -0
- package/src/agents/workflow/progress/format.ts +184 -0
- package/src/agents/workflow/progress/index.ts +3 -0
- package/src/agents/workflow/progress/model.ts +224 -0
- package/src/agents/workflow/progress/types.ts +144 -0
- package/src/agents/workflow/render.ts +46 -0
- package/src/agents/workflow/runtime/helpers.ts +236 -0
- package/src/agents/workflow/runtime/index.ts +3 -0
- package/src/agents/workflow/runtime/run.ts +646 -0
- package/src/agents/workflow/runtime/types.ts +273 -0
- package/src/agents/workflow/saved.ts +74 -0
- package/src/agents/workflow/store.ts +23 -0
- package/src/agents/workflow/task.ts +277 -0
- package/src/agents/workflow/tool-description.ts +32 -0
- package/src/agents/workflow/tools.ts +66 -0
- package/src/agents/workflow/ui/menu.ts +144 -0
- package/src/agents/workflow/ui/progress.ts +91 -0
- package/src/agents/workflow/worker/bootstrap.ts +316 -0
- package/src/agents/workflow/worker/flow.ts +218 -0
- package/src/agents/workflow/worker/index.ts +7 -0
- package/src/agents/workflow/worker/scope.ts +215 -0
- package/src/ask/.gitkeep +0 -0
- package/src/ask/form.ts +67 -0
- package/src/ask/index.ts +73 -0
- package/src/ask/keys.ts +32 -0
- package/src/ask/layout.ts +78 -0
- package/src/ask/queue.ts +40 -0
- package/src/ask/render.ts +62 -0
- package/src/ask/result.ts +56 -0
- package/src/ask/schema.ts +67 -0
- package/src/ask/tool-render.ts +49 -0
- package/src/ask/view.ts +406 -0
- package/src/goal/.gitkeep +0 -0
- package/src/goal/activity.ts +50 -0
- package/src/goal/commands.ts +75 -0
- package/src/goal/context.ts +36 -0
- package/src/goal/index.ts +38 -0
- package/src/goal/manager.ts +386 -0
- package/src/goal/presentation.ts +15 -0
- package/src/goal/render.ts +36 -0
- package/src/goal/snapshot.ts +78 -0
- package/src/goal/state.ts +39 -0
- package/src/goal/store.ts +59 -0
- package/src/goal/tools.ts +59 -0
- package/src/goal/wait.ts +39 -0
- package/src/index.ts +20 -0
- package/src/jobs/backends/linux-tree.ts +87 -0
- package/src/jobs/backends/pipe.ts +74 -0
- package/src/jobs/backends/process.ts +79 -0
- package/src/jobs/backends/pty-job.ts +45 -0
- package/src/jobs/backends/pty.ts +502 -0
- package/src/jobs/backends/windows-tree.ts +289 -0
- package/src/jobs/commands.ts +7 -0
- package/src/jobs/control.ts +13 -0
- package/src/jobs/index.ts +331 -0
- package/src/jobs/launch/config.ts +26 -0
- package/src/jobs/launch/name.ts +16 -0
- package/src/jobs/launch/presets.ts +61 -0
- package/src/jobs/log-viewer.ts +147 -0
- package/src/jobs/manager.ts +507 -0
- package/src/jobs/monitors/compile.ts +101 -0
- package/src/jobs/monitors/hands-free.ts +108 -0
- package/src/jobs/monitors/runtime.ts +165 -0
- package/src/jobs/output.ts +54 -0
- package/src/jobs/query.ts +62 -0
- package/src/jobs/render.ts +103 -0
- package/src/jobs/runtime.ts +89 -0
- package/src/jobs/state.ts +25 -0
- package/src/jobs/store.ts +168 -0
- package/src/jobs/terminal/keys.ts +292 -0
- package/src/jobs/terminal/protocol.ts +37 -0
- package/src/jobs/terminal/read.ts +131 -0
- package/src/jobs/terminal/render.ts +70 -0
- package/src/jobs/terminal/screen.ts +92 -0
- package/src/jobs/terminal/session.ts +100 -0
- package/src/jobs/terminal/shell.ts +22 -0
- package/src/jobs/terminal/snapshot.ts +8 -0
- package/src/jobs/terminal/visible-text.ts +53 -0
- package/src/jobs/tools.ts +203 -0
- package/src/jobs/types.ts +60 -0
- package/src/jobs/viewer/component.ts +209 -0
- package/src/jobs/viewer/metadata.ts +9 -0
- package/src/jobs/viewer.ts +149 -0
- package/src/jobs/workspace.ts +31 -0
- package/src/runtime/.gitkeep +0 -0
- package/src/runtime/binding.ts +26 -0
- package/src/runtime/cli-prompt.ts +24 -0
- package/src/runtime/clipboard.ts +16 -0
- package/src/runtime/config-edit.ts +31 -0
- package/src/runtime/config-fields.ts +65 -0
- package/src/runtime/config.ts +111 -0
- package/src/runtime/errors.ts +11 -0
- package/src/runtime/json-store.ts +156 -0
- package/src/runtime/notification-render.ts +35 -0
- package/src/runtime/notifications.ts +98 -0
- package/src/runtime/owner.ts +54 -0
- package/src/runtime/read.ts +200 -0
- package/src/runtime/renderers.ts +50 -0
- package/src/runtime/responses/index.ts +108 -0
- package/src/runtime/responses/payload.ts +78 -0
- package/src/runtime/settings/index.ts +24 -0
- package/src/runtime/settings/view.ts +84 -0
- package/src/runtime/suite.ts +192 -0
- package/src/runtime/text.ts +6 -0
- package/src/runtime/tools.ts +131 -0
- package/src/runtime/wait-render.ts +33 -0
- package/src/runtime/wait.ts +134 -0
- package/src/tasks/commands.ts +41 -0
- package/src/tasks/index.ts +305 -0
- package/src/tasks/model.ts +152 -0
- package/src/tasks/presentation.ts +40 -0
- package/src/tasks/query.ts +38 -0
- package/src/tasks/render.ts +54 -0
- package/src/tasks/schema.ts +25 -0
- package/src/tasks/store.ts +164 -0
- package/src/tasks/tools.ts +69 -0
- package/src/tasks/types.ts +61 -0
- package/src/tasks/viewer.ts +68 -0
- package/src/ui/.gitkeep +0 -0
- package/src/ui/actions.ts +50 -0
- package/src/ui/browser-chrome.ts +175 -0
- package/src/ui/browser.ts +292 -0
- package/src/ui/details.ts +111 -0
- package/src/ui/dock/line.ts +14 -0
- package/src/ui/dock/rows.ts +78 -0
- package/src/ui/dock.ts +224 -0
- package/src/ui/format.ts +25 -0
- package/src/ui/frame.ts +8 -0
- package/src/ui/inline-input.ts +98 -0
- package/src/ui/reading.ts +105 -0
- package/src/ui/rendering/builtin-command.ts +34 -0
- package/src/ui/rendering/command.ts +60 -0
- package/src/ui/rendering/read-page.ts +15 -0
- package/src/ui/rendering/shell/bash.ts +281 -0
- package/src/ui/rendering/shell/index.ts +24 -0
- package/src/ui/rendering/shell/powershell.ts +155 -0
- package/src/ui/rendering/shell/spans.ts +28 -0
- package/src/ui/scroll.ts +111 -0
- package/src/ui/select.ts +67 -0
- package/src/ui/status.ts +67 -0
- package/src/ui/structured-details.ts +41 -0
- package/src/ui/terminal.ts +137 -0
- package/src/ui/ticker.ts +18 -0
- package/src/ui/tool-render.ts +152 -0
- package/src/ui/transcript.ts +140 -0
- package/src/ui/viewer/agent-information.ts +34 -0
- package/src/ui/viewer/editor.ts +18 -0
- package/src/ui/viewer/navigation.ts +25 -0
- package/themes/oh-my-pi.json +95 -0
- package/third-party/UPSTREAM.md +88 -0
- package/third-party/licenses/.gitkeep +0 -0
- package/third-party/licenses/oh-my-pi.txt +23 -0
- package/third-party/licenses/pi-ask-user.txt +21 -0
- package/third-party/licenses/pi-background-jobs.txt +21 -0
- package/third-party/licenses/pi-goal.txt +21 -0
- package/third-party/licenses/pi-interactive-shell.txt +25 -0
- package/third-party/licenses/pi-subagents.txt +21 -0
- package/third-party/licenses/pi-tasks.txt +21 -0
- package/third-party/sources.json +111 -0
|
@@ -0,0 +1,438 @@
|
|
|
1
|
+
// Two-pool charging/FIFO and run lifecycle adapted from @tintinweb/pi-subagents 0.23.0 src/agent-manager.ts (MIT).
|
|
2
|
+
import { randomBytes } from 'node:crypto';
|
|
3
|
+
import { performance } from 'node:perf_hooks';
|
|
4
|
+
import type { ExtensionContext } from '@earendil-works/pi-coding-agent';
|
|
5
|
+
import type { SuiteConfig } from '../runtime/config.ts';
|
|
6
|
+
import type { StopOutcome } from '../runtime/tools.ts';
|
|
7
|
+
import { requireGeneration } from '../tasks/types.ts';
|
|
8
|
+
import { ToolError } from '../runtime/errors.ts';
|
|
9
|
+
import { resolveType } from './catalog.ts';
|
|
10
|
+
import { parentModelRuntime, resolveSettings } from './models.ts';
|
|
11
|
+
import { hydrate, transcript } from './records.ts';
|
|
12
|
+
import { compareRunRecency } from './run-groups.ts';
|
|
13
|
+
import { ModelRequestError, retryable } from './retry.ts';
|
|
14
|
+
import { AgentHistory } from './history.ts';
|
|
15
|
+
import { answerParent } from './questions.ts';
|
|
16
|
+
import { closeAgent } from './session.ts';
|
|
17
|
+
import { buildParentContext } from './resources/context.ts';
|
|
18
|
+
import { captureParent } from './parent.ts';
|
|
19
|
+
import { assignHandle, handleBase } from './mentions/grammar.ts';
|
|
20
|
+
import { active, isTopLevelAgent, recordWorkspace, visibleAgent, type AgentEventKind, type AgentRecord, type Execution, type ParentScope, type Pool, type StartAgent, type StartOptions } from './types.ts';
|
|
21
|
+
|
|
22
|
+
const allocate = (prefix: string) => `${prefix}_${randomBytes(4).toString('hex')}`;
|
|
23
|
+
export class AgentManager {
|
|
24
|
+
readonly runs = new Map<string, Execution>();
|
|
25
|
+
private histories = new Map<string, {record: AgentRecord; updatedAt: number}>();
|
|
26
|
+
private history = new AgentHistory();
|
|
27
|
+
private queue: Execution[] = [];
|
|
28
|
+
private counts = { background: 0, foreground: 0 };
|
|
29
|
+
private limits = { background: 10, foreground: 0 };
|
|
30
|
+
private closing = false;
|
|
31
|
+
private listeners = new Set<() => void>();
|
|
32
|
+
private eventListeners = new Set<(kind: AgentEventKind, run: Execution, details: Record<string, unknown>) => void>();
|
|
33
|
+
private closedRuns = new Set<string>();
|
|
34
|
+
private stops = new Map<string, Promise<StopOutcome>>();
|
|
35
|
+
private retained = new Map<string, number>();
|
|
36
|
+
private cleanupTimer?: NodeJS.Timeout;
|
|
37
|
+
constructor(private execute: (run: Execution) => Promise<void>, private stopJobs: (ids: string[]) => Promise<StopOutcome['affected']>) {}
|
|
38
|
+
get closed(): boolean { return this.closing; }
|
|
39
|
+
/** Replacing the owner drops in-memory executions: keep it while any run, question or unread result depends on it. */
|
|
40
|
+
busy(): boolean {
|
|
41
|
+
if (this.stops.size) return true;
|
|
42
|
+
for (const run of this.runs.values()) if (!run.settled || run.question && !run.question.seen || this.resultPending(run)) return true;
|
|
43
|
+
return false;
|
|
44
|
+
}
|
|
45
|
+
private resultPending(run: Execution): boolean {
|
|
46
|
+
const parent = run.record.parentRunId ? this.runs.get(run.record.parentRunId) : undefined;
|
|
47
|
+
// The workflow host consumes its own results; only a live nested parent can receive notices.
|
|
48
|
+
return !run.consumed && Boolean(run.record.background || run.notifyResult)
|
|
49
|
+
&& (run.record.parentRunId ? Boolean(parent && !parent.settled) : !run.record.workflowId);
|
|
50
|
+
}
|
|
51
|
+
configure(config: SuiteConfig): void {
|
|
52
|
+
this.limits = { background: config.agents.maxConcurrent, foreground: config.agents.maxConcurrentForeground };
|
|
53
|
+
this.drain();
|
|
54
|
+
}
|
|
55
|
+
subscribe(listener: () => void): () => void { this.listeners.add(listener); return () => this.listeners.delete(listener); }
|
|
56
|
+
changed = (): void => { for (const listener of [...this.listeners]) listener(); };
|
|
57
|
+
subscribeEvents(listener: (kind: AgentEventKind, run: Execution, details: Record<string, unknown>) => void): () => void {
|
|
58
|
+
this.eventListeners.add(listener); return () => this.eventListeners.delete(listener);
|
|
59
|
+
}
|
|
60
|
+
event(kind: AgentEventKind, run: Execution, details: Record<string, unknown> = {}): void {
|
|
61
|
+
if (kind === 'started') run.startup?.resolve(undefined);
|
|
62
|
+
for (const listener of [...this.eventListeners]) listener(kind, run, details);
|
|
63
|
+
}
|
|
64
|
+
async awaitStartup(run: Execution): Promise<void> {
|
|
65
|
+
// A queued spawn returns its ID without waiting for a pool slot, as upstream does.
|
|
66
|
+
const error = await run.startup?.promise;
|
|
67
|
+
if (error !== undefined) throw new Error(error);
|
|
68
|
+
}
|
|
69
|
+
restore(records: AgentRecord[]): void {
|
|
70
|
+
for (const record of records) if (!this.runs.has(record.runId)) this.histories.set(record.runId, {record: hydrate(record), updatedAt: Date.now()});
|
|
71
|
+
}
|
|
72
|
+
async discover(scope: ParentScope, config: SuiteConfig, signal?: AbortSignal): Promise<void> {
|
|
73
|
+
const candidates = await this.history.scan(scope, config, signal);
|
|
74
|
+
for (const candidate of candidates) {
|
|
75
|
+
if (this.runs.has(candidate.record.runId)) continue;
|
|
76
|
+
const old = this.histories.get(candidate.record.runId);
|
|
77
|
+
if (!old || candidate.updatedAt > old.updatedAt) this.histories.set(candidate.record.runId, candidate);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
async lookup(id: string, scope: ParentScope, config: SuiteConfig, runId?: string, signal?: AbortSignal) {
|
|
81
|
+
if (!this.records().some(record => record.id === id && (!runId || record.runId === runId))) await this.discover(scope, config, signal);
|
|
82
|
+
const found = this.get(id, runId);
|
|
83
|
+
if (recordWorkspace(found.record) !== (scope.run?.configCwd ?? scope.ctx.cwd)) throw new ToolError('NOT_FOUND', `No workspace agent ${id}. Use agent_list with scope:"workspace" and state:"all" to find an agent in this workspace.`, id);
|
|
84
|
+
return found;
|
|
85
|
+
}
|
|
86
|
+
/** Readers and workflow continuations keep their in-memory SDK tree until they close. */
|
|
87
|
+
retain(runId: string): () => void {
|
|
88
|
+
this.retained.set(runId, (this.retained.get(runId) ?? 0) + 1);
|
|
89
|
+
return () => {
|
|
90
|
+
const remaining = this.retained.get(runId)! - 1;
|
|
91
|
+
if (remaining) this.retained.set(runId, remaining);
|
|
92
|
+
else this.retained.delete(runId);
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
/** Adapt upstream's ten-minute sweep to the existing history and notification owners. */
|
|
96
|
+
sweep(now = Date.now()): void {
|
|
97
|
+
let changed = false;
|
|
98
|
+
for (const [runId, run] of this.runs) {
|
|
99
|
+
if (!run.settled || this.retained.has(runId) || Date.parse(run.record.endedAt!) >= now - 10 * 60_000) continue;
|
|
100
|
+
if (this.resultPending(run)) continue;
|
|
101
|
+
this.histories.set(runId, {record: this.view(run), updatedAt: Date.now()});
|
|
102
|
+
this.runs.delete(runId); this.closedRuns.delete(runId); changed = true;
|
|
103
|
+
}
|
|
104
|
+
if (!this.runs.size) { clearInterval(this.cleanupTimer); this.cleanupTimer = undefined; }
|
|
105
|
+
if (changed) this.changed();
|
|
106
|
+
}
|
|
107
|
+
records(): AgentRecord[] {
|
|
108
|
+
return [...this.histories.values()].map(history => history.record).concat([...this.runs.values()].map(run => this.view(run)));
|
|
109
|
+
}
|
|
110
|
+
view(run: Execution): AgentRecord {
|
|
111
|
+
const state = !run.settled && !active(run.record.state) ? run.controller.signal.aborted ? 'stopping' : 'running' : run.record.state;
|
|
112
|
+
return { ...run.record, state, elapsedMs: run.startedMonotonic !== undefined && !run.settled
|
|
113
|
+
? Math.round(performance.now() - run.startedMonotonic) : run.record.elapsedMs };
|
|
114
|
+
}
|
|
115
|
+
get(id: string, runId?: string): { record: AgentRecord; run?: Execution } {
|
|
116
|
+
const records = this.records().filter(record => record.id === id && (!runId || record.runId === runId))
|
|
117
|
+
.sort(compareRunRecency);
|
|
118
|
+
const record = records[0];
|
|
119
|
+
if (!record) throw new ToolError('NOT_FOUND', `No agent ${id}${runId ? ` run ${runId}` : ''}; discover with agent_list({"scope":"workspace","state":"all"})`, id);
|
|
120
|
+
return { record, run: this.runs.get(record.runId) };
|
|
121
|
+
}
|
|
122
|
+
isStopping(id: string): boolean {
|
|
123
|
+
// A stop may still own job cleanup after the run itself has settled.
|
|
124
|
+
for (const key of this.stops.keys()) if (key.startsWith(`${id}:`)) return true;
|
|
125
|
+
return false;
|
|
126
|
+
}
|
|
127
|
+
visible(record: AgentRecord, scope: ParentScope): boolean {
|
|
128
|
+
return visibleAgent(record, scope);
|
|
129
|
+
}
|
|
130
|
+
/** Workflow children report questions to their real parent without exposing ordinary steering. */
|
|
131
|
+
questionVisible(record: AgentRecord, scope: ParentScope): boolean {
|
|
132
|
+
return this.visible(record, scope) || !scope.run && record.workflowId !== undefined
|
|
133
|
+
&& record.parentAgentId === undefined && record.ownerSessionId === scope.ctx.sessionManager.getSessionId()
|
|
134
|
+
&& (record.anchorEntryId === null || scope.ctx.sessionManager.getBranch().some(entry => entry.id === record.anchorEntryId));
|
|
135
|
+
}
|
|
136
|
+
async start(request: StartAgent, scope: ParentScope, config: SuiteConfig, previous?: AgentRecord,
|
|
137
|
+
options: StartOptions = {}, continuation?: Execution): Promise<Execution> {
|
|
138
|
+
// Nested admission must use the child's own list. A facade without task tools may
|
|
139
|
+
// carry an ancestor store; that must never turn into permission to delegate its tasks.
|
|
140
|
+
scope = captureParent({ ...scope, taskStore: scope.run ? scope.run.taskStore : scope.taskStore });
|
|
141
|
+
options.signal?.throwIfAborted();
|
|
142
|
+
if (this.closing || scope.run && (!active(scope.run.record.state) || this.closedRuns.has(scope.run.record.runId))) {
|
|
143
|
+
throw new ToolError('NOT_RUNNING', 'Parent run has ended or is stopping. Ask its parent to start a new agent.');
|
|
144
|
+
}
|
|
145
|
+
const configCwd = scope.run?.configCwd ?? scope.ctx.cwd;
|
|
146
|
+
// A target-directory child reports its tools' cwd as untrusted. Carry the opened
|
|
147
|
+
// project's distinct trust with its config root through every nested generation.
|
|
148
|
+
const configTrusted = scope.run?.configTrusted ?? scope.ctx.isProjectTrusted();
|
|
149
|
+
const type = continuation?.type ?? resolveType(configCwd, previous?.type ?? request.type ?? 'general-purpose', {
|
|
150
|
+
trusted: configTrusted, packageGate: config.agents.packageAgents, typeSettings: config.agents.types });
|
|
151
|
+
if (scope.run) {
|
|
152
|
+
if (scope.run.isolated) throw new ToolError('AGENT_TYPE', 'An isolated child cannot start nested agents. Ask your parent to start another agent if needed.');
|
|
153
|
+
const allowed = scope.run.type.allowedSubagents;
|
|
154
|
+
if (!allowed || allowed !== 'all' && !allowed.includes(type.name)) throw new ToolError('AGENT_TYPE', `${scope.run.record.type} cannot start ${type.name}. Choose a type listed in allowed_subagents, or ask your parent to start it.`);
|
|
155
|
+
if (scope.run.record.ancestors.length + 1 >= config.agents.maxDepth) throw new ToolError('AGENT_DEPTH', 'agents.maxDepth reached. Ask your parent to delegate from a higher level.');
|
|
156
|
+
}
|
|
157
|
+
// Validate before task I/O or allocating a run. The runner also guards its
|
|
158
|
+
// SDK boundary because reload can retain managers from before this admission check.
|
|
159
|
+
parentModelRuntime(scope.ctx);
|
|
160
|
+
const settings = continuation ? { model: continuation.model, modelSource: continuation.record.modelSource,
|
|
161
|
+
thinking: continuation.record.thinking, thinkingSource: continuation.record.thinkingSource }
|
|
162
|
+
: resolveSettings(scope.ctx, type, request, config, previous?.individual);
|
|
163
|
+
const taskStore = scope.taskStore, taskId = previous?.taskId ?? request.taskId;
|
|
164
|
+
// A resumed run keeps its original task generation, even when the numeric ID was reused.
|
|
165
|
+
const taskGeneration = previous?.taskId ? previous.taskGeneration : request.taskGeneration;
|
|
166
|
+
if (taskId) {
|
|
167
|
+
requireGeneration(taskGeneration);
|
|
168
|
+
if (!taskStore) throw new ToolError('TASK_SCOPE', 'The direct parent has no task list. Omit taskId or enable the tasks module in the parent.');
|
|
169
|
+
const task = (await taskStore.snapshot(taskGeneration)).tasks.find(task => task.id === taskId);
|
|
170
|
+
if (!task?.parentId) throw new ToolError('NOT_FOUND', `No child task ${taskId} in the parent's current list. Use task_list to find a child task ID and its generation.`);
|
|
171
|
+
}
|
|
172
|
+
// Recheck after task I/O: stop closes subtree admission before awaiting any abort/job cleanup.
|
|
173
|
+
options.signal?.throwIfAborted();
|
|
174
|
+
if (this.closing || scope.run && (!active(scope.run.record.state) || this.closedRuns.has(scope.run.record.runId))) throw new ToolError('NOT_RUNNING', 'Parent run is stopping or has ended. Ask its parent to start a new agent.');
|
|
175
|
+
const id = previous?.id ?? allocate('agent');
|
|
176
|
+
// A settled child can still have leftover jobs being cleaned up by its stop operation.
|
|
177
|
+
if (this.isStopping(id)) throw new ToolError('ALREADY_RUNNING', `${id} is still stopping or cleaning up. Wait for agent_stop to finish before retrying.`, id);
|
|
178
|
+
if ([...this.runs.values()].some(run => run.record.id === id && !run.settled)) throw new ToolError('ALREADY_RUNNING', `${id} already has an active or finalizing run. Wait for it to finish before resuming.`, id);
|
|
179
|
+
const run = this.createRun(id, request, scope, config, options, type, settings, previous, continuation);
|
|
180
|
+
const { record } = run;
|
|
181
|
+
this.enqueue(run);
|
|
182
|
+
try { options.onSpawned?.(id); }
|
|
183
|
+
catch (error) { await this.stop(id, record.runId); throw error; }
|
|
184
|
+
this.bindAbort(run);
|
|
185
|
+
this.configure(config); this.changed();
|
|
186
|
+
if (record.state === 'queued') {
|
|
187
|
+
try { options.onQueued?.(id, this.queue.filter(item => item.record.background === record.background).indexOf(run)); }
|
|
188
|
+
catch (error) { await this.stop(id, record.runId); throw error; }
|
|
189
|
+
}
|
|
190
|
+
if (taskId && taskStore) {
|
|
191
|
+
try { await taskStore.link(taskId, { agentId: id }, taskGeneration!); }
|
|
192
|
+
catch (error) { throw new ToolError('TASK_LINK_FAILED', `Agent ${id} started, but linking task ${taskId} failed: ${String(error)}. Check the task before retrying the link; do not start another agent.`, id); }
|
|
193
|
+
}
|
|
194
|
+
return run;
|
|
195
|
+
}
|
|
196
|
+
private createRun(id: string, request: StartAgent, scope: ParentScope, config: SuiteConfig, options: StartOptions,
|
|
197
|
+
type: Execution['type'], settings: Pick<Execution, 'model'> & Pick<AgentRecord, 'modelSource' | 'thinking' | 'thinkingSource'>,
|
|
198
|
+
previous?: AgentRecord, continuation?: Execution): Execution {
|
|
199
|
+
const configCwd = scope.run?.configCwd ?? scope.ctx.cwd, configTrusted = scope.run?.configTrusted ?? scope.ctx.isProjectTrusted();
|
|
200
|
+
const taskId = previous?.taskId ?? request.taskId, taskGeneration = previous?.taskId ? previous.taskGeneration : request.taskGeneration;
|
|
201
|
+
// Handles and user aliases share a namespace across this owner's runs. Persisting them
|
|
202
|
+
// keeps a completed/resumed agent addressable without renumbering after reload or /tree.
|
|
203
|
+
const taken = new Set(this.records().filter(record => record.ownerSessionId === scope.owner!.ownerSessionId && record.id !== id)
|
|
204
|
+
.flatMap(record => [record.handle, record.alias].filter((name): name is string => name !== undefined)));
|
|
205
|
+
const workflowId = scope.run?.record.workflowId ?? options.workflowId;
|
|
206
|
+
const handle = scope.run || workflowId ? undefined : previous?.handle ?? assignHandle(handleBase(type.name), taken);
|
|
207
|
+
if (handle) taken.add(handle);
|
|
208
|
+
const alias = scope.run || workflowId ? undefined : previous?.alias ?? (request.name ? assignHandle(handleBase(request.name), taken) : undefined);
|
|
209
|
+
// A timer has no foreground caller or launch-time conversation; provenance selects
|
|
210
|
+
// background delivery and suppresses inherited text without changing the type definition.
|
|
211
|
+
const record: AgentRecord = { version: 1, id, runId: allocate('run'), type: type.name, name: request.name ?? previous?.name ?? type.displayName ?? type.name, handle, alias,
|
|
212
|
+
prompt: request.prompt, cwd: options.cwd ?? previous?.cwd ?? scope.ctx.cwd, configCwd, ...scope.owner!,
|
|
213
|
+
parentAgentId: scope.run?.record.id, parentRunId: scope.run?.record.runId,
|
|
214
|
+
ancestors: scope.run ? [...scope.run.record.ancestors, scope.run.record.runId] : [],
|
|
215
|
+
background: options.scheduleId ? true : type.runInBackground ?? request.background ?? true, scheduleId: options.scheduleId, workflowId, description: options.description, state: 'queued', createdAt: new Date(Math.max(Date.now(), previous ? Date.parse(previous.createdAt) + 1 : 0)).toISOString(),
|
|
216
|
+
model: `${settings.model.provider}/${settings.model.id}`, modelSource: settings.modelSource,
|
|
217
|
+
thinking: settings.thinking, thinkingSource: settings.thinkingSource,
|
|
218
|
+
persisted: previous?.persisted ?? type.persistSession ?? (!scope.run && config.agents.persistSessions), sessionFile: previous?.sessionFile,
|
|
219
|
+
taskId, taskGeneration, individual: previous?.individual, toolUses: 0, turns: 0 };
|
|
220
|
+
const run: Execution = { record, type, model: settings.model, parent: scope, controller: new AbortController(),
|
|
221
|
+
done: Promise.withResolvers(), pendingMessages: [], consumed: false, notifyResult: options.detached, maxTurns: type.maxTurns ?? request.maxTurns, request, config,
|
|
222
|
+
isolated: type.isolated ?? request.isolated, bypassQueue: options.bypassQueue, configCwd, configTrusted, options,
|
|
223
|
+
inheritedContext: !continuation && !options.scheduleId && (type.inheritContext ?? request.inheritContext) ? buildParentContext(scope.ctx) : undefined };
|
|
224
|
+
// Preserve a non-persisted transcript for same-process resume using the SDK's session tree.
|
|
225
|
+
if (previous && !previous.sessionFile) {
|
|
226
|
+
const prior = continuation ?? this.runs.get(previous.runId);
|
|
227
|
+
run.entries = transcript(previous, prior);
|
|
228
|
+
run.sessionManager = prior?.sessionManager;
|
|
229
|
+
}
|
|
230
|
+
return run;
|
|
231
|
+
}
|
|
232
|
+
private enqueue(run: Execution): void {
|
|
233
|
+
this.runs.set(run.record.runId, run); this.queue.push(run);
|
|
234
|
+
this.cleanupTimer ??= setInterval(() => this.sweep(), 60_000).unref();
|
|
235
|
+
this.event('created', run);
|
|
236
|
+
}
|
|
237
|
+
private bindAbort(run: Execution): void {
|
|
238
|
+
const { signal } = run.options;
|
|
239
|
+
if (!signal || run.settled) return;
|
|
240
|
+
const abort = () => { void this.stop(run.record.id, run.record.runId); };
|
|
241
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
242
|
+
run.detachAbort = () => signal.removeEventListener('abort', abort);
|
|
243
|
+
if (signal.aborted) abort();
|
|
244
|
+
}
|
|
245
|
+
/** Workflow continuation keeps its launch contract while using the SDK's existing session tree. */
|
|
246
|
+
resume(run: Execution, prompt: string, signal: AbortSignal, onSpawned?: (id: string) => void): Promise<Execution> {
|
|
247
|
+
if (!run.settled) throw new ToolError('ALREADY_RUNNING', `${run.record.id} is still finishing. Wait for this run to finish before resuming.`, run.record.id);
|
|
248
|
+
if (!run.sessionManager && !run.record.sessionFile) throw new ToolError('HISTORY_READ_ONLY', 'No workflow child session to continue. Start a new workflow child.', run.record.id);
|
|
249
|
+
return this.start({ ...run.request, prompt }, run.parent, run.config, run.record, { ...run.options, signal, onSpawned }, run);
|
|
250
|
+
}
|
|
251
|
+
/** Only an actual waiting caller can release a foreground run; RPC and resumed runs cannot. */
|
|
252
|
+
canSendToBackground(id: string, runId?: string): boolean {
|
|
253
|
+
const { record, run } = this.get(id, runId);
|
|
254
|
+
return Boolean(run?.foreground && !run.settled && isTopLevelAgent(record) && !record.background
|
|
255
|
+
&& active(run.record.state) && !['queued', 'stopping'].includes(run.record.state));
|
|
256
|
+
}
|
|
257
|
+
/** Adapt upstream's one-way handoff, including pool charging and caller wake-up. */
|
|
258
|
+
sendToBackground(id: string, runId?: string): boolean {
|
|
259
|
+
if (!this.canSendToBackground(id, runId)) return false;
|
|
260
|
+
const run = this.get(id, runId).run!;
|
|
261
|
+
if (run.chargedPool) {
|
|
262
|
+
this.counts[run.chargedPool]--; run.chargedPool = 'background'; this.counts.background++;
|
|
263
|
+
}
|
|
264
|
+
run.record.background = true; run.consumed = false;
|
|
265
|
+
run.foreground!.resolve(undefined);
|
|
266
|
+
this.changed(); this.drain(); return true;
|
|
267
|
+
}
|
|
268
|
+
private room(pool: Pool): boolean { return !this.limits[pool] || this.counts[pool] < this.limits[pool]; }
|
|
269
|
+
private pool(run: Execution): Pool | undefined {
|
|
270
|
+
if (!isTopLevelAgent(run.record) || run.options.detached && !run.record.background) return;
|
|
271
|
+
return run.record.background ? 'background' : 'foreground';
|
|
272
|
+
}
|
|
273
|
+
private drain(): void {
|
|
274
|
+
if (this.closing) return;
|
|
275
|
+
for (;;) {
|
|
276
|
+
// Choose the earliest runnable item for its own pool; a saturated foreground head must
|
|
277
|
+
// not block background work. Nested children are uncharged to avoid parent/child deadlock.
|
|
278
|
+
// Timed dispatches bypass saturation but still charge their ordinary pool below.
|
|
279
|
+
const index = this.queue.findIndex(run => {
|
|
280
|
+
if (run.retry?.timer) return false;
|
|
281
|
+
const pool = this.pool(run);
|
|
282
|
+
return pool === undefined || run.bypassQueue || this.room(pool);
|
|
283
|
+
});
|
|
284
|
+
if (index < 0) return;
|
|
285
|
+
const [run] = this.queue.splice(index, 1);
|
|
286
|
+
run.record.state = 'starting'; run.record.startedAt = new Date().toISOString(); run.startedMonotonic = performance.now();
|
|
287
|
+
run.startup = Promise.withResolvers();
|
|
288
|
+
run.chargedPool = this.pool(run);
|
|
289
|
+
if (run.chargedPool) this.counts[run.chargedPool]++;
|
|
290
|
+
void this.launch(run);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
private canAutoResume(run: Execution): boolean {
|
|
294
|
+
const parent = run.parent.run;
|
|
295
|
+
return !run.record.workflowId && !run.controller.signal.aborted && !run.terminated && !run.options.signal?.aborted
|
|
296
|
+
&& !this.closing && !this.isStopping(run.record.id)
|
|
297
|
+
&& (!parent || active(parent.record.state) && !this.closedRuns.has(parent.record.runId));
|
|
298
|
+
}
|
|
299
|
+
private queueAutoResume(run: Execution, error: ModelRequestError, attempt: number): void {
|
|
300
|
+
const { record, parent, config, type, model } = run;
|
|
301
|
+
const { maxRetries, baseDelayMs, maxAgentDelayMs } = error.retry;
|
|
302
|
+
const prompt = `The previous request failed with a network or upstream error: ${error.requestError}. Continue the same task from where you stopped. Do not repeat completed steps.`;
|
|
303
|
+
// The scope, model and task assignment were already admitted. Reusing them avoids I/O
|
|
304
|
+
// between the failed run settling and its replacement becoming the latest active run.
|
|
305
|
+
const next = this.createRun(record.id, { ...run.request, prompt }, parent, config,
|
|
306
|
+
{ ...run.options, onSpawned: undefined, onQueued: undefined }, type,
|
|
307
|
+
{ model, modelSource: record.modelSource, thinking: record.thinking, thinkingSource: record.thinkingSource }, record, run);
|
|
308
|
+
next.record.background = record.background; next.notifyResult = run.notifyResult;
|
|
309
|
+
next.foreground = run.foreground; next.pendingMessages = run.pendingMessages.splice(0);
|
|
310
|
+
next.autoResumes = attempt;
|
|
311
|
+
const retry: NonNullable<Execution['retry']> = { attempt, max: maxRetries };
|
|
312
|
+
const deadline = performance.now() + Math.min(baseDelayMs * 2 ** (attempt - 1), maxAgentDelayMs);
|
|
313
|
+
const arm = () => {
|
|
314
|
+
// Node clamps delays above 2^31-1 to 1ms; keep waiting toward the same deadline.
|
|
315
|
+
retry.timer = setTimeout(() => {
|
|
316
|
+
if (performance.now() < deadline) arm();
|
|
317
|
+
else { retry.timer = undefined; this.drain(); }
|
|
318
|
+
}, Math.min(2_147_483_647, Math.ceil(deadline - performance.now()))).unref();
|
|
319
|
+
};
|
|
320
|
+
next.retry = retry; arm();
|
|
321
|
+
run.replacement = next; run.consumed = true;
|
|
322
|
+
this.enqueue(next); this.bindAbort(next);
|
|
323
|
+
}
|
|
324
|
+
private async launch(run: Execution): Promise<void> {
|
|
325
|
+
let modelError: ModelRequestError | undefined;
|
|
326
|
+
try {
|
|
327
|
+
await this.execute(run);
|
|
328
|
+
if (run.record.state !== 'limited') run.record.state = run.controller.signal.aborted || run.terminated ? 'stopped' : 'completed';
|
|
329
|
+
} catch (error) {
|
|
330
|
+
run.record.error = error instanceof Error ? error.message : String(error);
|
|
331
|
+
if (run.record.state !== 'limited') run.record.state = run.controller.signal.aborted ? 'stopped' : 'failed';
|
|
332
|
+
if (error instanceof ModelRequestError && retryable(error)) modelError = error;
|
|
333
|
+
} finally {
|
|
334
|
+
// A settled direct parent cannot leave hidden nested sessions burning tokens.
|
|
335
|
+
this.closedRuns.add(run.record.runId);
|
|
336
|
+
try {
|
|
337
|
+
// A naturally completed child may still be finalizing its own descendants/session.
|
|
338
|
+
// Join that work without turning its completed result or leftover jobs into a stop.
|
|
339
|
+
const cleanup: Promise<unknown>[] = [...this.runs.values()].filter(child => child.record.parentRunId === run.record.runId && !child.settled)
|
|
340
|
+
.map(child => active(child.record.state) ? this.stop(child.record.id, child.record.runId) : child.done.promise);
|
|
341
|
+
if (run.controller.signal.aborted || run.terminated) cleanup.push(this.stopJobs([run.record.runId]));
|
|
342
|
+
// A failed child cleanup must not bypass other children or the parent's own jobs.
|
|
343
|
+
const outcomes = await Promise.allSettled(cleanup), failed = outcomes.find(outcome => outcome.status === 'rejected');
|
|
344
|
+
if (failed?.status === 'rejected') throw failed.reason;
|
|
345
|
+
} catch (error) {
|
|
346
|
+
modelError = undefined;
|
|
347
|
+
run.record.error = [run.record.error, `Execution cleanup failed: ${String(error)}`].filter(Boolean).join('; '); run.record.state = 'failed';
|
|
348
|
+
}
|
|
349
|
+
const attempt = (run.autoResumes ?? 0) + 1;
|
|
350
|
+
if (modelError && run.record.state === 'failed' && this.canAutoResume(run) && attempt > modelError.retry.maxRetries && run.autoResumes) {
|
|
351
|
+
run.record.error += ` · gave up after ${run.autoResumes} automatic resumes`;
|
|
352
|
+
}
|
|
353
|
+
run.record.endedAt = new Date().toISOString(); run.record.elapsedMs = Math.round(performance.now() - run.startedMonotonic!);
|
|
354
|
+
try { await closeAgent(run); }
|
|
355
|
+
catch (error) {
|
|
356
|
+
modelError = undefined;
|
|
357
|
+
run.record.error = [run.record.error, `Session finalization failed: ${String(error)}`].filter(Boolean).join('; '); run.record.state = 'failed';
|
|
358
|
+
}
|
|
359
|
+
if (run.chargedPool) this.counts[run.chargedPool]--;
|
|
360
|
+
run.settled = true; run.detachAbort?.();
|
|
361
|
+
// Publish the replacement before done/events/changed can wake the parent or wait.
|
|
362
|
+
if (modelError && run.record.state === 'failed' && attempt <= modelError.retry.maxRetries && this.canAutoResume(run)) {
|
|
363
|
+
this.queueAutoResume(run, modelError, attempt);
|
|
364
|
+
}
|
|
365
|
+
run.autoResumes = undefined;
|
|
366
|
+
run.startup?.resolve(run.record.error ?? 'Agent stopped before startup. Start it again if the task is still needed.');
|
|
367
|
+
run.done.resolve(this.view(run));
|
|
368
|
+
// Synchronous completion consumers must run before changed() schedules a parent wake.
|
|
369
|
+
if (!run.replacement) this.event(['failed', 'stopped', 'limited'].includes(run.record.state) ? 'failed' : 'completed', run);
|
|
370
|
+
this.changed(); this.drain();
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
async send(id: string, message: string, scope: ParentScope, config: SuiteConfig) {
|
|
374
|
+
const { record, run } = this.get(id);
|
|
375
|
+
if (run?.question && this.questionVisible(record, scope)) {
|
|
376
|
+
answerParent(run, message); run.autoResumes = undefined;
|
|
377
|
+
return { action: 'answered' as const, run };
|
|
378
|
+
}
|
|
379
|
+
if (!this.visible(record, scope)) throw new ToolError('NOT_OWNER', `${id} is not a direct child visible in this session. Send from its direct parent on the branch that started it.`, id);
|
|
380
|
+
if (run && !run.settled && !active(run.record.state)) throw new ToolError('NOT_RUNNING', `${id} is still finishing. Wait for it to finish before sending another message.`, id);
|
|
381
|
+
if (record.state === 'stopping') throw new ToolError('NOT_RUNNING', `${id} is stopping. Wait for agent_stop to finish before sending another message.`, id);
|
|
382
|
+
if (run && active(record.state)) {
|
|
383
|
+
run.autoResumes = undefined;
|
|
384
|
+
if (!run.session || !run.session.isStreaming) { run.pendingMessages.push(message); this.event('steered', run, { message }); return { action: 'queued' as const, run }; }
|
|
385
|
+
await run.session.steer(message); this.event('steered', run, { message }); return { action: 'steered' as const, run };
|
|
386
|
+
}
|
|
387
|
+
const next = await this.start({ prompt: message, background: record.background }, scope, config, record);
|
|
388
|
+
return { action: 'resumed' as const, run: next };
|
|
389
|
+
}
|
|
390
|
+
stop(id: string, runId?: string): Promise<StopOutcome> {
|
|
391
|
+
const { record, run } = this.get(id, runId);
|
|
392
|
+
const roots = this.records().filter(item => item.id === id && (!runId || item.runId === runId)).map(item => item.runId);
|
|
393
|
+
const stopKey = `${id}:${[...roots].sort().join(',')}`;
|
|
394
|
+
const existing = this.stops.get(stopKey);
|
|
395
|
+
if (existing) return existing;
|
|
396
|
+
for (const root of roots) this.closedRuns.add(root);
|
|
397
|
+
const targets = [...this.runs.values()].filter(item => roots.includes(item.record.runId) || item.record.ancestors.some(ancestor => roots.includes(ancestor)));
|
|
398
|
+
let requested = false;
|
|
399
|
+
// Abort handlers and change subscribers can stop synchronously. Publish their shared
|
|
400
|
+
// operation before invoking them; cleanup starts once all targets have transitioned.
|
|
401
|
+
const operation = Promise.resolve().then(async () => {
|
|
402
|
+
// Job cleanup can fail independently of model abort. Still join every child before
|
|
403
|
+
// reporting that failure, so callers cannot publish a settled parent prematurely.
|
|
404
|
+
const [jobsResult] = await Promise.allSettled([this.stopJobs(roots), Promise.all(targets.map(target => target.done.promise))]);
|
|
405
|
+
if (jobsResult.status === 'rejected') throw jobsResult.reason;
|
|
406
|
+
const jobs = jobsResult.value;
|
|
407
|
+
const affected = [...targets.map(target => ({ id: target.record.id, state: target.record.state })), ...jobs];
|
|
408
|
+
this.drain();
|
|
409
|
+
return { requested: requested || jobs.length > 0, state: this.get(id, record.runId).record.state,
|
|
410
|
+
cleanup: jobs.some(job => job.cleanup === 'unconfirmed' || job.cleanup === 'pending') ? 'unconfirmed' : 'confirmed', affected };
|
|
411
|
+
}).finally(() => this.stops.delete(stopKey));
|
|
412
|
+
this.stops.set(stopKey, operation);
|
|
413
|
+
const cancelled: {target: Execution; queued: boolean}[] = [];
|
|
414
|
+
for (const target of targets) if (active(target.record.state)) {
|
|
415
|
+
requested = true; this.closedRuns.add(target.record.runId);
|
|
416
|
+
const queued = target.record.state === 'queued';
|
|
417
|
+
cancelled.push({target, queued});
|
|
418
|
+
target.autoResumes = undefined;
|
|
419
|
+
if (queued) {
|
|
420
|
+
clearTimeout(target.retry?.timer); target.retry = undefined;
|
|
421
|
+
this.queue = this.queue.filter(item => item !== target);
|
|
422
|
+
target.record.state = 'stopped'; target.record.endedAt = new Date().toISOString(); target.record.elapsedMs = 0;
|
|
423
|
+
target.settled = true; target.detachAbort?.(); target.done.resolve(this.view(target));
|
|
424
|
+
} else target.record.state = 'stopping';
|
|
425
|
+
}
|
|
426
|
+
// Parent abort callbacks can drain the queue: close every target before invoking any.
|
|
427
|
+
for (const {target, queued} of cancelled) {
|
|
428
|
+
target.controller.abort(); if (queued) this.event('failed', target);
|
|
429
|
+
}
|
|
430
|
+
this.changed();
|
|
431
|
+
return operation;
|
|
432
|
+
}
|
|
433
|
+
async shutdown(): Promise<void> {
|
|
434
|
+
this.closing = true;
|
|
435
|
+
clearInterval(this.cleanupTimer); this.cleanupTimer = undefined;
|
|
436
|
+
await Promise.all([...new Set(this.records().filter(record => active(record.state)).map(record => record.id))].map(id => this.stop(id)));
|
|
437
|
+
}
|
|
438
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// Conversation cloning adapted from @tintinweb/pi-subagents 0.23.0 src/mention-clone.ts
|
|
2
|
+
// (MIT). Only the registered start tool runs, attributed to the real parent context.
|
|
3
|
+
import { createAgentSession, DefaultResourceLoader, getAgentDir, SessionManager, SettingsManager,
|
|
4
|
+
type ExtensionContext, type ExtensionToolContext, type ToolDefinition } from '@earendil-works/pi-coding-agent';
|
|
5
|
+
import { Type } from 'typebox';
|
|
6
|
+
import { agentMentionReminder } from './grammar.ts';
|
|
7
|
+
import { parentModelRuntime } from '../models.ts';
|
|
8
|
+
import type { registerAgentTools } from '../tools.ts';
|
|
9
|
+
|
|
10
|
+
export async function runMentionClone(ctx: ExtensionContext, type: string, message: string, agentTool: ReturnType<typeof registerAgentTools>,
|
|
11
|
+
signal: AbortSignal): Promise<void> {
|
|
12
|
+
// Capture the selected branch/prompt before any asynchronous setup; /tree and /new
|
|
13
|
+
// can change the parent's read-only session manager while the copy is being built.
|
|
14
|
+
const modelRuntime = parentModelRuntime(ctx);
|
|
15
|
+
const entries = ctx.sessionManager.getBranch(), systemPrompt = ctx.getSystemPrompt(), model = ctx.model, thinkingLevel = ctx.thinkingLevel;
|
|
16
|
+
const settingsManager = SettingsManager.create(ctx.cwd, getAgentDir(), { projectTrusted: ctx.isProjectTrusted() });
|
|
17
|
+
const cloneSchema = Type.Object({ prompt: Type.String({ minLength: 1 }) }, { additionalProperties: false });
|
|
18
|
+
let attempted = false, spawned = false;
|
|
19
|
+
let launchError: unknown;
|
|
20
|
+
const cloneTool: ToolDefinition<typeof cloneSchema> = { ...agentTool,
|
|
21
|
+
description: 'Start the requested agent once. Put the task and relevant context in prompt.',
|
|
22
|
+
parameters: cloneSchema,
|
|
23
|
+
execute: async (_id, params, toolSignal, update) => {
|
|
24
|
+
signal.throwIfAborted();
|
|
25
|
+
if (attempted) throw new Error('Start already attempted. Do not call agent_start again.');
|
|
26
|
+
attempted = true;
|
|
27
|
+
try {
|
|
28
|
+
const result = await agentTool.execute(undefined as never, { prompt: params.prompt, type, background: true },
|
|
29
|
+
toolSignal, update, ctx as ExtensionToolContext);
|
|
30
|
+
spawned = true;
|
|
31
|
+
return result;
|
|
32
|
+
} catch (error) { launchError = error; throw error; }
|
|
33
|
+
},
|
|
34
|
+
};
|
|
35
|
+
const loader = new DefaultResourceLoader({ cwd: ctx.cwd, agentDir: getAgentDir(), settingsManager,
|
|
36
|
+
noExtensions: true, noSkills: true, noPromptTemplates: true, noThemes: true, noContextFiles: true,
|
|
37
|
+
systemPromptOverride: () => systemPrompt, appendSystemPromptOverride: () => [],
|
|
38
|
+
});
|
|
39
|
+
await loader.reload(); signal.throwIfAborted();
|
|
40
|
+
const { session } = await createAgentSession({ cwd: ctx.cwd, agentDir: getAgentDir(), settingsManager,
|
|
41
|
+
sessionManager: SessionManager.inMemory(ctx.cwd, undefined, entries), resourceLoader: loader,
|
|
42
|
+
modelRuntime, model, thinkingLevel, tools: [cloneTool.name], customTools: [cloneTool] });
|
|
43
|
+
const abort = () => { void session.abort(); };
|
|
44
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
45
|
+
try {
|
|
46
|
+
signal.throwIfAborted();
|
|
47
|
+
await session.prompt(`${message}\n\n${agentMentionReminder(type)}`, { source: 'extension' });
|
|
48
|
+
signal.throwIfAborted();
|
|
49
|
+
if (!spawned) throw launchError ?? new Error('No agent started. Resend the @mention to retry.');
|
|
50
|
+
} finally { signal.removeEventListener('abort', abort); session.dispose(); }
|
|
51
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// Imported from @tintinweb/pi-subagents 0.23.0 src/mention.ts (MIT).
|
|
2
|
+
// Suggestions also accept CJK sentence-ending punctuation as a token boundary.
|
|
3
|
+
export const MENTION_TRIGGER = /(^|[\s。、?!])@([\w-]*)$/;
|
|
4
|
+
|
|
5
|
+
/** Send grammar: leading `@handle`, then a non-empty message. */
|
|
6
|
+
const MENTION_SEND = /^@([\w-]+)\s+([\s\S]+)$/;
|
|
7
|
+
|
|
8
|
+
// Cap the base to keep long type names and aliases from wrapping the suggestion popup.
|
|
9
|
+
const MAX_HANDLE_LENGTH = 64;
|
|
10
|
+
|
|
11
|
+
// `@main` routes to the main conversation.
|
|
12
|
+
const RESERVED_HANDLES: ReadonlySet<string> = new Set(["main"]);
|
|
13
|
+
|
|
14
|
+
/** Whether `@handle` names the main conversation rather than any subagent. */
|
|
15
|
+
export function isReservedHandle(handle: string): boolean {
|
|
16
|
+
return RESERVED_HANDLES.has(handle.toLowerCase());
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Slug of an agent type or name, restricted to the `[\w-]` the grammar allows. */
|
|
20
|
+
export function handleBase(type: string): string {
|
|
21
|
+
const slug = type.toLowerCase()
|
|
22
|
+
.replace(/[^a-z0-9_-]+/g, "-")
|
|
23
|
+
.replace(/^-+|-+$/g, "")
|
|
24
|
+
.slice(0, MAX_HANDLE_LENGTH)
|
|
25
|
+
// The slice can land mid-run and leave the trailing hyphen back.
|
|
26
|
+
.replace(/-+$/, "");
|
|
27
|
+
return slug || "agent";
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* `base`, else `base-2`, `base-3`, … — the first form that is neither `taken`
|
|
32
|
+
* nor reserved. Callers pass one shared `taken` set covering type-derived
|
|
33
|
+
* handles and model-supplied aliases alike, so the two can never collide.
|
|
34
|
+
*/
|
|
35
|
+
export function assignHandle(base: string, taken: ReadonlySet<string>): string {
|
|
36
|
+
let candidate = base;
|
|
37
|
+
let n = 1;
|
|
38
|
+
while (taken.has(candidate) || RESERVED_HANDLES.has(candidate)) {
|
|
39
|
+
n++;
|
|
40
|
+
candidate = `${base}-${n}`;
|
|
41
|
+
}
|
|
42
|
+
return candidate;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// An exact match for `agent-foo` takes precedence over the shorthand for `foo`.
|
|
46
|
+
export function stripAgentPrefix(handle: string): string | undefined {
|
|
47
|
+
const rest = /^agent-(.+)$/i.exec(handle)?.[1];
|
|
48
|
+
return rest || undefined;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Split `@handle message` into its parts, or null when the text isn't a send —
|
|
53
|
+
* a bare handle, a leading file path, or a mention that isn't at the start.
|
|
54
|
+
*/
|
|
55
|
+
export function parseMention(text: string): { handle: string; message: string } | null {
|
|
56
|
+
const match = MENTION_SEND.exec(text);
|
|
57
|
+
if (!match) return null;
|
|
58
|
+
const message = match[2].trim();
|
|
59
|
+
return message ? { handle: match[1], message } : null;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function agentMentionReminder(type: string): string {
|
|
63
|
+
return `<system-reminder>\nCall agent_start once for "${type}". Put the user's task and relevant context in prompt.\n</system-reminder>`;
|
|
64
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
// Input dispatch adapted from @tintinweb/pi-subagents 0.23.0 src/index.ts (MIT).
|
|
2
|
+
import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
|
|
3
|
+
import type { SessionBinding } from '../../runtime/binding.ts';
|
|
4
|
+
import type { SuiteConfig } from '../../runtime/config.ts';
|
|
5
|
+
import type { AgentsModule } from '../index.ts';
|
|
6
|
+
import { agentTypes } from '../catalog.ts';
|
|
7
|
+
import { isReservedHandle, parseMention, stripAgentPrefix } from './grammar.ts';
|
|
8
|
+
import { createMentionProvider, mentionRoster, resolveMentionTarget } from './provider.ts';
|
|
9
|
+
import { runMentionClone } from './clone.ts';
|
|
10
|
+
import type { registerAgentTools } from '../tools.ts';
|
|
11
|
+
import type { AgentType } from '../types.ts';
|
|
12
|
+
|
|
13
|
+
export function registerAgentMentions(pi: ExtensionAPI, agents: AgentsModule, binding: SessionBinding,
|
|
14
|
+
config: () => SuiteConfig, startTool: ReturnType<typeof registerAgentTools>, catalog?: (ctx: Parameters<AgentsModule['scope']>[0], fresh?: boolean) => AgentType[]) {
|
|
15
|
+
const clones = new Set<AbortController>();
|
|
16
|
+
let providerRegistered = false, types: AgentType[] = [];
|
|
17
|
+
const enabled = () => config().agents.mentions;
|
|
18
|
+
const loadTypes = (ctx: Parameters<AgentsModule['scope']>[0], fresh = false) => {
|
|
19
|
+
const settings = config();
|
|
20
|
+
types = catalog ? catalog(ctx, fresh) : agentTypes(ctx.cwd, undefined, { trusted: ctx.isProjectTrusted(), packageGate: settings.agents.packageAgents, typeSettings: settings.agents.types });
|
|
21
|
+
};
|
|
22
|
+
const roster = () => {
|
|
23
|
+
const current = binding.current;
|
|
24
|
+
return current ? mentionRoster(agents.manager, agents.scope(current.ctx), types) : [];
|
|
25
|
+
};
|
|
26
|
+
const cancel = () => { for (const controller of clones) controller.abort(); clones.clear(); };
|
|
27
|
+
pi.on('session_before_switch', cancel);
|
|
28
|
+
pi.on('session_shutdown', cancel);
|
|
29
|
+
const bind = (ctx: Parameters<AgentsModule['scope']>[0]) => {
|
|
30
|
+
cancel();
|
|
31
|
+
if (ctx.mode !== 'tui' || !enabled()) { types = []; return; }
|
|
32
|
+
// A session switch retains the host's provider stack; reload replaces the activation.
|
|
33
|
+
// Discover types at bind/dispatch, rather than reading every markdown/package per key.
|
|
34
|
+
loadTypes(ctx);
|
|
35
|
+
if (providerRegistered) return;
|
|
36
|
+
providerRegistered = true;
|
|
37
|
+
ctx.ui.addAutocompleteProvider(current => createMentionProvider(current, roster, enabled, error => {
|
|
38
|
+
binding.current?.ctx.ui.notify(`Completion failed: ${String(error)}`, 'error');
|
|
39
|
+
console.error('[pi-suite] autocomplete provider failed', error);
|
|
40
|
+
}));
|
|
41
|
+
};
|
|
42
|
+
pi.on('input', async (event, ctx) => {
|
|
43
|
+
// Print/RPC callers need a normal response; consuming their input would produce silence.
|
|
44
|
+
// Attachments remain on the parent's request because agent_send accepts text only.
|
|
45
|
+
if (!enabled() || event.source !== 'interactive' || ctx.mode !== 'tui') return { action: 'continue' };
|
|
46
|
+
const mention = parseMention(event.text);
|
|
47
|
+
if (!mention) return { action: 'continue' };
|
|
48
|
+
if (isReservedHandle(mention.handle)) return { action: 'transform', text: mention.message, images: event.images };
|
|
49
|
+
if (event.images?.length) return { action: 'continue' };
|
|
50
|
+
loadTypes(ctx, true);
|
|
51
|
+
const targets = roster(), alias = stripAgentPrefix(mention.handle);
|
|
52
|
+
const target = resolveMentionTarget(targets, mention.handle) ?? (alias ? resolveMentionTarget(targets, alias) : undefined);
|
|
53
|
+
if (!target) return { action: 'continue' };
|
|
54
|
+
if (target.kind === 'record') {
|
|
55
|
+
try {
|
|
56
|
+
const result = await agents.admitSend(target.record.id).send(target.record.id, mention.message, agents.scope(ctx), config());
|
|
57
|
+
// Mentions have no foreground tool result. Answers to a resumed foreground type
|
|
58
|
+
// or an already-consumed active run must use the ordinary completion notification.
|
|
59
|
+
result.run.notifyResult = true; result.run.consumed = false; agents.manager.changed();
|
|
60
|
+
ctx.ui.notify(`${result.action}: @${target.handle}`, 'info');
|
|
61
|
+
} catch (error) { ctx.ui.notify(`Could not send to @${target.handle}: ${String(error)}`, 'error'); }
|
|
62
|
+
return { action: 'handled' };
|
|
63
|
+
}
|
|
64
|
+
try { agents.admit(); }
|
|
65
|
+
catch (error) { ctx.ui.notify(String(error), 'error'); return { action: 'handled' }; }
|
|
66
|
+
const current = binding.current!, controller = new AbortController();
|
|
67
|
+
clones.add(controller); ctx.ui.notify(`Preparing @${target.handle}…`, 'info');
|
|
68
|
+
// Return control to the editor while the off-screen model writes the task. Cancellation
|
|
69
|
+
// is owned by this activation and fences /new, /tree and reload before any later spawn.
|
|
70
|
+
void runMentionClone(ctx, target.type, mention.message, startTool, controller.signal)
|
|
71
|
+
.catch(error => { if (binding.isCurrent(current) && !controller.signal.aborted) ctx.ui.notify(`Could not start @${target.handle}: ${String(error)}`, 'error'); })
|
|
72
|
+
.finally(() => { clones.delete(controller); });
|
|
73
|
+
return { action: 'handled' };
|
|
74
|
+
});
|
|
75
|
+
return { bind, refreshTypes() { if (binding.current && enabled()) loadTypes(binding.current.ctx, true); } };
|
|
76
|
+
}
|