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,79 @@
|
|
|
1
|
+
import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
|
|
2
|
+
import { SessionBinding } from '../runtime/binding.ts';
|
|
3
|
+
import { Notifications } from '../runtime/notifications.ts';
|
|
4
|
+
import { WaitRegistry, registerWait } from '../runtime/wait.ts';
|
|
5
|
+
import { Dock } from '../ui/dock.ts';
|
|
6
|
+
import { StatusPublisher } from '../ui/status.ts';
|
|
7
|
+
import { TasksModule } from '../tasks/index.ts';
|
|
8
|
+
import { registerTaskTools } from '../tasks/tools.ts';
|
|
9
|
+
import { JobsModule } from '../jobs/index.ts';
|
|
10
|
+
import { registerJobTools } from '../jobs/tools.ts';
|
|
11
|
+
import { askSchema, type AskParams } from '../ask/schema.ts';
|
|
12
|
+
import { registerBoundTool } from '../runtime/tools.ts';
|
|
13
|
+
import { askRenderers } from '../ask/tool-render.ts';
|
|
14
|
+
import { askToolResult } from '../ask/result.ts';
|
|
15
|
+
import { askParent } from './questions.ts';
|
|
16
|
+
import { AgentsModule } from './index.ts';
|
|
17
|
+
import { registerAgentTools } from './tools.ts';
|
|
18
|
+
import type { AgentManager } from './manager.ts';
|
|
19
|
+
import type { Execution } from './types.ts';
|
|
20
|
+
import { loadConfig } from '../runtime/config.ts';
|
|
21
|
+
import { registerSuiteRenderers } from '../runtime/renderers.ts';
|
|
22
|
+
|
|
23
|
+
/** Child tools own a private list; only an explicit assigned scope can update parent progress. */
|
|
24
|
+
export async function childSuite(pi: ExtensionAPI, run: Execution, manager: AgentManager): Promise<void> {
|
|
25
|
+
// Child loaders exclude the main suite factory. Register display before bound tools so
|
|
26
|
+
// child/history lookup shares the same definitions without rereading an arbitrary target cwd.
|
|
27
|
+
registerSuiteRenderers(pi, run.config.ui.highlightBuiltinCommands);
|
|
28
|
+
const config = run.config, binding = new SessionBinding(), dock = new Dock();
|
|
29
|
+
const status = new StatusPublisher(dock), notices = new Notifications(pi, binding), waits = new WaitRegistry();
|
|
30
|
+
const recovery = config.runtime.openAIResponsesAutoRecovery
|
|
31
|
+
? (await import('../runtime/responses/index.ts')).registerResponsesRecovery(pi, binding, true) : undefined;
|
|
32
|
+
const tasks = config.modules.tasks ? new TasksModule(binding, dock, { persisted: run.record.persisted,
|
|
33
|
+
assigned: run.record.taskId && run.parent.taskStore ? { id: run.record.taskId, generation: run.record.taskGeneration, store: run.parent.taskStore } : undefined }) : undefined;
|
|
34
|
+
const agents = new AgentsModule(pi, binding, notices, status, tasks, run, manager);
|
|
35
|
+
const creatorRoots = () => binding.current ? agents.visibleRunIds(binding.current.ctx) : [];
|
|
36
|
+
const jobs = config.modules.jobs ? new JobsModule(pi, binding, notices, status, creatorRoots) : undefined;
|
|
37
|
+
const ask = { ask: (params: AskParams, _ctx: unknown, _config: unknown, signal?: AbortSignal) => askParent(run, params, config.ask.timeout, manager.changed, signal) };
|
|
38
|
+
registerBoundTool(pi, { ...askRenderers('Ask parent'), name: 'ask_user', label: 'Ask parent', parameters: askSchema, executionMode: 'sequential',
|
|
39
|
+
description: 'Ask your direct parent and wait for an answer. A timeout or cancellation is never consent; it ends this run without an answer.',
|
|
40
|
+
async execute(_id, params, signal) {
|
|
41
|
+
const { result, questions } = await ask.ask(params, undefined, undefined, signal);
|
|
42
|
+
return { ...askToolResult(params, questions, result, 'parent'), terminate: result.status !== 'answered' };
|
|
43
|
+
} }, 'initial');
|
|
44
|
+
if (tasks) { registerTaskTools(pi, tasks); tasks.registerReminders(pi, () => config, notices); }
|
|
45
|
+
if (jobs) {
|
|
46
|
+
const viewer = { jobs, dock, notifications: notices, keys: () => config.jobs };
|
|
47
|
+
registerJobTools(pi, jobs, viewer, { config: () => config, tasks,
|
|
48
|
+
creator: { agentId: run.record.id, runId: run.record.runId,
|
|
49
|
+
ancestors: [...run.record.ancestors, ...run.record.workflowId ? [run.record.workflowId] : []] } });
|
|
50
|
+
waits.register(jobs);
|
|
51
|
+
}
|
|
52
|
+
// Read fresh type settings for each nested start; the parent's own tool list stays fixed.
|
|
53
|
+
if (run.type.allowedSubagents && !run.isolated && run.record.ancestors.length + 1 < config.agents.maxDepth) {
|
|
54
|
+
// Turning off job tools does not erase jobs created before reload. This unbound
|
|
55
|
+
// facade reads the same process owner without registering tools or notifications.
|
|
56
|
+
registerAgentTools(pi, agents, waits, () => loadConfig(run.configCwd), undefined, jobs ?? new JobsModule(pi, binding, notices, status));
|
|
57
|
+
}
|
|
58
|
+
waits.register(agents); registerWait(pi, waits);
|
|
59
|
+
pi.on('session_start', async (_event, ctx) => {
|
|
60
|
+
binding.bind(ctx);
|
|
61
|
+
recovery?.reset(ctx);
|
|
62
|
+
await tasks?.bind(ctx, { reason: 'startup' });
|
|
63
|
+
run.taskStore = tasks?.scope(ctx);
|
|
64
|
+
agents.bind(); jobs?.bind();
|
|
65
|
+
});
|
|
66
|
+
pi.on('input', event => { if (event.streamingBehavior === 'steer') waits.userSteered(); });
|
|
67
|
+
pi.on('message_start', event => { if (event.message.role === 'user') waits.steeringDelivered(); });
|
|
68
|
+
pi.on('session_tree', (_event, ctx) => { recovery?.reset(ctx); });
|
|
69
|
+
pi.on('agent_before_settle', event => {
|
|
70
|
+
const repair = recovery?.beforeSettle(event);
|
|
71
|
+
return notices.beforeSettle(repair ? { ...event, ...repair } : event) ?? repair;
|
|
72
|
+
});
|
|
73
|
+
pi.on('agent_settled', () => { recovery?.settled(); waits.steeringDelivered(); notices.flush(); });
|
|
74
|
+
pi.on('session_shutdown', () => {
|
|
75
|
+
// The child owns its bindings, while the shared job/agent runtimes belong to the Pi process.
|
|
76
|
+
recovery?.reset();
|
|
77
|
+
agents.detach(); jobs?.detach(); tasks?.detach(); notices.detach(); binding.revoke();
|
|
78
|
+
});
|
|
79
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';
|
|
2
|
+
import type { BrowsePage } from '../ui/browser.ts';
|
|
3
|
+
import type { AgentsModule } from './index.ts';
|
|
4
|
+
import type { Dock } from '../ui/dock.ts';
|
|
5
|
+
import type { Notifications } from '../runtime/notifications.ts';
|
|
6
|
+
import type { SuiteConfig } from '../runtime/config.ts';
|
|
7
|
+
import type { AgentScheduler } from './schedules/index.ts';
|
|
8
|
+
import type { AgentJobViewer } from './viewer.ts';
|
|
9
|
+
|
|
10
|
+
export interface SubagentsDeps {
|
|
11
|
+
agents: AgentsModule; dock: Dock; notices: Notifications; config: () => SuiteConfig; reload: (cwd: string) => void;
|
|
12
|
+
scheduler?: AgentScheduler; workflows?: { available(): boolean; show(ctx: ExtensionContext, page: BrowsePage): Promise<void> }; jobs?: AgentJobViewer;
|
|
13
|
+
}
|
|
14
|
+
export function registerSubagentsCommand(pi: ExtensionAPI, deps: SubagentsDeps): void {
|
|
15
|
+
pi.registerCommand('subagents', { description: 'Browse child runs, types, schedules, and workflows',
|
|
16
|
+
handler: async (args, ctx) => { const { showSubagents } = await import('./ui/index.ts'); await showSubagents(args, ctx, deps); } });
|
|
17
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// Embedded descriptions and prompts imported from pi-subagents default-agents.ts (MIT).
|
|
2
|
+
import type { AgentType } from './types.ts';
|
|
3
|
+
|
|
4
|
+
const readOnly = ['read', 'bash', 'grep', 'find', 'ls'];
|
|
5
|
+
export const defaultTypes: AgentType[] = [
|
|
6
|
+
{ name: 'general-purpose', description: "General-purpose agent for researching complex questions, searching for code, and executing multi-step tasks. When you are searching for a keyword or file and are not confident that you will find the right match in the first few tries use this agent to perform the search for you.",
|
|
7
|
+
systemPrompt: '', promptMode: 'append' },
|
|
8
|
+
{ name: 'Explore', description: "Fast read-only search agent for locating code. Use it to find files by pattern (eg. \"src/components/**/*.tsx\"), grep for symbols or keywords (eg. \"API endpoints\"), or answer \"where is X defined / which files reference Y.\" Do NOT use it for code review, design-doc auditing, cross-file consistency checks, or open-ended analysis — it reads excerpts rather than whole files and will miss content past its read window. When calling, specify search breadth: \"quick\" for a single targeted lookup, \"medium\" for moderate exploration, or \"very thorough\" to search across multiple locations and naming conventions.",
|
|
9
|
+
tools: readOnly, systemPrompt: `# CRITICAL: READ-ONLY MODE - NO FILE MODIFICATIONS
|
|
10
|
+
You are a file search specialist. You excel at thoroughly navigating and exploring codebases.
|
|
11
|
+
Your role is EXCLUSIVELY to search and analyze existing code. You do NOT have access to file editing tools.
|
|
12
|
+
|
|
13
|
+
You are STRICTLY PROHIBITED from:
|
|
14
|
+
- Creating new files
|
|
15
|
+
- Modifying existing files
|
|
16
|
+
- Deleting files
|
|
17
|
+
- Moving or copying files
|
|
18
|
+
- Creating temporary files anywhere, including /tmp
|
|
19
|
+
- Using redirect operators (>, >>, |) or heredocs to write to files
|
|
20
|
+
- Running ANY commands that change system state
|
|
21
|
+
|
|
22
|
+
Use Bash ONLY for read-only operations: ls, git status, git log, git diff, find, cat, head, tail.
|
|
23
|
+
|
|
24
|
+
# Tool Usage
|
|
25
|
+
- Use the find tool for file pattern matching (NOT the bash find command)
|
|
26
|
+
- Use the grep tool for content search (NOT bash grep/rg command)
|
|
27
|
+
- Use the read tool for reading files (NOT bash cat/head/tail)
|
|
28
|
+
- Use Bash ONLY for read-only operations
|
|
29
|
+
- Make independent tool calls in parallel for efficiency
|
|
30
|
+
- Adapt search approach based on thoroughness level specified
|
|
31
|
+
|
|
32
|
+
# Output
|
|
33
|
+
- Use absolute file paths in all references
|
|
34
|
+
- Report findings as regular messages
|
|
35
|
+
- Do not use emojis
|
|
36
|
+
- Be thorough and precise`, promptMode: 'replace' },
|
|
37
|
+
{ name: 'Plan', description: "Software architect agent for designing implementation plans. Use this when you need to plan the implementation strategy for a task. Returns step-by-step plans, identifies critical files, and considers architectural trade-offs.",
|
|
38
|
+
tools: readOnly, systemPrompt: `# CRITICAL: READ-ONLY MODE - NO FILE MODIFICATIONS
|
|
39
|
+
You are a software architect and planning specialist.
|
|
40
|
+
Your role is EXCLUSIVELY to explore the codebase and design implementation plans.
|
|
41
|
+
You do NOT have write or edit tools. Bash can modify files, so use it only for read-only commands.
|
|
42
|
+
|
|
43
|
+
You are STRICTLY PROHIBITED from:
|
|
44
|
+
- Creating new files
|
|
45
|
+
- Modifying existing files
|
|
46
|
+
- Deleting files
|
|
47
|
+
- Moving or copying files
|
|
48
|
+
- Creating temporary files anywhere, including /tmp
|
|
49
|
+
- Using redirect operators (>, >>, |) or heredocs to write to files
|
|
50
|
+
- Running ANY commands that change system state
|
|
51
|
+
|
|
52
|
+
# Planning Process
|
|
53
|
+
1. Understand requirements
|
|
54
|
+
2. Explore thoroughly (read files, find patterns, understand architecture)
|
|
55
|
+
3. Design solution based on your assigned perspective
|
|
56
|
+
4. Detail the plan with step-by-step implementation strategy
|
|
57
|
+
|
|
58
|
+
# Requirements
|
|
59
|
+
- Consider trade-offs and architectural decisions
|
|
60
|
+
- Identify dependencies and sequencing
|
|
61
|
+
- Anticipate potential challenges
|
|
62
|
+
- Follow existing patterns where appropriate
|
|
63
|
+
|
|
64
|
+
# Tool Usage
|
|
65
|
+
- Use the find tool for file pattern matching (NOT the bash find command)
|
|
66
|
+
- Use the grep tool for content search (NOT bash grep/rg command)
|
|
67
|
+
- Use the read tool for reading files (NOT bash cat/head/tail)
|
|
68
|
+
- Use Bash ONLY for read-only operations
|
|
69
|
+
|
|
70
|
+
# Output Format
|
|
71
|
+
- Use absolute file paths
|
|
72
|
+
- Do not use emojis
|
|
73
|
+
- End your response with:
|
|
74
|
+
|
|
75
|
+
### Critical Files for Implementation
|
|
76
|
+
List 3-5 files most critical for implementing this plan:
|
|
77
|
+
- /absolute/path/to/file.ts - [Brief reason]`, promptMode: 'replace' },
|
|
78
|
+
];
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { readdir, stat } from 'node:fs/promises';
|
|
2
|
+
import { join, resolve } from 'node:path';
|
|
3
|
+
import { getAgentDir, SettingsManager, type SessionEntry } from '@earendil-works/pi-coding-agent';
|
|
4
|
+
import type { SuiteConfig } from '../runtime/config.ts';
|
|
5
|
+
import { ToolError } from '../runtime/errors.ts';
|
|
6
|
+
import { agentTypes } from './catalog.ts';
|
|
7
|
+
import { AGENT_ENTRY, decodeAgentRecord, readAgentSession } from './records.ts';
|
|
8
|
+
import { active, recordWorkspace, type AgentRecord, type ParentScope } from './types.ts';
|
|
9
|
+
import { resourcePath } from './resources/paths.ts';
|
|
10
|
+
import { WORKFLOW_ENTRY_TYPE, decodeWorkflowEntry } from './workflow/entry.ts';
|
|
11
|
+
import { readWorkflowSnapshot } from './workflow/store.ts';
|
|
12
|
+
|
|
13
|
+
export type SavedAgentRecord = {record: AgentRecord; updatedAt: number};
|
|
14
|
+
type SavedReference = {path: string; cwd?: string};
|
|
15
|
+
type SavedFile = {stamp: string; records: SavedAgentRecord[]; sessions: SavedReference[]; workflows: SavedReference[]; leafId?: string | null};
|
|
16
|
+
/** Parsed-file cache only; AgentManager remains the sole owner of runtime/history records. */
|
|
17
|
+
export class AgentHistory {
|
|
18
|
+
private files = new Map<string, SavedFile>();
|
|
19
|
+
private async directory(path: string): Promise<string[]> {
|
|
20
|
+
try { return (await readdir(path)).filter(name => name.endsWith('.jsonl')).map(name => join(path, name)); }
|
|
21
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return []; throw error; }
|
|
22
|
+
}
|
|
23
|
+
async scan(scope: ParentScope, config: SuiteConfig, signal?: AbortSignal): Promise<SavedAgentRecord[]> {
|
|
24
|
+
const cwd = scope.run?.configCwd ?? scope.ctx.cwd, agentDir = getAgentDir();
|
|
25
|
+
const trusted = scope.run?.configTrusted ?? scope.ctx.isProjectTrusted();
|
|
26
|
+
const settings = SettingsManager.create(cwd, agentDir, {projectTrusted: trusted});
|
|
27
|
+
const customDirs = new Set([scope.ctx.sessionManager.getSessionDir(), process.env.PI_CODING_AGENT_SESSION_DIR,
|
|
28
|
+
settings.getSessionDir(), ...agentTypes(cwd, agentDir, {trusted, packageGate: config.agents.packageAgents})
|
|
29
|
+
.map(type => type.sessionDir)].filter((dir): dir is string => Boolean(dir)).map(dir => resourcePath(dir, cwd)));
|
|
30
|
+
const defaultRoot = join(agentDir, 'sessions');
|
|
31
|
+
let defaultDirs: string[] = [];
|
|
32
|
+
try { defaultDirs = (await readdir(defaultRoot, {withFileTypes: true})).filter(entry => entry.isDirectory() || entry.isSymbolicLink()).map(entry => join(defaultRoot, entry.name)); }
|
|
33
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }
|
|
34
|
+
const groups = await Promise.all([...new Set([...defaultDirs, ...customDirs])].map(dir => this.directory(dir)));
|
|
35
|
+
const pending = groups.flat().map(path => ({path, workflow: false}));
|
|
36
|
+
const seen = new Set<string>(), merged = new Map<string, SavedAgentRecord>();
|
|
37
|
+
const add = (candidate: SavedAgentRecord) => {
|
|
38
|
+
if (recordWorkspace(candidate.record) !== cwd) return;
|
|
39
|
+
const old = merged.get(candidate.record.runId);
|
|
40
|
+
if (!old) { merged.set(candidate.record.runId, candidate); return; }
|
|
41
|
+
const [first, last] = old.updatedAt <= candidate.updatedAt ? [old, candidate] : [candidate, old];
|
|
42
|
+
// Workflow snapshots deliberately omit result bodies. They must not erase the SDK's
|
|
43
|
+
// final result or turn a settled run back into a stale startup reference.
|
|
44
|
+
const record = {...first.record, ...last.record, result: last.record.result ?? first.record.result};
|
|
45
|
+
if (!active(first.record.state) && active(last.record.state)) Object.assign(record, {
|
|
46
|
+
state: first.record.state, endedAt: first.record.endedAt, endLeafId: first.record.endLeafId, error: first.record.error});
|
|
47
|
+
merged.set(record.runId, {record, updatedAt: last.updatedAt});
|
|
48
|
+
};
|
|
49
|
+
const follow = (file: SavedFile) => {
|
|
50
|
+
for (const candidate of file.records) add(candidate);
|
|
51
|
+
// A cache belongs to the file, not the workspace that first read it. Apply the
|
|
52
|
+
// query scope here so switching projects still follows their external references.
|
|
53
|
+
const applies = (reference: SavedReference) => reference.cwd === undefined || reference.cwd === cwd;
|
|
54
|
+
pending.push(...file.sessions.filter(applies).map(({path}) => ({path, workflow: false})),
|
|
55
|
+
...file.workflows.filter(applies).map(({path}) => ({path, workflow: true})));
|
|
56
|
+
};
|
|
57
|
+
// An in-memory parent still has durable child references outside the default roots.
|
|
58
|
+
const current = this.entries(scope.ctx.sessionManager.getEntries(), 'current session');
|
|
59
|
+
follow(current);
|
|
60
|
+
for (let index = 0; index < pending.length; index++) {
|
|
61
|
+
signal?.throwIfAborted();
|
|
62
|
+
const item = pending[index], path = resolve(item.path);
|
|
63
|
+
if (seen.has(path)) continue;
|
|
64
|
+
seen.add(path);
|
|
65
|
+
const stats = await stat(path), stamp = `${stats.mtimeMs}:${stats.size}`;
|
|
66
|
+
let file = this.files.get(path);
|
|
67
|
+
if (!file || file.stamp !== stamp) {
|
|
68
|
+
if (item.workflow) {
|
|
69
|
+
const data = readWorkflowSnapshot(path);
|
|
70
|
+
file = {stamp, records: data.children.map(record => ({record, updatedAt: stats.mtimeMs})),
|
|
71
|
+
sessions: data.children.flatMap(record => record.sessionFile ? [{path: record.sessionFile, cwd: recordWorkspace(record)}] : []), workflows: []};
|
|
72
|
+
} else {
|
|
73
|
+
const manager = readAgentSession(path);
|
|
74
|
+
file = {...this.entries(manager.getEntries(), path), stamp, leafId: manager.getLeafId()};
|
|
75
|
+
const parent = manager.getHeader()?.parentSession;
|
|
76
|
+
if (parent) file.sessions.push({path: parent});
|
|
77
|
+
}
|
|
78
|
+
this.files.set(path, file);
|
|
79
|
+
}
|
|
80
|
+
follow(file);
|
|
81
|
+
}
|
|
82
|
+
for (const path of this.files.keys()) if (!seen.has(path)) this.files.delete(path);
|
|
83
|
+
return [...merged.values()].map(candidate => {
|
|
84
|
+
const record = candidate.record;
|
|
85
|
+
if (!active(record.state)) return candidate;
|
|
86
|
+
// Saved startup state is evidence of an interrupted owner, not an active process.
|
|
87
|
+
return {...candidate, record: {...record, state: 'failed',
|
|
88
|
+
endLeafId: record.sessionFile ? this.files.get(resolve(record.sessionFile))?.leafId : record.endLeafId,
|
|
89
|
+
error: record.sessionFile ? 'This run is not active in this Pi process. Use agent_read to read the saved transcript.'
|
|
90
|
+
: 'This run is not active in this Pi process and has no saved transcript. Start a new agent.'}};
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
private entries(entries: readonly SessionEntry[], source: string): SavedFile {
|
|
94
|
+
const file: SavedFile = {stamp: '', records: [], sessions: [], workflows: []};
|
|
95
|
+
for (const entry of entries) if (entry.type === 'custom') {
|
|
96
|
+
if (entry.customType !== AGENT_ENTRY && entry.customType !== WORKFLOW_ENTRY_TYPE) continue;
|
|
97
|
+
const updatedAt = Date.parse(entry.timestamp);
|
|
98
|
+
if (!Number.isFinite(updatedAt)) throw new ToolError('AGENT_HISTORY', `Invalid suite record timestamp in ${source}. Check the saved timestamp before retrying.`);
|
|
99
|
+
if (entry.customType === AGENT_ENTRY) {
|
|
100
|
+
const record = decodeAgentRecord(entry.data, source);
|
|
101
|
+
file.records.push({record, updatedAt});
|
|
102
|
+
if (record.sessionFile) file.sessions.push({path: record.sessionFile, cwd: recordWorkspace(record)});
|
|
103
|
+
} else if (entry.customType === WORKFLOW_ENTRY_TYPE) {
|
|
104
|
+
const data = decodeWorkflowEntry(entry.data);
|
|
105
|
+
file.records.push(...data.children.map(record => ({record, updatedAt})));
|
|
106
|
+
file.workflows.push({path: data.recordPath, cwd: data.cwd});
|
|
107
|
+
file.sessions.push(...data.children.flatMap(record => record.sessionFile ? [{path: record.sessionFile, cwd: recordWorkspace(record)}] : []));
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return file;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
import type { ExtensionAPI, ExtensionContext } 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 { StatusPublisher } from '../ui/status.ts';
|
|
5
|
+
import { PresentationTicker } from '../ui/ticker.ts';
|
|
6
|
+
import type { DockRow } from '../ui/dock.ts';
|
|
7
|
+
import type { DisplayField, DisplayText } from '../ui/browser-chrome.ts';
|
|
8
|
+
import { countText, elapsedText } from '../ui/format.ts';
|
|
9
|
+
import type { Settlement, Waitable } from '../runtime/wait.ts';
|
|
10
|
+
import { sanitizeText } from '../runtime/text.ts';
|
|
11
|
+
import { boundedText } from '../runtime/read.ts';
|
|
12
|
+
import { active, executing, type AgentRecord, type Execution, type ParentScope } from './types.ts';
|
|
13
|
+
import { AGENT_ENTRY, recordsIn } from './records.ts';
|
|
14
|
+
import { groupAgentRuns } from './run-groups.ts';
|
|
15
|
+
import { retrySuffix } from './retry.ts';
|
|
16
|
+
import { questionNotification, questionText } from './questions.ts';
|
|
17
|
+
import { agentRuntime } from './runtime.ts';
|
|
18
|
+
import type { AgentManager } from './manager.ts';
|
|
19
|
+
import { customRendererLookup, toolRenderer } from '../runtime/tools.ts';
|
|
20
|
+
import { ToolError } from '../runtime/errors.ts';
|
|
21
|
+
import type { TasksModule } from '../tasks/index.ts';
|
|
22
|
+
|
|
23
|
+
export function summaryLine(record: AgentRecord): string {
|
|
24
|
+
return `${record.id} ${record.state} · ${boundedText(sanitizeText(record.name).replace(/[\r\n\t]/g, ' '), 200)} · ${record.runId}${record.elapsedMs === undefined ? '' : ` · ${(record.elapsedMs / 1000).toFixed(1)}s`}`;
|
|
25
|
+
}
|
|
26
|
+
export function agentSummary(record: AgentRecord) {
|
|
27
|
+
const { prompt, result, ...summary } = record;
|
|
28
|
+
return { ...summary, promptSummary: boundedText(prompt, 200), resultSummary: result === undefined ? undefined : boundedText(result, 500) };
|
|
29
|
+
}
|
|
30
|
+
export function usageText(record: AgentRecord): string | undefined {
|
|
31
|
+
const usage = record.usage;
|
|
32
|
+
return usage && `usage: input ${usage.tokens.input} · output ${usage.tokens.output} · cacheRead ${usage.tokens.cacheRead} · cacheWrite ${usage.tokens.cacheWrite} · total ${usage.tokens.total} · cost $${usage.cost.toFixed(6)}`;
|
|
33
|
+
}
|
|
34
|
+
function resultLines(record: AgentRecord, error = record.error): string[] {
|
|
35
|
+
return [record.error ? usageText(record) : undefined, record.error ? `error: ${error}` : undefined,
|
|
36
|
+
record.result === undefined ? undefined : boundedText(record.result, 2048),
|
|
37
|
+
record.result && Buffer.byteLength(record.result) > 2048 ? `full: agent_read({"id":"${record.id}","runId":"${record.runId}","stream":"result","offset":0})` : undefined].filter(value => value !== undefined);
|
|
38
|
+
}
|
|
39
|
+
function resultSummary(record: AgentRecord): string { return [summaryLine(record), ...resultLines(record)].join('\n'); }
|
|
40
|
+
function providerErrorMessage(error: string): string {
|
|
41
|
+
// Provider errors may be plain text or a JSON envelope prefixed with the HTTP status.
|
|
42
|
+
const json = error.trim().replace(/^\d{3}\s+/, '');
|
|
43
|
+
if (!json.startsWith('{')) return error;
|
|
44
|
+
try {
|
|
45
|
+
const message = JSON.parse(json)?.error?.message;
|
|
46
|
+
return typeof message === 'string' ? message : error;
|
|
47
|
+
} catch (cause) {
|
|
48
|
+
if (!(cause instanceof SyntaxError)) throw cause;
|
|
49
|
+
return error; // Not a complete provider envelope; show the original diagnostic.
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
function resultView(record: AgentRecord): NotificationView {
|
|
53
|
+
const { id, state, name, runId, elapsedMs, error } = record;
|
|
54
|
+
return { title: 'Agent result', state, meta: [id, runId, ...elapsedMs === undefined ? [] : [`${(elapsedMs / 1000).toFixed(1)}s`], boundedText(name, 200)],
|
|
55
|
+
body: resultLines(record, error && providerErrorMessage(error)).join('\n') };
|
|
56
|
+
}
|
|
57
|
+
export class AgentsModule implements Waitable {
|
|
58
|
+
readonly prefix = 'agent_';
|
|
59
|
+
readonly manager: AgentManager;
|
|
60
|
+
/** Set when the process owner comes from an earlier module load and is still busy. */
|
|
61
|
+
readonly stale?: string;
|
|
62
|
+
private warned = false;
|
|
63
|
+
private unsubscribe?: () => void;
|
|
64
|
+
private readonly ticker = new PresentationTicker(() => this.status.detailsVisible('agents'), () => {
|
|
65
|
+
const scope = this.scope(this.binding.current!.ctx);
|
|
66
|
+
this.publishActivities(this.manager.records().filter(record => this.manager.visible(record, scope)), scope);
|
|
67
|
+
});
|
|
68
|
+
private queued = new Set<string>();
|
|
69
|
+
private saved = new Map<string, string>();
|
|
70
|
+
constructor(private pi: ExtensionAPI, private binding: SessionBinding, private notifications: Notifications,
|
|
71
|
+
private status: StatusPublisher, private tasks?: TasksModule, private parentRun?: Execution, manager?: AgentManager) {
|
|
72
|
+
if (manager) this.manager = manager;
|
|
73
|
+
else ({ owner: this.manager, stale: this.stale } = agentRuntime());
|
|
74
|
+
}
|
|
75
|
+
/** A busy manager from before reload can finish runs but cannot start new ones. */
|
|
76
|
+
admit(): AgentManager {
|
|
77
|
+
if (this.stale) throw new ToolError('RUNTIME_UNAVAILABLE', this.stale);
|
|
78
|
+
return this.manager;
|
|
79
|
+
}
|
|
80
|
+
/** Steering or answering a live run stays available; resuming a settled one would start a new run. */
|
|
81
|
+
admitSend(id: string): AgentManager {
|
|
82
|
+
if (this.stale) {
|
|
83
|
+
const { record, run } = this.manager.get(id);
|
|
84
|
+
if (!run || !active(record.state)) return this.admit();
|
|
85
|
+
}
|
|
86
|
+
return this.manager;
|
|
87
|
+
}
|
|
88
|
+
/** Collected runs have no child runner; their transcript uses the Suite registry. */
|
|
89
|
+
renderer(name: string) { return toolRenderer(this.pi, name); }
|
|
90
|
+
customRendererLookup() { return customRendererLookup(this.pi); }
|
|
91
|
+
scope(ctx: ExtensionContext): ParentScope { return { ctx, run: this.parentRun, taskStore: this.tasks?.scope(ctx) ?? this.parentRun?.parent.taskStore }; }
|
|
92
|
+
visibleRunIds(ctx: ExtensionContext): string[] {
|
|
93
|
+
const scope = this.scope(ctx);
|
|
94
|
+
return this.manager.records().filter(record => this.manager.visible(record, scope)).map(record => record.runId);
|
|
95
|
+
}
|
|
96
|
+
bind(): void {
|
|
97
|
+
this.detach();
|
|
98
|
+
const current = this.binding.current;
|
|
99
|
+
if (!current) return;
|
|
100
|
+
if (this.stale && !this.warned) {
|
|
101
|
+
this.warned = true;
|
|
102
|
+
current.ctx.ui.notify(this.stale, 'warning');
|
|
103
|
+
}
|
|
104
|
+
const records = recordsIn(current.ctx.sessionManager.getBranch());
|
|
105
|
+
this.manager.restore(records);
|
|
106
|
+
for (const record of records) this.saved.set(record.runId, this.revision(record));
|
|
107
|
+
this.unsubscribe = this.manager.subscribe(() => this.refresh()); this.refresh();
|
|
108
|
+
}
|
|
109
|
+
detach(): void {
|
|
110
|
+
this.unsubscribe?.(); this.unsubscribe = undefined;
|
|
111
|
+
this.ticker.stop();
|
|
112
|
+
const current = this.binding.current;
|
|
113
|
+
if (current) for (const request of this.queued) this.notifications.cancel(current.sessionId, request);
|
|
114
|
+
this.queued.clear(); this.saved.clear(); this.status.setActivities('agents', []);
|
|
115
|
+
}
|
|
116
|
+
private rows(records: AgentRecord[], scope: ParentScope): { rows: DockRow[]; aside: DisplayText; ticking: boolean } {
|
|
117
|
+
// A consumed question is still awaiting its answer. Include workflow questions
|
|
118
|
+
// visible to this parent without exposing unrelated runs or nested descendants.
|
|
119
|
+
const visible = new Map(records.map(record => [record.runId, record]));
|
|
120
|
+
for (const run of this.manager.runs.values()) if (run.question && this.manager.questionVisible(run.record, scope)) {
|
|
121
|
+
visible.set(run.record.runId, this.manager.view(run));
|
|
122
|
+
}
|
|
123
|
+
// Pick representatives before filtering; an unread older failure may still notify,
|
|
124
|
+
// but must not keep a row after the latest run has superseded it.
|
|
125
|
+
const latest = Array.from(groupAgentRuns(visible.values()).values(), ([record]) => record);
|
|
126
|
+
const counts = new Map<string, number>();
|
|
127
|
+
const rows = latest.flatMap<DockRow>(record => {
|
|
128
|
+
const run = this.manager.runs.get(record.runId), question = Boolean(run?.question);
|
|
129
|
+
const failed = ['failed', 'limited'].includes(record.state) && run && !run.consumed;
|
|
130
|
+
if (!active(record.state) && !failed) return [];
|
|
131
|
+
const state = question ? 'waiting(parent)' : record.state;
|
|
132
|
+
counts.set(state, (counts.get(state) ?? 0) + 1);
|
|
133
|
+
const retry = retrySuffix(run);
|
|
134
|
+
const status: DisplayField[] = [{text: state, state}, ...retry ? [{text: retry, tone: 'dim' as const}] : []];
|
|
135
|
+
const basic: DisplayField[] = [...status, {text: ` · ${elapsedText(record.elapsedMs ?? 0)}`, tone: 'dim'}];
|
|
136
|
+
const tools = `${record.toolUses ?? 0} tools`;
|
|
137
|
+
const model = record.model.slice(record.model.indexOf('/') + 1);
|
|
138
|
+
return [{ id: `agent:${record.runId}`, text: `${sanitizeText(record.name).replace(/[\r\n\t]/g, ' ')} (${sanitizeText(model)})`,
|
|
139
|
+
suffix: [...basic, {text: ` · ↑${countText(record.usage?.tokens.input ?? 0)} ↓${countText(record.usage?.tokens.output ?? 0)} · ${tools}`, tone: 'dim'}],
|
|
140
|
+
compactSuffixes: [[...basic, {text: ` · ${tools}`, tone: 'dim'}], basic, status],
|
|
141
|
+
priority: question ? 100 : failed ? 80 : record.state === 'stopping' ? 75 : record.state === 'queued' ? 15 : 25 }];
|
|
142
|
+
});
|
|
143
|
+
const aside: DisplayField[] = ['starting', 'running', 'waiting', 'waiting(parent)', 'stopping', 'queued', 'failed', 'limited']
|
|
144
|
+
.filter(state => counts.has(state)).flatMap((state, index) => [
|
|
145
|
+
...index ? [{text: ' · ', tone: 'dim' as const}] : [], {text: `${counts.get(state)} ${state}`, state},
|
|
146
|
+
]);
|
|
147
|
+
return {rows, aside, ticking: latest.some(record => active(record.state))};
|
|
148
|
+
}
|
|
149
|
+
private publishActivities(records: AgentRecord[], scope: ParentScope): void {
|
|
150
|
+
const {rows, aside, ticking} = this.rows(records, scope);
|
|
151
|
+
this.status.setActivities('agents', records.filter(record => executing(record.state)).map(record => record.id), rows, aside);
|
|
152
|
+
this.ticker.update(ticking);
|
|
153
|
+
}
|
|
154
|
+
private revision(record: AgentRecord): string { return `${record.state}:${record.background}:${record.sessionFile ?? ''}:${record.endedAt ?? ''}:${record.model}:${record.thinking}:${JSON.stringify(record.individual)}`; }
|
|
155
|
+
private refresh(): void {
|
|
156
|
+
const current = this.binding.current;
|
|
157
|
+
if (!current) return;
|
|
158
|
+
const scope = this.scope(current.ctx), records = this.manager.records().filter(record => this.manager.visible(record, scope));
|
|
159
|
+
this.publishActivities(records, scope);
|
|
160
|
+
const unread = this.unreadNotices();
|
|
161
|
+
for (const request of this.queued) if (!unread.some(({ item }) => this.request(item) === request)) {
|
|
162
|
+
this.notifications.cancel(current.sessionId, request); this.queued.delete(request);
|
|
163
|
+
}
|
|
164
|
+
for (const record of records) {
|
|
165
|
+
// Only structural state changes become entries; token deltas and timers never grow the parent log.
|
|
166
|
+
const revision = this.revision(record);
|
|
167
|
+
if (this.saved.get(record.runId) !== revision) {
|
|
168
|
+
// Pi emits a synchronous session-entry event. Publish the revision first so a parent
|
|
169
|
+
// child subscriber cannot re-enter and append the same record indefinitely.
|
|
170
|
+
this.saved.set(record.runId, revision); this.pi.appendEntry(AGENT_ENTRY, record);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
for (const { item, view } of unread) {
|
|
174
|
+
const request = this.request(item);
|
|
175
|
+
if (this.queued.has(request)) continue;
|
|
176
|
+
this.queued.add(request);
|
|
177
|
+
this.notifications.enqueue(current.sessionId, request, item.summary, () => { this.queued.delete(request); this.consume(item); }, 'event', view());
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
// Include the run ID so consuming one result cannot cancel another run's notification.
|
|
181
|
+
private request(item: Settlement): string { return `agent:${item.id}:${item.runId}${item.question ? ':ask' : ':result'}`; }
|
|
182
|
+
settlement(id: string): Settlement {
|
|
183
|
+
const { record, run } = this.manager.get(id);
|
|
184
|
+
const question = run?.question && !run.question.seen;
|
|
185
|
+
return { id, runId: record.runId, state: record.state, settled: !active(record.state), question: Boolean(question),
|
|
186
|
+
summary: question ? questionText(run!) : active(record.state) ? summaryLine(record) : resultSummary(record) };
|
|
187
|
+
}
|
|
188
|
+
unread(): Settlement[] { return this.unreadNotices().map(({ item }) => item); }
|
|
189
|
+
private unreadNotices(): { item: Settlement; view: () => NotificationView }[] {
|
|
190
|
+
const current = this.binding.current;
|
|
191
|
+
if (!current) return [];
|
|
192
|
+
const scope = this.scope(current.ctx);
|
|
193
|
+
return [...this.manager.runs.values()].filter(run => run.question && !run.question.seen && this.manager.questionVisible(run.record, scope)
|
|
194
|
+
|| this.manager.visible(run.record, scope) && run.settled && !run.consumed && (run.record.background || run.notifyResult)).map(run => {
|
|
195
|
+
const record = this.manager.view(run);
|
|
196
|
+
const question = run.question && !run.question.seen ? questionNotification(run) : undefined;
|
|
197
|
+
const item: Settlement = { id: record.id, runId: record.runId, state: record.state, settled: !active(record.state),
|
|
198
|
+
question: Boolean(question), summary: question?.text ?? `Agent result: ${resultSummary(record)}` };
|
|
199
|
+
return { item, view: () => question?.view ?? resultView(record) };
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
subscribe(listener: () => void): () => void { return this.manager.subscribe(listener); }
|
|
203
|
+
consume(item: Settlement): void {
|
|
204
|
+
const { run } = this.manager.get(item.id, item.runId);
|
|
205
|
+
if (run) { if (item.question && run.question) run.question.seen = true; else if (item.settled) run.consumed = true; }
|
|
206
|
+
const current = this.binding.current, request = this.request(item);
|
|
207
|
+
if (current) this.notifications.cancel(current.sessionId, request);
|
|
208
|
+
this.queued.delete(request);
|
|
209
|
+
this.refresh();
|
|
210
|
+
}
|
|
211
|
+
}
|