aegiscode 7.0.7 → 7.0.9

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.
@@ -828,16 +828,35 @@ function rollTurn(roll, usage, opts = {}) {
828
828
  // number, and what stops the total standing still on exactly the turns the
829
829
  // pool declined to report on — the symptom this fallback exists to remove.
830
830
  const est = estimatedBuckets(opts.prompt, opts.reply, opts.reasoning);
831
+ // Thinking tokens the provider MEASURED, not estimated. On a subscription
832
+ // turn the deliberation text is withheld entirely (every real
833
+ // `thinking_delta` carries `thinking: ""`), so `estimatedBuckets` above
834
+ // cannot see the longest, priciest part of the turn and the live preview
835
+ // read 0 for the whole thinking phase. Added verbatim — it is already a
836
+ // token count, and it is billed output exactly as the reply is.
837
+ const measured =
838
+ typeof opts.measuredReasoningTokens === 'number' && opts.measuredReasoningTokens > 0
839
+ ? opts.measuredReasoningTokens
840
+ : 0;
831
841
  if (!est) {
832
- // Nothing reported AND no text to estimate from. The single case that
833
- // stays uncounted: `unknown` names the gap, where a fabricated zero would
834
- // read as a measurement.
835
- next.unknown += 1;
842
+ // A subscription turn with nothing written yet but thinking under way is
843
+ // NOT the `unknown` case: the provider measured it, so a zero would be a
844
+ // fabricated reading rather than an absent one.
845
+ if (!measured) {
846
+ // Nothing reported AND no text to estimate from. The single case that
847
+ // stays uncounted: `unknown` names the gap, where a fabricated zero
848
+ // would read as a measurement.
849
+ next.unknown += 1;
850
+ return next;
851
+ }
852
+ next.tokens += measured;
853
+ next.output += measured;
854
+ next.estimated += 1;
836
855
  return next;
837
856
  }
838
- next.tokens += est.input + est.output;
857
+ next.tokens += est.input + est.output + measured;
839
858
  next.input += est.input;
840
- next.output += est.output;
859
+ next.output += est.output + measured;
841
860
  next.estimated += 1;
842
861
  return next;
843
862
  }
@@ -0,0 +1,287 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
+ // Conveying a modified copy, or running one as a network service, owes the
5
+ // corresponding source under this licence (§5/§13) — see LICENSING.md.
6
+ 'use strict';
7
+
8
+ /**
9
+ * child.js — the Claude child's argv, DERIVED (AEGISONE, decision D8 rule 4).
10
+ *
11
+ * AEGISONE spawns `claude` for the Claude-Pro/BYOK path. That process runs its
12
+ * own permission system, and its prompts land on *its* stdin — which neither a
13
+ * GUI approval card nor the CLI's prompt loop can answer. The repo already ran
14
+ * this invocation for real (`benchmarks/frozen-run-final-noaider.json`):
15
+ *
16
+ * -p --output-format stream-json --dangerously-skip-permissions
17
+ * (ANTHROPIC_BASE_URL=api.deepseek.com/anthropic)
18
+ *
19
+ * Two bugs that shape every choice below:
20
+ *
21
+ * 1. **A hand-typed argv is a second decision.** If the spawn site writes its
22
+ * own flags, the child's policy and ours drift the moment either changes —
23
+ * and the child's is the one nobody can answer. So the argv is built here,
24
+ * from the posture record `one/src/permissions.js` already resolved, and
25
+ * the exact array is asserted by test (argv EQUALITY, not "a flag was
26
+ * passed"), for both child kinds.
27
+ * 2. **`-p` with an unanswered prompt is a HANG, not a refusal.** For a
28
+ * headless child the bypass is the derived skip; without it the child asks
29
+ * a question nobody can answer. The negative control for that lives with
30
+ * the runner (the "no one to answer it" path), and this module's half of it
31
+ * is that the headless argv carries NO permission flag when the posture
32
+ * says no skip — so the run fails fast instead of parking.
33
+ *
34
+ * ## Rule 4, in full
35
+ *
36
+ * headless `--dangerously-skip-permissions` iff our posture says skip;
37
+ * otherwise nothing at all (never a "harmless" default).
38
+ * interactive `--allow-dangerously-skip-permissions` instead — the same
39
+ * capability offered as an option rather than made the default,
40
+ * which is the narrowest thing that works and the variant
41
+ * Claude's own help describes as "without it being enabled by
42
+ * default".
43
+ * both `--allowedTools` / `--disallowedTools` from the SAME rule set
44
+ * (`allow` → allowed, `deny` → disallowed), so the child's policy
45
+ * tracks ours; `--permission-mode` only when it was explicitly
46
+ * given, validated against the CLI's own list, and ALWAYS
47
+ * recorded — recorded, never inferred.
48
+ *
49
+ * No `process.*` anywhere, module scope or not: the argv is a pure function of
50
+ * its descriptor, which is what makes the equality assertions above possible.
51
+ */
52
+
53
+ /** Rule 4's own flag spellings (verified against claude 2.1.228's --help). */
54
+ const FLAGS = Object.freeze({
55
+ headlessSkip: '--dangerously-skip-permissions',
56
+ interactiveSkip: '--allow-dangerously-skip-permissions',
57
+ permissionMode: '--permission-mode',
58
+ allowedTools: '--allowedTools',
59
+ disallowedTools: '--disallowedTools',
60
+ print: '-p',
61
+ outputFormat: '--output-format',
62
+ model: '--model',
63
+ // Conversation continuity for the Pro child (see `sessionId` below). Both
64
+ // spellings are the CLI's own (claude 2.1.228 --help): `--session-id <uuid>`
65
+ // names the session a NEW conversation runs in, `--resume <id>` reattaches to
66
+ // an existing one, which is what carries the prior turns' context across
67
+ // separate child processes.
68
+ sessionId: '--session-id',
69
+ resume: '--resume',
70
+ // The extra working directories the child may touch (claude 2.1.228 --help:
71
+ // "Additional directories to allow tool …"). See addDirArgs() — the spelling
72
+ // here is deliberately the EQUALS form and that is not cosmetic.
73
+ addDir: '--add-dir',
74
+ });
75
+
76
+ /**
77
+ * `--add-dir` is the child's own sandbox boundary: by default a headless child
78
+ * resolves every relative path and every tool's root against the directory it
79
+ * was spawned in, so a turn started in `repo/cli/` cannot read, run or even
80
+ * SEE `repo/test/` — the exact "outside the sandboxed directory" wall a real
81
+ * session reported from this product.
82
+ *
83
+ * ── why the EQUALS form, and why one flag per directory ─────────────────────
84
+ *
85
+ * `--add-dir` is VARIADIC: the child keeps consuming the words after it as
86
+ * directories. So the obvious `['--add-dir', dir, prompt]` is not merely
87
+ * fragile, it is broken — and this was measured against the installed binary
88
+ * (2.1.228), not reasoned about:
89
+ *
90
+ * claude -p --add-dir /tmp "do the thing" → Error: Input must be provided
91
+ * either through stdin or as a
92
+ * prompt argument when using --print
93
+ * claude -p --add-dir=/tmp "do the thing" → runs
94
+ *
95
+ * The prompt is the LAST item of the argv (rule 4 keeps it there, because the
96
+ * child reads it as the initial message). A space-form `--add-dir` immediately
97
+ * before it therefore swallows the user's prompt into the directory list, and
98
+ * the turn dies as an empty-input error before the model is ever reached.
99
+ * Attaching the value to the flag with `=` terminates the variadic run, so the
100
+ * prompt survives, and one flag per directory keeps a directory whose name
101
+ * begins with `-` from being re-read as another option. Empty and duplicate
102
+ * entries are dropped here rather than passed on: the list reaches the child's
103
+ * sandbox, so what it contains is a decision, not a formality.
104
+ */
105
+ function addDirArgs(dirs) {
106
+ const out = [];
107
+ for (const dir of unique(dirs)) out.push(`${FLAGS.addDir}=${dir}`);
108
+ return out;
109
+ }
110
+
111
+ /**
112
+ * A UUID, as `--session-id` requires. The CLI rejects anything else, and it
113
+ * rejects it AFTER the spawn — an argv that cannot work must not be built, so
114
+ * this returns null and the caller throws rather than typing a value the child
115
+ * will refuse while the turn looks as if it started.
116
+ */
117
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
118
+
119
+ const DEFAULT_OUTPUT_FORMAT = 'stream-json';
120
+
121
+ /** Dedupe while keeping the user's own rule order (rules are read top-down). */
122
+ function unique(list) {
123
+ const seen = new Set();
124
+ const out = [];
125
+ for (const item of Array.isArray(list) ? list : []) {
126
+ const v = String(item).trim();
127
+ if (!v || seen.has(v)) continue;
128
+ seen.add(v);
129
+ out.push(v);
130
+ }
131
+ return out;
132
+ }
133
+
134
+ /**
135
+ * Build the Claude child's argv from the resolved posture.
136
+ *
137
+ * @param {object} [descriptor]
138
+ * @param {object} [descriptor.posture] a record from resolvePosture()
139
+ * @param {string} [descriptor.prompt] initial prompt (both kinds accept one)
140
+ * @param {string} [descriptor.model] explicit model id, if any
141
+ * @param {string} [descriptor.outputFormat] headless only; defaults to stream-json
142
+ * @param {string} [descriptor.permissionMode] explicit passthrough, one of
143
+ * PERMISSION_MODES (else throw)
144
+ * @param {string} [descriptor.resumeSessionId] reattach to an existing child
145
+ * session → `--resume <uuid>`
146
+ * @param {string} [descriptor.sessionId] name a NEW child session, so a
147
+ * LATER turn can `--resume` it
148
+ * @param {string[]} [descriptor.addDir] extra directories the child may
149
+ * work in → `--add-dir=<dir>` each
150
+ * @param {string[]} [descriptor.extra] extra argv items, appended last
151
+ * @returns {{argv: string[], record: object}} both frozen
152
+ * @throws when `permissionMode` is set to something Claude does not accept —
153
+ * a mode we cannot name is a mode we must not silently drop, because
154
+ * the run log would then record "no passthrough" for a run that asked
155
+ * for one.
156
+ * @throws when a session id is given that is not a UUID. Same reason, harder:
157
+ * `claude` refuses a malformed `--session-id` itself, after the spawn,
158
+ * so passing one through would turn a continuity bug into an opaque
159
+ * failed turn.
160
+ */
161
+ function claudeArgv(descriptor = {}) {
162
+ const posture = descriptor.posture;
163
+ if (!posture || typeof posture !== 'object') {
164
+ throw new Error('claudeArgv requires a resolved posture record (one/src/permissions.js resolvePosture)');
165
+ }
166
+ const kind = posture.childKind;
167
+ const headless = kind !== 'interactive';
168
+
169
+ // Imported lazily to keep this module free of a load-time dependency on the
170
+ // evaluator, and to keep the enum's single definition in one place.
171
+ const { PERMISSION_MODES } = require('./permissions.js');
172
+
173
+ const modeGiven = descriptor.permissionMode !== undefined && descriptor.permissionMode !== null;
174
+ const mode = modeGiven ? String(descriptor.permissionMode) : null;
175
+ if (modeGiven && !PERMISSION_MODES.includes(mode)) {
176
+ throw new Error(
177
+ `--permission-mode ${JSON.stringify(mode)} is not one of ${PERMISSION_MODES.join('|')} — ` +
178
+ 'refusing to pass (or to silently drop) a mode the child does not accept.'
179
+ );
180
+ }
181
+
182
+ const rules = posture.rules || {};
183
+ const allowedTools = unique(rules.allow);
184
+ const disallowedTools = unique(rules.deny);
185
+ // Ask rules have no `--allowedTools`/`--disallowedTools` spelling: they are
186
+ // recorded rather than approximated, because approximating "ask" as "deny"
187
+ // would be a refusal the user never asked for.
188
+ const unmappedAsk = unique(rules.ask);
189
+
190
+ // ── conversation continuity ───────────────────────────────────────────────
191
+ //
192
+ // The Pro child runs its own agent loop, so the engine does not replay the
193
+ // transcript into it (engine.js's `pro` branch). Continuity therefore has to
194
+ // come from the CLI's own session store, or every turn is a new conversation
195
+ // with no memory of the last one — which is exactly what it was.
196
+ //
197
+ // `resumeSessionId` wins over `sessionId`: a reattach to a session we already
198
+ // had is the same conversation, and naming a NEW id while resuming would
199
+ // start a second thread beside the live one. Both are validated as UUIDs
200
+ // before they reach argv, because the CLI's own rejection lands after the
201
+ // spawn.
202
+ const wantedResumeId = descriptor.resumeSessionId ? String(descriptor.resumeSessionId).trim() : '';
203
+ const wantedNewId = descriptor.sessionId ? String(descriptor.sessionId).trim() : '';
204
+ const resumeId = wantedResumeId || null;
205
+ const newId = !resumeId && wantedNewId ? wantedNewId : null;
206
+ for (const [label, value] of [['resumeSessionId', resumeId], ['sessionId', newId]]) {
207
+ if (value && !UUID_RE.test(value)) {
208
+ throw new Error(
209
+ `${label} ${JSON.stringify(value)} is not a UUID — refusing to pass it to ` +
210
+ '--resume/--session-id, which the child rejects after the spawn (turning a ' +
211
+ 'continuity bug into an opaque failed turn).'
212
+ );
213
+ }
214
+ }
215
+
216
+ const argv = [];
217
+ if (headless) {
218
+ argv.push(FLAGS.print, FLAGS.outputFormat, String(descriptor.outputFormat || DEFAULT_OUTPUT_FORMAT));
219
+ }
220
+ if (descriptor.model) argv.push(FLAGS.model, String(descriptor.model));
221
+ // The widened sandbox, before the permission flags: what the child may reach
222
+ // is decided here, and the prompt stays last (see addDirArgs).
223
+ const addDir = addDirArgs(descriptor.addDir);
224
+ argv.push(...addDir);
225
+ if (allowedTools.length) argv.push(FLAGS.allowedTools, allowedTools.join(','));
226
+ if (disallowedTools.length) argv.push(FLAGS.disallowedTools, disallowedTools.join(','));
227
+ if (modeGiven) argv.push(FLAGS.permissionMode, mode);
228
+ if (posture.child && posture.child.flag) argv.push(posture.child.flag);
229
+ // Before `extra` (the transport's own flags) and before the prompt, which
230
+ // must stay last so the child reads it as the initial message.
231
+ if (resumeId) argv.push(FLAGS.resume, resumeId);
232
+ else if (newId) argv.push(FLAGS.sessionId, newId);
233
+ if (Array.isArray(descriptor.extra)) argv.push(...descriptor.extra.map(String));
234
+ if (descriptor.prompt !== undefined && descriptor.prompt !== null) argv.push(String(descriptor.prompt));
235
+
236
+ const record = Object.freeze({
237
+ kind,
238
+ // "always recorded" (rule 4): the mode is in the record whether or not it
239
+ // was passed, and `passThrough` says which of the two happened.
240
+ permissionMode: mode,
241
+ permissionModePassed: modeGiven,
242
+ skip: Boolean(posture.child && posture.child.skip),
243
+ skipFlag: (posture.child && posture.child.flag) || null,
244
+ allowedTools: Object.freeze(allowedTools),
245
+ disallowedTools: Object.freeze(disallowedTools),
246
+ unmappedAsk: Object.freeze(unmappedAsk),
247
+ // Recorded, not inferred, exactly like the argv: an install that WIDENED its
248
+ // sandbox for the child is the one thing a later reader of the run log must
249
+ // not have to reconstruct from the argv's shape.
250
+ addDir: Object.freeze(addDir.map((a) => a.slice(FLAGS.addDir.length + 1))),
251
+ // Continuity, recorded the same way the mode is: which of the two happened
252
+ // (reattached vs. named a new session) is part of what this turn asked for,
253
+ // and a caller reading only the argv would have to infer it from position.
254
+ resumeSessionId: resumeId,
255
+ sessionId: newId,
256
+ argv: Object.freeze(argv.slice()),
257
+ });
258
+
259
+ return { argv: record.argv, record };
260
+ }
261
+
262
+ /** The run-log line for a child argv (rule 4: recorded, never inferred). */
263
+ function childRecordLine(record) {
264
+ if (!record || typeof record !== 'object') return null;
265
+ const mode = record.permissionModePassed
266
+ ? `${FLAGS.permissionMode}=${record.permissionMode}`
267
+ : 'no --permission-mode (none was set)';
268
+ return (
269
+ `aegis: claude child [${record.kind}] ${record.skipFlag || 'no permission flag'} · ${mode} · ` +
270
+ `allowedTools=[${record.allowedTools.join(', ')}] disallowedTools=[${record.disallowedTools.join(', ')}]` +
271
+ (record.unmappedAsk.length ? ` (ask rules recorded, unmapped: ${record.unmappedAsk.join(', ')})` : '') +
272
+ // The widened sandbox, named for the same reason the mode is: "the child
273
+ // could only see its own directory" is otherwise indistinguishable, in a
274
+ // transcript, from "the model chose not to look".
275
+ (record.addDir && record.addDir.length ? ` · addDir=[${record.addDir.join(', ')}]` : '') +
276
+ // The continuity half, named rather than left to be read off the argv:
277
+ // "resumed" and "new id" are the two things a turn can mean here, and a
278
+ // turn that silently did neither is the bug this line makes visible.
279
+ (record.resumeSessionId
280
+ ? ` · resumed session ${record.resumeSessionId}`
281
+ : record.sessionId
282
+ ? ` · new session ${record.sessionId}`
283
+ : ' · no session id (each turn is a new conversation)')
284
+ );
285
+ }
286
+
287
+ module.exports = { FLAGS, DEFAULT_OUTPUT_FORMAT, claudeArgv, addDirArgs, childRecordLine };