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,93 @@
|
|
|
1
|
+
// Imported/adapted from @tintinweb/pi-subagents 0.23.0 src/workflow/entry.ts (MIT).
|
|
2
|
+
/**
|
|
3
|
+
* Parent history records ownership and lifecycle independently of tool calls.
|
|
4
|
+
* Plain JSON snapshots survive reload; AbortController and Worker controls stay
|
|
5
|
+
* with the process owner. Child references point to shared SDK sessions.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import type { WorkflowMeta } from "./meta.ts";
|
|
9
|
+
import type { WorkflowEntry, WorkflowRunStatus } from "./progress/index.ts";
|
|
10
|
+
import { createWorkflowTask, type WorkflowTask } from "./task.ts";
|
|
11
|
+
import { updateWorkflowProgressBatch } from './task.ts';
|
|
12
|
+
import type { SessionEntry } from '@earendil-works/pi-coding-agent';
|
|
13
|
+
import { ToolError } from '../../runtime/errors.ts';
|
|
14
|
+
import type { AgentRecord } from '../types.ts';
|
|
15
|
+
import { decodeAgentRecord } from '../records.ts';
|
|
16
|
+
|
|
17
|
+
export type WorkflowOwner = {ownerSessionId: string; anchorEntryId: string | null; cwd: string;
|
|
18
|
+
recordPath: string; resultPath: string; notified: boolean; children: AgentRecord[]};
|
|
19
|
+
export type OwnedWorkflowTask = WorkflowTask & WorkflowOwner;
|
|
20
|
+
|
|
21
|
+
/** Structural parent entry, also rendered through the native history registry. */
|
|
22
|
+
export const WORKFLOW_ENTRY_TYPE = "pi-suite:workflow-record";
|
|
23
|
+
|
|
24
|
+
/** The persisted snapshot of a run's lifecycle. */
|
|
25
|
+
export interface WorkflowEntryData extends WorkflowOwner {
|
|
26
|
+
version: 1;
|
|
27
|
+
id: string;
|
|
28
|
+
name: string;
|
|
29
|
+
status: WorkflowRunStatus;
|
|
30
|
+
startTime: number;
|
|
31
|
+
endTime?: number;
|
|
32
|
+
progress: WorkflowEntry[];
|
|
33
|
+
agentCount: number;
|
|
34
|
+
totalTokens: number;
|
|
35
|
+
meta?: WorkflowMeta;
|
|
36
|
+
scriptPath?: string;
|
|
37
|
+
journalPath?: string;
|
|
38
|
+
args?: unknown;
|
|
39
|
+
value?: unknown;
|
|
40
|
+
error?: string;
|
|
41
|
+
totalToolCalls: number;
|
|
42
|
+
totalPausedMs: number;
|
|
43
|
+
resumedFrom?: string;
|
|
44
|
+
replayedCount: number;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Snapshot a task for {@link WORKFLOW_ENTRY_TYPE}. */
|
|
48
|
+
export function workflowEntryData(task: OwnedWorkflowTask): WorkflowEntryData {
|
|
49
|
+
return {
|
|
50
|
+
version: 1, id: task.id, ownerSessionId: task.ownerSessionId, anchorEntryId: task.anchorEntryId,
|
|
51
|
+
cwd: task.cwd, recordPath: task.recordPath, resultPath: task.resultPath, notified: task.notified,
|
|
52
|
+
children: task.children,
|
|
53
|
+
name: task.workflowName ?? task.id,
|
|
54
|
+
status: task.status,
|
|
55
|
+
startTime: task.startTime,
|
|
56
|
+
endTime: task.endTime,
|
|
57
|
+
// The live task keeps appending progress after a tool result or entry is captured.
|
|
58
|
+
progress: task.workflowProgress.slice(),
|
|
59
|
+
agentCount: task.agentCount,
|
|
60
|
+
totalTokens: task.totalTokens,
|
|
61
|
+
scriptPath: task.scriptPath, journalPath: task.journalPath, args: task.args, value: task.value, error: task.error,
|
|
62
|
+
totalToolCalls: task.totalToolCalls, totalPausedMs: task.totalPausedMs, resumedFrom: task.resumedFrom, replayedCount: task.replayedCount,
|
|
63
|
+
...(task.meta !== undefined ? { meta: task.meta } : {}),
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Session/file boundary: records of a different shape cannot become runtime handles. */
|
|
68
|
+
export function decodeWorkflowEntry(value: unknown): WorkflowEntryData {
|
|
69
|
+
const data = value as WorkflowEntryData | undefined;
|
|
70
|
+
if (!data || data.version !== 1 || !/^wf_[a-f0-9]{12}$/.test(data.id) || typeof data.cwd !== 'string'
|
|
71
|
+
|| typeof data.ownerSessionId !== 'string' || !(data.anchorEntryId === null || typeof data.anchorEntryId === 'string')
|
|
72
|
+
|| typeof data.recordPath !== 'string' || typeof data.resultPath !== 'string' || typeof data.notified !== 'boolean'
|
|
73
|
+
|| !Array.isArray(data.children)
|
|
74
|
+
|| !['running', 'paused', 'completed', 'failed', 'killed'].includes(data.status) || !Array.isArray(data.progress)
|
|
75
|
+
|| typeof data.name !== 'string' || !Number.isFinite(data.startTime) || !Number.isInteger(data.agentCount)) {
|
|
76
|
+
throw new ToolError('WORKFLOW_HISTORY', 'Unsupported workflow record version or invalid data. Use a session with a valid workflow record.');
|
|
77
|
+
}
|
|
78
|
+
return { ...data, children: data.children.map(child => decodeAgentRecord(child, data.recordPath)) };
|
|
79
|
+
}
|
|
80
|
+
export function workflowEntries(entries: readonly SessionEntry[]): WorkflowEntryData[] {
|
|
81
|
+
const records = new Map<string, WorkflowEntryData>();
|
|
82
|
+
for (const entry of entries) if (entry.type === 'custom' && entry.customType === WORKFLOW_ENTRY_TYPE) {
|
|
83
|
+
const data = decodeWorkflowEntry(entry.data); records.set(data.id, data);
|
|
84
|
+
}
|
|
85
|
+
return [...records.values()];
|
|
86
|
+
}
|
|
87
|
+
export function taskFromEntry(data: WorkflowEntryData): OwnedWorkflowTask {
|
|
88
|
+
const task = Object.assign(createWorkflowTask({id: data.id, script: '', scriptPath: data.scriptPath,
|
|
89
|
+
args: data.args, meta: data.meta, startTime: data.startTime, journalPath: data.journalPath, resumedFrom: data.resumedFrom}),
|
|
90
|
+
{...data, workflowName: data.name});
|
|
91
|
+
updateWorkflowProgressBatch(task, data.progress);
|
|
92
|
+
return task;
|
|
93
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// Adapted from @tintinweb/pi-subagents 0.23.0 src/workflow/host.ts (MIT).
|
|
2
|
+
// Manager records are authoritative; gates share the public JobManager lifecycle.
|
|
3
|
+
import type { SuiteConfig } from '../../runtime/config.ts';
|
|
4
|
+
import { ToolError } from '../../runtime/errors.ts';
|
|
5
|
+
import type { JobManager } from '../../jobs/manager.ts';
|
|
6
|
+
import { readJobLog } from '../../jobs/query.ts';
|
|
7
|
+
import { resolvePiShell } from '../../jobs/terminal/shell.ts';
|
|
8
|
+
import type { AgentManager } from '../manager.ts';
|
|
9
|
+
import { captureParent } from '../parent.ts';
|
|
10
|
+
import type { AgentRecord, Execution, ParentScope, Thinking } from '../types.ts';
|
|
11
|
+
import { resolveWorkflowSource } from './saved.ts';
|
|
12
|
+
import type { WorkflowHost, WorkflowSpawnRequest, WorkflowSpawnResult } from './runtime/index.ts';
|
|
13
|
+
|
|
14
|
+
export const DEFAULT_GATE_TIMEOUT_MS = 10 * 60_000;
|
|
15
|
+
function toSpawnResult(record: AgentRecord): WorkflowSpawnResult {
|
|
16
|
+
const common = {tokens: record.usage?.tokens.total ?? 0, outputTokens: record.usage?.tokens.output ?? 0,
|
|
17
|
+
toolCalls: record.toolUses ?? 0, structuredRetried: record.structuredRetried};
|
|
18
|
+
if (record.state === 'completed') return {...common, ok: true, text: record.structuredJson ?? record.result ?? ''};
|
|
19
|
+
return {...common, ok: false, skipped: record.state === 'stopped', error: record.error ?? `Agent ${record.state}.`};
|
|
20
|
+
}
|
|
21
|
+
export function createWorkflowHost(deps: {
|
|
22
|
+
scope: ParentScope; manager: AgentManager; jobs: () => JobManager; config: () => SuiteConfig;
|
|
23
|
+
workflowId: string; signal: AbortSignal; gateTimeoutMs?: number;
|
|
24
|
+
}): WorkflowHost & {close(): Promise<void>} {
|
|
25
|
+
const scope = captureParent(deps.scope), manager = deps.manager;
|
|
26
|
+
const records = new Map<string, Execution>(), controllers = new Map<string, AbortController>();
|
|
27
|
+
const executions = new Set<AgentRecord>(), pending = new Set<Promise<WorkflowSpawnResult>>();
|
|
28
|
+
const retained = new Set<() => void>();
|
|
29
|
+
const signalFor = (id: string) => {
|
|
30
|
+
const controller = new AbortController(); controllers.set(id, controller);
|
|
31
|
+
return AbortSignal.any([controller.signal, deps.signal]);
|
|
32
|
+
};
|
|
33
|
+
function report(run: Execution, callback: WorkflowSpawnRequest['onResolved']): void {
|
|
34
|
+
const record = run.record;
|
|
35
|
+
callback?.({recordId: record.id, modelName: run.session?.model?.name ?? run.model.name,
|
|
36
|
+
modelId: record.model, thinking: record.thinking,
|
|
37
|
+
requestedThinking: run.request.thinking !== undefined && run.request.thinking !== record.thinking ? run.request.thinking : undefined});
|
|
38
|
+
}
|
|
39
|
+
function track(work: () => Promise<WorkflowSpawnResult>): Promise<WorkflowSpawnResult> {
|
|
40
|
+
// Startup rejection is this agent's business failure; the script receives null and the error goes to progress.
|
|
41
|
+
// This way callers that made early errors see them rolled up into the workflow result.
|
|
42
|
+
const operation = work().catch(error => ({ok: false, error: error instanceof Error ? error.message : String(error)}));
|
|
43
|
+
pending.add(operation); void operation.then(() => pending.delete(operation)); return operation;
|
|
44
|
+
}
|
|
45
|
+
async function waitForRun(run: Execution, callback: WorkflowSpawnRequest['onResolved']): Promise<WorkflowSpawnResult> {
|
|
46
|
+
executions.add(run.record);
|
|
47
|
+
retained.add(manager.retain(run.record.runId));
|
|
48
|
+
const off = manager.subscribeEvents((kind, current) => { if (kind === 'started' && current === run) report(run, callback); });
|
|
49
|
+
try {
|
|
50
|
+
if (run.session) report(run, callback);
|
|
51
|
+
return toSpawnResult(await run.done.promise);
|
|
52
|
+
} finally { off(); }
|
|
53
|
+
}
|
|
54
|
+
return {
|
|
55
|
+
spawnAgent(request) {
|
|
56
|
+
return track(async () => {
|
|
57
|
+
const signal = signalFor(request.agentId);
|
|
58
|
+
const run = await manager.start({prompt: request.prompt, type: request.agentType, name: request.label, background: true,
|
|
59
|
+
model: request.model, thinking: request.effort as Thinking | undefined}, scope, deps.config(), undefined,
|
|
60
|
+
{workflowId: deps.workflowId, signal, structuredOutput: request.schema,
|
|
61
|
+
onSpawned: id => request.onResolved?.({recordId: id})});
|
|
62
|
+
records.set(request.agentId, run);
|
|
63
|
+
return waitForRun(run, request.onResolved);
|
|
64
|
+
});
|
|
65
|
+
},
|
|
66
|
+
abortAgent(id) { controllers.get(id)?.abort(); },
|
|
67
|
+
resumeAgent(id, prompt, onResolved) {
|
|
68
|
+
return track(async () => {
|
|
69
|
+
const prior = records.get(id);
|
|
70
|
+
if (!prior) throw new ToolError('NOT_FOUND', `Cannot resume ${id}: it did not start. Pass the label of a completed child from this run.`);
|
|
71
|
+
const run = await manager.resume(prior, prompt, signalFor(id), recordId => onResolved?.({recordId}));
|
|
72
|
+
records.set(id, run); return waitForRun(run, onResolved);
|
|
73
|
+
});
|
|
74
|
+
},
|
|
75
|
+
loadWorkflow(ref) {
|
|
76
|
+
return resolveWorkflowSource(ref, scope.ctx.cwd, {trusted: scope.ctx.isProjectTrusted(), packageGate: deps.config().agents.packageWorkflows});
|
|
77
|
+
},
|
|
78
|
+
async runGate(command, options) {
|
|
79
|
+
const jobs = deps.jobs(), signal = AbortSignal.any([deps.signal, controllers.get(options.agentId)!.signal]);
|
|
80
|
+
const job = await jobs.start({command, name: `gate ${deps.workflowId}`, cwd: scope.ctx.cwd, mode: 'pipe', closeInput: true,
|
|
81
|
+
timeoutMs: deps.gateTimeoutMs ?? DEFAULT_GATE_TIMEOUT_MS, ...scope.owner!,
|
|
82
|
+
creator: {workflowId: deps.workflowId, runId: deps.workflowId, ancestors: []}},
|
|
83
|
+
resolvePiShell(scope.ctx.cwd, scope.ctx.isProjectTrusted()), signal);
|
|
84
|
+
options.onStarted?.(job.id);
|
|
85
|
+
// start's abort hook covers launch only. Keep the workflow signal attached through exit.
|
|
86
|
+
const abort = () => { void jobs.stop(job.id, 'agent').catch(error => process.emitWarning(`Workflow gate stop failed: ${String(error)}`)); };
|
|
87
|
+
signal.addEventListener('abort', abort, {once: true});
|
|
88
|
+
try {
|
|
89
|
+
if (signal.aborted) abort();
|
|
90
|
+
const result = await jobs.wait(job.id);
|
|
91
|
+
const [stdout, stderr] = await Promise.all(['stdout', 'stderr'].map(stream => readJobLog(jobs, result, stream as 'stdout' | 'stderr', {})));
|
|
92
|
+
const output = [stdout.text.trim(), stderr.text.trim(), result.error].filter(Boolean).join('\n');
|
|
93
|
+
jobs.markNotified(job.id);
|
|
94
|
+
return {ok: result.state === 'completed' && result.exitCode === 0 && !signal.aborted,
|
|
95
|
+
output: output || (result.state === 'completed' ? '' : `Gate ${result.state}: ${command}`)};
|
|
96
|
+
} finally { signal.removeEventListener('abort', abort); }
|
|
97
|
+
},
|
|
98
|
+
async close() {
|
|
99
|
+
for (const controller of controllers.values()) controller.abort();
|
|
100
|
+
try {
|
|
101
|
+
await Promise.all([...pending]);
|
|
102
|
+
// Each stop joins its child even if job cleanup fails. Join every request before
|
|
103
|
+
// publishing failure, and keep record identities for the owner's cleanup retry.
|
|
104
|
+
const results = await Promise.allSettled([...executions].map(record => manager.stop(record.id, record.runId)));
|
|
105
|
+
const gateJobs = await deps.jobs().stopCreatedBy([deps.workflowId]);
|
|
106
|
+
const failures = results.filter(result => result.status === 'rejected').map(result => result.reason);
|
|
107
|
+
if (failures.length) throw new AggregateError(failures, `Workflow child cleanup failed: ${failures.map(String).join('; ')}`);
|
|
108
|
+
const outcomes = results.filter(result => result.status === 'fulfilled').map(result => result.value);
|
|
109
|
+
if (outcomes.some(outcome => outcome.cleanup !== 'confirmed') || gateJobs.some(({job}) => ['pending', 'unconfirmed'].includes(job.cleanup.state))) {
|
|
110
|
+
throw new Error('Workflow execution cleanup remains unconfirmed');
|
|
111
|
+
}
|
|
112
|
+
executions.clear();
|
|
113
|
+
} finally {
|
|
114
|
+
for (const release of retained) release();
|
|
115
|
+
retained.clear(); records.clear(); controllers.clear();
|
|
116
|
+
}
|
|
117
|
+
},
|
|
118
|
+
};
|
|
119
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
|
|
2
|
+
import type { SessionBinding } from '../../runtime/binding.ts';
|
|
3
|
+
import type { Notifications, NotificationView } from '../../runtime/notifications.ts';
|
|
4
|
+
import type { Settlement, Waitable } from '../../runtime/wait.ts';
|
|
5
|
+
import type { Dock } from '../../ui/dock.ts';
|
|
6
|
+
import { sanitizeText } from '../../runtime/text.ts';
|
|
7
|
+
import { ToolError } from '../../runtime/errors.ts';
|
|
8
|
+
import type { AgentsModule } from '../index.ts';
|
|
9
|
+
import { WORKFLOW_ENTRY_TYPE, workflowEntries, type OwnedWorkflowTask } from './entry.ts';
|
|
10
|
+
import { WorkflowManager, workflowRuntime, workflowActive } from './manager.ts';
|
|
11
|
+
import { workflowResultText } from './task.ts';
|
|
12
|
+
import { formatDuration, elapsedMs } from './progress/index.ts';
|
|
13
|
+
|
|
14
|
+
export function workflowSummary(task: OwnedWorkflowTask, modelFacing = false): string {
|
|
15
|
+
const elapsed = elapsedMs(task, Date.now());
|
|
16
|
+
return `${task.id} ${task.status} · ${sanitizeText(task.workflowName ?? task.id).replace(/[\r\n\t]/g, ' ')} · ${task.doneCount}/${task.agentCount} agents · ${modelFacing ? `${(elapsed / 1000).toFixed(1)}s` : formatDuration(elapsed)}`;
|
|
17
|
+
}
|
|
18
|
+
function resultBody(task: OwnedWorkflowTask): string {
|
|
19
|
+
return `${workflowResultText(task).slice(0, 1000)}\nread: read({"path":${JSON.stringify(task.resultPath)}})`;
|
|
20
|
+
}
|
|
21
|
+
function resultView(task: OwnedWorkflowTask): NotificationView {
|
|
22
|
+
return { title: 'Workflow result', state: task.status, meta: [task.id, task.workflowName ?? task.id,
|
|
23
|
+
`${task.doneCount}/${task.agentCount} agents`, formatDuration(elapsedMs(task, Date.now()))], body: resultBody(task) };
|
|
24
|
+
}
|
|
25
|
+
/** Per-binding workflow view; the process-wide owner survives reload and session switches. */
|
|
26
|
+
export class WorkflowsModule implements Waitable {
|
|
27
|
+
readonly prefix = 'wf_';
|
|
28
|
+
readonly manager: WorkflowManager;
|
|
29
|
+
readonly stale?: string;
|
|
30
|
+
private warned = false;
|
|
31
|
+
private unsubscribe?: () => void;
|
|
32
|
+
private queued = new Set<string>();
|
|
33
|
+
private saved = new Map<string, string>();
|
|
34
|
+
constructor(private pi: ExtensionAPI, private binding: SessionBinding, private notices: Notifications,
|
|
35
|
+
private dock: Dock, private agents: AgentsModule, manager?: WorkflowManager) {
|
|
36
|
+
if (manager) { this.manager = manager; this.stale = agents.stale; }
|
|
37
|
+
else ({ owner: this.manager, stale: this.stale } = workflowRuntime({ owner: agents.manager, stale: agents.stale }));
|
|
38
|
+
dock.register('workflows', { title: 'Workflows', rows: () => this.list().filter(task => !this.manager.settled(task.id)).map(task => ({
|
|
39
|
+
id: task.id, text: `${task.id} ${task.workflowName ?? 'workflow'}`, priority: 60,
|
|
40
|
+
suffix: `${task.status} · ${task.doneCount}/${task.agentCount}`,
|
|
41
|
+
})) });
|
|
42
|
+
}
|
|
43
|
+
admit(): WorkflowManager {
|
|
44
|
+
if (this.stale) throw new ToolError('RUNTIME_UNAVAILABLE', this.stale);
|
|
45
|
+
return this.manager;
|
|
46
|
+
}
|
|
47
|
+
list(): OwnedWorkflowTask[] {
|
|
48
|
+
const current = this.binding.current;
|
|
49
|
+
return current ? [...this.manager.tasks.values()].filter(task => this.manager.visible(task, this.agents.scope(current.ctx))) : [];
|
|
50
|
+
}
|
|
51
|
+
bind(): void {
|
|
52
|
+
this.detach();
|
|
53
|
+
const current = this.binding.current; if (!current) return;
|
|
54
|
+
if (this.stale && !this.warned) {
|
|
55
|
+
this.warned = true;
|
|
56
|
+
current.ctx.ui.notify(this.stale, 'warning');
|
|
57
|
+
}
|
|
58
|
+
const entries = workflowEntries(current.ctx.sessionManager.getBranch()); this.manager.restore(entries);
|
|
59
|
+
for (const entry of entries) this.saved.set(entry.id, `${entry.status}:${entry.endTime ?? ''}:${entry.notified}:${entry.error ?? ''}`);
|
|
60
|
+
this.unsubscribe = this.manager.subscribe(() => this.refresh()); this.refresh();
|
|
61
|
+
}
|
|
62
|
+
detach(): void {
|
|
63
|
+
this.unsubscribe?.(); this.unsubscribe = undefined;
|
|
64
|
+
if (this.binding.current) for (const id of this.queued) this.notices.cancel(this.binding.current.sessionId, `workflow:${id}:result`);
|
|
65
|
+
this.queued.clear(); this.saved.clear(); this.dock.invalidate();
|
|
66
|
+
}
|
|
67
|
+
private refresh(): void {
|
|
68
|
+
const current = this.binding.current; if (!current) return;
|
|
69
|
+
for (const task of this.list()) {
|
|
70
|
+
// A status may change while result files are still being flushed. Parent history
|
|
71
|
+
// must announce completion only after the execution owner has settled it.
|
|
72
|
+
if (!workflowActive(task) && !this.manager.settled(task.id)) continue;
|
|
73
|
+
const revision = `${task.status}:${task.endTime ?? ''}:${task.notified}:${task.error ?? ''}`;
|
|
74
|
+
if (this.saved.get(task.id) !== revision) {
|
|
75
|
+
this.saved.set(task.id, revision); this.pi.appendEntry(WORKFLOW_ENTRY_TYPE, this.manager.snapshot(task));
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
for (const item of this.unread()) {
|
|
79
|
+
if (this.queued.has(item.id)) continue;
|
|
80
|
+
this.queued.add(item.id);
|
|
81
|
+
this.notices.enqueue(current.sessionId, `workflow:${item.id}:result`, item.summary, () => this.consume(item),
|
|
82
|
+
'event', resultView(this.manager.get(item.id)));
|
|
83
|
+
}
|
|
84
|
+
this.dock.invalidate();
|
|
85
|
+
}
|
|
86
|
+
settlement(id: string): Settlement {
|
|
87
|
+
const task = this.manager.get(id), current = this.binding.current;
|
|
88
|
+
if (!current || !this.manager.visible(task, this.agents.scope(current.ctx))) throw new Error(`Workflow ${id} is not visible on this branch. Wait from the session branch that started it.`);
|
|
89
|
+
return {id, state: task.status, settled: this.manager.settled(id), summary: `${workflowSummary(task, true)}\n${resultBody(task)}`};
|
|
90
|
+
}
|
|
91
|
+
unread(): Settlement[] { return this.list().filter(task => this.manager.settled(task.id) && !task.notified).map(task => this.settlement(task.id)); }
|
|
92
|
+
subscribe(listener: () => void): () => void { return this.manager.subscribe(listener); }
|
|
93
|
+
consume(item: Settlement): void {
|
|
94
|
+
if (!item.settled) return;
|
|
95
|
+
const task = this.manager.get(item.id); task.notified = true;
|
|
96
|
+
this.queued.delete(item.id);
|
|
97
|
+
if (this.binding.current) this.notices.cancel(this.binding.current.sessionId, `workflow:${item.id}:result`);
|
|
98
|
+
this.manager.changed();
|
|
99
|
+
}
|
|
100
|
+
}
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
// Imported/adapted from @tintinweb/pi-subagents 0.23.0 src/workflow/journal.ts (MIT).
|
|
2
|
+
/**
|
|
3
|
+
* journal.ts — the record a workflow run leaves so a later run can skip work.
|
|
4
|
+
*
|
|
5
|
+
* ## What resume actually buys
|
|
6
|
+
*
|
|
7
|
+
* The documented iteration loop is "edit the persisted script and re-run it".
|
|
8
|
+
* Without a journal that re-pays every agent from scratch, which for a 40-agent
|
|
9
|
+
* audit is the entire cost of the run — to change one line of the last stage.
|
|
10
|
+
* With one, the unchanged prefix comes back from disk and only the edit runs.
|
|
11
|
+
*
|
|
12
|
+
* ## Why a *prefix*, and not a lookup table
|
|
13
|
+
*
|
|
14
|
+
* Each entry is keyed by both its position in the run and a hash of everything
|
|
15
|
+
* that decides what that agent does. A replay walks positions in order and
|
|
16
|
+
* stops reusing at the first entry that does not match — every call from there
|
|
17
|
+
* on runs live. Reusing later matches out of order would be reusing a result
|
|
18
|
+
* produced under different upstream conditions: the same prompt at position 12
|
|
19
|
+
* of a *different* run is not the same work, because what fed it changed.
|
|
20
|
+
*
|
|
21
|
+
* A failed agent is journaled as a failure and never replayed as one. Resuming
|
|
22
|
+
* a run that died at agent 5 exists to retry agent 5, so the prefix ends there
|
|
23
|
+
* and 5 onwards run live — the alternative would make a failure permanent.
|
|
24
|
+
*
|
|
25
|
+
* ## Runs that use `agent({ resume })`
|
|
26
|
+
*
|
|
27
|
+
* Those are not replayed at all. A replayed agent is text from a file, not a
|
|
28
|
+
* live child, so there is no conversation in this run for a later `resume` to
|
|
29
|
+
* continue — and the id map that would find one belongs to the run that did
|
|
30
|
+
* the spawning. Rather than replay a prefix that strands the first `resume`
|
|
31
|
+
* call, a journal carrying one declines the whole cache and the run pays in
|
|
32
|
+
* full. Coarse on purpose: the alternative is tracking which label each entry
|
|
33
|
+
* ran under and capping the prefix below the earliest one that gets resumed,
|
|
34
|
+
* which is a second key concept for a case that costs one run.
|
|
35
|
+
*
|
|
36
|
+
* ## Ordering under concurrency
|
|
37
|
+
*
|
|
38
|
+
* Positions are assigned as calls arrive, and with `pipeline` that order
|
|
39
|
+
* depends on which agent finished first. A replay usually reproduces it, since
|
|
40
|
+
* cached calls answer in journal order, but it is not guaranteed. That is why
|
|
41
|
+
* the key is checked as well as the position: a run that interleaves
|
|
42
|
+
* differently loses cache hits, it never returns another agent's answer.
|
|
43
|
+
*
|
|
44
|
+
* The file is JSON Lines, appended as each agent settles, so a run that is
|
|
45
|
+
* killed mid-flight still leaves everything it had finished.
|
|
46
|
+
*/
|
|
47
|
+
|
|
48
|
+
import { createHash } from "node:crypto";
|
|
49
|
+
import { appendFileSync, readFileSync } from "node:fs";
|
|
50
|
+
|
|
51
|
+
/** One settled agent call, as replayed. */
|
|
52
|
+
export interface WorkflowJournalEntry {
|
|
53
|
+
/** Position in the run — the same counter that names `wf-agent-N`. */
|
|
54
|
+
index: number;
|
|
55
|
+
/** Hash of the call's payload; a mismatch ends the replayable prefix. */
|
|
56
|
+
key: string;
|
|
57
|
+
/** Whether the agent succeeded. A failure ends the prefix on replay. */
|
|
58
|
+
ok: boolean;
|
|
59
|
+
/** The agent's answer, when it had one. */
|
|
60
|
+
text?: string;
|
|
61
|
+
/**
|
|
62
|
+
* Whether the call continued an earlier child (`agent({ resume })`).
|
|
63
|
+
*
|
|
64
|
+
* A replayed agent leaves no session behind in the run that replays it — the
|
|
65
|
+
* conversation belongs to the run that actually spawned it, and the host's
|
|
66
|
+
* id map is per-run — so a later `resume` would have nothing to continue.
|
|
67
|
+
* Recording it lets the next run decline to replay at all rather than fail
|
|
68
|
+
* partway through, which is why the flag is on the journal and not derived.
|
|
69
|
+
*/
|
|
70
|
+
resumed?: true;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* The fields that decide what an agent does.
|
|
75
|
+
*
|
|
76
|
+
* Deliberately not the whole payload: `phaseIndex` and `phaseTitle` move the
|
|
77
|
+
* row around in the progress tree without changing a single token the agent
|
|
78
|
+
* sees, so re-grouping phases should not throw away an hour of results.
|
|
79
|
+
*/
|
|
80
|
+
export interface JournalKeyInput {
|
|
81
|
+
prompt: string;
|
|
82
|
+
label?: string;
|
|
83
|
+
model?: string;
|
|
84
|
+
agentType?: string;
|
|
85
|
+
effort?: string;
|
|
86
|
+
gate?: string;
|
|
87
|
+
resume?: string;
|
|
88
|
+
/** Serialized `agent({ schema })`, when the call asked for one. */
|
|
89
|
+
schema?: string;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Stable hash of a call's payload. Field order is fixed here, not by the caller. */
|
|
93
|
+
export function journalKey(input: JournalKeyInput): string {
|
|
94
|
+
const canonical = JSON.stringify([
|
|
95
|
+
input.prompt,
|
|
96
|
+
input.label ?? null,
|
|
97
|
+
input.model ?? null,
|
|
98
|
+
input.agentType ?? null,
|
|
99
|
+
input.effort ?? null,
|
|
100
|
+
input.gate ?? null,
|
|
101
|
+
input.resume ?? null,
|
|
102
|
+
input.schema ?? null,
|
|
103
|
+
]);
|
|
104
|
+
return createHash("sha256").update(canonical).digest("hex").slice(0, 32);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** A torn final append is reported separately; other corruption is an error. */
|
|
108
|
+
export function readJournal(path: string): { entries: WorkflowJournalEntry[]; truncated: boolean } {
|
|
109
|
+
const raw = readFileSync(path, "utf-8");
|
|
110
|
+
const lines = raw.split("\n"), entries: WorkflowJournalEntry[] = [];
|
|
111
|
+
const positions = new Set<number>();
|
|
112
|
+
let truncated = false;
|
|
113
|
+
for (let i = 0; i < lines.length; i++) {
|
|
114
|
+
const line = lines[i];
|
|
115
|
+
if (!line.trim()) continue;
|
|
116
|
+
let parsed: unknown;
|
|
117
|
+
try { parsed = JSON.parse(line); }
|
|
118
|
+
catch (error) {
|
|
119
|
+
// A process may die during its last append. Only this suffix can be dropped,
|
|
120
|
+
// and the caller receives a flag so a resumed run can report the partial journal.
|
|
121
|
+
if (i === lines.length - 1 && !raw.endsWith("\n")) { truncated = true; break; }
|
|
122
|
+
throw new Error(`Invalid workflow journal ${path}:${i + 1}: ${String(error)}. Omit resumeFromRunId to run without replay.`);
|
|
123
|
+
}
|
|
124
|
+
if (!isEntry(parsed) || positions.has(parsed.index)) throw new Error(`Invalid or duplicate workflow journal entry ${path}:${i + 1}. Omit resumeFromRunId to run without replay.`);
|
|
125
|
+
positions.add(parsed.index); entries.push(parsed);
|
|
126
|
+
}
|
|
127
|
+
entries.sort((a, b) => a.index - b.index);
|
|
128
|
+
return { entries, truncated };
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Persistence is part of the resume contract; the runtime reports append failures. */
|
|
132
|
+
export function appendJournal(path: string, entry: WorkflowJournalEntry): void {
|
|
133
|
+
appendFileSync(path, `${JSON.stringify(entry)}\n`, "utf-8");
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function isEntry(value: unknown): value is WorkflowJournalEntry {
|
|
137
|
+
if (typeof value !== "object" || value === null) return false;
|
|
138
|
+
const entry = value as Record<string, unknown>;
|
|
139
|
+
return (
|
|
140
|
+
Number.isInteger(entry.index) &&
|
|
141
|
+
(entry.index as number) >= 0 &&
|
|
142
|
+
typeof entry.key === "string" &&
|
|
143
|
+
typeof entry.ok === "boolean" &&
|
|
144
|
+
(entry.text === undefined || typeof entry.text === "string") &&
|
|
145
|
+
(entry.resumed === undefined || entry.resumed === true)
|
|
146
|
+
);
|
|
147
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Restrict the metadata fragment to literals before the upstream VM evaluates it.
|
|
3
|
+
* An empty VM alone still permits computations such as (() => 'name')(), which
|
|
4
|
+
* contradict the deterministic metadata contract. Strings keep JavaScript escapes.
|
|
5
|
+
*/
|
|
6
|
+
export function assertPureLiteral(source: string): void {
|
|
7
|
+
const lexer = /\s+|\/\/[^\r\n]*|\/\*[\s\S]*?\*\/|"(?:\\[\s\S]|[^"\\\r\n])*"|'(?:\\[\s\S]|[^'\\\r\n])*'|`(?:\\[\s\S]|[^`\\$]|\$(?!\{))*`|-?(?:0[xX][\da-fA-F]+|0[bB][01]+|0[oO][0-7]+|(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?)|[$_\p{ID_Start}][$_\u200c\u200d\p{ID_Continue}]*|[{}\[\]:,]/uy;
|
|
8
|
+
let position = 0;
|
|
9
|
+
function fail(): never { throw new Error(`Expected a pure literal at metadata offset ${position}.`); }
|
|
10
|
+
function next(): string | undefined {
|
|
11
|
+
while (position < source.length) {
|
|
12
|
+
lexer.lastIndex = position;
|
|
13
|
+
const match = lexer.exec(source);
|
|
14
|
+
if (!match) fail();
|
|
15
|
+
position = lexer.lastIndex;
|
|
16
|
+
const text = match[0];
|
|
17
|
+
if (/^\s|^\/\//.test(text) || text.startsWith('/*')) continue;
|
|
18
|
+
return text;
|
|
19
|
+
}
|
|
20
|
+
return undefined;
|
|
21
|
+
}
|
|
22
|
+
let token = next();
|
|
23
|
+
const take = () => { token = next(); };
|
|
24
|
+
function expect(text: string): void {
|
|
25
|
+
if (token !== text) fail();
|
|
26
|
+
take();
|
|
27
|
+
}
|
|
28
|
+
function isString(text: string): boolean { return /^['"`]/.test(text); }
|
|
29
|
+
function isNumber(text: string): boolean { return /^-?[\d.]/.test(text); }
|
|
30
|
+
// Read through a function because recursive parsing advances the current token.
|
|
31
|
+
const current = () => token;
|
|
32
|
+
function value(): void {
|
|
33
|
+
const text = current();
|
|
34
|
+
if (text === '{' || text === '[') {
|
|
35
|
+
const object = text === '{', end = object ? '}' : ']';
|
|
36
|
+
take();
|
|
37
|
+
while (current() !== end) {
|
|
38
|
+
if (object) {
|
|
39
|
+
const key = current();
|
|
40
|
+
if (key === undefined || !(isString(key) || isNumber(key) || /^[$_\p{ID_Start}]/u.test(key))) fail();
|
|
41
|
+
// Template literals are values; JavaScript does not allow them as bare keys.
|
|
42
|
+
if (key.startsWith('`')) fail();
|
|
43
|
+
take(); expect(':');
|
|
44
|
+
}
|
|
45
|
+
value();
|
|
46
|
+
if (current() === end) break;
|
|
47
|
+
expect(',');
|
|
48
|
+
}
|
|
49
|
+
expect(end);
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
if (text === undefined || !(isString(text) || isNumber(text) || ['true', 'false', 'null'].includes(text))) fail();
|
|
53
|
+
take();
|
|
54
|
+
}
|
|
55
|
+
value();
|
|
56
|
+
if (token !== undefined) fail();
|
|
57
|
+
}
|