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,111 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
4
|
+
import { Type, type Static } from "typebox";
|
|
5
|
+
import { Value } from "typebox/value";
|
|
6
|
+
import { Key, type KeyId } from "@earendil-works/pi-tui";
|
|
7
|
+
import { mergePresets, presetsSchema, type Preset } from "../jobs/launch/config.ts";
|
|
8
|
+
import { thinkingSchema } from "../agents/schema.ts";
|
|
9
|
+
import type { AgentTypeSettings } from "../agents/types.ts";
|
|
10
|
+
|
|
11
|
+
const keyNames = Object.values(Key).flatMap(key => typeof key === "string"
|
|
12
|
+
? [key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")] : []);
|
|
13
|
+
const keyPattern = `^(?:(?:ctrl|alt|shift|super)\\+)*(?:[a-z0-9]|${keyNames.join("|")})$`;
|
|
14
|
+
|
|
15
|
+
const display = Type.String({ enum: ["status", "dock", "hidden"] });
|
|
16
|
+
export const configSchema = Type.Object({
|
|
17
|
+
commands: Type.Optional(Type.Object({ exit: Type.Optional(Type.Boolean()) }, { additionalProperties: false })),
|
|
18
|
+
modules: Type.Optional(Type.Object({
|
|
19
|
+
ask: Type.Optional(Type.Boolean()), tasks: Type.Optional(Type.Boolean()),
|
|
20
|
+
jobs: Type.Optional(Type.Boolean()), goal: Type.Optional(Type.Boolean()),
|
|
21
|
+
agents: Type.Optional(Type.Boolean()),
|
|
22
|
+
}, { additionalProperties: false })),
|
|
23
|
+
runtime: Type.Optional(Type.Object({
|
|
24
|
+
openAIResponsesAutoRecovery: Type.Optional(Type.Boolean({ description: "Responses history ID recovery." })),
|
|
25
|
+
}, { additionalProperties: false })),
|
|
26
|
+
ui: Type.Optional(Type.Object({ maxRows: Type.Optional(Type.Integer({ minimum: 1, maximum: 30,
|
|
27
|
+
description: "Idle Dock rows: 1–30 (default 12)." })),
|
|
28
|
+
highlightBuiltinCommands: Type.Optional(Type.Boolean({ description: "Built-in Bash and PowerShell highlighting." })) }, { additionalProperties: false })),
|
|
29
|
+
ask: Type.Optional(Type.Object({
|
|
30
|
+
timeout: Type.Optional(Type.Integer({ minimum: 0, maximum: 2147483647 })),
|
|
31
|
+
historyKey: Type.Optional(Type.String({ pattern: keyPattern })),
|
|
32
|
+
}, { additionalProperties: false })),
|
|
33
|
+
goal: Type.Optional(Type.Object({ display: Type.Optional(display) }, { additionalProperties: false })),
|
|
34
|
+
tasks: Type.Optional(Type.Object({ reminders: Type.Optional(Type.Boolean()) }, { additionalProperties: false })),
|
|
35
|
+
agents: Type.Optional(Type.Object({
|
|
36
|
+
display: Type.Optional(display), maxConcurrent: Type.Optional(Type.Integer({ minimum: 1 })),
|
|
37
|
+
maxConcurrentForeground: Type.Optional(Type.Integer({ minimum: 0 })),
|
|
38
|
+
maxDepth: Type.Optional(Type.Integer({ minimum: 1 })), persistSessions: Type.Optional(Type.Boolean()),
|
|
39
|
+
defaultModel: Type.Optional(Type.String({ minLength: 1 })),
|
|
40
|
+
types: Type.Optional(Type.Record(Type.String(), Type.Object({ model: Type.Optional(Type.String({ minLength: 1 })),
|
|
41
|
+
thinking: Type.Optional(thinkingSchema), enabled: Type.Optional(Type.Boolean()) }, { additionalProperties: false }))),
|
|
42
|
+
packageAgents: Type.Optional(Type.Union([Type.Boolean(), Type.Array(Type.String({ minLength: 1 }))])),
|
|
43
|
+
mentions: Type.Optional(Type.Boolean()),
|
|
44
|
+
scheduling: Type.Optional(Type.Boolean()),
|
|
45
|
+
workflows: Type.Optional(Type.Boolean()),
|
|
46
|
+
packageWorkflows: Type.Optional(Type.Union([Type.Boolean(), Type.Array(Type.String({ minLength: 1 }))])),
|
|
47
|
+
}, { additionalProperties: false })),
|
|
48
|
+
jobs: Type.Optional(Type.Object({
|
|
49
|
+
display: Type.Optional(display),
|
|
50
|
+
detachKey: Type.Optional(Type.String({ pattern: keyPattern })),
|
|
51
|
+
returnKey: Type.Optional(Type.String({ pattern: keyPattern })),
|
|
52
|
+
transferKey: Type.Optional(Type.String({ pattern: keyPattern })),
|
|
53
|
+
agents: Type.Optional(presetsSchema),
|
|
54
|
+
}, { additionalProperties: false })),
|
|
55
|
+
}, { additionalProperties: false });
|
|
56
|
+
|
|
57
|
+
export type DisplayMode = "status" | "dock" | "hidden";
|
|
58
|
+
export interface SuiteConfig {
|
|
59
|
+
commands: { exit: boolean };
|
|
60
|
+
modules: Record<"ask" | "tasks" | "jobs" | "goal" | "agents", boolean>;
|
|
61
|
+
runtime: { openAIResponsesAutoRecovery: boolean };
|
|
62
|
+
ui: { maxRows: number; highlightBuiltinCommands: boolean };
|
|
63
|
+
ask: { timeout: number; historyKey: KeyId };
|
|
64
|
+
goal: { display: DisplayMode };
|
|
65
|
+
tasks: { reminders: boolean };
|
|
66
|
+
agents: { display: DisplayMode; maxConcurrent: number; maxConcurrentForeground: number;
|
|
67
|
+
maxDepth: number; persistSessions: boolean; defaultModel?: string;
|
|
68
|
+
types: Record<string, AgentTypeSettings>; packageAgents?: boolean | string[];
|
|
69
|
+
mentions: boolean; scheduling: boolean; workflows: boolean; packageWorkflows?: boolean | string[] };
|
|
70
|
+
/** Terminal view keys: leave the view, hand input back to the model, send the screen to the model. */
|
|
71
|
+
jobs: { display: DisplayMode; detachKey: KeyId; returnKey: KeyId; transferKey: KeyId;
|
|
72
|
+
agents: Record<string, Preset> };
|
|
73
|
+
}
|
|
74
|
+
export const defaults: SuiteConfig = {
|
|
75
|
+
commands: { exit: true },
|
|
76
|
+
modules: { ask: true, tasks: true, jobs: true, goal: true, agents: true },
|
|
77
|
+
runtime: { openAIResponsesAutoRecovery: false },
|
|
78
|
+
ui: { maxRows: 12, highlightBuiltinCommands: true }, ask: { timeout: 600000, historyKey: "ctrl+h" },
|
|
79
|
+
goal: { display: "status" }, agents: { display: "status", maxConcurrent: 10, maxConcurrentForeground: 0,
|
|
80
|
+
maxDepth: 3, persistSessions: true, types: {}, mentions: true, scheduling: true, workflows: true },
|
|
81
|
+
tasks: { reminders: true },
|
|
82
|
+
// tmux intercepts Ctrl+B as its default prefix before the terminal view can see it.
|
|
83
|
+
jobs: { display: "status", detachKey: Key.ctrl(Key.rightbracket), returnKey: "ctrl+g", transferKey: "ctrl+t",
|
|
84
|
+
agents: mergePresets() },
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
export function readConfig(path: string): Static<typeof configSchema> {
|
|
88
|
+
let raw: string;
|
|
89
|
+
try { raw = readFileSync(path, "utf8"); }
|
|
90
|
+
catch (error) {
|
|
91
|
+
// Absence means no override; permission and I/O failures must remain visible.
|
|
92
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return {};
|
|
93
|
+
throw error;
|
|
94
|
+
}
|
|
95
|
+
const value: unknown = JSON.parse(raw);
|
|
96
|
+
if (!Value.Check(configSchema, value)) throw new Error(`Invalid pi-suite configuration: ${path}`);
|
|
97
|
+
return value;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function loadConfig(cwd: string, agentDir = getAgentDir()): SuiteConfig {
|
|
101
|
+
const user = readConfig(join(agentDir, "pi-suite.json"));
|
|
102
|
+
const project = readConfig(join(cwd, ".pi", "pi-suite.json"));
|
|
103
|
+
// Merge individual sections so a project timeout does not reset user shortcuts.
|
|
104
|
+
const config = Object.fromEntries(Object.entries(defaults).map(([key, value]) => [
|
|
105
|
+
key, { ...value, ...user[key as keyof typeof user], ...project[key as keyof typeof project] },
|
|
106
|
+
])) as unknown as SuiteConfig;
|
|
107
|
+
config.jobs.agents = mergePresets(user.jobs?.agents, project.jobs?.agents);
|
|
108
|
+
config.agents.types = Object.fromEntries([...new Set([...Object.keys(user.agents?.types ?? {}), ...Object.keys(project.agents?.types ?? {})])]
|
|
109
|
+
.map(type => [type, { ...user.agents?.types?.[type], ...project.agents?.types?.[type] }]));
|
|
110
|
+
return config;
|
|
111
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** Stable error codes shared by every model tool (doc/current/runtime/tools.md). */
|
|
2
|
+
export type ToolErrorCode =
|
|
3
|
+
| 'INVALID_ARGS' | 'NOT_FOUND' | 'AMBIGUOUS_NAME' | 'HISTORY_READ_ONLY' | 'NOT_RUNNING' | 'USER_CONTROL'
|
|
4
|
+
| 'STALE_BINDING' | 'CLOSING' | 'UNSUPPORTED_STREAM' | (string & {});
|
|
5
|
+
export class ToolError extends Error {
|
|
6
|
+
code: ToolErrorCode; objectId?: string;
|
|
7
|
+
constructor(code: ToolErrorCode, message: string, objectId?: string) {
|
|
8
|
+
// The code leads the message because tool errors reach the model as text only.
|
|
9
|
+
super(`${code}: ${message}`); this.name = 'ToolError'; this.code = code; this.objectId = objectId;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
// Adapted from @tintinweb/pi-tasks 0.9.1 src/task-store.ts (MIT).
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import { watch, type FSWatcher } from 'node:fs';
|
|
4
|
+
import { access, mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
|
|
5
|
+
import { basename, dirname } from 'node:path';
|
|
6
|
+
import { setTimeout as sleep } from 'node:timers/promises';
|
|
7
|
+
import { ToolError } from './errors.ts';
|
|
8
|
+
|
|
9
|
+
const code = (error: unknown) => (error as NodeJS.ErrnoException).code;
|
|
10
|
+
async function remove(path: string): Promise<void> { try { await unlink(path); } catch (error) { if (code(error) !== 'ENOENT') throw error; } }
|
|
11
|
+
function live(pid: number): boolean {
|
|
12
|
+
try { process.kill(pid, 0); return true; } catch (error) { if (code(error) === 'ESRCH') return false; if (code(error) === 'EPERM') return true; throw error; }
|
|
13
|
+
}
|
|
14
|
+
async function lock(path: string, prefix: string, signal?: AbortSignal): Promise<string> {
|
|
15
|
+
await mkdir(dirname(path), { recursive: true });
|
|
16
|
+
const token = `${process.pid}:${randomUUID()}`;
|
|
17
|
+
for (let poll = 0; poll < 100; poll++) {
|
|
18
|
+
signal?.throwIfAborted();
|
|
19
|
+
try { await writeFile(path, token, { flag: 'wx', mode: 0o600 }); return token; }
|
|
20
|
+
catch (error) {
|
|
21
|
+
// Windows exposes a delete-pending lock name as EPERM until the last reader closes.
|
|
22
|
+
if (process.platform === 'win32' && code(error) === 'EPERM') { await sleep(50, undefined, { signal }); continue; }
|
|
23
|
+
if (code(error) !== 'EEXIST') throw error;
|
|
24
|
+
}
|
|
25
|
+
let owner: string;
|
|
26
|
+
try { owner = await readFile(path, 'utf8'); }
|
|
27
|
+
catch (error) {
|
|
28
|
+
if (code(error) === 'ENOENT') continue;
|
|
29
|
+
if (process.platform === 'win32' && code(error) === 'EPERM') { await sleep(50, undefined, { signal }); continue; }
|
|
30
|
+
throw error;
|
|
31
|
+
}
|
|
32
|
+
const pid = Number.parseInt(owner, 10);
|
|
33
|
+
// Creation precedes token writing; tolerate the brief empty-file window before reclaiming.
|
|
34
|
+
if (pid > 0 ? !live(pid) : poll >= 2) {
|
|
35
|
+
try { if (await readFile(path, 'utf8') === owner) await remove(path); }
|
|
36
|
+
catch (error) { if (code(error) !== 'ENOENT') throw error; }
|
|
37
|
+
} else await sleep(50, undefined, { signal });
|
|
38
|
+
}
|
|
39
|
+
throw new ToolError(`${prefix}_LOCK_TIMEOUT`, `File is locked: ${path}. Wait for the writer to finish, then retry.`);
|
|
40
|
+
}
|
|
41
|
+
async function unlock(path: string, token: string): Promise<void> {
|
|
42
|
+
// A reclaimed lock may belong to a successor; release only our exact pid:uuid token.
|
|
43
|
+
try { if (await readFile(path, 'utf8') === token) await unlink(path); }
|
|
44
|
+
catch (error) { if (code(error) !== 'ENOENT') throw error; }
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export class JsonStore<Data> {
|
|
48
|
+
protected data: Data;
|
|
49
|
+
private queue = Promise.resolve();
|
|
50
|
+
private listeners = new Set<() => void>();
|
|
51
|
+
private observers = new Map<() => void, (error: unknown) => void>();
|
|
52
|
+
private watcher?: FSWatcher;
|
|
53
|
+
private refreshTimer?: NodeJS.Timeout;
|
|
54
|
+
constructor(readonly path: string | undefined, initial: Data, private decode: (value: unknown) => Data, private prefix: string,
|
|
55
|
+
private options: { missing?: () => Data; skipUnchanged?: boolean } = {}) { this.data = initial; }
|
|
56
|
+
subscribe(listener: () => void, onExternalError?: (error: unknown) => void): () => void {
|
|
57
|
+
this.listeners.add(listener);
|
|
58
|
+
if (onExternalError) { this.observers.set(listener, onExternalError); this.observe(); }
|
|
59
|
+
return () => {
|
|
60
|
+
this.listeners.delete(listener); this.observers.delete(listener);
|
|
61
|
+
if (!this.observers.size) { this.watcher?.close(); this.watcher = undefined; clearTimeout(this.refreshTimer); this.refreshTimer = undefined; }
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
private observe(): void {
|
|
65
|
+
if (!this.path || this.watcher || !this.observers.size) return;
|
|
66
|
+
const target = dirname(this.path);
|
|
67
|
+
let directory = target;
|
|
68
|
+
for (;;) {
|
|
69
|
+
try {
|
|
70
|
+
// Observe the directory because commits replace the inode. Before its first
|
|
71
|
+
// creation, an existing ancestor detects new directories without polling.
|
|
72
|
+
this.watcher = watch(directory, { persistent: false }, (_event, name) => {
|
|
73
|
+
if (directory !== target) { this.watcher?.close(); this.watcher = undefined; this.observe(); }
|
|
74
|
+
else if (name && String(name) !== basename(this.path!)) return;
|
|
75
|
+
if (!this.observers.size) return;
|
|
76
|
+
clearTimeout(this.refreshTimer);
|
|
77
|
+
this.refreshTimer = setTimeout(() => {
|
|
78
|
+
this.refreshTimer = undefined;
|
|
79
|
+
void this.snapshot().catch(error => { for (const report of this.observers.values()) report(error); });
|
|
80
|
+
}, 25);
|
|
81
|
+
this.refreshTimer.unref();
|
|
82
|
+
});
|
|
83
|
+
this.watcher.on('error', error => { for (const report of this.observers.values()) report(error); });
|
|
84
|
+
return;
|
|
85
|
+
} catch (error) {
|
|
86
|
+
if (code(error) === 'ENOENT' && dirname(directory) !== directory) { directory = dirname(directory); continue; }
|
|
87
|
+
for (const report of this.observers.values()) report(error);
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
get current(): Data { return this.data; }
|
|
93
|
+
private async load(): Promise<Data> {
|
|
94
|
+
if (!this.path) return this.data;
|
|
95
|
+
let text: string;
|
|
96
|
+
try { text = await readFile(this.path, 'utf8'); } catch (error) { if (code(error) === 'ENOENT') return this.options.missing ? this.options.missing() : this.data; throw error; }
|
|
97
|
+
try {
|
|
98
|
+
const value: unknown = JSON.parse(text);
|
|
99
|
+
return this.decode(value);
|
|
100
|
+
} catch (error) { throw new ToolError(`${this.prefix}_STORE_INVALID`, `Invalid data in ${this.path}: ${String(error)}; current state is retained. Repair the file before retrying.`); }
|
|
101
|
+
}
|
|
102
|
+
private serial<T>(run: () => Promise<T>): Promise<T> {
|
|
103
|
+
const work = this.queue.then(run);
|
|
104
|
+
// Release this serialization slot after failures too; the caller still receives rejection.
|
|
105
|
+
this.queue = work.then(() => {}, () => {}); return work;
|
|
106
|
+
}
|
|
107
|
+
snapshot(): Promise<Data> {
|
|
108
|
+
return this.serial(async () => {
|
|
109
|
+
// Windows cannot atomically replace a file while another process still holds its read handle.
|
|
110
|
+
// Snapshot shares the cross-process lock so the old target closes before rename.
|
|
111
|
+
const lockPath = process.platform === 'win32' && this.path ? `${this.path}.lock` : undefined;
|
|
112
|
+
// A missing snapshot linearizes before the first commit; do not create its directory/lock
|
|
113
|
+
// or open a target that could appear concurrently without participating in the lock.
|
|
114
|
+
if (lockPath) {
|
|
115
|
+
try { await access(this.path!); }
|
|
116
|
+
catch (error) { if (code(error) === 'ENOENT') {
|
|
117
|
+
const data = this.options.missing ? this.options.missing() : this.data;
|
|
118
|
+
const changed = JSON.stringify(data) !== JSON.stringify(this.data);
|
|
119
|
+
this.data = data;
|
|
120
|
+
if (changed) for (const listener of this.listeners) listener();
|
|
121
|
+
return structuredClone(this.data);
|
|
122
|
+
} throw error; }
|
|
123
|
+
}
|
|
124
|
+
const token = lockPath ? await lock(lockPath, this.prefix) : undefined;
|
|
125
|
+
try {
|
|
126
|
+
const data = await this.load(), changed = JSON.stringify(data) !== JSON.stringify(this.data);
|
|
127
|
+
this.data = data;
|
|
128
|
+
if (changed) for (const listener of this.listeners) listener();
|
|
129
|
+
return structuredClone(this.data);
|
|
130
|
+
}
|
|
131
|
+
finally { if (lockPath && token) await unlock(lockPath, token); }
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
protected mutate<T>(apply: (data: Data) => T, signal?: AbortSignal): Promise<T> {
|
|
135
|
+
return this.serial(async () => {
|
|
136
|
+
const token = this.path ? await lock(`${this.path}.lock`, this.prefix, signal) : undefined;
|
|
137
|
+
try {
|
|
138
|
+
const loaded = await this.load(), data = structuredClone(loaded);
|
|
139
|
+
signal?.throwIfAborted();
|
|
140
|
+
const result = apply(data);
|
|
141
|
+
const changed = JSON.stringify(data) !== JSON.stringify(loaded);
|
|
142
|
+
if (this.path && (!this.options.skipUnchanged || changed)) {
|
|
143
|
+
const tmp = `${this.path}.${token!.split(':')[1]}.tmp`;
|
|
144
|
+
try {
|
|
145
|
+
await writeFile(tmp, JSON.stringify(data, null, 2), { mode: 0o600 });
|
|
146
|
+
signal?.throwIfAborted(); await rename(tmp, this.path);
|
|
147
|
+
} finally { await remove(tmp); }
|
|
148
|
+
}
|
|
149
|
+
const cacheChanged = JSON.stringify(data) !== JSON.stringify(this.data);
|
|
150
|
+
this.data = data;
|
|
151
|
+
if (!this.options.skipUnchanged || cacheChanged) for (const listener of this.listeners) listener();
|
|
152
|
+
return result;
|
|
153
|
+
} finally { if (this.path && token) await unlock(`${this.path}.lock`, token); }
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { MessageRenderer } from '@earendil-works/pi-coding-agent';
|
|
2
|
+
import { Box, Container, Text } from '@earendil-works/pi-tui';
|
|
3
|
+
import { stateLine, toolLine, type ToolLine } from '../ui/tool-render.ts';
|
|
4
|
+
import type { NotificationDetails } from './notifications.ts';
|
|
5
|
+
import { sanitizeText } from './text.ts';
|
|
6
|
+
|
|
7
|
+
export const notificationRenderer: MessageRenderer<NotificationDetails> = (message, { expanded, outputPad }, theme) => {
|
|
8
|
+
const { details, content } = message;
|
|
9
|
+
// Quiet job notices retain their original string content; queued notices use text blocks.
|
|
10
|
+
const blocks = typeof content === 'string' ? [{ type: 'text' as const, text: content }] : content;
|
|
11
|
+
if (details?.notificationVersion !== 1 || details.segments?.length !== blocks.length) return;
|
|
12
|
+
const visible = blocks.flatMap((block, index) => {
|
|
13
|
+
const segment = details.segments[index];
|
|
14
|
+
return segment.source === 'goal-continuation' ? [] : [{ block, view: segment.view }];
|
|
15
|
+
});
|
|
16
|
+
// Only presentation is filtered. Leave image events to Pi instead of dropping their images here.
|
|
17
|
+
if (visible.some(({ block }) => block.type !== 'text')) return;
|
|
18
|
+
if (!visible.length) return new Container();
|
|
19
|
+
if (!visible.some(({ view }) => view)) {
|
|
20
|
+
return new Text(sanitizeText(visible.map(({ block }) => block.type === 'text' ? block.text : '').join('\n')), outputPad, 0);
|
|
21
|
+
}
|
|
22
|
+
const body = new Box(outputPad, 0);
|
|
23
|
+
for (const { block, view } of visible) {
|
|
24
|
+
if (!view) {
|
|
25
|
+
if (block.type === 'text') body.addChild(new Text(sanitizeText(block.text), 0, 0));
|
|
26
|
+
continue;
|
|
27
|
+
}
|
|
28
|
+
const line: ToolLine = { icon: '', title: view.title, meta: [
|
|
29
|
+
...view.state ? [{ text: view.state, tone: stateLine(view.state).tone ?? 'accent' }] : [], ...view.meta ?? [],
|
|
30
|
+
] };
|
|
31
|
+
body.addChild({ render: width => [toolLine(theme, line, width)], invalidate() {} });
|
|
32
|
+
if (expanded && view.body) body.addChild(new Text(sanitizeText(view.body), 0, 0));
|
|
33
|
+
}
|
|
34
|
+
return body;
|
|
35
|
+
};
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import type { AgentBeforeSettleEvent, BoundaryResult, ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import type { TextContent } from "@earendil-works/pi-ai";
|
|
3
|
+
import type { SessionBinding } from "./binding.ts";
|
|
4
|
+
|
|
5
|
+
// Jobs, agents, workflows and Goal share this delivery path; UI readers never send follow-ups.
|
|
6
|
+
type Source = "event" | "goal-continuation" | "reminder";
|
|
7
|
+
/** Display only; content remains the model-facing notification protocol. */
|
|
8
|
+
export type NotificationView = { title: string; state?: string; meta?: string[]; body?: string };
|
|
9
|
+
type Pending = { text: string; source: Source; delivered?: () => void; view?: NotificationView };
|
|
10
|
+
type Segment = { requestId: string; source: Source; view?: NotificationView };
|
|
11
|
+
export type NotificationDetails = { notificationVersion: 1; segments: Segment[] };
|
|
12
|
+
// Direct child questions can wake a parent even when ordinary results must wait.
|
|
13
|
+
export const isQuestion = (requestId: string): boolean => requestId.startsWith("agent:") && requestId.endsWith(":ask");
|
|
14
|
+
export class Notifications {
|
|
15
|
+
private pending = new Map<string, Map<string, Pending>>();
|
|
16
|
+
private blockers = new Set<symbol>();
|
|
17
|
+
private admission: (requestIds: string[]) => boolean = () => true;
|
|
18
|
+
private idleTimer?: NodeJS.Timeout;
|
|
19
|
+
constructor(private pi: ExtensionAPI, private binding: SessionBinding) {}
|
|
20
|
+
// Goal checks request IDs so a queued child question can be distinguished from a result.
|
|
21
|
+
setAdmission(admission: (requestIds: string[]) => boolean): void { this.admission = admission; }
|
|
22
|
+
private admitted(sessionId: string): boolean {
|
|
23
|
+
const messages = this.pending.get(sessionId);
|
|
24
|
+
return Boolean(messages?.size) && this.admission([...messages!.keys()]);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
cancel(sessionId: string, id: string): void { this.pending.get(sessionId)?.delete(id); }
|
|
28
|
+
has(sessionId: string, id: string): boolean { return this.pending.get(sessionId)?.has(id) ?? false; }
|
|
29
|
+
detach(): void { clearTimeout(this.idleTimer); this.idleTimer = undefined; }
|
|
30
|
+
|
|
31
|
+
hold(): () => void {
|
|
32
|
+
const token = Symbol();
|
|
33
|
+
this.blockers.add(token);
|
|
34
|
+
return () => { this.blockers.delete(token); this.flush(); };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** delivered runs once the message has left the queue; a later enqueue under the same ID replaces it. */
|
|
38
|
+
enqueue(sessionId: string, id: string, text: string, delivered?: () => void, source: Source = "event", view?: NotificationView): void {
|
|
39
|
+
let messages = this.pending.get(sessionId);
|
|
40
|
+
if (!messages) this.pending.set(sessionId, messages = new Map());
|
|
41
|
+
messages.set(id, { text, delivered, source, view });
|
|
42
|
+
this.flush();
|
|
43
|
+
}
|
|
44
|
+
private take(sessionId: string): { content: TextContent[]; details: NotificationDetails } {
|
|
45
|
+
const messages = this.pending.get(sessionId)!;
|
|
46
|
+
this.pending.delete(sessionId);
|
|
47
|
+
for (const message of messages.values()) message.delivered?.();
|
|
48
|
+
// Details align with the model-facing content blocks; display never changes delivery.
|
|
49
|
+
const events = [...messages].filter(([, message]) => message.source !== 'goal-continuation');
|
|
50
|
+
// A real result/question already supplies the wake text. Goal still receives its
|
|
51
|
+
// exactly-once delivery callback, without a redundant independent control block.
|
|
52
|
+
const visible = events.length ? events : [...messages];
|
|
53
|
+
const segments = visible.map(([requestId, { source, view }]) => ({ requestId, source, ...(view && { view }) }));
|
|
54
|
+
return { content: visible.map(([, message]) => ({ type: "text", text: message.text })), details: { notificationVersion: 1, segments } };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// Turn-end reminders are appended to history without scheduling a turn.
|
|
58
|
+
reminder(requestId: string, text: string) {
|
|
59
|
+
return { type: 'custom_message' as const, customType: 'pi-suite:notification', display: false,
|
|
60
|
+
content: [{ type: 'text' as const, text }],
|
|
61
|
+
details: { notificationVersion: 1, segments: [{ requestId, source: 'reminder' }] } satisfies NotificationDetails };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
beforeSettle(event: AgentBeforeSettleEvent): BoundaryResult | undefined {
|
|
65
|
+
const active = this.binding.current;
|
|
66
|
+
if (!active || this.blockers.size || event.outcome !== "completed") return;
|
|
67
|
+
// Existing host/extension work already has a runnable continuation. Leave our batch for
|
|
68
|
+
// the next boundary instead of adding another request or changing its ordering.
|
|
69
|
+
if (event.continue || event.context.pendingMessages.length) return;
|
|
70
|
+
if (!this.admitted(active.sessionId)) return;
|
|
71
|
+
return { continue: true, entries: [...event.entries, { type: "custom_message", customType: "pi-suite:notification",
|
|
72
|
+
...this.take(active.sessionId), display: false }] };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
afterHostOperation(): void {
|
|
76
|
+
this.detach();
|
|
77
|
+
const captured = this.binding.current;
|
|
78
|
+
if (!captured || !this.pending.get(captured.sessionId)?.size) return;
|
|
79
|
+
// Pi 1.5.0 emits session_compact/session_tree before clearing their busy flags,
|
|
80
|
+
// without public extension end callbacks. Only these operations need an idle check.
|
|
81
|
+
const check = () => {
|
|
82
|
+
if (!this.binding.isCurrent(captured)) return;
|
|
83
|
+
if (captured.ctx.isIdle()) { this.idleTimer = undefined; this.flush(); }
|
|
84
|
+
else this.idleTimer = setTimeout(check, 25);
|
|
85
|
+
};
|
|
86
|
+
this.idleTimer = setTimeout(check, 0);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
flush(): void {
|
|
90
|
+
const active = this.binding.current;
|
|
91
|
+
if (!active || this.blockers.size || !active.ctx.isIdle() || active.ctx.hasPendingMessages()) return;
|
|
92
|
+
if (!this.admitted(active.sessionId)) return;
|
|
93
|
+
const message = this.take(active.sessionId);
|
|
94
|
+
this.pi.sendMessage({ customType: "pi-suite:notification", ...message,
|
|
95
|
+
display: message.details.segments.some(segment => segment.source !== "goal-continuation") },
|
|
96
|
+
{ triggerTurn: true, deliverAs: "followUp" });
|
|
97
|
+
}
|
|
98
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Process-wide execution owners (agents, workflows) survive /reload so running children keep
|
|
3
|
+
* their sessions. An owner also keeps the closures of the module load that created it, so a
|
|
4
|
+
* reload must not silently reuse it: new code would drive old internals (for example an old
|
|
5
|
+
* config schema rejecting fields the current release writes). Each module load gets its own
|
|
6
|
+
* implementation identity; an idle owner from another load is retired and replaced, a busy one
|
|
7
|
+
* stays observable but is marked stale so callers refuse new executions until it is idle.
|
|
8
|
+
*/
|
|
9
|
+
export interface ExecutionOwner { readonly closed: boolean; busy(): boolean; shutdown(): Promise<void> }
|
|
10
|
+
type ExistingOwner = Pick<ExecutionOwner, 'closed' | 'shutdown'> & Partial<Pick<ExecutionOwner, 'busy'>>;
|
|
11
|
+
type Slot<T> = { implementation?: symbol; owner: T };
|
|
12
|
+
export type OwnerHandle<T> = { owner: T; stale?: string };
|
|
13
|
+
|
|
14
|
+
// One identity per evaluation of this module; Pi re-evaluates extension modules on /reload.
|
|
15
|
+
const implementation = Symbol('pi-suite execution implementation');
|
|
16
|
+
const globals = globalThis as unknown as Record<symbol, Map<string, unknown> | undefined>;
|
|
17
|
+
|
|
18
|
+
/** Owners written before this slot format carry no identity and cannot prove they are idle. */
|
|
19
|
+
function slotOf(value: unknown): Slot<ExistingOwner> {
|
|
20
|
+
return value && typeof value === 'object' && 'implementation' in value && 'owner' in value
|
|
21
|
+
? value as Slot<ExistingOwner> : { owner: value as ExistingOwner };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function existingOwner(key: string, agentDir: string): ExistingOwner | undefined {
|
|
25
|
+
const value = globals[Symbol.for(key)]?.get(agentDir);
|
|
26
|
+
return value === undefined ? undefined : slotOf(value).owner;
|
|
27
|
+
}
|
|
28
|
+
export function ownerBusy(key: string, agentDir: string): boolean {
|
|
29
|
+
const owner = existingOwner(key, agentDir);
|
|
30
|
+
return !!owner && !owner.closed && (owner.busy?.() ?? true);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Busy also counts dependants: retiring an agents owner would close it under a running workflow. */
|
|
34
|
+
export function acquireOwner<T extends ExecutionOwner>(key: string, label: string, agentDir: string, create: () => T,
|
|
35
|
+
options: { dependants?: () => boolean; matches?: (owner: T) => boolean } = {}): OwnerHandle<T> {
|
|
36
|
+
const owners = globals[Symbol.for(key)] ??= new Map();
|
|
37
|
+
const existing = owners.get(agentDir);
|
|
38
|
+
if (existing !== undefined) {
|
|
39
|
+
const slot = slotOf(existing);
|
|
40
|
+
if (!slot.owner.closed) {
|
|
41
|
+
const owner = slot.owner as T;
|
|
42
|
+
if (slot.implementation === implementation && (options.matches?.(owner) ?? true)) return { owner };
|
|
43
|
+
if (!slot.implementation || !slot.owner.busy) return { owner,
|
|
44
|
+
stale: `The ${label} runtime from an earlier pi-suite load cannot report when it is idle. Restart Pi.` };
|
|
45
|
+
if (slot.owner.busy() || options.dependants?.()) return { owner,
|
|
46
|
+
stale: `The ${label} runtime from an earlier pi-suite load still has running work, so new runs are disabled. Let it finish or stop it, then /reload.` };
|
|
47
|
+
// Idle: nothing runs under the old closures, so closing it loses no execution.
|
|
48
|
+
void slot.owner.shutdown().catch(error => process.emitWarning(`pi-suite ${label} runtime retirement failed: ${String(error)}`));
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
const owner = create();
|
|
52
|
+
owners.set(agentDir, { implementation, owner } satisfies Slot<T>);
|
|
53
|
+
return { owner };
|
|
54
|
+
}
|