@sshirkit/dsh-orchestrator 1.0.1 → 1.0.3
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 +65 -30
- package/README.zh.md +62 -29
- package/lib/client.js +809 -311
- package/lib/delegate-status.js +42 -67
- package/lib/delegate.js +98 -140
- package/lib/gate.js +11 -5
- package/lib/index.js +533 -442
- package/lib/orchestrate.js +143 -129
- package/lib/read-index.js +186 -0
- package/lib/reconcile.js +2 -3
- package/lib/rules.js +22 -10
- package/lib/session-tools.js +516 -0
- package/lib/state-store.js +14 -9
- package/lib/supervise.js +69 -85
- package/lib/switch-notice.js +2 -2
- package/lib/timeline.js +23 -181
- package/lib/tool-surface.js +57 -9
- package/lib/worker.js +18 -7
- package/lib/worktree-manage.js +3 -10
- package/lib/worktree.js +3 -12
- package/lib/write-lease.js +57 -12
- package/package.json +1 -1
- package/lib/git-audit.js +0 -383
- package/lib/write-audit.js +0 -333
|
@@ -0,0 +1,516 @@
|
|
|
1
|
+
import { randomInt } from 'node:crypto'
|
|
2
|
+
import { isDelegatedChild, resolveEffectiveAllowedTools } from './gate.js'
|
|
3
|
+
import { encodeRecordKey } from './state-store.js'
|
|
4
|
+
|
|
5
|
+
export const SESSION_TOOLS_DOMAIN = 'dsh_orchestrator_session_tools'
|
|
6
|
+
export const SESSION_TOOLS_TABLE = 'session_allowed_tools'
|
|
7
|
+
export const SESSION_TOOLS_PACKAGE = '@sshirkit/dsh-orchestrator'
|
|
8
|
+
export const SESSION_TOOLS_NAMESPACE = 'orchestratorSession'
|
|
9
|
+
|
|
10
|
+
const LEGACY_RECORD_FIELDS = ['sessionId', 'allowedTools', 'revision', 'updatedAt']
|
|
11
|
+
const RECORD_FIELDS = ['sessionId', 'config', 'revision', 'updatedAt']
|
|
12
|
+
const STATE_FIELDS = ['sessionId', 'enabled', 'allowedTools', 'config', 'revision', 'storageReady']
|
|
13
|
+
const CONFIG_DEFAULTS = Object.freeze({
|
|
14
|
+
enabled: true,
|
|
15
|
+
worktreeIsolationEnabled: true,
|
|
16
|
+
readOnlyEnabled: false,
|
|
17
|
+
peerReadOnlyConsultEnabled: false,
|
|
18
|
+
mainRoute: null,
|
|
19
|
+
workerRoute: null,
|
|
20
|
+
superviseIntervalSeconds: 600,
|
|
21
|
+
superviseMaxNoticesPerChild: 3,
|
|
22
|
+
superviseUnlimited: false,
|
|
23
|
+
allowedTools: Object.freeze([]),
|
|
24
|
+
})
|
|
25
|
+
const CONFIG_FIELDS = Object.keys(CONFIG_DEFAULTS)
|
|
26
|
+
const ownersKey = Symbol.for('@sshirkit/dsh-orchestrator/session-tools-domain-owners')
|
|
27
|
+
const owners = globalThis[ownersKey] ??= new WeakMap()
|
|
28
|
+
const cordisOriginal = Symbol.for('cordis.original')
|
|
29
|
+
|
|
30
|
+
function reserveDomain(facility) {
|
|
31
|
+
const key = facility[cordisOriginal] ?? facility
|
|
32
|
+
const previous = owners.get(key)
|
|
33
|
+
let release
|
|
34
|
+
const hold = new Promise((resolve) => { release = resolve })
|
|
35
|
+
const tail = Promise.resolve(previous).then(() => hold)
|
|
36
|
+
owners.set(key, tail)
|
|
37
|
+
void tail.then(() => {
|
|
38
|
+
if (owners.get(key) === tail) owners.delete(key)
|
|
39
|
+
})
|
|
40
|
+
return { previous, release }
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function nonempty(value, field) {
|
|
44
|
+
if (typeof value !== 'string' || value.trim() === '') {
|
|
45
|
+
throw new TypeError(`${field} must be a non-empty string`)
|
|
46
|
+
}
|
|
47
|
+
return value
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const parseSessionId = (value) => nonempty(value, 'sessionId')
|
|
51
|
+
|
|
52
|
+
function parseNames(value) {
|
|
53
|
+
if (!Array.isArray(value)) throw new TypeError('allowedTools must be an array')
|
|
54
|
+
const names = new Set()
|
|
55
|
+
for (const name of value) names.add(nonempty(name, 'tool name'))
|
|
56
|
+
return [...names]
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function parseRevision(value) {
|
|
60
|
+
if (!Number.isSafeInteger(value) || value < 0) {
|
|
61
|
+
throw new TypeError('revision must be a non-negative safe integer')
|
|
62
|
+
}
|
|
63
|
+
return value
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function fields(value, names) {
|
|
67
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value) ||
|
|
68
|
+
Object.keys(value).length !== names.length || !names.every((key) => Object.hasOwn(value, key))) {
|
|
69
|
+
throw new TypeError(`expected record with fields ${names.join(', ')}`)
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function objectRecord(value) {
|
|
74
|
+
const prototype = value !== null && typeof value === 'object' ? Object.getPrototypeOf(value) : undefined
|
|
75
|
+
return prototype === Object.prototype || prototype === null
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function parseSessionRoute(value, field) {
|
|
79
|
+
if (value === null) return null
|
|
80
|
+
if (!objectRecord(value) || !Object.hasOwn(value, 'provider') || !Object.hasOwn(value, 'model') ||
|
|
81
|
+
Object.keys(value).some((key) => !['provider', 'model', 'reasoningEffort'].includes(key))) {
|
|
82
|
+
throw new TypeError(`${field} must be a route with provider, model and optional reasoningEffort, or null`)
|
|
83
|
+
}
|
|
84
|
+
const provider = nonempty(value.provider, `${field}.provider`).trim()
|
|
85
|
+
const model = nonempty(value.model, `${field}.model`).trim()
|
|
86
|
+
if (Object.hasOwn(value, 'reasoningEffort') && typeof value.reasoningEffort !== 'string') {
|
|
87
|
+
throw new TypeError(`${field}.reasoningEffort must be a string`)
|
|
88
|
+
}
|
|
89
|
+
const reasoningEffort = value.reasoningEffort?.trim()
|
|
90
|
+
return { provider, model, ...(reasoningEffort && { reasoningEffort }) }
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function integer(value, field, min, max) {
|
|
94
|
+
if (!Number.isInteger(value) || value < min || value > max) {
|
|
95
|
+
throw new TypeError(`${field} must be an integer in ${min}..${max}`)
|
|
96
|
+
}
|
|
97
|
+
return value
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function parseSessionConfigPatch(value) {
|
|
101
|
+
if (!objectRecord(value)) throw new TypeError('config must be an object')
|
|
102
|
+
const patch = {}
|
|
103
|
+
for (const [key, item] of Object.entries(value)) {
|
|
104
|
+
if (!Object.hasOwn(CONFIG_DEFAULTS, key)) throw new TypeError(`unknown config field: ${key}`)
|
|
105
|
+
if (typeof CONFIG_DEFAULTS[key] === 'boolean') {
|
|
106
|
+
if (typeof item !== 'boolean') throw new TypeError(`${key} must be a boolean`)
|
|
107
|
+
patch[key] = item
|
|
108
|
+
} else if (key === 'mainRoute' || key === 'workerRoute') {
|
|
109
|
+
patch[key] = parseSessionRoute(item, key)
|
|
110
|
+
} else if (key === 'allowedTools') {
|
|
111
|
+
patch[key] = parseNames(item)
|
|
112
|
+
} else {
|
|
113
|
+
patch[key] = key === 'superviseIntervalSeconds' ? integer(item, key, 10, 86400) : integer(item, key, 0, 20)
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
return patch
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function parseRecord(value) {
|
|
120
|
+
const legacy = value != null && Object.hasOwn(value, 'allowedTools')
|
|
121
|
+
fields(value, legacy ? LEGACY_RECORD_FIELDS : RECORD_FIELDS)
|
|
122
|
+
const config = legacy ? { allowedTools: parseNames(value.allowedTools) } : parseSessionConfigPatch(value.config)
|
|
123
|
+
const storedNames = legacy ? value.allowedTools : value.config.allowedTools
|
|
124
|
+
if (config.allowedTools?.length !== storedNames?.length) throw new TypeError('duplicate stored tool name')
|
|
125
|
+
if (!Number.isSafeInteger(value.updatedAt) || value.updatedAt < 0) throw new TypeError('invalid updatedAt')
|
|
126
|
+
return {
|
|
127
|
+
sessionId: parseSessionId(value.sessionId),
|
|
128
|
+
config,
|
|
129
|
+
revision: parseRevision(value.revision),
|
|
130
|
+
updatedAt: value.updatedAt,
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function parseResult(value) {
|
|
135
|
+
if (value?.ok === false) {
|
|
136
|
+
fields(value, ['ok', 'error'])
|
|
137
|
+
fields(value.error, ['code', 'message'])
|
|
138
|
+
nonempty(value.error.code, 'error code')
|
|
139
|
+
nonempty(value.error.message, 'error message')
|
|
140
|
+
return value
|
|
141
|
+
}
|
|
142
|
+
fields(value, STATE_FIELDS)
|
|
143
|
+
if (typeof value.enabled !== 'boolean' || typeof value.storageReady !== 'boolean') {
|
|
144
|
+
throw new TypeError('enabled and storageReady must be booleans')
|
|
145
|
+
}
|
|
146
|
+
parseSessionId(value.sessionId)
|
|
147
|
+
fields(value.config, CONFIG_FIELDS)
|
|
148
|
+
const config = parseSessionConfigPatch(value.config)
|
|
149
|
+
const allowedTools = parseNames(value.allowedTools)
|
|
150
|
+
if (allowedTools.length !== value.allowedTools.length || allowedTools.length !== value.config.allowedTools.length ||
|
|
151
|
+
!allowedTools.every((name, index) => config.allowedTools[index] === name)) {
|
|
152
|
+
throw new TypeError('allowedTools must match config.allowedTools exactly')
|
|
153
|
+
}
|
|
154
|
+
parseRevision(value.revision)
|
|
155
|
+
return { ...value, allowedTools, config }
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Client mirror lives in the host's non-ESM web bundle. Keep contract parity tested. */
|
|
159
|
+
export function createSessionToolsDescriptors() {
|
|
160
|
+
const codec = (typeSymbol, parse) => ({ mode: 'strict', typeSymbol, create: () => ({ parse }) })
|
|
161
|
+
const parameter = (name, typeSymbol, parse) => ({
|
|
162
|
+
name, wire: name, source: 'json', codec: codec(typeSymbol, parse),
|
|
163
|
+
})
|
|
164
|
+
const session = parameter('sessionId', 'SessionId', parseSessionId)
|
|
165
|
+
const names = parameter('allowedTools', 'OrchestratorToolNames', parseNames)
|
|
166
|
+
const revision = parameter('expectedRevision', 'OrchestratorToolsRevision', parseRevision)
|
|
167
|
+
const config = parameter('config', 'OrchestratorSessionConfigPatch', parseSessionConfigPatch)
|
|
168
|
+
const result = codec('OrchestratorSessionToolsResult', parseResult)
|
|
169
|
+
const methods = { get: [session], set: [session, names, revision], setConfig: [session, config, revision],
|
|
170
|
+
clear: [session, revision] }
|
|
171
|
+
return Object.entries(methods)
|
|
172
|
+
.map(([method, parameters]) => ({
|
|
173
|
+
id: `${SESSION_TOOLS_PACKAGE}/${SESSION_TOOLS_NAMESPACE}/${method}`,
|
|
174
|
+
service: SESSION_TOOLS_NAMESPACE,
|
|
175
|
+
namespace: SESSION_TOOLS_NAMESPACE,
|
|
176
|
+
method,
|
|
177
|
+
invocation: { kind: 'direct' },
|
|
178
|
+
parameters,
|
|
179
|
+
result,
|
|
180
|
+
}))
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const domainSpec = {
|
|
184
|
+
name: SESSION_TOOLS_DOMAIN,
|
|
185
|
+
version: 1,
|
|
186
|
+
layout: 'single',
|
|
187
|
+
tables: { [SESSION_TOOLS_TABLE]: { valueSchema: { parse: parseRecord } } },
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const errorMessage = (error) => typeof error?.message === 'string' ? error.message : String(error)
|
|
191
|
+
const failure = (code, message) => ({ ok: false, error: { code, message } })
|
|
192
|
+
const isMissing = (error) => ['SESSION_QUERY_SESSION_NOT_FOUND', 'not-found', 'session-not-found'].includes(error?.code)
|
|
193
|
+
|
|
194
|
+
function optionalService(ctx, name) {
|
|
195
|
+
try {
|
|
196
|
+
return ctx.get?.(name) ?? ctx[name]
|
|
197
|
+
} catch {
|
|
198
|
+
return undefined
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** A live lookup wins; cold sessions can still be addressed by their durable ID. */
|
|
203
|
+
async function checkSession(ctx, id) {
|
|
204
|
+
const sessions = optionalService(ctx, 'sessions')
|
|
205
|
+
const liveLookup = typeof sessions?.get === 'function' || typeof sessions?.has === 'function'
|
|
206
|
+
if (typeof sessions?.get === 'function' ? await sessions.get(id) : await sessions?.has?.(id)) return true
|
|
207
|
+
const query = optionalService(ctx, 'sessionQuery')
|
|
208
|
+
if (typeof query?.inspectSession === 'function') {
|
|
209
|
+
try {
|
|
210
|
+
return Boolean(await query.inspectSession(id, () => true))
|
|
211
|
+
} catch (error) {
|
|
212
|
+
if (isMissing(error)) return false
|
|
213
|
+
throw error
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
return liveLookup ? false : undefined
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
export function rootSessionIdOf(subject) {
|
|
220
|
+
if (typeof subject === 'string') return subject
|
|
221
|
+
const session = subject?.session
|
|
222
|
+
const header = session?.header
|
|
223
|
+
const id = session?.id ?? subject?.sessionId ?? subject?.id
|
|
224
|
+
return isDelegatedChild(subject) ? header?.rootSessionId ?? header?.parentSession ?? id : id
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
export function createSessionTools({
|
|
228
|
+
facility, ctx = {}, logger, globalConfigFor = () => ({}), globalAllowedFor, onConfigChanged,
|
|
229
|
+
} = {}) {
|
|
230
|
+
const records = new Map()
|
|
231
|
+
const clearedRevisions = new Map()
|
|
232
|
+
// No tombstones on disk: a new incarnation chooses a different token for an absent row,
|
|
233
|
+
// so a stale client cannot reuse the pre-clear token after a restart (ABA).
|
|
234
|
+
const initialRevision = randomInt(1, 2 ** 48 - 1)
|
|
235
|
+
const reservation = typeof facility?.open === 'function' ? reserveDomain(facility) : undefined
|
|
236
|
+
let domain
|
|
237
|
+
let table
|
|
238
|
+
let storageReady = false
|
|
239
|
+
let stopping = false
|
|
240
|
+
let tail = Promise.resolve()
|
|
241
|
+
let closing
|
|
242
|
+
let storageError = 'Session tools storage is unavailable'
|
|
243
|
+
|
|
244
|
+
const warn = (message) => {
|
|
245
|
+
try { logger?.warn?.(`orchestrator: ${message}`) } catch { /* Diagnostics cannot stop teardown. */ }
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
const ready = (async () => {
|
|
249
|
+
if (!reservation) return
|
|
250
|
+
await reservation.previous
|
|
251
|
+
if (stopping) return
|
|
252
|
+
try {
|
|
253
|
+
domain = await facility.open(domainSpec)
|
|
254
|
+
const opened = domain.table(SESSION_TOOLS_TABLE)
|
|
255
|
+
const hydrated = new Map()
|
|
256
|
+
for (const [key, value] of opened.entries()) {
|
|
257
|
+
const row = parseRecord(value)
|
|
258
|
+
if (encodeRecordKey(row.sessionId) !== key) throw new Error('Session tools record key does not match its sessionId')
|
|
259
|
+
hydrated.set(row.sessionId, row)
|
|
260
|
+
}
|
|
261
|
+
if (stopping) return
|
|
262
|
+
for (const [id, row] of hydrated) records.set(id, row)
|
|
263
|
+
table = opened
|
|
264
|
+
storageReady = true
|
|
265
|
+
} catch (error) {
|
|
266
|
+
storageError = errorMessage(error)
|
|
267
|
+
warn(`session tools storage could not open: ${storageError}`)
|
|
268
|
+
}
|
|
269
|
+
})()
|
|
270
|
+
|
|
271
|
+
function parentRootId(subject) {
|
|
272
|
+
const lookup = (id) => optionalService(ctx, 'agents')?.get?.(id) ?? {
|
|
273
|
+
session: optionalService(ctx, 'sessions')?.get?.(id), sessionId: id,
|
|
274
|
+
}
|
|
275
|
+
let agent = typeof subject === 'string' ? lookup(subject) : subject
|
|
276
|
+
if (!isDelegatedChild(agent)) return rootSessionIdOf(agent)
|
|
277
|
+
try {
|
|
278
|
+
const rootId = optionalService(ctx, 'subagents')?.rootOf?.(agent)?.id
|
|
279
|
+
if (rootId) return rootId
|
|
280
|
+
} catch {
|
|
281
|
+
// Creation and cold recovery can resolve the parent before the runtime owner is registered.
|
|
282
|
+
}
|
|
283
|
+
const seen = new Set()
|
|
284
|
+
while (isDelegatedChild(agent)) {
|
|
285
|
+
const id = rootSessionIdOf(agent)
|
|
286
|
+
if (!id || seen.has(id)) return undefined
|
|
287
|
+
seen.add(id)
|
|
288
|
+
agent = lookup(id)
|
|
289
|
+
}
|
|
290
|
+
return rootSessionIdOf(agent)
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
function resolveSessionConfig(subject) {
|
|
294
|
+
const global = { ...CONFIG_DEFAULTS, mainRoute: currentMainRoute(), ...globalConfigFor() }
|
|
295
|
+
// A profile written by an older release may still carry a fractional interval.
|
|
296
|
+
for (const [field, min, max] of [['superviseIntervalSeconds', 10, 86400], ['superviseMaxNoticesPerChild', 0, 20]]) {
|
|
297
|
+
if (!Number.isInteger(global[field]) || global[field] < min || global[field] > max) global[field] = CONFIG_DEFAULTS[field]
|
|
298
|
+
}
|
|
299
|
+
const patch = records.get(parentRootId(subject))?.config
|
|
300
|
+
const config = {
|
|
301
|
+
...global,
|
|
302
|
+
...patch,
|
|
303
|
+
mainRoute: patch?.mainRoute ?? global.mainRoute,
|
|
304
|
+
workerRoute: patch?.workerRoute ?? global.workerRoute,
|
|
305
|
+
allowedTools: parseNames(patch?.allowedTools ?? globalAllowedFor?.() ?? global.allowedTools),
|
|
306
|
+
}
|
|
307
|
+
return parseSessionConfigPatch(config)
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
function getSessionOverride(sessionId) {
|
|
311
|
+
const row = records.get(sessionId)
|
|
312
|
+
return {
|
|
313
|
+
active: row !== undefined,
|
|
314
|
+
allowedTools: [...(row?.config.allowedTools ?? [])],
|
|
315
|
+
revision: row?.revision ?? clearedRevisions.get(sessionId) ?? initialRevision,
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
function resolveAllowedTools(subject, { globalAllowed, allowAgentTeam, catalog, defaultAllowed } = {}) {
|
|
320
|
+
// Undefined means no main-agent whitelist; the existing child mask takes over.
|
|
321
|
+
if (isDelegatedChild(subject)) return undefined
|
|
322
|
+
const override = records.get(parentRootId(subject))?.config
|
|
323
|
+
return resolveEffectiveAllowedTools(override?.allowedTools ?? globalAllowed, {
|
|
324
|
+
defaults: defaultAllowed, allowAgentTeam, availableTools: catalog,
|
|
325
|
+
})
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
function currentMainRoute() {
|
|
329
|
+
try {
|
|
330
|
+
const route = optionalService(ctx, 'agentDefaultModel')?.currentSelection?.()
|
|
331
|
+
return route === undefined ? null : parseSessionRoute(route, 'mainRoute')
|
|
332
|
+
} catch {
|
|
333
|
+
return null
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
function selectMainRoute(agent, route) {
|
|
338
|
+
if (stopping || !agent || isDelegatedChild(agent) || route === null) return
|
|
339
|
+
try {
|
|
340
|
+
// The host captures the selection once per step; select does not disturb a prepared request.
|
|
341
|
+
agent.model?.select?.(route)
|
|
342
|
+
} catch (error) {
|
|
343
|
+
warn(`cannot select session main route for ${agent.id}: ${errorMessage(error)}`)
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
function restoreMainRoute(agent) {
|
|
348
|
+
const route = records.get(rootSessionIdOf(agent))?.config?.mainRoute
|
|
349
|
+
if (route) selectMainRoute(agent, route)
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
function state(sessionId) {
|
|
353
|
+
const { active, revision } = getSessionOverride(sessionId)
|
|
354
|
+
const config = resolveSessionConfig(sessionId)
|
|
355
|
+
return {
|
|
356
|
+
sessionId,
|
|
357
|
+
enabled: active,
|
|
358
|
+
allowedTools: config.allowedTools,
|
|
359
|
+
config,
|
|
360
|
+
revision,
|
|
361
|
+
storageReady: storageReady && !stopping,
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
async function validateSession(sessionId) {
|
|
366
|
+
try {
|
|
367
|
+
if (await checkSession(ctx, sessionId) === false) return failure('SESSION_NOT_FOUND', 'Session does not exist')
|
|
368
|
+
} catch (error) {
|
|
369
|
+
return failure('SESSION_LOOKUP_FAILED', errorMessage(error))
|
|
370
|
+
}
|
|
371
|
+
return undefined
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
async function get(sessionId) {
|
|
375
|
+
try { parseSessionId(sessionId) } catch (error) {
|
|
376
|
+
return failure('INVALID_ARGUMENT', errorMessage(error))
|
|
377
|
+
}
|
|
378
|
+
await ready
|
|
379
|
+
return await validateSession(sessionId) ?? state(sessionId)
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
function write(operation, sessionId, expectedRevision, value) {
|
|
383
|
+
if (stopping) return Promise.resolve(failure('STORAGE_UNAVAILABLE', storageError))
|
|
384
|
+
const next = tail.then(async () => {
|
|
385
|
+
await ready
|
|
386
|
+
if (!storageReady || stopping) return failure('STORAGE_UNAVAILABLE', storageError)
|
|
387
|
+
const invalidSession = await validateSession(sessionId)
|
|
388
|
+
if (invalidSession) return invalidSession
|
|
389
|
+
const before = getSessionOverride(sessionId)
|
|
390
|
+
if (before.revision !== expectedRevision) return failure('REVISION_CONFLICT', 'Session tools revision changed; reload and try again')
|
|
391
|
+
if (operation === 'clear' && !before.active) return state(sessionId)
|
|
392
|
+
const previous = records.get(sessionId)
|
|
393
|
+
const changes = value ?? {}
|
|
394
|
+
if (changes.mainRoute) {
|
|
395
|
+
try {
|
|
396
|
+
await optionalService(ctx, 'llm')?.resolveCallConfig?.({ ...changes.mainRoute })
|
|
397
|
+
} catch (error) {
|
|
398
|
+
return failure('INVALID_MAIN_ROUTE', errorMessage(error))
|
|
399
|
+
}
|
|
400
|
+
if (stopping) return failure('STORAGE_UNAVAILABLE', storageError)
|
|
401
|
+
}
|
|
402
|
+
const key = encodeRecordKey(sessionId)
|
|
403
|
+
try {
|
|
404
|
+
const revision = parseRevision(before.revision + 1)
|
|
405
|
+
if (operation === 'clear') {
|
|
406
|
+
parseRecord(records.get(sessionId))
|
|
407
|
+
if (await table.delete(key) === false) throw new Error('Session tools deletion was not confirmed')
|
|
408
|
+
records.delete(sessionId)
|
|
409
|
+
clearedRevisions.set(sessionId, revision)
|
|
410
|
+
} else {
|
|
411
|
+
const row = parseRecord({ sessionId, config: { ...previous?.config, ...changes }, revision, updatedAt: Date.now() })
|
|
412
|
+
if (await table.put(key, row) === false) throw new Error('Session tools write was not confirmed')
|
|
413
|
+
records.set(sessionId, row)
|
|
414
|
+
clearedRevisions.delete(sessionId)
|
|
415
|
+
}
|
|
416
|
+
} catch (error) {
|
|
417
|
+
if (error?.code === 'unknown-state') {
|
|
418
|
+
storageReady = false
|
|
419
|
+
storageError = errorMessage(error)
|
|
420
|
+
}
|
|
421
|
+
return failure('STORAGE_WRITE_FAILED', errorMessage(error))
|
|
422
|
+
}
|
|
423
|
+
if (!stopping) {
|
|
424
|
+
if (operation === 'clear' || Object.hasOwn(changes, 'mainRoute')) {
|
|
425
|
+
const agent = optionalService(ctx, 'agents')?.get?.(sessionId)
|
|
426
|
+
selectMainRoute(agent, changes.mainRoute ?? currentMainRoute())
|
|
427
|
+
}
|
|
428
|
+
try {
|
|
429
|
+
onConfigChanged?.(sessionId)
|
|
430
|
+
} catch (error) {
|
|
431
|
+
warn(`cannot refresh session config for ${sessionId}: ${errorMessage(error)}`)
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
return state(sessionId)
|
|
435
|
+
})
|
|
436
|
+
tail = next.then(() => {}, () => {})
|
|
437
|
+
return next
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
function setConfig(sessionId, config, expectedRevision) {
|
|
441
|
+
try {
|
|
442
|
+
return write('set', parseSessionId(sessionId), parseRevision(expectedRevision), parseSessionConfigPatch(config))
|
|
443
|
+
} catch (error) {
|
|
444
|
+
return Promise.resolve(failure('INVALID_ARGUMENT', errorMessage(error)))
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
function set(sessionId, allowedTools, expectedRevision) {
|
|
449
|
+
return setConfig(sessionId, { allowedTools }, expectedRevision)
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
function clear(sessionId, expectedRevision) {
|
|
453
|
+
try {
|
|
454
|
+
return write('clear', parseSessionId(sessionId), parseRevision(expectedRevision))
|
|
455
|
+
} catch (error) {
|
|
456
|
+
return Promise.resolve(failure('INVALID_ARGUMENT', errorMessage(error)))
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
function close() {
|
|
461
|
+
if (closing) return closing
|
|
462
|
+
stopping = true
|
|
463
|
+
closing = Promise.all([ready, tail]).then(() => domain?.close()).finally(() => reservation?.release())
|
|
464
|
+
return closing
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
return {
|
|
468
|
+
ready, close, get, set, setConfig, clear, getSessionOverride, resolveAllowedTools, resolveSessionConfig,
|
|
469
|
+
currentMainRoute, selectMainRoute, restoreMainRoute, resolveRootId: parentRootId,
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
export function mountSessionToolsRemote(ctx, controller) {
|
|
474
|
+
let unprovide
|
|
475
|
+
let unregister
|
|
476
|
+
let available = false
|
|
477
|
+
let error
|
|
478
|
+
let closing
|
|
479
|
+
const dispose = () => {
|
|
480
|
+
available = false
|
|
481
|
+
if (closing) return closing
|
|
482
|
+
const release = (disposer) => {
|
|
483
|
+
try { return Promise.resolve(disposer?.()) } catch (error) { return Promise.reject(error) }
|
|
484
|
+
}
|
|
485
|
+
closing = Promise.all([release(unregister), release(unprovide)])
|
|
486
|
+
return closing
|
|
487
|
+
}
|
|
488
|
+
try {
|
|
489
|
+
const typert = optionalService(ctx, 'typert')
|
|
490
|
+
if (typeof typert?.register !== 'function' || typeof ctx.provide !== 'function') {
|
|
491
|
+
return { available, error: 'Typert session tools Remote is unavailable', dispose }
|
|
492
|
+
}
|
|
493
|
+
const service = {
|
|
494
|
+
get: controller.get, set: controller.set, setConfig: controller.setConfig, clear: controller.clear,
|
|
495
|
+
}
|
|
496
|
+
// Gateway checks the ordinary public property and the original object's identity.
|
|
497
|
+
// bindTypertRemote would also add ctx.invocation for a service carrying a ctx;
|
|
498
|
+
// this direct, closure-backed service has no ctx and needs no such accessor.
|
|
499
|
+
service.typertRemote = Object.freeze({
|
|
500
|
+
service, serviceKey: SESSION_TOOLS_NAMESPACE, namespace: SESSION_TOOLS_NAMESPACE,
|
|
501
|
+
})
|
|
502
|
+
unprovide = ctx.provide(SESSION_TOOLS_NAMESPACE, service)
|
|
503
|
+
unregister = typert.register({
|
|
504
|
+
package: SESSION_TOOLS_PACKAGE,
|
|
505
|
+
face: 'host',
|
|
506
|
+
schemas: [],
|
|
507
|
+
model: { services: [], events: [], objects: [] },
|
|
508
|
+
invocations: createSessionToolsDescriptors(),
|
|
509
|
+
})
|
|
510
|
+
available = true
|
|
511
|
+
} catch (cause) {
|
|
512
|
+
error = errorMessage(cause)
|
|
513
|
+
void dispose().catch(() => {})
|
|
514
|
+
}
|
|
515
|
+
return { get available() { return available }, error, dispose }
|
|
516
|
+
}
|
package/lib/state-store.js
CHANGED
|
@@ -18,6 +18,9 @@ const isTime = (value) => Number.isFinite(value) && value >= 0
|
|
|
18
18
|
const isListOf = (check) => (value) => Array.isArray(value) && Array.from(value).every(check)
|
|
19
19
|
const isTextList = isListOf(isText)
|
|
20
20
|
const isIdList = isListOf(isId)
|
|
21
|
+
const isNonBlank = (value) => isText(value) && value.trim() !== ''
|
|
22
|
+
const isNextTurn = (value) => isObject(value) && isBoolean(value.readOnly) &&
|
|
23
|
+
isIdList(value.writeScope) && (value.readOnly ? value.writeScope.length === 0 : value.writeScope.length > 0)
|
|
21
24
|
|
|
22
25
|
function isObject(value) {
|
|
23
26
|
if (value === null || typeof value !== 'object') return false
|
|
@@ -36,27 +39,28 @@ const TABLES = {
|
|
|
36
39
|
repoRoot: isText, sourceCwd: isText, subPath: isText, worktreePath: isText, execCwd: isText,
|
|
37
40
|
branch: isText, baseBranch: isText, baseCommit: isText, label: isText, state: isId,
|
|
38
41
|
mergeCommit: isText, cleaned: isBoolean, locked: isBoolean, createdAt: isTime,
|
|
39
|
-
updatedAt: isTime,
|
|
42
|
+
updatedAt: isTime,
|
|
40
43
|
},
|
|
41
44
|
},
|
|
42
45
|
delegates: {
|
|
43
46
|
key: 'childId',
|
|
44
47
|
fields: {
|
|
45
48
|
parentId: isText, rootSessionId: isText, agentName: isId, label: isText, cwd: isText, readOnly: isBoolean,
|
|
46
|
-
writeScope: isTextList,
|
|
49
|
+
writeScope: isTextList, batchId: isText, itemIndex: isCount,
|
|
47
50
|
stageIndex: isCount, worktreeId: isText, leaseId: isText, attemptSeq: isCount, runId: isText,
|
|
48
|
-
dispatchState: isId, stopReason: isText,
|
|
49
|
-
|
|
51
|
+
dispatchState: isId, stopReason: isText, leaseState: isId,
|
|
52
|
+
startedAt: isTime, endedAt: isTime,
|
|
50
53
|
updatedAt: isTime, retry: isObject, watchCursor: isObject,
|
|
51
|
-
|
|
52
|
-
|
|
54
|
+
wakeActionKey: isText,
|
|
55
|
+
pendingNextTurn: isNextTurn, allowNewReason: isNonBlank,
|
|
56
|
+
disposedAt: isTime, releasedAt: isTime,
|
|
53
57
|
},
|
|
54
58
|
},
|
|
55
59
|
leases: {
|
|
56
60
|
key: 'leaseId',
|
|
57
61
|
fields: {
|
|
58
62
|
ownerKind: isText, ownerId: isText, parentId: isText, entries: isLeaseEntries,
|
|
59
|
-
issuedAt: isTime, expiresAt: isTime,
|
|
63
|
+
issuedAt: isTime, expiresAt: isTime,
|
|
60
64
|
},
|
|
61
65
|
},
|
|
62
66
|
actions: {
|
|
@@ -400,8 +404,9 @@ export function createStateStore({
|
|
|
400
404
|
for (const childId of record.childIds ?? []) protectedChildren.add(childId)
|
|
401
405
|
}
|
|
402
406
|
const delegates = [...records.delegates].filter(([id, record]) => {
|
|
403
|
-
|
|
404
|
-
|
|
407
|
+
const wakeup = record.wakeActionKey && records.actions.get(record.wakeActionKey)
|
|
408
|
+
if (!TERMINAL_DISPATCH_STATES.has(record.dispatchState) || protectedChildren.has(id) ||
|
|
409
|
+
record.pendingNextTurn || (record.wakeActionKey && wakeup?.phase !== 'done')) return false
|
|
405
410
|
if (!record.worktreeId) return true
|
|
406
411
|
const worktree = records.worktrees.get(record.worktreeId)
|
|
407
412
|
return Boolean(worktree) && !needsWorktreeReview(worktree)
|