@chroxy/server 0.11.10 → 0.11.11
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/CONFIG.md +4 -2
- package/package.json +3 -3
- package/src/acp-session.js +5 -1
- package/src/agent-connections.js +12 -1
- package/src/agent-control/client.js +29 -0
- package/src/agent-control/events.js +8 -4
- package/src/agent-control/local-connection.js +34 -16
- package/src/agent-control/mcp-server.js +2 -0
- package/src/anthropic-compatible-config.js +1 -0
- package/src/anthropic-gemini-shim.js +444 -0
- package/src/anthropic-gemini-translate.js +1030 -0
- package/src/base-session.js +319 -2
- package/src/bound-client-policy.js +12 -0
- package/src/byok-mcp-config.js +9 -5
- package/src/byok-mcp-trust.js +34 -20
- package/src/byok-session.js +62 -9
- package/src/byok-tool-executor.js +81 -1
- package/src/claude-setting-sources.js +74 -0
- package/src/claude-tui/pty-driver.js +5 -1
- package/src/claude-tui/usage-limit.js +2 -2
- package/src/claude-tui-session.js +57 -4
- package/src/cli/agent-cmd.js +236 -0
- package/src/cli/connection-state.js +54 -0
- package/src/cli/freshness-cmd.js +53 -0
- package/src/cli/pages-cmd.js +6 -4
- package/src/cli/pair-code-cmd.js +7 -6
- package/src/cli/pair-discord-cmd.js +7 -6
- package/src/cli/schedule-cmd.js +25 -3
- package/src/cli/server-cmd.js +6 -0
- package/src/cli/shell-cmd.js +7 -4
- package/src/cli/status-cmd.js +19 -5
- package/src/cli-session.js +190 -11
- package/src/cli.js +4 -0
- package/src/codex-app-server-session.js +78 -17
- package/src/codex-error-text.js +114 -0
- package/src/config-dir-migration.js +11 -6
- package/src/config.js +23 -3
- package/src/connection-info.js +73 -14
- package/src/continuations.js +153 -40
- package/src/conversation-scanner.js +2 -21
- package/src/conversation-search.js +4 -17
- package/src/dev-preview.js +2 -1
- package/src/docker-session.js +10 -1
- package/src/doctor.js +14 -3
- package/src/durable-write.js +35 -0
- package/src/environments/authority.js +7 -1
- package/src/event-normalizer.js +35 -2
- package/src/folder-trust-wire.js +137 -0
- package/src/folder-trust-worker.js +17 -0
- package/src/folder-trust.js +1572 -0
- package/src/freshness/activity-meter.js +101 -0
- package/src/freshness/adapter.js +199 -0
- package/src/freshness/checks.js +239 -0
- package/src/freshness/config.js +98 -0
- package/src/freshness/core.js +185 -0
- package/src/freshness/derive.js +680 -0
- package/src/freshness/exchange.js +305 -0
- package/src/freshness/file-ledger.js +400 -0
- package/src/freshness/grade.js +81 -0
- package/src/freshness/hash.js +45 -0
- package/src/freshness/inbox.js +163 -0
- package/src/freshness/index.js +20 -0
- package/src/freshness/investigation.js +474 -0
- package/src/freshness/keys.js +177 -0
- package/src/freshness/ledger.js +122 -0
- package/src/freshness/outbox.js +131 -0
- package/src/freshness/policy.js +599 -0
- package/src/freshness/queue.js +843 -0
- package/src/freshness/read-errors.js +23 -0
- package/src/freshness/render.js +153 -0
- package/src/freshness/runtime.js +113 -0
- package/src/freshness/session-registry-adapter.js +161 -0
- package/src/freshness/state-file-adapter.js +167 -0
- package/src/freshness-runner/build-info.js +139 -0
- package/src/freshness-runner/cli.js +105 -0
- package/src/freshness-runner/run-tick.js +109 -0
- package/src/freshness-runner/stamp.js +57 -0
- package/src/freshness-sources/claude-transcript-adapter.js +211 -0
- package/src/freshness-sources/codex-transcript-adapter.js +33 -0
- package/src/freshness-sources/index.js +8 -0
- package/src/gemini-byok-session.js +292 -0
- package/src/gemini-credentials.js +67 -0
- package/src/gemini-key-safety.js +246 -0
- package/src/gemini-models.js +386 -0
- package/src/handler-utils.js +6 -13
- package/src/handlers/checkpoint-handlers.js +8 -0
- package/src/handlers/folder-trust-handlers.js +90 -0
- package/src/handlers/input-handlers.js +40 -11
- package/src/handlers/principal-admin-handlers.js +229 -0
- package/src/handlers/principal-handlers.js +262 -0
- package/src/handlers/scheduler-handlers.js +4 -4
- package/src/handlers/session-handlers.js +10 -1
- package/src/handlers/settings-handlers.js +42 -8
- package/src/handlers/skills-handlers.js +7 -0
- package/src/history-page.js +8 -0
- package/src/jsonl-reader.js +90 -10
- package/src/jsonl-subprocess-session.js +4 -1
- package/src/logger.js +105 -15
- package/src/mailbox-route.js +102 -0
- package/src/notification-prefs.js +15 -0
- package/src/orchestration/orchestration-manager.js +38 -9
- package/src/orchestration/permission-gate.js +4 -1
- package/src/orchestration/run-record.js +11 -0
- package/src/orchestration/turn-driver.js +151 -33
- package/src/orphan-reaper.js +77 -20
- package/src/outgoing-policy.js +10 -4
- package/src/permission-floor.js +54 -2
- package/src/permission-manager.js +32 -13
- package/src/permission-resolved-by.js +89 -0
- package/src/permission-resolver.js +7 -3
- package/src/platform.js +156 -4
- package/src/principal-audit.js +189 -0
- package/src/principal-binding.js +25 -0
- package/src/principal-brakes.js +21 -0
- package/src/principal-effect.js +101 -0
- package/src/principal-journal.js +905 -0
- package/src/principal-kill-switch.js +183 -0
- package/src/principal-label.js +5 -0
- package/src/principal-pending-permissions.js +177 -0
- package/src/principal-policy.js +1094 -0
- package/src/principal-sessions-snapshot.js +208 -0
- package/src/principal-store.js +488 -0
- package/src/principal-subscriptions.js +283 -0
- package/src/providers.js +2 -0
- package/src/redaction.js +181 -22
- package/src/scheduled-task-store.js +12 -0
- package/src/scheduler.js +304 -17
- package/src/sdk-session.js +60 -7
- package/src/server-cli/push-notification-handler.js +6 -1
- package/src/server-cli.js +30 -1
- package/src/session-ci-watcher.js +210 -37
- package/src/session-manager.js +590 -19
- package/src/session-message-history.js +121 -2
- package/src/session-name-allocator.js +685 -0
- package/src/statusline.js +78 -19
- package/src/summarize-session.js +2 -0
- package/src/turn-outcome.js +5 -2
- package/src/utils/argv-safety.js +29 -0
- package/src/utils/binary-package-manifest.js +57 -15
- package/src/utils/bounded-regex-worker.js +4 -0
- package/src/utils/bounded-regex.js +16 -7
- package/src/utils/pid-liveness.js +47 -0
- package/src/web-task-manager.js +45 -4
- package/src/worktree-gc.js +195 -4
- package/src/ws-auth.js +103 -19
- package/src/ws-broadcaster.js +39 -7
- package/src/ws-client-manager.js +8 -0
- package/src/ws-file-ops/browser.js +35 -3
- package/src/ws-forwarding.js +23 -3
- package/src/ws-handler-context.js +18 -0
- package/src/ws-history.js +79 -12
- package/src/ws-message-handlers.js +10 -2
- package/src/ws-server.js +253 -13
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which read error codes describe one file that was read, and which describe
|
|
3
|
+
* the source. The only classifier: every consumer asks `isFileLevelReadError`.
|
|
4
|
+
*
|
|
5
|
+
* A code is listed only if it describes one file in every adapter that emits it
|
|
6
|
+
* (`shape_changed` is not: the state-file and registry adapters report it for the
|
|
7
|
+
* whole source). An allowlist, so it fails safe: a code that is not named here (an unknown or
|
|
8
|
+
* future code, a missing one, `unreadable`, `source_missing`, `unsupported`,
|
|
9
|
+
* `adapter_fault`) counts as describing the source, as every error did before
|
|
10
|
+
* the split. The docs guide lists the same codes and a test holds the two
|
|
11
|
+
* lists equal.
|
|
12
|
+
*/
|
|
13
|
+
export const FILE_LEVEL_READ_ERRORS = Object.freeze(new Set(['window_exhausted', 'tail_too_small', 'corrupt', 'bad_timestamp']))
|
|
14
|
+
|
|
15
|
+
/** Whether an error code describes the one file that was read, not the source. */
|
|
16
|
+
export function isFileLevelReadError(code) {
|
|
17
|
+
return typeof code === 'string' && FILE_LEVEL_READ_ERRORS.has(code)
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Whether a check state (`outcome`, `errorCode`) is an error that describes the source. */
|
|
21
|
+
export function isSourceLevelError(check) {
|
|
22
|
+
return Boolean(check) && check.outcome === 'error' && !isFileLevelReadError(check.errorCode)
|
|
23
|
+
}
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Templates for the outbox: what an item, the digest, an echo and an alert
|
|
3
|
+
* say. No model writes any of it. Every sentence is fixed here, and the only
|
|
4
|
+
* values put into one are the item's declared-status fields (state, what it is
|
|
5
|
+
* blocked on, the decision, the next step, the owner it names, its time) and
|
|
6
|
+
* the session's source and id, each cleaned and cut to a length first.
|
|
7
|
+
*
|
|
8
|
+
* Nothing here reads a clock: a text names absolute times only, so the same
|
|
9
|
+
* item in the same state renders the same text and an unchanged item is never
|
|
10
|
+
* "updated". Pure functions over the derived state.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { H } from './hash.js'
|
|
14
|
+
import { effectiveState } from './derive.js'
|
|
15
|
+
|
|
16
|
+
const KEY_LEN = 32
|
|
17
|
+
|
|
18
|
+
/** The outbox key of an item's episode: stable, and the same on every restart. */
|
|
19
|
+
export function itemKey(itemId, episode) {
|
|
20
|
+
return H('outbox_key', itemId, episode).slice(0, KEY_LEN)
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** The id of one outbox record, from what it is made of. */
|
|
24
|
+
export function recId(...parts) {
|
|
25
|
+
return H('outbox_rec', ...parts).slice(0, KEY_LEN)
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export const DIGEST_KEY = H('outbox_digest').slice(0, KEY_LEN)
|
|
29
|
+
|
|
30
|
+
export const HEX_ID = new RegExp(`^[0-9a-f]{${KEY_LEN}}$`)
|
|
31
|
+
|
|
32
|
+
/** A value put in a text: one line, no control characters, cut to `max` characters. */
|
|
33
|
+
export function clean(value, max) {
|
|
34
|
+
if (value === null || value === undefined) return ''
|
|
35
|
+
// Control characters and every Unicode format character (bidi overrides and
|
|
36
|
+
// isolates, zero-width characters) become a space.
|
|
37
|
+
// That includes ZWJ and the soft hyphen, so an emoji ZWJ sequence splits: by design,
|
|
38
|
+
// safety in operator-visible text wins over emoji rendering.
|
|
39
|
+
const flat = String(value).replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029\p{Cf}]+/gu, ' ').replace(/\s+/g, ' ').trim()
|
|
40
|
+
// Cut by code point, so a surrogate pair is never split.
|
|
41
|
+
const points = Array.from(flat)
|
|
42
|
+
return points.length > max ? points.slice(0, Math.max(0, max - 1)).join('') + '…' : flat
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function iso(ms) {
|
|
46
|
+
return Number.isFinite(ms) ? new Date(ms).toISOString() : 'unknown time'
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function who(session, max) {
|
|
50
|
+
return session ? `session ${clean(session.source, 64)}/${clean(session.native_id, max)}` : 'a session'
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function reportOf(state, id) {
|
|
54
|
+
return id ? (state.reports.get(id)?.body ?? null) : null
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function field(label, value, max) {
|
|
58
|
+
const v = clean(value, max)
|
|
59
|
+
return v ? `${label}: ${v}` : null
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** One short line naming an item. */
|
|
63
|
+
export function headline(item, max = 240) {
|
|
64
|
+
const w = who(item.session, max)
|
|
65
|
+
switch (item.origin) {
|
|
66
|
+
case 'owner':
|
|
67
|
+
return `${w} needs the owner`
|
|
68
|
+
case 'attention':
|
|
69
|
+
return `${w} has an old status report`
|
|
70
|
+
case 'gone':
|
|
71
|
+
return `${w} is no longer listed`
|
|
72
|
+
case 'outage':
|
|
73
|
+
return `source ${clean(item.source, 64)} cannot be read`
|
|
74
|
+
case 'seed':
|
|
75
|
+
return `a seed to paste for ${clean(item.seed?.scope, max)}`
|
|
76
|
+
default:
|
|
77
|
+
return `${clean(item.kind, 64)} for ${w}`
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function ownerLines(state, item, max) {
|
|
82
|
+
const lines = []
|
|
83
|
+
const declared = item.asks.get('declared')
|
|
84
|
+
if (declared) {
|
|
85
|
+
const rep = reportOf(state, declared.report_id)
|
|
86
|
+
lines.push(field('Blocked on', rep?.declared_blocked_on, max), field('Decision', rep?.decision, max), field('Next', rep?.next, max), field('Reported', rep ? iso(rep.last_report_at) : null, max))
|
|
87
|
+
}
|
|
88
|
+
if (item.asks.has('prompt')) lines.push('A prompt is waiting for an answer.')
|
|
89
|
+
return lines
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function conditionLines(item, max) {
|
|
93
|
+
return item.carried.map((c) => `Also: the status report went stale (${clean(c.trigger, 64)}), since ${iso(c.since)}.`).slice(0, 3).map((l) => clean(l, max * 2))
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* The text of an open or closed item, and whether it is open. `title` is
|
|
98
|
+
* the headline the item was first rendered under, kept for the closed text.
|
|
99
|
+
*/
|
|
100
|
+
export function renderItem(state, item, { max, title = null, unconfirmed = false } = {}) {
|
|
101
|
+
if (!item.open) {
|
|
102
|
+
const how = item.closedAs ? ` (${clean(item.closedAs.replace(':', ' '), 64)})` : ''
|
|
103
|
+
return { text: `Closed${how}: ${clean(title ?? headline(item, max), max * 2)}`, status: 'closed' }
|
|
104
|
+
}
|
|
105
|
+
const lines = [`${clean(headline(item, max), max * 2)}.`]
|
|
106
|
+
if (item.origin === 'owner') lines.push(...ownerLines(state, item, max), ...conditionLines(item, max))
|
|
107
|
+
else if (item.origin === 'attention' || item.origin === 'gone') {
|
|
108
|
+
const rep = reportOf(state, item.reportId)
|
|
109
|
+
lines.push(field('Last report', rep ? iso(rep.last_report_at) : null, max), field('State', rep?.state, max), field('Trigger', item.condition?.trigger, max))
|
|
110
|
+
} else if (item.origin === 'seed') {
|
|
111
|
+
lines.push(field('Written', item.seed ? iso(item.seed.written_at) : null, max))
|
|
112
|
+
}
|
|
113
|
+
if (item.state === 'acknowledged') lines.push('Marked done; it closes when the next check agrees.')
|
|
114
|
+
if (item.state === 'deferred') lines.push(`Deferred until ${iso(item.deferUntil)}.`)
|
|
115
|
+
if (item.state === 'exhausted') lines.push('No more reminders will be sent.')
|
|
116
|
+
if (unconfirmed) lines.push('Delivery of an earlier message was not confirmed.')
|
|
117
|
+
return { text: lines.filter(Boolean).join('\n'), status: 'open' }
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** The line a further delivery of an item starts with. */
|
|
121
|
+
export function stepLine(step, n) {
|
|
122
|
+
if (step === 'reminded') return `Reminder ${n}.`
|
|
123
|
+
if (step === 'returned') return 'Marked done earlier, but the latest status still shows it open.'
|
|
124
|
+
return null
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** The digest: one line per open item, in a stable order, cut to `maxItems`. */
|
|
128
|
+
export function renderDigest(state, now, { max, maxItems }) {
|
|
129
|
+
const open = [...state.items.values()].filter((it) => it.open).sort((a, b) => (a.orderTime ?? 0) - (b.orderTime ?? 0) || (a.itemId < b.itemId ? -1 : 1))
|
|
130
|
+
if (open.length === 0) return { text: 'No open items.', count: 0 }
|
|
131
|
+
const lines = [`Open items: ${open.length}.`]
|
|
132
|
+
for (const it of open.slice(0, maxItems)) lines.push(`- ${effectiveState(it, now)}: ${clean(headline(it, max), max * 2)}`)
|
|
133
|
+
if (open.length > maxItems) lines.push(`and ${open.length - maxItems} more.`)
|
|
134
|
+
return { text: lines.join('\n'), count: open.length }
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export const ECHO = Object.freeze({
|
|
138
|
+
done: (title) => `Noted: marked done, ${title}. It closes when the next check agrees.`,
|
|
139
|
+
dismiss: (title) => `Noted: dismissed, ${title}.`,
|
|
140
|
+
defer: (title, until) => `Noted: deferred until ${iso(until)}, ${title}.`,
|
|
141
|
+
capped: (title) => `Further lines about this item were not applied (too many): ${title}.`,
|
|
142
|
+
refused: (title, reason) => `Not applied (${reason}): ${title}.`,
|
|
143
|
+
})
|
|
144
|
+
|
|
145
|
+
export const ALERT = (title) => `Marked done, but the latest status still shows it open: ${title}. The item stays open.`
|
|
146
|
+
|
|
147
|
+
export const REFUSAL_TEXT = Object.freeze({
|
|
148
|
+
too_long: 'longer than the longest deferral allowed',
|
|
149
|
+
too_many: 'more deferrals than allowed for this item',
|
|
150
|
+
until_not_in_future: 'the time is not in the future',
|
|
151
|
+
not_active: 'the item is not the one waiting for an answer',
|
|
152
|
+
not_dismissable: 'this kind of item cannot be dismissed',
|
|
153
|
+
})
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The driver half of the freshness model: a model context, the `run` loop
|
|
3
|
+
* that executes a planner against it, the configuration record and the list
|
|
4
|
+
* of sessions a tick tracks.
|
|
5
|
+
*
|
|
6
|
+
* A model context is `{ ledger, state, policy }`: the ledger is the durable
|
|
7
|
+
* part, `state` is derived from it (derive.js) and is discarded on a restart,
|
|
8
|
+
* and `policy` is the rule set (policy.js). Planners are generators that
|
|
9
|
+
* yield operations; `run()` executes them against the context. Every
|
|
10
|
+
* outward effect is an operation the driver hands to the caller's `deliver`
|
|
11
|
+
* function; the code here performs none.
|
|
12
|
+
*
|
|
13
|
+
* This is the one implementation. The model tests (tests/freshness) and the
|
|
14
|
+
* file-backed reconciler (core.js) both import it.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { canonical, H } from './hash.js'
|
|
18
|
+
import { deriveState, foldRecord, sessionsOf } from './derive.js'
|
|
19
|
+
import { put } from './checks.js'
|
|
20
|
+
import { append, createLedger, loadLedger } from './ledger.js'
|
|
21
|
+
import { DEFAULT_POLICY } from './policy.js'
|
|
22
|
+
import { configKey, sessionKey } from './keys.js'
|
|
23
|
+
|
|
24
|
+
/** A fresh model context. */
|
|
25
|
+
export function createModel({ ledgerId, policy = DEFAULT_POLICY }) {
|
|
26
|
+
const ledger = createLedger({ ledgerId })
|
|
27
|
+
return { ledger, state: deriveState([], policy), policy }
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Rebuild a context from ledger records alone, as after a crash: the
|
|
32
|
+
* ledger's index and every derived value are recomputed; nothing survives
|
|
33
|
+
* from the previous process.
|
|
34
|
+
*/
|
|
35
|
+
export function restoreModel({ ledgerId, records, policy = DEFAULT_POLICY }) {
|
|
36
|
+
const ledger = loadLedger({ ledgerId, records: records.slice() })
|
|
37
|
+
return { ledger, state: deriveState(ledger.records, policy), policy }
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Execute a planner against a context. `deliver(effect)` performs a send
|
|
42
|
+
* and returns 'delivered' or 'failed'. Returns { sends, value }.
|
|
43
|
+
*
|
|
44
|
+
* `appendRecord(draft, at)` is the one place a record is written. It
|
|
45
|
+
* defaults to the in-memory ledger; the file-backed reconciler passes one
|
|
46
|
+
* that also makes the record durable.
|
|
47
|
+
*/
|
|
48
|
+
export function run(ctx, gen, { deliver = () => 'delivered', appendRecord = (draft, at) => append(ctx.ledger, draft, at) } = {}) {
|
|
49
|
+
const sends = []
|
|
50
|
+
let res = gen.next()
|
|
51
|
+
while (!res.done) {
|
|
52
|
+
const op = res.value
|
|
53
|
+
let reply
|
|
54
|
+
if (op.op === 'append') {
|
|
55
|
+
reply = appendRecord(op.record, op.at)
|
|
56
|
+
if (reply.record) foldRecord(ctx.state, reply.record)
|
|
57
|
+
} else if (op.op === 'send') {
|
|
58
|
+
sends.push(op.effect)
|
|
59
|
+
reply = deliver(op.effect)
|
|
60
|
+
} else {
|
|
61
|
+
throw new Error(`run: unknown op ${op.op}`)
|
|
62
|
+
}
|
|
63
|
+
res = gen.next(reply)
|
|
64
|
+
}
|
|
65
|
+
return { sends, value: res.value }
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Plan a configuration record. The full values are stored (the DESIGN-GAP note below). */
|
|
69
|
+
export function* planConfig(ctx, { config, now }) {
|
|
70
|
+
const st = ctx.state
|
|
71
|
+
const configHash = H(config)
|
|
72
|
+
const previous = st.lastConfigId
|
|
73
|
+
const id = configKey(previous, configHash)
|
|
74
|
+
if (st.index.has(id)) return { configRef: st.configRef }
|
|
75
|
+
const configRef = 'cfg_' + configHash.slice(0, 12)
|
|
76
|
+
const prevValues = st.config
|
|
77
|
+
const changed = prevValues ? Object.keys(config).filter((k) => canonical(config[k]) !== canonical(prevValues[k])) : Object.keys(config)
|
|
78
|
+
yield put(
|
|
79
|
+
{
|
|
80
|
+
kind: 'config',
|
|
81
|
+
id,
|
|
82
|
+
body: {
|
|
83
|
+
config_ref: configRef,
|
|
84
|
+
previous_config_ref: st.configRef,
|
|
85
|
+
config_hash: configHash,
|
|
86
|
+
changed_fields: changed,
|
|
87
|
+
// DESIGN-GAP: the `config` body carries only a hash and the names of
|
|
88
|
+
// the changed fields, so the thresholds a check was graded under are
|
|
89
|
+
// not derivable from the ledger alone. The model stores the values.
|
|
90
|
+
values: config,
|
|
91
|
+
},
|
|
92
|
+
},
|
|
93
|
+
now,
|
|
94
|
+
)
|
|
95
|
+
return { configRef }
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* The sessions a tick of `source` reads: every session the ledger already
|
|
100
|
+
* tracks plus every session the source lists now, in key order. A tracked
|
|
101
|
+
* session the source no longer lists is `listed: false`; when the source
|
|
102
|
+
* cannot be listed at all (`list` returned null) `listed` is null and the
|
|
103
|
+
* session is read anyway, so the read reports the failure.
|
|
104
|
+
*/
|
|
105
|
+
export function trackedSessions(ctx, source, world) {
|
|
106
|
+
const listed = world.list(source)
|
|
107
|
+
const out = new Map()
|
|
108
|
+
for (const s of sessionsOf(ctx.state, source)) out.set(s.sk, { session: s.session, scope: s.scope, listed: listed == null ? null : false })
|
|
109
|
+
if (listed) {
|
|
110
|
+
for (const e of listed) out.set(sessionKey(e.session), { session: e.session, scope: e.scope ?? null, listed: true })
|
|
111
|
+
}
|
|
112
|
+
return [...out.entries()].sort((a, b) => (a[0] < b[0] ? -1 : 1)).map(([, v]) => v)
|
|
113
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Adapter over the Claude Code command-line tool's local registry of live
|
|
3
|
+
* sessions: a directory holding one JSON file per live process, named for the
|
|
4
|
+
* process id (`<pid>.json`). It is activity evidence only.
|
|
5
|
+
*
|
|
6
|
+
* A registry row says a session is live and whether it is busy. It is not a
|
|
7
|
+
* status report: this adapter never returns a report, so a session it reads is
|
|
8
|
+
* graded `unknown` (no status line) and can never be `fresh`, whatever the
|
|
9
|
+
* row's time. What it does return is native activity: whether a turn is in
|
|
10
|
+
* flight, and a `registry_busy` or `registry_idle` event timed at the row's
|
|
11
|
+
* `statusUpdatedAt`, with the host application in the event's `ref`.
|
|
12
|
+
*
|
|
13
|
+
* The registry is not a documented interface, so every read is shape-checked
|
|
14
|
+
* and a shape it does not know is `error`, never `idle` and never `no_report`:
|
|
15
|
+
*
|
|
16
|
+
* - only files named `<digits>.json` are read; every other file in the
|
|
17
|
+
* directory is ignored without being opened;
|
|
18
|
+
* - such a file must be a regular file of bounded size holding a JSON object
|
|
19
|
+
* with a `sessionId` (a short token), a `cwd` string, a `status` of `busy`
|
|
20
|
+
* or `idle`, a `statusUpdatedAt` in epoch milliseconds and an `entrypoint`
|
|
21
|
+
* string. Any other value in those fields, an unreadable file or a
|
|
22
|
+
* duplicate `sessionId` makes the whole registry unreadable for that tick;
|
|
23
|
+
* - extra keys are expected (the format is not ours) and ignored.
|
|
24
|
+
*
|
|
25
|
+
* Only `sessionId`, the last path segment of `cwd` (the project), `status`,
|
|
26
|
+
* `statusUpdatedAt` and `entrypoint` are carried out of a row. The session
|
|
27
|
+
* title (`name`) and every other field are never read into a value this module
|
|
28
|
+
* returns, so they cannot reach the ledger. An `entrypoint` that is not a short
|
|
29
|
+
* lowercase token is recorded as `other`; the raw string is not kept.
|
|
30
|
+
*
|
|
31
|
+
* The directory is only read, never written. `list()` takes one snapshot and
|
|
32
|
+
* the `read()` calls that follow answer from it. A directory with no
|
|
33
|
+
* row files is a registry with no live sessions, unless it holds a regular `*.json`
|
|
34
|
+
* file under another name, which is a changed format and reads as `error`.
|
|
35
|
+
*
|
|
36
|
+
* Time: `statusUpdatedAt` is the time the row's status last changed
|
|
37
|
+
* (`report_time_basis` is `none`: there is no report). A row dated further in
|
|
38
|
+
* the future than `MAX_FUTURE_MS` is `error: clock_skew`.
|
|
39
|
+
*/
|
|
40
|
+
|
|
41
|
+
import fs from 'node:fs'
|
|
42
|
+
import path from 'node:path'
|
|
43
|
+
import { validSourceName } from './adapter.js'
|
|
44
|
+
|
|
45
|
+
/** The source name the reconciler's configuration must give capabilities for. */
|
|
46
|
+
export const REGISTRY_SOURCE = 'claude-session-registry'
|
|
47
|
+
|
|
48
|
+
/** The capabilities `coreConfig` registers for the registry source: native activity and scope, no report. */
|
|
49
|
+
export const REGISTRY_CAPS = Object.freeze({ native_in_read: true, activity_read: false, scope: true, can_confirm_gone: true, report_time_basis: 'none' })
|
|
50
|
+
|
|
51
|
+
export const REGISTRY_BASES = Object.freeze({ busy: 'registry_busy', idle: 'registry_idle' })
|
|
52
|
+
|
|
53
|
+
const DEFAULT_MAX_FILES = 2000
|
|
54
|
+
const DEFAULT_MAX_FILE_BYTES = 64 * 1024
|
|
55
|
+
const MAX_FUTURE_MS = 5 * 60 * 1000
|
|
56
|
+
// Epoch milliseconds are far above this; epoch seconds are far below it.
|
|
57
|
+
const MIN_EPOCH_MS = 1e11
|
|
58
|
+
const SESSION_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/
|
|
59
|
+
const ROW_FILE_RE = /^[0-9]{1,10}\.json$/
|
|
60
|
+
|
|
61
|
+
function isPlain(v) {
|
|
62
|
+
return v !== null && typeof v === 'object' && !Array.isArray(v)
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The project a working directory maps to: its last path segment, made safe to store. */
|
|
66
|
+
function projectOf(cwd) {
|
|
67
|
+
const seg = cwd.split(/[\\/]/).filter(Boolean).pop() ?? ''
|
|
68
|
+
const safe = seg.replace(/[^A-Za-z0-9._@+ -]/g, '_').slice(0, 64)
|
|
69
|
+
return safe === '' ? 'root' : safe
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** The host application an entrypoint names, or `other`. */
|
|
73
|
+
function appOf(entrypoint) {
|
|
74
|
+
const t = entrypoint.toLowerCase()
|
|
75
|
+
return validSourceName(t) ? t : 'other'
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** One row, validated and cut down to the fields this module uses, or null when the shape is not known. */
|
|
79
|
+
function parseRow(doc) {
|
|
80
|
+
if (!isPlain(doc)) return null
|
|
81
|
+
const { sessionId, cwd, status, statusUpdatedAt, entrypoint } = doc
|
|
82
|
+
if (typeof sessionId !== 'string' || !SESSION_ID_RE.test(sessionId)) return null
|
|
83
|
+
if (typeof cwd !== 'string' || cwd === '' || cwd.length > 4096) return null
|
|
84
|
+
if (status !== 'busy' && status !== 'idle') return null
|
|
85
|
+
if (!Number.isSafeInteger(statusUpdatedAt) || statusUpdatedAt < MIN_EPOCH_MS) return null
|
|
86
|
+
if (typeof entrypoint !== 'string' || entrypoint === '' || entrypoint.length > 200) return null
|
|
87
|
+
return { id: sessionId, project: projectOf(cwd), busy: status === 'busy', since: statusUpdatedAt, app: appOf(entrypoint) }
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Take one snapshot of the registry directory: `{ rows }` (a Map from session
|
|
92
|
+
* id to `{ id, project, busy, since, app }`) or `{ error }` with a code.
|
|
93
|
+
*/
|
|
94
|
+
export function loadRegistry(dir, { maxFiles = DEFAULT_MAX_FILES, maxFileBytes = DEFAULT_MAX_FILE_BYTES } = {}) {
|
|
95
|
+
let entries
|
|
96
|
+
try {
|
|
97
|
+
entries = fs.readdirSync(dir, { withFileTypes: true })
|
|
98
|
+
} catch (err) {
|
|
99
|
+
if (err?.code === 'ENOTDIR') return { error: 'shape_changed' }
|
|
100
|
+
return { error: err?.code === 'ENOENT' ? 'source_missing' : 'unreachable' }
|
|
101
|
+
}
|
|
102
|
+
const candidates = entries.filter((e) => ROW_FILE_RE.test(e.name))
|
|
103
|
+
if (candidates.length > maxFiles) return { error: 'too_large' }
|
|
104
|
+
// Rows under a name this module does not know are a changed format, not an empty registry.
|
|
105
|
+
if (candidates.length === 0 && entries.some((e) => e.isFile() && e.name.endsWith('.json'))) return { error: 'shape_changed' }
|
|
106
|
+
const rows = new Map()
|
|
107
|
+
for (const e of candidates.sort((a, b) => (a.name < b.name ? -1 : 1))) {
|
|
108
|
+
if (!e.isFile()) return { error: 'shape_changed' }
|
|
109
|
+
let text
|
|
110
|
+
try {
|
|
111
|
+
const file = path.join(dir, e.name)
|
|
112
|
+
if (fs.statSync(file).size > maxFileBytes) return { error: 'too_large' }
|
|
113
|
+
text = fs.readFileSync(file, 'utf8')
|
|
114
|
+
} catch (err) {
|
|
115
|
+
// The process ended between the listing and the read: the row is gone.
|
|
116
|
+
if (err?.code === 'ENOENT') continue
|
|
117
|
+
return { error: 'unreachable' }
|
|
118
|
+
}
|
|
119
|
+
let doc
|
|
120
|
+
try {
|
|
121
|
+
doc = JSON.parse(text)
|
|
122
|
+
} catch {
|
|
123
|
+
return { error: 'parse_failed' }
|
|
124
|
+
}
|
|
125
|
+
const row = parseRow(doc)
|
|
126
|
+
if (row === null || rows.has(row.id)) return { error: 'shape_changed' }
|
|
127
|
+
rows.set(row.id, row)
|
|
128
|
+
}
|
|
129
|
+
return { rows }
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* @param {object} opts
|
|
134
|
+
* @param {string} opts.dir the registry directory
|
|
135
|
+
* @param {string} [opts.source] source name (default `claude-session-registry`)
|
|
136
|
+
* @param {number} [opts.maxFiles] refuse a registry with more rows than this
|
|
137
|
+
* @param {number} [opts.maxFileBytes] refuse a larger row file
|
|
138
|
+
*/
|
|
139
|
+
export function createSessionRegistryAdapter({ dir, source = REGISTRY_SOURCE, maxFiles, maxFileBytes }) {
|
|
140
|
+
if (typeof dir !== 'string' || dir === '') throw new TypeError('createSessionRegistryAdapter: dir is required')
|
|
141
|
+
if (!validSourceName(source)) throw new TypeError('createSessionRegistryAdapter: source must be a short lowercase name')
|
|
142
|
+
const limits = { maxFiles, maxFileBytes }
|
|
143
|
+
let snapshot = null
|
|
144
|
+
return {
|
|
145
|
+
source,
|
|
146
|
+
list() {
|
|
147
|
+
snapshot = loadRegistry(dir, limits)
|
|
148
|
+
if (snapshot.error) return null
|
|
149
|
+
return [...snapshot.rows.values()].map((r) => ({ session: { source, native_id: r.id, incarnation: null }, scope: r.project }))
|
|
150
|
+
},
|
|
151
|
+
read(session, now) {
|
|
152
|
+
if (!snapshot) snapshot = loadRegistry(dir, limits)
|
|
153
|
+
if (snapshot.error) return { outcome: 'error', error_code: snapshot.error }
|
|
154
|
+
const row = snapshot.rows.get(session.native_id)
|
|
155
|
+
if (!row) return { listed: false }
|
|
156
|
+
if (Number.isFinite(now) && row.since - now > MAX_FUTURE_MS) return { outcome: 'error', error_code: 'clock_skew' }
|
|
157
|
+
const basis = row.busy ? REGISTRY_BASES.busy : REGISTRY_BASES.idle
|
|
158
|
+
return { outcome: 'no_report', native: { turn_in_flight: row.busy, events: [{ basis, ref: row.app, activity_at: row.since }] } }
|
|
159
|
+
},
|
|
160
|
+
}
|
|
161
|
+
}
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Adapter over the daemon's persisted session-state file
|
|
3
|
+
* (`~/.chroxy/session-state.json`, written by `SessionStatePersistence`).
|
|
4
|
+
*
|
|
5
|
+
* It reads declared-status fields and nothing else. Of each persisted session
|
|
6
|
+
* it takes the `id` and the `declaredStatus` object, and of that object the
|
|
7
|
+
* `state`, `next`, `blockedOn`, `decision`, `updatedAt` and `source` fields.
|
|
8
|
+
* Everything else the file holds (names, working directories, history,
|
|
9
|
+
* usage, `summary` text) is never read into a value this module returns, so
|
|
10
|
+
* it cannot reach the ledger.
|
|
11
|
+
*
|
|
12
|
+
* The file is opened read-only and never written. Every read is shape-checked:
|
|
13
|
+
*
|
|
14
|
+
* - the file must be a JSON object with `version: 1` and a `sessions` array
|
|
15
|
+
* whose entries are objects with a unique non-empty string `id`;
|
|
16
|
+
* - a session's `declaredStatus`, when present, must satisfy the daemon's
|
|
17
|
+
* own strict `DeclaredStatusSchema` (an unknown key is a changed shape);
|
|
18
|
+
* - an entry with no `declaredStatus` must still look like one the daemon
|
|
19
|
+
* wrote (it always writes `sdkSessionId` and `conversationId`) and must
|
|
20
|
+
* not carry a declaration-shaped object under another key. An entry that
|
|
21
|
+
* fails either is a changed shape, so a renamed or restructured field
|
|
22
|
+
* reads as an error. What cannot be told apart is a declaration dropped
|
|
23
|
+
* from an otherwise intact entry: that is a session that never declared.
|
|
24
|
+
*
|
|
25
|
+
* A file that fails the first check cannot be listed (`list()` is null, and
|
|
26
|
+
* every tracked session's read is `error: shape_changed`). A session whose
|
|
27
|
+
* declaration fails the second reads as `error: shape_changed`. A changed
|
|
28
|
+
* shape is therefore always an error, never `idle`, never `no_report`.
|
|
29
|
+
*
|
|
30
|
+
* `list()` takes one snapshot of the file; the `read()` calls that follow
|
|
31
|
+
* answer from it, so one tick sees one consistent file.
|
|
32
|
+
*
|
|
33
|
+
* Time: the daemon stamps `updatedAt` when the declaration changes, so the
|
|
34
|
+
* report time is a changed-at time (README: `report_time_basis: changed_at`).
|
|
35
|
+
* A decision carried by such a declaration may be inherited from an earlier
|
|
36
|
+
* one, so it is recorded `possibly_inherited`, never `stated`.
|
|
37
|
+
*/
|
|
38
|
+
|
|
39
|
+
import fs from 'node:fs'
|
|
40
|
+
import { DeclaredStatusSchema } from '@chroxy/protocol'
|
|
41
|
+
import { extractDeclaredStatus } from '../declared-status.js'
|
|
42
|
+
|
|
43
|
+
/** The source name the reconciler's configuration must give capabilities for. */
|
|
44
|
+
export const STATE_FILE_SOURCE = 'chroxy-state-file'
|
|
45
|
+
|
|
46
|
+
/** The capabilities `coreConfig` registers for the state-file source. */
|
|
47
|
+
export const STATE_FILE_CAPS = Object.freeze({ native_in_read: false, activity_read: false, scope: false, can_confirm_gone: true, report_time_basis: 'changed_at' })
|
|
48
|
+
|
|
49
|
+
const DEFAULT_MAX_BYTES = 64 * 1024 * 1024
|
|
50
|
+
const DECLARED_VIA = { marker: 'marker', api: 'api', hook: 'hook' }
|
|
51
|
+
|
|
52
|
+
function isPlain(v) {
|
|
53
|
+
return v !== null && typeof v === 'object' && !Array.isArray(v)
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** The name after `OWNER:` in a next-step line, or null. */
|
|
57
|
+
function ownerOf(next) {
|
|
58
|
+
if (typeof next !== 'string') return null
|
|
59
|
+
const m = /\bOWNER:\s*(\S.*)$/i.exec(next)
|
|
60
|
+
return m ? m[1].trim() : null
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Map one validated declared status (the daemon's own object) to a report.
|
|
65
|
+
* The same mapping serves a declaration parsed from message text with
|
|
66
|
+
* `extractDeclaredStatus`, which yields the same fields.
|
|
67
|
+
*/
|
|
68
|
+
export function reportFromDeclared(declared, { updatedAt, via }) {
|
|
69
|
+
const relayed = via === 'api' || via === 'hook'
|
|
70
|
+
const decision = typeof declared.decision === 'string' && declared.decision !== '' ? declared.decision : null
|
|
71
|
+
return {
|
|
72
|
+
state: declared.state,
|
|
73
|
+
last_report_at: updatedAt,
|
|
74
|
+
declared_via: via,
|
|
75
|
+
next: declared.next ?? null,
|
|
76
|
+
declared_blocked_on: declared.blockedOn ?? null,
|
|
77
|
+
decision: relayed ? null : decision,
|
|
78
|
+
decision_basis: relayed || decision == null ? 'none' : via === 'transcript' ? 'stated' : 'possibly_inherited',
|
|
79
|
+
owner_named: relayed ? null : ownerOf(declared.next),
|
|
80
|
+
seed_ref: null,
|
|
81
|
+
time_trusted: true,
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Parse a status block from one completed message with the daemon's parser
|
|
87
|
+
* (`extractDeclaredStatus`) and map it to a report timed `updatedAt`, or null
|
|
88
|
+
* when the text carries no valid declaration. Used by sources that hold message
|
|
89
|
+
* text rather than the daemon's parsed object.
|
|
90
|
+
*/
|
|
91
|
+
export function reportFromText(text, { updatedAt }) {
|
|
92
|
+
const declared = extractDeclaredStatus(text)
|
|
93
|
+
return declared ? reportFromDeclared(declared, { updatedAt, via: 'transcript' }) : null
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const DECLARATION_STATES = new Set(['running', 'idle', 'blocked', 'stalled', 'done', 'unknown'])
|
|
97
|
+
const SHAPE_CHANGED = Symbol('shape_changed')
|
|
98
|
+
|
|
99
|
+
/** Does this entry carry an object shaped like a declaration under a key other than `declaredStatus`? */
|
|
100
|
+
function hasMisplacedDeclaration(entry) {
|
|
101
|
+
return Object.entries(entry).some(([k, v]) => k !== 'declaredStatus' && isPlain(v) && DECLARATION_STATES.has(v.state) && typeof v.summary === 'string' && typeof v.updatedAt === 'number')
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** What the daemon's entry for a session with no declaration looks like. */
|
|
105
|
+
function looksLikeDaemonEntry(entry) {
|
|
106
|
+
return 'sdkSessionId' in entry && 'conversationId' in entry
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function loadSnapshot(path, maxBytes) {
|
|
110
|
+
let text
|
|
111
|
+
try {
|
|
112
|
+
const st = fs.statSync(path)
|
|
113
|
+
if (!st.isFile()) return { error: 'shape_changed' }
|
|
114
|
+
if (st.size > maxBytes) return { error: 'too_large' }
|
|
115
|
+
text = fs.readFileSync(path, 'utf8')
|
|
116
|
+
} catch (err) {
|
|
117
|
+
return { error: err?.code === 'ENOENT' ? 'source_missing' : 'unreachable' }
|
|
118
|
+
}
|
|
119
|
+
let doc
|
|
120
|
+
try {
|
|
121
|
+
doc = JSON.parse(text)
|
|
122
|
+
} catch {
|
|
123
|
+
return { error: 'parse_failed' }
|
|
124
|
+
}
|
|
125
|
+
if (!isPlain(doc) || doc.version !== 1 || !Array.isArray(doc.sessions)) return { error: 'shape_changed' }
|
|
126
|
+
const byId = new Map()
|
|
127
|
+
for (const entry of doc.sessions) {
|
|
128
|
+
if (!isPlain(entry) || typeof entry.id !== 'string' || entry.id === '' || entry.id.length > 256 || byId.has(entry.id)) {
|
|
129
|
+
return { error: 'shape_changed' }
|
|
130
|
+
}
|
|
131
|
+
// Only the declaration is carried forward; the rest of the entry is dropped here.
|
|
132
|
+
if (entry.declaredStatus !== undefined) byId.set(entry.id, entry.declaredStatus)
|
|
133
|
+
else byId.set(entry.id, looksLikeDaemonEntry(entry) && !hasMisplacedDeclaration(entry) ? undefined : SHAPE_CHANGED)
|
|
134
|
+
}
|
|
135
|
+
return { byId }
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* @param {object} opts
|
|
140
|
+
* @param {string} opts.path path of the daemon's session-state file
|
|
141
|
+
* @param {string} [opts.source] source name (default `chroxy-state-file`)
|
|
142
|
+
* @param {number} [opts.maxBytes] refuse a larger file
|
|
143
|
+
*/
|
|
144
|
+
export function createStateFileAdapter({ path, source = STATE_FILE_SOURCE, maxBytes = DEFAULT_MAX_BYTES }) {
|
|
145
|
+
if (typeof path !== 'string' || path === '') throw new TypeError('createStateFileAdapter: path is required')
|
|
146
|
+
let snapshot = null
|
|
147
|
+
return {
|
|
148
|
+
source,
|
|
149
|
+
list() {
|
|
150
|
+
snapshot = loadSnapshot(path, maxBytes)
|
|
151
|
+
if (snapshot.error) return null
|
|
152
|
+
return [...snapshot.byId.keys()].map((id) => ({ session: { source, native_id: id, incarnation: null }, scope: null }))
|
|
153
|
+
},
|
|
154
|
+
read(session) {
|
|
155
|
+
if (!snapshot) snapshot = loadSnapshot(path, maxBytes)
|
|
156
|
+
if (snapshot.error) return { outcome: 'error', error_code: snapshot.error }
|
|
157
|
+
if (!snapshot.byId.has(session.native_id)) return { listed: false }
|
|
158
|
+
const raw = snapshot.byId.get(session.native_id)
|
|
159
|
+
if (raw === SHAPE_CHANGED) return { outcome: 'error', error_code: 'shape_changed' }
|
|
160
|
+
if (raw === undefined) return { outcome: 'no_report' }
|
|
161
|
+
const parsed = DeclaredStatusSchema.safeParse(raw)
|
|
162
|
+
if (!parsed.success) return { outcome: 'error', error_code: 'shape_changed' }
|
|
163
|
+
const d = parsed.data
|
|
164
|
+
return { outcome: 'ok', report: reportFromDeclared(d, { updatedAt: d.updatedAt, via: DECLARED_VIA[d.source] }) }
|
|
165
|
+
},
|
|
166
|
+
}
|
|
167
|
+
}
|