pi-crew 0.1.45 → 0.1.46
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/README.md +5 -5
- package/agents/analyst.md +1 -1
- package/agents/critic.md +1 -1
- package/agents/executor.md +1 -1
- package/agents/explorer.md +1 -1
- package/agents/planner.md +1 -1
- package/agents/reviewer.md +1 -1
- package/agents/security-reviewer.md +1 -1
- package/agents/test-engineer.md +1 -1
- package/agents/verifier.md +1 -1
- package/agents/writer.md +1 -1
- package/docs/next-upgrade-roadmap.md +733 -0
- package/docs/refactor-tasks-phase3.md +394 -394
- package/docs/refactor-tasks-phase4.md +564 -564
- package/docs/refactor-tasks-phase5.md +402 -402
- package/docs/refactor-tasks-phase6.md +662 -662
- package/docs/research-awesome-agent-skills-distillation.md +100 -0
- package/docs/research-extension-examples.md +297 -297
- package/docs/research-extension-system.md +324 -324
- package/docs/research-oh-my-pi-distillation.md +322 -0
- package/docs/research-optimization-plan.md +548 -548
- package/docs/research-phase10-distillation.md +198 -198
- package/docs/research-phase11-distillation.md +201 -201
- package/docs/research-pi-coding-agent.md +357 -357
- package/docs/research-source-pi-crew-reference.md +174 -174
- package/docs/runtime-flow.md +148 -148
- package/docs/source-runtime-refactor-map.md +107 -83
- package/docs/usage.md +3 -3
- package/index.ts +6 -6
- package/install.mjs +52 -8
- package/package.json +1 -1
- package/schema.json +2 -1
- package/skills/async-worker-recovery/SKILL.md +42 -0
- package/skills/context-artifact-hygiene/SKILL.md +52 -0
- package/skills/delegation-patterns/SKILL.md +54 -0
- package/skills/mailbox-interactive/SKILL.md +40 -0
- package/skills/model-routing-context/SKILL.md +39 -0
- package/skills/multi-perspective-review/SKILL.md +58 -0
- package/skills/observability-reliability/SKILL.md +41 -0
- package/skills/ownership-session-security/SKILL.md +41 -0
- package/skills/pi-extension-lifecycle/SKILL.md +39 -0
- package/skills/requirements-to-task-packet/SKILL.md +63 -0
- package/skills/resource-discovery-config/SKILL.md +41 -0
- package/skills/runtime-state-reader/SKILL.md +44 -0
- package/skills/secure-agent-orchestration-review/SKILL.md +45 -0
- package/skills/state-mutation-locking/SKILL.md +42 -0
- package/skills/systematic-debugging/SKILL.md +67 -0
- package/skills/ui-render-performance/SKILL.md +39 -0
- package/skills/verification-before-done/SKILL.md +57 -0
- package/skills/worktree-isolation/SKILL.md +39 -0
- package/src/agents/agent-serializer.ts +34 -34
- package/src/agents/discover-agents.ts +12 -11
- package/src/config/config.ts +48 -24
- package/src/config/defaults.ts +14 -0
- package/src/extension/cross-extension-rpc.ts +82 -82
- package/src/extension/project-init.ts +62 -2
- package/src/extension/register.ts +11 -9
- package/src/extension/registration/commands.ts +32 -25
- package/src/extension/registration/compaction-guard.ts +125 -125
- package/src/extension/registration/subagent-helpers.ts +8 -0
- package/src/extension/registration/subagent-tools.ts +149 -148
- package/src/extension/registration/team-tool.ts +8 -6
- package/src/extension/run-bundle-schema.ts +89 -89
- package/src/extension/run-index.ts +13 -5
- package/src/extension/run-maintenance.ts +62 -43
- package/src/extension/team-tool/api.ts +25 -8
- package/src/extension/team-tool/cancel.ts +33 -4
- package/src/extension/team-tool/context.ts +5 -0
- package/src/extension/team-tool/handle-settings.ts +188 -188
- package/src/extension/team-tool/inspect.ts +41 -41
- package/src/extension/team-tool/lifecycle-actions.ts +91 -79
- package/src/extension/team-tool/plan.ts +19 -19
- package/src/extension/team-tool/respond.ts +37 -17
- package/src/extension/team-tool/run.ts +52 -10
- package/src/extension/team-tool/status.ts +12 -1
- package/src/extension/team-tool-types.ts +2 -0
- package/src/extension/team-tool.ts +32 -11
- package/src/i18n.ts +184 -184
- package/src/observability/event-to-metric.ts +8 -1
- package/src/observability/exporters/otlp-exporter.ts +77 -77
- package/src/prompt/prompt-runtime.ts +72 -72
- package/src/runtime/agent-control.ts +63 -63
- package/src/runtime/agent-memory.ts +72 -72
- package/src/runtime/agent-observability.ts +114 -114
- package/src/runtime/async-marker.ts +26 -26
- package/src/runtime/attention-events.ts +28 -28
- package/src/runtime/background-runner.ts +59 -53
- package/src/runtime/cancellation.ts +51 -0
- package/src/runtime/child-pi.ts +457 -444
- package/src/runtime/completion-guard.ts +190 -190
- package/src/runtime/crash-recovery.ts +1 -0
- package/src/runtime/crew-agent-records.ts +38 -6
- package/src/runtime/deadletter.ts +1 -0
- package/src/runtime/delivery-coordinator.ts +46 -25
- package/src/runtime/direct-run.ts +35 -35
- package/src/runtime/effectiveness.ts +76 -0
- package/src/runtime/foreground-control.ts +82 -82
- package/src/runtime/green-contract.ts +46 -46
- package/src/runtime/group-join.ts +106 -106
- package/src/runtime/heartbeat-gradient.ts +28 -28
- package/src/runtime/heartbeat-watcher.ts +124 -124
- package/src/runtime/live-agent-control.ts +88 -87
- package/src/runtime/live-agent-manager.ts +103 -85
- package/src/runtime/live-control-realtime.ts +36 -36
- package/src/runtime/live-session-runtime.ts +309 -305
- package/src/runtime/manifest-cache.ts +17 -2
- package/src/runtime/model-fallback.ts +6 -4
- package/src/runtime/parallel-research.ts +44 -44
- package/src/runtime/pi-args.ts +18 -3
- package/src/runtime/pi-json-output.ts +111 -111
- package/src/runtime/policy-engine.ts +79 -79
- package/src/runtime/process-status.ts +5 -1
- package/src/runtime/progress-event-coalescer.ts +43 -43
- package/src/runtime/recovery-recipes.ts +74 -74
- package/src/runtime/retry-executor.ts +81 -64
- package/src/runtime/role-permission.ts +39 -39
- package/src/runtime/runtime-resolver.ts +22 -6
- package/src/runtime/session-resources.ts +25 -25
- package/src/runtime/session-snapshot.ts +59 -59
- package/src/runtime/session-usage.ts +79 -79
- package/src/runtime/sidechain-output.ts +29 -29
- package/src/runtime/skill-instructions.ts +222 -0
- package/src/runtime/stale-reconciler.ts +4 -14
- package/src/runtime/subagent-manager.ts +3 -0
- package/src/runtime/supervisor-contact.ts +59 -59
- package/src/runtime/task-display.ts +38 -38
- package/src/runtime/task-output-context.ts +127 -127
- package/src/runtime/task-runner/capabilities.ts +78 -0
- package/src/runtime/task-runner/live-executor.ts +105 -101
- package/src/runtime/task-runner/progress.ts +119 -119
- package/src/runtime/task-runner/prompt-builder.ts +3 -1
- package/src/runtime/task-runner/prompt-pipeline.ts +64 -0
- package/src/runtime/task-runner/result-utils.ts +14 -14
- package/src/runtime/task-runner/state-helpers.ts +22 -22
- package/src/runtime/task-runner.ts +44 -5
- package/src/runtime/team-runner.ts +78 -15
- package/src/runtime/worker-heartbeat.ts +21 -21
- package/src/runtime/worker-startup.ts +57 -57
- package/src/schema/config-schema.ts +1 -0
- package/src/schema/team-tool-schema.ts +3 -3
- package/src/state/active-run-registry.ts +165 -0
- package/src/state/contracts.ts +1 -1
- package/src/state/mailbox.ts +44 -4
- package/src/state/state-store.ts +8 -1
- package/src/state/task-claims.ts +44 -44
- package/src/state/types.ts +44 -2
- package/src/state/usage.ts +29 -29
- package/src/subagents/async-entry.ts +1 -1
- package/src/subagents/index.ts +3 -3
- package/src/subagents/live/control.ts +1 -1
- package/src/subagents/live/manager.ts +1 -1
- package/src/subagents/live/realtime.ts +1 -1
- package/src/subagents/live/session-runtime.ts +1 -1
- package/src/subagents/manager.ts +1 -1
- package/src/subagents/spawn.ts +1 -1
- package/src/teams/team-config.ts +1 -0
- package/src/teams/team-serializer.ts +38 -38
- package/src/types/diff.d.ts +18 -18
- package/src/ui/crew-footer.ts +101 -101
- package/src/ui/crew-select-list.ts +111 -111
- package/src/ui/crew-widget.ts +4 -3
- package/src/ui/dashboard-panes/metrics-pane.ts +34 -34
- package/src/ui/dashboard-panes/progress-pane.ts +2 -0
- package/src/ui/dynamic-border.ts +25 -25
- package/src/ui/layout-primitives.ts +106 -106
- package/src/ui/loaders.ts +158 -158
- package/src/ui/render-diff.ts +119 -119
- package/src/ui/render-scheduler.ts +143 -143
- package/src/ui/run-snapshot-cache.ts +10 -2
- package/src/ui/snapshot-types.ts +2 -0
- package/src/ui/spinner.ts +17 -17
- package/src/ui/status-colors.ts +58 -58
- package/src/ui/syntax-highlight.ts +116 -116
- package/src/utils/atomic-write.ts +33 -33
- package/src/utils/completion-dedupe.ts +63 -63
- package/src/utils/frontmatter.ts +68 -68
- package/src/utils/git.ts +262 -262
- package/src/utils/ids.ts +12 -12
- package/src/utils/names.ts +27 -27
- package/src/utils/paths.ts +4 -2
- package/src/utils/redaction.ts +44 -44
- package/src/utils/safe-paths.ts +47 -47
- package/src/utils/sleep.ts +32 -32
- package/src/workflows/validate-workflow.ts +40 -40
- package/src/workflows/workflow-config.ts +1 -0
- package/src/worktree/branch-freshness.ts +45 -45
- package/teams/default.team.md +12 -12
- package/teams/fast-fix.team.md +11 -11
- package/teams/implementation.team.md +18 -18
- package/teams/parallel-research.team.md +14 -14
- package/teams/research.team.md +11 -11
- package/teams/review.team.md +12 -12
- package/workflows/default.workflow.md +29 -29
- package/workflows/fast-fix.workflow.md +22 -22
- package/workflows/implementation.workflow.md +38 -38
- package/workflows/parallel-research.workflow.md +46 -46
- package/workflows/research.workflow.md +22 -22
- package/workflows/review.workflow.md +30 -30
|
@@ -1,305 +1,309 @@
|
|
|
1
|
-
import * as fs from "node:fs";
|
|
2
|
-
import * as path from "node:path";
|
|
3
|
-
import type { AgentConfig } from "../agents/agent-config.ts";
|
|
4
|
-
import type { CrewRuntimeConfig } from "../config/config.ts";
|
|
5
|
-
import type { TeamRunManifest, TeamTaskState, UsageState } from "../state/types.ts";
|
|
6
|
-
import { buildMemoryBlock } from "./agent-memory.ts";
|
|
7
|
-
import { registerLiveAgent, updateLiveAgentStatus } from "./live-agent-manager.ts";
|
|
8
|
-
import { applyLiveAgentControlRequest, applyLiveAgentControlRequests, type LiveAgentControlCursor } from "./live-agent-control.ts";
|
|
9
|
-
import { subscribeLiveControlRealtime } from "./live-control-realtime.ts";
|
|
10
|
-
import { eventToSidechainType, sidechainOutputPath, writeSidechainEntry } from "./sidechain-output.ts";
|
|
11
|
-
import type { WorkflowStep } from "../workflows/workflow-config.ts";
|
|
12
|
-
import { isLiveSessionRuntimeAvailable } from "./runtime-resolver.ts";
|
|
13
|
-
import { redactSecrets } from "../utils/redaction.ts";
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
};
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
return [];
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
const
|
|
101
|
-
if (
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
if (
|
|
127
|
-
const
|
|
128
|
-
const
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
`
|
|
144
|
-
`
|
|
145
|
-
|
|
146
|
-
input.agent.
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
const
|
|
164
|
-
|
|
165
|
-
const
|
|
166
|
-
const
|
|
167
|
-
const
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
const
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
const
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
let
|
|
203
|
-
let
|
|
204
|
-
let
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
...(
|
|
228
|
-
...(
|
|
229
|
-
...(
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
}
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
if (
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
}
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
const
|
|
298
|
-
updateLiveAgentStatus(
|
|
299
|
-
return { available: true, exitCode:
|
|
300
|
-
}
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
}
|
|
305
|
-
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import type { AgentConfig } from "../agents/agent-config.ts";
|
|
4
|
+
import type { CrewRuntimeConfig } from "../config/config.ts";
|
|
5
|
+
import type { TeamRunManifest, TeamTaskState, UsageState } from "../state/types.ts";
|
|
6
|
+
import { buildMemoryBlock } from "./agent-memory.ts";
|
|
7
|
+
import { registerLiveAgent, updateLiveAgentStatus } from "./live-agent-manager.ts";
|
|
8
|
+
import { applyLiveAgentControlRequest, applyLiveAgentControlRequests, type LiveAgentControlCursor } from "./live-agent-control.ts";
|
|
9
|
+
import { subscribeLiveControlRealtime } from "./live-control-realtime.ts";
|
|
10
|
+
import { eventToSidechainType, sidechainOutputPath, writeSidechainEntry } from "./sidechain-output.ts";
|
|
11
|
+
import type { WorkflowStep } from "../workflows/workflow-config.ts";
|
|
12
|
+
import { isLiveSessionRuntimeAvailable } from "./runtime-resolver.ts";
|
|
13
|
+
import { redactSecrets } from "../utils/redaction.ts";
|
|
14
|
+
import { buildConfiguredModelRouting } from "./model-fallback.ts";
|
|
15
|
+
|
|
16
|
+
export interface LiveSessionSpawnInput {
|
|
17
|
+
manifest: TeamRunManifest;
|
|
18
|
+
task: TeamTaskState;
|
|
19
|
+
step: WorkflowStep;
|
|
20
|
+
agent: AgentConfig;
|
|
21
|
+
prompt: string;
|
|
22
|
+
signal?: AbortSignal;
|
|
23
|
+
transcriptPath?: string;
|
|
24
|
+
onEvent?: (event: unknown) => void;
|
|
25
|
+
onOutput?: (text: string) => void;
|
|
26
|
+
runtimeConfig?: CrewRuntimeConfig;
|
|
27
|
+
parentContext?: string;
|
|
28
|
+
parentModel?: unknown;
|
|
29
|
+
modelRegistry?: unknown;
|
|
30
|
+
modelOverride?: string;
|
|
31
|
+
teamRoleModel?: string;
|
|
32
|
+
isCurrent?: () => boolean;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface LiveSessionRunResult {
|
|
36
|
+
available: true;
|
|
37
|
+
exitCode: number | null;
|
|
38
|
+
stdout: string;
|
|
39
|
+
stderr: string;
|
|
40
|
+
jsonEvents: number;
|
|
41
|
+
usage?: UsageState;
|
|
42
|
+
error?: string;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface LiveSessionUnavailableResult {
|
|
46
|
+
available: false;
|
|
47
|
+
reason: string;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export interface LiveSessionPlannedResult {
|
|
51
|
+
available: true;
|
|
52
|
+
reason: string;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
type LiveSessionModule = Record<string, unknown> & {
|
|
56
|
+
createAgentSession?: (options?: Record<string, unknown>) => Promise<{ session: LiveSessionLike; modelFallbackMessage?: string }>;
|
|
57
|
+
DefaultResourceLoader?: new (options: Record<string, unknown>) => { reload?: () => Promise<void> };
|
|
58
|
+
SessionManager?: { inMemory?: (cwd?: string) => unknown; create?: (cwd?: string, sessionDir?: string) => unknown };
|
|
59
|
+
SettingsManager?: { create?: (cwd?: string, agentDir?: string) => unknown };
|
|
60
|
+
getAgentDir?: () => string;
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
type LiveSessionLike = {
|
|
64
|
+
subscribe?: (listener: (event: unknown) => void) => (() => void);
|
|
65
|
+
prompt?: (text: string, options?: Record<string, unknown>) => Promise<void>;
|
|
66
|
+
steer?: (text: string) => Promise<void>;
|
|
67
|
+
abort?: () => Promise<void> | void;
|
|
68
|
+
getStats?: () => unknown;
|
|
69
|
+
stats?: unknown;
|
|
70
|
+
bindExtensions?: (bindings?: Record<string, unknown>) => Promise<void>;
|
|
71
|
+
getActiveToolNames?: () => string[];
|
|
72
|
+
setActiveToolsByName?: (names: string[]) => void;
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
function appendTranscript(filePath: string | undefined, event: unknown): void {
|
|
76
|
+
if (!filePath) return;
|
|
77
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
78
|
+
fs.appendFileSync(filePath, `${JSON.stringify(redactSecrets(event))}\n`, "utf-8");
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function asRecord(value: unknown): Record<string, unknown> | undefined {
|
|
82
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : undefined;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function textFromContent(content: unknown): string[] {
|
|
86
|
+
if (typeof content === "string") return [content];
|
|
87
|
+
if (!Array.isArray(content)) return [];
|
|
88
|
+
return content.flatMap((part) => {
|
|
89
|
+
const obj = asRecord(part);
|
|
90
|
+
if (!obj) return [];
|
|
91
|
+
if (obj.type === "text" && typeof obj.text === "string") return [obj.text];
|
|
92
|
+
if (typeof obj.content === "string") return [obj.content];
|
|
93
|
+
return [];
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function eventText(event: unknown): string[] {
|
|
98
|
+
const obj = asRecord(event);
|
|
99
|
+
if (!obj) return [];
|
|
100
|
+
const text: string[] = [];
|
|
101
|
+
if (typeof obj.text === "string") text.push(obj.text);
|
|
102
|
+
text.push(...textFromContent(obj.content));
|
|
103
|
+
const message = asRecord(obj.message);
|
|
104
|
+
if (message) text.push(...textFromContent(message.content));
|
|
105
|
+
return text.filter((entry) => entry.trim());
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function finalAssistantText(event: unknown): string[] {
|
|
109
|
+
const obj = asRecord(event);
|
|
110
|
+
if (!obj || obj.type !== "message_end") return [];
|
|
111
|
+
const message = asRecord(obj.message);
|
|
112
|
+
if (message?.role !== "assistant") return [];
|
|
113
|
+
return textFromContent(message.content);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function numberField(obj: Record<string, unknown> | undefined, keys: string[]): number | undefined {
|
|
117
|
+
if (!obj) return undefined;
|
|
118
|
+
for (const key of keys) {
|
|
119
|
+
const value = obj[key];
|
|
120
|
+
if (typeof value === "number" && Number.isFinite(value)) return value;
|
|
121
|
+
}
|
|
122
|
+
return undefined;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function modelFromRegistry(modelRegistry: unknown, modelId: string | undefined): unknown {
|
|
126
|
+
if (!modelId || !modelId.includes("/")) return undefined;
|
|
127
|
+
const registry = asRecord(modelRegistry);
|
|
128
|
+
const find = registry?.find;
|
|
129
|
+
if (typeof find !== "function") return undefined;
|
|
130
|
+
const [provider, ...modelParts] = modelId.split("/");
|
|
131
|
+
const id = modelParts.join("/");
|
|
132
|
+
try {
|
|
133
|
+
return find.call(modelRegistry, provider, id);
|
|
134
|
+
} catch {
|
|
135
|
+
return undefined;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function liveSystemPrompt(input: LiveSessionSpawnInput): string {
|
|
140
|
+
const memory = input.agent.memory ? buildMemoryBlock(input.agent.name, input.agent.memory, input.task.cwd, Boolean(input.agent.tools?.some((tool) => tool === "write" || tool === "edit"))) : "";
|
|
141
|
+
return [
|
|
142
|
+
"# pi-crew Live Subagent",
|
|
143
|
+
`Run ID: ${input.manifest.runId}`,
|
|
144
|
+
`Task ID: ${input.task.id}`,
|
|
145
|
+
`Role: ${input.task.role}`,
|
|
146
|
+
`Agent: ${input.agent.name}`,
|
|
147
|
+
`Working directory: ${input.task.cwd}`,
|
|
148
|
+
"",
|
|
149
|
+
input.agent.systemPrompt || "Follow the user task exactly and report verification evidence.",
|
|
150
|
+
memory ? `\n${memory}` : "",
|
|
151
|
+
].filter(Boolean).join("\n");
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function filterActiveTools(session: LiveSessionLike, agent: AgentConfig): void {
|
|
155
|
+
if (typeof session.getActiveToolNames !== "function" || typeof session.setActiveToolsByName !== "function") return;
|
|
156
|
+
const recursiveTools = new Set(["team", "Team", "Agent", "get_subagent_result", "steer_subagent"]);
|
|
157
|
+
const allowed = agent.tools?.length ? new Set(agent.tools) : undefined;
|
|
158
|
+
const active = session.getActiveToolNames().filter((name) => !recursiveTools.has(name) && (!allowed || allowed.has(name)));
|
|
159
|
+
session.setActiveToolsByName(active);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function usageFromStats(stats: unknown): UsageState | undefined {
|
|
163
|
+
const obj = asRecord(stats);
|
|
164
|
+
if (!obj) return undefined;
|
|
165
|
+
const input = numberField(obj, ["input", "inputTokens", "input_tokens"]);
|
|
166
|
+
const output = numberField(obj, ["output", "outputTokens", "output_tokens"]);
|
|
167
|
+
const cacheRead = numberField(obj, ["cacheRead", "cache_read"]);
|
|
168
|
+
const cacheWrite = numberField(obj, ["cacheWrite", "cache_write"]);
|
|
169
|
+
const cost = numberField(obj, ["cost"]);
|
|
170
|
+
const turns = numberField(obj, ["turns", "turnCount", "turn_count"]);
|
|
171
|
+
return [input, output, cacheRead, cacheWrite, cost, turns].some((value) => value !== undefined) ? { input, output, cacheRead, cacheWrite, cost, turns } : undefined;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export async function probeLiveSessionRuntime(): Promise<LiveSessionUnavailableResult | LiveSessionPlannedResult> {
|
|
175
|
+
const availability = await isLiveSessionRuntimeAvailable();
|
|
176
|
+
if (!availability.available) return { available: false, reason: availability.reason ?? "Live-session runtime is unavailable." };
|
|
177
|
+
return { available: true, reason: "Live-session SDK exports are available and pi-crew can run experimental in-process live agents when runtime.mode=live-session." };
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
export async function runLiveSessionTask(input: LiveSessionSpawnInput): Promise<LiveSessionRunResult> {
|
|
181
|
+
const isCurrent = input.isCurrent ?? (() => true);
|
|
182
|
+
if (process.env.PI_CREW_MOCK_LIVE_SESSION === "success") {
|
|
183
|
+
const agentId = `${input.manifest.runId}:${input.task.id}`;
|
|
184
|
+
const inherited = input.runtimeConfig?.inheritContext === true && input.parentContext ? ` with inherited context: ${input.parentContext}` : "";
|
|
185
|
+
const event = { type: "message_end", message: { role: "assistant", content: [{ type: "text", text: `Mock live-session success for ${input.agent.name}${inherited}` }] } };
|
|
186
|
+
const mockSession = { steer: async () => {}, prompt: async () => {}, abort: async () => {} };
|
|
187
|
+
registerLiveAgent({ agentId, runId: input.manifest.runId, taskId: input.task.id, session: mockSession, status: "running" });
|
|
188
|
+
appendTranscript(input.transcriptPath, event);
|
|
189
|
+
const sidechainPath = sidechainOutputPath(input.manifest.stateRoot, input.task.id);
|
|
190
|
+
writeSidechainEntry(sidechainPath, { agentId, type: "user", message: { role: "user", content: input.prompt }, cwd: input.task.cwd });
|
|
191
|
+
writeSidechainEntry(sidechainPath, { agentId, type: "message", message: event, cwd: input.task.cwd });
|
|
192
|
+
if (isCurrent()) input.onEvent?.(event);
|
|
193
|
+
const stdout = `Mock live-session success for ${input.agent.name}${inherited}`;
|
|
194
|
+
if (isCurrent()) input.onOutput?.(stdout);
|
|
195
|
+
updateLiveAgentStatus(agentId, "completed");
|
|
196
|
+
return { available: true, exitCode: 0, stdout, stderr: "", jsonEvents: 1 };
|
|
197
|
+
}
|
|
198
|
+
const availability = await isLiveSessionRuntimeAvailable();
|
|
199
|
+
if (!availability.available) return { available: true, exitCode: 1, stdout: "", stderr: availability.reason ?? "Live-session runtime unavailable.", jsonEvents: 0, error: availability.reason };
|
|
200
|
+
const mod = await import("@mariozechner/pi-coding-agent") as LiveSessionModule;
|
|
201
|
+
if (typeof mod.createAgentSession !== "function") return { available: true, exitCode: 1, stdout: "", stderr: "createAgentSession export is unavailable.", jsonEvents: 0, error: "createAgentSession export is unavailable." };
|
|
202
|
+
let session: LiveSessionLike | undefined;
|
|
203
|
+
let unsubscribe: (() => void) | undefined;
|
|
204
|
+
let unsubscribeControlRealtime: (() => void) | undefined;
|
|
205
|
+
let controlTimer: ReturnType<typeof setInterval> | undefined;
|
|
206
|
+
let stdout = "";
|
|
207
|
+
let jsonEvents = 0;
|
|
208
|
+
try {
|
|
209
|
+
const agentDir = typeof mod.getAgentDir === "function" ? mod.getAgentDir() : undefined;
|
|
210
|
+
let resourceLoader: unknown;
|
|
211
|
+
if (mod.DefaultResourceLoader && agentDir) {
|
|
212
|
+
resourceLoader = new mod.DefaultResourceLoader({
|
|
213
|
+
cwd: input.task.cwd,
|
|
214
|
+
agentDir,
|
|
215
|
+
noPromptTemplates: true,
|
|
216
|
+
noThemes: true,
|
|
217
|
+
noContextFiles: input.runtimeConfig?.inheritContext !== true,
|
|
218
|
+
systemPromptOverride: () => liveSystemPrompt(input),
|
|
219
|
+
appendSystemPromptOverride: () => [],
|
|
220
|
+
});
|
|
221
|
+
await (resourceLoader as { reload?: () => Promise<void> }).reload?.();
|
|
222
|
+
}
|
|
223
|
+
const modelRouting = buildConfiguredModelRouting({ overrideModel: input.modelOverride, stepModel: input.step.model, teamRoleModel: input.teamRoleModel, agentModel: input.agent.model, fallbackModels: input.agent.fallbackModels, parentModel: input.parentModel, modelRegistry: input.modelRegistry, cwd: input.manifest.cwd });
|
|
224
|
+
const resolvedModel = modelFromRegistry(input.modelRegistry, modelRouting.candidates[0] ?? modelRouting.requested) ?? input.parentModel;
|
|
225
|
+
const created = await mod.createAgentSession({
|
|
226
|
+
cwd: input.task.cwd,
|
|
227
|
+
...(agentDir ? { agentDir } : {}),
|
|
228
|
+
...(resourceLoader ? { resourceLoader } : {}),
|
|
229
|
+
...(mod.SessionManager?.inMemory ? { sessionManager: mod.SessionManager.inMemory(input.task.cwd) } : {}),
|
|
230
|
+
...(mod.SettingsManager?.create && agentDir ? { settingsManager: mod.SettingsManager.create(input.task.cwd, agentDir) } : {}),
|
|
231
|
+
...(input.modelRegistry ? { modelRegistry: input.modelRegistry } : {}),
|
|
232
|
+
...(resolvedModel ? { model: resolvedModel } : {}),
|
|
233
|
+
...(input.agent.thinking ? { thinkingLevel: input.agent.thinking } : {}),
|
|
234
|
+
});
|
|
235
|
+
session = created.session;
|
|
236
|
+
filterActiveTools(session, input.agent);
|
|
237
|
+
await session.bindExtensions?.({});
|
|
238
|
+
const agentId = `${input.manifest.runId}:${input.task.id}`;
|
|
239
|
+
registerLiveAgent({ agentId, runId: input.manifest.runId, taskId: input.task.id, session, status: "running" });
|
|
240
|
+
let controlCursor: LiveAgentControlCursor = { offset: 0 };
|
|
241
|
+
const seenControlRequestIds = new Set<string>();
|
|
242
|
+
let controlBusy = false;
|
|
243
|
+
const pollControl = async () => {
|
|
244
|
+
if (!isCurrent() || controlBusy || !session) return;
|
|
245
|
+
controlBusy = true;
|
|
246
|
+
try {
|
|
247
|
+
controlCursor = await applyLiveAgentControlRequests({ manifest: input.manifest, taskId: input.task.id, agentId, session, cursor: controlCursor, seenRequestIds: seenControlRequestIds });
|
|
248
|
+
} finally {
|
|
249
|
+
controlBusy = false;
|
|
250
|
+
}
|
|
251
|
+
};
|
|
252
|
+
unsubscribeControlRealtime = subscribeLiveControlRealtime((request) => {
|
|
253
|
+
if (!isCurrent() || request.runId !== input.manifest.runId || request.taskId !== input.task.id || !session) return;
|
|
254
|
+
void applyLiveAgentControlRequest({ request, taskId: input.task.id, agentId, session, seenRequestIds: seenControlRequestIds });
|
|
255
|
+
});
|
|
256
|
+
await pollControl();
|
|
257
|
+
controlTimer = setInterval(() => {
|
|
258
|
+
if (isCurrent()) void pollControl();
|
|
259
|
+
}, 500);
|
|
260
|
+
let turnCount = 0;
|
|
261
|
+
let softLimitReached = false;
|
|
262
|
+
const maxTurns = input.runtimeConfig?.maxTurns;
|
|
263
|
+
const graceTurns = input.runtimeConfig?.graceTurns ?? 5;
|
|
264
|
+
const sidechainPath = sidechainOutputPath(input.manifest.stateRoot, input.task.id);
|
|
265
|
+
writeSidechainEntry(sidechainPath, { agentId, type: "user", message: { role: "user", content: input.prompt }, cwd: input.task.cwd });
|
|
266
|
+
if (typeof session.subscribe === "function") {
|
|
267
|
+
unsubscribe = session.subscribe((event) => {
|
|
268
|
+
if (!isCurrent()) return;
|
|
269
|
+
jsonEvents += 1;
|
|
270
|
+
appendTranscript(input.transcriptPath, event);
|
|
271
|
+
const sidechainType = eventToSidechainType(event);
|
|
272
|
+
if (sidechainType) writeSidechainEntry(sidechainPath, { agentId, type: sidechainType, message: event, cwd: input.task.cwd });
|
|
273
|
+
const obj = asRecord(event);
|
|
274
|
+
if (obj?.type === "turn_end") {
|
|
275
|
+
turnCount += 1;
|
|
276
|
+
if (maxTurns !== undefined && !softLimitReached && turnCount >= maxTurns) {
|
|
277
|
+
softLimitReached = true;
|
|
278
|
+
void session?.steer?.("You have reached your turn limit. Wrap up immediately — provide your final answer now.");
|
|
279
|
+
} else if (maxTurns !== undefined && softLimitReached && turnCount >= maxTurns + graceTurns) {
|
|
280
|
+
void session?.abort?.();
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
input.onEvent?.(event);
|
|
284
|
+
const text = [...eventText(event), ...finalAssistantText(event)].join("\n");
|
|
285
|
+
if (text.trim()) {
|
|
286
|
+
stdout += `${text}\n`;
|
|
287
|
+
input.onOutput?.(text);
|
|
288
|
+
}
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
if (input.signal) {
|
|
292
|
+
if (input.signal.aborted) await session.abort?.();
|
|
293
|
+
else input.signal.addEventListener("abort", () => { void session?.abort?.(); }, { once: true });
|
|
294
|
+
}
|
|
295
|
+
const effectivePrompt = input.runtimeConfig?.inheritContext === true && input.parentContext ? `${input.parentContext}\n\n---\n# Live Subagent Task\n${input.prompt}` : input.prompt;
|
|
296
|
+
await session.prompt?.(effectivePrompt, { source: "api", expandPromptTemplates: false });
|
|
297
|
+
const usage = usageFromStats(typeof session.getStats === "function" ? session.getStats() : session.stats);
|
|
298
|
+
updateLiveAgentStatus(agentId, "completed");
|
|
299
|
+
return { available: true, exitCode: 0, stdout: stdout.trim(), stderr: created.modelFallbackMessage ?? "", jsonEvents, usage };
|
|
300
|
+
} catch (error) {
|
|
301
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
302
|
+
updateLiveAgentStatus(`${input.manifest.runId}:${input.task.id}`, "failed");
|
|
303
|
+
return { available: true, exitCode: 1, stdout: stdout.trim(), stderr: message, jsonEvents, error: message };
|
|
304
|
+
} finally {
|
|
305
|
+
if (controlTimer) clearInterval(controlTimer);
|
|
306
|
+
unsubscribeControlRealtime?.();
|
|
307
|
+
unsubscribe?.();
|
|
308
|
+
}
|
|
309
|
+
}
|