@loka1/pi-orchestra 0.0.0-stage → 0.6.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.
@@ -0,0 +1,99 @@
1
+ /**
2
+ * The small bit of git the coordinator needs: which commit a dispatch started
3
+ * from, and what changed since. Everything degrades to a message when the
4
+ * working directory is not a repository.
5
+ */
6
+
7
+ import { execFileSync } from "node:child_process";
8
+
9
+ export interface DiffSummary {
10
+ /** Short stat lines plus the file count. */
11
+ stat: string;
12
+ /** Full patch, possibly clipped. */
13
+ diff: string;
14
+ /** Changed files, parsed from --numstat, plus untracked ones. */
15
+ files: string[];
16
+ /** Files git does not track yet (they are not in the patch). */
17
+ untracked: string[];
18
+ base: string;
19
+ head: string;
20
+ clipNote?: string;
21
+ }
22
+
23
+ function git(cwd: string, args: string[]): string | undefined {
24
+ try {
25
+ return execFileSync("git", args, {
26
+ cwd,
27
+ encoding: "utf8",
28
+ stdio: ["ignore", "pipe", "ignore"],
29
+ maxBuffer: 8 * 1024 * 1024,
30
+ }).trim();
31
+ } catch {
32
+ return undefined;
33
+ }
34
+ }
35
+
36
+ /** Current HEAD, or undefined outside a git repository. */
37
+ export function gitHead(cwd: string): string | undefined {
38
+ return git(cwd, ["rev-parse", "HEAD"]);
39
+ }
40
+
41
+ /** True when `base` is still a commit in this repository. */
42
+ export function isCommit(cwd: string, base: string | undefined): boolean {
43
+ if (!base) return false;
44
+ return git(cwd, ["cat-file", "-e", `${base}^{commit}`]) !== undefined;
45
+ }
46
+
47
+ /**
48
+ * Diff from `base` to the working tree (tracked files only), clipped to
49
+ * `maxLines`. Returns undefined when git or the base commit is unavailable.
50
+ */
51
+ export function gitDiff(cwd: string, base: string | undefined, options: { maxLines?: number } = {}): DiffSummary | undefined {
52
+ if (!base || !isCommit(cwd, base)) return undefined;
53
+ const head = gitHead(cwd);
54
+ const stat = git(cwd, ["diff", "--stat", base]) ?? "";
55
+ const patch = git(cwd, ["diff", base]) ?? "";
56
+ const numstat = git(cwd, ["diff", "--numstat", base]) ?? "";
57
+ const files = numstat
58
+ .split("\n")
59
+ .map((line) => line.split("\t")[2])
60
+ .filter((name): name is string => Boolean(name));
61
+ const untracked = (git(cwd, ["ls-files", "--others", "--exclude-standard"]) ?? "")
62
+ .split("\n")
63
+ .filter(Boolean);
64
+ const maxLines = options.maxLines ?? 600;
65
+ const lines = patch.split("\n");
66
+ const clipped = lines.slice(0, maxLines);
67
+ return {
68
+ base,
69
+ head: head ?? "",
70
+ stat,
71
+ diff: clipped.join("\n"),
72
+ files: [...files, ...untracked],
73
+ untracked,
74
+ clipNote: lines.length > maxLines ? `… ${lines.length - maxLines} more diff lines (raise maxLines or use git diff)` : undefined,
75
+ };
76
+ }
77
+
78
+ /** Compact change summary: tracked stats plus a list of untracked files. */
79
+ export function statText(summary: DiffSummary | undefined): string {
80
+ if (!summary) return "(no diff available)";
81
+ const parts: string[] = [];
82
+ if (summary.stat) parts.push(summary.stat);
83
+ if (summary.untracked.length > 0) parts.push(`untracked: ${summary.untracked.join(", ")}`);
84
+ return parts.join("\n") || "(no changes)";
85
+ }
86
+
87
+ /** Text form for the tool and the browser pager. */
88
+ export function diffReport(summary: DiffSummary | undefined, header: string): string {
89
+ if (!summary) return `${header}\n(no diff available: not a git repository, or the recorded base commit is gone)`;
90
+ const lines = [header, `base ${summary.base.slice(0, 12)}${summary.head ? ` → working tree (HEAD ${summary.head.slice(0, 12)})` : ""}`];
91
+ if (summary.files.length === 0) {
92
+ lines.push("", "No changed files.");
93
+ return lines.join("\n");
94
+ }
95
+ lines.push("", statText(summary));
96
+ lines.push("", summary.diff || "(no tracked changes to show; untracked files are listed above)");
97
+ if (summary.clipNote) lines.push(summary.clipNote);
98
+ return lines.join("\n");
99
+ }
@@ -0,0 +1,233 @@
1
+ /**
2
+ * Worker log reading.
3
+ *
4
+ * Workers stream their JSONL events into `.pi/orchestra/logs/<dispatch>.jsonl`.
5
+ * These helpers turn that stream into a compact, human-readable transcript.
6
+ */
7
+
8
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
9
+ import { join } from "node:path";
10
+
11
+ import { redact } from "./redact.ts";
12
+
13
+ export interface LogEntry {
14
+ kind: "text" | "tool" | "result" | "error" | "start" | "settle";
15
+ text: string;
16
+ }
17
+
18
+ function blockText(content: unknown): string {
19
+ if (typeof content === "string") return content;
20
+ if (!Array.isArray(content)) return "";
21
+ const parts: string[] = [];
22
+ for (const block of content) {
23
+ if (!block || typeof block !== "object") continue;
24
+ const typed = block as { type?: string; text?: string };
25
+ if (typed.type === "text" && typeof typed.text === "string") parts.push(typed.text);
26
+ }
27
+ return parts.join("\n").trim();
28
+ }
29
+
30
+ export function renderLogLine(line: string): LogEntry | undefined {
31
+ let record: Record<string, unknown>;
32
+ try {
33
+ record = JSON.parse(line) as Record<string, unknown>;
34
+ } catch {
35
+ return undefined;
36
+ }
37
+
38
+ switch (record.type) {
39
+ case "agent_start":
40
+ return { kind: "start", text: "started" };
41
+ case "agent_settled":
42
+ return { kind: "settle", text: record.aborted === true ? "settled (aborted)" : "settled" };
43
+ case "tool_execution_start": {
44
+ const args = record.args as Record<string, unknown> | undefined;
45
+ return { kind: "tool", text: `${String(record.toolName ?? "tool")}${toolArgsSummary(args)}` };
46
+ }
47
+ case "tool_execution_end": {
48
+ const isError = record.isError === true;
49
+ const text = blockText((record.result as { content?: unknown } | undefined)?.content);
50
+ const firstLine = text.split("\n")[0] ?? "";
51
+ return {
52
+ kind: isError ? "error" : "result",
53
+ text: firstLine.length > 160 ? `${firstLine.slice(0, 160)}…` : firstLine,
54
+ };
55
+ }
56
+ case "message_end": {
57
+ const message = record.message as { role?: string; content?: unknown } | undefined;
58
+ if (!message) return undefined;
59
+ if (message.role === "assistant") {
60
+ const text = blockText(message.content);
61
+ if (text) return { kind: "text", text };
62
+ }
63
+ if (message.role === "toolResult") {
64
+ const text = blockText(message.content);
65
+ const firstLine = text.split("\n")[0] ?? "";
66
+ return {
67
+ kind: message.isError ? "error" : "result",
68
+ text: firstLine.length > 160 ? `${firstLine.slice(0, 160)}…` : firstLine,
69
+ };
70
+ }
71
+ return undefined;
72
+ }
73
+ case "turn_end":
74
+ return undefined;
75
+ default:
76
+ return undefined;
77
+ }
78
+ }
79
+
80
+ /** One-line hint about a tool call's most interesting argument. */
81
+ export function toolArgsSummary(args: Record<string, unknown> | undefined): string {
82
+ if (!args) return "";
83
+ const interesting = ["command", "path", "file_path", "pattern", "query", "url", "message"];
84
+ for (const key of interesting) {
85
+ const value = args[key];
86
+ if (typeof value === "string" && value.trim()) {
87
+ const flat = value.replace(/\s+/g, " ").trim();
88
+ return ` ${flat.length > 100 ? `${flat.slice(0, 100)}…` : flat}`;
89
+ }
90
+ }
91
+ return "";
92
+ }
93
+
94
+ /** Parse a whole log file into at most `maxEntries` compact entries (tail). */
95
+ /** Raw events from a worker log, newest `limit` only. */
96
+ export function readRecords(logPath: string, limit = 2000): Array<Record<string, unknown>> {
97
+ if (!existsSync(logPath)) return [];
98
+ let raw: string;
99
+ try {
100
+ raw = readFileSync(logPath, "utf8");
101
+ } catch {
102
+ return [];
103
+ }
104
+ const lines = raw.split("\n").filter((line) => line.trim());
105
+ const recent = limit > 0 ? lines.slice(-limit) : lines;
106
+ const records: Array<Record<string, unknown>> = [];
107
+ for (const line of recent) {
108
+ try {
109
+ const record = JSON.parse(line) as Record<string, unknown>;
110
+ if (record && typeof record === "object") records.push(record);
111
+ } catch {
112
+ // a partially written line at the tail is expected while a worker runs
113
+ }
114
+ }
115
+ return records;
116
+ }
117
+
118
+ export function readTranscript(logPath: string, maxEntries = 40): LogEntry[] {
119
+ if (!existsSync(logPath)) return [];
120
+ let raw: string;
121
+ try {
122
+ raw = readFileSync(logPath, "utf8");
123
+ } catch {
124
+ return [];
125
+ }
126
+ const lines = raw.split("\n");
127
+ const entries: LogEntry[] = [];
128
+ for (const line of lines) {
129
+ if (!line.trim()) continue;
130
+ const entry = renderLogLine(line);
131
+ if (!entry) continue;
132
+ if (entry.kind === "text" && entries.length > 0) {
133
+ const last = entries[entries.length - 1];
134
+ // Collapse a repeated identical text block (streamed then finalized).
135
+ if (last?.kind === "text" && last.text === entry.text) continue;
136
+ }
137
+ entries.push(entry);
138
+ }
139
+ return entries.slice(-maxEntries);
140
+ }
141
+
142
+ export function transcriptText(entries: LogEntry[]): string {
143
+ return redact(entries
144
+ .map((entry) => {
145
+ switch (entry.kind) {
146
+ case "tool":
147
+ return `→ ${entry.text}`;
148
+ case "result":
149
+ return ` ${entry.text}`;
150
+ case "error":
151
+ return ` ✗ ${entry.text}`;
152
+ case "start":
153
+ return "▶ started";
154
+ case "settle":
155
+ return `■ ${entry.text}`;
156
+ default:
157
+ return entry.text;
158
+ }
159
+ })
160
+ .join("\n"));
161
+ }
162
+
163
+
164
+ // ---------------------------------------------------------------------------
165
+ // search across transcripts
166
+ // ---------------------------------------------------------------------------
167
+
168
+ export interface SearchHit {
169
+ dispatchId: string;
170
+ /** 1-based line number in the JSONL file, so a hit can be traced back. */
171
+ line: number;
172
+ kind: LogEntry["kind"];
173
+ text: string;
174
+ }
175
+
176
+ function matches(tokens: string[], text: string): boolean {
177
+ const haystack = text.toLowerCase();
178
+ return tokens.every((token) => haystack.includes(token));
179
+ }
180
+
181
+ /** Every rendered entry of one log that matches all tokens. */
182
+ export function searchTranscript(logPath: string, query: string, limit = 20): SearchHit[] {
183
+ const tokens = query.trim().toLowerCase().split(/\s+/).filter(Boolean);
184
+ if (tokens.length === 0 || limit <= 0) return [];
185
+ let raw: string;
186
+ try {
187
+ raw = readFileSync(logPath, "utf8");
188
+ } catch {
189
+ return [];
190
+ }
191
+ const dispatchId = logPath.split("/").pop()?.replace(/\.jsonl$/, "") ?? logPath;
192
+ const hits: SearchHit[] = [];
193
+ const lines = raw.split("\n");
194
+ for (let index = 0; index < lines.length; index += 1) {
195
+ const line = lines[index];
196
+ if (!line?.trim()) continue;
197
+ const entry = renderLogLine(line);
198
+ if (!entry) continue;
199
+ const text = redact(entry.text);
200
+ if (!matches(tokens, text)) continue;
201
+ hits.push({ dispatchId, line: index + 1, kind: entry.kind, text });
202
+ if (hits.length >= limit) break;
203
+ }
204
+ return hits;
205
+ }
206
+
207
+ /** Search every log in a store, newest dispatch files first. */
208
+ export function searchLogs(
209
+ logsDir: string,
210
+ query: string,
211
+ options: { limit?: number; dispatches?: string[] } = {},
212
+ ): SearchHit[] {
213
+ if (!existsSync(logsDir)) return [];
214
+ const limit = options.limit ?? 40;
215
+ if (limit <= 0) return [];
216
+ const wanted = options.dispatches ? new Set(options.dispatches) : undefined;
217
+ let files: string[];
218
+ try {
219
+ files = readdirSync(logsDir).filter((file) => file.endsWith(".jsonl"));
220
+ } catch {
221
+ return [];
222
+ }
223
+ files.sort();
224
+ const hits: SearchHit[] = [];
225
+ for (const file of files) {
226
+ const dispatchId = file.replace(/\.jsonl$/, "");
227
+ if (wanted && !wanted.has(dispatchId)) continue;
228
+ const found = searchTranscript(join(logsDir, file), query, limit - hits.length);
229
+ hits.push(...found);
230
+ if (hits.length >= limit) break;
231
+ }
232
+ return hits;
233
+ }
@@ -0,0 +1,115 @@
1
+ /**
2
+ * File-based mail between a worker and its coordinator.
3
+ *
4
+ * A worker calls the `orchestra_ask` tool, which writes `mail/<dispatch>/q-<id>.json`
5
+ * and waits for `mail/<dispatch>/q-<id>.answer.json`. The coordinator polls the
6
+ * mail directory, surfaces pending questions to the model/user, and answers with
7
+ * the `orchestra_answer` tool (or `orchestra` action `answer`).
8
+ *
9
+ * Files are the transport on purpose: both sides are separate processes and
10
+ * neither needs a network port or a shared runtime.
11
+ */
12
+
13
+ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
14
+ import { join } from "node:path";
15
+ import { randomUUID } from "node:crypto";
16
+ import { nowIso } from "./state.ts";
17
+
18
+ export interface Question {
19
+ id: string;
20
+ dispatchId: string;
21
+ question: string;
22
+ options?: string[];
23
+ createdAt: string;
24
+ }
25
+
26
+ export function mailDir(root: string, dispatchId: string): string {
27
+ return join(root, "mail", dispatchId);
28
+ }
29
+
30
+ function ensureMailDir(root: string, dispatchId: string): string {
31
+ const dir = mailDir(root, dispatchId);
32
+ mkdirSync(dir, { recursive: true });
33
+ return dir;
34
+ }
35
+
36
+ export function postQuestion(
37
+ root: string,
38
+ dispatchId: string,
39
+ question: string,
40
+ options?: string[],
41
+ ): Question {
42
+ const dir = ensureMailDir(root, dispatchId);
43
+ const entry: Question = {
44
+ id: `q_${randomUUID().replace(/-/g, "").slice(0, 8)}`,
45
+ dispatchId,
46
+ question,
47
+ options,
48
+ createdAt: nowIso(),
49
+ };
50
+ writeFileSync(join(dir, `${entry.id}.json`), JSON.stringify(entry), "utf8");
51
+ return entry;
52
+ }
53
+
54
+ export function readAnswer(root: string, dispatchId: string, questionId: string): string | undefined {
55
+ const path = join(mailDir(root, dispatchId), `${questionId}.answer.json`);
56
+ if (!existsSync(path)) return undefined;
57
+ try {
58
+ const parsed = JSON.parse(readFileSync(path, "utf8")) as { answer?: string };
59
+ return parsed.answer;
60
+ } catch {
61
+ return undefined;
62
+ }
63
+ }
64
+
65
+ export function writeAnswer(root: string, dispatchId: string, questionId: string, answer: string): void {
66
+ const dir = ensureMailDir(root, dispatchId);
67
+ writeFileSync(join(dir, `${questionId}.answer.json`), JSON.stringify({ answer, answeredAt: nowIso() }), "utf8");
68
+ }
69
+
70
+ /** Pending (unanswered) questions across every dispatch. */
71
+ export function pendingQuestions(root: string): Question[] {
72
+ const base = join(root, "mail");
73
+ if (!existsSync(base)) return [];
74
+ const questions: Question[] = [];
75
+ for (const entry of readdirSync(base, { withFileTypes: true })) {
76
+ if (!entry.isDirectory()) continue;
77
+ const dir = join(base, entry.name);
78
+ for (const file of readdirSync(dir)) {
79
+ if (!file.endsWith(".json") || file.endsWith(".answer.json")) continue;
80
+ if (existsSync(join(dir, `${file.slice(0, -5)}.answer.json`))) continue;
81
+ try {
82
+ const parsed = JSON.parse(readFileSync(join(dir, file), "utf8")) as Question;
83
+ if (parsed?.id && parsed?.question) questions.push(parsed);
84
+ } catch {
85
+ // Ignore a partially written file; the next poll picks it up.
86
+ }
87
+ }
88
+ }
89
+ return questions.sort((a, b) => a.createdAt.localeCompare(b.createdAt));
90
+ }
91
+
92
+ export interface WaitOptions {
93
+ timeoutMs: number;
94
+ signal?: AbortSignal;
95
+ pollMs?: number;
96
+ }
97
+
98
+ /** Block until the coordinator answers, the timeout fires, or the tool call is aborted. */
99
+ export async function waitForAnswer(
100
+ root: string,
101
+ dispatchId: string,
102
+ questionId: string,
103
+ options: WaitOptions,
104
+ ): Promise<{ answer: string } | { reason: "timeout" | "aborted" }> {
105
+ const deadline = Date.now() + Math.max(1000, options.timeoutMs);
106
+ const pollMs = options.pollMs ?? 400;
107
+
108
+ while (Date.now() < deadline) {
109
+ if (options.signal?.aborted) return { reason: "aborted" };
110
+ const answer = readAnswer(root, dispatchId, questionId);
111
+ if (answer !== undefined) return { answer };
112
+ await new Promise((resolve) => setTimeout(resolve, pollMs));
113
+ }
114
+ return { reason: "timeout" };
115
+ }