Repository navigation
Expand file tree
/
Copy pathagentActions.ts
More file actions
1042 lines (1029 loc) · 39 KB
/
Copy pathagentActions.ts
File metadata and controls
1042 lines (1029 loc) · 39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import path from 'node:path';
import { assertMathCanonicalPath, repositoryRelativePath } from '../../src/math/paths';
import { mathDigest, readMathFile, readMathText } from '../../src/math/mathRuntimeIo';
import { currentWorkerProject } from '../../src/solver/workerProject';
import { teamEvidenceRefSchema } from '../../src/solver/agentTeamEvidenceRef';
import {
webAgentActionKinds,
webAgentActionLimits as limits,
webLeanClassifications,
type WebAgentActionBody,
type WebAgentActionIntent,
type WebAgentFileChange,
type WebAgentLeanCheck,
type WebLeanMessage,
type WebAgentLeanSearch,
type WebAgentLibraryAction,
type WebAgentLibraryDeclaration,
} from './shared';
type Item = Record<string, unknown>;
export type AgentActionContext = {
workerId: string;
/** The Agent's own workspace; its paths read relative to it ("./generated/problem"). */ worktree: string;
/** Host directories: the application, its build state, the run directory with the other Agents' worktrees. Never shown. */
hidden: readonly string[];
/** The Agent commands' file; `bun '<tool>' check-lean` reads `math check-lean`. */ tool?: string;
apiKey?: string;
solverRunId?: string;
nativeRole?: 'lead' | 'member';
};
const escape = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');
// A directory name continues with these, so `worktree` never matches the start of `worktree-2`.
const notName = '(?![A-Za-z0-9._-])';
const ansi = /\u001b\[[0-9;?]*[ -/]*[@-~]/gu;
const lockLine = /^\{"event":"lean_lock_(?:waiting|acquired)"[^\n]*\}\n?/gmu;
const string = (value: unknown) => (typeof value === 'string' ? value : undefined);
const object = (value: unknown): Item | undefined =>
value && typeof value === 'object' && !Array.isArray(value) ? (value as Item) : undefined;
const count = (value: unknown) =>
typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined;
function clip(value: string, limit: number) {
if (value.length <= limit) return { text: value, clipped: false };
return { text: limit > 0 ? `${value.slice(0, limit - 1)}…` : '', clipped: true };
}
/** The start and the end of a long output; the middle is what a reader skips. */
function clipOutput(value: string) {
if (value.length <= limits.output) return { text: value, clipped: false };
return {
text: `${value.slice(0, limits.outputHead)}\n…\n${value.slice(value.length - (limits.output - limits.outputHead - 3))}`,
clipped: true,
};
}
/** `bash -lc '…'` as the command inside it. */
export function unwrapShell(command: string) {
const wrapped = /^(?:\/(?:usr\/)?bin\/)?(?:ba|z)?sh\s+-l?c\s+(['"])([\s\S]*)\1$/u.exec(command.trim());
if (!wrapped) return command.trim();
return wrapped[1] === "'" ? wrapped[2]!.replaceAll(`'\\''`, `'`) : wrapped[2]!.replace(/\\(["\\$`])/gu, '$1');
}
/** Replaces the Agent's workspace with "." and every host directory with "…"; `hidden` says whether one appeared. */
export function createAgentPathMask(context: AgentActionContext) {
const rules: RegExp[] = [];
const tool = context.tool
? new RegExp(String.raw`(?:\bbun\s+)?'?${escape(path.resolve(context.tool))}'?`, 'gu')
: undefined;
const own = new RegExp(escape(path.resolve(context.worktree)) + notName, 'gu');
for (const root of [...new Set(context.hidden.map(item => path.resolve(item)))].sort((a, b) => b.length - a.length))
rules.push(new RegExp(escape(root) + notName + '(?:/[^\\s\'"`;|&)\\]}]*)?', 'gu'));
return (value: string) => {
let text = context.apiKey && context.apiKey.length >= 8 ? value.replaceAll(context.apiKey, '[REDACTED]') : value;
if (tool) text = text.replace(tool, 'math');
text = text.replace(own, '.');
let hidden = false;
for (const rule of rules)
text = text.replace(rule, () => {
hidden = true;
return '…';
});
return { text, hidden };
};
}
const statuses: Record<string, WebAgentActionBody['status']> = {
inProgress: 'running',
completed: 'done',
failed: 'failed',
declined: 'declined',
};
// Streaming items start empty; only those that run for a while are worth a "running" row.
const startedKinds = new Set([
'commandExecution',
'webSearch',
'mcpToolCall',
'dynamicToolCall',
'reasoning',
'agentMessage',
'collabAgentToolCall',
]);
const collaborationTools = new Map([
['spawnAgent', 'spawn_agent'],
['sendInput', 'send_input'],
['resumeAgent', 'resume_agent'],
['wait', 'wait_agent'],
['closeAgent', 'close_agent'],
['sendMessage', 'send_message'],
['followupTask', 'followup_task'],
['interruptAgent', 'interrupt_agent'],
['listAgents', 'list_agents'],
]);
const subAgentActivities = new Map([
['started', 'agent_started'],
['interacted', 'agent_contacted'],
['interrupted', 'agent_interrupted'],
['completed', 'agent_turn_completed'],
]);
/** The last JSON object a command printed; the Agent's tools end with their result on one line. */
function lastJson(output: string): Item | undefined {
const line = output
.trimEnd()
.split('\n')
.reverse()
.find(value => value.startsWith('{'));
try {
return line ? object(JSON.parse(line)) : undefined;
} catch {
return;
}
}
const digest = (value: unknown): value is string => typeof value === 'string' && /^[a-f0-9]{64}$/u.test(value);
const classification = (value: unknown) => webLeanClassifications.find(item => item === value);
export function sanitizeAgentLeanCheck(result: Item, mask: (value: string) => string): WebAgentLeanCheck | undefined {
const classified = classification(result.classification);
if (typeof result.timedOut !== 'boolean' || (!Array.isArray(result.messages) && !classified)) return;
const messageView = (value: unknown): WebLeanMessage | undefined => {
const message = object(value),
severity = message?.severity,
text = string(message?.message);
if (!message || !text || (severity !== 'error' && severity !== 'warning' && severity !== 'info')) return;
const file = string(message.file),
line = count(message.line),
column = count(message.column),
goalText = string(message.goalText);
return {
severity,
...(file ? { file: clip(mask(file), 1_000).text } : {}),
...(line !== undefined ? { line } : {}),
...(column !== undefined ? { column } : {}),
text: clip(mask(text).trim(), limits.leanMessage).text,
...(goalText && { goalText: clip(mask(goalText), limits.leanMessage).text }),
};
};
const all = (Array.isArray(result.messages) ? result.messages : []).flatMap(value => {
const message = messageView(value);
return message ? [message] : [];
});
const error = object(result.error);
if (!all.length && error) {
const message = messageView({ ...error, severity: 'error' });
if (message) all.push(message);
}
const firstBlocking = messageView(result.firstBlocking);
// Errors first: a reader wants what blocks the proof before its warnings.
const ordered = [
...all.filter(message => message.severity === 'error'),
...all.filter(message => message.severity !== 'error'),
];
const messages = ordered.slice(0, limits.leanMessages);
const artifacts = (Array.isArray(result.diagnosticArtifacts) ? result.diagnosticArtifacts : [])
.flatMap(value => {
const ref = object(value),
file = string(ref?.path);
if (
!ref ||
!file ||
!repositoryRelativePath(file) ||
!file.startsWith('.lake/') ||
file.length > 1_000 ||
!digest(ref.digest) ||
!digest(ref.sourceDigest) ||
!digest(ref.environmentDigest)
)
return [];
return [
{ path: file, digest: ref.digest, sourceDigest: ref.sourceDigest, environmentDigest: ref.environmentDigest },
];
})
.slice(-limits.leanArtifacts);
const omitted = all.length - messages.length + (count(result.omittedMessages) ?? 0);
return {
passed: result.exitCode === 0 && !result.timedOut,
...(result.timedOut ? { timedOut: true } : {}),
messages,
...(omitted ? { omittedMessages: omitted } : {}),
...(firstBlocking && { firstBlocking }),
...(classified && { classification: classified }),
...(digest(result.sourceDigest) && { sourceDigest: result.sourceDigest }),
...(digest(result.environmentDigest) && { environmentDigest: result.environmentDigest }),
...(artifacts.length && { artifacts }),
};
}
/** Copy a bounded source only while its exact bytes still match the saved diagnostic artifact. */
function checkedLeanSource(
lean: WebAgentLeanCheck,
result: Item,
context: AgentActionContext,
mask: (value: string) => string,
): WebAgentLeanCheck['checkedSource'] {
if (
!lean.artifacts?.length ||
!lean.sourceDigest ||
!lean.environmentDigest ||
(lean.classification !== 'lean' && lean.classification !== 'success')
)
return;
try {
const project = currentWorkerProject(context.worktree);
const projectPrefix = mask(project).replace(/\/$/u, '') + '/';
const localPath = (file?: string) =>
file?.startsWith(projectPrefix) ? file.slice(projectPrefix.length) : file?.replace(/^\.\//u, '');
const blocking = localPath(lean.firstBlocking?.file);
for (const ref of lean.artifacts.toReversed()) {
if (ref.sourceDigest !== lean.sourceDigest || ref.environmentDigest !== lean.environmentDigest) continue;
const artifact = path.join(project, ref.path);
assertMathCanonicalPath(artifact);
const text = readMathText(artifact, 10 * 1024 * 1024);
if (mathDigest(text) !== ref.digest) continue;
const record = object(JSON.parse(text)),
file = string(record?.file);
if (
!record ||
record.schema !== 'theoremos.lean-diagnostics.v1' ||
record.sourceCurrent !== true ||
record.sourceDigest !== lean.sourceDigest ||
record.environmentDigest !== lean.environmentDigest ||
record.exitCode !== result.exitCode ||
!file ||
!file.endsWith('.lean') ||
!repositoryRelativePath(file) ||
(blocking && blocking !== file)
)
continue;
const suffix = '.lake/diagnostic-artifacts/' + ref.digest + '.json';
if (!ref.path.endsWith(suffix)) continue;
const root = path.join(project, ref.path.slice(0, -suffix.length));
const identity =
Array.isArray(record.sourceFiles) && record.sourceFiles.map(object).find(source => source?.file === file);
if (!identity || !digest(identity.digest)) continue;
const absolute = path.join(root, file);
assertMathCanonicalPath(absolute);
const bytes = readMathFile(absolute, limits.leanSource).bytes;
if (mathDigest(bytes) !== identity.digest) continue;
const source = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
if (mask(source) !== source) continue;
for (const message of [...lean.messages, ...(lean.firstBlocking ? [lean.firstBlocking] : [])])
if (localPath(message.file) === file) message.file = file;
return { file, digest: identity.digest, text: source, artifact: ref.digest };
}
} catch {
/* The diagnostic remains readable when the source is gone, moved or changed. */
}
}
function leanSearch(result: Item, mask: (value: string) => string): WebAgentLeanSearch | undefined {
const queries = Array.isArray(result.queries)
? result.queries
: string(result.query) !== undefined
? [result]
: undefined;
if (!queries) return;
const found = queries.slice(0, limits.queries).flatMap(value => {
const entry = object(value),
query = string(entry?.query);
if (!entry || query === undefined || !Array.isArray(entry.results)) return [];
const names = entry.results
.flatMap(match => {
const name = string(object(match)?.qualifiedName) ?? string(object(match)?.name);
return name ? [clip(name, limits.name).text] : [];
})
.slice(0, limits.names);
return [
{ query: clip(mask(query), limits.query).text, total: count(entry.totalMatches) ?? entry.results.length, names },
];
});
return found.length ? found : undefined;
}
function libraryAction(
result: Item,
command: string,
mask: (value: string) => string,
): WebAgentLibraryAction | undefined {
const operation = /\blibrary\s+(search|get|request)\b/u.exec(command)?.[1];
const schema =
operation === 'search'
? 'theorem-os.library-search.v1'
: operation === 'get'
? 'theorem-os.library-source.v1'
: operation === 'request'
? 'theorem-os.library-request-result.v1'
: undefined;
const identity = object(result.library),
id = string(identity?.id),
revision = string(identity?.revision),
catalogDigest = string(identity?.catalogDigest);
if (
!schema ||
result.schema !== schema ||
!id ||
!revision ||
!catalogDigest ||
!/^[a-f0-9]{64}$/u.test(catalogDigest)
)
return;
const library = {
id: clip(mask(id), limits.name).text,
revision: clip(mask(revision), limits.name).text,
catalogDigest,
};
const declaration = (value: unknown): WebAgentLibraryDeclaration | undefined => {
const entry = object(value),
name = string(entry?.name),
installation = entry?.installation;
if (!name || (installation !== 'installed-frozen' && installation !== 'not-installed')) return;
return { name: clip(mask(name), limits.name).text, installation };
};
const declarations = (value: unknown) => {
if (!Array.isArray(value)) return;
const entries = value.map(declaration);
if (entries.some(entry => !entry)) return;
return {
entries: (entries as WebAgentLibraryDeclaration[]).slice(0, limits.names),
omitted: Math.max(0, entries.length - limits.names),
};
};
if (operation === 'search') {
const query = string(result.query),
goal = string(result.goal),
hits = declarations(result.hits),
references = declarations(result.namedReferences);
if (query === undefined || !hits || !references) return;
return {
library,
operation,
query: clip(mask(query), limits.query).text,
...(goal ? { goal: clip(mask(goal), limits.query).text } : {}),
hits: hits.entries,
namedReferences: references.entries,
...(hits.omitted ? { omittedHits: hits.omitted } : {}),
...(references.omitted ? { omittedReferences: references.omitted } : {}),
};
}
if (operation === 'get') {
const source = object(result.source),
offset = count(source?.offset),
nextOffset = source?.nextOffset,
complete = source?.complete;
const entry = declaration({ ...object(result.declaration), installation: result.installation });
if (
!entry ||
offset === undefined ||
typeof complete !== 'boolean' ||
(complete ? nextOffset !== null : count(nextOffset) === undefined || (nextOffset as number) <= offset)
)
return;
return {
library,
operation,
declaration: entry,
source: { offset, nextOffset: nextOffset as number | null, complete },
};
}
if (operation === 'request') {
const entries = declarations(result.declarations),
status = result.status;
if (!entries?.entries.length || (status !== 'queued' && status !== 'already-installed')) return;
return {
library,
operation,
status,
declarations: entries.entries,
...(entries.omitted ? { omittedDeclarations: entries.omitted } : {}),
};
}
}
/**
* One Codex thread item as the run's owner may see it, or undefined for items that are the host's own words
* (its prompts and context) or that carry nothing to show.
*/
export function sanitizeAgentItem(
phase: 'started' | 'completed',
item: Item,
context: AgentActionContext,
): WebAgentActionBody | undefined {
const type = string(item.type),
itemId = string(item.id);
if (!type || !itemId || itemId.length > 200 || (phase === 'started' && !startedKinds.has(type))) return;
const mask = createAgentPathMask(context),
shown = (value: string) => mask(value.replace(ansi, '')).text;
const base = { workerId: context.workerId, itemId, phase };
const status = (fallback: WebAgentActionBody['status']) =>
statuses[string(item.status) ?? ''] ?? (phase === 'started' ? 'running' : fallback);
const text = (
value: string | undefined,
kind: WebAgentActionBody['kind'],
fallback: WebAgentActionBody['status'] = 'done',
): WebAgentActionBody => {
const clipped = clip(shown(value ?? '').trim(), limits.text);
return {
...base,
kind,
status: phase === 'started' ? 'running' : fallback,
...(clipped.text ? { text: clipped.text } : {}),
...(clipped.clipped ? { textClipped: true } : {}),
};
};
switch (type) {
case 'commandExecution': {
const raw = unwrapShell(string(item.command) ?? '');
const command = mask(raw.replace(ansi, '')),
cwd = string(item.cwd);
const outsideCwd =
cwd !== undefined && path.relative(path.resolve(context.worktree), path.resolve(cwd)).startsWith('..');
const rawOutput = (string(item.aggregatedOutput) ?? '').replace(ansi, '').replace(lockLine, '');
const output = mask(rawOutput);
// Completed mathematics tools read as bounded reports, their JSON only the carrier. The fields shown are masked;
// ignored source text, origins and Lean package directories never enter the structured report.
const result = !command.hidden && !outsideCwd && phase === 'completed' ? lastJson(output.text) : undefined;
const masked = (value: string) => mask(value).text;
const library = result ? libraryAction(result, command.text, masked) : undefined;
const lean =
result && !library && /\bcheck-lean\b/u.test(command.text) ? sanitizeAgentLeanCheck(result, masked) : undefined;
if (lean && result) {
const source = checkedLeanSource(lean, result, context, masked);
if (source) lean.checkedSource = source;
const work = object(result.candidate),
candidate = teamEvidenceRefSchema.safeParse(work?.ref);
// Only a saved source and its check can substantiate a trial, including a Lean failure.
if (
lean.checkedSource &&
work?.file === lean.checkedSource.file &&
context.solverRunId &&
candidate.success &&
raw.includes(candidate.data)
)
lean.candidate = {
ref: candidate.data,
solverRunId: context.solverRunId,
...(context.nativeRole && { nativeRole: context.nativeRole }),
};
}
const found =
result && !library && !lean && /\bsearch-lean\b/u.test(command.text) ? leanSearch(result, masked) : undefined;
const withheld = !library && !lean && !found && (command.hidden || output.hidden || outsideCwd);
const shownCommand = clip(command.text.replace(/\b([a-f0-9]{12})[a-f0-9]{52}\b/gu, '$1…'), limits.command);
const intents = (Array.isArray(item.commandActions) ? item.commandActions : [])
.flatMap((value): WebAgentActionIntent[] => {
const action = object(value),
kind = string(action?.type);
const type =
kind === 'read' ? 'read' : kind === 'listFiles' ? 'list' : kind === 'search' ? 'search' : undefined;
if (!action || !type) return [];
const where = string(action.path),
query = string(action.query);
return [
{
type,
...(where ? { path: clip(mask(where).text, 1_000).text } : {}),
...(query ? { query: clip(shown(query), limits.query).text } : {}),
},
];
})
.slice(0, limits.intents);
const tail = clipOutput(output.text.replace(/\s+$/u, ''));
const exitCode =
typeof item.exitCode === 'number' && Number.isSafeInteger(item.exitCode) ? item.exitCode : undefined;
// Whatever Codex calls it, a command that exited nonzero failed.
const state = status('done');
return {
...base,
kind: 'command',
status: state === 'done' && exitCode ? 'failed' : state,
command: shownCommand.text,
...(intents.length ? { intents } : {}),
...(withheld
? { withheld: true }
: library
? { library }
: lean
? { lean }
: found
? { found }
: tail.text
? { output: tail.text, ...(tail.clipped ? { outputClipped: true } : {}) }
: {}),
...(exitCode !== undefined ? { exitCode } : {}),
...(count(item.durationMs) !== undefined ? { durationMs: count(item.durationMs) } : {}),
};
}
case 'fileChange': {
const all = Array.isArray(item.changes) ? item.changes : [];
let budget = limits.diffs;
const changes = all.slice(0, limits.changes).flatMap((value): WebAgentFileChange[] => {
const change = object(value),
file = string(change?.path);
if (!change || !file) return [];
const kind = string(object(change.kind)?.type),
where = mask(file),
moved = string(object(change.kind)?.move_path);
const diff = where.hidden
? undefined
: clip(shown(string(change.diff) ?? ''), Math.min(limits.diff, Math.max(0, budget)));
if (diff) budget -= diff.text.length;
return [
{
path: clip(where.text, 1_000).text,
change: kind === 'add' || kind === 'delete' ? kind : 'update',
...(moved ? { movedTo: clip(mask(moved).text, 1_000).text } : {}),
...(diff?.text ? { diff: diff.text } : {}),
...(diff?.clipped || (where.hidden && string(change.diff)) ? { clipped: true } : {}),
},
];
});
return {
...base,
kind: 'edit',
status: status('done'),
changes,
...(all.length > changes.length ? { omittedChanges: all.length - changes.length } : {}),
};
}
case 'reasoning': {
const parts = (value: unknown) =>
Array.isArray(value)
? value.filter((part): part is string => typeof part === 'string' && part.trim() !== '')
: [];
const summary = parts(item.summary);
if (!summary.length) return;
return { ...text(summary.join('\n\n'), 'reasoning'), textSource: 'summary' };
}
case 'agentMessage': {
if (phase === 'started' && (item.phase !== 'commentary' || !string(item.text)?.trim())) return;
return {
...text(string(item.text), 'message'),
...(item.phase === 'commentary' ? { textSource: 'commentary' as const } : {}),
};
}
case 'plan':
return text(string(item.text), 'plan');
case 'webSearch': {
const action = object(item.action),
query = string(item.query) ?? string(action?.query),
url = string(action?.url);
return {
...base,
kind: 'search',
status: status('done'),
...(query ? { query: clip(shown(query), limits.query).text } : {}),
...(url ? { url: clip(url, limits.query).text } : {}),
};
}
case 'mcpToolCall':
case 'dynamicToolCall': {
const server = string(item.server) ?? string(item.namespace),
name = string(item.tool) ?? 'tool';
const args =
item.arguments === undefined ? '' : clip(shown(JSON.stringify(item.arguments) ?? ''), limits.arguments).text;
const failed = item.success === false || item.error;
return {
...base,
kind: 'tool',
status: status(failed ? 'failed' : 'done'),
tool: clip(server ? `${server}.${name}` : name, 200).text,
...(args && args !== '{}' && args !== 'null' ? { arguments: args } : {}),
...(count(item.durationMs) !== undefined ? { durationMs: count(item.durationMs) } : {}),
};
}
case 'collabAgentToolCall': {
const tool = collaborationTools.get(string(item.tool) ?? '');
if (!tool) return;
// Native thread ids and raw tool prompts are unnecessary for displaying the action.
return {
...base,
kind: 'tool',
tool: 'collaboration.' + tool,
status: item.status === 'interrupted' ? 'failed' : status('done'),
};
}
case 'subAgentActivity': {
const activity = subAgentActivities.get(string(item.kind) ?? ''),
agent = string(item.agentPath);
if (!activity) return;
// This is a lifecycle observation, with proof acceptance reported separately by Lean.
return {
...base,
kind: 'tool',
tool: 'collaboration.' + activity,
status: 'done',
...(agent ? { arguments: clip(shown(agent), limits.arguments).text } : {}),
};
}
case 'imageView':
return {
...base,
kind: 'tool',
status: 'done',
tool: 'view_image',
arguments: clip(mask(string(item.path) ?? '').text, limits.arguments).text,
};
case 'contextCompaction':
return { ...base, kind: 'compaction', status: 'done' };
// User messages and hook prompts are the host's instructions to the Agent, not something the Agent did.
default:
return;
}
}
const keys = new Set([
'workerId',
'itemId',
'phase',
'kind',
'status',
'command',
'intents',
'output',
'outputClipped',
'withheld',
'exitCode',
'durationMs',
'lean',
'found',
'library',
'changes',
'omittedChanges',
'text',
'textClipped',
'textSource',
'query',
'url',
'tool',
'arguments',
]);
const short = (value: unknown, limit: number) =>
value === undefined || (typeof value === 'string' && value.length <= limit);
const flag = (value: unknown) => value === undefined || value === true;
const integer = (value: unknown) => value === undefined || (typeof value === 'number' && Number.isSafeInteger(value));
const only = (item: Item, allowed: readonly string[]) => Object.keys(item).every(key => allowed.includes(key));
export function isWebAgentLeanCheck(value: unknown): value is WebAgentLeanCheck {
const lean = object(value);
const diagnostic = (entry: unknown) => {
const message = object(entry);
return (
!!message &&
only(message, ['severity', 'file', 'line', 'column', 'text', 'goalText']) &&
['error', 'warning', 'info'].includes(message.severity as string) &&
short(message.file, 1_000) &&
integer(message.line) &&
integer(message.column) &&
typeof message.text === 'string' &&
short(message.text, limits.leanMessage) &&
short(message.goalText, limits.leanMessage)
);
};
if (
!lean ||
!only(lean, [
'passed',
'timedOut',
'messages',
'omittedMessages',
'firstBlocking',
'classification',
'sourceDigest',
'environmentDigest',
'artifacts',
'checkedSource',
'candidate',
]) ||
typeof lean.passed !== 'boolean' ||
!flag(lean.timedOut) ||
!integer(lean.omittedMessages) ||
(lean.classification !== undefined && !classification(lean.classification)) ||
(lean.firstBlocking !== undefined && !diagnostic(lean.firstBlocking)) ||
(lean.sourceDigest !== undefined && !digest(lean.sourceDigest)) ||
(lean.environmentDigest !== undefined && !digest(lean.environmentDigest)) ||
!Array.isArray(lean.messages) ||
lean.messages.length > limits.leanMessages ||
!lean.messages.every(diagnostic)
)
return false;
if (
lean.artifacts !== undefined &&
(!Array.isArray(lean.artifacts) ||
lean.artifacts.length > limits.leanArtifacts ||
!lean.artifacts.every(value => {
const ref = object(value);
return (
ref &&
only(ref, ['path', 'digest', 'sourceDigest', 'environmentDigest']) &&
typeof ref.path === 'string' &&
short(ref.path, 1_000) &&
repositoryRelativePath(ref.path) &&
digest(ref.digest) &&
digest(ref.sourceDigest) &&
digest(ref.environmentDigest)
);
}))
)
return false;
const checked = object(lean.checkedSource);
if (
lean.checkedSource !== undefined &&
(!checked ||
!only(checked, ['file', 'digest', 'text', 'artifact']) ||
typeof checked.file !== 'string' ||
!short(checked.file, 1_000) ||
!repositoryRelativePath(checked.file) ||
typeof checked.text !== 'string' ||
Buffer.byteLength(checked.text) > limits.leanSource ||
mathDigest(checked.text) !== checked.digest ||
!Array.isArray(lean.artifacts) ||
!lean.artifacts.some(
ref =>
ref.digest === checked.artifact &&
ref.sourceDigest === lean.sourceDigest &&
ref.environmentDigest === lean.environmentDigest,
))
)
return false;
const candidate = object(lean.candidate);
return (
lean.candidate === undefined ||
Boolean(
checked &&
candidate &&
only(candidate, ['ref', 'solverRunId', 'nativeRole']) &&
(candidate.nativeRole === undefined || candidate.nativeRole === 'lead' || candidate.nativeRole === 'member') &&
teamEvidenceRefSchema.safeParse(candidate.ref).success &&
typeof candidate.solverRunId === 'string' &&
candidate.solverRunId.length > 0 &&
candidate.solverRunId.length <= 128,
)
);
}
function isLeanSearch(value: unknown) {
return (
Array.isArray(value) &&
value.length >= 1 &&
value.length <= limits.queries &&
value.every(entry => {
const query = object(entry);
return (
!!query &&
only(query, ['query', 'total', 'names']) &&
typeof query.query === 'string' &&
short(query.query, limits.query) &&
typeof query.total === 'number' &&
Number.isSafeInteger(query.total) &&
query.total >= 0 &&
Array.isArray(query.names) &&
query.names.length <= limits.names &&
query.names.every(name => typeof name === 'string' && name.length <= limits.name)
);
})
);
}
function isLibraryAction(value: unknown) {
const action = object(value),
identity = object(action?.library);
const requiredText = (value: unknown) => typeof value === 'string' && value.length > 0 && short(value, limits.name);
const omitted = (value: unknown) => value === undefined || count(value) !== undefined;
const declaration = (value: unknown) => {
const item = object(value);
return (
!!item &&
only(item, ['name', 'installation']) &&
requiredText(item.name) &&
['installed-frozen', 'not-installed'].includes(item.installation as string)
);
};
const declarations = (value: unknown) =>
Array.isArray(value) && value.length <= limits.names && value.every(declaration);
if (
!action ||
!identity ||
!only(identity, ['id', 'revision', 'catalogDigest']) ||
!requiredText(identity.id) ||
!requiredText(identity.revision) ||
typeof identity.catalogDigest !== 'string' ||
!/^[a-f0-9]{64}$/u.test(identity.catalogDigest)
)
return false;
if (action.operation === 'search')
return (
only(action, [
'library',
'operation',
'query',
'goal',
'hits',
'namedReferences',
'omittedHits',
'omittedReferences',
]) &&
typeof action.query === 'string' &&
short(action.query, limits.query) &&
short(action.goal, limits.query) &&
declarations(action.hits) &&
declarations(action.namedReferences) &&
omitted(action.omittedHits) &&
omitted(action.omittedReferences)
);
if (action.operation === 'get') {
const source = object(action.source);
return (
only(action, ['library', 'operation', 'declaration', 'source']) &&
declaration(action.declaration) &&
!!source &&
only(source, ['offset', 'nextOffset', 'complete']) &&
count(source.offset) !== undefined &&
typeof source.complete === 'boolean' &&
(source.complete
? source.nextOffset === null
: count(source.nextOffset) !== undefined && (source.nextOffset as number) > (source.offset as number))
);
}
return (
action.operation === 'request' &&
only(action, ['library', 'operation', 'status', 'declarations', 'omittedDeclarations']) &&
['queued', 'already-installed'].includes(action.status as string) &&
declarations(action.declarations) &&
(action.declarations as unknown[]).length > 0 &&
omitted(action.omittedDeclarations)
);
}
/** The shape and limits sanitizeAgentItem produces; the server accepts nothing else from a worker. */
export function isWebAgentActionBody(value: unknown): value is WebAgentActionBody {
const action = object(value);
if (!action || Object.keys(action).some(key => !keys.has(key))) return false;
if (typeof action.workerId !== 'string' || !/^[a-zA-Z0-9_-]{1,64}$/u.test(action.workerId)) return false;
if (typeof action.itemId !== 'string' || !action.itemId || action.itemId.length > 200) return false;
if (
!['started', 'completed'].includes(action.phase as string) ||
!(webAgentActionKinds as readonly unknown[]).includes(action.kind)
)
return false;
if (!['running', 'done', 'failed', 'declined'].includes(action.status as string)) return false;
if (
action.textSource !== undefined &&
!(
(action.textSource === 'summary' && action.kind === 'reasoning') ||
(action.textSource === 'commentary' && action.kind === 'message')
)
)
return false;
if (
!short(action.command, limits.command) ||
!short(action.output, limits.output) ||
!short(action.text, limits.text) ||
!short(action.query, limits.query) ||
!short(action.url, limits.query) ||
!short(action.tool, 200) ||
!short(action.arguments, limits.arguments)
)
return false;
if (
![action.outputClipped, action.withheld, action.textClipped].every(flag) ||
![action.exitCode, action.durationMs, action.omittedChanges].every(integer)
)
return false;
if (
(action.lean !== undefined && !isWebAgentLeanCheck(action.lean)) ||
(action.found !== undefined && !isLeanSearch(action.found))
)
return false;
if (
action.library !== undefined &&
(action.kind !== 'command' ||
action.phase !== 'completed' ||
!isLibraryAction(action.library) ||
[action.lean, action.found, action.output, action.outputClipped, action.withheld].some(
value => value !== undefined,
))
)
return false;
if (
action.intents !== undefined &&
(!Array.isArray(action.intents) ||
action.intents.length > limits.intents ||
!action.intents.every(intent => {
const item = object(intent);
return (
item &&
Object.keys(item).every(key => ['type', 'path', 'query'].includes(key)) &&
['read', 'list', 'search'].includes(item.type as string) &&
short(item.path, 1_000) &&
short(item.query, limits.query)
);
}))
)
return false;
if (
action.changes !== undefined &&
(!Array.isArray(action.changes) ||
action.changes.length > limits.changes ||
!action.changes.every(change => {
const item = object(change);
return (
item &&
Object.keys(item).every(key => ['path', 'change', 'movedTo', 'diff', 'clipped'].includes(key)) &&
typeof item.path === 'string' &&
short(item.path, 1_000) &&
['add', 'delete', 'update'].includes(item.change as string) &&
short(item.movedTo, 1_000) &&
short(item.diff, limits.diff) &&
flag(item.clipped)
);
}))
)
return false;
return JSON.stringify(action).length <= limits.encoded;
}
/** Coalesce only sanitized public text snapshots; lifecycle reports and tool actions remain immediate. */
export function createAgentActionStream(send: (action: WebAgentActionBody) => void) {
const reasoningIntervalMs = 4_000,
reasoningPreviewBytes = 2_048;
const runningPreview = (action: WebAgentActionBody) => {
if (action.kind !== 'reasoning' || !action.text || Buffer.byteLength(action.text) <= reasoningPreviewBytes)
return action;
const bytes = Buffer.from(action.text);
let start = bytes.length - reasoningPreviewBytes + Buffer.byteLength('…');
while ((bytes[start]! & 0xc0) === 0x80) start++;
return { ...action, text: '…' + bytes.toString('utf8', start), textClipped: true };
};
type Entry = {
sentAt?: number;
signature?: string;
latest?: WebAgentActionBody;
pending?: WebAgentActionBody;
timer?: ReturnType<typeof setTimeout>;
completed?: boolean;
};
const entries = new Map<string, Entry>();
let accepting = true;
const deliver = (action: WebAgentActionBody) => {
try {
send(action);
} catch {
/* Observation never changes the run. */
}
};
const signature = (action: WebAgentActionBody) =>
JSON.stringify([action.kind, action.textSource, action.text, action.textClipped]);
const emit = (entry: Entry, action: WebAgentActionBody) => {
entry.pending = undefined;
entry.sentAt = Date.now();
entry.signature = signature(action);
deliver(action);
};
const stop = () => {
accepting = false;
for (const entry of entries.values()) {
clearTimeout(entry.timer);
entry.timer = undefined;
entry.pending = undefined;
}
};
return {
reset() {
stop();
entries.clear();
accepting = true;
},
stop,
write(phase: 'started' | 'completed', itemId: string, action?: WebAgentActionBody, incremental = false) {
let entry = entries.get(itemId);
if (phase === 'completed') {
if (entry?.completed) return;
if (!entry) {
entry = {};
entries.set(itemId, entry);
}
clearTimeout(entry.timer);
entry.timer = undefined;
entry.pending = undefined;
entry.completed = true;
// Some clients omit text in the final lifecycle item. Preserve only an already sanitized public snapshot.
const retained = entry.latest
? { ...entry.latest, phase: 'completed' as const, status: 'done' as const }
: undefined;
const final =
action?.text === undefined && retained && (!action || action.textSource === retained.textSource)
? { ...retained, ...action }