amicus 4.2.1 → 4.4.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.
- package/.claude-plugin/plugin.json +1 -1
- package/CHANGELOG.md +46 -1
- package/README.md +8 -4
- package/bin/amicus.js +5 -0
- package/electron/ipc-workspace.js +283 -0
- package/electron/main.js +27 -0
- package/electron/preload-workspace.js +40 -0
- package/electron/workspace-shell.js +85 -0
- package/electron/workspace-ui/index.html +111 -0
- package/electron/workspace-ui/live-model.js +101 -0
- package/electron/workspace-ui/md-lite.js +119 -0
- package/electron/workspace-ui/workspace-app.js +240 -0
- package/electron/workspace-ui/workspace-matrix.js +212 -0
- package/electron/workspace-ui/workspace-panels.js +226 -0
- package/electron/workspace-ui/workspace-render.js +271 -0
- package/electron/workspace-ui/workspace-verbs.js +247 -0
- package/electron/workspace-ui/workspace.css +172 -0
- package/package.json +1 -1
- package/schemas/council-run-live.schema.json +57 -0
- package/schemas/council-run.schema.json +14 -0
- package/schemas/event.schema.json +15 -0
- package/schemas/progress.schema.json +37 -0
- package/schemas/run-live.schema.json +15 -0
- package/schemas/spend.schema.json +26 -1
- package/schemas/wave-live.schema.json +15 -0
- package/skills/second-opinion/MODEL-NOTES.md +53 -5
- package/src/cli-handlers-council-run.js +86 -8
- package/src/cli-handlers-run.js +26 -0
- package/src/cli-handlers-spend.js +94 -32
- package/src/cli-handlers-watch.js +116 -0
- package/src/cli.js +58 -1
- package/src/council/briefings.js +35 -2
- package/src/council/run-budget.js +224 -0
- package/src/council/run-chair.js +10 -2
- package/src/council/run-debate.js +5 -1
- package/src/council/run-launch.js +58 -7
- package/src/council/run-stages.js +30 -3
- package/src/council/run.js +44 -15
- package/src/headless.js +356 -15
- package/src/mcp-council-awareness.js +98 -3
- package/src/mcp-council-run.js +28 -4
- package/src/mcp-notify.js +54 -0
- package/src/mcp-server.js +51 -1
- package/src/mcp-spend.js +125 -0
- package/src/mcp-tools.js +39 -0
- package/src/mcp-wait.js +28 -2
- package/src/observe/council-legs.js +183 -0
- package/src/observe/events.js +156 -0
- package/src/observe/follow.js +26 -0
- package/src/observe/live-doc.js +56 -0
- package/src/observe/on-complete.js +117 -0
- package/src/observe/watch-render.js +168 -0
- package/src/opencode-client.js +15 -3
- package/src/sidecar/child-sessions.js +198 -0
- package/src/sidecar/continue.js +32 -0
- package/src/sidecar/conversation-mirror.js +111 -37
- package/src/sidecar/fallback-chains.js +65 -0
- package/src/sidecar/fanout-budget.js +71 -0
- package/src/sidecar/fanout-leg-fallback.js +189 -0
- package/src/sidecar/fanout-leg.js +81 -27
- package/src/sidecar/fanout-retry.js +208 -0
- package/src/sidecar/fanout-validate.js +42 -4
- package/src/sidecar/fanout.js +54 -41
- package/src/sidecar/progress.js +5 -0
- package/src/sidecar/resume.js +12 -0
- package/src/sidecar/start.js +13 -1
- package/src/sidecar/tool-part.js +196 -0
- package/src/sidecar/workspace-window.js +62 -0
- package/src/spend-query.js +119 -0
- package/src/utils/env-num.js +42 -0
- package/src/utils/error-classify.js +31 -0
- package/src/utils/model-tiers.js +1 -1
- package/src/utils/path-fence.js +82 -0
- package/src/utils/pricing.js +98 -9
- package/src/utils/spend-ledger.js +24 -1
- package/src/workspace/artifact-guard.js +187 -0
- package/src/workspace/blind-mode.js +32 -0
- package/src/workspace/fold-format.js +95 -0
- package/src/workspace/live-normalize.js +156 -0
- package/src/workspace/matrix-model.js +94 -0
- package/src/workspace/run-detail.js +223 -0
- package/src/workspace/run-scan.js +148 -0
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
// src/sidecar/tool-part.js
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* @module sidecar/tool-part
|
|
6
|
+
* OpenCode's TOOL-PART shape and its status vocabulary (v4.4 B4 part 1).
|
|
7
|
+
*
|
|
8
|
+
* WHY THIS EXISTS. The mirror used to model a tool call as an Anthropic-style
|
|
9
|
+
* `tool_use` part cleared by a matching `tool_result` part carrying
|
|
10
|
+
* `tool_use_id`. **OpenCode has no such part type.** Established empirically
|
|
11
|
+
* before designing against it (see tests/sidecar/tool-part-status.test.js for
|
|
12
|
+
* the full derivation):
|
|
13
|
+
*
|
|
14
|
+
* - 5,129 persisted parts in this machine's OpenCode database resolve to
|
|
15
|
+
* exactly six `type` values: text, step-start, reasoning, step-finish,
|
|
16
|
+
* tool, patch. No `tool_result`. No `tool_use`.
|
|
17
|
+
* - The 35 recorded legs of `council-wsgate01/`..`council-wsgate04/` wrote
|
|
18
|
+
* **36 `tool_use` records and ZERO `tool_result` records**. So the
|
|
19
|
+
* diagnosis's proposed `pendingToolCalls.length === 0` gate, keyed on a
|
|
20
|
+
* `tool_result` that never arrives, would have hung every tool-using leg
|
|
21
|
+
* to its full `--timeout`.
|
|
22
|
+
*
|
|
23
|
+
* THE REAL SHAPE (@opencode-ai/sdk `ToolPart`):
|
|
24
|
+
* `{id, sessionID, messageID, type:'tool', callID, tool:<name>, state}`
|
|
25
|
+
* where `state` is the `ToolState` union.
|
|
26
|
+
*
|
|
27
|
+
* STATUS VOCABULARY:
|
|
28
|
+
* - DECLARED by the SDK's `ToolState` union: 'pending' | 'running' |
|
|
29
|
+
* 'completed' | 'error'.
|
|
30
|
+
* - OBSERVED across all 1,307 persisted tool parts: completed 1148,
|
|
31
|
+
* error 150, running 9. 'pending' is declared but never persisted — it is
|
|
32
|
+
* the pre-execution transient (`{input, raw}`, no `time` at all).
|
|
33
|
+
* - TERMINAL is 'completed' | 'error', verified structurally: all 1,298
|
|
34
|
+
* terminal parts carry `state.time.end`; all 9 non-terminal parts carry
|
|
35
|
+
* `state.time.start` and no `end`. Disjoint and exhaustive.
|
|
36
|
+
*
|
|
37
|
+
* The 9 `running` parts are LEFTOVERS — `time_updated` within milliseconds of
|
|
38
|
+
* `time_created`, all from three killed sessions that never wrote a terminal
|
|
39
|
+
* status. A stale non-terminal status can therefore persist forever, which is
|
|
40
|
+
* why any wait keyed on this vocabulary MUST be bounded (headless.js's
|
|
41
|
+
* TOOL_SETTLE_GRACE_MS).
|
|
42
|
+
*/
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* The statuses that mean "this tool call is finished and its session is no
|
|
46
|
+
* longer working on it". Anything else — including an unrecognised or absent
|
|
47
|
+
* status — is treated as still live: terminality is never INVENTED, it must be
|
|
48
|
+
* positively observed.
|
|
49
|
+
* @type {Set<string>}
|
|
50
|
+
*/
|
|
51
|
+
const TERMINAL_TOOL_STATUSES = new Set(['completed', 'error']);
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* The statuses that POSITIVELY tell us OpenCode is still working on a tool call.
|
|
55
|
+
*
|
|
56
|
+
* This is deliberately NOT `!TERMINAL` — the difference is the anti-hang
|
|
57
|
+
* guarantee. A tool part carrying no `state` at all (the legacy `tool_use`
|
|
58
|
+
* shape, which the repo's own fixtures still emit) gives us no evidence in
|
|
59
|
+
* either direction, and deferring a leg's completion on an ABSENCE of evidence
|
|
60
|
+
* is precisely how a completion gate hangs. So:
|
|
61
|
+
*
|
|
62
|
+
* - `getPendingToolCalls` = not-yet-terminal, INCLUDING unknown shape.
|
|
63
|
+
* Feeds B53's wedge detector, whose whole job is the no-evidence case, and
|
|
64
|
+
* whose semantics are therefore unchanged.
|
|
65
|
+
* - `getLiveToolCalls` = positively observed 'pending' or 'running'.
|
|
66
|
+
* Feeds the v4.4 completion gate: it will only ever hold a leg open on
|
|
67
|
+
* evidence that the session really is still working.
|
|
68
|
+
* @type {Set<string>}
|
|
69
|
+
*/
|
|
70
|
+
const LIVE_TOOL_STATUSES = new Set(['pending', 'running']);
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Is this part a tool call at all? Accepts OpenCode's real `'tool'` type and
|
|
74
|
+
* the legacy `'tool_use'` shape that older fixtures/providers emit.
|
|
75
|
+
* @param {object} part
|
|
76
|
+
* @returns {boolean}
|
|
77
|
+
*/
|
|
78
|
+
function isToolPart(part) {
|
|
79
|
+
return !!part && (part.type === 'tool' || part.type === 'tool_use');
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* The tool's name. Reads OpenCode's real field (`part.tool`) and falls back to
|
|
84
|
+
* the legacy `part.name`. The mirror previously read ONLY `part.name`, which
|
|
85
|
+
* the real shape never has — which is why all 36 recorded tool records carry an
|
|
86
|
+
* id and nothing else, and why headless.js's `Task`-subagent summary log was
|
|
87
|
+
* permanently empty.
|
|
88
|
+
* @param {object} part
|
|
89
|
+
* @returns {string|undefined}
|
|
90
|
+
*/
|
|
91
|
+
function toolPartName(part) {
|
|
92
|
+
if (!part) { return undefined; }
|
|
93
|
+
return part.tool !== undefined ? part.tool : part.name;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* The tool's input. Real shape carries it on `state.input`; the legacy shape on
|
|
98
|
+
* `part.input`.
|
|
99
|
+
* @param {object} part
|
|
100
|
+
* @returns {object|undefined}
|
|
101
|
+
*/
|
|
102
|
+
function toolPartInput(part) {
|
|
103
|
+
if (!part) { return undefined; }
|
|
104
|
+
if (part.state && part.state.input !== undefined) { return part.state.input; }
|
|
105
|
+
return part.input;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Has this tool call reached a TERMINAL status? A part with no `state` (the
|
|
110
|
+
* legacy shape) is NOT settled — unknown status must never read as "finished",
|
|
111
|
+
* which is what keeps B53's wedge detection working on legacy fixtures.
|
|
112
|
+
* @param {object} part
|
|
113
|
+
* @returns {boolean}
|
|
114
|
+
*/
|
|
115
|
+
function isToolPartSettled(part) {
|
|
116
|
+
const status = toolPartStatus(part);
|
|
117
|
+
return typeof status === 'string' && TERMINAL_TOOL_STATUSES.has(status);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* The observed `state.status`, or undefined when the part carries no state
|
|
122
|
+
* (legacy shape) — "unknown", which is NOT the same as either terminal or live.
|
|
123
|
+
* @param {object} part
|
|
124
|
+
* @returns {string|undefined}
|
|
125
|
+
*/
|
|
126
|
+
function toolPartStatus(part) {
|
|
127
|
+
const status = part && part.state && part.state.status;
|
|
128
|
+
return typeof status === 'string' && status !== '' ? status : undefined;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Is this tool call POSITIVELY observed as still executing? See
|
|
133
|
+
* LIVE_TOOL_STATUSES for why this is not simply `!isToolPartSettled`.
|
|
134
|
+
* @param {object} part
|
|
135
|
+
* @returns {boolean}
|
|
136
|
+
*/
|
|
137
|
+
function isToolPartLive(part) {
|
|
138
|
+
const status = toolPartStatus(part);
|
|
139
|
+
return status !== undefined && LIVE_TOOL_STATUSES.has(status);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Is this a SUBAGENT (child-session) tool call? OpenCode names it `task`
|
|
144
|
+
* (lowercase — the pre-existing `t.name === 'Task'` comparison in headless.js
|
|
145
|
+
* could never match, a second bug on top of the missing `part.tool` read).
|
|
146
|
+
*
|
|
147
|
+
* This is the signal for B4: a `task` call spawns a CHILD OpenCode session
|
|
148
|
+
* whose spend is billed separately and is NOT rolled into the parent session's
|
|
149
|
+
* cost, so a leg that made one has cost we cannot claim to know. Verified 1:1
|
|
150
|
+
* on the recorded corpus — exactly 2 `task` calls across 37 sessions, and
|
|
151
|
+
* exactly 2 child sessions, each parented by the calling leg's session
|
|
152
|
+
* (wsgate01-s1-2 → $0.021460, wsgate02-s1-3 → $0.471046).
|
|
153
|
+
* @param {{name?: string}} toolCall a recorded {id,name,input} entry
|
|
154
|
+
* @returns {boolean}
|
|
155
|
+
*/
|
|
156
|
+
function isSubagentToolCall(toolCall) {
|
|
157
|
+
const name = toolCall && toolCall.name;
|
|
158
|
+
return typeof name === 'string' && name.toLowerCase() === 'task';
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Tool calls that have NOT reached a terminal `state.status` — as far as we can
|
|
163
|
+
* observe, OpenCode may still be working on them and the session may still be
|
|
164
|
+
* billing. INCLUDES the unknown-shape case (no `state` at all). Feeds the
|
|
165
|
+
* headless poll loop's B53 wedge detector, whose whole purpose is that case.
|
|
166
|
+
*
|
|
167
|
+
* v4.4 B4 part 1: this used to clear only on a `tool_result` part carrying
|
|
168
|
+
* `tool_use_id` — a part type OpenCode never emits (0 of 36 recorded tool
|
|
169
|
+
* records) — so it never cleared for any real leg. It is now driven by the real
|
|
170
|
+
* `state.status` vocabulary, with the legacy `tool_result` path kept for
|
|
171
|
+
* back-compat. Returns a fresh array; `state.pendingToolCalls` is the live
|
|
172
|
+
* source of truth.
|
|
173
|
+
* @param {{pendingToolCalls: Map}} state from createMirrorState()
|
|
174
|
+
* @returns {Array<{id:string,name:string,status:string|undefined,firstSeenAt:string}>}
|
|
175
|
+
*/
|
|
176
|
+
function getPendingToolCalls(state) {
|
|
177
|
+
return Array.from(state.pendingToolCalls.values());
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Tool calls POSITIVELY observed as still executing. A strict SUBSET of
|
|
182
|
+
* getPendingToolCalls — see LIVE_TOOL_STATUSES for why the difference is the
|
|
183
|
+
* anti-hang guarantee. This is what the v4.4 completion gate reads.
|
|
184
|
+
* @param {{pendingToolCalls: Map}} state from createMirrorState()
|
|
185
|
+
* @returns {Array<{id:string,name:string,status:string,firstSeenAt:string}>}
|
|
186
|
+
*/
|
|
187
|
+
function getLiveToolCalls(state) {
|
|
188
|
+
return getPendingToolCalls(state)
|
|
189
|
+
.filter((t) => t.status !== undefined && LIVE_TOOL_STATUSES.has(t.status));
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
module.exports = {
|
|
193
|
+
TERMINAL_TOOL_STATUSES, LIVE_TOOL_STATUSES, isToolPart, toolPartName, toolPartInput,
|
|
194
|
+
toolPartStatus, isToolPartSettled, isToolPartLive, isSubagentToolCall,
|
|
195
|
+
getPendingToolCalls, getLiveToolCalls,
|
|
196
|
+
};
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Council Workspace launcher (v4.4 §4.3/§4.4) — setup-window.js pattern:
|
|
3
|
+
* ensureElectron() (the one place provisioning is allowed, #55) → spawn
|
|
4
|
+
* electron/main.js in council-workspace mode. Unlike setup (which buffers),
|
|
5
|
+
* this RELAYS child stdout live — the nonced fold block must reach the
|
|
6
|
+
* launching terminal's command output verbatim. Exit code propagates
|
|
7
|
+
* (0 on fold-then-close and on plain close).
|
|
8
|
+
*/
|
|
9
|
+
'use strict';
|
|
10
|
+
|
|
11
|
+
const { spawn } = require('child_process');
|
|
12
|
+
const path = require('path');
|
|
13
|
+
const { logger } = require('../utils/logger');
|
|
14
|
+
const { getElectronPath } = require('./interactive-process');
|
|
15
|
+
const { ensureElectron } = require('./electron-ensure');
|
|
16
|
+
const { generateFoldNonce } = require('../utils/fold-marker');
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* @param {{project: string, runId?: string}} opts
|
|
20
|
+
* @param {{ensureElectron?: Function, spawn?: Function, nonce?: string}} [deps] test injection
|
|
21
|
+
* @returns {Promise<{code: number, error?: string}>}
|
|
22
|
+
*/
|
|
23
|
+
async function launchWorkspaceWindow({ project, runId = '' }, deps = {}) {
|
|
24
|
+
const ensure = deps.ensureElectron || ensureElectron;
|
|
25
|
+
const spawnFn = deps.spawn || spawn;
|
|
26
|
+
const ensured = await ensure();
|
|
27
|
+
if (!ensured.ok) {
|
|
28
|
+
return { code: 1, error: ensured.reason || 'Electron not installed' };
|
|
29
|
+
}
|
|
30
|
+
return new Promise((resolve) => {
|
|
31
|
+
const electronPath = ensured.path || getElectronPath();
|
|
32
|
+
const mainPath = path.join(__dirname, '..', '..', 'electron', 'main.js');
|
|
33
|
+
const env = {
|
|
34
|
+
...process.env,
|
|
35
|
+
AMICUS_MODE: 'council-workspace',
|
|
36
|
+
AMICUS_PROJECT: project,
|
|
37
|
+
AMICUS_RUN_ID: runId || '',
|
|
38
|
+
AMICUS_FOLD_NONCE: deps.nonce || generateFoldNonce(),
|
|
39
|
+
};
|
|
40
|
+
const debugPort = process.env.AMICUS_DEBUG_PORT;
|
|
41
|
+
const args = debugPort ? [`--remote-debugging-port=${debugPort}`, mainPath] : [mainPath];
|
|
42
|
+
logger.info('Launching council workspace', { runId: runId || '(run list)', debugPort: debugPort || 'disabled' });
|
|
43
|
+
|
|
44
|
+
const proc = spawnFn(electronPath, args, { env, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
45
|
+
|
|
46
|
+
proc.stdout.setEncoding('utf-8');
|
|
47
|
+
proc.stdout.on('data', (chunk) => { process.stdout.write(chunk); }); // fold relay — live, verbatim
|
|
48
|
+
proc.stderr.setEncoding('utf-8');
|
|
49
|
+
proc.stderr.on('data', (chunk) => { logger.debug('Workspace stderr', { data: String(chunk).trim() }); });
|
|
50
|
+
|
|
51
|
+
proc.on('error', (err) => {
|
|
52
|
+
logger.error('Workspace failed to spawn', { error: err.message });
|
|
53
|
+
resolve({ code: 1, error: `Failed to start workspace: ${err.message}` });
|
|
54
|
+
});
|
|
55
|
+
proc.on('close', (code) => {
|
|
56
|
+
logger.info('Workspace closed', { code });
|
|
57
|
+
resolve({ code: code === null ? 1 : code });
|
|
58
|
+
});
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
module.exports = { launchWorkspaceWindow };
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// src/spend-query.js
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* @module spend-query
|
|
6
|
+
* Pure query/rollup helpers for `amicus spend` (spec §7.3 filters/group-by,
|
|
7
|
+
* §6.3/resolved Q6 `wasted`). Split out of src/cli-handlers-spend.js (which
|
|
8
|
+
* re-exports these) to stay under the 300-line size gate — see that file's
|
|
9
|
+
* module docblock. No I/O, no CLI concerns: everything here is rows-in,
|
|
10
|
+
* rows/rollup-out and independently testable.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Valid `--group-by`/`groupBy` dimensions — the SINGLE source of truth shared
|
|
15
|
+
* by the CLI's validity check (cli-handlers-spend.js), the MCP `amicus_spend`
|
|
16
|
+
* tool's `groupBy` Zod enum (mcp-tools.js), and rowKey()'s switch below. Do
|
|
17
|
+
* NOT hand-copy this array elsewhere: a 7th dimension added here must reach
|
|
18
|
+
* both surfaces automatically, not just the one someone remembered to edit.
|
|
19
|
+
*/
|
|
20
|
+
const GROUP_DIMS = ['model', 'wave', 'council', 'project', 'op', 'day'];
|
|
21
|
+
|
|
22
|
+
/** Cap on rows returned when a caller opts into raw rows (CLI --rows / MCP rows:true). */
|
|
23
|
+
const ROWS_CAP = 1000;
|
|
24
|
+
|
|
25
|
+
function emptyTokens() {
|
|
26
|
+
return { input: 0, output: 0, reasoning: 0, cacheRead: 0, cacheWrite: 0 };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function addTokens(into, tokens) {
|
|
30
|
+
if (!tokens) { return; }
|
|
31
|
+
for (const k of Object.keys(into)) { into[k] += tokens[k] || 0; }
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Pure row filter over the additive attribution fields (spec 7.3). */
|
|
35
|
+
function filterRows(rows, f = {}) {
|
|
36
|
+
const cutoff = (f.since !== undefined && f.since !== null && f.now !== undefined) ? f.now - f.since * 86400000 : null;
|
|
37
|
+
return rows.filter((r) => {
|
|
38
|
+
if (f.wave && r.waveId !== f.wave) { return false; }
|
|
39
|
+
if (f.council && r.councilRunId !== f.council && r.councilName !== f.council) { return false; }
|
|
40
|
+
if (f.project && r.project !== f.project) { return false; }
|
|
41
|
+
if (f.model && !String(r.model || '').startsWith(f.model)) { return false; }
|
|
42
|
+
if (f.op && r.op !== f.op) { return false; }
|
|
43
|
+
if (f.failed && (r.status === 'complete' || !r.status)) { return false; }
|
|
44
|
+
if (cutoff !== null) { const t = Date.parse(r.ts); if (!Number.isFinite(t) || t < cutoff) { return false; } }
|
|
45
|
+
return true;
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** dimension -> row key. null/absent -> '(unattributed)'. `day` = the ISO date. */
|
|
50
|
+
function rowKey(row, dimension) {
|
|
51
|
+
switch (dimension) {
|
|
52
|
+
case 'model': return row.model || '(unattributed)';
|
|
53
|
+
case 'wave': return row.waveId || '(unattributed)';
|
|
54
|
+
case 'council': return row.councilRunId || row.councilName || '(unattributed)';
|
|
55
|
+
case 'project': return row.project || '(unattributed)';
|
|
56
|
+
case 'op': return row.op || '(unattributed)';
|
|
57
|
+
case 'day': return typeof row.ts === 'string' ? row.ts.slice(0, 10) : '(unattributed)';
|
|
58
|
+
default: return '(unattributed)';
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Group rows into {key, amount, tokens, runs, unpricedRows, sourceMix},
|
|
64
|
+
* most-expensive first.
|
|
65
|
+
*
|
|
66
|
+
* v4.4: `amount` deliberately stays a plain number — the published
|
|
67
|
+
* spend.schema.json pins `groups[].amount` to `type: "number"` — so
|
|
68
|
+
* `unpricedRows` is how a group says "this figure omits N rows we cannot
|
|
69
|
+
* price". Without it, a group of entirely unpriced rows was indistinguishable
|
|
70
|
+
* from a group that genuinely cost $0 (diagnosis §8).
|
|
71
|
+
*/
|
|
72
|
+
function groupRows(rows, dimension) {
|
|
73
|
+
const map = new Map();
|
|
74
|
+
for (const r of rows) {
|
|
75
|
+
const key = rowKey(r, dimension);
|
|
76
|
+
if (!map.has(key)) { map.set(key, { key, amount: 0, tokens: emptyTokens(), runs: 0, unpricedRows: 0, sourceMix: { reported: 0, estimated: 0, unknown: 0 } }); }
|
|
77
|
+
const b = map.get(key);
|
|
78
|
+
b.runs += 1;
|
|
79
|
+
addTokens(b.tokens, r.tokens);
|
|
80
|
+
const cost = r.cost || {};
|
|
81
|
+
if (typeof cost.amount === 'number') { b.amount += cost.amount; } else { b.unpricedRows += 1; }
|
|
82
|
+
const src = (cost.source === 'reported' || cost.source === 'estimated') ? cost.source : 'unknown';
|
|
83
|
+
b.sourceMix[src] += 1;
|
|
84
|
+
}
|
|
85
|
+
return [...map.values()].sort((a, b) => b.amount - a.amount);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Wasted spend = every row with an EXPLICIT non-complete status, bucketed by
|
|
90
|
+
* status (spec 6.3, resolved Q6). A row with status null/absent (pre-v4.3,
|
|
91
|
+
* or any row that never reached a terminal status write) is deliberately
|
|
92
|
+
* EXCLUDED here — not "complete" and not "wasted" — because we cannot know
|
|
93
|
+
* whether that historical run actually failed; counting it would fabricate
|
|
94
|
+
* a failure that was never recorded. Contrast with groupRows(), where a null
|
|
95
|
+
* dimension is a first-class '(unattributed)' bucket (grouping never drops
|
|
96
|
+
* a row); computeWasted intentionally drops it instead.
|
|
97
|
+
*/
|
|
98
|
+
function computeWasted(rows) {
|
|
99
|
+
const out = { amount: 0, tokens: emptyTokens(), runs: 0, unpricedRows: 0, byStatus: {} };
|
|
100
|
+
for (const r of rows) {
|
|
101
|
+
if (r.status === 'complete' || !r.status) { continue; }
|
|
102
|
+
out.runs += 1;
|
|
103
|
+
addTokens(out.tokens, r.tokens);
|
|
104
|
+
// v4.4: null→0 here is arithmetic, not a claim. `unpricedRows` records how
|
|
105
|
+
// many failed rows we could not price so "wasted $X" is never mistaken for
|
|
106
|
+
// the whole loss (see groupRows for why `amount` stays a number).
|
|
107
|
+
const priced = r.cost && typeof r.cost.amount === 'number';
|
|
108
|
+
const amt = priced ? r.cost.amount : 0;
|
|
109
|
+
if (!priced) { out.unpricedRows += 1; }
|
|
110
|
+
out.amount += amt;
|
|
111
|
+
if (!out.byStatus[r.status]) { out.byStatus[r.status] = { amount: 0, runs: 0, unpricedRows: 0 }; }
|
|
112
|
+
out.byStatus[r.status].amount += amt;
|
|
113
|
+
out.byStatus[r.status].runs += 1;
|
|
114
|
+
if (!priced) { out.byStatus[r.status].unpricedRows += 1; }
|
|
115
|
+
}
|
|
116
|
+
return out;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
module.exports = { filterRows, groupRows, computeWasted, emptyTokens, addTokens, GROUP_DIMS, ROWS_CAP };
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// src/utils/env-num.js
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* @module utils/env-num
|
|
6
|
+
* Numeric environment override that HONORS an explicit `0`.
|
|
7
|
+
*
|
|
8
|
+
* WHY THIS EXISTS. The idiom `Number(process.env.X) || DEFAULT` is wrong for any
|
|
9
|
+
* knob whose "off" value is `0`, because `0` is falsy and is therefore rewritten
|
|
10
|
+
* back into `DEFAULT`. v4.4 shipped four such knobs — `AMICUS_USAGE_SETTLE_POLLS`,
|
|
11
|
+
* `AMICUS_USAGE_SETTLE_INTERVAL_MS`, `AMICUS_USAGE_SETTLE_CALL_TIMEOUT_MS` and
|
|
12
|
+
* `AMICUS_TOOL_SETTLE_GRACE_MS` — each documenting `0` as the disable switch in
|
|
13
|
+
* its docblock and (for the last one) in the CHANGELOG, while making that switch
|
|
14
|
+
* unreachable from the environment. The operator could read the escape hatch and
|
|
15
|
+
* not use it.
|
|
16
|
+
*
|
|
17
|
+
* SEMANTICS. An explicit, finite numeric value always wins, `0` included. Unset,
|
|
18
|
+
* blank/whitespace-only, and non-finite values fall back to the default:
|
|
19
|
+
* - blank matters because `Number('') === 0`, so a bare `export AMICUS_X=` would
|
|
20
|
+
* otherwise read as an intentional disable rather than the accident it is;
|
|
21
|
+
* - non-finite matters because `Number('Infinity')` would otherwise be fed
|
|
22
|
+
* straight into `setTimeout`/comparison arithmetic.
|
|
23
|
+
*
|
|
24
|
+
* NOT A BLANKET REPLACEMENT. Several older knobs (`AMICUS_POLL_INTERVAL_MS`,
|
|
25
|
+
* `AMICUS_STABLE_*_POLLS`, `AMICUS_TOOL_CALL_STALL_MS`, `AMICUS_MAX_SESSIONS`, …)
|
|
26
|
+
* deliberately keep `||`: `0` is not a documented escape hatch for any of them and
|
|
27
|
+
* honoring it would busy-loop a poller or silently disable a stall guard. Migrate a
|
|
28
|
+
* knob to this helper only when `0` is a value its call site actually understands.
|
|
29
|
+
*
|
|
30
|
+
* @param {string} name environment variable name
|
|
31
|
+
* @param {number} dflt value used when unset / blank / non-finite
|
|
32
|
+
* @param {object} [env] environment object (test seam; defaults to process.env)
|
|
33
|
+
* @returns {number}
|
|
34
|
+
*/
|
|
35
|
+
function envNumber(name, dflt, env) {
|
|
36
|
+
const raw = (env || process.env)[name];
|
|
37
|
+
if (raw === undefined || raw === null || String(raw).trim() === '') { return dflt; }
|
|
38
|
+
const n = Number(raw);
|
|
39
|
+
return Number.isFinite(n) ? n : dflt;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
module.exports = { envNumber };
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @module error-classify
|
|
5
|
+
* Conservative classification of an OpenCode leg-error string into a trigger
|
|
6
|
+
* class (spec 6.2). Fallback substitution fires ONLY on capacity signals
|
|
7
|
+
* (rate-limit|overload). timeout is excluded (resolved Q3: a slow model on a
|
|
8
|
+
* heavy task is not a capacity signal — --retry-failed covers it); auth /
|
|
9
|
+
* validation never substitute. Misclassification cost is bounded either way:
|
|
10
|
+
* one extra cheaper attempt, or status quo.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
const RATE_LIMIT = /429|rate ?limit|too many requests|quota|resource exhausted/i;
|
|
14
|
+
const OVERLOAD = /529|503|overload|capacity|server busy|service unavailable/i;
|
|
15
|
+
const AUTH = /401|403|unauthorized|forbidden|invalid api key|authentication/i;
|
|
16
|
+
const TIMEOUT = /timed? ?out|timeout|deadline exceeded/i;
|
|
17
|
+
|
|
18
|
+
/** @param {string} message @returns {'rate-limit'|'overload'|'auth'|'timeout'|'other'} */
|
|
19
|
+
function classifyLegError(message) {
|
|
20
|
+
const m = String(message || '');
|
|
21
|
+
if (RATE_LIMIT.test(m)) { return 'rate-limit'; }
|
|
22
|
+
if (OVERLOAD.test(m)) { return 'overload'; }
|
|
23
|
+
if (AUTH.test(m)) { return 'auth'; }
|
|
24
|
+
if (TIMEOUT.test(m)) { return 'timeout'; }
|
|
25
|
+
return 'other';
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Only capacity signals trigger a cheaper-model substitution. */
|
|
29
|
+
function isRetryable(cls) { return cls === 'rate-limit' || cls === 'overload'; }
|
|
30
|
+
|
|
31
|
+
module.exports = { classifyLegError, isRetryable };
|
package/src/utils/model-tiers.js
CHANGED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared realpath-containment fence.
|
|
3
|
+
*
|
|
4
|
+
* Single source of truth for "is this resolved path inside that resolved
|
|
5
|
+
* directory" — the primitive that defeats symlink escapes AND tampered/stale
|
|
6
|
+
* pointer files (a `council-<id>.json` pointer's `runDir` is validated only
|
|
7
|
+
* for truthiness by src/council/run-state.js's readPointer, so nothing
|
|
8
|
+
* upstream of this check guarantees it stays inside the project).
|
|
9
|
+
*
|
|
10
|
+
* It is a LEAF: `fs` + `path` and nothing else, no require cycle possible.
|
|
11
|
+
* That was first needed inside the v4.4 workspace layer —
|
|
12
|
+
* src/workspace/artifact-guard.js requires src/workspace/run-scan.js for
|
|
13
|
+
* readPointer, so if run-scan.js also required artifact-guard.js for this
|
|
14
|
+
* helper, the two would require each other and one side's destructured import
|
|
15
|
+
* would silently resolve to undefined depending on load order.
|
|
16
|
+
*
|
|
17
|
+
* It lives in src/utils/ rather than src/workspace/ because its consumers are
|
|
18
|
+
* no longer all workspace modules: the shipped v4.3 surfaces
|
|
19
|
+
* (src/mcp-council-awareness.js behind amicus_status / amicus_abort /
|
|
20
|
+
* amicus_list, src/cli-handlers-watch.js and src/observe/watch-render.js behind
|
|
21
|
+
* `amicus watch`) fence the same pointer with the same check. Keeping it under
|
|
22
|
+
* src/workspace/ would have made three stable shipped surfaces depend on a
|
|
23
|
+
* feature directory added in v4.4 — the only inverted require in the tree, and
|
|
24
|
+
* one that would turn any future reorganisation of that layer into a breaking
|
|
25
|
+
* change for those tools. src/utils/ is the neutral layer src/workspace/
|
|
26
|
+
* already depends on (formatCost, fold-marker), so the arrow now points one way.
|
|
27
|
+
*/
|
|
28
|
+
'use strict';
|
|
29
|
+
|
|
30
|
+
const fs = require('fs');
|
|
31
|
+
const path = require('path');
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* True when `targetRealPath` is exactly `dirRealPath` or a proper descendant
|
|
35
|
+
* of it. Both arguments MUST already be resolved through realpathSync — this
|
|
36
|
+
* is a pure string-prefix check.
|
|
37
|
+
* @param {string} dirRealPath
|
|
38
|
+
* @param {string} targetRealPath
|
|
39
|
+
* @returns {boolean}
|
|
40
|
+
*/
|
|
41
|
+
function isRealpathContained(dirRealPath, targetRealPath) {
|
|
42
|
+
const dir = String(dirRealPath);
|
|
43
|
+
const target = String(targetRealPath);
|
|
44
|
+
if (target === dir) { return true; }
|
|
45
|
+
// ⚠️ COUNCIL REVIEW R2 (A6): when dirRealPath IS a filesystem root, it already
|
|
46
|
+
// ends in a separator ('/' on POSIX, 'C:\\' on Windows) — blindly appending
|
|
47
|
+
// another (the old `dirRealPath + path.sep`) doubles it ('//' / 'C:\\\\'), and
|
|
48
|
+
// no real path ever starts with that, so containment silently returned false
|
|
49
|
+
// for every path under a root dirRealPath. Only append the separator when it
|
|
50
|
+
// isn't already there.
|
|
51
|
+
const base = dir.endsWith(path.sep) ? dir : dir + path.sep;
|
|
52
|
+
// The separator-qualified prefix (not a bare `startsWith(dir)`) is what defeats
|
|
53
|
+
// the sibling-prefix trap: '/foobar' must not be considered inside '/foo'.
|
|
54
|
+
return target.startsWith(base);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Fail-closed, disk-resolving form of isRealpathContained: resolves BOTH
|
|
59
|
+
* arguments through realpathSync and applies the same containment test.
|
|
60
|
+
* Returns false when either side cannot be resolved — a missing directory, a
|
|
61
|
+
* dangling symlink, a permission error, or a non-string `targetPath` straight
|
|
62
|
+
* out of a hand-edited pointer file — so an unresolvable path is REFUSED
|
|
63
|
+
* rather than trusted.
|
|
64
|
+
*
|
|
65
|
+
* The v4.4 workspace consumers keep calling isRealpathContained directly
|
|
66
|
+
* because each has to tell "unreadable" apart from "escapes" in the error row
|
|
67
|
+
* it renders. The v4.3 CLI/MCP consumers (src/mcp-council-awareness.js,
|
|
68
|
+
* src/cli-handlers-watch.js, src/observe/watch-render.js) collapse every
|
|
69
|
+
* failure into one outcome — no payload / skip the row / kind 'unknown' — so
|
|
70
|
+
* they take this boolean form instead of repeating the two try/catch blocks at
|
|
71
|
+
* four more call sites.
|
|
72
|
+
* @param {string} dirPath
|
|
73
|
+
* @param {string} targetPath
|
|
74
|
+
* @returns {boolean}
|
|
75
|
+
*/
|
|
76
|
+
function containsOnDisk(dirPath, targetPath) {
|
|
77
|
+
try {
|
|
78
|
+
return isRealpathContained(fs.realpathSync(dirPath), fs.realpathSync(targetPath));
|
|
79
|
+
} catch { return false; }
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
module.exports = { isRealpathContained, containsOnDisk };
|