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.
Files changed (220) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +100 -2
  3. package/README.zh-CN.md +101 -0
  4. package/package.json +63 -4
  5. package/skills/pi-suite-jobs/SKILL.md +76 -0
  6. package/skills/pi-suite-workflow/SKILL.md +114 -0
  7. package/src/agents/catalog.ts +80 -0
  8. package/src/agents/child.ts +79 -0
  9. package/src/agents/commands.ts +17 -0
  10. package/src/agents/defaults.ts +78 -0
  11. package/src/agents/history.ts +112 -0
  12. package/src/agents/index.ts +211 -0
  13. package/src/agents/manager.ts +438 -0
  14. package/src/agents/mentions/clone.ts +51 -0
  15. package/src/agents/mentions/grammar.ts +64 -0
  16. package/src/agents/mentions/index.ts +76 -0
  17. package/src/agents/mentions/provider.ts +79 -0
  18. package/src/agents/model-editor.ts +95 -0
  19. package/src/agents/models.ts +43 -0
  20. package/src/agents/output/schema.ts +101 -0
  21. package/src/agents/output/tool.ts +98 -0
  22. package/src/agents/parent.ts +13 -0
  23. package/src/agents/questions.ts +63 -0
  24. package/src/agents/records.ts +90 -0
  25. package/src/agents/registry.ts +20 -0
  26. package/src/agents/render.ts +85 -0
  27. package/src/agents/resources/context.ts +48 -0
  28. package/src/agents/resources/loader.ts +86 -0
  29. package/src/agents/resources/memory.ts +67 -0
  30. package/src/agents/resources/packages.ts +96 -0
  31. package/src/agents/resources/paths.ts +8 -0
  32. package/src/agents/resources/prompts.ts +11 -0
  33. package/src/agents/resources/scope.ts +147 -0
  34. package/src/agents/resources/selectors.ts +186 -0
  35. package/src/agents/retry.ts +20 -0
  36. package/src/agents/rpc/handlers.ts +62 -0
  37. package/src/agents/rpc/index.ts +73 -0
  38. package/src/agents/rpc/options.ts +44 -0
  39. package/src/agents/run-groups.ts +16 -0
  40. package/src/agents/runner.ts +131 -0
  41. package/src/agents/runtime.ts +40 -0
  42. package/src/agents/schedules/index.ts +136 -0
  43. package/src/agents/schedules/menu.ts +38 -0
  44. package/src/agents/schedules/parse.ts +42 -0
  45. package/src/agents/schedules/store.ts +78 -0
  46. package/src/agents/schema.ts +5 -0
  47. package/src/agents/session.ts +29 -0
  48. package/src/agents/tools.ts +177 -0
  49. package/src/agents/types.ts +87 -0
  50. package/src/agents/ui/index.ts +42 -0
  51. package/src/agents/ui/runs.ts +122 -0
  52. package/src/agents/ui/types.ts +91 -0
  53. package/src/agents/viewer-info.ts +36 -0
  54. package/src/agents/viewer.ts +160 -0
  55. package/src/agents/workflow/collisions.ts +124 -0
  56. package/src/agents/workflow/entry.ts +93 -0
  57. package/src/agents/workflow/host.ts +119 -0
  58. package/src/agents/workflow/index.ts +100 -0
  59. package/src/agents/workflow/journal.ts +147 -0
  60. package/src/agents/workflow/literal.ts +57 -0
  61. package/src/agents/workflow/manager.ts +169 -0
  62. package/src/agents/workflow/meta.ts +323 -0
  63. package/src/agents/workflow/progress/format.ts +184 -0
  64. package/src/agents/workflow/progress/index.ts +3 -0
  65. package/src/agents/workflow/progress/model.ts +224 -0
  66. package/src/agents/workflow/progress/types.ts +144 -0
  67. package/src/agents/workflow/render.ts +46 -0
  68. package/src/agents/workflow/runtime/helpers.ts +236 -0
  69. package/src/agents/workflow/runtime/index.ts +3 -0
  70. package/src/agents/workflow/runtime/run.ts +646 -0
  71. package/src/agents/workflow/runtime/types.ts +273 -0
  72. package/src/agents/workflow/saved.ts +74 -0
  73. package/src/agents/workflow/store.ts +23 -0
  74. package/src/agents/workflow/task.ts +277 -0
  75. package/src/agents/workflow/tool-description.ts +32 -0
  76. package/src/agents/workflow/tools.ts +66 -0
  77. package/src/agents/workflow/ui/menu.ts +144 -0
  78. package/src/agents/workflow/ui/progress.ts +91 -0
  79. package/src/agents/workflow/worker/bootstrap.ts +316 -0
  80. package/src/agents/workflow/worker/flow.ts +218 -0
  81. package/src/agents/workflow/worker/index.ts +7 -0
  82. package/src/agents/workflow/worker/scope.ts +215 -0
  83. package/src/ask/.gitkeep +0 -0
  84. package/src/ask/form.ts +67 -0
  85. package/src/ask/index.ts +73 -0
  86. package/src/ask/keys.ts +32 -0
  87. package/src/ask/layout.ts +78 -0
  88. package/src/ask/queue.ts +40 -0
  89. package/src/ask/render.ts +62 -0
  90. package/src/ask/result.ts +56 -0
  91. package/src/ask/schema.ts +67 -0
  92. package/src/ask/tool-render.ts +49 -0
  93. package/src/ask/view.ts +406 -0
  94. package/src/goal/.gitkeep +0 -0
  95. package/src/goal/activity.ts +50 -0
  96. package/src/goal/commands.ts +75 -0
  97. package/src/goal/context.ts +36 -0
  98. package/src/goal/index.ts +38 -0
  99. package/src/goal/manager.ts +386 -0
  100. package/src/goal/presentation.ts +15 -0
  101. package/src/goal/render.ts +36 -0
  102. package/src/goal/snapshot.ts +78 -0
  103. package/src/goal/state.ts +39 -0
  104. package/src/goal/store.ts +59 -0
  105. package/src/goal/tools.ts +59 -0
  106. package/src/goal/wait.ts +39 -0
  107. package/src/index.ts +20 -0
  108. package/src/jobs/backends/linux-tree.ts +87 -0
  109. package/src/jobs/backends/pipe.ts +74 -0
  110. package/src/jobs/backends/process.ts +79 -0
  111. package/src/jobs/backends/pty-job.ts +45 -0
  112. package/src/jobs/backends/pty.ts +502 -0
  113. package/src/jobs/backends/windows-tree.ts +289 -0
  114. package/src/jobs/commands.ts +7 -0
  115. package/src/jobs/control.ts +13 -0
  116. package/src/jobs/index.ts +331 -0
  117. package/src/jobs/launch/config.ts +26 -0
  118. package/src/jobs/launch/name.ts +16 -0
  119. package/src/jobs/launch/presets.ts +61 -0
  120. package/src/jobs/log-viewer.ts +147 -0
  121. package/src/jobs/manager.ts +507 -0
  122. package/src/jobs/monitors/compile.ts +101 -0
  123. package/src/jobs/monitors/hands-free.ts +108 -0
  124. package/src/jobs/monitors/runtime.ts +165 -0
  125. package/src/jobs/output.ts +54 -0
  126. package/src/jobs/query.ts +62 -0
  127. package/src/jobs/render.ts +103 -0
  128. package/src/jobs/runtime.ts +89 -0
  129. package/src/jobs/state.ts +25 -0
  130. package/src/jobs/store.ts +168 -0
  131. package/src/jobs/terminal/keys.ts +292 -0
  132. package/src/jobs/terminal/protocol.ts +37 -0
  133. package/src/jobs/terminal/read.ts +131 -0
  134. package/src/jobs/terminal/render.ts +70 -0
  135. package/src/jobs/terminal/screen.ts +92 -0
  136. package/src/jobs/terminal/session.ts +100 -0
  137. package/src/jobs/terminal/shell.ts +22 -0
  138. package/src/jobs/terminal/snapshot.ts +8 -0
  139. package/src/jobs/terminal/visible-text.ts +53 -0
  140. package/src/jobs/tools.ts +203 -0
  141. package/src/jobs/types.ts +60 -0
  142. package/src/jobs/viewer/component.ts +209 -0
  143. package/src/jobs/viewer/metadata.ts +9 -0
  144. package/src/jobs/viewer.ts +149 -0
  145. package/src/jobs/workspace.ts +31 -0
  146. package/src/runtime/.gitkeep +0 -0
  147. package/src/runtime/binding.ts +26 -0
  148. package/src/runtime/cli-prompt.ts +24 -0
  149. package/src/runtime/clipboard.ts +16 -0
  150. package/src/runtime/config-edit.ts +31 -0
  151. package/src/runtime/config-fields.ts +65 -0
  152. package/src/runtime/config.ts +111 -0
  153. package/src/runtime/errors.ts +11 -0
  154. package/src/runtime/json-store.ts +156 -0
  155. package/src/runtime/notification-render.ts +35 -0
  156. package/src/runtime/notifications.ts +98 -0
  157. package/src/runtime/owner.ts +54 -0
  158. package/src/runtime/read.ts +200 -0
  159. package/src/runtime/renderers.ts +50 -0
  160. package/src/runtime/responses/index.ts +108 -0
  161. package/src/runtime/responses/payload.ts +78 -0
  162. package/src/runtime/settings/index.ts +24 -0
  163. package/src/runtime/settings/view.ts +84 -0
  164. package/src/runtime/suite.ts +192 -0
  165. package/src/runtime/text.ts +6 -0
  166. package/src/runtime/tools.ts +131 -0
  167. package/src/runtime/wait-render.ts +33 -0
  168. package/src/runtime/wait.ts +134 -0
  169. package/src/tasks/commands.ts +41 -0
  170. package/src/tasks/index.ts +305 -0
  171. package/src/tasks/model.ts +152 -0
  172. package/src/tasks/presentation.ts +40 -0
  173. package/src/tasks/query.ts +38 -0
  174. package/src/tasks/render.ts +54 -0
  175. package/src/tasks/schema.ts +25 -0
  176. package/src/tasks/store.ts +164 -0
  177. package/src/tasks/tools.ts +69 -0
  178. package/src/tasks/types.ts +61 -0
  179. package/src/tasks/viewer.ts +68 -0
  180. package/src/ui/.gitkeep +0 -0
  181. package/src/ui/actions.ts +50 -0
  182. package/src/ui/browser-chrome.ts +175 -0
  183. package/src/ui/browser.ts +292 -0
  184. package/src/ui/details.ts +111 -0
  185. package/src/ui/dock/line.ts +14 -0
  186. package/src/ui/dock/rows.ts +78 -0
  187. package/src/ui/dock.ts +224 -0
  188. package/src/ui/format.ts +25 -0
  189. package/src/ui/frame.ts +8 -0
  190. package/src/ui/inline-input.ts +98 -0
  191. package/src/ui/reading.ts +105 -0
  192. package/src/ui/rendering/builtin-command.ts +34 -0
  193. package/src/ui/rendering/command.ts +60 -0
  194. package/src/ui/rendering/read-page.ts +15 -0
  195. package/src/ui/rendering/shell/bash.ts +281 -0
  196. package/src/ui/rendering/shell/index.ts +24 -0
  197. package/src/ui/rendering/shell/powershell.ts +155 -0
  198. package/src/ui/rendering/shell/spans.ts +28 -0
  199. package/src/ui/scroll.ts +111 -0
  200. package/src/ui/select.ts +67 -0
  201. package/src/ui/status.ts +67 -0
  202. package/src/ui/structured-details.ts +41 -0
  203. package/src/ui/terminal.ts +137 -0
  204. package/src/ui/ticker.ts +18 -0
  205. package/src/ui/tool-render.ts +152 -0
  206. package/src/ui/transcript.ts +140 -0
  207. package/src/ui/viewer/agent-information.ts +34 -0
  208. package/src/ui/viewer/editor.ts +18 -0
  209. package/src/ui/viewer/navigation.ts +25 -0
  210. package/themes/oh-my-pi.json +95 -0
  211. package/third-party/UPSTREAM.md +88 -0
  212. package/third-party/licenses/.gitkeep +0 -0
  213. package/third-party/licenses/oh-my-pi.txt +23 -0
  214. package/third-party/licenses/pi-ask-user.txt +21 -0
  215. package/third-party/licenses/pi-background-jobs.txt +21 -0
  216. package/third-party/licenses/pi-goal.txt +21 -0
  217. package/third-party/licenses/pi-interactive-shell.txt +25 -0
  218. package/third-party/licenses/pi-subagents.txt +21 -0
  219. package/third-party/licenses/pi-tasks.txt +21 -0
  220. package/third-party/sources.json +111 -0
@@ -0,0 +1,79 @@
1
+ // Grammar, roster and additive autocomplete adapted from @tintinweb/pi-subagents
2
+ // 0.23.0 src/ui/agent-mention.ts (MIT). Saved run records are the history source.
3
+ import type { AutocompleteItem, AutocompleteProvider, AutocompleteSuggestions } from '@earendil-works/pi-tui';
4
+ import { active, type AgentRecord, type AgentType, type ParentScope } from '../types.ts';
5
+ import type { AgentManager } from '../manager.ts';
6
+ import { handleBase, isReservedHandle, MENTION_TRIGGER } from './grammar.ts';
7
+
8
+ export type MentionTarget =
9
+ | { kind: 'record'; handle: string; record: AgentRecord; typeLabel: string }
10
+ | { kind: 'type'; handle: string; type: string; description: string };
11
+
12
+ /** Dispatch and completion share this roster, so foreign branches never become targets. */
13
+ export function mentionRoster(manager: AgentManager, scope: ParentScope, types: AgentType[]): MentionTarget[] {
14
+ const latest = new Map<string, AgentRecord>();
15
+ for (const record of manager.records().filter(record => manager.visible(record, scope)).sort((a, b) => a.createdAt.localeCompare(b.createdAt))) latest.set(record.id, record);
16
+ const records = [...latest.values()].filter(record => record.handle)
17
+ .sort((a, b) => Number(active(b.state)) - Number(active(a.state)) || b.createdAt.localeCompare(a.createdAt));
18
+ const taken = new Set<string>(), targets: MentionTarget[] = [];
19
+ for (const record of records) {
20
+ const handle = record.alias ?? record.handle!;
21
+ taken.add(handle.toLowerCase()); taken.add(record.handle!.toLowerCase());
22
+ targets.push({ kind: 'record', handle, record, typeLabel: types.find(type => type.name === record.type)?.displayName ?? record.type });
23
+ }
24
+ for (const type of types) {
25
+ const handle = handleBase(type.name);
26
+ if (type.enabled === false || taken.has(handle) || isReservedHandle(handle)) continue;
27
+ taken.add(handle); targets.push({ kind: 'type', handle, type: type.name, description: type.description });
28
+ }
29
+ return targets;
30
+ }
31
+
32
+ export function resolveMentionTarget(targets: MentionTarget[], handle: string): MentionTarget | undefined {
33
+ const wanted = handle.toLowerCase();
34
+ return targets.find(target => target.handle.toLowerCase() === wanted
35
+ || target.kind === 'record' && target.record.handle?.toLowerCase() === wanted);
36
+ }
37
+
38
+ export function createMentionProvider(current: AutocompleteProvider, roster: () => MentionTarget[], isEnabled: () => boolean,
39
+ reportFailure: (error: unknown) => void): AutocompleteProvider {
40
+ let warned = false;
41
+ return {
42
+ triggerCharacters: ['@'],
43
+ async getSuggestions(lines, cursorLine, cursorCol, options): Promise<AutocompleteSuggestions | null> {
44
+ const match = isEnabled() ? MENTION_TRIGGER.exec((lines[cursorLine] ?? '').slice(0, cursorCol)) : null;
45
+ const items: AutocompleteItem[] = match ? roster().filter(target => target.handle.toLowerCase().startsWith(match[2].toLowerCase()))
46
+ .map(target => ({ value: `@${target.handle}`, label: `@${target.handle}`, description: describeTarget(target) })) : [];
47
+ const mine = items.length ? { items, prefix: `@${match![2]}` } : null;
48
+ let theirs: AutocompleteSuggestions | null;
49
+ try { theirs = await current.getSuggestions(lines, cursorLine, cursorCol, options); }
50
+ catch (error) {
51
+ // Pi's editor awaits providers without a rejection handler. Keep agent matches
52
+ // usable if an inner provider fails, and report the failure once.
53
+ if (options?.signal?.aborted) return null;
54
+ if (!warned) { warned = true; reportFailure(error); }
55
+ return mine;
56
+ }
57
+ if (!mine) return theirs;
58
+ if (!theirs) return mine;
59
+ return { items: [...mine.items, ...theirs.items], prefix: mine.prefix };
60
+ },
61
+ applyCompletion(lines, cursorLine, cursorCol, item, prefix) {
62
+ return current.applyCompletion(lines, cursorLine, cursorCol, item, prefix);
63
+ },
64
+ shouldTriggerFileCompletion(lines, cursorLine, cursorCol) {
65
+ return current.shouldTriggerFileCompletion?.(lines, cursorLine, cursorCol) ?? true;
66
+ },
67
+ };
68
+ }
69
+
70
+ function describeTarget(target: MentionTarget): string {
71
+ if (target.kind === 'type') return `start · ${summarize(target.description)}`;
72
+ const { state, name, alias } = target.record;
73
+ const action = state === 'stopping' ? 'stopping' : active(state) ? 'send message' : 'resume';
74
+ return `${action} · ${alias ? `${target.typeLabel} · ` : ''}${state} · ${summarize(name)}`;
75
+ }
76
+ function summarize(description: string): string {
77
+ const first = (description.match(/^.*?[.!?](?=\s|$)/s)?.[0] ?? description).replace(/\s+/g, ' ').trim();
78
+ return first.length > 60 ? `${first.slice(0, 59).trimEnd()}…` : first;
79
+ }
@@ -0,0 +1,95 @@
1
+ import type { Model } from '@earendil-works/pi-ai';
2
+ import { getSupportedThinkingLevels } from '@earendil-works/pi-ai';
3
+ import { clampThinkingLevel } from '@earendil-works/pi-ai/compat';
4
+ import type { ExtensionContext } from '@earendil-works/pi-coding-agent';
5
+ import type { SuiteConfig } from '../runtime/config.ts';
6
+ import { agentTypeLocations, agentTypeModelAfterClear, writeAgentType } from '../runtime/config-edit.ts';
7
+ import { resolveModel, resolveSettings } from './models.ts';
8
+ import { agentTypes } from './catalog.ts';
9
+ import { active, type AgentType, type ModelOverrides } from './types.ts';
10
+ import { ToolError } from '../runtime/errors.ts';
11
+ import type { AgentManager } from './manager.ts';
12
+ import { selectValue } from '../ui/select.ts';
13
+ import { getAgentDir } from '@earendil-works/pi-coding-agent';
14
+ import type { ViewerNavigation } from '../ui/viewer/navigation.ts';
15
+
16
+ export async function chooseModelSettings(ctx: ExtensionContext, title: string, initial: ModelOverrides, inherited: () => Model<any> | undefined, navigation?: ViewerNavigation): Promise<ModelOverrides | undefined> {
17
+ const available = ctx.modelRegistry.getAvailable().sort((a, b) => `${a.provider}/${a.id}`.localeCompare(`${b.provider}/${b.id}`));
18
+ // ModelSelector needs the host's private ModelRuntime and cannot represent clearing an
19
+ // override. Reuse the shared native fuzzy picker without changing the main session model.
20
+ const items = [{ value: '', label: 'No override' }, ...available.map(model => ({
21
+ value: `${model.provider}/${model.id}`, label: `${model.provider}/${model.id}`, description: model.name,
22
+ }))];
23
+ const selected = await selectValue(ctx, `${title} · Model`, items, initial.model ?? '', { filter: true, navigation });
24
+ if (selected === undefined) return;
25
+ const model = selected || undefined;
26
+ const effective = model ? resolveModel(ctx, model, title) : inherited();
27
+ const levels = ['', ...effective ? getSupportedThinkingLevels(effective) : ['off' as const]];
28
+ const thinking = await selectValue(ctx, `${title} · Thinking`, levels.map(value => ({ value, label: value || 'No override' })), initial.thinking ?? '', {navigation});
29
+ if (thinking === undefined) return;
30
+ return { model, thinking: thinking ? thinking as ModelOverrides['thinking'] : undefined };
31
+ }
32
+
33
+ export async function editTypeModel(ctx: ExtensionContext, config: SuiteConfig, reload: (cwd: string) => void, selectedType?: AgentType, navigation?: ViewerNavigation): Promise<void> {
34
+ let type = selectedType;
35
+ if (!type) {
36
+ const types = agentTypes(ctx.cwd, getAgentDir(), { trusted: ctx.isProjectTrusted(), packageGate: config.agents.packageAgents });
37
+ const selected = await ctx.ui.select('Select agent type', types.map(type => type.name));
38
+ if (selected === undefined) return;
39
+ type = types.find(type => type.name === selected)!;
40
+ }
41
+ const initial = config.agents.types[type.name] ?? {};
42
+ const locations = agentTypeLocations(ctx.cwd, type.name);
43
+ ctx.ui.notify(`${type.name} · model: ${locations.model}\nthinking: ${locations.thinking}`);
44
+ const fallback = () => resolveSettings(ctx, type, { prompt: '' }, { ...config, agents: { ...config.agents,
45
+ types: { [type.name]: { model: agentTypeModelAfterClear(ctx.cwd, type.name) } } } }).model;
46
+ const changes = await chooseModelSettings(ctx, type.name, initial, fallback, navigation);
47
+ if (!changes) return;
48
+ try { await writeAgentType(ctx.cwd, type.name, changes); }
49
+ // Model and thinking may live in different files; reload also reflects any field already
50
+ // saved if the other file reports an I/O error. The write error remains visible to the host.
51
+ finally { reload(ctx.cwd); }
52
+ ctx.ui.notify(`${type.name}: model/thinking saved for new runs`);
53
+ }
54
+
55
+ export async function updateAgentModel(manager: AgentManager, ctx: ExtensionContext, id: string, changes: ModelOverrides, runId?: string): Promise<void> {
56
+ const { record, run } = manager.get(id, runId);
57
+ // Validate even an idle agent's planned model now, so unavailable selections fail at the edit.
58
+ if (changes.model) resolveModel(ctx, changes.model, `${id} individual model`);
59
+ if (run && active(record.state)) {
60
+ // Clearing an individual override restores this execution's launch choices. Type edits
61
+ // made afterwards must not leak into a running or queued execution through this action.
62
+ const request = { ...run.request,
63
+ model: changes.model === undefined ? run.request.model : undefined,
64
+ thinking: changes.thinking === undefined ? run.request.thinking : undefined };
65
+ const resolved = resolveSettings(run.parent.ctx, run.type, request, run.config, changes);
66
+ const session = run.session;
67
+ if (session) {
68
+ await session.setModel(resolved.model, { persist: false });
69
+ session.setThinkingLevel(resolved.thinking, { persist: false });
70
+ run.record.contextUsage = session.getContextUsage();
71
+ }
72
+ if (!run.settled) Object.assign(run.record, { model: `${resolved.model.provider}/${resolved.model.id}`, modelSource: resolved.modelSource,
73
+ thinking: session?.thinkingLevel ?? resolved.thinking, thinkingSource: resolved.thinkingSource });
74
+ run.model = resolved.model;
75
+ }
76
+ if (run) run.record.individual = changes;
77
+ else manager.restore([{ ...record, individual: changes }]);
78
+ manager.changed();
79
+ }
80
+
81
+ export async function editAgentModel(ctx: ExtensionContext, manager: AgentManager, id: string, config: SuiteConfig, runId?: string, navigation?: ViewerNavigation): Promise<void> {
82
+ const { record, run } = manager.get(id, runId);
83
+ const inherited = () => {
84
+ // Records stay editable after their type is disabled: the enabled check runs in
85
+ // resolveType when a new execution starts, not here. Look the type up without that check.
86
+ const type = run?.type ?? agentTypes(ctx.cwd, getAgentDir(), { trusted: ctx.isProjectTrusted(), packageGate: config.agents.packageAgents }).find(type => type.name === record.type);
87
+ if (!type) throw new ToolError('AGENT_TYPE', `Unknown agent type: ${record.type}. Restore its definition before clearing the model override.`);
88
+ return resolveSettings(run?.parent.ctx ?? ctx, type, run?.request ?? { prompt: '' }, run?.config ?? config).model;
89
+ };
90
+ const changes = await chooseModelSettings(ctx, `${id} (${record.runId}) · next request`, record.individual ?? {}, inherited, navigation);
91
+ if (!changes) return;
92
+ // A selector may outlive a resume; bind the write to the run opened, never the agent's latest run.
93
+ await updateAgentModel(manager, ctx, id, changes, record.runId);
94
+ ctx.ui.notify(`${id} (${record.runId}): model/thinking applies to its next request`);
95
+ }
@@ -0,0 +1,43 @@
1
+ // Matching/priorities adapted from @tintinweb/pi-subagents 0.23.0 src/model-resolver.ts
2
+ // and src/invocation-config.ts (MIT); explicit identities do not use its provider fallback.
3
+ import type { ExtensionContext, ModelRuntime } from '@earendil-works/pi-coding-agent';
4
+ import type { SuiteConfig } from '../runtime/config.ts';
5
+ import { ToolError } from '../runtime/errors.ts';
6
+ import type { AgentType, ModelOverrides, ModelSource, StartAgent, ParentContext } from './types.ts';
7
+
8
+ export function parentModelRuntime(ctx: Pick<ExtensionContext, 'modelRegistry'>): ModelRuntime {
9
+ // Pi 1.5.0 keeps this field private (doc/current/agents/models.md#模型运行时桥接). Check the
10
+ // runtime methods, not class identity: CLI bundles and SDK modules can load different classes.
11
+ // Passing undefined would make createAgentSession silently create an independent runtime.
12
+ const runtime = (ctx.modelRegistry as unknown as { runtime?: ModelRuntime }).runtime;
13
+ if (!runtime || typeof runtime.getModel !== 'function' || typeof runtime.streamSimple !== 'function'
14
+ || typeof runtime.resolveModel !== 'function') {
15
+ throw new ToolError('MODEL_RUNTIME_UNAVAILABLE', 'Pi compatibility error: ModelRegistry.runtime cannot supply the parent model runtime, so child agents and type mentions cannot start; no independent runtime will be created. Run the Pi version this package supports (1.5.0).');
16
+ }
17
+ return runtime;
18
+ }
19
+
20
+ export function resolveModel(ctx: Pick<ExtensionContext, 'modelRegistry'>, name: string, source: string, fuzzy = false) {
21
+ const available = ctx.modelRegistry.getAvailable();
22
+ // A provider prefix is an exact identity; never substitute a same-named model elsewhere.
23
+ const exact = available.filter(model => `${model.provider}/${model.id}` === name || (!name.includes('/') && model.id === name));
24
+ const matches = exact.length ? exact : fuzzy && !name.includes('/') ? available.filter(model => `${model.id} ${model.name}`.toLowerCase().includes(name.toLowerCase())) : [];
25
+ if (matches.length !== 1) throw new ToolError('MODEL_UNAVAILABLE', `${source} specifies ${name}, which matches no authenticated model or more than one. Use an exact provider/modelId that is available.`);
26
+ return matches[0];
27
+ }
28
+ export function resolveSettings(ctx: ParentContext, type: AgentType, request: StartAgent, config: SuiteConfig, individual?: ModelOverrides) {
29
+ const override = config.agents.types[type.name];
30
+ const modelOptions: [string | undefined, ModelSource, string, boolean][] = [
31
+ [request.model, 'parameter', 'agent_start.model', true],
32
+ [individual?.model, 'individual', `${type.name} individual model`, false],
33
+ [override?.model, 'type', `agents.types.${type.name}.model`, false],
34
+ [type.model, 'frontmatter', `${type.sourcePath ?? type.name}:model`, true],
35
+ [config.agents.defaultModel, 'default', 'agents.defaultModel', false],
36
+ ];
37
+ const selected = modelOptions.find(([value]) => value !== undefined);
38
+ const model = selected ? resolveModel(ctx, selected[0]!, selected[2], selected[3]) : ctx.model;
39
+ if (!model) throw new ToolError('MODEL_UNAVAILABLE', 'Parent session has no model to inherit. Pass model or set agents.defaultModel.');
40
+ const thinkingSource: ModelSource = request.thinking !== undefined ? 'parameter' : individual?.thinking !== undefined ? 'individual' : override?.thinking !== undefined ? 'type' : type.thinking !== undefined ? 'frontmatter' : 'inherited';
41
+ return { model, modelSource: selected?.[1] ?? 'inherited',
42
+ thinking: request.thinking ?? individual?.thinking ?? override?.thinking ?? type.thinking ?? ctx.thinkingLevel ?? 'off', thinkingSource };
43
+ }
@@ -0,0 +1,101 @@
1
+ // Imported/adapted from @tintinweb/pi-subagents 0.23.0 src/workflow/json-schema.ts (MIT).
2
+ // TypeBox v1 accepts plain JSON Schema without a TypeBox Kind symbol. Pass the
3
+ // same object to the provider and the checker so the two use the same contract.
4
+ // Keep the checker independent of Pi so workflow recovery can validate stored
5
+ // values without opening a child session. Pi also validates live tool inputs.
6
+
7
+ import { Check, Errors } from "typebox/value";
8
+
9
+ /** Maximum length of the serialized schema in UTF-16 code units. */
10
+ const MAX_SCHEMA_BYTES = 64 * 1024;
11
+
12
+ /** How many validation errors are quoted back to the model. */
13
+ const MAX_REPORTED_ERRORS = 5;
14
+
15
+ export interface CompiledSchema {
16
+ /** The schema as given, for the tool's `parameters` and the journal key. */
17
+ readonly schema: Record<string, unknown>;
18
+ /** `true`, or a human-readable account of what is wrong. */
19
+ check(value: unknown): true | string;
20
+ }
21
+
22
+ export type SchemaCompilation =
23
+ | { ok: true; compiled: CompiledSchema }
24
+ | { ok: false; message: string };
25
+
26
+ /**
27
+ * Turn a script-supplied schema into something we can check against.
28
+ *
29
+ * Rejects up front rather than at the first tool call. A schema whose root is
30
+ * not an object cannot be a tool's input schema at all, so it would break every
31
+ * request the child makes rather than just the last one — and the author should
32
+ * hear about that before a model is paid to discover it.
33
+ */
34
+ export function compileJsonSchema(schema: unknown): SchemaCompilation {
35
+ if (typeof schema !== "object" || schema === null || Array.isArray(schema)) {
36
+ return { ok: false, message: 'Invalid agent() opts.schema. Pass a JSON Schema object.' };
37
+ }
38
+ const root = schema as Record<string, unknown>;
39
+ if (root.type !== "object") {
40
+ return {
41
+ ok: false,
42
+ message: 'agent() opts.schema has a non-object or missing root type. Set the root type to "object".',
43
+ };
44
+ }
45
+
46
+ let serialized: string;
47
+ try {
48
+ serialized = JSON.stringify(root);
49
+ } catch {
50
+ return { ok: false, message: 'Cannot serialize agent() opts.schema. Pass a JSON-serializable schema.' };
51
+ }
52
+ if (serialized.length > MAX_SCHEMA_BYTES) {
53
+ return {
54
+ ok: false,
55
+ message: `agent() opts.schema is too large (${serialized.length} UTF-16 code units; max ${MAX_SCHEMA_BYTES}). Shorten the schema.`,
56
+ };
57
+ }
58
+
59
+ // Smoke-tested here so a schema the validator cannot walk fails at the call
60
+ // that wrote it, with the schema in hand, rather than inside a child's tool
61
+ // handler where the only symptom is an agent that never returns.
62
+ try {
63
+ Check(root, {});
64
+ } catch (error) {
65
+ return {
66
+ ok: false,
67
+ message: `Cannot validate agent() opts.schema: ${
68
+ error instanceof Error ? error.message : String(error)
69
+ }. Fix the schema before retrying.`,
70
+ };
71
+ }
72
+
73
+ return { ok: true, compiled: { schema: root, check: value => checkAgainst(root, value) } };
74
+ }
75
+
76
+ function checkAgainst(schema: Record<string, unknown>, value: unknown): true | string {
77
+ let valid: boolean;
78
+ try {
79
+ valid = Check(schema, value);
80
+ } catch (error) {
81
+ // Reported rather than thrown: a schema that compiled but trips on a
82
+ // particular value must fail that call, not the run.
83
+ return `the value could not be validated: ${error instanceof Error ? error.message : String(error)}`;
84
+ }
85
+ if (valid) return true;
86
+
87
+ const reported: string[] = [];
88
+ try {
89
+ for (const error of Errors(schema, value)) {
90
+ // `instancePath` is JSON Pointer (`/a/b`); the model wrote the schema in
91
+ // JavaScript, so it reads `$.a.b` far more easily.
92
+ const path = String(error.instancePath ?? "");
93
+ const where = path === "" ? "$" : `$${path.replace(/\//g, ".")}`;
94
+ reported.push(`${where}: ${error.message}`);
95
+ if (reported.length >= MAX_REPORTED_ERRORS) break;
96
+ }
97
+ } catch (error) {
98
+ return `schema error reporting failed: ${error instanceof Error ? error.message : String(error)}`;
99
+ }
100
+ return reported.length > 0 ? reported.join("; ") : "the value does not match the required schema";
101
+ }
@@ -0,0 +1,98 @@
1
+ // Imported/adapted from @tintinweb/pi-subagents 0.23.0 src/structured-output.ts (MIT).
2
+ // The name matches Claude Code so ported prompts can still call StructuredOutput.
3
+ // AgentSession does not expose toolChoice. Constrained sampling and tool guidance
4
+ // help the model make the call; validation and one final prompt cover failures.
5
+
6
+ import { defineTool, type ToolDefinition } from "@earendil-works/pi-coding-agent";
7
+ import { stateLine, toolRenderers } from "../../ui/tool-render.ts";
8
+ import type { CompiledSchema } from "./schema.ts";
9
+
10
+ // The child runner injects this tool. Adding it to the subagent exclusion list
11
+ // would hide it; adding it to the built-in list would let frontmatter select it.
12
+ export const STRUCTURED_OUTPUT_TOOL_NAME = "StructuredOutput";
13
+
14
+ type OutputDetails = { payload?: string; error?: string };
15
+ export const structuredOutputRenderers = toolRenderers<unknown, OutputDetails>({
16
+ call: () => ({ icon: "", title: STRUCTURED_OUTPUT_TOOL_NAME }),
17
+ collapsed: () => ({ ...stateLine("completed"), title: STRUCTURED_OUTPUT_TOOL_NAME, summary: "accepted" }),
18
+ error: details => ({ summary: "rejected", diagnostic: details?.error }),
19
+ expanded: details => details?.payload === undefined ? [] : [{ code: details.payload, language: "json" }],
20
+ });
21
+
22
+ export interface StructuredCapture {
23
+ json?: string;
24
+ /** Why the most recent attempt was rejected, for the retry prompt. */
25
+ lastError?: string;
26
+ /** Whether the tool was called at all — "never tried" reads differently. */
27
+ called: boolean;
28
+ }
29
+
30
+ export function createStructuredCapture(): StructuredCapture {
31
+ return { called: false };
32
+ }
33
+
34
+ // The runner owns capture so it can check the result even if the model never calls the tool.
35
+ export function createStructuredOutputTool(
36
+ compiled: CompiledSchema,
37
+ capture: StructuredCapture,
38
+ ): ToolDefinition {
39
+ return defineTool({
40
+ ...structuredOutputRenderers,
41
+ name: STRUCTURED_OUTPUT_TOOL_NAME,
42
+ label: "Structured Output",
43
+ description:
44
+ "Submit your complete final answer in one StructuredOutput call. Use the schema fields, not prose. If rejected, fix the reported fields and call again.",
45
+ promptSnippet: "Submit a structured final answer",
46
+ promptGuidelines: [
47
+ "Put the complete final answer in StructuredOutput; prose does not count as the result.",
48
+ ],
49
+ // Pass the caller's JSON Schema directly so the provider sees the same fields the checker validates.
50
+ parameters: compiled.schema as never,
51
+ // "prefer", not "require": a provider that cannot constrain sampling should
52
+ // fall through to validation-and-retry rather than fail the call outright.
53
+ constrainedSampling: { type: "json_schema", strict: "prefer" },
54
+ // Models occasionally send the whole payload as one JSON string instead of
55
+ // an object. Recovering that costs nothing and saves a whole retry.
56
+ prepareArguments: (args: unknown) => {
57
+ if (typeof args !== "string") return args as never;
58
+ return JSON.parse(args) as never;
59
+ },
60
+ execute: async (_toolCallId, params) => {
61
+ capture.called = true;
62
+ const verdict = compiled.check(params);
63
+ if (verdict !== true) {
64
+ capture.lastError = verdict;
65
+ // `isError` puts the reason in front of the model as a tool result, so
66
+ // it can correct itself inside this same run. This is where most
67
+ // mismatches are resolved; the prompt-level retry is the backstop.
68
+ return {
69
+ content: [{
70
+ type: "text",
71
+ text: `${verdict}\nFix the reported fields and call StructuredOutput again.`,
72
+ }],
73
+ isError: true,
74
+ details: { error: verdict } satisfies OutputDetails,
75
+ };
76
+ }
77
+ // Last valid call wins: a model that calls twice meant the second one. The payload
78
+ // also goes into details so replay needs neither the schema nor the call arguments.
79
+ capture.json = JSON.stringify(params);
80
+ capture.lastError = undefined;
81
+ return { content: [{ type: "text", text: "Recorded." }], details: { payload: capture.json } satisfies OutputDetails };
82
+ },
83
+ }) as ToolDefinition;
84
+ }
85
+
86
+ /**
87
+ * The one extra prompt sent when a run ended with nothing captured.
88
+ *
89
+ * Distinguishes "never called it" from "called it wrongly" — the two need
90
+ * different corrections, and telling a model it got the shape wrong when it
91
+ * never answered at all sends it looking for a mistake it did not make.
92
+ */
93
+ export function structuredRetryPrompt(capture: StructuredCapture): string {
94
+ const reason = capture.called && capture.lastError !== undefined
95
+ ? `StructuredOutput rejected the last call: ${capture.lastError}`
96
+ : `You did not call ${STRUCTURED_OUTPUT_TOOL_NAME}.`;
97
+ return `${reason}\n\nCall ${STRUCTURED_OUTPUT_TOOL_NAME} with your complete answer, not prose.`;
98
+ }
@@ -0,0 +1,13 @@
1
+ import type { ParentScope } from './types.ts';
2
+
3
+ /** Pi context getters are revoked on reload; queued and workflow execution retain facts instead. */
4
+ export function captureParent(scope: ParentScope): ParentScope {
5
+ const { ctx } = scope, trusted = ctx.isProjectTrusted(), systemPrompt = ctx.getSystemPrompt();
6
+ const sessionManager = ctx.sessionManager;
7
+ return { ...scope,
8
+ ctx: { cwd: ctx.cwd, model: ctx.model, modelRegistry: ctx.modelRegistry, thinkingLevel: ctx.thinkingLevel,
9
+ sessionManager, isProjectTrusted: () => trusted, getSystemPrompt: () => systemPrompt },
10
+ owner: scope.owner ?? { ownerSessionId: scope.run?.record.ownerSessionId ?? sessionManager.getSessionId(),
11
+ anchorEntryId: scope.run ? scope.run.record.anchorEntryId : sessionManager.getLeafId() },
12
+ };
13
+ }
@@ -0,0 +1,63 @@
1
+ import { normalize, type AskParams, type AskResult, type Question, type Response } from '../ask/schema.ts';
2
+ import { ToolError } from '../runtime/errors.ts';
3
+ import type { NotificationView } from '../runtime/notifications.ts';
4
+ import type { Execution } from './types.ts';
5
+
6
+ export function questionNotification(run: Execution): { text: string; view: NotificationView } {
7
+ const { id, name } = run.record, state = 'waiting(parent)';
8
+ const body = [...run.question!.questions.flatMap(question => [question.question, ...question.options.map(option => `${option.id}: ${option.title}`)]),
9
+ `answer: agent_send({"id":"${id}","message":"…"})`].filter(Boolean).join('\n');
10
+ return { text: `${id} ${name} ${state}\n${body}`, view: { title: 'Agent question', state, meta: [id, name], body } };
11
+ }
12
+ export function questionText(run: Execution): string { return questionNotification(run).text; }
13
+ export async function askParent(run: Execution, params: AskParams, timeoutMs: number, changed: () => void, signal?: AbortSignal): Promise<{ result: AskResult; questions: Question[] }> {
14
+ const questions = normalize(params), done = Promise.withResolvers<AskResult>();
15
+ if (run.controller.signal.aborted || signal?.aborted) return { result: { status: 'cancelled' as const, responses: [] }, questions };
16
+ const previous = run.record.state;
17
+ const question = { params, questions, seen: false, finish: (result: AskResult) => {
18
+ if (run.question !== question) return;
19
+ run.question = undefined; done.resolve(result);
20
+ } };
21
+ run.question = question; run.record.state = 'waiting';
22
+ const cancel = () => question.finish({ status: 'cancelled', responses: [] });
23
+ run.controller.signal.addEventListener('abort', cancel, { once: true });
24
+ signal?.addEventListener('abort', cancel, { once: true });
25
+ const timeout = params.timeoutMs ?? timeoutMs;
26
+ const timer = timeout ? setTimeout(() => question.finish({ status: 'timed_out', responses: [] }), timeout) : undefined;
27
+ try {
28
+ changed();
29
+ const result = await done.promise;
30
+ // Pi's tool terminate contract ends a turn without setting agent_settled.aborted. Preserve
31
+ // the unanswered status so the manager cannot present an expired question as success.
32
+ if (result.status !== 'answered') run.terminated = true;
33
+ return { result, questions };
34
+ }
35
+ finally {
36
+ clearTimeout(timer); signal?.removeEventListener('abort', cancel); run.controller.signal.removeEventListener('abort', cancel);
37
+ if (run.question === question) run.question = undefined;
38
+ if (run.record.state === 'waiting') run.record.state = previous;
39
+ changed();
40
+ }
41
+ }
42
+ function answer(question: Question, text: string | string[]): Response {
43
+ if (Array.isArray(text) && !question.allowMultiple) throw new ToolError('INVALID_ANSWER', 'This is a single-choice question. Send one option ID, title, or text answer.');
44
+ const inputs = Array.isArray(text) ? text : [text];
45
+ const selected = inputs.map(input => question.options.filter(option => option.id === input || option.title === input));
46
+ if (selected.every(matches => matches.length === 1) && inputs.length) {
47
+ // Deduplicate IDs before building the paired title and ID lists.
48
+ const options = [...new Map(selected.map(matches => matches[0]).map(option => [option.id, option])).values()];
49
+ return { kind: 'selection', selections: options.map(option => option.title), optionIds: options.map(option => option.id) };
50
+ }
51
+ if (Array.isArray(text)) throw new ToolError('INVALID_ANSWER', 'The selection array needs valid choices. Send a nonempty array of exact option IDs or titles.');
52
+ return { kind: 'freeform', text };
53
+ }
54
+ export function answerParent(run: Execution, message: string): void {
55
+ const questions = run.question!.questions;
56
+ const inputs: unknown = questions.length > 1 ? JSON.parse(message)
57
+ : [questions[0].allowMultiple && message.trim().startsWith('[') ? JSON.parse(message) : message];
58
+ if (!Array.isArray(inputs) || inputs.length !== questions.length || inputs.some(input => typeof input !== 'string'
59
+ && (!Array.isArray(input) || input.some(item => typeof item !== 'string')))) {
60
+ throw new ToolError('INVALID_ANSWER', 'Answer shape does not match the questions. Send one string per question, or a string array for multiple selections.');
61
+ }
62
+ run.question!.finish({ status: 'answered', responses: questions.map((question, index) => answer(question, inputs[index])) });
63
+ }
@@ -0,0 +1,90 @@
1
+ // Pi custom entries and resume references adapted from pi-subagents agent-record-entry.ts (MIT).
2
+ import { readFileSync } from 'node:fs';
3
+ import { CURRENT_SESSION_VERSION, parseSessionEntries, SessionManager, type SessionEntry } from '@earendil-works/pi-coding-agent';
4
+ import { Type } from 'typebox';
5
+ import { Value } from 'typebox/value';
6
+ import { ToolError } from '../runtime/errors.ts';
7
+ import { objectId } from '../runtime/tools.ts';
8
+ import { active, type AgentRecord, type Execution } from './types.ts';
9
+
10
+ export const AGENT_ENTRY = 'pi-suite:agent-record';
11
+ const string = Type.String();
12
+ const agentId = objectId('agent', 'agent_3fa1c2d0'), runId = objectId('run', 'run_3fa1c2d0');
13
+ const recordSchema = Type.Object({
14
+ version: Type.Literal(1), id: agentId, runId, type: string, name: string, prompt: string, cwd: string,
15
+ ownerSessionId: string, anchorEntryId: Type.Union([string, Type.Null()]), ancestors: Type.Array(runId),
16
+ background: Type.Boolean(), persisted: Type.Boolean(), createdAt: string,
17
+ state: Type.Union(['queued', 'starting', 'running', 'waiting', 'stopping', 'completed', 'failed', 'stopped', 'limited'].map(state => Type.Literal(state))),
18
+ model: string, modelSource: string, thinking: string, thinkingSource: string,
19
+ configCwd: Type.Optional(string), parentAgentId: Type.Optional(agentId), parentRunId: Type.Optional(runId),
20
+ sessionFile: Type.Optional(string), endLeafId: Type.Optional(Type.Union([string, Type.Null()])),
21
+ usage: Type.Optional(Type.Object({tokens: Type.Object(Object.fromEntries(
22
+ ['input', 'output', 'cacheRead', 'cacheWrite', 'total'].map(key => [key, Type.Number()]))), cost: Type.Number()})),
23
+ contextUsage: Type.Optional(Type.Object({ tokens: Type.Union([Type.Number(), Type.Null()]), contextWindow: Type.Number(),
24
+ percent: Type.Union([Type.Number(), Type.Null()]) })),
25
+ result: Type.Optional(string), error: Type.Optional(string), individual: Type.Optional(Type.Object({model: Type.Optional(string), thinking: Type.Optional(string)})),
26
+ }, {additionalProperties: true});
27
+ /** Validate saved suite data once, before it can enter Manager or workflow history. */
28
+ export function decodeAgentRecord(value: unknown, source = 'session entry'): AgentRecord {
29
+ if (!Value.Check(recordSchema, value)) throw new ToolError('AGENT_HISTORY', `Invalid agent record version or data in ${source}. Check that the record is complete and uses version 1.`);
30
+ return value as AgentRecord;
31
+ }
32
+ /** Pi's disk open can repair files. Its in-memory tree migrates and reads without writes. */
33
+ export function readAgentSession(path: string): SessionManager {
34
+ const content = readFileSync(path, 'utf8'), entries = parseSessionEntries(content), header = entries[0];
35
+ // Pi's parser skips malformed lines. Saved suite history must report corruption rather
36
+ // than silently presenting an earlier result; migration/tree construction still use Pi.
37
+ if (entries.length !== content.split('\n').reduce((count, line) => count + (line.trim() ? 1 : 0), 0)) {
38
+ throw new ToolError('AGENT_HISTORY', `Malformed session JSONL in ${path}. Use an intact copy of the file.`);
39
+ }
40
+ if (!header || header.type !== 'session' || typeof header.id !== 'string' || typeof header.cwd !== 'string'
41
+ || header.version !== undefined && (!Number.isInteger(header.version) || header.version < 1 || header.version > CURRENT_SESSION_VERSION)) {
42
+ throw new ToolError('AGENT_HISTORY', `Invalid or unsupported session header in ${path}. Use an intact session file supported by this Pi version.`);
43
+ }
44
+ return SessionManager.inMemory(header.cwd, undefined, entries);
45
+ }
46
+ export function recordsIn(entries: readonly SessionEntry[]): AgentRecord[] {
47
+ const runs = new Map<string, AgentRecord>();
48
+ for (const entry of entries) if (entry.type === 'custom' && entry.customType === AGENT_ENTRY) {
49
+ const record = decodeAgentRecord(entry.data);
50
+ runs.set(record.runId, record);
51
+ }
52
+ return [...runs.values()];
53
+ }
54
+ /** A detached parent's startup entry still points to the child's durable final run entry. */
55
+ export function hydrate(record: AgentRecord): AgentRecord {
56
+ if (!record.sessionFile) return active(record.state) ? {...record, state: 'failed',
57
+ error: 'This run is not active in this Pi process and has no saved transcript. Start a new agent.'} : record;
58
+ if (!active(record.state) && record.result !== undefined) return record;
59
+ const manager = readAgentSession(record.sessionFile);
60
+ const saved = recordsIn(manager.getEntries()).find(run => run.runId === record.runId) ?? record;
61
+ return active(saved.state) ? { ...saved, state: 'failed', endLeafId: manager.getLeafId(),
62
+ error: 'This run is not active in this Pi process. Use agent_read to read the saved transcript.' } : saved;
63
+ }
64
+ export function transcript(record: AgentRecord, run?: Execution): SessionEntry[] {
65
+ if (run?.session) return [...run.session.sessionManager.getBranch(record.endLeafId ?? undefined), ...run.streamingEntry ? [run.streamingEntry] : [], ...run.liveResults?.values() ?? []];
66
+ if (run?.entries) return run.entries;
67
+ if (!record.sessionFile) throw new ToolError('HISTORY_UNAVAILABLE', `${record.id} has no saved transcript and its session is not in memory. Start a new agent.`, record.id);
68
+ const manager = readAgentSession(record.sessionFile);
69
+ if (record.endLeafId && !manager.getEntry(record.endLeafId)) throw new ToolError('AGENT_HISTORY', `Missing history leaf ${record.endLeafId} in ${record.sessionFile}. Use an intact session file.`, record.id);
70
+ return manager.getBranch(record.endLeafId ?? undefined);
71
+ }
72
+ export function resultText(entries: SessionEntry[]): string {
73
+ for (const entry of [...entries].reverse()) if (entry.type === 'message' && entry.message.role === 'assistant') {
74
+ const text = entry.message.content.filter(block => block.type === 'text').map(block => block.text).join('\n');
75
+ if (text) return text;
76
+ }
77
+ return '';
78
+ }
79
+ /** Model-facing serialization keeps complete messages so offsets before the streaming tail stay stable. */
80
+ export function transcriptText(entries: SessionEntry[]): string {
81
+ return entries.flatMap(entry => {
82
+ if (entry.type !== 'message') return [];
83
+ const message = entry.message;
84
+ if (message.role === 'user') return [`[user]\n${typeof message.content === 'string' ? message.content : message.content.map(block => block.type === 'text' ? block.text : '[image]').join('\n')}`];
85
+ if (message.role === 'assistant') return message.content.map(block => block.type === 'text' ? `[assistant]\n${block.text}`
86
+ : block.type === 'thinking' ? `[thinking]\n${block.thinking}` : `[tool ${block.name} ${block.id}]\n${JSON.stringify(block.arguments)}`);
87
+ if (message.role === 'toolResult') return [`[result ${message.toolName} ${message.toolCallId}${message.isError ? ' error' : ''}]\n${message.content.map(block => block.type === 'text' ? block.text : '[image]').join('\n')}`];
88
+ return [];
89
+ }).join('\n\n');
90
+ }
@@ -0,0 +1,20 @@
1
+ import { getAgentDir } from '@earendil-works/pi-coding-agent';
2
+ import type { AgentManager } from './manager.ts';
3
+ import { existingOwner } from '../runtime/owner.ts';
4
+
5
+ // Reloaded factories and display-only imports share the execution owners, not a
6
+ // second name cache that would need synchronization on every lifecycle change.
7
+ export const AGENT_OWNER = 'pi-suite.agents.runtime.v1';
8
+ export const WORKFLOW_OWNER = 'pi-suite.workflows.runtime.v1';
9
+
10
+ /** Query only: renderers and quit never acquire or replace an owner. */
11
+ export function existingAgentRuntime(agentDir: string): AgentManager | undefined {
12
+ return existingOwner(AGENT_OWNER, agentDir) as AgentManager | undefined;
13
+ }
14
+
15
+ /** Only consult records already loaded in this process; renderers do not scan session files. */
16
+ export function agentDisplayName(id: string, runId?: string): string {
17
+ if (!id?.startsWith('agent_')) return id;
18
+ return existingAgentRuntime(getAgentDir())?.records()
19
+ .find(record => record.id === id && (!runId || record.runId === runId) && !record.workflowId)?.name ?? id;
20
+ }