@rarog/server 1.0.1 → 1.1.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -3
- package/node_modules/@rarog/shared/package.json +1 -1
- package/node_modules/@rarog/shared/src/decode.js +49 -3
- package/node_modules/@rarog/shared/src/protocol/files.js +33 -0
- package/node_modules/@rarog/shared/src/protocol/inbox.js +38 -0
- package/node_modules/@rarog/shared/src/protocol.js +16 -17
- package/node_modules/@rarog/shared/src/rest.js +106 -12
- package/node_modules/@rarog/shared/src/sentences/rest.js +13 -0
- package/package.json +3 -3
- package/server/src/bootstrap/consent.js +88 -2
- package/server/src/bootstrap/http.js +3 -2
- package/server/src/bootstrap/inbox.js +29 -4
- package/server/src/bootstrap/sse.js +2 -1
- package/server/src/cli/doctor-no-hook.js +162 -0
- package/server/src/cli/doctor.js +2 -0
- package/server/src/cli/update-channel.js +100 -0
- package/server/src/cli/update-registry.js +160 -62
- package/server/src/cli/update.js +13 -3
- package/server/src/companion/turns-settle.js +4 -1
- package/server/src/companion/turns.js +36 -5
- package/server/src/config/files.js +32 -0
- package/server/src/config/flags.js +10 -1
- package/server/src/config-env.js +24 -0
- package/server/src/config.js +6 -2
- package/server/src/demo/files.js +49 -0
- package/server/src/demo/inbox.js +73 -0
- package/server/src/demo/review-routes.js +6 -1
- package/server/src/device-effects.js +3 -1
- package/server/src/drivers/herdr/consent-no-hook-io.js +89 -0
- package/server/src/drivers/herdr/consent-no-hook.js +316 -0
- package/server/src/drivers/herdr/refusals.js +226 -0
- package/server/src/drivers/herdr/returned-prompt.js +172 -0
- package/server/src/drivers/herdr-driver.js +116 -287
- package/server/src/files/file-index.js +246 -0
- package/server/src/files/ignored.js +119 -0
- package/server/src/files/listing.js +76 -0
- package/server/src/files/path-rule.js +145 -0
- package/server/src/files/refusals.js +36 -0
- package/server/src/files/send-file.js +115 -0
- package/server/src/files/session-download.js +51 -0
- package/server/src/files/session-files.js +38 -0
- package/server/src/files/session-gate.js +48 -0
- package/server/src/git-status.js +3 -2
- package/server/src/herdr/audit.js +1 -1
- package/server/src/herdr/dialogs/hook/contract.js +16 -9
- package/server/src/herdr/dialogs/index.js +6 -1
- package/server/src/herdr/dialogs/layer1/hook-list/hook-list.js +132 -59
- package/server/src/herdr/dialogs/layer1/hook-list/session-facts.js +135 -0
- package/server/src/herdr/dialogs/layer1/version-gate.js +13 -5
- package/server/src/herdr/dialogs/no-hook.js +63 -0
- package/server/src/herdr/dialogs/screen/block.js +10 -0
- package/server/src/herdr/dialogs/screen/parse.js +10 -1
- package/server/src/herdr/jsonl-pending.js +25 -1
- package/server/src/inbox/card.js +18 -9
- package/server/src/inbox/dialogs.js +40 -12
- package/server/src/inbox/heads.js +55 -0
- package/server/src/inbox/inbox.js +24 -2
- package/server/src/inbox/index.js +3 -1
- package/server/src/index.js +22 -18
- package/server/src/install/repair.js +8 -0
- package/server/src/log-timestamps.js +9 -4
- package/server/src/router.js +7 -1
- package/server/src/routes/devices.js +2 -2
- package/server/src/routes/inbox.js +91 -0
- package/server/src/routes/sessions.js +135 -14
- package/server/src/routes/system.js +5 -4
- package/server/src/safe-read.js +86 -1
- package/server/src/sessions/companion-scope.js +6 -2
- package/server/src/sessions/demo-modules.js +16 -0
- package/server/src/sessions/diff-measure.js +30 -0
- package/server/src/sessions/manager.js +64 -152
- package/server/src/sessions/ring-buffer.js +18 -3
- package/server/src/sessions/seen-marks.js +9 -6
- package/server/src/sessions/session-scope.js +30 -0
- package/server/src/sessions/session.js +20 -1
- package/server/src/sessions/waiting-line.js +72 -0
- package/server/src/sse.js +40 -6
- package/server/src/version.js +30 -0
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The file tree of the demo sessions: one fixed project that every demo session lists through
|
|
3
|
+
* `GET /api/sessions/:id/files` and downloads a file of through `GET /api/sessions/:id/files/raw`, with no disk and
|
|
4
|
+
* no git. It agrees with the demo diff (`DEMO_DIFF_FILES` of the mock driver): the added and the modified file stand
|
|
5
|
+
* in `src`, the deleted one does not.
|
|
6
|
+
*/
|
|
7
|
+
import { compareFileEntries } from '@rarog/shared';
|
|
8
|
+
/** Path of every file of the demo project → its text; a directory is every leading part of a path. */
|
|
9
|
+
export const DEMO_FILES = {
|
|
10
|
+
'README.md': '# notes\n\nA small notes service: write, list and remove notes.\n',
|
|
11
|
+
'package.json': '{\n "name": "notes",\n "private": true,\n "type": "module"\n}\n',
|
|
12
|
+
'tsconfig.json': '{\n "compilerOptions": {\n "strict": true,\n "outDir": "dist"\n }\n}\n',
|
|
13
|
+
'docs/guide.md': '# Guide\n\nRun the tests before every release.\n',
|
|
14
|
+
'src/index.ts': "export { addNote, listNotes } from './notes.ts';\n",
|
|
15
|
+
'src/notes.ts': 'export const listNotes = (): string[] => [];\nexport const addNote = (text: string): string => text;\n',
|
|
16
|
+
'src/notes.test.ts': "import { listNotes } from './notes.ts';\n\nconsole.assert(listNotes().length === 0);\n",
|
|
17
|
+
'dist/index.js': "export { addNote, listNotes } from './notes.js';\n",
|
|
18
|
+
'dist/notes.js': 'export const listNotes = () => [];\nexport const addNote = (text) => text;\n',
|
|
19
|
+
};
|
|
20
|
+
/** Directories git ignores in the demo project (its `.gitignore` names `dist/`), with everything under them. */
|
|
21
|
+
const IGNORED_DIRS = ['dist'];
|
|
22
|
+
const isIgnored = (rel) => IGNORED_DIRS.some((dir) => rel === dir || rel.startsWith(`${dir}/`));
|
|
23
|
+
/**
|
|
24
|
+
* The entries of the directory `dir` of the demo project (`''` = the session directory), in the order of a listing;
|
|
25
|
+
* `null` when the project has no such directory.
|
|
26
|
+
*/
|
|
27
|
+
export function demoFileEntries(dir) {
|
|
28
|
+
const prefix = dir === '' ? '' : `${dir}/`;
|
|
29
|
+
const entries = new Map();
|
|
30
|
+
for (const [file, text] of Object.entries(DEMO_FILES)) {
|
|
31
|
+
if (!file.startsWith(prefix))
|
|
32
|
+
continue;
|
|
33
|
+
const rest = file.slice(prefix.length);
|
|
34
|
+
const slash = rest.indexOf('/');
|
|
35
|
+
const name = slash === -1 ? rest : rest.slice(0, slash);
|
|
36
|
+
const label = isIgnored(`${prefix}${name}`) ? { ignored: true } : {};
|
|
37
|
+
entries.set(name, slash === -1
|
|
38
|
+
? { name, kind: 'file', size: Buffer.byteLength(text, 'utf8'), ...label }
|
|
39
|
+
: { name, kind: 'dir', ...label });
|
|
40
|
+
}
|
|
41
|
+
if (entries.size === 0)
|
|
42
|
+
return dir === '' ? [] : null;
|
|
43
|
+
return [...entries.values()].sort(compareFileEntries);
|
|
44
|
+
}
|
|
45
|
+
/** The bytes of the file `rel` of the demo project (its UTF-8 text); `null` when the project has no such file. */
|
|
46
|
+
export function demoFileBytes(rel) {
|
|
47
|
+
const text = Object.hasOwn(DEMO_FILES, rel) ? DEMO_FILES[rel] : undefined;
|
|
48
|
+
return text === undefined ? null : Buffer.from(text, 'utf8');
|
|
49
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { segmentByInput } from '../herdr/input-segments.js';
|
|
2
|
+
import { demoBlocks } from './seeds.js';
|
|
3
|
+
/**
|
|
4
|
+
* The session manager with an engine conversation for every demo session in scope: a seed without a live driver
|
|
5
|
+
* (a session that hit its limit, say) has none, and the tracker gives a session without one no card. The made-up
|
|
6
|
+
* conversation is the session id behind a prefix; nothing outside the demo Inbox sees it.
|
|
7
|
+
*/
|
|
8
|
+
export function demoInboxManager(manager) {
|
|
9
|
+
return {
|
|
10
|
+
get: manager.get.bind(manager),
|
|
11
|
+
list: manager.list.bind(manager),
|
|
12
|
+
companionTarget: (id) => {
|
|
13
|
+
const target = manager.companionTarget(id);
|
|
14
|
+
return target === null || target.agentSessionId !== undefined
|
|
15
|
+
? target : { ...target, agentSessionId: `demo-conversation-${id}` };
|
|
16
|
+
},
|
|
17
|
+
markSeen: manager.markSeen.bind(manager),
|
|
18
|
+
markUnseen: manager.markUnseen.bind(manager),
|
|
19
|
+
onEvent: manager.onEvent.bind(manager),
|
|
20
|
+
onConversationChange: manager.onConversationChange.bind(manager),
|
|
21
|
+
eventsSince: manager.eventsSince.bind(manager),
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
/** The dialog events of a session stream the tracker folds for the identity of a decision card's dialog. */
|
|
25
|
+
const DIALOG_EVENTS = new Set([
|
|
26
|
+
'permission-pending', 'permission-settled', 'permission-resolved', 'question-pending', 'question-resolved',
|
|
27
|
+
]);
|
|
28
|
+
/**
|
|
29
|
+
* Segments of the demo session that writes the engine conversation `agentSessionId`, from the `message` events of
|
|
30
|
+
* its ring. The opening entry of a turn has no file entry id, so a turn is keyed by its time and text: the seeds get
|
|
31
|
+
* new times at every start, so a removal made before a demo restart matches no card after it. A ring that already
|
|
32
|
+
* dropped its first events reads as `unreadable`, and the card keeps the turn it showed.
|
|
33
|
+
*/
|
|
34
|
+
export function createDemoSegmentReader(manager) {
|
|
35
|
+
return (_cwd, agentSessionId) => Promise.resolve(readDemoSegments(manager, agentSessionId));
|
|
36
|
+
}
|
|
37
|
+
function readDemoSegments(manager, agentSessionId) {
|
|
38
|
+
const sessionId = manager.list().find((session) => conversationOf(manager, session.id) === agentSessionId)?.id;
|
|
39
|
+
if (sessionId === undefined)
|
|
40
|
+
return { kind: 'no-file' };
|
|
41
|
+
const replay = manager.eventsSince(sessionId, 0);
|
|
42
|
+
if (replay.tooOld)
|
|
43
|
+
return { kind: 'unreadable' };
|
|
44
|
+
const entries = replay.events.flatMap(({ event }) => (event.type === 'message' ? [entryOf(event.message)] : []));
|
|
45
|
+
return { kind: 'read', segments: segmentByInput(agentSessionId, entries).segments, wholeFile: true };
|
|
46
|
+
}
|
|
47
|
+
function conversationOf(manager, sessionId) {
|
|
48
|
+
try {
|
|
49
|
+
return manager.companionTarget(sessionId)?.agentSessionId;
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
return undefined;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
function entryOf(message) {
|
|
56
|
+
return {
|
|
57
|
+
role: message.role, blocks: demoBlocks(message.blocks), at: message.at,
|
|
58
|
+
...(message.notice === undefined ? {} : { notice: message.notice }),
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Hands the tracker the dialog events already in the rings of the demo sessions: the seeds register their permission
|
|
63
|
+
* cards while the manager is built, before the tracker listens, so without them a demo decision card would have no
|
|
64
|
+
* request id. The ring holds every dialog event in order, so a repeated event folds to the same state.
|
|
65
|
+
*/
|
|
66
|
+
export function replayDemoDialogs(manager, inbox) {
|
|
67
|
+
for (const session of manager.list()) {
|
|
68
|
+
for (const { event } of manager.eventsSince(session.id, 0).events) {
|
|
69
|
+
if (DIALOG_EVENTS.has(event.type))
|
|
70
|
+
inbox.noteEvent(session.id, event);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
*/
|
|
24
24
|
/** Akcje `/api/sessions/:id/<akcja>` (`segments[3]` w routerze): wszystkie dozwolone, podakcje dziedziczą klasę. */
|
|
25
25
|
const SESSION_ACTIONS = [
|
|
26
|
-
'answers', 'close', 'commands', 'diff', 'focus', 'interrupt', 'messages', 'mode', 'model', 'permission',
|
|
26
|
+
'answers', 'close', 'commands', 'diff', 'files', 'focus', 'interrupt', 'messages', 'mode', 'model', 'permission',
|
|
27
27
|
'permissions', 'queue', 'restart', 'resume', 'seen', 'stream', 'unseen', 'uploads',
|
|
28
28
|
];
|
|
29
29
|
export const REVIEW_ROUTES = [
|
|
@@ -57,6 +57,11 @@ export const REVIEW_ROUTES = [
|
|
|
57
57
|
{ route: '/api/push/live-activity/end', class: 'allow' },
|
|
58
58
|
{ route: '/api/sessions', class: 'allow' },
|
|
59
59
|
...SESSION_ACTIONS.map((action) => ({ route: `/api/sessions/:id/${action}`, class: 'allow' })),
|
|
60
|
+
// Inbox cards of the demo sessions; a removal lands in `inbox.json` of the demo data directory.
|
|
61
|
+
{ route: '/api/inbox', class: 'allow' },
|
|
62
|
+
{ route: '/api/inbox/:id', class: 'allow' },
|
|
63
|
+
{ route: '/api/inbox/:id/remove', class: 'allow' },
|
|
64
|
+
{ route: '/api/inbox/:id/restore', class: 'allow' },
|
|
60
65
|
// Kod parowania dla testów UI, który odpina wszystkie urządzenia: w trybie recenzji router go nie wydaje.
|
|
61
66
|
{ route: '/api/demo/pairing', class: 'absent' },
|
|
62
67
|
// Agent głosowy: demo nie ma pliku rozmowy ani procesu `claude -p`, więc trasy nie ma także dla recenzenta.
|
|
@@ -9,6 +9,7 @@ export function attachDeactivation(store, targets) {
|
|
|
9
9
|
const streams = targets.hub.closeOwner(id);
|
|
10
10
|
const sockets = targets.term?.closeOwner(id) ?? 0;
|
|
11
11
|
const questions = targets.companion?.closeOwner(id) ?? 0;
|
|
12
|
+
const downloads = targets.files?.closeOwner(id) ?? 0;
|
|
12
13
|
revokeDevice(id);
|
|
13
14
|
let tokens = 0;
|
|
14
15
|
const apns = targets.apns;
|
|
@@ -20,7 +21,8 @@ export function attachDeactivation(store, targets) {
|
|
|
20
21
|
tokens = apns.devices.removeOwnedBy(id).length;
|
|
21
22
|
}
|
|
22
23
|
targets.log(`devices: ${id} revoked (${by}) — streams: ${String(streams)},`
|
|
23
|
-
+ ` consoles: ${String(sockets)}, APNs tokens: ${String(tokens)}, voice agent: ${String(questions)}
|
|
24
|
+
+ ` consoles: ${String(sockets)}, APNs tokens: ${String(tokens)}, voice agent: ${String(questions)},`
|
|
25
|
+
+ ` file downloads: ${String(downloads)}`);
|
|
24
26
|
}
|
|
25
27
|
});
|
|
26
28
|
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The two system reads of the consent-without-hook detector (`consent-no-hook.ts`): whether `ps` shows Rarog's hook
|
|
3
|
+
* as a child of the session process, and how fresh the session's `statusLine` dump is. Each read gives an answer or
|
|
4
|
+
* "unknown"; neither throws, and neither reads a file's content.
|
|
5
|
+
*/
|
|
6
|
+
import { execFile } from 'node:child_process';
|
|
7
|
+
import { stat } from 'node:fs/promises';
|
|
8
|
+
import { STATUSLINE_FRESH_MS } from '../../herdr/hook-config.js';
|
|
9
|
+
import { statuslinePath } from '../../herdr/statusline.js';
|
|
10
|
+
/** `ps` from an absolute path (macOS and Linux), without the server's `PATH`. */
|
|
11
|
+
const PS_PATH = '/bin/ps';
|
|
12
|
+
/** Every process with its parent and its arguments, unwrapped: the hook is a direct child of the session process. */
|
|
13
|
+
const PS_ARGS = ['-A', '-ww', '-o', 'ppid=,args='];
|
|
14
|
+
/**
|
|
15
|
+
* Ceiling of the `ps` run; it runs once per judgement of a consent dialog without a hook trace, off the card's path. A
|
|
16
|
+
* registry that stops saying `waiting: permission` during the facts read gives the episode one more judgement.
|
|
17
|
+
*/
|
|
18
|
+
const PS_TIMEOUT_MS = 1_000;
|
|
19
|
+
/** Ceiling of the `ps` output (every process of the machine). */
|
|
20
|
+
const PS_MAX_BUFFER = 8 * 1024 * 1024;
|
|
21
|
+
const runPs = (args) => new Promise((resolve) => {
|
|
22
|
+
execFile(PS_PATH, [...args], { timeout: PS_TIMEOUT_MS, maxBuffer: PS_MAX_BUFFER, encoding: 'utf8' }, (err, out) => {
|
|
23
|
+
resolve(err === null ? out : null);
|
|
24
|
+
});
|
|
25
|
+
});
|
|
26
|
+
/** The interpreter of the hook command, by its name or its path. */
|
|
27
|
+
const NODE = /(?:^|\/)node$/;
|
|
28
|
+
/**
|
|
29
|
+
* Whether the arguments of one process are the hook command: `node`, then `script` as its first argument, then the end
|
|
30
|
+
* or a space. `ps` joins the arguments with spaces, so with whitespace in the interpreter or in `script` the bounds of
|
|
31
|
+
* the arguments are not settled: `null`.
|
|
32
|
+
*/
|
|
33
|
+
function hookArgs(args, script) {
|
|
34
|
+
const needle = ` ${script}`;
|
|
35
|
+
for (let at = args.indexOf(needle); at !== -1; at = args.indexOf(needle, at + 1)) {
|
|
36
|
+
const end = at + needle.length;
|
|
37
|
+
if (end < args.length && args[end] !== ' ')
|
|
38
|
+
continue;
|
|
39
|
+
const interpreter = args.slice(0, at);
|
|
40
|
+
if (!NODE.test(interpreter))
|
|
41
|
+
continue;
|
|
42
|
+
return /\s/.test(interpreter) || /\s/.test(script) ? null : true;
|
|
43
|
+
}
|
|
44
|
+
return false;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Whether a child of the process `pid` runs the hook script `script` (`node <home>/.claude/hooks/rarog/rarog-pending.mjs
|
|
48
|
+
* --answer-wait=…`, measured on CLI 2.1.330: a direct child of the session's `claude` process, also for a subagent's
|
|
49
|
+
* dialog). `null` = `ps` unavailable, its output unreadable or a child whose arguments may be the hook but whose
|
|
50
|
+
* argument bounds `ps` does not settle: never "no hook".
|
|
51
|
+
*/
|
|
52
|
+
export async function hookChildRunning(pid, script, run = runPs) {
|
|
53
|
+
const out = await run(PS_ARGS).catch(() => null);
|
|
54
|
+
if (out === null)
|
|
55
|
+
return null;
|
|
56
|
+
let rows = 0;
|
|
57
|
+
let unsettled = false;
|
|
58
|
+
for (const line of out.split('\n')) {
|
|
59
|
+
const row = /^\s*(\d+)\s+(.*)$/.exec(line);
|
|
60
|
+
if (row === null)
|
|
61
|
+
continue;
|
|
62
|
+
rows += 1;
|
|
63
|
+
if (Number(row[1]) !== pid)
|
|
64
|
+
continue;
|
|
65
|
+
const hook = hookArgs(row[2] ?? '', script);
|
|
66
|
+
if (hook === true)
|
|
67
|
+
return true;
|
|
68
|
+
if (hook === null)
|
|
69
|
+
unsettled = true;
|
|
70
|
+
}
|
|
71
|
+
// A run that lists no process at all did not list this machine's processes.
|
|
72
|
+
return rows === 0 || unsettled ? null : false;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Freshness of the session's `statusLine` dump (`<root>/<session>.json`) by its modification time: `fresh` within
|
|
76
|
+
* {@link STATUSLINE_FRESH_MS} of `now`, `stale` older, `none` without a regular file there. It is an observation in
|
|
77
|
+
* the log line, not a cause: the dump refreshes on events only.
|
|
78
|
+
*/
|
|
79
|
+
export async function statuslineFreshness(root, engineSessionId, now) {
|
|
80
|
+
try {
|
|
81
|
+
const file = await stat(statuslinePath(root, engineSessionId));
|
|
82
|
+
if (!file.isFile())
|
|
83
|
+
return 'none';
|
|
84
|
+
return now - file.mtimeMs <= STATUSLINE_FRESH_MS ? 'fresh' : 'stale';
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
87
|
+
return 'none';
|
|
88
|
+
}
|
|
89
|
+
}
|
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
import { consentModeNow, noApproveButtonLine, noHookCause, noHookLine, offPathApprove, subagentDialogOnScreen, } from '../../herdr/dialogs/index.js';
|
|
2
|
+
import { consentChannelOpen } from '../../herdr/dialogs/hook/contract.js';
|
|
3
|
+
/**
|
|
4
|
+
* The grace from the episode start: a hook trace that comes within it means the hook came. Hooks that came were measured
|
|
5
|
+
* 6–528 ms after the block, and the hook process stands in `ps` 26–154 ms after the CLI registry enters `waiting`
|
|
6
|
+
* (CLI 2.1.330).
|
|
7
|
+
*/
|
|
8
|
+
export const NO_HOOK_GRACE_MS = 3_000;
|
|
9
|
+
/**
|
|
10
|
+
* Evaluations per episode, the first one included. An evaluation reads the session facts and runs `ps`; one that ends
|
|
11
|
+
* without channel mode or the `permission` class goes again at the next registry signal, and a registry that flaps
|
|
12
|
+
* between no answer and `waiting: permission` during the reads would otherwise cost one facts read and one `ps` per
|
|
13
|
+
* flap. Past the budget the episode stays judged and gets no line.
|
|
14
|
+
*/
|
|
15
|
+
export const NO_HOOK_EVALUATIONS = 3;
|
|
16
|
+
/** Reads of the session facts per episode: a read that ends on another process or `cwd` gives none and goes again. */
|
|
17
|
+
const FACTS_READS = 2;
|
|
18
|
+
/** Card identities remembered for the `no approve button` line; past the cap the memory starts again. */
|
|
19
|
+
const BUTTONLESS_MAX = 256;
|
|
20
|
+
let episodes = 0;
|
|
21
|
+
/** The call the card stands for: the jsonl entry or the hook call key; `undefined` = a card from the screen alone. */
|
|
22
|
+
const callIdOf = (card) => card.active.origin?.toolUseId ?? card.active.callId ?? card.active.origin?.callKey;
|
|
23
|
+
/**
|
|
24
|
+
* Whether the card shows the dialog of the episode: a card swap within one dialog (a degraded or screen card replaced
|
|
25
|
+
* by the jsonl card) keeps the episode, while another call or another dialog block starts a new one.
|
|
26
|
+
*/
|
|
27
|
+
function sameDialog(episode, card) {
|
|
28
|
+
const callId = callIdOf(card);
|
|
29
|
+
if (episode.callId !== undefined && callId !== undefined && episode.callId !== callId)
|
|
30
|
+
return false;
|
|
31
|
+
const print = card.active.bodyPrint;
|
|
32
|
+
return episode.print === undefined || print === undefined || episode.print === print;
|
|
33
|
+
}
|
|
34
|
+
export class ConsentNoHook {
|
|
35
|
+
#deps;
|
|
36
|
+
#scheduler;
|
|
37
|
+
#inScope;
|
|
38
|
+
#cwd;
|
|
39
|
+
#port;
|
|
40
|
+
#episode = null;
|
|
41
|
+
/** End of the last episode, epoch; `0` before the first one (registrations of this process only). */
|
|
42
|
+
#since = 0;
|
|
43
|
+
/** Card identities that already have their `no approve button` line. */
|
|
44
|
+
#buttonless = new Set();
|
|
45
|
+
/** Within {@link handover}: the block changes hands, it does not end. */
|
|
46
|
+
#handingOver = false;
|
|
47
|
+
constructor(config, port) {
|
|
48
|
+
this.#deps = config.deps;
|
|
49
|
+
this.#scheduler = config.scheduler;
|
|
50
|
+
this.#inScope = config.inScope;
|
|
51
|
+
this.#cwd = config.cwd;
|
|
52
|
+
this.#port = port;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* A card for the standing dialog, before the channel gate decides whether it goes out (`#showCard`). The same dialog
|
|
56
|
+
* keeps its episode; a new dialog closes the old one and opens its own that starts at the block start, or at this card
|
|
57
|
+
* when an earlier episode of the same block ended. The grace timer then orders the judgement.
|
|
58
|
+
*/
|
|
59
|
+
noteCard(card) {
|
|
60
|
+
this.#observe(() => { this.#noteCard(card); });
|
|
61
|
+
}
|
|
62
|
+
#noteCard(card) {
|
|
63
|
+
if (this.#deps.consentNoHook === undefined || !this.#inScope || this.#port.disposed())
|
|
64
|
+
return;
|
|
65
|
+
const sessionId = this.#port.agentSessionId();
|
|
66
|
+
if (sessionId === '')
|
|
67
|
+
return;
|
|
68
|
+
const current = this.#episode;
|
|
69
|
+
if (current !== null && this.#stands(current) && sameDialog(current, card)) {
|
|
70
|
+
this.#describe(current, card);
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
const now = this.#scheduler.now();
|
|
74
|
+
const sameBlock = current !== null && current.blockSeq === this.#port.blockedSeq();
|
|
75
|
+
// The previous dialog ended at Rarog's key after it opened, otherwise now, when another dialog replaced it; an
|
|
76
|
+
// episode the block end already ended keeps that moment.
|
|
77
|
+
const answeredAt = this.#port.answeredAt();
|
|
78
|
+
if (current !== null)
|
|
79
|
+
this.#end(current, answeredAt > current.openedAt ? Math.min(now, answeredAt) : now);
|
|
80
|
+
episodes += 1;
|
|
81
|
+
const t0 = sameBlock ? now : Math.min(now, this.#port.blockedAt());
|
|
82
|
+
const episode = {
|
|
83
|
+
id: `no-hook:${String(episodes)}`, sessionId, blockSeq: this.#port.blockedSeq(), t0, openedAt: now,
|
|
84
|
+
since: this.#since, callId: undefined, print: undefined, tool: card.active.toolName, screenButton: false,
|
|
85
|
+
thread: 'main', waiting: this.#port.cliWaiting() === 'permission', timer: null, evaluations: 0, state: 'grace',
|
|
86
|
+
};
|
|
87
|
+
this.#describe(episode, card);
|
|
88
|
+
this.#episode = episode;
|
|
89
|
+
episode.timer = this.#scheduler.setTimeout(() => {
|
|
90
|
+
episode.timer = null;
|
|
91
|
+
if (episode.state === 'grace')
|
|
92
|
+
episode.state = 'due';
|
|
93
|
+
this.#observe(() => { this.#judge(episode); });
|
|
94
|
+
}, Math.max(0, t0 + NO_HOOK_GRACE_MS - now));
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* A card that goes out: when the channel gate took its approve button (the `off` path card would have it), one
|
|
98
|
+
* `consent: no approve button` line per card identity.
|
|
99
|
+
*/
|
|
100
|
+
cardShown(card, event) {
|
|
101
|
+
this.#observe(() => { this.#cardShown(card, event); });
|
|
102
|
+
}
|
|
103
|
+
#cardShown(card, event) {
|
|
104
|
+
if (event.type !== 'permission-request' || event.canAllow !== false || !offPathApprove(card.event))
|
|
105
|
+
return;
|
|
106
|
+
const reqId = card.active.reqId;
|
|
107
|
+
if (this.#buttonless.has(reqId))
|
|
108
|
+
return;
|
|
109
|
+
if (this.#buttonless.size >= BUTTONLESS_MAX)
|
|
110
|
+
this.#buttonless.clear();
|
|
111
|
+
this.#buttonless.add(reqId);
|
|
112
|
+
const sessionId = this.#port.agentSessionId();
|
|
113
|
+
const rules = this.#proofRules(sessionId);
|
|
114
|
+
const thread = this.#threadOf(card);
|
|
115
|
+
this.#log(noApproveButtonLine({
|
|
116
|
+
sessionId, reason: event.unavailable ?? null, tool: card.active.toolName, channel: consentModeNow(this.#deps),
|
|
117
|
+
rule: rules === null ? null : rules[thread === 'main' ? 'main' : 'subagents'], cli: this.#port.cliVersion(),
|
|
118
|
+
}));
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* A registry signal came. `closed` (the registry says `active`) after the registry said `waiting: permission` within
|
|
122
|
+
* the episode is a desk decision, which ends it; an `active` before that is a read from before the dialog. Otherwise
|
|
123
|
+
* an episode past its grace that waited for the `permission` class is judged now.
|
|
124
|
+
*/
|
|
125
|
+
registrySignal(closed = false) {
|
|
126
|
+
this.#observe(() => { this.#registrySignal(closed); });
|
|
127
|
+
}
|
|
128
|
+
#registrySignal(closed) {
|
|
129
|
+
const episode = this.#episode;
|
|
130
|
+
if (episode === null || episode.state === 'ended')
|
|
131
|
+
return;
|
|
132
|
+
if (closed && episode.waiting) {
|
|
133
|
+
this.#end(episode, this.#scheduler.now());
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
if (this.#port.cliWaiting() === 'permission')
|
|
137
|
+
episode.waiting = true;
|
|
138
|
+
if (episode.state === 'due')
|
|
139
|
+
this.#judge(episode);
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* `drop` hands the effective block over within one block (herdr's own `blocked` follows the CLI registry
|
|
143
|
+
* hold): a block end signalled while the block is between its two holders does not end the episode, which keeps its
|
|
144
|
+
* start and its grace timer.
|
|
145
|
+
*/
|
|
146
|
+
handover(drop) {
|
|
147
|
+
this.#handingOver = true;
|
|
148
|
+
try {
|
|
149
|
+
drop();
|
|
150
|
+
}
|
|
151
|
+
finally {
|
|
152
|
+
this.#handingOver = false;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
/** The effective block ended: the dialog is gone or answered at the desk, so its episode ends. */
|
|
156
|
+
blockEnded() {
|
|
157
|
+
if (this.#handingOver)
|
|
158
|
+
return;
|
|
159
|
+
this.#observe(() => {
|
|
160
|
+
const episode = this.#episode;
|
|
161
|
+
if (episode !== null && episode.state !== 'ended')
|
|
162
|
+
this.#end(episode, this.#scheduler.now());
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
dispose() {
|
|
166
|
+
const episode = this.#episode;
|
|
167
|
+
this.#episode = null;
|
|
168
|
+
this.#observe(() => {
|
|
169
|
+
if (episode?.timer !== null && episode?.timer !== undefined)
|
|
170
|
+
this.#scheduler.clearTimeout(episode.timer);
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* One step of the detector, called from the card, the poll, the registry signal and the grace timer. The detector
|
|
175
|
+
* only observes, so its failure never reaches them: the episode may lose its line, the card and the block go on.
|
|
176
|
+
* The evaluation past the grace that reads the facts goes on after the step returned; its failure takes the same
|
|
177
|
+
* `#failed` line.
|
|
178
|
+
*/
|
|
179
|
+
#observe(step) {
|
|
180
|
+
try {
|
|
181
|
+
step();
|
|
182
|
+
}
|
|
183
|
+
catch (err) {
|
|
184
|
+
this.#failed(err);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
/** The line of a detector failure, by the error's name only. */
|
|
188
|
+
#failed(err) {
|
|
189
|
+
try {
|
|
190
|
+
this.#deps.logger?.(`consent: no hook detector failed (${err instanceof Error ? err.name : typeof err})`);
|
|
191
|
+
}
|
|
192
|
+
catch {
|
|
193
|
+
// The logger itself failed: nothing more to tell.
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
/** The card's tool, the `off` path button and the thread, from the latest card of the episode. */
|
|
197
|
+
#describe(episode, card) {
|
|
198
|
+
episode.callId ??= callIdOf(card);
|
|
199
|
+
episode.print ??= card.active.bodyPrint;
|
|
200
|
+
episode.tool = card.active.toolName;
|
|
201
|
+
episode.screenButton = offPathApprove(card.event);
|
|
202
|
+
episode.thread = this.#threadOf(card);
|
|
203
|
+
}
|
|
204
|
+
/** Whether the episode still stands: same session and block, no own key since it opened, not ended. */
|
|
205
|
+
#stands(episode) {
|
|
206
|
+
return episode.state !== 'ended' && !this.#port.disposed() && this.#port.agentSessionId() === episode.sessionId
|
|
207
|
+
&& this.#port.blockedNow() && this.#port.blockedSeq() === episode.blockSeq
|
|
208
|
+
&& this.#port.answeredAt() <= episode.openedAt;
|
|
209
|
+
}
|
|
210
|
+
/** Ends the episode at `at` (scheduler clock): the next episode's registration window starts there. */
|
|
211
|
+
#end(episode, at) {
|
|
212
|
+
if (episode.timer !== null)
|
|
213
|
+
this.#scheduler.clearTimeout(episode.timer);
|
|
214
|
+
episode.timer = null;
|
|
215
|
+
if (episode.state === 'ended')
|
|
216
|
+
return;
|
|
217
|
+
episode.state = 'ended';
|
|
218
|
+
this.#since = Math.max(this.#since, this.#epochOf(at));
|
|
219
|
+
}
|
|
220
|
+
/** A scheduler time as epoch ms: the scheduler and the epoch clock differ in tests. */
|
|
221
|
+
#epochOf(at) {
|
|
222
|
+
return this.#deps.now() - (this.#scheduler.now() - at);
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* The judgement past the grace: only in channel mode, for the `permission` class from the registry and without a hook trace.
|
|
226
|
+
* Without the class yet it waits for the next registry signal.
|
|
227
|
+
*/
|
|
228
|
+
#judge(episode) {
|
|
229
|
+
const sources = this.#deps.consentNoHook;
|
|
230
|
+
if (sources === undefined || this.#episode !== episode || episode.state !== 'due')
|
|
231
|
+
return;
|
|
232
|
+
if (!this.#stands(episode)) {
|
|
233
|
+
this.#end(episode, this.#scheduler.now());
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
if (!consentChannelOpen(consentModeNow(this.#deps)) || this.#port.cliWaiting() !== 'permission')
|
|
237
|
+
return;
|
|
238
|
+
episode.state = 'judged';
|
|
239
|
+
if (this.#traced(sources, episode))
|
|
240
|
+
return;
|
|
241
|
+
episode.evaluations += 1;
|
|
242
|
+
void this.#judgeFacts(sources, episode).catch((err) => { this.#failed(err); });
|
|
243
|
+
}
|
|
244
|
+
async #judgeFacts(sources, episode) {
|
|
245
|
+
let facts = null;
|
|
246
|
+
for (let read = 0; read < FACTS_READS && facts === null; read += 1) {
|
|
247
|
+
facts = await sources.facts({ sessionId: episode.sessionId, episode: episode.id }).catch(() => null);
|
|
248
|
+
}
|
|
249
|
+
const pid = facts?.process?.pid;
|
|
250
|
+
const [hookRunning, statusline] = await Promise.all([
|
|
251
|
+
pid === undefined ? null : sources.hookRunning(pid).catch(() => null),
|
|
252
|
+
sources.statusline(episode.sessionId).catch(() => 'none'),
|
|
253
|
+
]);
|
|
254
|
+
// The reads take time: a trace or an end (a desk decision included) that came meanwhile wins over the line, and
|
|
255
|
+
// without channel mode or the `permission` class now the judgement waits for the next registry signal again, while
|
|
256
|
+
// the episode has evaluations left.
|
|
257
|
+
if (this.#episode !== episode || !this.#stands(episode) || this.#traced(sources, episode))
|
|
258
|
+
return;
|
|
259
|
+
if (!consentChannelOpen(consentModeNow(this.#deps)) || this.#port.cliWaiting() !== 'permission') {
|
|
260
|
+
if (episode.evaluations < NO_HOOK_EVALUATIONS)
|
|
261
|
+
episode.state = 'due';
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
const layers = facts?.layers ?? null;
|
|
265
|
+
this.#log(noHookLine({
|
|
266
|
+
sessionId: episode.sessionId,
|
|
267
|
+
cause: noHookCause({
|
|
268
|
+
hookRunning, outsideWorkArea: this.#outsideWorkArea(sources, facts?.cwd ?? null),
|
|
269
|
+
disableAllHooks: layers?.disableAllHooks ?? null, allowManagedHooksOnly: layers?.allowManagedHooksOnly ?? null,
|
|
270
|
+
rarogEntry: layers?.rarogEntry ?? null,
|
|
271
|
+
}),
|
|
272
|
+
tool: episode.tool, cli: this.#port.cliVersion(), mode: this.#port.permissionMode(), thread: episode.thread,
|
|
273
|
+
afterMs: this.#scheduler.now() - episode.t0, hooks: facts?.verdict ?? null, statusline,
|
|
274
|
+
screenButton: episode.screenButton,
|
|
275
|
+
}));
|
|
276
|
+
}
|
|
277
|
+
/** A trace of the hook since the previous episode; a source that throws or cannot read counts as one. */
|
|
278
|
+
#traced(sources, episode) {
|
|
279
|
+
try {
|
|
280
|
+
return sources.hookTrace(episode.sessionId, episode.since) !== false;
|
|
281
|
+
}
|
|
282
|
+
catch {
|
|
283
|
+
return true;
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
/** The session `cwd` from the registry outside the work area; the pane's own `cwd` is in scope already. */
|
|
287
|
+
#outsideWorkArea(sources, cwd) {
|
|
288
|
+
if (cwd === null)
|
|
289
|
+
return null;
|
|
290
|
+
if (cwd === this.#cwd)
|
|
291
|
+
return false;
|
|
292
|
+
try {
|
|
293
|
+
return sources.outsideWorkArea(cwd);
|
|
294
|
+
}
|
|
295
|
+
catch {
|
|
296
|
+
return null;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
#threadOf(card) {
|
|
300
|
+
if (card.active.origin?.agentId !== undefined)
|
|
301
|
+
return 'subagent';
|
|
302
|
+
const screen = this.#port.screenText();
|
|
303
|
+
return screen !== null && subagentDialogOnScreen(screen) ? 'subagent' : 'main';
|
|
304
|
+
}
|
|
305
|
+
#proofRules(sessionId) {
|
|
306
|
+
try {
|
|
307
|
+
return this.#deps.consentNoHook?.proofRules(sessionId) ?? null;
|
|
308
|
+
}
|
|
309
|
+
catch {
|
|
310
|
+
return null;
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
#log(line) {
|
|
314
|
+
this.#deps.logger?.(line);
|
|
315
|
+
}
|
|
316
|
+
}
|