@mainwave/cli 0.14.0 → 0.16.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/README.md +62 -19
- package/dist/adapters/codex-cli.js +169 -15
- package/dist/commands.js +5 -2
- package/dist/core/apply.js +35 -36
- package/dist/core/codecs/toml-profile.js +1 -7
- package/dist/core/codex-trust.js +135 -34
- package/dist/core/doctor.js +97 -32
- package/dist/core/markers.js +19 -5
- package/dist/core/remove.js +54 -10
- package/dist/core/setup-removal.js +197 -0
- package/dist/core/store.js +37 -0
- package/dist/core/wizard.js +33 -2
- package/dist/main.js +9 -3
- package/hooks/codex-turns.mjs +124 -31
- package/hooks/kiro-otlp.mjs +4 -15
- package/hooks/marker-core.mjs +21 -0
- package/hooks/matchers.json +1 -1
- package/hooks/plan-snapshot.mjs +54 -23
- package/hooks/vocabulary.d.mts +3 -0
- package/hooks/vocabulary.mjs +11 -3
- package/package.json +6 -6
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import { promises as fs } from 'node:fs';
|
|
2
|
+
import { tomlOtelCodec } from './codecs/toml-otel.js';
|
|
3
|
+
import { approvedHookKeys, hookTrustKey, mainwaveHookKeys, withoutHookStates, } from './codex-trust.js';
|
|
4
|
+
import { planMarkers, prepareMarkersFile } from './markers.js';
|
|
5
|
+
import { isErrnoCode, isSamePath, prepareUpdate, readExistingEnv } from './settings.js';
|
|
6
|
+
export const planSetupRemoval = async (adapter, options = {}) => {
|
|
7
|
+
const path = adapter.paths.global;
|
|
8
|
+
const env = await readExistingEnv(path, adapter.codec);
|
|
9
|
+
const owns = env !== null && (adapter.holdsOwnSetup?.(env) ?? true);
|
|
10
|
+
const config = await prepareUpdate({
|
|
11
|
+
path,
|
|
12
|
+
newEnv: {},
|
|
13
|
+
managedKeys: owns ? [...adapter.managedEnvKeys, ...(adapter.retiredEnvKeys ?? [])] : [],
|
|
14
|
+
codec: adapter.codec,
|
|
15
|
+
});
|
|
16
|
+
const holdsKey = (fileEnv) => fileEnv !== null && (adapter.holdsOwnKey ?? adapter.holdsOwnSetup)?.(fileEnv) === true;
|
|
17
|
+
const configKey = holdsKey(env);
|
|
18
|
+
const hooksFile = adapter.markers?.hooksFile;
|
|
19
|
+
const approvals = options.approvals === true;
|
|
20
|
+
let removals;
|
|
21
|
+
let keys = [];
|
|
22
|
+
if (hooksFile === undefined) {
|
|
23
|
+
removals = [{ update: config, markersPlan: null, approvals: 0, holdsKey: configKey }];
|
|
24
|
+
}
|
|
25
|
+
else if (isSamePath(hooksFile.path, path)) {
|
|
26
|
+
const before = config.next;
|
|
27
|
+
const markersPlan = config.exists ? planMarkers(config.next, []) : null;
|
|
28
|
+
if (markersPlan !== null)
|
|
29
|
+
config.next = markersPlan.next;
|
|
30
|
+
const removal = {
|
|
31
|
+
update: config,
|
|
32
|
+
markersPlan,
|
|
33
|
+
approvals: 0,
|
|
34
|
+
holdsKey: configKey,
|
|
35
|
+
};
|
|
36
|
+
if (approvals && markersPlan !== null) {
|
|
37
|
+
keys = mainwaveHookKeys(before, hooksFile.path);
|
|
38
|
+
removal.moved = movedHooks(before, markersPlan.next, hooksFile.path, adapter.trustFiles);
|
|
39
|
+
}
|
|
40
|
+
removals = [removal];
|
|
41
|
+
}
|
|
42
|
+
else {
|
|
43
|
+
const hooks = await prepareMarkersFile(hooksFile.path, hooksFile.codec, []);
|
|
44
|
+
const next = hooks.plan.next;
|
|
45
|
+
const empty = next !== null && typeof next === 'object' && Object.keys(next).length === 0;
|
|
46
|
+
const emptied = hooks.update.exists && hooks.plan.changed && empty;
|
|
47
|
+
const linkTarget = emptied && (await fs.lstat(hooksFile.path)).isSymbolicLink()
|
|
48
|
+
? await fs.realpath(hooksFile.path)
|
|
49
|
+
: undefined;
|
|
50
|
+
const removal = {
|
|
51
|
+
update: hooks.update,
|
|
52
|
+
markersPlan: hooks.plan,
|
|
53
|
+
approvals: 0,
|
|
54
|
+
holdsKey: false,
|
|
55
|
+
...(linkTarget !== undefined ? { linkTarget } : emptied ? { remove: true } : {}),
|
|
56
|
+
};
|
|
57
|
+
if (approvals && hooks.plan.removed.length > 0) {
|
|
58
|
+
const body = await fs.readFile(hooksFile.path, 'utf8');
|
|
59
|
+
const before = hooksFile.codec.parse(body, hooksFile.path);
|
|
60
|
+
keys = mainwaveHookKeys(before, hooksFile.path);
|
|
61
|
+
removal.moved = movedHooks(before, hooks.plan.next, hooksFile.path, adapter.trustFiles);
|
|
62
|
+
}
|
|
63
|
+
removals = [{ update: config, markersPlan: null, approvals: 0, holdsKey: configKey }, removal];
|
|
64
|
+
}
|
|
65
|
+
if (keys.length === 0)
|
|
66
|
+
return removals;
|
|
67
|
+
return dropApprovals(removals, adapter.trustFiles ?? [], new Set(keys), (doc) => holdsKey(tomlOtelCodec.readEnv(doc)));
|
|
68
|
+
};
|
|
69
|
+
const movedHooks = (before, after, keySource, trustFiles = []) => {
|
|
70
|
+
const eventsOf = (doc) => isRecord(doc) && isRecord(doc.hooks) ? doc.hooks : {};
|
|
71
|
+
const approved = approvedHookKeys(trustFiles);
|
|
72
|
+
const moved = [];
|
|
73
|
+
const kept = eventsOf(after);
|
|
74
|
+
for (const [event, groups] of Object.entries(eventsOf(before))) {
|
|
75
|
+
const left = kept[event];
|
|
76
|
+
if (!Array.isArray(groups) || !Array.isArray(left))
|
|
77
|
+
continue;
|
|
78
|
+
let at = 0;
|
|
79
|
+
for (const [gi, group] of groups.entries()) {
|
|
80
|
+
if (at >= left.length || JSON.stringify(group) !== JSON.stringify(left[at]))
|
|
81
|
+
continue;
|
|
82
|
+
if (at !== gi && isRecord(group) && Array.isArray(group.hooks)) {
|
|
83
|
+
for (const [hi, handler] of group.hooks.entries()) {
|
|
84
|
+
if (!isRecord(handler) || typeof handler.command !== 'string')
|
|
85
|
+
continue;
|
|
86
|
+
if (approved?.has(hookTrustKey(keySource, event, gi, hi)) === false)
|
|
87
|
+
continue;
|
|
88
|
+
moved.push({ event, command: handler.command });
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
at++;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return moved;
|
|
95
|
+
};
|
|
96
|
+
const isRecord = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
97
|
+
const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;
|
|
98
|
+
const shownCommand = (command) => {
|
|
99
|
+
const program = command
|
|
100
|
+
.trim()
|
|
101
|
+
.split(/\s+/)
|
|
102
|
+
.find((word) => !ASSIGNMENT.test(word));
|
|
103
|
+
const name = program
|
|
104
|
+
?.replace(/^["']|["']$/g, '')
|
|
105
|
+
.split(/[\\/]/)
|
|
106
|
+
.pop();
|
|
107
|
+
return name ? `${name} (arguments hidden)` : '(command hidden)';
|
|
108
|
+
};
|
|
109
|
+
const dropApprovals = async (removals, trustFiles, keys, holdsKey) => {
|
|
110
|
+
const out = [...removals];
|
|
111
|
+
for (const file of trustFiles) {
|
|
112
|
+
let at = out.findIndex((r) => isSamePath(r.update.path, file));
|
|
113
|
+
if (at < 0) {
|
|
114
|
+
const update = await prepareUpdate({
|
|
115
|
+
path: file,
|
|
116
|
+
newEnv: {},
|
|
117
|
+
managedKeys: [],
|
|
118
|
+
codec: tomlOtelCodec,
|
|
119
|
+
});
|
|
120
|
+
if (!update.exists)
|
|
121
|
+
continue;
|
|
122
|
+
at = out.findIndex((r) => removals.includes(r));
|
|
123
|
+
out.splice(at, 0, {
|
|
124
|
+
update,
|
|
125
|
+
markersPlan: null,
|
|
126
|
+
approvals: 0,
|
|
127
|
+
holdsKey: holdsKey(update.next),
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
const removal = out[at];
|
|
131
|
+
const { codec } = removal.update;
|
|
132
|
+
const { text, dropped } = withoutHookStates(codec.serialize(removal.update.next), keys);
|
|
133
|
+
if (dropped === 0)
|
|
134
|
+
continue;
|
|
135
|
+
removal.update.next = codec.parse(text, removal.update.path);
|
|
136
|
+
removal.approvals += dropped;
|
|
137
|
+
}
|
|
138
|
+
return out;
|
|
139
|
+
};
|
|
140
|
+
const removalChanges = ({ update, markersPlan, approvals }) => update.diff.added.length > 0 ||
|
|
141
|
+
update.diff.changed.length > 0 ||
|
|
142
|
+
update.diff.removed.length > 0 ||
|
|
143
|
+
markersPlan?.changed === true ||
|
|
144
|
+
approvals > 0;
|
|
145
|
+
export const removalSteps = async (removals) => Promise.all(removals.filter(removalChanges).map(removalStep));
|
|
146
|
+
const isSymlink = async (path) => {
|
|
147
|
+
try {
|
|
148
|
+
return (await fs.lstat(path)).isSymbolicLink();
|
|
149
|
+
}
|
|
150
|
+
catch (err) {
|
|
151
|
+
if (isErrnoCode(err, 'ENOENT'))
|
|
152
|
+
return false;
|
|
153
|
+
throw err;
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
const removalStep = async (removal) => {
|
|
157
|
+
const { update, markersPlan, approvals, holdsKey } = removal;
|
|
158
|
+
const left = update.codec.serialize(update.next).trim();
|
|
159
|
+
if (left === '' || left === '{}') {
|
|
160
|
+
if (await isSymlink(update.path)) {
|
|
161
|
+
const target = await fs.realpath(update.path);
|
|
162
|
+
return {
|
|
163
|
+
kind: 'update',
|
|
164
|
+
update,
|
|
165
|
+
holdsKey,
|
|
166
|
+
note: `${update.path}: links to ${target}; keep the link and leave that file ` +
|
|
167
|
+
`${left === '{}' ? 'as {}' : 'empty'} (only Mainwave's setup in it)`,
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
return {
|
|
171
|
+
kind: 'delete',
|
|
172
|
+
path: update.path,
|
|
173
|
+
holdsKey,
|
|
174
|
+
note: `${update.path}: delete (only Mainwave's setup in it)`,
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
const hooks = markersPlan?.removed.length ?? 0;
|
|
178
|
+
const parts = [
|
|
179
|
+
...(update.diff.removed.length > 0 ? ["Mainwave's telemetry settings"] : []),
|
|
180
|
+
...(hooks > 0 ? [`${hooks} Mainwave ${hooks === 1 ? 'hook' : 'hooks'}`] : []),
|
|
181
|
+
...(approvals > 0
|
|
182
|
+
? [`Codex's ${approvals === 1 ? 'approval' : 'approvals'} of Mainwave hooks`]
|
|
183
|
+
: []),
|
|
184
|
+
];
|
|
185
|
+
const moved = removal.moved ?? [];
|
|
186
|
+
const reapprove = moved.length === 0
|
|
187
|
+
? ''
|
|
188
|
+
: `\n This moves ${moved.length === 1 ? 'a hook' : 'hooks'} of other tools that Codex ` +
|
|
189
|
+
`approved by position, so Codex will ask you to approve ${moved.length === 1 ? 'it' : 'them'} again:` +
|
|
190
|
+
moved.map((h) => `\n ${h.event}: ${shownCommand(h.command)}`).join('');
|
|
191
|
+
return {
|
|
192
|
+
kind: 'update',
|
|
193
|
+
update,
|
|
194
|
+
holdsKey,
|
|
195
|
+
note: `${update.path}: remove ${parts.join(', ')}; keep the rest${reapprove}`,
|
|
196
|
+
};
|
|
197
|
+
};
|
package/dist/core/store.js
CHANGED
|
@@ -174,6 +174,43 @@ export const updateSettings = async (patch) => withFileLock(settingsPath(), asyn
|
|
|
174
174
|
await writeJson(settingsPath(), next);
|
|
175
175
|
return next;
|
|
176
176
|
});
|
|
177
|
+
const withoutHookFiles = (hooks, files) => {
|
|
178
|
+
if (!isPlainObject(hooks))
|
|
179
|
+
return undefined;
|
|
180
|
+
const next = { ...hooks };
|
|
181
|
+
let changed = false;
|
|
182
|
+
for (const kind of ['events', 'routes']) {
|
|
183
|
+
const record = next[kind];
|
|
184
|
+
if (!isPlainObject(record))
|
|
185
|
+
continue;
|
|
186
|
+
let kept = record;
|
|
187
|
+
for (const { adapter, file } of files) {
|
|
188
|
+
const perFile = kept[adapter];
|
|
189
|
+
if (!isPlainObject(perFile) || !(file in perFile))
|
|
190
|
+
continue;
|
|
191
|
+
kept = {
|
|
192
|
+
...kept,
|
|
193
|
+
[adapter]: Object.fromEntries(Object.entries(perFile).filter(([f]) => f !== file)),
|
|
194
|
+
};
|
|
195
|
+
changed = true;
|
|
196
|
+
}
|
|
197
|
+
next[kind] = kept;
|
|
198
|
+
}
|
|
199
|
+
return changed ? next : undefined;
|
|
200
|
+
};
|
|
201
|
+
export const forgetHookFiles = async (files) => {
|
|
202
|
+
if (withoutHookFiles((await readSettings()).hooks, files) === undefined)
|
|
203
|
+
return false;
|
|
204
|
+
return withFileLock(settingsPath(), async () => {
|
|
205
|
+
await assertSettingsWritable();
|
|
206
|
+
const current = await readSettings();
|
|
207
|
+
const hooks = withoutHookFiles(current.hooks, files);
|
|
208
|
+
if (hooks === undefined)
|
|
209
|
+
return false;
|
|
210
|
+
await writeJson(settingsPath(), { ...current, hooks });
|
|
211
|
+
return true;
|
|
212
|
+
});
|
|
213
|
+
};
|
|
177
214
|
export const KEEP_ORG_PACKS = 'keep';
|
|
178
215
|
export const hasOrgEntry = async (configDir, path) => orgDirsIn(await readSettingsText(path)).includes(configDir);
|
|
179
216
|
const sameList = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
|
package/dist/core/wizard.js
CHANGED
|
@@ -19,7 +19,7 @@ import { VERSION } from './version.js';
|
|
|
19
19
|
import { emitJson, say, setJsonMode } from './ui.js';
|
|
20
20
|
import { validateCollector } from './validate.js';
|
|
21
21
|
import { runVerify } from './verify.js';
|
|
22
|
-
import { CODEX_ADAPTER_NAME, codexCliFor, codexHome, codexHomeIssues, findCodexProfileSetups, parseProfileName, profileConflict, profileFileName, profileOtherExporterWarning, } from '../adapters/codex-cli.js';
|
|
22
|
+
import { CODEX_ADAPTER_NAME, codexCliFor, codexHome, codexHomeIssues, findCodexProfileSetups, homeSharedExporterWarning, otherProfileSetupsNote, parseProfileName, profileConflict, profileFileName, profileOtherExporterWarning, profileRefusal, } from '../adapters/codex-cli.js';
|
|
23
23
|
const validateWithRetry = async (initialUrl, initialKey, interactive) => {
|
|
24
24
|
let url = initialUrl;
|
|
25
25
|
let key = initialKey;
|
|
@@ -265,6 +265,25 @@ const resolveCodexAdapters = async (adapters, profile, interactive) => {
|
|
|
265
265
|
const found = findCodexProfileSetups(home);
|
|
266
266
|
if (found.length === 0)
|
|
267
267
|
return { adapters: [...adapters] };
|
|
268
|
+
const refused = found.flatMap((p) => {
|
|
269
|
+
const refusal = profileRefusal(home, p);
|
|
270
|
+
return refusal === undefined ? [] : [{ profile: p, refusal }];
|
|
271
|
+
});
|
|
272
|
+
if (refused.length > 0) {
|
|
273
|
+
const run = (p) => `\`mainwave-cli setup codex --profile ${p}\``;
|
|
274
|
+
const healthy = found.filter((p) => !refused.some((r) => r.profile === p));
|
|
275
|
+
throw new WizardAbort([
|
|
276
|
+
...refused.map((r) => `Codex profile ${r.profile} holds a Mainwave setup in a file setup can't edit: ${r.refusal}.`),
|
|
277
|
+
`Until then, ${refused.map((r) => run(r.profile)).join(' and ')} and a switch to all ` +
|
|
278
|
+
'sessions stop on the same problem.',
|
|
279
|
+
...(healthy.length === 0
|
|
280
|
+
? []
|
|
281
|
+
: [
|
|
282
|
+
`To update ${healthy.length === 1 ? 'profile' : 'profiles'} ${healthy.join(', ')} now, ` +
|
|
283
|
+
`run ${healthy.map(run).join(' or ')}.`,
|
|
284
|
+
]),
|
|
285
|
+
].join(' '));
|
|
286
|
+
}
|
|
268
287
|
if (!interactive) {
|
|
269
288
|
const files = found.map(profileFileName).join(', ');
|
|
270
289
|
throw new WizardAbort(`Codex sends to Mainwave only from ${found.length === 1 ? 'profile' : 'profiles'} ${found.join(', ')} (${files} in ${home}). ` +
|
|
@@ -370,11 +389,20 @@ export const runSetup = async (requested, rawOptions = {}) => {
|
|
|
370
389
|
`(${plan.keptPin.name ?? plan.keptPin.id}). Pass --no-use-case to unpin it.`));
|
|
371
390
|
}
|
|
372
391
|
}
|
|
373
|
-
const otherExporter =
|
|
392
|
+
const otherExporter = !adapters.some((a) => a.name === CODEX_ADAPTER_NAME)
|
|
393
|
+
? undefined
|
|
394
|
+
: codexProfile === undefined
|
|
395
|
+
? homeSharedExporterWarning(codexHome())
|
|
396
|
+
: profileOtherExporterWarning(codexHome(), codexProfile);
|
|
374
397
|
if (otherExporter !== undefined) {
|
|
375
398
|
say('');
|
|
376
399
|
say(color.yellow(`⚠ ${otherExporter}`));
|
|
377
400
|
}
|
|
401
|
+
const otherProfiles = codexProfile === undefined ? undefined : otherProfileSetupsNote(codexHome(), codexProfile);
|
|
402
|
+
if (otherProfiles !== undefined) {
|
|
403
|
+
say('');
|
|
404
|
+
say(color.yellow(`⚠ ${otherProfiles}`));
|
|
405
|
+
}
|
|
378
406
|
if (planHasChanges(plans) && !options.yes) {
|
|
379
407
|
if (!interactive) {
|
|
380
408
|
throw new WizardAbort('refusing to write without confirmation — pass --yes');
|
|
@@ -653,6 +681,9 @@ const printRestartNotice = (adapters) => {
|
|
|
653
681
|
' already open keeps the old settings and sends nothing. Quit and reopen each\n' +
|
|
654
682
|
' one (including this one, if you ran setup from inside it) before checking\n' +
|
|
655
683
|
' for telemetry.'));
|
|
684
|
+
for (const a of adapters)
|
|
685
|
+
if (a.lingeringProcess)
|
|
686
|
+
say(color.yellow(` ${a.lingeringProcess.onSetup}`));
|
|
656
687
|
};
|
|
657
688
|
const printPostSetupTips = (adapters) => {
|
|
658
689
|
const killSwitch = process.env.DISABLE_TELEMETRY === '1'
|
package/dist/main.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { claudeCodeFor } from './adapters/claude-code.js';
|
|
2
|
-
import { codexCliFor, homeTarget, parseProfileName, profileTarget } from './adapters/codex-cli.js';
|
|
2
|
+
import { CODEX_ADAPTER_NAME, codexCliFor, homeTarget, parseProfileName, profileTarget, } from './adapters/codex-cli.js';
|
|
3
3
|
import { adapterNames, adapters } from './adapters/index.js';
|
|
4
4
|
import { commandFlags, detailsBlock, isCommand, usageBlock } from './commands.js';
|
|
5
5
|
import { runLogin, runLogout, runWhoami } from './core/auth-commands.js';
|
|
@@ -300,10 +300,16 @@ const HANDLERS = {
|
|
|
300
300
|
if (named.length === 0) {
|
|
301
301
|
throw new WizardAbort('--remove needs the tools to remove, e.g. `setup kiro-ide --remove`');
|
|
302
302
|
}
|
|
303
|
+
let targets = named;
|
|
303
304
|
if (flags.has('profile')) {
|
|
304
|
-
|
|
305
|
+
const profile = parseProfileName(flags.value('profile'));
|
|
306
|
+
if (!named.some((a) => a.name === CODEX_ADAPTER_NAME)) {
|
|
307
|
+
throw new WizardAbort('--profile applies to Codex only: name codex among the tools, e.g. ' +
|
|
308
|
+
`\`setup codex --remove --profile ${profile}\``);
|
|
309
|
+
}
|
|
310
|
+
targets = named.map((a) => a.name === CODEX_ADAPTER_NAME ? codexCliFor(profileTarget(profile)) : a);
|
|
305
311
|
}
|
|
306
|
-
return await runRemove(
|
|
312
|
+
return await runRemove(targets, {
|
|
307
313
|
yes: flags.bool('yes') === true,
|
|
308
314
|
json: flags.bool('json') === true,
|
|
309
315
|
});
|
package/hooks/codex-turns.mjs
CHANGED
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
// across inserts, so each span is sent once, when it ends, with the times the
|
|
16
16
|
// hook process read. A small per-session state file under
|
|
17
17
|
// `~/.mainwave/state/codex-turns/` holds what is open between events; it is
|
|
18
|
-
// deleted once nothing is open.
|
|
18
|
+
// deleted once nothing is open and no abandoned turn awaits a late Stop.
|
|
19
19
|
//
|
|
20
20
|
// Sent: session, turn and agent ids, agent type, working directory, a tool
|
|
21
21
|
// name for a permission wait, and times. Never the prompt, the assistant
|
|
@@ -53,6 +53,7 @@ import {
|
|
|
53
53
|
markerResourceAttrs,
|
|
54
54
|
markerTool,
|
|
55
55
|
opaqueIdExact,
|
|
56
|
+
stampActivity,
|
|
56
57
|
stringAttr,
|
|
57
58
|
} from './marker-core.mjs'
|
|
58
59
|
import {
|
|
@@ -79,6 +80,12 @@ export const STATE_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000
|
|
|
79
80
|
|
|
80
81
|
const LOCK_WAIT_MS = 1500
|
|
81
82
|
const LOCK_STALE_MS = 10_000
|
|
83
|
+
/** A main SessionStart abandons an open turn only when the turn started at
|
|
84
|
+
* least this long before it. Codex fires SessionStart with the run's first
|
|
85
|
+
* prompt, and their hooks lock in either order milliseconds apart. It is
|
|
86
|
+
* also how long after the abandoning event a Stop or Interrupt for the
|
|
87
|
+
* abandoned turn may read its clock and still end it (§ `applyEvent`). */
|
|
88
|
+
export const SESSION_START_STALE_MS = 5000
|
|
82
89
|
|
|
83
90
|
/** Codex runs the Stop and Interrupt groups synchronously (`codex exec` exits
|
|
84
91
|
* without waiting for an async hook), so it waits for this feature at the
|
|
@@ -100,7 +107,8 @@ export const stateDir = (argv) =>
|
|
|
100
107
|
|
|
101
108
|
/** `abandoned` is the last turn a new prompt or session start abandoned, kept
|
|
102
109
|
* so a Stop or Interrupt for it that locks late can still end it (§
|
|
103
|
-
* `applyEvent`). It
|
|
110
|
+
* `applyEvent`). It keeps the state file until that Stop or a later turn's
|
|
111
|
+
* own end clears it (§ `isEmptyState`). */
|
|
104
112
|
export const emptyState = () => ({ v: 1, turn: null, subagents: {}, waits: {}, abandoned: null })
|
|
105
113
|
|
|
106
114
|
/** A well-formed state read back from disk, else an empty one. */
|
|
@@ -125,6 +133,17 @@ export const parseState = (text) => {
|
|
|
125
133
|
const OPAQUE_NAME_RE = /^[A-Za-z0-9_.:/ -]{1,128}$/
|
|
126
134
|
const opaqueName = (v) => (typeof v === 'string' && OPAQUE_NAME_RE.test(v) ? v : undefined)
|
|
127
135
|
|
|
136
|
+
/** SessionStart's `source` values this feature knows; any other reads as none. */
|
|
137
|
+
const SESSION_SOURCES = new Set(['startup', 'resume', 'clear', 'compact', 'fork'])
|
|
138
|
+
|
|
139
|
+
/** Sources whose SessionStart abandons nothing. A `startup`, `fork` or
|
|
140
|
+
* `clear` session id is new (a fork records its parent thread, and `/clear`
|
|
141
|
+
* starts a new chat), so its state holds only this run's events, which may
|
|
142
|
+
* have locked first. A `compact` start keeps the id inside the same running
|
|
143
|
+
* process, so the open turn is live. Only `resume` (or no known source) can
|
|
144
|
+
* find a killed run's leftovers. */
|
|
145
|
+
const ABANDONS_NOTHING = new Set(['startup', 'fork', 'clear', 'compact'])
|
|
146
|
+
|
|
128
147
|
/** The only fields of the hook input this feature reads. */
|
|
129
148
|
export const readInput = (payload, event) => ({
|
|
130
149
|
event,
|
|
@@ -133,6 +152,7 @@ export const readInput = (payload, event) => ({
|
|
|
133
152
|
agentId: opaqueIdExact(payload?.agent_id),
|
|
134
153
|
agentType: opaqueName(payload?.agent_type),
|
|
135
154
|
toolName: opaqueName(payload?.tool_name),
|
|
155
|
+
source: SESSION_SOURCES.has(payload?.source) ? payload.source : undefined,
|
|
136
156
|
cwd:
|
|
137
157
|
typeof payload?.cwd === 'string' && isAbsolute(payload.cwd) && payload.cwd.length <= 4096
|
|
138
158
|
? payload.cwd
|
|
@@ -147,16 +167,28 @@ export const readInput = (payload, event) => ({
|
|
|
147
167
|
* What closes what (the contract with the collector):
|
|
148
168
|
*
|
|
149
169
|
* - Only an event with no `agent_id` opens or closes a main turn. A new
|
|
150
|
-
* UserPromptSubmit
|
|
151
|
-
*
|
|
152
|
-
*
|
|
153
|
-
*
|
|
170
|
+
* UserPromptSubmit finds a turn still open and abandons it, ending it at the
|
|
171
|
+
* last event it saw, so a killed Codex never stretches a turn across the
|
|
172
|
+
* developer's absence; one that saw no later event is dropped. A main
|
|
173
|
+
* SessionStart whose `source` is `startup`, `fork`, `clear` or `compact`
|
|
174
|
+
* abandons nothing: the session id is new, or (`compact`) the same running
|
|
175
|
+
* process, so whatever is open is this run's own. Any other main
|
|
176
|
+
* SessionStart (`resume`, or none) abandons the same way
|
|
177
|
+
* only a turn that started more than `SESSION_START_STALE_MS` before it:
|
|
178
|
+
* Codex fires it together with the run's first UserPromptSubmit, so a turn
|
|
179
|
+
* just opened may be that prompt's own, and the prompt abandons a stale
|
|
180
|
+
* one anyway.
|
|
181
|
+
* - A main event whose turn id names another turn than the open one belongs
|
|
182
|
+
* to the next run, locking before that run's prompt. It neither extends
|
|
183
|
+
* the open turn's last event nor ends a wait under it, and as a
|
|
184
|
+
* PermissionRequest it opens no wait.
|
|
154
185
|
* - A permission wait ends at the first later PostToolUse, PreModelRequest,
|
|
155
|
-
* PermissionRequest, Stop, Interrupt
|
|
156
|
-
*
|
|
157
|
-
* its turn). PreToolUse is not one: Codex
|
|
158
|
-
* never ends that call's wait.
|
|
159
|
-
* the PreModelRequest before it
|
|
186
|
+
* PermissionRequest, Stop, Interrupt or SubagentStop of the same session
|
|
187
|
+
* and agent, or a subagent's own SessionStart (a main SessionStart ends a
|
|
188
|
+
* main wait by abandoning its stale turn). PreToolUse is not one: Codex
|
|
189
|
+
* runs it before the approval, so it never ends that call's wait.
|
|
190
|
+
* PostModelRequest is not one either, because the PreModelRequest before it
|
|
191
|
+
* already did.
|
|
160
192
|
* - A turn that ends takes its open waits (end = the turn's end) and any
|
|
161
193
|
* subagent still open (abandoned, end = its last event) with it.
|
|
162
194
|
* - Hooks read the clock before they take the state lock, so events can reach
|
|
@@ -166,14 +198,18 @@ export const readInput = (payload, event) => ({
|
|
|
166
198
|
* that turn's Stop. The reverse, an async UserPromptSubmit locking after its
|
|
167
199
|
* own synchronous Stop, needs a turn that finishes faster than Node starts.
|
|
168
200
|
* These guards cover the reorderings seen or reviewed, not every possible
|
|
169
|
-
* one: a
|
|
170
|
-
*
|
|
171
|
-
*
|
|
172
|
-
*
|
|
173
|
-
*
|
|
174
|
-
*
|
|
175
|
-
*
|
|
176
|
-
*
|
|
201
|
+
* one: a UserPromptSubmit abandons only a turn that started earlier; a
|
|
202
|
+
* `startup`, `fork`, `clear` or `compact` SessionStart abandons nothing,
|
|
203
|
+
* and any other only a subagent that started earlier or a turn that
|
|
204
|
+
* started well before; a Stop or Interrupt without a turn id closes only a
|
|
205
|
+
* turn that started no later than itself; a Stop or Interrupt whose turn id names
|
|
206
|
+
* the turn last abandoned, and that read its clock no more than
|
|
207
|
+
* `SESSION_START_STALE_MS` after the abandoning event, sends that turn
|
|
208
|
+
* again with its real end reason and end (the span ids are the same, so
|
|
209
|
+
* the row replaces the abandoned one); a PermissionRequest or SubagentStart
|
|
210
|
+
* older than the open turn, or with none open, is dropped; and an event ends only a wait that started no
|
|
211
|
+
* later than itself, except that a turn's or subagent's own end takes its
|
|
212
|
+
* waits.
|
|
177
213
|
*/
|
|
178
214
|
export const applyEvent = (state, input, now) => {
|
|
179
215
|
const st = structuredClone(state)
|
|
@@ -230,8 +266,12 @@ export const applyEvent = (state, input, now) => {
|
|
|
230
266
|
}
|
|
231
267
|
st.turn = null
|
|
232
268
|
if (reason === 'abandoned') {
|
|
233
|
-
st.abandoned = { turnId: t.turnId, startMs: t.startMs, cwd: t.cwd }
|
|
269
|
+
st.abandoned = { turnId: t.turnId, startMs: t.startMs, cwd: t.cwd, atMs: now }
|
|
234
270
|
if (t.lastMs <= t.startMs) return
|
|
271
|
+
} else {
|
|
272
|
+
// A later turn ended normally, so the abandoned one's Stop, which fires
|
|
273
|
+
// before that turn's prompt, is long past.
|
|
274
|
+
st.abandoned = null
|
|
235
275
|
}
|
|
236
276
|
out.push({
|
|
237
277
|
kind: 'turn',
|
|
@@ -244,10 +284,17 @@ export const applyEvent = (state, input, now) => {
|
|
|
244
284
|
})
|
|
245
285
|
}
|
|
246
286
|
|
|
287
|
+
// A main event naming another turn is the next run's, locking before that
|
|
288
|
+
// run's prompt: it is no work inside the open turn and ends none of its
|
|
289
|
+
// waits.
|
|
290
|
+
const mismatched = () =>
|
|
291
|
+
st.turn !== null && agentId === undefined && turnId !== undefined && turnId !== st.turn.turnId
|
|
292
|
+
const ofOpenTurn = () => st.turn !== null && !mismatched()
|
|
293
|
+
|
|
247
294
|
// A subagent's event is also work inside the open main turn, so a turn
|
|
248
295
|
// abandoned after a kill ends at its subagents' last event too.
|
|
249
296
|
const touch = () => {
|
|
250
|
-
if (
|
|
297
|
+
if (ofOpenTurn()) st.turn.lastMs = Math.max(st.turn.lastMs, now)
|
|
251
298
|
if (agentId !== undefined && st.subagents[agentId] !== undefined) {
|
|
252
299
|
st.subagents[agentId].lastMs = Math.max(st.subagents[agentId].lastMs, now)
|
|
253
300
|
}
|
|
@@ -282,8 +329,21 @@ export const applyEvent = (state, input, now) => {
|
|
|
282
329
|
// With no turn id, only a turn that started no later than this event
|
|
283
330
|
// can be the one it ends.
|
|
284
331
|
if (st.turn.startMs <= now) closeTurn(now, reason, event)
|
|
285
|
-
} else if (
|
|
332
|
+
} else if (
|
|
333
|
+
a !== null &&
|
|
334
|
+
turnId === a.turnId &&
|
|
335
|
+
a.startMs <= now &&
|
|
336
|
+
// A record written by an earlier release has no `atMs`; its late
|
|
337
|
+
// Stop is refused, so the abandoned row stays.
|
|
338
|
+
Number.isFinite(a.atMs) &&
|
|
339
|
+
now <= a.atMs + SESSION_START_STALE_MS
|
|
340
|
+
) {
|
|
286
341
|
// The turn a queued prompt abandoned before this event took the lock.
|
|
342
|
+
// Codex submits that prompt the moment the turn ends, so the two
|
|
343
|
+
// read their clocks within a Node start of each other. A later one
|
|
344
|
+
// would stretch the turn across a gap, so the abandoned row stays.
|
|
345
|
+
// A Stop that Codex replayed right after a resume would still pass;
|
|
346
|
+
// no replay has been seen, and no clock tells the two apart.
|
|
287
347
|
st.abandoned = null
|
|
288
348
|
out.push({
|
|
289
349
|
kind: 'turn',
|
|
@@ -300,8 +360,9 @@ export const applyEvent = (state, input, now) => {
|
|
|
300
360
|
case 'PermissionRequest':
|
|
301
361
|
touch()
|
|
302
362
|
// None open, or one that started after this request: the request
|
|
303
|
-
// belongs to an earlier turn.
|
|
304
|
-
|
|
363
|
+
// belongs to an earlier turn. A main request naming another turn
|
|
364
|
+
// belongs to a later one whose prompt has not locked yet.
|
|
365
|
+
if (!ofOpenTurn() || now < st.turn.startMs) break
|
|
305
366
|
if (st.waits[key] !== undefined && now < st.waits[key].startMs) break
|
|
306
367
|
closeWait(key, now, event)
|
|
307
368
|
st.waits[key] = {
|
|
@@ -315,7 +376,7 @@ export const applyEvent = (state, input, now) => {
|
|
|
315
376
|
case 'PostToolUse':
|
|
316
377
|
case 'PreModelRequest':
|
|
317
378
|
touch()
|
|
318
|
-
closeWait(key, now, event)
|
|
379
|
+
if (!mismatched()) closeWait(key, now, event)
|
|
319
380
|
break
|
|
320
381
|
case 'SubagentStart':
|
|
321
382
|
if (agentId === undefined) break
|
|
@@ -349,17 +410,27 @@ export const applyEvent = (state, input, now) => {
|
|
|
349
410
|
closeWait(key, now, event)
|
|
350
411
|
break
|
|
351
412
|
}
|
|
352
|
-
//
|
|
353
|
-
|
|
413
|
+
// A startup, fork or clear session id is new, and a compact start is
|
|
414
|
+
// the same running process, so everything in its state came from this
|
|
415
|
+
// run's own events, which may have locked first: nothing is left over
|
|
416
|
+
// to abandon, whatever the clocks say.
|
|
417
|
+
if (ABANDONS_NOTHING.has(input.source)) break
|
|
418
|
+
// Codex fires SessionStart with the run's first prompt, both hooks
|
|
419
|
+
// async, and either may read the clock first, so a turn that started
|
|
420
|
+
// just before may be this run's own new one: it is left to the next
|
|
421
|
+
// UserPromptSubmit, which abandons it if it is an earlier run's. One
|
|
422
|
+
// that started well before is an earlier run's.
|
|
423
|
+
if (st.turn !== null && st.turn.startMs < now - SESSION_START_STALE_MS) {
|
|
354
424
|
closeTurn(st.turn.lastMs, 'abandoned', event)
|
|
355
425
|
}
|
|
426
|
+
if (st.turn !== null) break
|
|
356
427
|
for (const id of Object.keys(st.subagents)) {
|
|
357
428
|
if (st.subagents[id].startMs < now) {
|
|
358
429
|
closeSubagent(id, st.subagents[id].lastMs, 'abandoned', event)
|
|
359
430
|
}
|
|
360
431
|
}
|
|
361
432
|
// Waits live only inside a turn; with none open, any left are stale.
|
|
362
|
-
|
|
433
|
+
st.waits = {}
|
|
363
434
|
break
|
|
364
435
|
default:
|
|
365
436
|
break
|
|
@@ -490,9 +561,13 @@ const writeAtomic = (file, text) => {
|
|
|
490
561
|
renameSync(tmp, file)
|
|
491
562
|
}
|
|
492
563
|
|
|
493
|
-
/** Nothing open
|
|
564
|
+
/** Nothing open and no abandoned turn a late Stop may still end: the state
|
|
565
|
+
* file can go (no file reads back as this). */
|
|
494
566
|
export const isEmptyState = (s) =>
|
|
495
|
-
s.turn === null &&
|
|
567
|
+
s.turn === null &&
|
|
568
|
+
s.abandoned === null &&
|
|
569
|
+
Object.keys(s.subagents).length === 0 &&
|
|
570
|
+
Object.keys(s.waits).length === 0
|
|
496
571
|
|
|
497
572
|
/** Delete every state file nobody has touched for STATE_MAX_AGE_MS. */
|
|
498
573
|
export const sweepStale = (dir, nowMs) => {
|
|
@@ -538,6 +613,7 @@ export const handle = async (
|
|
|
538
613
|
|
|
539
614
|
const sync = Object.hasOwn(SYNC_CAPS, name) ? SYNC_CAPS[name] : undefined
|
|
540
615
|
let closed = []
|
|
616
|
+
let abandonedId
|
|
541
617
|
const locked = await withLock(
|
|
542
618
|
file,
|
|
543
619
|
() => {
|
|
@@ -549,6 +625,7 @@ export const handle = async (
|
|
|
549
625
|
}
|
|
550
626
|
const next = applyEvent(before, input, t)
|
|
551
627
|
closed = next.closed
|
|
628
|
+
abandonedId = next.state.abandoned?.turnId
|
|
552
629
|
if (isEmptyState(next.state)) {
|
|
553
630
|
try {
|
|
554
631
|
unlinkSync(file)
|
|
@@ -566,6 +643,20 @@ export const handle = async (
|
|
|
566
643
|
return
|
|
567
644
|
}
|
|
568
645
|
if (name === 'SessionStart') sweepStale(dir, t)
|
|
646
|
+
// A main Stop or Interrupt that names a turn and found none to end can
|
|
647
|
+
// mean a turn went unsent: log it, so a lost turn leaves a trace. One with
|
|
648
|
+
// no turn id may belong to a turn this run already sent, and one that names
|
|
649
|
+
// the turn just recorded as abandoned has had that turn sent, so neither
|
|
650
|
+
// logs.
|
|
651
|
+
if (
|
|
652
|
+
(name === 'Stop' || name === 'Interrupt') &&
|
|
653
|
+
input.agentId === undefined &&
|
|
654
|
+
input.turnId !== undefined &&
|
|
655
|
+
input.turnId !== abandonedId &&
|
|
656
|
+
!closed.some((c) => c.kind === 'turn')
|
|
657
|
+
) {
|
|
658
|
+
log(`skip ${name}: no open turn`)
|
|
659
|
+
}
|
|
569
660
|
if (closed.length === 0) return
|
|
570
661
|
|
|
571
662
|
const tool = markerTool(argv)
|
|
@@ -583,7 +674,7 @@ export const handle = async (
|
|
|
583
674
|
log(`skip ${closed.length} codex span(s): no Mainwave collector in ${where}`)
|
|
584
675
|
return
|
|
585
676
|
}
|
|
586
|
-
await emit({
|
|
677
|
+
const status = await emit({
|
|
587
678
|
endpoint,
|
|
588
679
|
bearer,
|
|
589
680
|
body: buildBody(closed, resourceAttrs),
|
|
@@ -591,4 +682,6 @@ export const handle = async (
|
|
|
591
682
|
log,
|
|
592
683
|
...(sync ? { timeoutMs: sync.postTimeoutMs } : {}),
|
|
593
684
|
})
|
|
685
|
+
// The log also takes skips, so only this sidecar says a turn was delivered.
|
|
686
|
+
stampActivity(status, argv, CODEX_TURNS_LOG)
|
|
594
687
|
}
|