@aragon-agent/cli 0.6.48 → 0.6.50
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 +19 -0
- package/README.md +1 -0
- package/dist/agent/controller.d.ts +21 -0
- package/dist/agent/controller.js +35 -8
- package/dist/agent/governance-wiring.d.ts +2 -0
- package/dist/agent/governance-wiring.js +4 -0
- package/dist/app/App.d.ts +2 -4
- package/dist/app/App.js +279 -522
- package/dist/cli.js +8 -150
- package/dist/commands/catalog.d.ts +17 -0
- package/dist/commands/catalog.js +52 -0
- package/dist/commands/create-registry.d.ts +13 -0
- package/dist/commands/create-registry.js +19 -0
- package/dist/commands/governance-command.js +5 -1
- package/dist/commands/skills.js +18 -67
- package/dist/config/env.d.ts +2 -0
- package/dist/config/env.js +11 -1
- package/dist/config/load.js +4 -0
- package/dist/fast/review-call.d.ts +6 -0
- package/dist/fast/review-call.js +10 -0
- package/dist/governance/engine/budget.d.ts +18 -6
- package/dist/governance/engine/budget.js +61 -19
- package/dist/governance/engine/engine-core.d.ts +10 -0
- package/dist/governance/engine/engine-core.js +56 -9
- package/dist/governance/engine/engine.d.ts +1 -0
- package/dist/governance/engine/engine.js +9 -10
- package/dist/governance/engine/inspector.js +4 -3
- package/dist/governance/engine/lifecycle.js +4 -2
- package/dist/governance/engine/report.js +7 -1
- package/dist/governance/engine/run-digest.js +2 -1
- package/dist/governance/engine/stage-runner.js +1 -1
- package/dist/governance/engine/submissions.d.ts +2 -0
- package/dist/governance/engine/submissions.js +22 -3
- package/dist/governance/engine/visibility.d.ts +10 -0
- package/dist/governance/engine/visibility.js +28 -0
- package/dist/governance/rules/settlement.d.ts +7 -0
- package/dist/governance/rules/settlement.js +24 -0
- package/dist/governance/tools/shared-tools.d.ts +2 -0
- package/dist/governance/tools/shared-tools.js +15 -1
- package/dist/governance/tools/submit-tools.js +14 -7
- package/dist/host/commands.d.ts +18 -0
- package/dist/host/commands.js +30 -0
- package/dist/host/controller-factory.d.ts +109 -0
- package/dist/host/controller-factory.js +159 -0
- package/dist/host/controller-feed.d.ts +122 -0
- package/dist/host/controller-feed.js +356 -0
- package/dist/host/index-build.d.ts +23 -0
- package/dist/host/index-build.js +35 -0
- package/dist/host/index.d.ts +21 -0
- package/dist/host/index.js +21 -0
- package/dist/host/interaction.d.ts +58 -0
- package/dist/host/interaction.js +165 -0
- package/dist/host/logging.d.ts +7 -0
- package/dist/host/logging.js +7 -0
- package/dist/host/prompts.d.ts +10 -0
- package/dist/host/prompts.js +9 -0
- package/dist/host/sessions.d.ts +87 -0
- package/dist/host/sessions.js +234 -0
- package/dist/host/settings.d.ts +104 -0
- package/dist/host/settings.js +235 -0
- package/dist/host/skills.d.ts +19 -0
- package/dist/host/skills.js +38 -0
- package/dist/skills/command-names.d.ts +19 -0
- package/dist/skills/command-names.js +28 -0
- package/dist/skills/invoke.d.ts +38 -0
- package/dist/skills/invoke.js +65 -0
- package/dist/team/overseer.d.ts +25 -1
- package/dist/team/overseer.js +38 -1
- package/dist/team/runtime.d.ts +2 -0
- package/dist/team/runtime.js +10 -7
- package/dist/team/subagent.js +6 -4
- package/package.json +3 -3
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Submit / interrupt state machine for a host that has no Ink `App`.
|
|
3
|
+
*
|
|
4
|
+
* THE DECISION TABLE IS `App.tsx::submitMessage` AND THE ESC HANDLER, restated without React
|
|
5
|
+
* refs. It is a RESTATEMENT, not an extraction: those two functions are woven through the
|
|
6
|
+
* TUI's refs (follow-through timers, nudge budget, run metrics), so moving them would have
|
|
7
|
+
* meant rewriting the TUI's own submit path. `interaction.test.ts` pins the branches this
|
|
8
|
+
* class shares with it (restart guard, starting guard, queue-while-running, preflight
|
|
9
|
+
* failure, `not-started` outcome, double-Esc ladder) so the two cannot drift silently.
|
|
10
|
+
*
|
|
11
|
+
* NOT HERE, ON PURPOSE: the todo follow-through and the forced-dispatch nudge. Both are
|
|
12
|
+
* TUI-initiated continuations; a desktop host that wants them calls `submit(...,
|
|
13
|
+
* { userInitiated: false })` itself after `onAgentEnd`.
|
|
14
|
+
*
|
|
15
|
+
* NO INK, NO TTY (layering gate L9).
|
|
16
|
+
*/
|
|
17
|
+
import { appendPrompt } from '../config/prompt-history.js';
|
|
18
|
+
import { bumpSubmitCount } from '../config/ui-state.js';
|
|
19
|
+
import { postureAppliedToast } from '../governance/copy.js';
|
|
20
|
+
import { advanceInterruptGesture, cancelInterruptConfirmation, } from '@aragon-agent/tui/input/interrupt-gesture';
|
|
21
|
+
import { splitPosture } from '@aragon-agent/tui/model/governance/posture';
|
|
22
|
+
import { buildInvocationCard, invocationCardsEnabled } from '@aragon-agent/tui/model/agent/invocation-card';
|
|
23
|
+
import { getSecrets } from '@aragon-agent/tui/model/logging/secret-registry';
|
|
24
|
+
import { redactText } from '../logging/redact.js';
|
|
25
|
+
export class InteractionCoordinator {
|
|
26
|
+
ports;
|
|
27
|
+
phaseValue = 'idle';
|
|
28
|
+
sequence = 0;
|
|
29
|
+
gesture = { phase: 'ready' };
|
|
30
|
+
disposed = false;
|
|
31
|
+
constructor(ports) {
|
|
32
|
+
this.ports = ports;
|
|
33
|
+
}
|
|
34
|
+
get phase() {
|
|
35
|
+
return this.phaseValue;
|
|
36
|
+
}
|
|
37
|
+
/** Feed `agent_start` / `agent_end` here so `phase` follows the engine. */
|
|
38
|
+
onAgentStart() {
|
|
39
|
+
this.phaseValue = 'running';
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* `agent_end`: the run is over, so a deferred `plan -> build` (or any posture change that
|
|
43
|
+
* waited for a governed stage) becomes real here and nowhere else.
|
|
44
|
+
*/
|
|
45
|
+
onAgentEnd() {
|
|
46
|
+
this.phaseValue = 'idle';
|
|
47
|
+
this.gesture = { phase: 'ready' };
|
|
48
|
+
const { controller, dispatch } = this.ports;
|
|
49
|
+
const applied = controller.applyPendingPosture();
|
|
50
|
+
if (!applied)
|
|
51
|
+
return;
|
|
52
|
+
const split = splitPosture(applied.effective);
|
|
53
|
+
dispatch({
|
|
54
|
+
type: 'setAgentMode',
|
|
55
|
+
mode: split.mode,
|
|
56
|
+
pending: null,
|
|
57
|
+
posture: applied.effective,
|
|
58
|
+
pendingPosture: applied.pending,
|
|
59
|
+
});
|
|
60
|
+
dispatch({ type: 'pushToast', level: 'info', text: postureAppliedToast(applied.effective) });
|
|
61
|
+
}
|
|
62
|
+
/** Send a message to the agent, bypassing slash parsing. */
|
|
63
|
+
submit(message, opts = {}) {
|
|
64
|
+
const { controller, dispatch, notify } = this.ports;
|
|
65
|
+
if (controller.getConfig().modelSettingsRestartRequired) {
|
|
66
|
+
return { accepted: false, reason: 'Settings require a restart before sending requests.' };
|
|
67
|
+
}
|
|
68
|
+
if (this.phaseValue === 'starting') {
|
|
69
|
+
return { accepted: false, reason: 'A run is still starting. Stop it before sending again.' };
|
|
70
|
+
}
|
|
71
|
+
// Same rule as `App.submitMessage`: the card (redact -> normalise -> limit) replaces what the
|
|
72
|
+
// TRANSCRIPT shows; `message`, the model's input, is never touched.
|
|
73
|
+
const card = opts.invocation && invocationCardsEnabled()
|
|
74
|
+
? buildInvocationCard(opts.invocation, (text) => redactText(text, getSecrets()))
|
|
75
|
+
: undefined;
|
|
76
|
+
const shown = card?.commandLine ?? message;
|
|
77
|
+
if (this.phaseValue === 'running' || controller.isCompactionBusy?.()) {
|
|
78
|
+
try {
|
|
79
|
+
const queueId = controller.queueUserMessage(message);
|
|
80
|
+
dispatch({ type: 'steerQueued', queueId, text: shown, ...(card ? { invocation: card } : {}) });
|
|
81
|
+
return { accepted: true };
|
|
82
|
+
}
|
|
83
|
+
catch (error) {
|
|
84
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
85
|
+
notify('error', reason);
|
|
86
|
+
return { accepted: false, reason };
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
this.gesture = { phase: 'ready' };
|
|
90
|
+
const sequence = ++this.sequence;
|
|
91
|
+
this.phaseValue = 'starting';
|
|
92
|
+
dispatch({ type: 'runStarting' });
|
|
93
|
+
if (opts.userInitiated !== false) {
|
|
94
|
+
// A card's payload must never reach the up-arrow history (the same gate as the terminal).
|
|
95
|
+
if (!card)
|
|
96
|
+
appendPrompt(message);
|
|
97
|
+
controller.setSubmitCount(bumpSubmitCount());
|
|
98
|
+
}
|
|
99
|
+
dispatch({ type: 'submit', text: shown, ...(card ? { invocation: card } : {}) });
|
|
100
|
+
const pre = controller.preflight();
|
|
101
|
+
if (!pre.ok) {
|
|
102
|
+
dispatch({ type: 'runError' });
|
|
103
|
+
notify('error', pre.message ?? 'Configuration error.');
|
|
104
|
+
this.phaseValue = 'idle';
|
|
105
|
+
dispatch({ type: 'runEnd' }); // reset status; nothing was started
|
|
106
|
+
return { accepted: true };
|
|
107
|
+
}
|
|
108
|
+
// Fire-and-forget: events drive the UI. prompt() never rejects.
|
|
109
|
+
void controller.prompt(message, { todoPolicy: opts.todoPolicy ?? 'new-task' }).then((outcome) => {
|
|
110
|
+
if (this.disposed || sequence !== this.sequence)
|
|
111
|
+
return;
|
|
112
|
+
if (outcome?.status !== 'not-started')
|
|
113
|
+
return;
|
|
114
|
+
if (outcome.reason !== 'cancelled')
|
|
115
|
+
dispatch({ type: 'runError' });
|
|
116
|
+
this.phaseValue = 'idle';
|
|
117
|
+
dispatch({ type: 'runEnd' });
|
|
118
|
+
});
|
|
119
|
+
return { accepted: true };
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* One Esc / Stop press. First press arms and returns `hint`; a second inside the window
|
|
123
|
+
* aborts; a third (or any press while stopping) force-stops. A press while still
|
|
124
|
+
* `starting` cancels the pending run outright, because there is nothing to unwind.
|
|
125
|
+
*/
|
|
126
|
+
interrupt(now = performance.now()) {
|
|
127
|
+
const { controller, dispatch } = this.ports;
|
|
128
|
+
const next = advanceInterruptGesture(this.gesture, now);
|
|
129
|
+
this.gesture = next.state;
|
|
130
|
+
if (next.action === 'hint')
|
|
131
|
+
return 'hint';
|
|
132
|
+
const wasStarting = this.phaseValue === 'starting';
|
|
133
|
+
dispatch({ type: 'abortMark' });
|
|
134
|
+
if (next.action === 'force-stop' || wasStarting) {
|
|
135
|
+
this.sequence += 1;
|
|
136
|
+
this.phaseValue = 'idle';
|
|
137
|
+
this.gesture = { phase: 'ready' };
|
|
138
|
+
if (next.action === 'force-stop')
|
|
139
|
+
controller.forceStop();
|
|
140
|
+
else
|
|
141
|
+
controller.abort();
|
|
142
|
+
dispatch({ type: 'runEnd' });
|
|
143
|
+
dispatch({
|
|
144
|
+
type: 'pushToast',
|
|
145
|
+
level: 'warn',
|
|
146
|
+
text: next.action === 'force-stop' ? 'Force-stopped.' : 'Pending run cancelled.',
|
|
147
|
+
});
|
|
148
|
+
return next.action;
|
|
149
|
+
}
|
|
150
|
+
controller.abort();
|
|
151
|
+
return 'abort';
|
|
152
|
+
}
|
|
153
|
+
/** Any other input disarms a pending first Esc but cannot undo a requested stop. */
|
|
154
|
+
cancelInterruptConfirmation() {
|
|
155
|
+
this.gesture = cancelInterruptConfirmation(this.gesture);
|
|
156
|
+
}
|
|
157
|
+
dispose() {
|
|
158
|
+
this.disposed = true;
|
|
159
|
+
this.sequence += 1;
|
|
160
|
+
if (this.phaseValue === 'starting' || this.ports.controller.isCompactionBusy?.()) {
|
|
161
|
+
this.ports.controller.abort();
|
|
162
|
+
}
|
|
163
|
+
this.phaseValue = 'idle';
|
|
164
|
+
}
|
|
165
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Logging for a GUI host's session process: the same log file, line format and redaction the
|
|
3
|
+
* terminal writes, so a bug report that includes `~/.aragon-agent/logs` reads the same
|
|
4
|
+
* whichever front end produced it. Re-exports only; the behaviour lives in `logging/`.
|
|
5
|
+
*/
|
|
6
|
+
export { attachAgentEvents, attachTeamEvents, installLogging } from '../logging/install.js';
|
|
7
|
+
export { getLogger } from '../logging/logger.js';
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Logging for a GUI host's session process: the same log file, line format and redaction the
|
|
3
|
+
* terminal writes, so a bug report that includes `~/.aragon-agent/logs` reads the same
|
|
4
|
+
* whichever front end produced it. Re-exports only; the behaviour lives in `logging/`.
|
|
5
|
+
*/
|
|
6
|
+
export { attachAgentEvents, attachTeamEvents, installLogging } from '../logging/install.js';
|
|
7
|
+
export { getLogger } from '../logging/logger.js';
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Prompt-library facade: the same `quick-prompts.json` store the terminal reads and writes,
|
|
3
|
+
* re-exported as the one surface a GUI host may depend on.
|
|
4
|
+
*
|
|
5
|
+
* A PURE RE-EXPORT, ON PURPOSE. The store already serializes writes, repairs a damaged file
|
|
6
|
+
* (keeping a `.bak`) and reports repairs once; a wrapper that re-implemented any of that
|
|
7
|
+
* would drift. Hosts import from here so the layering gate has a single deep-import target.
|
|
8
|
+
*/
|
|
9
|
+
export { createPrompt, deletePrompt, flushPromptStats, getPromptLibraryRevision, loadPromptLibrary, movePrompt, recordPromptUse, reorderPrompts, setPromptFavorite, sortPromptIds, takePromptRepairNotice, updatePrompt, } from '../prompts/store.js';
|
|
10
|
+
export type { PromptDraftInput, PromptLibrary, PromptMutationResult, PromptSortKey, PromptWriteError, QuickPrompt, } from '@aragon-agent/tui/model/prompts/types';
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Prompt-library facade: the same `quick-prompts.json` store the terminal reads and writes,
|
|
3
|
+
* re-exported as the one surface a GUI host may depend on.
|
|
4
|
+
*
|
|
5
|
+
* A PURE RE-EXPORT, ON PURPOSE. The store already serializes writes, repairs a damaged file
|
|
6
|
+
* (keeping a `.bak`) and reports repairs once; a wrapper that re-implemented any of that
|
|
7
|
+
* would drift. Hosts import from here so the layering gate has a single deep-import target.
|
|
8
|
+
*/
|
|
9
|
+
export { createPrompt, deletePrompt, flushPromptStats, getPromptLibraryRevision, loadPromptLibrary, movePrompt, recordPromptUse, reorderPrompts, setPromptFavorite, sortPromptIds, takePromptRepairNotice, updatePrompt, } from '../prompts/store.js';
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Session-file facade for a host that must list, open and edit sessions WITHOUT a TUI.
|
|
3
|
+
*
|
|
4
|
+
* THE LIST IS DELIBERATELY SPLIT IN TWO. `meta` is the LAST key `writeSession` emits, after
|
|
5
|
+
* `messages`, `entries` and `todos`, so reading "just the header" is impossible and parsing
|
|
6
|
+
* every file whole costs hundreds of megabytes on a long history. {@link scanSessionFiles}
|
|
7
|
+
* is the cheap half (`readdir` + `stat`, no parsing); {@link describeSessionFile} is the
|
|
8
|
+
* expensive half and is meant to run off the UI thread, behind a cache keyed by
|
|
9
|
+
* `mtimeMs + size`. This module does not own the cache or the worker - it only supplies
|
|
10
|
+
* the two pure halves - so it stays free of thread and Electron concerns.
|
|
11
|
+
*
|
|
12
|
+
* NO INK, NO TTY (checked by the layering gate's L9 over this module's import closure).
|
|
13
|
+
*/
|
|
14
|
+
import { type SavedSession } from '../session/persist.js';
|
|
15
|
+
import { isValidSessionId, removeSession, sessionPathFor, sessionsDir, type SessionOrigin } from '../session/store.js';
|
|
16
|
+
import { SessionCheckpointWriter } from '../session/checkpoint.js';
|
|
17
|
+
export { isValidSessionId, removeSession, sessionPathFor, sessionsDir, SessionCheckpointWriter };
|
|
18
|
+
/** One session file as seen by `stat` alone. */
|
|
19
|
+
export interface SessionFileStat {
|
|
20
|
+
id: string;
|
|
21
|
+
path: string;
|
|
22
|
+
mtimeMs: number;
|
|
23
|
+
size: number;
|
|
24
|
+
}
|
|
25
|
+
/** One parsed row. `unreadable` rows keep the file visible instead of dropping it. */
|
|
26
|
+
export interface SessionRowData {
|
|
27
|
+
id: string;
|
|
28
|
+
path: string;
|
|
29
|
+
mtimeMs: number;
|
|
30
|
+
size: number;
|
|
31
|
+
unreadable: boolean;
|
|
32
|
+
title: string | null;
|
|
33
|
+
cwd: string;
|
|
34
|
+
updatedAt: number;
|
|
35
|
+
turns: number;
|
|
36
|
+
provider: string;
|
|
37
|
+
model: string;
|
|
38
|
+
origin: SessionOrigin;
|
|
39
|
+
pinned: boolean;
|
|
40
|
+
live: boolean;
|
|
41
|
+
branchOf?: string;
|
|
42
|
+
}
|
|
43
|
+
/** `readdir` + `stat`, newest first. Never parses a file; never throws. */
|
|
44
|
+
export declare function scanSessionFiles(dir?: string): SessionFileStat[];
|
|
45
|
+
/** Parse one file into a row. THE EXPENSIVE HALF: call it off the UI thread. */
|
|
46
|
+
export declare function describeSessionFile(file: SessionFileStat): SessionRowData;
|
|
47
|
+
export interface SessionLockInspection {
|
|
48
|
+
held: boolean;
|
|
49
|
+
/** True when the holder is a live process that is not in `ownPids`. */
|
|
50
|
+
ownedElsewhere: boolean;
|
|
51
|
+
pid?: number;
|
|
52
|
+
host?: string;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Who holds `<id>.lock`, WITHOUT taking it. A lock from a dead pid on this host is stale;
|
|
56
|
+
* a lock from another host is treated as live (we cannot probe it). `ownPids` lets the
|
|
57
|
+
* desktop recognise its own session hosts and not report them as "in the terminal".
|
|
58
|
+
*/
|
|
59
|
+
export declare function inspectSessionLock(id: string, ownPids?: readonly number[]): SessionLockInspection;
|
|
60
|
+
/** True when another live process is writing this session. */
|
|
61
|
+
export declare function isLiveOwnedElsewhere(id: string, ownPids?: readonly number[]): boolean;
|
|
62
|
+
/** Read one session by id. `null` for a missing, unreadable or invalid id. */
|
|
63
|
+
export declare function openSession(id: string): SavedSession | null;
|
|
64
|
+
/** Pin or unpin a session (`sessions prune` never deletes a pinned one). */
|
|
65
|
+
export declare function pinSession(id: string, pinned: boolean): boolean;
|
|
66
|
+
/**
|
|
67
|
+
* Copy a session to a new id that records `branchOf`. The copy is NOT live and carries no
|
|
68
|
+
* lock, so two writers can never share it; the original is untouched.
|
|
69
|
+
*/
|
|
70
|
+
export declare function branchSession(id: string): {
|
|
71
|
+
ok: true;
|
|
72
|
+
id: string;
|
|
73
|
+
} | {
|
|
74
|
+
ok: false;
|
|
75
|
+
};
|
|
76
|
+
export { applyRestoredSession, resolveStartupSession } from '../session/startup-session.js';
|
|
77
|
+
export type { SessionIdentity, StartupSessionResolution } from '../session/startup-session.js';
|
|
78
|
+
/**
|
|
79
|
+
* Mint and reserve an id for a brand-new session, or `null` if none could be reserved.
|
|
80
|
+
*
|
|
81
|
+
* The desktop main process needs the id BEFORE the host process exists (it keys the host
|
|
82
|
+
* pool, the window's port and the sidebar row by it), so reservation happens here instead of
|
|
83
|
+
* inside the host's `resolveStartupSession`. The reservation is the same legal empty
|
|
84
|
+
* `SavedSession` the terminal writes, so the file lists, loads and can be deleted like any
|
|
85
|
+
* other, and no other process can claim the name.
|
|
86
|
+
*/
|
|
87
|
+
export declare function reserveNewSession(): string | null;
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Session-file facade for a host that must list, open and edit sessions WITHOUT a TUI.
|
|
3
|
+
*
|
|
4
|
+
* THE LIST IS DELIBERATELY SPLIT IN TWO. `meta` is the LAST key `writeSession` emits, after
|
|
5
|
+
* `messages`, `entries` and `todos`, so reading "just the header" is impossible and parsing
|
|
6
|
+
* every file whole costs hundreds of megabytes on a long history. {@link scanSessionFiles}
|
|
7
|
+
* is the cheap half (`readdir` + `stat`, no parsing); {@link describeSessionFile} is the
|
|
8
|
+
* expensive half and is meant to run off the UI thread, behind a cache keyed by
|
|
9
|
+
* `mtimeMs + size`. This module does not own the cache or the worker - it only supplies
|
|
10
|
+
* the two pure halves - so it stays free of thread and Electron concerns.
|
|
11
|
+
*
|
|
12
|
+
* NO INK, NO TTY (checked by the layering gate's L9 over this module's import closure).
|
|
13
|
+
*/
|
|
14
|
+
import { existsSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
|
|
15
|
+
import { hostname } from 'node:os';
|
|
16
|
+
import { join } from 'node:path';
|
|
17
|
+
import process from 'node:process';
|
|
18
|
+
import { randomUUID } from 'node:crypto';
|
|
19
|
+
import { branchSessionId, createSessionId, reserveSessionId } from '../session/identity.js';
|
|
20
|
+
import { SESSION_ID_LIMITS } from '../session/limits.js';
|
|
21
|
+
import { loadSession } from '../session/persist.js';
|
|
22
|
+
import { basenameId, isValidSessionId, readSessionFile, removeSession, sessionPathFor, sessionsDir, writeSession, } from '../session/store.js';
|
|
23
|
+
import { SessionCheckpointWriter } from '../session/checkpoint.js';
|
|
24
|
+
export { isValidSessionId, removeSession, sessionPathFor, sessionsDir, SessionCheckpointWriter };
|
|
25
|
+
const POINTER_FILE = '.last.json';
|
|
26
|
+
/** `readdir` + `stat`, newest first. Never parses a file; never throws. */
|
|
27
|
+
export function scanSessionFiles(dir = sessionsDir()) {
|
|
28
|
+
if (!existsSync(dir))
|
|
29
|
+
return [];
|
|
30
|
+
const out = [];
|
|
31
|
+
let names;
|
|
32
|
+
try {
|
|
33
|
+
names = readdirSync(dir);
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return [];
|
|
37
|
+
}
|
|
38
|
+
for (const name of names) {
|
|
39
|
+
if (name === POINTER_FILE || name.endsWith('.lock') || !name.endsWith('.json'))
|
|
40
|
+
continue;
|
|
41
|
+
const path = join(dir, name);
|
|
42
|
+
try {
|
|
43
|
+
const stats = statSync(path);
|
|
44
|
+
if (!stats.isFile())
|
|
45
|
+
continue;
|
|
46
|
+
out.push({ id: basenameId(path), path, mtimeMs: stats.mtimeMs, size: stats.size });
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
/* A file that vanished between readdir and stat is simply not listed. */
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return out.sort((a, b) => b.mtimeMs - a.mtimeMs);
|
|
53
|
+
}
|
|
54
|
+
/** The first user message, collapsed to one line, used when no task summary exists. */
|
|
55
|
+
function firstUserLine(saved) {
|
|
56
|
+
for (const message of saved.messages) {
|
|
57
|
+
if (message.role !== 'user')
|
|
58
|
+
continue;
|
|
59
|
+
const text = typeof message.content === 'string'
|
|
60
|
+
? message.content
|
|
61
|
+
: message.content.map((part) => (part.type === 'text' ? part.text : '')).join(' ');
|
|
62
|
+
const line = text.replace(/\s+/g, ' ').trim();
|
|
63
|
+
if (line)
|
|
64
|
+
return line.slice(0, 120);
|
|
65
|
+
}
|
|
66
|
+
return null;
|
|
67
|
+
}
|
|
68
|
+
/** Parse one file into a row. THE EXPENSIVE HALF: call it off the UI thread. */
|
|
69
|
+
export function describeSessionFile(file) {
|
|
70
|
+
const saved = readSessionFile(file.path);
|
|
71
|
+
if (!saved) {
|
|
72
|
+
return {
|
|
73
|
+
...file, unreadable: true, title: null, cwd: '', updatedAt: file.mtimeMs, turns: 0,
|
|
74
|
+
provider: '', model: '', origin: 'exec', pinned: false, live: false,
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
const meta = saved.meta;
|
|
78
|
+
return {
|
|
79
|
+
...file,
|
|
80
|
+
unreadable: false,
|
|
81
|
+
title: firstUserLine(saved),
|
|
82
|
+
cwd: meta?.cwd ?? '',
|
|
83
|
+
updatedAt: meta?.updatedAt ?? saved.savedAt ?? file.mtimeMs,
|
|
84
|
+
turns: meta?.turns ?? 0,
|
|
85
|
+
provider: meta?.provider ?? saved.model?.providerId ?? '',
|
|
86
|
+
model: meta?.model ?? saved.model?.modelId ?? '',
|
|
87
|
+
origin: meta?.origin === 'tui' ? 'tui' : 'exec',
|
|
88
|
+
pinned: meta?.pinned === true,
|
|
89
|
+
live: meta?.live === true,
|
|
90
|
+
...(meta?.branchOf ? { branchOf: meta.branchOf } : {}),
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
function isAlive(pid) {
|
|
94
|
+
try {
|
|
95
|
+
process.kill(pid, 0);
|
|
96
|
+
return true;
|
|
97
|
+
}
|
|
98
|
+
catch (error) {
|
|
99
|
+
return error.code !== 'ESRCH';
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Who holds `<id>.lock`, WITHOUT taking it. A lock from a dead pid on this host is stale;
|
|
104
|
+
* a lock from another host is treated as live (we cannot probe it). `ownPids` lets the
|
|
105
|
+
* desktop recognise its own session hosts and not report them as "in the terminal".
|
|
106
|
+
*/
|
|
107
|
+
export function inspectSessionLock(id, ownPids = []) {
|
|
108
|
+
if (!isValidSessionId(id))
|
|
109
|
+
return { held: false, ownedElsewhere: false };
|
|
110
|
+
const path = join(sessionsDir(), `${id}.lock`);
|
|
111
|
+
let payload;
|
|
112
|
+
try {
|
|
113
|
+
payload = JSON.parse(readFileSync(path, 'utf-8'));
|
|
114
|
+
}
|
|
115
|
+
catch {
|
|
116
|
+
return { held: false, ownedElsewhere: false };
|
|
117
|
+
}
|
|
118
|
+
if (typeof payload.pid !== 'number' || typeof payload.host !== 'string') {
|
|
119
|
+
return { held: false, ownedElsewhere: false };
|
|
120
|
+
}
|
|
121
|
+
const sameHost = payload.host === hostname();
|
|
122
|
+
const alive = sameHost ? isAlive(payload.pid) : true;
|
|
123
|
+
const mine = ownPids.includes(payload.pid);
|
|
124
|
+
return {
|
|
125
|
+
held: alive,
|
|
126
|
+
ownedElsewhere: alive && !mine && payload.pid !== process.pid,
|
|
127
|
+
pid: payload.pid,
|
|
128
|
+
host: payload.host,
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
/** True when another live process is writing this session. */
|
|
132
|
+
export function isLiveOwnedElsewhere(id, ownPids = []) {
|
|
133
|
+
return inspectSessionLock(id, ownPids).ownedElsewhere;
|
|
134
|
+
}
|
|
135
|
+
/** Read one session by id. `null` for a missing, unreadable or invalid id. */
|
|
136
|
+
export function openSession(id) {
|
|
137
|
+
if (!isValidSessionId(id))
|
|
138
|
+
return null;
|
|
139
|
+
const path = sessionPathFor(id);
|
|
140
|
+
if (!existsSync(path))
|
|
141
|
+
return null;
|
|
142
|
+
try {
|
|
143
|
+
return loadSession(path);
|
|
144
|
+
}
|
|
145
|
+
catch {
|
|
146
|
+
return null;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
/** Atomic read-modify-write of one session file's `meta`; `false` if it cannot be done. */
|
|
150
|
+
function rewriteMeta(id, edit) {
|
|
151
|
+
if (!isValidSessionId(id))
|
|
152
|
+
return false;
|
|
153
|
+
const path = sessionPathFor(id);
|
|
154
|
+
let raw;
|
|
155
|
+
try {
|
|
156
|
+
raw = JSON.parse(readFileSync(path, 'utf-8'));
|
|
157
|
+
}
|
|
158
|
+
catch {
|
|
159
|
+
return false;
|
|
160
|
+
}
|
|
161
|
+
const meta = raw['meta'];
|
|
162
|
+
if (!meta || typeof meta !== 'object')
|
|
163
|
+
return false;
|
|
164
|
+
edit(meta);
|
|
165
|
+
const tmp = `${path}.${process.pid}.${randomUUID()}.tmp`;
|
|
166
|
+
try {
|
|
167
|
+
writeFileSync(tmp, `${JSON.stringify(raw, null, 2)}\n`, { encoding: 'utf-8', flag: 'wx' });
|
|
168
|
+
renameSync(tmp, path);
|
|
169
|
+
return true;
|
|
170
|
+
}
|
|
171
|
+
catch {
|
|
172
|
+
return false;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
/** Pin or unpin a session (`sessions prune` never deletes a pinned one). */
|
|
176
|
+
export function pinSession(id, pinned) {
|
|
177
|
+
return rewriteMeta(id, (meta) => {
|
|
178
|
+
if (pinned)
|
|
179
|
+
meta.pinned = true;
|
|
180
|
+
else
|
|
181
|
+
delete meta.pinned;
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Copy a session to a new id that records `branchOf`. The copy is NOT live and carries no
|
|
186
|
+
* lock, so two writers can never share it; the original is untouched.
|
|
187
|
+
*/
|
|
188
|
+
export function branchSession(id) {
|
|
189
|
+
const source = openSession(id);
|
|
190
|
+
if (!source?.meta)
|
|
191
|
+
return { ok: false };
|
|
192
|
+
const childId = branchSessionId(id);
|
|
193
|
+
const now = Date.now();
|
|
194
|
+
try {
|
|
195
|
+
const { pinned: _pinned, live: _live, ...inheritedMeta } = source.meta;
|
|
196
|
+
writeSession({
|
|
197
|
+
id: childId,
|
|
198
|
+
session: {
|
|
199
|
+
model: source.model ?? { providerId: source.meta.provider, modelId: source.meta.model },
|
|
200
|
+
messages: source.messages,
|
|
201
|
+
...(source.compactionIdentity ? { compactionIdentity: source.compactionIdentity } : {}),
|
|
202
|
+
entries: source.entries,
|
|
203
|
+
...(source.todos ? { todos: source.todos } : {}),
|
|
204
|
+
...(source.acceptance ? { acceptance: source.acceptance } : {}),
|
|
205
|
+
},
|
|
206
|
+
meta: { ...inheritedMeta, id: childId, createdAt: now, updatedAt: now, branchOf: id, origin: 'tui' },
|
|
207
|
+
});
|
|
208
|
+
return { ok: true, id: childId };
|
|
209
|
+
}
|
|
210
|
+
catch {
|
|
211
|
+
return { ok: false };
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
// Startup resolution, shared with the terminal so both mint ids, branch and restore alike.
|
|
215
|
+
// `applyRestoredSession` adopts a saved conversation into a controller; `resolveStartupSession`
|
|
216
|
+
// reserves an id (fresh) or derives a child id (resume = branch, the terminal's own rule).
|
|
217
|
+
export { applyRestoredSession, resolveStartupSession } from '../session/startup-session.js';
|
|
218
|
+
/**
|
|
219
|
+
* Mint and reserve an id for a brand-new session, or `null` if none could be reserved.
|
|
220
|
+
*
|
|
221
|
+
* The desktop main process needs the id BEFORE the host process exists (it keys the host
|
|
222
|
+
* pool, the window's port and the sidebar row by it), so reservation happens here instead of
|
|
223
|
+
* inside the host's `resolveStartupSession`. The reservation is the same legal empty
|
|
224
|
+
* `SavedSession` the terminal writes, so the file lists, loads and can be deleted like any
|
|
225
|
+
* other, and no other process can claim the name.
|
|
226
|
+
*/
|
|
227
|
+
export function reserveNewSession() {
|
|
228
|
+
for (let attempt = 0; attempt < SESSION_ID_LIMITS.reserveAttempts; attempt += 1) {
|
|
229
|
+
const id = createSessionId();
|
|
230
|
+
if (reserveSessionId(id))
|
|
231
|
+
return id;
|
|
232
|
+
}
|
|
233
|
+
return null;
|
|
234
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Config facade for hosts that own no controller (the Electron main process).
|
|
3
|
+
*
|
|
4
|
+
* EVERY WRITE GOES THROUGH THE SAME FUNCTIONS THE TUI USES (`commitModelSettings` for the
|
|
5
|
+
* compare-and-swap, `mergePersistedConfig` for clamping), so a desktop write and a terminal
|
|
6
|
+
* write can interleave on one `config.json` without losing an update. Nothing here holds a
|
|
7
|
+
* controller and nothing here writes to stdout.
|
|
8
|
+
*
|
|
9
|
+
* KEYS NEVER LEAVE THIS MODULE IN THE CLEAR except through {@link revealApiKey}: the view
|
|
10
|
+
* carries `{ present, tail, source }` per provider and per profile.
|
|
11
|
+
*/
|
|
12
|
+
import { type ModelInfo } from '@aragon-agent/core';
|
|
13
|
+
import { type ConfigReadError, type ModelSettingsPatch, type ModelSettingsSaveResult } from '../config/model-profile-store.js';
|
|
14
|
+
import { type PersistedConfig } from '@aragon-agent/tui/model/config/schema';
|
|
15
|
+
import type { ModelProfile, ModelProfilesConfig } from '@aragon-agent/tui/model/config/model-profiles';
|
|
16
|
+
/**
|
|
17
|
+
* Keys the terminal owns and a GUI neither shows nor edits (spec A.4 "shared-keep").
|
|
18
|
+
* They are preserved byte-for-byte by {@link patchConfig}; this list only feeds the
|
|
19
|
+
* settings page's "N terminal-only settings are kept" line.
|
|
20
|
+
*/
|
|
21
|
+
export declare const TERMINAL_ONLY_KEYS: readonly string[];
|
|
22
|
+
export interface MaskedKey {
|
|
23
|
+
present: boolean;
|
|
24
|
+
/** Last four characters, or '' when absent. Never enough to reconstruct a key. */
|
|
25
|
+
tail: string;
|
|
26
|
+
source: 'file' | 'env' | 'none';
|
|
27
|
+
}
|
|
28
|
+
export interface MaskedProfile extends Omit<ModelProfile, 'apiKey'> {
|
|
29
|
+
key: MaskedKey;
|
|
30
|
+
}
|
|
31
|
+
export interface ConfigView extends Omit<PersistedConfig, 'apiKeys' | 'modelProfiles'> {
|
|
32
|
+
apiKeys: Record<string, MaskedKey>;
|
|
33
|
+
modelProfiles: (Omit<ModelProfilesConfig, 'entries'> & {
|
|
34
|
+
entries: MaskedProfile[];
|
|
35
|
+
}) | null;
|
|
36
|
+
}
|
|
37
|
+
export interface ConfigViewResult {
|
|
38
|
+
ok: boolean;
|
|
39
|
+
/** sha256 of the file bytes, or `missing` / `unreadable`. The CAS token. */
|
|
40
|
+
revision: string;
|
|
41
|
+
path: string;
|
|
42
|
+
view: ConfigView | null;
|
|
43
|
+
error?: ConfigReadError;
|
|
44
|
+
/** Keys present in the file that this build does not know. Preserved on write. */
|
|
45
|
+
unknownKeys: string[];
|
|
46
|
+
terminalOnlyKeys: string[];
|
|
47
|
+
}
|
|
48
|
+
export type ConfigPatchResult = {
|
|
49
|
+
ok: true;
|
|
50
|
+
revision: string;
|
|
51
|
+
changedKeys: string[];
|
|
52
|
+
} | {
|
|
53
|
+
ok: false;
|
|
54
|
+
code: NonNullable<ModelSettingsSaveResult['code']>;
|
|
55
|
+
revision: string;
|
|
56
|
+
};
|
|
57
|
+
/** Project a normalized config into the masked shape a renderer may see. */
|
|
58
|
+
export declare function toConfigView(config: PersistedConfig): ConfigView;
|
|
59
|
+
/** Read the config file, never throwing and never resetting a damaged file. */
|
|
60
|
+
export declare function readConfigView(): ConfigViewResult;
|
|
61
|
+
/**
|
|
62
|
+
* Apply `patch` to the file that is on disk NOW, behind a revision check.
|
|
63
|
+
*
|
|
64
|
+
* FIDELITY RULE: the write starts from the RAW parsed file, not from the normalized object.
|
|
65
|
+
* Only top-level keys whose normalized value actually changed are overwritten, so a key a
|
|
66
|
+
* newer terminal build wrote (or one this build does not know) survives, and a patch that
|
|
67
|
+
* touches `theme` produces a diff of exactly `theme` (AC-14).
|
|
68
|
+
*/
|
|
69
|
+
export declare function patchConfig(input: {
|
|
70
|
+
baseRevision: string;
|
|
71
|
+
patch: ModelSettingsPatch & {
|
|
72
|
+
modelProfiles?: ModelProfilesConfig;
|
|
73
|
+
};
|
|
74
|
+
}): ConfigPatchResult;
|
|
75
|
+
/** The ONE path that returns a stored key in the clear; the caller audits it. */
|
|
76
|
+
export declare function revealApiKey(provider: string, profileId?: string): string | null;
|
|
77
|
+
/** Register every stored secret with the log redactor. Call at boot and on `config.changed`. */
|
|
78
|
+
export declare function registerConfigSecrets(): void;
|
|
79
|
+
export interface ConnectionDraft {
|
|
80
|
+
provider: string;
|
|
81
|
+
model: string;
|
|
82
|
+
baseUrl?: string | null;
|
|
83
|
+
/** Clear key from an unsaved draft. When absent the stored/env key is used. */
|
|
84
|
+
apiKey?: string | null;
|
|
85
|
+
/** Stored profile whose key to use when the draft carries none. */
|
|
86
|
+
profileId?: string;
|
|
87
|
+
}
|
|
88
|
+
export type ConnectionStage = 'config' | 'network' | 'auth' | 'model' | 'stream' | 'ok';
|
|
89
|
+
export interface ConnectionTestResult {
|
|
90
|
+
ok: boolean;
|
|
91
|
+
stage: ConnectionStage;
|
|
92
|
+
/** Human-readable, actionable reason; never contains the key. */
|
|
93
|
+
detail: string;
|
|
94
|
+
latencyMs?: number;
|
|
95
|
+
}
|
|
96
|
+
/** One tiny streamed request, classified by stage. Aborts after 20 s. */
|
|
97
|
+
export declare function testConnection(draft: ConnectionDraft, signal?: AbortSignal): Promise<ConnectionTestResult>;
|
|
98
|
+
/** List the models a draft can reach. Never throws; an unreachable endpoint yields `[]`. */
|
|
99
|
+
export declare function discoverModels(draft: Pick<ConnectionDraft, 'provider' | 'baseUrl' | 'apiKey' | 'profileId'>, signal?: AbortSignal): Promise<ModelInfo[]>;
|
|
100
|
+
export { redactText } from '../logging/redact.js';
|
|
101
|
+
export { getSecrets } from '@aragon-agent/tui/model/logging/secret-registry';
|
|
102
|
+
export { runDoctorChecks } from '../diagnostics/doctor.js';
|
|
103
|
+
export type { DoctorReport } from '../diagnostics/doctor.js';
|
|
104
|
+
export { getConfigBackupPath, getConfigPath as getConfigFilePath, getHomeRoot, getLogsDir, isHomeOverridden, } from '../config/app-paths.js';
|