@nredd/pi-subagents 0.0.0-stage → 0.22.0-nredd.10

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.
Files changed (88) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1444 -2
  3. package/dist/chunks/chunk-MSGGFB5Q.ts +6755 -0
  4. package/dist/chunks/chunk-MSGGFB5Q.ts.map +7 -0
  5. package/dist/chunks/conversation-viewer-A7AMRDVY.ts +15 -0
  6. package/dist/chunks/conversation-viewer-A7AMRDVY.ts.map +7 -0
  7. package/dist/index.ts +9874 -0
  8. package/dist/index.ts.map +7 -0
  9. package/package.json +82 -4
  10. package/src/abortable.ts +43 -0
  11. package/src/agent-color.ts +161 -0
  12. package/src/agent-file-toggle.ts +298 -0
  13. package/src/agent-manager.ts +2431 -0
  14. package/src/agent-runner.ts +1703 -0
  15. package/src/agent-source-badge.ts +75 -0
  16. package/src/agent-types.ts +346 -0
  17. package/src/child-context.ts +33 -0
  18. package/src/clock.ts +25 -0
  19. package/src/completion-outbox.ts +144 -0
  20. package/src/context.ts +58 -0
  21. package/src/cross-extension-rpc.ts +200 -0
  22. package/src/custom-agents.ts +441 -0
  23. package/src/default-agents.ts +126 -0
  24. package/src/detached-results.ts +150 -0
  25. package/src/enabled-models.ts +181 -0
  26. package/src/enterprise-local.ts +67 -0
  27. package/src/env.ts +33 -0
  28. package/src/error-message.ts +11 -0
  29. package/src/git-path.ts +66 -0
  30. package/src/group-join.ts +142 -0
  31. package/src/home-paths.ts +27 -0
  32. package/src/index.ts +5047 -0
  33. package/src/invocation-config.ts +158 -0
  34. package/src/memory.ts +179 -0
  35. package/src/mention-clone.ts +200 -0
  36. package/src/mention.ts +141 -0
  37. package/src/model-call.ts +83 -0
  38. package/src/model-resolver.ts +333 -0
  39. package/src/model-scope.ts +71 -0
  40. package/src/model-selection.ts +170 -0
  41. package/src/model-tiers.ts +176 -0
  42. package/src/nested-tools.ts +512 -0
  43. package/src/notification-result.ts +118 -0
  44. package/src/output-file.ts +186 -0
  45. package/src/package-resources.ts +639 -0
  46. package/src/plan-mode-children.ts +176 -0
  47. package/src/process-budget.ts +346 -0
  48. package/src/prompts.ts +161 -0
  49. package/src/quota-admission.ts +121 -0
  50. package/src/resource-loader.ts +65 -0
  51. package/src/schedule-store.ts +153 -0
  52. package/src/schedule.ts +514 -0
  53. package/src/settings.ts +851 -0
  54. package/src/skill-loader.ts +288 -0
  55. package/src/stale-ctx.ts +16 -0
  56. package/src/startup-error.ts +29 -0
  57. package/src/status-note.ts +113 -0
  58. package/src/structured-output.ts +130 -0
  59. package/src/types.ts +487 -0
  60. package/src/ui/agent-mention.ts +219 -0
  61. package/src/ui/agent-row.ts +245 -0
  62. package/src/ui/agent-widget.ts +722 -0
  63. package/src/ui/conversation-viewer.ts +837 -0
  64. package/src/ui/fallback-flag.ts +114 -0
  65. package/src/ui/fleet-list.ts +1020 -0
  66. package/src/ui/fleet-state.ts +154 -0
  67. package/src/ui/notification-view.ts +139 -0
  68. package/src/ui/schedule-menu.ts +105 -0
  69. package/src/ui/select-item.ts +45 -0
  70. package/src/ui/viewer-keys.ts +39 -0
  71. package/src/ui/workflow-card.ts +459 -0
  72. package/src/ui/workflow-dialog.ts +1138 -0
  73. package/src/ui/workflow-menu.ts +193 -0
  74. package/src/usage.ts +167 -0
  75. package/src/workflow/collisions.ts +123 -0
  76. package/src/workflow/entry.ts +47 -0
  77. package/src/workflow/host.ts +398 -0
  78. package/src/workflow/journal.ts +176 -0
  79. package/src/workflow/json-schema.ts +129 -0
  80. package/src/workflow/meta.ts +329 -0
  81. package/src/workflow/progress.ts +554 -0
  82. package/src/workflow/runtime.ts +1249 -0
  83. package/src/workflow/saved.ts +259 -0
  84. package/src/workflow/task.ts +317 -0
  85. package/src/workflow/tool-description.ts +200 -0
  86. package/src/workflow/worker-source.ts +903 -0
  87. package/src/worktree.ts +520 -0
  88. package/src/xml.ts +13 -0
@@ -0,0 +1,186 @@
1
+ /**
2
+ * output-file.ts — Streaming JSONL output file for agent transcripts.
3
+ *
4
+ * Creates a per-agent output file that streams conversation turns as JSONL,
5
+ * matching Claude Code's task output file format.
6
+ */
7
+
8
+ import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
9
+ import { tmpdir } from "node:os";
10
+ import { join } from "node:path";
11
+ import type { AgentSession, AgentSessionEvent } from "@earendil-works/pi-coding-agent";
12
+ import { type ModelFallback, modelFallbackNote } from "./model-resolver.js";
13
+ import { type TierDisclosure, tierDisclosure, tierNote } from "./model-tiers.js";
14
+
15
+ /**
16
+ * Project/global default for writing a subagent's `.output` transcript; a custom
17
+ * agent's `output_transcript` overrides it per agent.
18
+ *
19
+ * State lives here rather than in an index.ts closure because both spawn paths
20
+ * need it — the top-level Agent tool and the nested delegation tools. Same
21
+ * reason `scopeModels` lives in model-scope.ts: a setting only one path can read
22
+ * is a setting the other path silently ignores.
23
+ */
24
+ let outputTranscriptDefault = true;
25
+
26
+ export function getOutputTranscriptDefault(): boolean { return outputTranscriptDefault; }
27
+ export function setOutputTranscriptDefault(b: boolean): void { outputTranscriptDefault = b; }
28
+
29
+ /**
30
+ * Encode a cwd path as a filesystem-safe directory name. Handles:
31
+ * - POSIX: "/home/user/project" → "home-user-project"
32
+ * - Windows: "C:\Users\foo\project" → "Users-foo-project"
33
+ * - UNC: "\\\\server\\share\\project" → "server-share-project"
34
+ */
35
+ export function encodeCwd(cwd: string): string {
36
+ return cwd
37
+ .replace(/[/\\]/g, "-") // both separators → dash
38
+ .replace(/^[A-Za-z]:-/, "") // strip Windows drive prefix ("C:-")
39
+ .replace(/^-+/, ""); // strip leading dashes (POSIX root, UNC)
40
+ }
41
+
42
+ /**
43
+ * The per-session scratch directory, created if missing.
44
+ * Mirrors Claude Code's layout: /tmp/{prefix}-{uid}/{encoded-cwd}/{sessionId}/tasks
45
+ *
46
+ * Shared with the workflow tool, which persists each invocation's script here so
47
+ * iterating on one is edit-file-then-rerun — the same convention, one directory.
48
+ */
49
+ export function sessionTaskDir(cwd: string, sessionId: string): string {
50
+ const encoded = encodeCwd(cwd);
51
+ const root = join(tmpdir(), `pi-subagents-${process.getuid?.() ?? 0}`);
52
+ mkdirSync(root, { recursive: true, mode: 0o700 });
53
+ // chmod is a no-op on Windows and throws on some Windows filesystems.
54
+ // On Unix we still want to enforce 0o700 past umask, so only swallow on Windows.
55
+ try {
56
+ chmodSync(root, 0o700);
57
+ } catch (err) {
58
+ if (process.platform !== "win32") throw err;
59
+ }
60
+ const dir = join(root, encoded, sessionId, "tasks");
61
+ mkdirSync(dir, { recursive: true });
62
+ return dir;
63
+ }
64
+
65
+ /** Create the output file path, ensuring the directory exists. */
66
+ export function createOutputFilePath(cwd: string, agentId: string, sessionId: string): string {
67
+ return join(sessionTaskDir(cwd, sessionId), `${agentId}.output`);
68
+ }
69
+
70
+ /**
71
+ * Ensure a transcript file exists without disturbing what is already in it.
72
+ *
73
+ * A resume reuses the agent's existing transcript (same deterministic path), so
74
+ * it must never call `writeInitialEntry` — that truncates, discarding turns the
75
+ * completion notification still points the user at, and any history the session
76
+ * has since compacted away is gone for good. Appending nothing creates the file
77
+ * when this is the agent's first transcript and is a no-op when it is not.
78
+ */
79
+ export function ensureOutputFile(path: string): void {
80
+ try {
81
+ appendFileSync(path, "", "utf-8");
82
+ } catch { /* ignore — streaming writes are best-effort too */ }
83
+ }
84
+
85
+ /** Append the model-fallback disclosure as a transcript line (best effort, like streaming writes). */
86
+ export function appendModelFallbackEntry(path: string, agentId: string, fallback: ModelFallback): void {
87
+ try {
88
+ // A resumed agent reuses its transcript, which may already say it.
89
+ if (existsSync(path) && readFileSync(path, "utf-8").includes('"type":"model-fallback"')) return;
90
+ appendFileSync(
91
+ path,
92
+ `${JSON.stringify({ isSidechain: true, agentId, type: "model-fallback", modelFallback: fallback, note: modelFallbackNote(fallback), timestamp: new Date().toISOString() })}\n`,
93
+ "utf-8",
94
+ );
95
+ } catch { /* ignore */ }
96
+ }
97
+
98
+ /** Append tier provenance separately from assistant messages for durable replay. */
99
+ export function appendModelTierEntry(path: string, agentId: string, modelTier: TierDisclosure): void {
100
+ try {
101
+ appendFileSync(path, `${JSON.stringify({ isSidechain: true, agentId, type: "model-tier", modelTier: tierDisclosure(modelTier), note: tierNote(modelTier), timestamp: new Date().toISOString() })}\n`, "utf-8");
102
+ } catch { /* transcript writes are best effort */ }
103
+ }
104
+
105
+ /** Write the initial user prompt entry. */
106
+ export function writeInitialEntry(path: string, agentId: string, prompt: string, cwd: string): void {
107
+ const entry = {
108
+ isSidechain: true,
109
+ agentId,
110
+ type: "user",
111
+ message: { role: "user", content: prompt },
112
+ timestamp: new Date().toISOString(),
113
+ cwd,
114
+ };
115
+ writeFileSync(path, JSON.stringify(entry) + "\n", "utf-8");
116
+ }
117
+
118
+ /**
119
+ * Subscribe to session events and flush new messages to the output file on each turn_end.
120
+ * Returns a cleanup function that does a final flush and unsubscribes.
121
+ */
122
+ export function streamToOutputFile(
123
+ session: AgentSession,
124
+ path: string,
125
+ agentId: string,
126
+ cwd: string,
127
+ startIndex?: number,
128
+ ): () => void {
129
+ // Index of the first message this stream is responsible for. A resume hands
130
+ // in the session's length as of just before the run: the session already
131
+ // holds every prior turn, and re-emitting those would duplicate history that
132
+ // is already in the file. A spawn has already written its prompt as the
133
+ // initial entry, so it starts after the first user message — found on the
134
+ // first flush, because pi puts a system message ahead of it and adds both
135
+ // only once the prompt runs.
136
+ let writtenCount = startIndex;
137
+
138
+ const flush = () => {
139
+ const messages = session.messages;
140
+ if (writtenCount === undefined) {
141
+ const prompt = messages.findIndex((m) => m.role === "user");
142
+ if (prompt === -1) return;
143
+ writtenCount = prompt + 1;
144
+ }
145
+ while (writtenCount < messages.length) {
146
+ const msg = messages[writtenCount++];
147
+ // Pi's prompt and tool-loadout records; a Claude Code transcript has no
148
+ // such entry.
149
+ if (msg.role === "system") continue;
150
+ const entry = {
151
+ isSidechain: true,
152
+ agentId,
153
+ type: msg.role === "assistant" ? "assistant" : msg.role === "user" ? "user" : "toolResult",
154
+ message: msg,
155
+ timestamp: new Date().toISOString(),
156
+ cwd,
157
+ };
158
+ try {
159
+ appendFileSync(path, JSON.stringify(entry) + "\n", "utf-8");
160
+ } catch { /* ignore write errors */ }
161
+ }
162
+ };
163
+
164
+ const unsubscribe = session.subscribe((event: AgentSessionEvent) => {
165
+ if (event.type === "turn_end") flush();
166
+ // Compaction replaces session.messages with a shorter, summarized array,
167
+ // leaving writtenCount past the new end — without re-anchoring, the flush
168
+ // loop would never match again and streaming would halt for good (#145).
169
+ // Flush before it runs so any not-yet-flushed tail still reaches the file,
170
+ // then re-anchor to the rebuilt array once it lands. The re-anchor is
171
+ // deferred a microtask because on the overflow-retry path pi trims the
172
+ // trailing error assistant message AFTER emitting compaction_end —
173
+ // anchoring synchronously would sit one past the trimmed array and skip
174
+ // the first post-compaction message. Aborted/failed compactions leave
175
+ // session.messages untouched, so only successful ones re-anchor.
176
+ if (event.type === "compaction_start") flush();
177
+ if (event.type === "compaction_end" && !event.aborted && event.result) {
178
+ queueMicrotask(() => { writtenCount = session.messages.length; });
179
+ }
180
+ });
181
+
182
+ return () => {
183
+ flush();
184
+ unsubscribe();
185
+ };
186
+ }