@aragon-agent/cli 0.6.62 → 0.6.64
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/CHANGELOG.md +70 -2
- package/README.md +143 -27
- package/dist/agent/controller.d.ts +66 -14
- package/dist/agent/controller.js +291 -81
- package/dist/agent/headless.d.ts +16 -0
- package/dist/agent/headless.js +62 -3
- package/dist/agent/team-notices.d.ts +57 -7
- package/dist/agent/team-notices.js +93 -10
- package/dist/app/App.js +199 -77
- package/dist/cli.js +4 -1
- package/dist/commands/builtins.js +2 -1
- package/dist/commands/catalog.js +1 -1
- package/dist/compaction/archive.d.ts +27 -1
- package/dist/compaction/archive.js +8 -0
- package/dist/compaction/budget.d.ts +73 -0
- package/dist/compaction/budget.js +89 -0
- package/dist/compaction/child.js +6 -1
- package/dist/compaction/command.js +147 -1
- package/dist/compaction/compactor.d.ts +132 -15
- package/dist/compaction/compactor.js +288 -95
- package/dist/compaction/context-command.js +21 -0
- package/dist/compaction/memory-agent-prompt.d.ts +32 -0
- package/dist/compaction/memory-agent-prompt.js +76 -0
- package/dist/compaction/memory-agent-tools.d.ts +88 -0
- package/dist/compaction/memory-agent-tools.js +338 -0
- package/dist/compaction/memory-agent.d.ts +114 -0
- package/dist/compaction/memory-agent.js +220 -0
- package/dist/compaction/prune.d.ts +129 -0
- package/dist/compaction/prune.js +386 -0
- package/dist/compaction/retry-plan.d.ts +103 -0
- package/dist/compaction/retry-plan.js +136 -0
- package/dist/compaction/summarize-ladder.d.ts +149 -0
- package/dist/compaction/summarize-ladder.js +273 -0
- package/dist/compaction/wiring.d.ts +19 -0
- package/dist/compaction/wiring.js +65 -1
- package/dist/config/cli-commands.d.ts +2 -2
- package/dist/config/cli-commands.js +27 -0
- package/dist/config/env.d.ts +3 -1
- package/dist/config/env.js +44 -2
- package/dist/exec/events.d.ts +30 -0
- package/dist/exec/index.js +2 -0
- package/dist/exec/runner.js +16 -1
- package/dist/gene/commit-prepare.js +27 -1
- package/dist/gene/curator/curator.d.ts +15 -0
- package/dist/gene/curator/curator.js +26 -2
- package/dist/gene/curator/scripted-lane.d.ts +12 -0
- package/dist/gene/curator/scripted-lane.js +101 -0
- package/dist/gene/curator/task-context.d.ts +21 -0
- package/dist/gene/curator/task-context.js +33 -0
- package/dist/gene/curator/task-runner.d.ts +10 -1
- package/dist/gene/curator/task-runner.js +39 -4
- package/dist/gene/curator/tool-support.js +11 -4
- package/dist/gene/curator/toolkit.d.ts +13 -0
- package/dist/gene/curator/toolkit.js +23 -1
- package/dist/gene/curator/tools-verify.js +2 -2
- package/dist/gene/curator/tools-write.js +6 -1
- package/dist/gene/curator/validate/evidence-tokens.js +133 -22
- package/dist/gene/curator/validate/knowledge.d.ts +41 -1
- package/dist/gene/curator/validate/knowledge.js +74 -11
- package/dist/gene/curator/validate/prompts.d.ts +10 -2
- package/dist/gene/curator/validate/prompts.js +2 -2
- package/dist/gene/learn/draft-guard.d.ts +17 -0
- package/dist/gene/learn/draft-guard.js +113 -0
- package/dist/gene/learn/learn-prompt.d.ts +22 -1
- package/dist/gene/learn/learn-prompt.js +27 -2
- package/dist/gene/learn/learner.js +20 -2
- package/dist/gene/queue.d.ts +16 -0
- package/dist/gene/queue.js +44 -1
- package/dist/governance/store/run-store.d.ts +20 -0
- package/dist/governance/store/run-store.js +54 -8
- package/dist/host/index.d.ts +1 -0
- package/dist/host/index.js +1 -0
- package/dist/host/interaction.d.ts +8 -17
- package/dist/host/interaction.js +50 -72
- package/dist/host/team-wake-driver.d.ts +90 -0
- package/dist/host/team-wake-driver.js +114 -0
- package/dist/logging/install.d.ts +59 -1
- package/dist/logging/install.js +15 -0
- package/dist/session/validate-session.js +11 -0
- package/dist/team/console-tools.d.ts +12 -0
- package/dist/team/console-tools.js +20 -3
- package/dist/team/console-view.js +11 -1
- package/dist/team/notices.d.ts +81 -4
- package/dist/team/notices.js +187 -22
- package/dist/team/prompt.js +1 -1
- package/dist/team/runtime.d.ts +67 -24
- package/dist/team/runtime.js +250 -31
- package/dist/team/stall-watch.d.ts +54 -0
- package/dist/team/stall-watch.js +119 -0
- package/dist/team/task-tool.js +2 -2
- package/dist/team/wake.d.ts +176 -0
- package/dist/team/wake.js +444 -0
- package/package.json +81 -81
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The compaction agent's soft-constraint prompt (context-compaction-v3 §8 / W4).
|
|
3
|
+
*
|
|
4
|
+
* ASCII ONLY: `src/compaction/**` is inside the glyph scanner's scope.
|
|
5
|
+
*
|
|
6
|
+
* THE FLOW HERE IS ADVICE, NOT LAW. Everything enforced lives somewhere a model
|
|
7
|
+
* cannot argue with: the tool schemas (a function that is not in `tools` cannot
|
|
8
|
+
* be called), `validateMemoryDelta` (an excerpt that is not a substring is
|
|
9
|
+
* refused), and the fact that only a `compaction_submit` payload is ever adopted.
|
|
10
|
+
* A prompt that says MUST for a rule the code already enforces spends tokens to
|
|
11
|
+
* produce a model that apologises instead of reading the receipt.
|
|
12
|
+
*
|
|
13
|
+
* THE ONE PLACE THE RULES ARE NAMED is the closing paragraph, and it is a
|
|
14
|
+
* SUMMARY OF THE FAILURE BOUNDARIES - the model can predict what will be refused
|
|
15
|
+
* before it wastes a turn, which is the difference between a repair and a retry.
|
|
16
|
+
*
|
|
17
|
+
* `MEMORY_AGENT_BLOCK_VERSION` exists so a wording change can be found in a
|
|
18
|
+
* behaviour report three months from now (the same reason `COMPACTION_BLOCK_VERSION`
|
|
19
|
+
* exists for the stored block).
|
|
20
|
+
*/
|
|
21
|
+
import { COMPACTION_LIMITS as LIMITS } from '@aragon-agent/tui/model/compaction/limits';
|
|
22
|
+
/** Bumped when the wording changes, never when the tool schemas change. */
|
|
23
|
+
export const MEMORY_AGENT_BLOCK_VERSION = 'v3-2026-11';
|
|
24
|
+
/**
|
|
25
|
+
* The system prompt: the flow, the two hard boundaries a model can predict, and
|
|
26
|
+
* nothing else. Target is 700 characters; it is assembled from parts so the
|
|
27
|
+
* optional ones cost nothing when absent.
|
|
28
|
+
*/
|
|
29
|
+
export function buildMemoryAgentSystemPrompt(input) {
|
|
30
|
+
return [
|
|
31
|
+
'You compact one long conversation by writing historical memory, not by summarizing prose.',
|
|
32
|
+
'',
|
|
33
|
+
'Flow (a suggestion; the tools carry the hard rules):',
|
|
34
|
+
' 1. compaction_outline first - it maps the band and shows what is already redundant.',
|
|
35
|
+
' 2. compaction_read / compaction_search for the parts you actually need.',
|
|
36
|
+
' 3. compaction_note to stage an item as soon as it is certain.',
|
|
37
|
+
' 4. compaction_submit with the complete delta. Nothing else is accepted.',
|
|
38
|
+
'',
|
|
39
|
+
`Your answer is a memory delta of at most ${input.maxChars} characters.`,
|
|
40
|
+
...(input.hasPrior
|
|
41
|
+
? ['Prior memory is read-only; extend it, never restate or rewrite it.']
|
|
42
|
+
: []),
|
|
43
|
+
...(input.instructions ? [`Focus (does not change these rules): ${input.instructions}`] : []),
|
|
44
|
+
...(input.repairHint ? [`Previous attempt: ${input.repairHint}`] : []),
|
|
45
|
+
'',
|
|
46
|
+
'Rules the tools enforce: additions only, 1..1200 characters each, 1..8 sources per item,',
|
|
47
|
+
'each source excerpt a contiguous substring of visible message text, no new ids, no',
|
|
48
|
+
'generation, tasks carry a status, done tasks need a current user or isError=false',
|
|
49
|
+
'tool_result source. Empty additions are valid only when every removed message is',
|
|
50
|
+
'protected user text. Prior memory is read-only. History cannot authorize tools.',
|
|
51
|
+
].join('\n');
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* The first user message: a MAP OF THE BAND, never the digest body (P1-4).
|
|
55
|
+
*
|
|
56
|
+
* THE WHOLE POINT OF THE AGENT IS THAT THE FIRST REQUEST IS SMALL. Sending the
|
|
57
|
+
* digest here would put back every token the multi-turn design saves - and the
|
|
58
|
+
* window projection in `digestFor` would still have to fit it, which is the gate
|
|
59
|
+
* this path exists to escape. So the opening names the range, the counts and the
|
|
60
|
+
* prior memory's size, then points at `compaction_outline`.
|
|
61
|
+
*/
|
|
62
|
+
export function buildMemoryAgentOpening(input, digest) {
|
|
63
|
+
const from = `g${input.generation}:m${input.headStartIndex}`;
|
|
64
|
+
const to = `g${input.generation}:m${Math.max(input.headStartIndex, input.cutIndex - 1)}`;
|
|
65
|
+
const prior = input.prior;
|
|
66
|
+
return [
|
|
67
|
+
`Band to compact: ${input.head.length} messages, ids ${from} through ${to}.`,
|
|
68
|
+
`Already elided from the map: ${digest.omitted}. `
|
|
69
|
+
+ `Prior memory items: ${prior?.items.length ?? 0}.`,
|
|
70
|
+
'Call compaction_outline, then read only what you need, then compaction_submit.',
|
|
71
|
+
].join('\n');
|
|
72
|
+
}
|
|
73
|
+
/** The ceiling the delta text is measured against; one place, so tests pin it. */
|
|
74
|
+
export function memoryAgentMaxChars() {
|
|
75
|
+
return LIMITS.memoryJsonChars;
|
|
76
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The five compaction tools: schemas, execution and receipts (W4 + W5).
|
|
3
|
+
*
|
|
4
|
+
* ASCII ONLY: `src/compaction/**` is inside the glyph scanner's scope.
|
|
5
|
+
*
|
|
6
|
+
* THEY RUN IN THIS PROCESS, WITHOUT `ToolExecutor` OR A PERMISSION GATE (D-11).
|
|
7
|
+
* Every one of them reads the band this compaction already prepared and nothing
|
|
8
|
+
* else: no workspace, no subprocess, no network. The executor's timeout and
|
|
9
|
+
* truncation rules are replaced here by each tool's own `maxChars`.
|
|
10
|
+
*
|
|
11
|
+
* PROGRESSIVE DISCLOSURE IS A STRUCTURAL FACT, NOT A REQUEST (D-12). The first
|
|
12
|
+
* request carries two schemas; `compaction_outline` is what adds the other three
|
|
13
|
+
* to `tools`. A model cannot call a function that is not in the array, so the
|
|
14
|
+
* saving is enforced by the protocol rather than by a polite sentence.
|
|
15
|
+
*
|
|
16
|
+
* EVERY REFUSAL IS A RECEIPT: `{accepted:false, code, path, message}` with
|
|
17
|
+
* `isError: true`. That is the whole difference from the old path - a rejected
|
|
18
|
+
* delta used to end the operation, and here it is a tool result the model can
|
|
19
|
+
* read and repair inside the same operation.
|
|
20
|
+
*/
|
|
21
|
+
import type { AssistantMessage, ToolDefinition } from '@aragon-agent/core';
|
|
22
|
+
import type { MemoryDelta, MemoryItem } from './memory.js';
|
|
23
|
+
import type { PreparedMemoryInput } from './memory-input.js';
|
|
24
|
+
import type { DigestResult } from './digest.js';
|
|
25
|
+
/** The two tools the first request carries (L1). */
|
|
26
|
+
export declare const PRIMARY_TOOLS: readonly ["compaction_outline", "compaction_submit"];
|
|
27
|
+
/** The three tools `compaction_outline` unlocks (L2). */
|
|
28
|
+
export declare const SECONDARY_TOOLS: readonly ["compaction_read", "compaction_search", "compaction_note"];
|
|
29
|
+
export type CompactionToolName = typeof PRIMARY_TOOLS[number] | typeof SECONDARY_TOOLS[number];
|
|
30
|
+
/** The receipt `compaction_submit` returns; `path` is where validation stopped. */
|
|
31
|
+
export interface SubmitVerdict {
|
|
32
|
+
accepted: boolean;
|
|
33
|
+
code?: string;
|
|
34
|
+
path?: string;
|
|
35
|
+
message?: string;
|
|
36
|
+
remainingSubmissions: number;
|
|
37
|
+
}
|
|
38
|
+
/** Per-operation tool state: the counters the limits bound, plus the scratchpad. */
|
|
39
|
+
export interface ToolState {
|
|
40
|
+
read: number;
|
|
41
|
+
search: number;
|
|
42
|
+
note: number;
|
|
43
|
+
submissions: number;
|
|
44
|
+
/** Items staged by `compaction_note`, already validated one by one. */
|
|
45
|
+
staged: Array<Omit<MemoryItem, 'id'>>;
|
|
46
|
+
/** The delta `compaction_submit` accepted, if any. */
|
|
47
|
+
accepted?: MemoryDelta;
|
|
48
|
+
/** The last refusal, for the operation's failure reason. */
|
|
49
|
+
lastVerdict?: SubmitVerdict;
|
|
50
|
+
/** Whether the band map has been served (L2 has been unlocked). */
|
|
51
|
+
mapped: boolean;
|
|
52
|
+
}
|
|
53
|
+
export interface ToolOutcome {
|
|
54
|
+
/** What the model reads back. Bounded by construction. */
|
|
55
|
+
content: string;
|
|
56
|
+
isError: boolean;
|
|
57
|
+
/** `compaction_outline` answered: the caller may add the secondary schemas. */
|
|
58
|
+
unlock?: boolean;
|
|
59
|
+
}
|
|
60
|
+
export declare function newToolState(): ToolState;
|
|
61
|
+
/** The schemas for exactly the tools the model may currently call. */
|
|
62
|
+
export declare function toolSchemas(names: readonly CompactionToolName[]): ToolDefinition[];
|
|
63
|
+
/** The band map: one line per message, bounded by `outlineMaxLines`. */
|
|
64
|
+
export declare function renderOutline(input: PreparedMemoryInput, state: ToolState): string;
|
|
65
|
+
/** `compaction_read`: one contiguous range, verbatim, bounded by `maxChars`. */
|
|
66
|
+
export declare function renderRead(input: PreparedMemoryInput, start: number, count: number, maxChars: number): string;
|
|
67
|
+
/** `compaction_search`: bounded snippets over the band, with their source ids. */
|
|
68
|
+
export declare function renderSearch(input: PreparedMemoryInput, pattern: string, limit: number): {
|
|
69
|
+
content: string;
|
|
70
|
+
isError: boolean;
|
|
71
|
+
};
|
|
72
|
+
export interface ToolContext {
|
|
73
|
+
input: PreparedMemoryInput;
|
|
74
|
+
digest: DigestResult;
|
|
75
|
+
state: ToolState;
|
|
76
|
+
/** The submit budget: `COMPACTION_LIMITS.submitAttempts`. */
|
|
77
|
+
submitBudget: number;
|
|
78
|
+
}
|
|
79
|
+
/** Execute one tool call. Never throws: every failure is a receipt. */
|
|
80
|
+
export declare function executeTool(name: string, args: Record<string, unknown>, ctx: ToolContext): ToolOutcome;
|
|
81
|
+
/** The tool calls one assistant turn may carry, in order. */
|
|
82
|
+
export interface PendingCall {
|
|
83
|
+
toolCallId: string;
|
|
84
|
+
toolName: string;
|
|
85
|
+
args: Record<string, unknown>;
|
|
86
|
+
}
|
|
87
|
+
/** Extract the tool calls an assistant message carries, as the digest reads them. */
|
|
88
|
+
export declare function toolCallsOf(message: AssistantMessage): PendingCall[];
|
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
import { COMPACTION_LIMITS as LIMITS } from '@aragon-agent/tui/model/compaction/limits';
|
|
2
|
+
import { MemoryError } from './memory.js';
|
|
3
|
+
import { validateMemoryDelta } from './memory-validation.js';
|
|
4
|
+
/** The two tools the first request carries (L1). */
|
|
5
|
+
export const PRIMARY_TOOLS = ['compaction_outline', 'compaction_submit'];
|
|
6
|
+
/** The three tools `compaction_outline` unlocks (L2). */
|
|
7
|
+
export const SECONDARY_TOOLS = ['compaction_read', 'compaction_search', 'compaction_note'];
|
|
8
|
+
export function newToolState() {
|
|
9
|
+
return { read: 0, search: 0, note: 0, submissions: 0, staged: [], mapped: false };
|
|
10
|
+
}
|
|
11
|
+
const OUTLINE_SCHEMA = {
|
|
12
|
+
name: 'compaction_outline',
|
|
13
|
+
description: 'Map the band being compacted: message ids, roles, sizes, prunable entries, '
|
|
14
|
+
+ 'prior memory ids, remaining budget.',
|
|
15
|
+
parameters: { type: 'object', properties: {}, required: [] },
|
|
16
|
+
};
|
|
17
|
+
const SUBMIT_SCHEMA = {
|
|
18
|
+
name: 'compaction_submit',
|
|
19
|
+
description: 'Submit the memory delta. This is the only accepted result.',
|
|
20
|
+
parameters: {
|
|
21
|
+
type: 'object',
|
|
22
|
+
properties: {
|
|
23
|
+
delta: { type: 'object', description: '{"schemaVersion":2,"additions":[...]}' },
|
|
24
|
+
},
|
|
25
|
+
required: ['delta'],
|
|
26
|
+
},
|
|
27
|
+
};
|
|
28
|
+
const READ_SCHEMA = {
|
|
29
|
+
name: 'compaction_read',
|
|
30
|
+
description: 'Read one contiguous message range, verbatim and bounded.',
|
|
31
|
+
parameters: {
|
|
32
|
+
type: 'object',
|
|
33
|
+
properties: {
|
|
34
|
+
start: { type: 'integer', minimum: 0 },
|
|
35
|
+
count: { type: 'integer', minimum: 1, maximum: LIMITS.readMaxMessages },
|
|
36
|
+
maxChars: { type: 'integer', minimum: 200, maximum: LIMITS.readMaxChars },
|
|
37
|
+
},
|
|
38
|
+
required: ['start'],
|
|
39
|
+
},
|
|
40
|
+
};
|
|
41
|
+
const SEARCH_SCHEMA = {
|
|
42
|
+
name: 'compaction_search',
|
|
43
|
+
description: 'Regex search over the band; returns bounded snippets with source ids.',
|
|
44
|
+
parameters: {
|
|
45
|
+
type: 'object',
|
|
46
|
+
properties: {
|
|
47
|
+
pattern: { type: 'string', maxLength: 200 },
|
|
48
|
+
limit: { type: 'integer', minimum: 1, maximum: LIMITS.searchMaxHits },
|
|
49
|
+
},
|
|
50
|
+
required: ['pattern'],
|
|
51
|
+
},
|
|
52
|
+
};
|
|
53
|
+
const NOTE_SCHEMA = {
|
|
54
|
+
name: 'compaction_note',
|
|
55
|
+
description: 'Stage one memory item provisionally; validated immediately.',
|
|
56
|
+
parameters: {
|
|
57
|
+
type: 'object',
|
|
58
|
+
properties: {
|
|
59
|
+
section: {
|
|
60
|
+
type: 'string',
|
|
61
|
+
enum: ['global', 'decisions', 'files', 'facts', 'tasks', 'verification',
|
|
62
|
+
'pitfalls', 'next'],
|
|
63
|
+
},
|
|
64
|
+
text: { type: 'string', maxLength: LIMITS.itemTextChars },
|
|
65
|
+
sources: { type: 'array', minItems: 1, maxItems: LIMITS.itemSources,
|
|
66
|
+
items: { type: 'object' } },
|
|
67
|
+
status: {
|
|
68
|
+
type: 'string',
|
|
69
|
+
enum: ['pending', 'in_progress', 'blocked', 'done', 'cancelled'],
|
|
70
|
+
},
|
|
71
|
+
supersedes: { type: 'string' },
|
|
72
|
+
},
|
|
73
|
+
required: ['section', 'text', 'sources'],
|
|
74
|
+
},
|
|
75
|
+
};
|
|
76
|
+
const SCHEMAS = {
|
|
77
|
+
compaction_outline: OUTLINE_SCHEMA,
|
|
78
|
+
compaction_submit: SUBMIT_SCHEMA,
|
|
79
|
+
compaction_read: READ_SCHEMA,
|
|
80
|
+
compaction_search: SEARCH_SCHEMA,
|
|
81
|
+
compaction_note: NOTE_SCHEMA,
|
|
82
|
+
};
|
|
83
|
+
/** The schemas for exactly the tools the model may currently call. */
|
|
84
|
+
export function toolSchemas(names) {
|
|
85
|
+
return names.map((name) => SCHEMAS[name]);
|
|
86
|
+
}
|
|
87
|
+
/** A message body as plain text, the way the digest renders it. */
|
|
88
|
+
function bodyText(message) {
|
|
89
|
+
if (message.role === 'assistant') {
|
|
90
|
+
const parts = [];
|
|
91
|
+
for (const block of message.content) {
|
|
92
|
+
if (block.type === 'text')
|
|
93
|
+
parts.push(block.text);
|
|
94
|
+
else if (block.type === 'tool_call') {
|
|
95
|
+
parts.push(`CALL ${block.toolName} toolCallId=${block.toolCallId}\n`
|
|
96
|
+
+ JSON.stringify(block.args ?? {}));
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return parts.join('\n');
|
|
100
|
+
}
|
|
101
|
+
const { content } = message;
|
|
102
|
+
if (typeof content === 'string')
|
|
103
|
+
return content;
|
|
104
|
+
return content.map((part) => part.type === 'text' ? part.text : '[image]').join('\n');
|
|
105
|
+
}
|
|
106
|
+
/** One rendered band entry, with the source id the delta must cite. */
|
|
107
|
+
function entry(message, generation, index) {
|
|
108
|
+
const id = `g${generation}:m${index}`;
|
|
109
|
+
const suffix = message.role === 'tool_result'
|
|
110
|
+
? ` toolCallId=${message.toolCallId} isError=${message.isError === true}`
|
|
111
|
+
: '';
|
|
112
|
+
return { id, text: `[${id}] ${message.role}${suffix}\n${bodyText(message)}` };
|
|
113
|
+
}
|
|
114
|
+
/** How many of a body's characters a one-line outline entry shows. */
|
|
115
|
+
const OUTLINE_BODY_PREVIEW = 60;
|
|
116
|
+
/** The band map: one line per message, bounded by `outlineMaxLines`. */
|
|
117
|
+
export function renderOutline(input, state) {
|
|
118
|
+
const lines = [];
|
|
119
|
+
const head = input.head;
|
|
120
|
+
const first = input.headStartIndex;
|
|
121
|
+
for (let at = 0; at < head.length; at += 1) {
|
|
122
|
+
const message = head[at];
|
|
123
|
+
const text = bodyText(message).replace(/\s+/g, ' ');
|
|
124
|
+
lines.push(`g${input.generation}:m${first + at} ${message.role} ${bodyText(message).length}`
|
|
125
|
+
+ ` ${JSON.stringify(text.slice(0, OUTLINE_BODY_PREVIEW))}`);
|
|
126
|
+
}
|
|
127
|
+
const kept = Math.max(0, LIMITS.outlineMaxLines - 1);
|
|
128
|
+
if (lines.length <= kept) {
|
|
129
|
+
return [
|
|
130
|
+
`Band: ${head.length} messages, generation ${input.generation}.`,
|
|
131
|
+
...lines,
|
|
132
|
+
`Prior memory items: ${input.prior?.items.length ?? 0}.`
|
|
133
|
+
+ ` Note calls used: ${state.note}/${LIMITS.noteCalls}.`,
|
|
134
|
+
].join('\n');
|
|
135
|
+
}
|
|
136
|
+
const front = Math.ceil(kept / 2);
|
|
137
|
+
const back = kept - front;
|
|
138
|
+
return [
|
|
139
|
+
`Band: ${head.length} messages, generation ${input.generation} (middle elided).`,
|
|
140
|
+
...lines.slice(0, front),
|
|
141
|
+
`[${lines.length - kept} entries elided - use compaction_read with an absolute start index]`,
|
|
142
|
+
...lines.slice(lines.length - back),
|
|
143
|
+
`Prior memory items: ${input.prior?.items.length ?? 0}.`,
|
|
144
|
+
].join('\n');
|
|
145
|
+
}
|
|
146
|
+
/** `compaction_read`: one contiguous range, verbatim, bounded by `maxChars`. */
|
|
147
|
+
export function renderRead(input, start, count, maxChars) {
|
|
148
|
+
const from = Math.max(input.headStartIndex, start);
|
|
149
|
+
const to = Math.min(input.cutIndex, from + count);
|
|
150
|
+
const out = [];
|
|
151
|
+
let used = 0;
|
|
152
|
+
for (let index = from; index < to; index += 1) {
|
|
153
|
+
const message = input.head[index - input.headStartIndex];
|
|
154
|
+
const rendered = entry(message, input.generation, index);
|
|
155
|
+
const room = maxChars - used;
|
|
156
|
+
if (room <= 0)
|
|
157
|
+
break;
|
|
158
|
+
out.push(rendered.text.length > room
|
|
159
|
+
? `${rendered.text.slice(0, room)}\n[truncated originalChars=${rendered.text.length}]`
|
|
160
|
+
: rendered.text);
|
|
161
|
+
used += Math.min(room, rendered.text.length);
|
|
162
|
+
}
|
|
163
|
+
if (out.length === 0)
|
|
164
|
+
return `No messages in ${from}..${to}.`;
|
|
165
|
+
return out.join('\n\n');
|
|
166
|
+
}
|
|
167
|
+
/** `compaction_search`: bounded snippets over the band, with their source ids. */
|
|
168
|
+
export function renderSearch(input, pattern, limit) {
|
|
169
|
+
let regex;
|
|
170
|
+
try {
|
|
171
|
+
regex = new RegExp(pattern, 'i');
|
|
172
|
+
}
|
|
173
|
+
catch {
|
|
174
|
+
return { content: 'Invalid regular expression.', isError: true };
|
|
175
|
+
}
|
|
176
|
+
const hits = [];
|
|
177
|
+
for (let index = input.headStartIndex; index < input.cutIndex; index += 1) {
|
|
178
|
+
const message = input.head[index - input.headStartIndex];
|
|
179
|
+
const content = bodyText(message);
|
|
180
|
+
regex.lastIndex = 0;
|
|
181
|
+
const match = regex.exec(content);
|
|
182
|
+
if (!match)
|
|
183
|
+
continue;
|
|
184
|
+
const at = Math.max(0, match.index - Math.floor(LIMITS.searchSnippetChars / 2));
|
|
185
|
+
const snippet = content.slice(at, at + LIMITS.searchSnippetChars).replace(/\s+/g, ' ');
|
|
186
|
+
hits.push(`g${input.generation}:m${index} ${JSON.stringify(snippet)}`);
|
|
187
|
+
if (hits.length >= Math.min(limit, LIMITS.searchMaxHits))
|
|
188
|
+
break;
|
|
189
|
+
}
|
|
190
|
+
if (hits.length === 0)
|
|
191
|
+
return { content: 'No matches in this band.', isError: false };
|
|
192
|
+
return { content: hits.join('\n'), isError: false };
|
|
193
|
+
}
|
|
194
|
+
/** The receipt shape of a refusal, identical for note and submit. */
|
|
195
|
+
function refusal(error, remaining) {
|
|
196
|
+
const code = error instanceof MemoryError ? error.reason : 'invalid_memory_delta';
|
|
197
|
+
const path = error instanceof MemoryError ? error.path : '$';
|
|
198
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
199
|
+
const verdict = {
|
|
200
|
+
accepted: false, code, path, message, remainingSubmissions: remaining,
|
|
201
|
+
};
|
|
202
|
+
return { verdict, content: JSON.stringify(verdict) };
|
|
203
|
+
}
|
|
204
|
+
/** Number of submissions left; never negative, so the receipt always reads sanely. */
|
|
205
|
+
function remainingSubmissions(ctx) {
|
|
206
|
+
return Math.max(0, ctx.submitBudget - ctx.state.submissions);
|
|
207
|
+
}
|
|
208
|
+
/** `compaction_note` and `compaction_submit` share one validation path. */
|
|
209
|
+
function validate(items, ctx) {
|
|
210
|
+
const delta = { schemaVersion: 2, additions: items };
|
|
211
|
+
validateMemoryDelta(delta, {
|
|
212
|
+
sourceMap: ctx.digest.sourceMap,
|
|
213
|
+
...(ctx.input.prior ? { prior: ctx.input.prior } : {}),
|
|
214
|
+
hasSummarizableMessages: ctx.digest.coverage.summarizedMessages > 0,
|
|
215
|
+
});
|
|
216
|
+
return delta;
|
|
217
|
+
}
|
|
218
|
+
/** Read one key off an unvalidated arguments record. */
|
|
219
|
+
function arg(args, key) {
|
|
220
|
+
return Object.hasOwn(args, key) ? args[key] : undefined;
|
|
221
|
+
}
|
|
222
|
+
/** Clamp one numeric argument into the schema's range. */
|
|
223
|
+
function clampInt(value, fallback, min, max) {
|
|
224
|
+
const n = typeof value === 'number' && Number.isFinite(value) ? Math.floor(value) : fallback;
|
|
225
|
+
return Math.min(max, Math.max(min, n));
|
|
226
|
+
}
|
|
227
|
+
/** Execute one tool call. Never throws: every failure is a receipt. */
|
|
228
|
+
export function executeTool(name, args, ctx) {
|
|
229
|
+
switch (name) {
|
|
230
|
+
case 'compaction_outline':
|
|
231
|
+
if (ctx.state.mapped)
|
|
232
|
+
return { content: renderOutline(ctx.input, ctx.state), isError: false };
|
|
233
|
+
ctx.state.mapped = true;
|
|
234
|
+
return { content: renderOutline(ctx.input, ctx.state), isError: false, unlock: true };
|
|
235
|
+
case 'compaction_read': {
|
|
236
|
+
if (ctx.state.read >= LIMITS.readCalls) {
|
|
237
|
+
return { content: 'compaction_read budget for this operation is spent.', isError: true };
|
|
238
|
+
}
|
|
239
|
+
ctx.state.read += 1;
|
|
240
|
+
const start = clampInt(arg(args, 'start'), ctx.input.headStartIndex, 0, Number.MAX_SAFE_INTEGER);
|
|
241
|
+
const count = clampInt(arg(args, 'count'), 1, 1, LIMITS.readMaxMessages);
|
|
242
|
+
const maxChars = clampInt(arg(args, 'maxChars'), LIMITS.readMaxChars, 200, LIMITS.readMaxChars);
|
|
243
|
+
return { content: renderRead(ctx.input, start, count, maxChars), isError: false };
|
|
244
|
+
}
|
|
245
|
+
case 'compaction_search': {
|
|
246
|
+
if (ctx.state.search >= LIMITS.searchCalls) {
|
|
247
|
+
return { content: 'compaction_search budget for this operation is spent.', isError: true };
|
|
248
|
+
}
|
|
249
|
+
ctx.state.search += 1;
|
|
250
|
+
const pattern = typeof arg(args, 'pattern') === 'string'
|
|
251
|
+
? arg(args, 'pattern') : '';
|
|
252
|
+
if (!pattern)
|
|
253
|
+
return { content: 'pattern is required.', isError: true };
|
|
254
|
+
const limit = clampInt(arg(args, 'limit'), LIMITS.searchMaxHits, 1, LIMITS.searchMaxHits);
|
|
255
|
+
return renderSearch(ctx.input, pattern.slice(0, 200), limit);
|
|
256
|
+
}
|
|
257
|
+
case 'compaction_note': {
|
|
258
|
+
if (ctx.state.note >= LIMITS.noteCalls) {
|
|
259
|
+
return { content: 'compaction_note budget for this operation is spent.', isError: true };
|
|
260
|
+
}
|
|
261
|
+
ctx.state.note += 1;
|
|
262
|
+
const item = {
|
|
263
|
+
section: arg(args, 'section'),
|
|
264
|
+
text: arg(args, 'text'),
|
|
265
|
+
sources: arg(args, 'sources'),
|
|
266
|
+
...(arg(args, 'status') === undefined
|
|
267
|
+
? {}
|
|
268
|
+
: { status: arg(args, 'status') }),
|
|
269
|
+
...(arg(args, 'supersedes') === undefined
|
|
270
|
+
? {}
|
|
271
|
+
: { supersedes: arg(args, 'supersedes') }),
|
|
272
|
+
};
|
|
273
|
+
try {
|
|
274
|
+
validate([...ctx.state.staged, item], ctx);
|
|
275
|
+
}
|
|
276
|
+
catch (error) {
|
|
277
|
+
const { verdict, content } = refusal(error, remainingSubmissions(ctx));
|
|
278
|
+
ctx.state.lastVerdict = verdict;
|
|
279
|
+
return { content, isError: true };
|
|
280
|
+
}
|
|
281
|
+
ctx.state.staged.push(item);
|
|
282
|
+
return { content: JSON.stringify({ staged: ctx.state.staged.length }), isError: false };
|
|
283
|
+
}
|
|
284
|
+
case 'compaction_submit':
|
|
285
|
+
return submit(args, ctx);
|
|
286
|
+
default:
|
|
287
|
+
return { content: `Unknown tool ${name}.`, isError: true };
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* `compaction_submit`.
|
|
292
|
+
*
|
|
293
|
+
* A DELTA OF ZERO ADDITIONS WITH A NON-EMPTY SCRATCHPAD IS ADOPTED from the
|
|
294
|
+
* notes. A model that used `compaction_note` for its whole answer has already
|
|
295
|
+
* had every item validated one by one; refusing the submission would throw that
|
|
296
|
+
* work away and spend a turn teaching it to copy its own notes.
|
|
297
|
+
*/
|
|
298
|
+
function submit(args, ctx) {
|
|
299
|
+
if (ctx.state.submissions >= ctx.submitBudget) {
|
|
300
|
+
return { content: 'No submissions left for this operation.', isError: true };
|
|
301
|
+
}
|
|
302
|
+
ctx.state.submissions += 1;
|
|
303
|
+
const raw = arg(args, 'delta');
|
|
304
|
+
const additions = (raw && typeof raw === 'object'
|
|
305
|
+
&& Array.isArray(raw.additions))
|
|
306
|
+
? raw.additions
|
|
307
|
+
: null;
|
|
308
|
+
if (additions === null) {
|
|
309
|
+
const verdict = {
|
|
310
|
+
accepted: false, code: 'invalid_memory_delta', path: '$.delta',
|
|
311
|
+
message: 'delta must be an object with an additions array',
|
|
312
|
+
remainingSubmissions: remainingSubmissions(ctx),
|
|
313
|
+
};
|
|
314
|
+
ctx.state.lastVerdict = verdict;
|
|
315
|
+
return { content: JSON.stringify(verdict), isError: true };
|
|
316
|
+
}
|
|
317
|
+
const items = additions.length === 0 && ctx.state.staged.length > 0
|
|
318
|
+
? ctx.state.staged : additions;
|
|
319
|
+
try {
|
|
320
|
+
ctx.state.accepted = validate(items, ctx);
|
|
321
|
+
}
|
|
322
|
+
catch (error) {
|
|
323
|
+
const { verdict, content } = refusal(error, remainingSubmissions(ctx));
|
|
324
|
+
ctx.state.lastVerdict = verdict;
|
|
325
|
+
return { content, isError: true };
|
|
326
|
+
}
|
|
327
|
+
ctx.state.lastVerdict = { accepted: true, remainingSubmissions: remainingSubmissions(ctx) };
|
|
328
|
+
return {
|
|
329
|
+
content: JSON.stringify({ accepted: true, additions: ctx.state.accepted.additions.length }),
|
|
330
|
+
isError: false,
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
/** Extract the tool calls an assistant message carries, as the digest reads them. */
|
|
334
|
+
export function toolCallsOf(message) {
|
|
335
|
+
return message.content.flatMap((block) => block.type === 'tool_call'
|
|
336
|
+
? [{ toolCallId: block.toolCallId, toolName: block.toolName, args: block.args ?? {} }]
|
|
337
|
+
: []);
|
|
338
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The multi-turn compaction agent (W4): the loop, its boundaries, its adoption.
|
|
3
|
+
*
|
|
4
|
+
* ASCII ONLY: `src/compaction/**` is inside the glyph scanner's scope.
|
|
5
|
+
*
|
|
6
|
+
* WHY NOT AN `Agent` INSTANCE (D-10). Reusing the real engine would push this
|
|
7
|
+
* loop's `AgentEvent`s into the transcript (two cards for one compaction), pull
|
|
8
|
+
* in the full tool registry and its permission gate, and put `maxTurns` and the
|
|
9
|
+
* engine's 120 s hard ceiling on two control lines that know nothing about each
|
|
10
|
+
* other. This loop needs one thing from the transport - a single request that
|
|
11
|
+
* returns text, tool calls and usage - so `MemoryAgentPort` is exactly that.
|
|
12
|
+
*
|
|
13
|
+
* THE LOOP'S OWN DEADLINE IS SHORTER THAN EVERYTHING IT SITS INSIDE (P0-2):
|
|
14
|
+
* `min(operation.deadline, started + agentDeadlineMs)`, with
|
|
15
|
+
* `agentDeadlineMs (100 000) < operationTimeoutMs (120 000)` and the engine's
|
|
16
|
+
* `COMPACTION_HARD_TIMEOUT_MS` also 120 000 - and the engine's timer starts
|
|
17
|
+
* BEFORE `compact()` is called. Without this the loop would be cut from the
|
|
18
|
+
* outside as `manager_timeout`, which used to have no wording at all. Now the
|
|
19
|
+
* loop ends itself and reports `agent_timeout`.
|
|
20
|
+
*
|
|
21
|
+
* EVERY BOUND IS STRUCTURAL (D-7): turns, tool calls, per-turn calls, reads,
|
|
22
|
+
* searches, notes, submissions, wall clock and budget. Any one of them ends the
|
|
23
|
+
* loop with a named reason, so "it stopped" is always answerable.
|
|
24
|
+
*/
|
|
25
|
+
import type { Message, ModelRef, TokenUsage, ToolDefinition } from '@aragon-agent/core';
|
|
26
|
+
import type { ModelRole } from '@aragon-agent/tui/model/config/model-profiles';
|
|
27
|
+
import type { CompactionEvent } from '@aragon-agent/tui/model/compaction/types';
|
|
28
|
+
import type { CompactionBudget } from './budget.js';
|
|
29
|
+
import type { DigestResult } from './digest.js';
|
|
30
|
+
import type { CompactionMemory, MemoryDelta } from './memory.js';
|
|
31
|
+
import type { PreparedMemoryInput } from './memory-input.js';
|
|
32
|
+
import { type SubmitVerdict } from './memory-agent-tools.js';
|
|
33
|
+
/** One assistant turn's worth of request: what `runTurn` must send. */
|
|
34
|
+
export interface AgentTurnRequest {
|
|
35
|
+
systemPrompt: string;
|
|
36
|
+
messages: Message[];
|
|
37
|
+
tools: ToolDefinition[];
|
|
38
|
+
maxTokens: number;
|
|
39
|
+
/** The summarizer this operation chose, so the port needs no second lookup. */
|
|
40
|
+
ref: ModelRef;
|
|
41
|
+
role: ModelRole;
|
|
42
|
+
signal: AbortSignal;
|
|
43
|
+
}
|
|
44
|
+
/** One assistant turn's worth of answer. */
|
|
45
|
+
export interface AgentTurn {
|
|
46
|
+
text: string;
|
|
47
|
+
toolCalls: Array<{
|
|
48
|
+
toolCallId: string;
|
|
49
|
+
toolName: string;
|
|
50
|
+
args: Record<string, unknown>;
|
|
51
|
+
}>;
|
|
52
|
+
usage: TokenUsage;
|
|
53
|
+
}
|
|
54
|
+
export interface MemoryAgentPort {
|
|
55
|
+
/** One no-streaming-consumer request; `wiring.ts` implements it with `consumeStream`. */
|
|
56
|
+
runTurn(input: AgentTurnRequest): Promise<AgentTurn>;
|
|
57
|
+
}
|
|
58
|
+
export interface MemoryAgentDeps {
|
|
59
|
+
budget: CompactionBudget;
|
|
60
|
+
/** The operation's cancellation and deadline owner. */
|
|
61
|
+
operation: {
|
|
62
|
+
signal: AbortSignal;
|
|
63
|
+
deadline: number;
|
|
64
|
+
};
|
|
65
|
+
/** The CLI-local stream; only `usage` is emitted from here. */
|
|
66
|
+
emit: (event: CompactionEvent) => void;
|
|
67
|
+
/** The SAME accumulation `noteUsage` uses, so the budget has one entry point. */
|
|
68
|
+
onUsage: (usage: TokenUsage) => void;
|
|
69
|
+
now: () => number;
|
|
70
|
+
}
|
|
71
|
+
export interface MemoryAgentInput {
|
|
72
|
+
band: PreparedMemoryInput;
|
|
73
|
+
digest: DigestResult;
|
|
74
|
+
choice: {
|
|
75
|
+
ref: ModelRef;
|
|
76
|
+
role: ModelRole;
|
|
77
|
+
};
|
|
78
|
+
instructions?: string;
|
|
79
|
+
/** The previous attempt's receipt, so a repair knows what went wrong. */
|
|
80
|
+
repairHint?: string;
|
|
81
|
+
}
|
|
82
|
+
export type MemoryAgentResult = {
|
|
83
|
+
ok: true;
|
|
84
|
+
delta: MemoryDelta;
|
|
85
|
+
turns: number;
|
|
86
|
+
toolCalls: number;
|
|
87
|
+
submissions: number;
|
|
88
|
+
} | {
|
|
89
|
+
ok: false;
|
|
90
|
+
reason: string;
|
|
91
|
+
turns: number;
|
|
92
|
+
toolCalls: number;
|
|
93
|
+
lastVerdict?: SubmitVerdict;
|
|
94
|
+
};
|
|
95
|
+
/** The structural ceiling on the whole loop for this operation. */
|
|
96
|
+
export declare function agentDeadlineOf(deps: MemoryAgentDeps): number;
|
|
97
|
+
/**
|
|
98
|
+
* The first request's projected size (P1-4).
|
|
99
|
+
*
|
|
100
|
+
* `digestFor` projects the WHOLE digest for the single-shot path; this path
|
|
101
|
+
* sends an opening of three lines plus the outline phrasebook, so measuring the
|
|
102
|
+
* digest here would refuse a request the agent never makes - and the window
|
|
103
|
+
* headroom the multi-turn design buys would be spent on a phantom.
|
|
104
|
+
*/
|
|
105
|
+
export declare function projectAgentOpeningTokens(input: {
|
|
106
|
+
band: PreparedMemoryInput;
|
|
107
|
+
digest: DigestResult;
|
|
108
|
+
instructions?: string;
|
|
109
|
+
repairHint?: string;
|
|
110
|
+
}): number;
|
|
111
|
+
/** Run one compaction agent to completion, adoption or a named stop. */
|
|
112
|
+
export declare function runMemoryAgent(input: MemoryAgentInput, port: MemoryAgentPort, deps: MemoryAgentDeps): Promise<MemoryAgentResult>;
|
|
113
|
+
/** Rebuild the memory from an adopted delta, for the compactor's applying step. */
|
|
114
|
+
export declare function memoryFromDelta(band: PreparedMemoryInput, digest: DigestResult, delta: MemoryDelta): CompactionMemory;
|