@aeondave/pi-persona 1.17.1 → 1.17.3
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/AGENTS.md +59 -28
- package/CHANGELOG.md +234 -0
- package/README.md +16 -12
- package/agents/architect.md +21 -0
- package/agents/balthasar.md +17 -22
- package/agents/casper.md +17 -23
- package/agents/evidence-verifier.md +31 -16
- package/agents/melchior.md +17 -22
- package/agents/operator.md +15 -55
- package/agents/research.md +14 -48
- package/agents/reviewer.md +20 -39
- package/agents/scout.md +14 -15
- package/agents/verifier.md +15 -16
- package/docs/ARCHITECTURE.md +183 -55
- package/docs/EXPERIENCE.md +19 -9
- package/docs/MONITORS.md +62 -3
- package/docs/REFERENCE.md +82 -32
- package/docs/SPINE.md +2 -2
- package/docs/STRATEGIES.md +23 -8
- package/docs/TELEMETRY.md +1 -0
- package/flows/deep-review.flow.json +1 -1
- package/package.json +9 -8
- package/personas/audit.md +28 -17
- package/personas/dev.md +30 -32
- package/personas/elite.md +223 -221
- package/personas/judge.md +25 -19
- package/personas/magi.md +26 -29
- package/personas/planner.md +31 -24
- package/personas/researcher.md +25 -26
- package/personas/swarm.md +35 -25
- package/personas/verify.md +30 -19
- package/src/agents/agent.ts +20 -0
- package/src/bridge.ts +3 -2
- package/src/core/brief.ts +429 -356
- package/src/core/config.ts +15 -10
- package/src/core/model-catalog.ts +171 -0
- package/src/core/model-tier.ts +89 -0
- package/src/core/models.ts +13 -4
- package/src/core/monitor-output.ts +85 -0
- package/src/core/monitor.ts +34 -2
- package/src/core/nudge.ts +176 -23
- package/src/core/seed.ts +99 -6
- package/src/core/session-runs.ts +87 -0
- package/src/core/settings.ts +1 -1
- package/src/core/timer.ts +34 -9
- package/src/engine/adapter.ts +12 -8
- package/src/engine/async.ts +165 -146
- package/src/engine/child.ts +2 -2
- package/src/engine/host-module.ts +12 -0
- package/src/engine/inproc.ts +12 -7
- package/src/engine/stream.ts +4 -20
- package/src/exocom/install.ts +2 -1
- package/src/extension/engine.ts +43 -16
- package/src/extension/hooks.ts +106 -36
- package/src/extension/persona-model-settings.ts +31 -13
- package/src/extension/shared.ts +15 -7
- package/src/extension.ts +505 -241
- package/src/monitor/archive.ts +235 -0
- package/src/monitor/session.ts +21 -1
- package/src/orchestration/flow-journal.ts +26 -5
- package/src/orchestration/flow-run.ts +38 -13
- package/src/orchestration/flow.ts +9 -2
- package/src/orchestration/reducers.ts +9 -5
- package/src/orchestration/render.ts +1 -1
- package/src/orchestration/sdk.ts +17 -5
- package/src/orchestration/strategies/compete.ts +5 -1
- package/src/orchestration/strategies/council-rounds.ts +2 -0
- package/src/orchestration/strategies/critic-loop.ts +3 -0
- package/src/orchestration/strategies/debate.ts +2 -0
- package/src/orchestration/strategies/fanout.ts +3 -2
- package/src/orchestration/strategies/judge.ts +5 -1
- package/src/orchestration/strategies/magi.ts +40 -23
- package/src/orchestration/strategies/map.ts +13 -3
- package/src/orchestration/strategies/pair.ts +2 -0
- package/src/orchestration/strategies/pipeline.ts +2 -0
- package/src/orchestration/strategies/synthesize.ts +27 -7
- package/src/orchestration/strategy.ts +31 -0
- package/src/persona/persona.ts +7 -3
- package/src/telemetry/contract.ts +1 -1
- package/src/tools/background-run.ts +151 -0
- package/src/tools/council.ts +77 -52
- package/src/tools/delegate-tool.ts +310 -280
- package/src/tools/delegate.ts +22 -210
- package/src/tools/exocom-work.ts +18 -53
- package/src/tools/exocom.ts +15 -19
- package/src/tools/flow.ts +85 -28
- package/src/tools/intercom-tool.ts +108 -118
- package/src/tools/intercom.ts +1 -1
- package/src/tools/models.ts +19 -9
- package/src/tools/monitor.ts +39 -6
- package/src/tools/timer.ts +11 -13
- package/src/ui/agent-overlay.ts +55 -14
- package/src/ui/agent-tree.ts +84 -18
- package/src/ui/compact-widget.ts +25 -0
- package/src/ui/failure-summary.ts +55 -0
- package/src/ui/literal-tool-result.ts +24 -0
- package/src/ui/model-picker.ts +158 -81
- package/src/ui/persona-settings.ts +9 -3
- package/src/ui/presentation.ts +24 -0
- package/src/ui/report-body.ts +63 -0
- package/src/ui/session-cards.ts +189 -0
- package/src/ui/wake-rows.ts +262 -0
- package/teams.yaml +5 -1
|
@@ -5,11 +5,13 @@
|
|
|
5
5
|
* comes from the roster's personas; bias guards live in the vote reducer.
|
|
6
6
|
*
|
|
7
7
|
* Reflection round (params.reflect, default ON): after the independent round, each
|
|
8
|
-
* core sees the
|
|
9
|
-
*
|
|
8
|
+
* core sees the PANEL's positions **anonymised** — its own among them, unmarked, because the
|
|
9
|
+
* reflecting leg is a fresh session and that list is its only memory of round 1 — and casts a
|
|
10
|
+
* FINAL vote, revising only if a genuinely new consideration moves it (holding is fine). This
|
|
10
11
|
* lets a core catch a blind spot without turning MAGI into groupthink: the positions
|
|
11
12
|
* are anonymised (no "defer to Casper" authority bias), it is exactly ONE round (not
|
|
12
|
-
* iterate-to-consensus — that is `council-rounds`), and dissent is always preserved.
|
|
13
|
+
* iterate-to-consensus — that is `council-rounds`), and dissent is always preserved. A core whose
|
|
14
|
+
* reflection leg fails keeps the valid vote it already cast (disclosed in the ruling footer).
|
|
13
15
|
* Set `reflect: false` for a pure independent poll (uncorrelated errors, cheapest).
|
|
14
16
|
*/
|
|
15
17
|
|
|
@@ -55,6 +57,8 @@ function rescuedModel(c: AgentResult | undefined): string | undefined {
|
|
|
55
57
|
|
|
56
58
|
export const magi: Strategy = {
|
|
57
59
|
name: "magi",
|
|
60
|
+
when: "contested fork: voters pick on a closed-choice question (yes/no, A/B); majority plus dissent",
|
|
61
|
+
team: "magi",
|
|
58
62
|
params: {
|
|
59
63
|
aggregate: { type: "string", default: "majority", doc: '"majority" | "unanimity"' },
|
|
60
64
|
reflect: { type: "boolean", default: true, doc: "one anonymised reflection round" },
|
|
@@ -88,7 +92,6 @@ export const magi: Strategy = {
|
|
|
88
92
|
return cancelled(round1.map((c) => c.usage));
|
|
89
93
|
}
|
|
90
94
|
|
|
91
|
-
let candidates = opening;
|
|
92
95
|
const okCount = opening.filter((c) => c.ok).length;
|
|
93
96
|
const tokensBeforeReflection = round1.reduce((total, result) => total + result.usage.input + result.usage.output, 0);
|
|
94
97
|
// A reflection is meaningful only when every core can participate. Under an active token
|
|
@@ -97,19 +100,19 @@ export const magi: Strategy = {
|
|
|
97
100
|
// goes for children: a rescue already spent a child per recovered core, and exceeding
|
|
98
101
|
// `maxChildren` THROWS out of sdk.agent() — turning a poll that has a ruling into no ruling.
|
|
99
102
|
const childrenUsed = round1.length + round1.filter((c) => c.modelRecovery).length;
|
|
100
|
-
const
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
}
|
|
103
|
+
const wantsReflection = reflect && okCount >= 2;
|
|
104
|
+
const skip = !wantsReflection ? undefined
|
|
105
|
+
: sdk.limits.budgetTokens > 0 && tokensBeforeReflection + team.length > sdk.limits.budgetTokens
|
|
106
|
+
? { why: "token budget", detail: `cannot fund the full panel (${sdk.limits.budgetTokens})` }
|
|
107
|
+
: childrenUsed + team.length > sdk.limits.maxChildren
|
|
108
|
+
? { why: "child budget", detail: `cannot fund the full panel (maxChildren ${sdk.limits.maxChildren}, ${childrenUsed} used)` }
|
|
109
|
+
: undefined;
|
|
110
|
+
const didReflect = wantsReflection && !skip;
|
|
111
|
+
if (skip) sdk.log(`magi: reflection skipped — ${skip.why} ${skip.detail}`);
|
|
110
112
|
|
|
113
|
+
let reflected: AgentResult[] = [];
|
|
111
114
|
if (didReflect) {
|
|
112
|
-
// Round 2 — each core sees the
|
|
115
|
+
// Round 2 — each core sees the panel's positions ANONYMISED (no author identity, so a
|
|
113
116
|
// core can't defer to a "senior" peer) and casts its FINAL vote. Instructed to hold
|
|
114
117
|
// unless genuinely moved, so this informs without manufacturing false consensus.
|
|
115
118
|
const positions = opening
|
|
@@ -123,7 +126,7 @@ export const magi: Strategy = {
|
|
|
123
126
|
// The recovered model must survive into this round: rebuilding from `rosterSpec(m)` alone
|
|
124
127
|
// would hand the rescued core back the model that just broke, so it fails again, is
|
|
125
128
|
// quarantined as invalid, and the recovery buys nothing but tokens.
|
|
126
|
-
|
|
129
|
+
reflected = await sdk.parallel(
|
|
127
130
|
team.map((m, i) => () => {
|
|
128
131
|
const model = rescuedModel(opening[i]);
|
|
129
132
|
return sdk.agent({ ...rosterSpec(m), ...(model ? { model } : {}), task: reflectTask, outputContract: "default" });
|
|
@@ -134,11 +137,23 @@ export const magi: Strategy = {
|
|
|
134
137
|
// DURING the reflection round is visible here only as every core settling
|
|
135
138
|
// `failureKind: "abort"` — as is one on a caller that passed no signal. Without the
|
|
136
139
|
// second clause a stopped run reports a normal-looking "no ruling" from a killed poll.
|
|
137
|
-
if (sdk.signal?.aborted ||
|
|
138
|
-
return cancelled([...round1, ...
|
|
140
|
+
if (sdk.signal?.aborted || reflected.every((c) => c.failureKind === "abort")) {
|
|
141
|
+
return cancelled([...round1, ...reflected].map((c) => c.usage));
|
|
139
142
|
}
|
|
140
143
|
}
|
|
141
|
-
|
|
144
|
+
// A reflection leg that FAILED (timeout, provider, contract...) is a missing second opinion, not a
|
|
145
|
+
// missing voter: the core keeps the valid vote it already cast, so a 3-core poll stays a 3-core
|
|
146
|
+
// poll. A STOPPED leg is never substituted. The substituted vote is not billed again (`allRuns`).
|
|
147
|
+
const ballots = didReflect
|
|
148
|
+
? reflected.map((r, i) => {
|
|
149
|
+
const first = opening[i];
|
|
150
|
+
return !r.ok && r.failureKind !== "abort" && first?.ok ? first : r;
|
|
151
|
+
})
|
|
152
|
+
: opening;
|
|
153
|
+
const kept = didReflect ? ballots.filter((b, i) => b !== reflected[i]).length : 0;
|
|
154
|
+
// "Reflected" means at least one core cast a second-round vote; a round that failed everywhere changed nothing.
|
|
155
|
+
const reflectedAny = didReflect && kept < ballots.length;
|
|
156
|
+
const decision = sdk.reduce.vote(ballots, { aggregate, keepBestFallback: true });
|
|
142
157
|
|
|
143
158
|
// Lead with the ruling (the answer); the decision/tally plumbing is a compact footer,
|
|
144
159
|
// not the headline. The collapsed council card shows `headline`; the supervisor still
|
|
@@ -156,8 +171,10 @@ export const magi: Strategy = {
|
|
|
156
171
|
const rescuedLine = rescued.length > 0
|
|
157
172
|
? ` · ${rescued.length} core${rescued.length === 1 ? "" : "s"} recovered on ${[...new Set(rescued.map((c) => c.modelRecovery?.to ?? ""))].filter(Boolean).join(", ")}`
|
|
158
173
|
: "";
|
|
174
|
+
const keptLine = kept > 0 ? ` · ${kept} core${kept === 1 ? "" : "s"} kept their round-1 vote (reflection failed)` : "";
|
|
175
|
+
const skipLine = skip ? ` · reflection skipped (${skip.why})` : "";
|
|
159
176
|
lines.push(
|
|
160
|
-
`\n— magi: ${decision.status}${
|
|
177
|
+
`\n— magi: ${decision.status}${reflectedAny ? " (after 1 reflection round)" : ""}${decision.usedFallback ? " · fell back to best-by-confidence" : ""} · tally ${tally}${invalid}${rescuedLine}${keptLine}${skipLine}`,
|
|
161
178
|
);
|
|
162
179
|
|
|
163
180
|
const winnerResult = decision.winner?.structured?.result;
|
|
@@ -170,16 +187,16 @@ export const magi: Strategy = {
|
|
|
170
187
|
// Usage sums EVERY run the poll actually paid for: the opening round (each logical result
|
|
171
188
|
// already carries its rescue's tokens exactly once) and the reflection round, kept separate
|
|
172
189
|
// from the opening one when reflection ran.
|
|
173
|
-
const allRuns: AgentResult[] =
|
|
190
|
+
const allRuns: AgentResult[] = [...round1, ...reflected];
|
|
174
191
|
const result: AgentResult = {
|
|
175
192
|
agent: "magi",
|
|
176
193
|
output: lines.join("\n"),
|
|
177
|
-
structured: { status: decision.status, tally: decision.tally, usedFallback: decision.usedFallback, reflected:
|
|
194
|
+
structured: { status: decision.status, tally: decision.tally, usedFallback: decision.usedFallback, reflected: reflectedAny, headline },
|
|
178
195
|
usage: sumUsage(allRuns.map((c) => c.usage)),
|
|
179
196
|
ok: decision.winner !== undefined,
|
|
180
197
|
};
|
|
181
198
|
if (!result.ok) {
|
|
182
|
-
const cause = summarizeFailedResults(
|
|
199
|
+
const cause = summarizeFailedResults(ballots, "magi produced no ruling");
|
|
183
200
|
result.error = cause.error;
|
|
184
201
|
result.failureKind = cause.failureKind;
|
|
185
202
|
}
|
|
@@ -16,6 +16,7 @@ import { fenceUntrusted } from "../../core/fence.ts";
|
|
|
16
16
|
import { cappedList } from "../../core/format.ts";
|
|
17
17
|
import { validateParallelWriteSets } from "../../core/ownership.ts";
|
|
18
18
|
import type { ChildUsage } from "../../engine/stream.ts";
|
|
19
|
+
import { compactInlineText } from "../../ui/presentation.ts";
|
|
19
20
|
import { itemLedger, type ItemLedgerEntry, sumUsage } from "../reducers.ts";
|
|
20
21
|
import { parseAuxActor } from "../params.ts";
|
|
21
22
|
import { rosterSpec, type RosterMember, type RosterSpec } from "../roster.ts";
|
|
@@ -144,10 +145,16 @@ async function splitIntoItems(
|
|
|
144
145
|
task: string,
|
|
145
146
|
maxItems: number,
|
|
146
147
|
reserveChildren: number,
|
|
148
|
+
declareWriteSets: boolean,
|
|
147
149
|
): Promise<SplitOutcome> {
|
|
150
|
+
// With ownership on, the splitter is the only party that can declare each item's write set, so it is asked
|
|
151
|
+
// for the object shape itself: one instruction, not a string array here and objects in the caller's prose.
|
|
152
|
+
const shape = declareWriteSets
|
|
153
|
+
? 'a JSON array of {"item": "<short description>", "writeSet": ["<every path a worker would edit>"]} objects (use [] for a read-only item)'
|
|
154
|
+
: "a JSON array of short strings";
|
|
148
155
|
const split = await sdk.agent({
|
|
149
156
|
...splitter,
|
|
150
|
-
task: `Break this task into independent sub-items. Return ONLY
|
|
157
|
+
task: `Break this task into independent sub-items. Return ONLY ${shape} — one per sub-item, nothing else.\n\nTask: ${task}`,
|
|
151
158
|
}, { reserveChildren });
|
|
152
159
|
if (!split.ok) {
|
|
153
160
|
return {
|
|
@@ -263,6 +270,9 @@ function buildItemLedger(
|
|
|
263
270
|
|
|
264
271
|
export const map: Strategy = {
|
|
265
272
|
name: "map",
|
|
273
|
+
when: "N items found at runtime: splitter lists, worker handles each in parallel",
|
|
274
|
+
roster: "[splitter, worker]",
|
|
275
|
+
team: "swarm",
|
|
266
276
|
params: {
|
|
267
277
|
maxItems: { type: "number", doc: "default AND ceiling: the run's maxChildren, less the splitter's own slot" },
|
|
268
278
|
peers: { type: "boolean", default: false, doc: "workers share load-bearing cross-item discoveries live" },
|
|
@@ -304,7 +314,7 @@ export const map: Strategy = {
|
|
|
304
314
|
// conservative upper bound; the cap above already guarantees the reserved waves fit.
|
|
305
315
|
const maxWorkerItems = Math.max(0, Math.floor(maxItems));
|
|
306
316
|
const splitReserve = maxWorkerItems * (reviewer ? 2 : 1);
|
|
307
|
-
const split = await splitIntoItems(sdk, splitter, input.task, maxItems, splitReserve);
|
|
317
|
+
const split = await splitIntoItems(sdk, splitter, input.task, maxItems, splitReserve, ownership !== "off");
|
|
308
318
|
if (!split.ok) return split.result;
|
|
309
319
|
const { allItems, items, dropped, usage: splitUsage } = split;
|
|
310
320
|
sdk.log(`map: ${items.length} items → ${worker.agent}${peers ? " (cross-talk on)" : ""}`);
|
|
@@ -317,7 +327,7 @@ export const map: Strategy = {
|
|
|
317
327
|
if (ownership === "enforce") enforceOwnershipOrThrow(items);
|
|
318
328
|
|
|
319
329
|
const results = await runWorkers(sdk, worker, input.task, items, peers, reviewer ? items.length : 0);
|
|
320
|
-
const agg = sdk.reduce.aggregate(results);
|
|
330
|
+
const agg = sdk.reduce.aggregate(results, items.map((it, i) => `item ${i + 1}: ${compactInlineText(it.item, { maxChars: 60 })}`));
|
|
321
331
|
// Say what was left out. The clamp is right — a worker per item past the cap would trip the
|
|
322
332
|
// pre-spawn guard and lose the whole fan-out — but an aggregate that silently covers part of
|
|
323
333
|
// the splitter's list reads as a complete answer over an incomplete input set.
|
|
@@ -35,6 +35,8 @@ const NAVIGATOR_PROTOCOL = [
|
|
|
35
35
|
|
|
36
36
|
export const pair: Strategy = {
|
|
37
37
|
name: "pair",
|
|
38
|
+
when: "one member works, a navigator reviews live",
|
|
39
|
+
roster: "[driver, navigator]",
|
|
38
40
|
async run(input, sdk) {
|
|
39
41
|
const team = input.roster ? sdk.roster.team(input.roster) : [];
|
|
40
42
|
if (team.length < 2) throw new Error("pair: a roster of [driver, navigator] is required");
|
|
@@ -44,6 +44,8 @@ function failed(results: AgentResult[], upstream: string, step: AgentResult): Ag
|
|
|
44
44
|
|
|
45
45
|
export const pipeline: Strategy = {
|
|
46
46
|
name: "pipeline",
|
|
47
|
+
when: "ad-hoc ordered stages you name (no installed flow needed): each member refines the previous output; the last answer is the result",
|
|
48
|
+
roster: "stages, in order",
|
|
47
49
|
async run(input, sdk) {
|
|
48
50
|
const team = input.roster ? sdk.roster.team(input.roster) : [];
|
|
49
51
|
if (team.length === 0) throw new Error("pipeline: a non-empty roster is required");
|
|
@@ -10,8 +10,9 @@
|
|
|
10
10
|
* peers?: boolean (gatherers share contradictions/corroborations live — default off) }
|
|
11
11
|
*/
|
|
12
12
|
|
|
13
|
-
import { rosterSpec } from "../roster.ts";
|
|
13
|
+
import { rosterNodeKeys, rosterSpec } from "../roster.ts";
|
|
14
14
|
import { fenceUntrusted } from "../../core/fence.ts";
|
|
15
|
+
import { sanitizeStatusLabel } from "../../core/display-label.ts";
|
|
15
16
|
import { parseAuxActor } from "../params.ts";
|
|
16
17
|
import { sumUsage, summarizeFailedResults } from "../reducers.ts";
|
|
17
18
|
import type { Strategy } from "../sdk.ts";
|
|
@@ -28,6 +29,9 @@ const CROSS_TALK = [
|
|
|
28
29
|
|
|
29
30
|
export const synthesize: Strategy = {
|
|
30
31
|
name: "synthesize",
|
|
32
|
+
when: "many angles into ONE deliverable: gatherers in parallel, one synthesiser merges",
|
|
33
|
+
roster: "gatherers",
|
|
34
|
+
team: "review",
|
|
31
35
|
params: {
|
|
32
36
|
// The default IS roster[0] — declared as `rosterIndex`, never as an agent name: the
|
|
33
37
|
// participant collector resolves "override, else roster[rosterIndex], else `default`",
|
|
@@ -61,10 +65,12 @@ export const synthesize: Strategy = {
|
|
|
61
65
|
}, { reserveChildren: 1 }), // leave the mandatory merge slot; SDK reserves queued gatherers
|
|
62
66
|
),
|
|
63
67
|
);
|
|
64
|
-
|
|
68
|
+
// Lens-aware labels (`reviewer · SECURITY`): the synthesizer must see WHICH lens found what.
|
|
69
|
+
const labels = rosterNodeKeys(team);
|
|
70
|
+
const usable = results.flatMap((r, i) => (r.ok && r.output.trim() ? [{ label: labels[i], output: r.output.trim() }] : []));
|
|
65
71
|
if (usable.length === 0) {
|
|
66
72
|
const cause = summarizeFailedResults(results, "no gatherer produced output");
|
|
67
|
-
const reasons = results.map((r) => `[${
|
|
73
|
+
const reasons = results.map((r, i) => `[${labels[i]}] ${r.error ?? "(no output)"}`).join("; ");
|
|
68
74
|
return {
|
|
69
75
|
agent: "synthesize",
|
|
70
76
|
output: `(no gatherer produced output: ${reasons})`,
|
|
@@ -74,13 +80,27 @@ export const synthesize: Strategy = {
|
|
|
74
80
|
failureKind: cause.failureKind,
|
|
75
81
|
};
|
|
76
82
|
}
|
|
83
|
+
// A partial merge is useful, but a missing review lens is not a clean review. Carry the
|
|
84
|
+
// runtime coverage into BOTH the merger's input and its returned output, even if it omits it.
|
|
85
|
+
const missing = results.flatMap((r, i) => r.ok && r.output.trim() ? [] : [{
|
|
86
|
+
member: sanitizeStatusLabel(labels[i] ?? r.agent),
|
|
87
|
+
status: r.ok ? "empty" : "failed",
|
|
88
|
+
detail: sanitizeStatusLabel(r.ok ? "no output" : r.error ?? "no failure detail", "no failure detail", 200),
|
|
89
|
+
}]);
|
|
90
|
+
const coverage = missing.length > 0 ? { expected: team.length, usable: usable.length, missing } : undefined;
|
|
91
|
+
const coverageNote = coverage ? [
|
|
92
|
+
`Incomplete coverage: ${usable.length}/${team.length} gatherers returned usable findings. Missing members were not reviewed; do not present this as a complete review.`,
|
|
93
|
+
fenceUntrusted(missing.slice(0, 16).map((m) => `${m.member} — ${m.status}: ${m.detail}`).join("\n")),
|
|
94
|
+
...(missing.length > 16 ? [`${missing.length - 16} additional missing members are recorded in the result's coverage metadata.`] : []),
|
|
95
|
+
].join("\n") : "";
|
|
77
96
|
|
|
78
|
-
const sections = usable.map((
|
|
97
|
+
const sections = usable.map((u) => `--- [${u.label}] ---\n${fenceUntrusted(u.output)}`).join("\n\n");
|
|
79
98
|
const final = await sdk.agent({
|
|
80
99
|
...synthesizer,
|
|
81
100
|
task:
|
|
82
101
|
`Synthesise the findings below into ONE coherent, de-duplicated answer to the task. ` +
|
|
83
102
|
`Resolve contradictions explicitly (say which finding you trusted and why) and keep every load-bearing detail.\n\n` +
|
|
103
|
+
(coverageNote ? `${coverageNote}\n\n` : "") +
|
|
84
104
|
`Task: ${input.task}\n\nFindings:\n${sections}`,
|
|
85
105
|
});
|
|
86
106
|
|
|
@@ -88,12 +108,12 @@ export const synthesize: Strategy = {
|
|
|
88
108
|
// the synthesiser's `result` field if it emitted one, else the first non-empty line.
|
|
89
109
|
const firstLine = final.output.split("\n").map((l) => l.trim()).find((l) => l.length > 0) ?? "";
|
|
90
110
|
const structuredResult = final.structured?.result;
|
|
91
|
-
const headline =
|
|
111
|
+
const headline = `${coverage ? `Incomplete coverage: ${usable.length}/${team.length} · ` : ""}${typeof structuredResult === "string" && structuredResult.trim() ? structuredResult : firstLine}`.slice(0, 120);
|
|
92
112
|
|
|
93
113
|
const result: AgentResult = {
|
|
94
114
|
agent: "synthesize",
|
|
95
|
-
output: final.output,
|
|
96
|
-
structured: { ...(final.structured ?? {}), gatherers: usable.length, headline },
|
|
115
|
+
output: coverageNote ? `${coverageNote}\n\n${final.output}` : final.output,
|
|
116
|
+
structured: { ...(final.structured ?? {}), gatherers: usable.length, headline, ...(coverage ? { coverage } : {}) },
|
|
97
117
|
usage: sumUsage([...results, final].map((r) => r.usage)),
|
|
98
118
|
ok: final.ok,
|
|
99
119
|
};
|
|
@@ -47,3 +47,34 @@ export function knownParams(name: string): Record<string, StrategyParam> | undef
|
|
|
47
47
|
const strategy = BUILTINS[name];
|
|
48
48
|
return strategy ? (strategy.params ?? {}) : undefined;
|
|
49
49
|
}
|
|
50
|
+
|
|
51
|
+
/** One line per strategy for the council tool's description, generated from the registry:
|
|
52
|
+
* `- name(params, required*) — when; roster: positions; default team X.` Guidance on which method fits a
|
|
53
|
+
* problem class lives with the method, so it cannot drift from what the code does. */
|
|
54
|
+
export function strategyCatalog(): string {
|
|
55
|
+
return strategyNames()
|
|
56
|
+
.map((name) => {
|
|
57
|
+
const s = BUILTINS[name] as Strategy;
|
|
58
|
+
const keys = Object.keys(s.params ?? {}).map((k) => (s.required?.includes(k) ? `${k}*` : k));
|
|
59
|
+
const head = `- ${name}${keys.length > 0 ? `(${keys.join(", ")})` : ""}`;
|
|
60
|
+
// `magi` is the fallback every call already gets, so only a different default team is worth a mention.
|
|
61
|
+
const team = s.team && s.team !== "magi" ? `; default team ${s.team}` : "";
|
|
62
|
+
return `${head}${s.when ? ` — ${s.when}` : ""}${s.roster ? `; roster: ${s.roster}` : ""}${team}.`;
|
|
63
|
+
})
|
|
64
|
+
.join("\n");
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Refuse a council call that cannot run, BEFORE any run, tree row or model picker exists: a
|
|
68
|
+
* `required` param that is missing or blank (blank counts as missing, exactly as the strategies'
|
|
69
|
+
* own `parseAuxActor` reads it). `undefined` means the call is sound. An UNKNOWN strategy is not
|
|
70
|
+
* judged here: the run itself fails with the installed list (an interactive council reports that in
|
|
71
|
+
* its completion follow-up, not in the launching call). */
|
|
72
|
+
export function missingRequiredParams(name: string, params: Record<string, unknown>): string | undefined {
|
|
73
|
+
const strategy = BUILTINS[name];
|
|
74
|
+
const missing = (strategy?.required ?? []).filter((key) => {
|
|
75
|
+
const value = params[key];
|
|
76
|
+
return value === undefined || value === null || (typeof value === "string" && !value.trim());
|
|
77
|
+
});
|
|
78
|
+
if (missing.length === 0) return undefined;
|
|
79
|
+
return `"${name}" requires ${missing.map((key) => `params.${key} — ${strategy?.params?.[key]?.doc ?? "required"}`).join("; ")}`;
|
|
80
|
+
}
|
package/src/persona/persona.ts
CHANGED
|
@@ -11,6 +11,7 @@ import { asBoolean, asPermission, asStringArray, parseYamlSubset, splitFrontmatt
|
|
|
11
11
|
import type { Permission } from "../core/permissions.ts";
|
|
12
12
|
import { asSystemPromptMode, type SystemPromptMode } from "../core/types.ts";
|
|
13
13
|
import { parseRuntimeRosterMember, type RosterMember } from "../orchestration/roster.ts";
|
|
14
|
+
import { getStrategy } from "../orchestration/strategy.ts";
|
|
14
15
|
|
|
15
16
|
export type OrchestrationMode = "solo" | "parallel" | "pipeline" | "strategy" | "flow";
|
|
16
17
|
const ORCHESTRATION_MODES: readonly OrchestrationMode[] = ["solo", "parallel", "pipeline", "strategy", "flow"];
|
|
@@ -323,16 +324,19 @@ export function resolveCouncilInvocation(
|
|
|
323
324
|
if (!parsed.ok) return { ok: false, error: parsed.error };
|
|
324
325
|
members = parsed.members;
|
|
325
326
|
}
|
|
327
|
+
// A call that switches to another method starts from THAT method's team and params: the profile's roster and
|
|
328
|
+
// params belong to the profile's own strategy (dev's `repair` pair would otherwise be seated as magi voters).
|
|
329
|
+
const switched = strategy !== (base?.strategy || "magi");
|
|
326
330
|
const roster = members
|
|
327
331
|
? ""
|
|
328
332
|
: request.roster?.trim() ||
|
|
333
|
+
(switched ? getStrategy(strategy)?.team : undefined) ||
|
|
329
334
|
base?.roster ||
|
|
330
335
|
sourcePersona?.orchestration?.roster ||
|
|
331
336
|
(!requestedName ? activePersona?.orchestration?.roster : undefined) ||
|
|
332
337
|
"magi";
|
|
333
|
-
//
|
|
334
|
-
|
|
335
|
-
const inheritedParams = strategy !== (base?.strategy || "magi") ? {} : base?.params ?? {};
|
|
338
|
+
// Only explicitly supplied params cross a strategy switch.
|
|
339
|
+
const inheritedParams = switched ? {} : base?.params ?? {};
|
|
336
340
|
const value: ResolvedCouncilInvocation = {
|
|
337
341
|
strategy,
|
|
338
342
|
roster,
|
|
@@ -4,7 +4,7 @@ export const TELEMETRY_EVENT_NAME = "pi:telemetry" as const;
|
|
|
4
4
|
export const LEGACY_TELEMETRY_EVENT_NAME = "pi-persona:telemetry" as const;
|
|
5
5
|
export const LEGACY_TELEMETRY_VERSION = 1 as const;
|
|
6
6
|
export const TELEMETRY_PRODUCER_ID = "pi-persona" as const;
|
|
7
|
-
export const TELEMETRY_PRODUCER_VERSION = "1.17.
|
|
7
|
+
export const TELEMETRY_PRODUCER_VERSION = "1.17.3" as const;
|
|
8
8
|
|
|
9
9
|
export type InstanceStatus = "active" | "idle" | "stopped" | "stale" | (string & {});
|
|
10
10
|
export type AgentKind = "subagent" | "delegate" | "council" | "flow" | "phase" | (string & {});
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `council` and `flow` as ONE tracked run (the same machinery `delegate` uses): a visible strategy or
|
|
3
|
+
* flow is launched into the {@link AsyncRunTracker}, rooted in the agent tree at `async:<runId>`, and
|
|
4
|
+
* reachable through the stop key `async:<runId>`: `intercom stop`, stop all, and `x` on the run's root row
|
|
5
|
+
* in the f9 overlay all end the whole run. Interactive sessions get a receipt at once and ONE completion
|
|
6
|
+
* follow-up (`renderCompletion`); headless sessions join the same run before the tool returns, so the
|
|
7
|
+
* single turn carries the result.
|
|
8
|
+
*
|
|
9
|
+
* Which semaphore gates what:
|
|
10
|
+
* - `slots` is the launch pool `delegate` already uses (`maxConcurrency`). A council or flow takes ONE
|
|
11
|
+
* slot for the whole run, exactly like one delegate leg, and shows `queued` until it has it.
|
|
12
|
+
* - The strategy SDK's own per-run semaphore (`orchestration/sdk.ts`) gates the legs INSIDE the run, so
|
|
13
|
+
* a council's members never compete with delegate legs for these slots and cannot deadlock on them.
|
|
14
|
+
* A flow parked at a human checkpoint keeps its slot for the wait: the operator owns that wait, and
|
|
15
|
+
* stopping the run releases it.
|
|
16
|
+
* - Token budgets, the child limit and the fork-bomb guard live in that SDK and the engine, untouched.
|
|
17
|
+
*/
|
|
18
|
+
import { END_TURN_NOTE } from "../core/brief.ts";
|
|
19
|
+
import type { ChildUsage } from "../engine/stream.ts";
|
|
20
|
+
import { emptyUsage } from "../engine/stream.ts";
|
|
21
|
+
import type { AgentResult } from "../orchestration/types.ts";
|
|
22
|
+
import type { Semaphore } from "../orchestration/parallel.ts";
|
|
23
|
+
import { madeHeadway, type AsyncRun, type AsyncRunTracker, type IdleCoalescingNotifier, type ProgressReading } from "../engine/async.ts";
|
|
24
|
+
import type { AgentTree } from "../ui/agent-tree.ts";
|
|
25
|
+
import type { ChildUsageLedger } from "../ui/usage.ts";
|
|
26
|
+
|
|
27
|
+
/** What a visible runner is handed when it works for a tracked run (absent ⇒ it roots and stops itself). */
|
|
28
|
+
export interface TrackedRun {
|
|
29
|
+
/** The tree root of this run: `async:<runId>`. Its nodes hang under it. */
|
|
30
|
+
rootId: string;
|
|
31
|
+
/** Fires when the run is stopped — by key, by `intercom stop`, or by the headless tool call's abort. */
|
|
32
|
+
signal: AbortSignal;
|
|
33
|
+
/** Interactive: the launching turn has ended and the supervisor is idle, so a coached leg may block on an
|
|
34
|
+
* ask (the run's engines are built `async`). Headless: the call is parked in the turn and could not answer. */
|
|
35
|
+
background: boolean;
|
|
36
|
+
/** One leg progressed: feeds the run's cumulative tokens, and its stall clock when the leg made headway. */
|
|
37
|
+
onProgress(leg: string, progress: ProgressReading): void;
|
|
38
|
+
/** The run is blocked on the operator (a flow checkpoint) — or released again (`undefined`). */
|
|
39
|
+
onAwaiting(label: string | undefined): void;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface BackgroundRunDeps {
|
|
43
|
+
tracker: AsyncRunTracker;
|
|
44
|
+
agentTree: AgentTree;
|
|
45
|
+
stopRegistry: Map<string, () => void>;
|
|
46
|
+
/** The launch pool shared with `delegate` (see the module comment). */
|
|
47
|
+
slots: Semaphore;
|
|
48
|
+
completionNotifier: Pick<IdleCoalescingNotifier<AsyncRun>, "discard">;
|
|
49
|
+
startPeek(): void;
|
|
50
|
+
childUsage: ChildUsageLedger;
|
|
51
|
+
publishPersonaCost(): void;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** `inline` (headless) skips the status monitor: the launching call joins the run and nobody reads a status card. */
|
|
55
|
+
export interface LaunchMeta { kind: "council" | "flow"; label: string; task: string; inline: boolean }
|
|
56
|
+
|
|
57
|
+
type RunWork = (run: TrackedRun) => Promise<AgentResult>;
|
|
58
|
+
|
|
59
|
+
/** The receipt an interactive `council`/`flow` launch returns. `wake` finishes "you will be woken ONCE ...". */
|
|
60
|
+
export function launchReceipt(kind: LaunchMeta["kind"], id: string, subject: string, wake: string): string {
|
|
61
|
+
return `Launched ${kind} ${id} (${subject}) in the background — you will be woken ONCE ${wake} (${END_TURN_NOTE}).`;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export interface BackgroundRuns {
|
|
65
|
+
/** Launch `work` as one tracked run and return its id. */
|
|
66
|
+
launch(meta: LaunchMeta, work: RunWork): string;
|
|
67
|
+
/** Join launched runs (headless): wait for all of them, stop them if `signal` aborts, drop the follow-ups
|
|
68
|
+
* this return replaces, and bill their usage once. `onSettled` sees each settle as (done, total). */
|
|
69
|
+
settle(ids: readonly string[], signal: AbortSignal | undefined, onSettled?: (done: number, total: number) => void): Promise<{ runs: AsyncRun[]; usage: ChildUsage }>;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function createBackgroundRuns(d: BackgroundRunDeps): BackgroundRuns {
|
|
73
|
+
function launch(meta: LaunchMeta, work: RunWork): string {
|
|
74
|
+
// `mutates`: a strategy's legs and their tool grants are decided leg by leg inside the run, so the run
|
|
75
|
+
// is classed as a potential writer — the fail-closed answer for a persona's fresh-verification policy
|
|
76
|
+
// (whose refusal says "may mutate", which is all this classification knows).
|
|
77
|
+
const id = d.tracker.launch({ agent: meta.label, task: meta.task, label: meta.label, mutates: true, queued: true }, (onProgress, runId) => {
|
|
78
|
+
const rootId = `async:${runId}`;
|
|
79
|
+
const ac = new AbortController();
|
|
80
|
+
d.stopRegistry.set(rootId, () => ac.abort());
|
|
81
|
+
const legSeen = new Map<string, ProgressReading>();
|
|
82
|
+
const legTokens = new Map<string, number>();
|
|
83
|
+
const snapshot = (output = ""): { output: string; turns: number; tokens: number } => ({ output, turns: 0, tokens: [...legTokens.values()].reduce((a, b) => a + b, 0) });
|
|
84
|
+
const run: TrackedRun = {
|
|
85
|
+
rootId,
|
|
86
|
+
signal: ac.signal,
|
|
87
|
+
background: !meta.inline,
|
|
88
|
+
onProgress: (leg, progress) => {
|
|
89
|
+
// Headway is judged per leg - the run's own snapshot is only their token sum - by the same rule a
|
|
90
|
+
// delegate leg is held to, so one chatty tool in one leg cannot keep the whole run looking alive.
|
|
91
|
+
if (madeHeadway(legSeen.get(leg), progress)) d.tracker.advance(runId);
|
|
92
|
+
legSeen.set(leg, progress);
|
|
93
|
+
legTokens.set(leg, progress.tokens ?? legTokens.get(leg) ?? 0);
|
|
94
|
+
onProgress(snapshot());
|
|
95
|
+
},
|
|
96
|
+
onAwaiting: (label) => {
|
|
97
|
+
d.tracker.setAwaiting(runId, label);
|
|
98
|
+
},
|
|
99
|
+
};
|
|
100
|
+
return d.slots
|
|
101
|
+
.with(async () => {
|
|
102
|
+
d.tracker.markAdmitted(runId);
|
|
103
|
+
const result = await work(run);
|
|
104
|
+
// A ruling or plan that did not complete lives in `result.output`, but a failed or stopped run's
|
|
105
|
+
// report salvages the tracker's `progress.output` — hand it over so that work is not lost.
|
|
106
|
+
if (!result.ok && result.output) onProgress(snapshot(result.output));
|
|
107
|
+
return result;
|
|
108
|
+
}, ac.signal)
|
|
109
|
+
.catch((error: unknown): AgentResult => {
|
|
110
|
+
if (!ac.signal.aborted) throw error;
|
|
111
|
+
return { agent: meta.label, output: "", usage: emptyUsage(), ok: false, error: "run aborted", failureKind: "abort" };
|
|
112
|
+
});
|
|
113
|
+
});
|
|
114
|
+
// Visible while queued, so `x` and the tree's stop work before the pool grants a slot; the visible runner
|
|
115
|
+
// upserts this same row when it starts.
|
|
116
|
+
d.agentTree.add({ id: `async:${id}`, label: meta.label, kind: meta.kind, status: "running", detail: "queued" });
|
|
117
|
+
if (!meta.inline) d.startPeek();
|
|
118
|
+
return id;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
async function settle(ids: readonly string[], signal: AbortSignal | undefined, onSettled?: (done: number, total: number) => void): Promise<{ runs: AsyncRun[]; usage: ChildUsage }> {
|
|
122
|
+
const runs = ids.flatMap((id) => d.tracker.peek(id) ?? []); // launch() registers each, and a running entry is never evicted
|
|
123
|
+
const stopAll = (): void => {
|
|
124
|
+
for (const id of ids) d.stopRegistry.get(`async:${id}`)?.();
|
|
125
|
+
};
|
|
126
|
+
if (signal?.aborted) stopAll();
|
|
127
|
+
else signal?.addEventListener("abort", stopAll, { once: true });
|
|
128
|
+
try {
|
|
129
|
+
if (runs.some((run) => !run.settled)) {
|
|
130
|
+
await new Promise<void>((resolve) => {
|
|
131
|
+
const off = d.tracker.onComplete(() => {
|
|
132
|
+
const done = runs.filter((run) => run.settled).length;
|
|
133
|
+
onSettled?.(done, runs.length);
|
|
134
|
+
if (done === runs.length) {
|
|
135
|
+
off();
|
|
136
|
+
resolve();
|
|
137
|
+
}
|
|
138
|
+
});
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
} finally {
|
|
142
|
+
signal?.removeEventListener("abort", stopAll);
|
|
143
|
+
}
|
|
144
|
+
d.completionNotifier.discard((pending) => ids.includes(pending.id)); // this return IS the delivery
|
|
145
|
+
const usage = d.childUsage.accountMany(runs.map((run) => ({ key: run.id, usage: run.result?.usage ?? emptyUsage() })));
|
|
146
|
+
d.publishPersonaCost();
|
|
147
|
+
return { runs, usage };
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
return { launch, settle };
|
|
151
|
+
}
|