@aragon-agent/cli 0.6.52 → 0.6.54

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.
Files changed (80) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/README.md +4042 -3982
  3. package/dist/agent/controller.d.ts +26 -0
  4. package/dist/agent/controller.js +129 -1
  5. package/dist/agent/system-prompt.d.ts +14 -0
  6. package/dist/agent/system-prompt.js +3 -0
  7. package/dist/app/App.d.ts +7 -0
  8. package/dist/app/App.js +135 -6
  9. package/dist/cli.js +25 -1
  10. package/dist/commands/builtins.js +10 -0
  11. package/dist/commands/catalog.js +1 -0
  12. package/dist/commands/registry.d.ts +7 -0
  13. package/dist/compaction/compactor.d.ts +26 -0
  14. package/dist/compaction/compactor.js +81 -8
  15. package/dist/compaction/summarize-call.d.ts +22 -0
  16. package/dist/compaction/summarize-call.js +29 -0
  17. package/dist/compaction/wiring.js +22 -3
  18. package/dist/config/app-paths.d.ts +13 -0
  19. package/dist/config/app-paths.js +15 -0
  20. package/dist/config/cli-commands.d.ts +15 -0
  21. package/dist/config/cli-commands.js +32 -1
  22. package/dist/config/env.d.ts +1 -0
  23. package/dist/config/env.js +11 -0
  24. package/dist/config/load.d.ts +6 -0
  25. package/dist/config/load.js +10 -1
  26. package/dist/config/store.js +10 -1
  27. package/dist/exec/bridge/server.js +9 -2
  28. package/dist/exec/options.js +16 -2
  29. package/dist/governance/prompts/orchestrator-block.js +2 -2
  30. package/dist/host/controller-factory.d.ts +25 -0
  31. package/dist/host/controller-factory.js +7 -0
  32. package/dist/host/follow-up-seed.d.ts +109 -0
  33. package/dist/host/follow-up-seed.js +196 -0
  34. package/dist/host/follow-up.d.ts +73 -0
  35. package/dist/host/follow-up.js +123 -0
  36. package/dist/host/index.d.ts +3 -0
  37. package/dist/host/index.js +3 -0
  38. package/dist/host/memory.d.ts +21 -0
  39. package/dist/host/memory.js +17 -0
  40. package/dist/host/sessions.d.ts +32 -2
  41. package/dist/host/sessions.js +40 -2
  42. package/dist/logging/install.d.ts +1 -0
  43. package/dist/logging/install.js +4 -0
  44. package/dist/logging/logger.d.ts +1 -1
  45. package/dist/memory/block.d.ts +24 -0
  46. package/dist/memory/block.js +54 -0
  47. package/dist/memory/command.d.ts +31 -0
  48. package/dist/memory/command.js +350 -0
  49. package/dist/memory/format.d.ts +51 -0
  50. package/dist/memory/format.js +308 -0
  51. package/dist/memory/paths.d.ts +68 -0
  52. package/dist/memory/paths.js +172 -0
  53. package/dist/memory/plan.d.ts +37 -0
  54. package/dist/memory/plan.js +184 -0
  55. package/dist/memory/resolve.d.ts +45 -0
  56. package/dist/memory/resolve.js +54 -0
  57. package/dist/memory/secrets.d.ts +30 -0
  58. package/dist/memory/secrets.js +73 -0
  59. package/dist/memory/service.d.ts +175 -0
  60. package/dist/memory/service.js +576 -0
  61. package/dist/memory/store.d.ts +133 -0
  62. package/dist/memory/store.js +694 -0
  63. package/dist/memory/tools.d.ts +36 -0
  64. package/dist/memory/tools.js +527 -0
  65. package/dist/memory/transfer.d.ts +53 -0
  66. package/dist/memory/transfer.js +93 -0
  67. package/dist/session/checkpoint.d.ts +18 -0
  68. package/dist/session/checkpoint.js +34 -0
  69. package/dist/session/limits.d.ts +16 -0
  70. package/dist/session/limits.js +16 -0
  71. package/dist/session/persist.d.ts +47 -0
  72. package/dist/session/persist.js +1 -0
  73. package/dist/session/startup-session.d.ts +6 -0
  74. package/dist/session/startup-session.js +3 -0
  75. package/dist/session/store.d.ts +14 -0
  76. package/dist/session/store.js +18 -0
  77. package/dist/session/validate-session.js +98 -0
  78. package/dist/tools/index.d.ts +21 -2
  79. package/dist/tools/index.js +33 -0
  80. package/package.json +3 -3
@@ -6,7 +6,7 @@
6
6
  * legitimately long single tool run can never be watchdog-killed.
7
7
  */
8
8
  import process from 'node:process';
9
- import { DEFAULT_CONFIG, DEFAULT_SCROLL_MODE, IDLE_TIMEOUT_MARGIN_MS, clampDensity, clampHumanTimeout, clampCompactionConfig, clampLogConfig, clampFastConfig, clampRetryConfig, clampSkillsConfig, clampTeamConfig, clampTodoConfig, clampBashConfig, clampJobsConfig, clampPromptsConfig, clampTaskSummaryConfig, clampUpdateConfig, clampTheme, clampThinkingLevel, clampContextWindow, clampMaxTokens, clampMaxRenderInterval, clampScrollMode, clampScrollResumeMs, clampTranscriptRetain, clampTranscriptWindow, coercePositiveInt, isAutoToken, isSkillsToolPolicyMode, legacyTeamCeilingPatch, legacyTeamFanoutPatch, LEGACY_TEAM_FANOUT_DEFAULTS, parseThresholdInput, } from '@aragon-agent/tui/model/config/schema';
9
+ import { DEFAULT_CONFIG, DEFAULT_SCROLL_MODE, IDLE_TIMEOUT_MARGIN_MS, clampDensity, clampHumanTimeout, clampCompactionConfig, clampLogConfig, clampFastConfig, clampRetryConfig, clampSkillsConfig, clampTeamConfig, clampTodoConfig, clampBashConfig, clampJobsConfig, clampPromptsConfig, clampMemoryConfig, clampTaskSummaryConfig, clampUpdateConfig, clampTheme, clampThinkingLevel, clampContextWindow, clampMaxTokens, clampMaxRenderInterval, clampScrollMode, clampScrollResumeMs, clampTranscriptRetain, clampTranscriptWindow, coercePositiveInt, isAutoToken, isSkillsToolPolicyMode, legacyTeamCeilingPatch, legacyTeamFanoutPatch, LEGACY_TEAM_FANOUT_DEFAULTS, parseThresholdInput, } from '@aragon-agent/tui/model/config/schema';
10
10
  import { loadDotenv, readEnvConfig, readEnvDisabledSkills } from './env.js';
11
11
  import { readConfigFile, updatePersistedConfig } from './store.js';
12
12
  import { projectModelProfiles, resolveModelProfileState, resolveModelRoleKey, } from '@aragon-agent/tui/model/config/model-profile-resolution';
@@ -797,6 +797,15 @@ export function loadConfig(flags = {}, options = {}) {
797
797
  taskSummary: clampTaskSummaryConfig({ ...DEFAULT_CONFIG.taskSummary,
798
798
  ...(env.partial.taskSummary ?? {}), ...(file.taskSummary ?? {}) }),
799
799
  governance,
800
+ // Agent memory: file < env kill switch < `--no-memory`, clamped like every section. The
801
+ // kill switches can only switch `enabled` OFF; they are applied AFTER the file so they
802
+ // outrank it, and `clampMemoryConfig` keeps `agentWrites` on the safe side of a typo.
803
+ memory: clampMemoryConfig({
804
+ ...DEFAULT_CONFIG.memory,
805
+ ...(file.memory ?? {}),
806
+ ...(env.partial.memory ?? {}),
807
+ ...(flags.memory === false ? { enabled: false } : {}),
808
+ }),
800
809
  initialPosture,
801
810
  cwd,
802
811
  color,
@@ -17,7 +17,7 @@ import { getConfigPath, getSessionsDir } from './app-paths.js';
17
17
  import { registerProfileSecrets, registerSecretsFrom } from '@aragon-agent/tui/model/logging/secret-registry';
18
18
  import { adaptLegacyConnectionPatch, ModelProfileConfigError, readModelSettingsDisk } from './model-profile-store.js';
19
19
  import { normalizeModelProfiles } from '@aragon-agent/tui/model/config/model-profiles';
20
- import { clampBashConfig, clampJobsConfig, clampPromptsConfig, clampTaskSummaryConfig, CONFIG_VERSION, DEFAULT_CONFIG, clampCompactionConfig, clampFastConfig, clampGovernanceConfig, clampLogConfig, clampMaxTokens, clampRetryConfig, clampSkillsConfig, clampTeamConfig, clampTodoConfig, clampContextWindow, clampUpdateConfig, isAutoToken, stripLegacyStateKeys, stripRetiredConfigKeys, } from '@aragon-agent/tui/model/config/schema';
20
+ import { clampBashConfig, clampJobsConfig, clampPromptsConfig, clampTaskSummaryConfig, CONFIG_VERSION, DEFAULT_CONFIG, clampCompactionConfig, clampFastConfig, clampGovernanceConfig, clampLogConfig, clampMemoryConfig, clampMaxTokens, clampRetryConfig, clampSkillsConfig, clampTeamConfig, clampTodoConfig, clampContextWindow, clampUpdateConfig, isAutoToken, stripLegacyStateKeys, stripRetiredConfigKeys, } from '@aragon-agent/tui/model/config/schema';
21
21
  /**
22
22
  * Normalize `maxTokens` for both directions of the config file.
23
23
  *
@@ -220,6 +220,10 @@ export function normalizePersistedConfig(input) {
220
220
  ...DEFAULT_CONFIG.governance,
221
221
  ...(partial.governance ?? {}),
222
222
  }),
223
+ // And the fifteenth. A `config.json` predating agent memory must resolve a whole
224
+ // section, and a hand-edited one is clamped: the file cannot carry a budget the
225
+ // planner would refuse or an `agentWrites` that is neither of the three values.
226
+ memory: clampMemoryConfig({ ...DEFAULT_CONFIG.memory, ...(partial.memory ?? {}) }),
223
227
  };
224
228
  }
225
229
  /**
@@ -347,6 +351,11 @@ export function mergePersistedConfig(current, patch) {
347
351
  // absent, and without the clamp 9 reaches the disk and the engine's ceiling is the
348
352
  // only thing that stops it. The WRITE half of the two-direction gate.
349
353
  governance: clampGovernanceConfig({ ...current.governance, ...(patch.governance ?? {}) }),
354
+ // The fifteenth section, and the tenth time this file records the same trap.
355
+ // `aragon config set memory.autoload false` sends `{ memory: { autoload: false } }`;
356
+ // without this merge the shallow spread REPLACES the section and `agentWrites` is
357
+ // written absent - which must never read back as anything but `ask`.
358
+ memory: clampMemoryConfig({ ...current.memory, ...(patch.memory ?? {}) }),
350
359
  };
351
360
  return merged;
352
361
  }
@@ -23,7 +23,7 @@
23
23
  * model cannot see it and the caller can.
24
24
  */
25
25
  import { errorResult } from '@aragon-agent/core';
26
- import { HOST_TOOL_NAMES } from '../../tools/index.js';
26
+ import { HOST_TOOL_NAMES, MEMORY_TOOL_NAMES } from '../../tools/index.js';
27
27
  import { TEAM_SUBAGENT_TOOL_NAMES } from '@aragon-agent/tui/model/team/limits';
28
28
  import { BRIDGE_LIMITS } from './limits.js';
29
29
  import { createPendingTable } from './pending.js';
@@ -34,8 +34,15 @@ export function createBridgeServer(options) {
34
34
  const sessionId = options.sessionId;
35
35
  const writer = options.writer;
36
36
  const pending = createPendingTable({ now });
37
+ // The memory tools are in `HOST_TOOL_NAMES` (the superset a skill may name) but a headless
38
+ // run NEVER registers them (agent-memory D-20), so reserving their names would only reject a
39
+ // caller tool called `memory_search` - a perfectly legitimate integration (RV-5).
40
+ const memoryNames = new Set(MEMORY_TOOL_NAMES);
37
41
  const reserved = options.reservedToolNames ??
38
- new Set([...HOST_TOOL_NAMES, ...TEAM_SUBAGENT_TOOL_NAMES]);
42
+ new Set([
43
+ ...HOST_TOOL_NAMES.filter((name) => !memoryNames.has(name)),
44
+ ...TEAM_SUBAGENT_TOOL_NAMES,
45
+ ]);
39
46
  let open = true;
40
47
  let turn = 0;
41
48
  let turnPorts = null;
@@ -14,7 +14,7 @@
14
14
  * half-written event would corrupt every consumer. The caller writes the message
15
15
  * to stderr and exits.
16
16
  */
17
- import { HOST_TOOL_NAMES } from '../tools/index.js';
17
+ import { HOST_TOOL_NAMES, MEMORY_TOOL_NAMES } from '../tools/index.js';
18
18
  import { isValidSessionId } from '../session/store.js';
19
19
  import { BRIDGE_LIMITS } from './bridge/limits.js';
20
20
  import { RESULT_LIMITS } from './result/limits.js';
@@ -43,7 +43,16 @@ const ON_HOOK_TIMEOUT_MODES = ['deny', 'allow', 'error'];
43
43
  * "can this declaration ever take effect?", and the answer for these two is yes,
44
44
  * just not here - so exec accepts it and says one line on stderr.
45
45
  */
46
- const NEVER_REGISTERED_HEADLESS = ['ask_user', 'submit_plan'];
46
+ const NEVER_REGISTERED_HEADLESS = [
47
+ 'ask_user',
48
+ 'submit_plan',
49
+ // The memory tools (agent-memory D-20): a headless run neither builds the memory block nor
50
+ // registers the tools, so naming them here validates (they are in HOST_TOOL_NAMES) and then
51
+ // does nothing - which the warnings below say out loud instead of accepting in silence.
52
+ 'memory_search',
53
+ 'memory_read',
54
+ 'memory_write',
55
+ ];
47
56
  /**
48
57
  * Flags that need to observe or interrupt the stream `runHeadless` owns, and are
49
58
  * therefore REFUSED under `--output-format text` (D-1).
@@ -217,6 +226,11 @@ export function resolveExecOptions(raw, context = {}) {
217
226
  "stopReason 'max_turns' and error.code 'result_schema_unsatisfied'.");
218
227
  }
219
228
  }
229
+ for (const name of denyTools) {
230
+ if (MEMORY_TOOL_NAMES.includes(name)) {
231
+ warnings.push(`--deny-tool ${name}: that tool is never registered in a headless run, so this deny has no effect.`);
232
+ }
233
+ }
220
234
  if (structured.resultSchemaPath === undefined && denyTools.includes('submit_result')) {
221
235
  // W-3. `submit_result` is registered ONLY by `--result-schema`, so denying it here
222
236
  // denies a name that will never exist. Same argument as NEVER_REGISTERED_HEADLESS.
@@ -67,8 +67,8 @@ function powersSection() {
67
67
  '',
68
68
  'Your tools: gov_run, gov_dispatch, ask_user, todo_write, and every tool that only reads',
69
69
  '(read_file, list_dir, glob, grep, skill, skill_find, bash_output, job_wait, job_list).',
70
- 'write_file, edit_file, bash, bash_kill, skill_install, skill_create and task are refused in',
71
- 'this mode on purpose: all implementation happens through dispatched agents.',
70
+ 'write_file, edit_file, bash, bash_kill, skill_install, skill_create, memory_write and task are',
71
+ 'refused in this mode on purpose: all implementation happens through dispatched agents.',
72
72
  ];
73
73
  }
74
74
  function startSteps(maxWorkPackages) {
@@ -19,6 +19,8 @@ import type { ToolPermission } from '../exec/permission.js';
19
19
  import type { ToolHookRunner } from '../exec/hooks/tool-wrapper.js';
20
20
  import type { ApprovalGate } from '../skills/service.js';
21
21
  import { SessionCheckpointWriter, type LiveSessionView } from '../session/checkpoint.js';
22
+ import type { SessionFollowUpMeta } from '../session/persist.js';
23
+ import type { SessionLockHandle } from '../session/store.js';
22
24
  import type { ToolGate } from '../tools/tool-gate.js';
23
25
  import type { ConfirmRequest } from '../tools/index.js';
24
26
  /** Re-exported so a host can name the controller type without a deep import. */
@@ -106,4 +108,27 @@ export declare function createSessionWriter(input: {
106
108
  readView: () => LiveSessionView | undefined;
107
109
  readParentId: () => string | undefined;
108
110
  startPinned: boolean;
111
+ /**
112
+ * Where this session's checkpoints go, and whether it takes the sessions-directory lock
113
+ * (desktop-follow-up-panel P1-1 / P2-11).
114
+ *
115
+ * ABSENT FOR EVERY EXISTING CALLER, which is what keeps `cli.tsx`'s two sites byte-identical:
116
+ * `SessionCheckpointWriter` already defaults `pathFor` to `sessionPathFor` and `lockFor` to
117
+ * `tryAcquireSessionLock`, and a follow-up session is the only producer that answers differently.
118
+ *
119
+ * `lockFor: () => null` IS NOT "NO LOCK NEEDED", it is "THIS PATH CANNOT USE THAT LOCK":
120
+ * `tryAcquireSessionLock` always writes `<sessions>/<id>.lock`, so a follow-up writing under
121
+ * `sessions/follow-ups/` would leave an orphan lock in the SESSIONS directory for a file that is
122
+ * not there. The two keys travel together for that reason.
123
+ */
124
+ paths?: {
125
+ pathFor: (id: string) => string;
126
+ lockFor: (id: string) => SessionLockHandle | null;
127
+ };
128
+ /**
129
+ * The follow-up block this session records, as a VALUE (P1-1). Absent for every ordinary
130
+ * session, which is what keeps its checkpoint bytes identical to one written before this
131
+ * feature.
132
+ */
133
+ followUp?: SessionFollowUpMeta;
109
134
  }): SessionCheckpointWriter;
@@ -141,6 +141,8 @@ export function createSessionWriter(input) {
141
141
  // The verdicts travel with the plan; read from the STORE, not from the render
142
142
  // projection, so a checkpoint taken while the capability is off still saves them.
143
143
  readAcceptance: () => controller.getAcceptanceItems(),
144
+ // Mounts and switches only - ids, never text (agent-memory I-18).
145
+ readMemory: () => controller.getMemoryService()?.exportState(),
144
146
  // READ AT WRITE TIME: `/model` rebuilds the config, and a checkpoint that
145
147
  // recorded the model from launch would name the wrong one after a switch.
146
148
  readModel: () => {
@@ -155,5 +157,10 @@ export function createSessionWriter(input) {
155
157
  version: VERSION,
156
158
  readParentId: input.readParentId,
157
159
  startPinned: input.startPinned,
160
+ // NAMED, NOT SPREAD (the R3 lesson above): a dependency this factory does not name here is
161
+ // dropped in silence, and the symptom of a dropped `paths` is a follow-up file written into
162
+ // the sessions directory, where it would appear in the sidebar (R-9).
163
+ ...(input.paths ? { pathFor: input.paths.pathFor, lockFor: input.paths.lockFor } : {}),
164
+ ...(input.followUp ? { followUp: input.followUp } : {}),
158
165
  });
159
166
  }
@@ -0,0 +1,109 @@
1
+ /**
2
+ * The follow-up panel's context seed (desktop-follow-up-panel §4.4).
3
+ *
4
+ * A follow-up conversation starts from a SNAPSHOT of its parent: the newest tail of the parent's
5
+ * history that fits a small budget, cut only at a boundary the engine itself considers safe, plus
6
+ * the excerpt the user highlighted (which travels in the child's system prompt, not here).
7
+ *
8
+ * WHY A CUT INSTEAD OF A SUMMARY. A summary would be a second model call - latency, cost, and a
9
+ * lossy paraphrase - to answer a question about text the user is looking at right now. The
10
+ * structural rules that make a history sendable already exist in the engine
11
+ * (`findSafeCutIndices` / `validateHistory` / `relieveTail`), so this module composes them rather
12
+ * than inventing a second set. It is pure: no IO, no logger, no model, no Ink.
13
+ *
14
+ * `FollowUpSeed` AND `FollowUpSeedInput` ARE DEFINED HERE AND NOWHERE ELSE. They are the payload
15
+ * of a control-plane message (main process <-> host, §7.3), so a second copy in the desktop app's
16
+ * `shared/` would drift; that side re-exports these types with `import type` instead.
17
+ */
18
+ import { type Message } from '@aragon-agent/core';
19
+ export interface FollowUpSeedInput {
20
+ /** The parent's complete history, read-only. */
21
+ messages: readonly Message[];
22
+ /**
23
+ * The system prompt the token projection is measured against.
24
+ *
25
+ * NOT "the child's final system prompt" - the parent cannot obtain that. It is
26
+ * `parentController.getSystemPrompt() + buildFollowUpPromptBlock(anchor)`, which is exact
27
+ * because `appendSystemPrompt` is concatenated verbatim by `buildSystemPrompt`. The child
28
+ * re-measures with its OWN prompt before adopting the seed (§4.4 step 7), so this number only
29
+ * has to be close to be useful and is never the last word.
30
+ */
31
+ systemPrompt: string;
32
+ /** The parent's context window; absent means 200k. */
33
+ contextWindow?: number;
34
+ /** The input budget for the child; absent means window x 0.5, capped at 24k. */
35
+ budgetTokens?: number;
36
+ }
37
+ export interface FollowUpSeed {
38
+ messages: Message[];
39
+ /** Complete turns dropped from the head, for an honest notice in the panel. */
40
+ omittedTurns: number;
41
+ /** Projected input tokens of `messages` (`estimatePromptTokens`). */
42
+ tokens: number;
43
+ /** Tool results whose bodies were clipped by tail relief. */
44
+ clipped: number;
45
+ }
46
+ /** Half the window, and never more than this: a follow-up is a side question, not a session. */
47
+ export declare const FOLLOW_UP_BUDGET_TOKENS = 24000;
48
+ export declare const FOLLOW_UP_BUDGET_WINDOW_RATIO = 0.5;
49
+ /**
50
+ * The first message of a cut history, when the cut left it starting with a non-`user` role.
51
+ *
52
+ * Some providers refuse a history whose first message is not from the user, and a silent refusal
53
+ * is discovered by the user as "the panel does not answer". The text is deliberately plain: it is
54
+ * read by the model, not by the user.
55
+ */
56
+ export declare const FOLLOW_UP_OMITTED_HEADER = "[earlier turns omitted]";
57
+ /**
58
+ * Plan the seed.
59
+ *
60
+ * THE SIX STEPS ARE SEPARATE ON PURPOSE (spec §4.4): each one is a decision a reader has to be
61
+ * able to check on its own, and merging any two of them hides a rule that has a test.
62
+ *
63
+ * AN EMPTY SEED IS NOT AN ERROR. Every failure below (no safe cut, an unsendable result) returns
64
+ * the empty seed, and the caller turns that into `seedSource: 'excerpt'` plus one honest line in
65
+ * the panel. Throwing here would make the panel's first frame depend on the parent's history
66
+ * being tidy, which is exactly the case the excerpt-only fallback exists for.
67
+ */
68
+ export declare function planFollowUpSeed(input: FollowUpSeedInput): FollowUpSeed;
69
+ /** The empty seed, for callers that want to spell "no context" without building one. */
70
+ export declare function emptyFollowUpSeed(): FollowUpSeed;
71
+ /** Why a seed was not adopted. Every value degrades the panel to "excerpt only" with one sentence. */
72
+ export type AdoptSeedRefusal = 'empty' | 'too_large' | 'unsendable';
73
+ export interface AdoptFollowUpSeedInput {
74
+ seed: FollowUpSeed | null;
75
+ /**
76
+ * THE ADOPTING HOST'S OWN system prompt, anchor block included.
77
+ *
78
+ * The parent measured the seed against `parentSystemPrompt + block`; this host may carry a
79
+ * different persona or a model switch that landed in between, so the same messages can cost a
80
+ * different number of tokens here. This second measurement is what makes the parent's "exact
81
+ * equation" degrade into SLOWER rather than wrong when the two prompts drift (P0-2's second gate).
82
+ */
83
+ systemPrompt: string;
84
+ /** The host's budget; absent means `FOLLOW_UP_BUDGET_TOKENS` bounded by half `contextWindow`. */
85
+ budgetTokens?: number;
86
+ contextWindow?: number;
87
+ }
88
+ export interface AdoptFollowUpSeedResult {
89
+ /** The messages to hand `replaceMessages`, or `null` when the seed was refused. */
90
+ messages: Message[] | null;
91
+ refusal?: AdoptSeedRefusal;
92
+ /** Tool results clipped in total: the parent's pass plus this host's re-measurement. */
93
+ clipped: number;
94
+ }
95
+ /**
96
+ * Decide whether this host may adopt a seed the parent produced.
97
+ *
98
+ * THREE GATES, IN THIS ORDER AND NO OTHER:
99
+ *
100
+ * 1. `closeDanglingToolCalls` - an interrupted parent turn left a call with no result, which is
101
+ * normal and must be repaired rather than refused.
102
+ * 2. the budget, measured HERE, with relief as the last rung before giving up.
103
+ * 3. `validateHistory` - the structural gate. `replaceMessages` validates NOTHING (its own source
104
+ * says so), so an unsendable history handed to it becomes a provider 400 in the panel.
105
+ *
106
+ * A REFUSAL IS NOT AN ERROR: the caller starts from the excerpt and says so. Trimming a seed that
107
+ * failed the gate into something smaller would answer confidently about context that was lost.
108
+ */
109
+ export declare function adoptFollowUpSeed(input: AdoptFollowUpSeedInput): AdoptFollowUpSeedResult;
@@ -0,0 +1,196 @@
1
+ /**
2
+ * The follow-up panel's context seed (desktop-follow-up-panel §4.4).
3
+ *
4
+ * A follow-up conversation starts from a SNAPSHOT of its parent: the newest tail of the parent's
5
+ * history that fits a small budget, cut only at a boundary the engine itself considers safe, plus
6
+ * the excerpt the user highlighted (which travels in the child's system prompt, not here).
7
+ *
8
+ * WHY A CUT INSTEAD OF A SUMMARY. A summary would be a second model call - latency, cost, and a
9
+ * lossy paraphrase - to answer a question about text the user is looking at right now. The
10
+ * structural rules that make a history sendable already exist in the engine
11
+ * (`findSafeCutIndices` / `validateHistory` / `relieveTail`), so this module composes them rather
12
+ * than inventing a second set. It is pure: no IO, no logger, no model, no Ink.
13
+ *
14
+ * `FollowUpSeed` AND `FollowUpSeedInput` ARE DEFINED HERE AND NOWHERE ELSE. They are the payload
15
+ * of a control-plane message (main process <-> host, §7.3), so a second copy in the desktop app's
16
+ * `shared/` would drift; that side re-exports these types with `import type` instead.
17
+ */
18
+ import { findSafeCutIndices, estimatePromptTokens, relieveTail, validateHistory, } from '@aragon-agent/core';
19
+ import { COMPACTION_LIMITS, tailClipMarker } from '@aragon-agent/tui/model/compaction/limits';
20
+ import { closeDanglingToolCalls } from '../session/checkpoint.js';
21
+ /** The default window when the caller has no model metadata to hand. */
22
+ const DEFAULT_CONTEXT_WINDOW = 200_000;
23
+ /** Half the window, and never more than this: a follow-up is a side question, not a session. */
24
+ export const FOLLOW_UP_BUDGET_TOKENS = 24_000;
25
+ export const FOLLOW_UP_BUDGET_WINDOW_RATIO = 0.5;
26
+ /**
27
+ * The first message of a cut history, when the cut left it starting with a non-`user` role.
28
+ *
29
+ * Some providers refuse a history whose first message is not from the user, and a silent refusal
30
+ * is discovered by the user as "the panel does not answer". The text is deliberately plain: it is
31
+ * read by the model, not by the user.
32
+ */
33
+ export const FOLLOW_UP_OMITTED_HEADER = '[earlier turns omitted]';
34
+ function emptySeed() {
35
+ return { messages: [], omittedTurns: 0, tokens: 0, clipped: 0 };
36
+ }
37
+ /** The budget this call may spend: explicit, else half the window, else the fixed ceiling. */
38
+ function resolveBudget(input) {
39
+ if (input.budgetTokens !== undefined && Number.isFinite(input.budgetTokens) && input.budgetTokens > 0) {
40
+ return Math.floor(input.budgetTokens);
41
+ }
42
+ const window = input.contextWindow !== undefined && Number.isFinite(input.contextWindow) && input.contextWindow > 0
43
+ ? input.contextWindow
44
+ : DEFAULT_CONTEXT_WINDOW;
45
+ return Math.min(FOLLOW_UP_BUDGET_TOKENS, Math.floor(window * FOLLOW_UP_BUDGET_WINDOW_RATIO));
46
+ }
47
+ /**
48
+ * The smallest safe cut whose tail fits `budgetTokens`.
49
+ *
50
+ * SMALLEST INDEX, NOT SMALLEST TOKEN COUNT. Indices are walked in ascending order and the estimate
51
+ * is computed per candidate, so the answer is "the most context that fits". Sorting by token count
52
+ * would be cheaper and would also make the same input produce different cuts on different runs,
53
+ * which is the worst property a seed can have.
54
+ *
55
+ * TWO CORRECTIONS TO THE DESIGN'S STEP 2, both found while implementing it (see "实施过程发现的方案
56
+ * 缺陷" in the spec):
57
+ *
58
+ * - INDEX 0 IS A CANDIDATE. The design filtered it out, which dropped the parent's FIRST user
59
+ * message - often the task statement - even when the whole history fit comfortably, and made
60
+ * the panel report "1 turn omitted" for no reason.
61
+ * - `messages.length` IS NOT. An empty tail measures 0 tokens, so it "fits" every budget and
62
+ * would win every time no real cut fit - turning the tail-relief step into dead code and
63
+ * answering with an empty seed instead of a clipped one. A slice that keeps nothing is not a
64
+ * seed; the caller's fallback (excerpt only) is the honest answer when nothing fits.
65
+ */
66
+ function chooseCut(messages, systemPrompt, budgetTokens) {
67
+ const candidates = findSafeCutIndices(messages).filter((index) => index < messages.length);
68
+ if (candidates.length === 0)
69
+ return -1;
70
+ for (const index of candidates) {
71
+ if (estimatePromptTokens(messages.slice(index), systemPrompt) <= budgetTokens)
72
+ return index;
73
+ }
74
+ return candidates[candidates.length - 1];
75
+ }
76
+ /** A history that starts with anything but `user` gets a plain leading message. */
77
+ function ensureUserFirst(messages) {
78
+ if (messages.length === 0)
79
+ return messages;
80
+ if (messages[0].role === 'user')
81
+ return messages;
82
+ return [{ role: 'user', content: FOLLOW_UP_OMITTED_HEADER }, ...messages];
83
+ }
84
+ /**
85
+ * Plan the seed.
86
+ *
87
+ * THE SIX STEPS ARE SEPARATE ON PURPOSE (spec §4.4): each one is a decision a reader has to be
88
+ * able to check on its own, and merging any two of them hides a rule that has a test.
89
+ *
90
+ * AN EMPTY SEED IS NOT AN ERROR. Every failure below (no safe cut, an unsendable result) returns
91
+ * the empty seed, and the caller turns that into `seedSource: 'excerpt'` plus one honest line in
92
+ * the panel. Throwing here would make the panel's first frame depend on the parent's history
93
+ * being tidy, which is exactly the case the excerpt-only fallback exists for.
94
+ */
95
+ export function planFollowUpSeed(input) {
96
+ const { messages } = input;
97
+ if (messages.length === 0)
98
+ return emptySeed();
99
+ const budgetTokens = resolveBudget(input);
100
+ const cut = chooseCut(messages, input.systemPrompt, budgetTokens);
101
+ if (cut < 0)
102
+ return emptySeed();
103
+ // Step 2's answer, THEN the `user` header, THEN relief - in that order, because the header is a
104
+ // message like any other and adding it after the relief pass could push a seed that had just been
105
+ // brought under budget back over it.
106
+ let slice = ensureUserFirst(messages.slice(cut));
107
+ let clipped = 0;
108
+ if (estimatePromptTokens(slice, input.systemPrompt) > budgetTokens) {
109
+ const relieved = relieveTail(slice, {
110
+ from: 0,
111
+ clipChars: COMPACTION_LIMITS.tailToolResultChars,
112
+ targetTokens: budgetTokens,
113
+ systemPrompt: input.systemPrompt,
114
+ marker: tailClipMarker,
115
+ });
116
+ slice = relieved.messages;
117
+ clipped = relieved.clippedMessages;
118
+ }
119
+ return settle(slice, input.systemPrompt, budgetTokens, countOmittedTurns(messages, cut), clipped);
120
+ }
121
+ /**
122
+ * Turns left behind, counted as `user` messages (one opening message per turn).
123
+ *
124
+ * COUNTING MESSAGES WOULD LIE: one turn that used forty tools is eighty messages wide and still one
125
+ * turn, so a length difference would tell the user that forty turns were dropped when one was.
126
+ */
127
+ function countOmittedTurns(messages, cut) {
128
+ return messages.slice(0, cut).filter((message) => message.role === 'user').length;
129
+ }
130
+ /**
131
+ * The gate, and the report.
132
+ *
133
+ * `validateHistory` IS THE LAST WORD (4.4 step 5): an unsendable history must never reach the engine,
134
+ * and `replaceMessages` - the only thing that does reach it - validates nothing at all. A refusal here
135
+ * is not an error; it is the excerpt-only start, said out loud by the panel.
136
+ */
137
+ function settle(messages, systemPrompt, budgetTokens, omittedTurns, clipped) {
138
+ const verdict = validateHistory(messages);
139
+ if (!verdict.ok)
140
+ return emptySeed();
141
+ const tokens = estimatePromptTokens(messages, systemPrompt);
142
+ if (tokens > budgetTokens)
143
+ return emptySeed();
144
+ return { messages, omittedTurns, tokens, clipped };
145
+ }
146
+ /** The empty seed, for callers that want to spell "no context" without building one. */
147
+ export function emptyFollowUpSeed() {
148
+ return emptySeed();
149
+ }
150
+ /**
151
+ * Decide whether this host may adopt a seed the parent produced.
152
+ *
153
+ * THREE GATES, IN THIS ORDER AND NO OTHER:
154
+ *
155
+ * 1. `closeDanglingToolCalls` - an interrupted parent turn left a call with no result, which is
156
+ * normal and must be repaired rather than refused.
157
+ * 2. the budget, measured HERE, with relief as the last rung before giving up.
158
+ * 3. `validateHistory` - the structural gate. `replaceMessages` validates NOTHING (its own source
159
+ * says so), so an unsendable history handed to it becomes a provider 400 in the panel.
160
+ *
161
+ * A REFUSAL IS NOT AN ERROR: the caller starts from the excerpt and says so. Trimming a seed that
162
+ * failed the gate into something smaller would answer confidently about context that was lost.
163
+ */
164
+ export function adoptFollowUpSeed(input) {
165
+ const seed = input.seed;
166
+ if (!seed || seed.messages.length === 0)
167
+ return { messages: null, refusal: 'empty', clipped: 0 };
168
+ const budgetTokens = resolveBudget({
169
+ messages: seed.messages,
170
+ systemPrompt: input.systemPrompt,
171
+ ...(input.budgetTokens === undefined ? {} : { budgetTokens: input.budgetTokens }),
172
+ ...(input.contextWindow === undefined ? {} : { contextWindow: input.contextWindow }),
173
+ });
174
+ const repaired = closeDanglingToolCalls(seed.messages);
175
+ let messages = repaired.messages;
176
+ // THE PARENT'S COUNT IS KEPT AND THIS HOST'S RELIEF IS ADDED: the panel reports how much of the
177
+ // context was trimmed in total, and a re-clip here is part of that story, not a second one.
178
+ let clipped = seed.clipped;
179
+ if (estimatePromptTokens(messages, input.systemPrompt) > budgetTokens) {
180
+ const relieved = relieveTail(messages, {
181
+ from: 0,
182
+ clipChars: COMPACTION_LIMITS.tailToolResultChars,
183
+ targetTokens: budgetTokens,
184
+ systemPrompt: input.systemPrompt,
185
+ marker: tailClipMarker,
186
+ });
187
+ messages = relieved.messages;
188
+ clipped += relieved.clippedMessages;
189
+ if (estimatePromptTokens(messages, input.systemPrompt) > budgetTokens) {
190
+ return { messages: null, refusal: 'too_large', clipped };
191
+ }
192
+ }
193
+ if (!validateHistory(messages).ok)
194
+ return { messages: null, refusal: 'unsendable', clipped };
195
+ return { messages, clipped };
196
+ }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * The follow-up panel's prompt block, its session ids and its file location
3
+ * (desktop-follow-up-panel §7.4).
4
+ *
5
+ * A follow-up is a SECOND conversation that starts from a snapshot of the first one. Three
6
+ * things about it are pure and therefore live here rather than in the desktop app: the text
7
+ * the child host prepends to its system prompt, the id shape, and the directory its
8
+ * checkpoints are written to.
9
+ *
10
+ * NO INK, NO TTY (L9 over `host/index.ts`): this module imports only the session id minting and the
11
+ * store's path builders, so it stays reachable from a utilityProcess and from a test alike.
12
+ */
13
+ /**
14
+ * The block's own version, beside `COMPACTION_BLOCK_VERSION` in spirit.
15
+ *
16
+ * A seed request and the block that answers it are produced by two processes that may be
17
+ * different builds of the app, so the block says which revision wrote it. `fv-1` is the only
18
+ * one today; `planFollowUpSeed` does not read it (the block is host text, not a wire field).
19
+ */
20
+ export declare const FOLLOW_UP_PROMPT_VERSION = "fv-1";
21
+ /**
22
+ * What the renderer knows about the highlighted text. Mirrors `FollowUpAnchorInput` in the
23
+ * desktop app's `shared/ipc-contract.ts`; declared here so this package's prompt builder does
24
+ * not have to import the desktop's types (it must not).
25
+ */
26
+ export interface FollowUpPromptAnchor {
27
+ entryId: string | null;
28
+ entryKind: 'assistant' | 'user' | 'tool' | 'notice' | 'unknown';
29
+ text: string;
30
+ truncated: boolean;
31
+ charStart: number;
32
+ charEnd: number;
33
+ streaming: boolean;
34
+ }
35
+ /**
36
+ * The three characters that would otherwise let quoted text escape its own XML element.
37
+ *
38
+ * Applied to the excerpt AND to the entry id: an id is normally `e12`, but it is data from the window,
39
+ * and the `Anchor:` line sits OUTSIDE `<excerpt>` - an id carrying `</follow_up_context>` would end the
40
+ * block and turn the rest of the quote into instructions.
41
+ */
42
+ export declare function escapeExcerptText(text: string): string;
43
+ /**
44
+ * The block a child host appends to its own system prompt.
45
+ *
46
+ * WHY THE RULES ARE EXPLICIT. The excerpt is text the user selected, which is the same trust
47
+ * level as anything else they type - but it arrives inside a prompt that also contains the
48
+ * parent conversation, so the block has to say out loud that the excerpt is *quoted material*
49
+ * rather than an instruction the model should follow (R-12). The escaping is the mechanical
50
+ * half of the same sentence: without it, a code sample containing `</excerpt>` would end the
51
+ * element early and the remaining rules would read as part of the quote.
52
+ */
53
+ export declare function buildFollowUpPromptBlock(anchor: FollowUpPromptAnchor): string;
54
+ /**
55
+ * `'fu-' + createSessionId()`.
56
+ *
57
+ * THE PARENT IS NOT PART OF THE ID. A parent id can be 64 characters on its own, so
58
+ * `parent-child` would overflow `SESSION_ID_RE`; the lineage belongs in `meta.branchOf` and
59
+ * `meta.followUp.parentId`, which is where a reader looks for it anyway.
60
+ */
61
+ export declare function createFollowUpSessionId(random?: () => number): string;
62
+ /** Whether an id is one this module could have minted (used by the desktop main process). */
63
+ export declare function isFollowUpSessionId(id: string): boolean;
64
+ /**
65
+ * `<sessions>/follow-ups/<id>.json`.
66
+ *
67
+ * THE DIRECTORY IS THE ISOLATION (D-2). `listSessions` reads the sessions folder flat and skips
68
+ * anything that is not a `.json` file, so a subdirectory is invisible to the sidebar, to
69
+ * `aragon sessions list` and to `prune` without any of them learning that this feature exists.
70
+ * The path itself lives in `session/store.ts` (that module owns every session filename and its
71
+ * id validation); this name is the one the host layer and the desktop import.
72
+ */
73
+ export { followUpsDir, followUpSessionPathFor as followUpPathFor } from '../session/store.js';