@sshirkit/dsh-orchestrator 1.0.2 → 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.
@@ -7,8 +7,22 @@ export const SESSION_TOOLS_TABLE = 'session_allowed_tools'
7
7
  export const SESSION_TOOLS_PACKAGE = '@sshirkit/dsh-orchestrator'
8
8
  export const SESSION_TOOLS_NAMESPACE = 'orchestratorSession'
9
9
 
10
- const RECORD_FIELDS = ['sessionId', 'allowedTools', 'revision', 'updatedAt']
11
- const STATE_FIELDS = ['sessionId', 'enabled', 'allowedTools', 'revision', 'storageReady']
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)
12
26
  const ownersKey = Symbol.for('@sshirkit/dsh-orchestrator/session-tools-domain-owners')
13
27
  const owners = globalThis[ownersKey] ??= new WeakMap()
14
28
  const cordisOriginal = Symbol.for('cordis.original')
@@ -56,14 +70,62 @@ function fields(value, names) {
56
70
  }
57
71
  }
58
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
+
59
119
  function parseRecord(value) {
60
- fields(value, RECORD_FIELDS)
61
- const allowedTools = parseNames(value.allowedTools)
62
- if (allowedTools.length !== value.allowedTools.length) throw new TypeError('duplicate stored tool name')
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')
63
125
  if (!Number.isSafeInteger(value.updatedAt) || value.updatedAt < 0) throw new TypeError('invalid updatedAt')
64
126
  return {
65
127
  sessionId: parseSessionId(value.sessionId),
66
- allowedTools,
128
+ config,
67
129
  revision: parseRevision(value.revision),
68
130
  updatedAt: value.updatedAt,
69
131
  }
@@ -82,9 +144,15 @@ function parseResult(value) {
82
144
  throw new TypeError('enabled and storageReady must be booleans')
83
145
  }
84
146
  parseSessionId(value.sessionId)
85
- parseNames(value.allowedTools)
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
+ }
86
154
  parseRevision(value.revision)
87
- return value
155
+ return { ...value, allowedTools, config }
88
156
  }
89
157
 
90
158
  /** Client mirror lives in the host's non-ESM web bundle. Keep contract parity tested. */
@@ -96,8 +164,11 @@ export function createSessionToolsDescriptors() {
96
164
  const session = parameter('sessionId', 'SessionId', parseSessionId)
97
165
  const names = parameter('allowedTools', 'OrchestratorToolNames', parseNames)
98
166
  const revision = parameter('expectedRevision', 'OrchestratorToolsRevision', parseRevision)
167
+ const config = parameter('config', 'OrchestratorSessionConfigPatch', parseSessionConfigPatch)
99
168
  const result = codec('OrchestratorSessionToolsResult', parseResult)
100
- return Object.entries({ get: [session], set: [session, names, revision], clear: [session, revision] })
169
+ const methods = { get: [session], set: [session, names, revision], setConfig: [session, config, revision],
170
+ clear: [session, revision] }
171
+ return Object.entries(methods)
101
172
  .map(([method, parameters]) => ({
102
173
  id: `${SESSION_TOOLS_PACKAGE}/${SESSION_TOOLS_NAMESPACE}/${method}`,
103
174
  service: SESSION_TOOLS_NAMESPACE,
@@ -145,11 +216,17 @@ async function checkSession(ctx, id) {
145
216
  return liveLookup ? false : undefined
146
217
  }
147
218
 
148
- function idOf(subject) {
149
- return typeof subject === 'string' ? subject : subject?.session?.id ?? subject?.sessionId
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
150
225
  }
151
226
 
152
- export function createSessionTools({ facility, ctx = {}, logger, globalAllowedFor = () => [] } = {}) {
227
+ export function createSessionTools({
228
+ facility, ctx = {}, logger, globalConfigFor = () => ({}), globalAllowedFor, onConfigChanged,
229
+ } = {}) {
153
230
  const records = new Map()
154
231
  const clearedRevisions = new Map()
155
232
  // No tombstones on disk: a new incarnation chooses a different token for an absent row,
@@ -191,11 +268,50 @@ export function createSessionTools({ facility, ctx = {}, logger, globalAllowedFo
191
268
  }
192
269
  })()
193
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
+
194
310
  function getSessionOverride(sessionId) {
195
311
  const row = records.get(sessionId)
196
312
  return {
197
313
  active: row !== undefined,
198
- allowedTools: row ? [...row.allowedTools] : [],
314
+ allowedTools: [...(row?.config.allowedTools ?? [])],
199
315
  revision: row?.revision ?? clearedRevisions.get(sessionId) ?? initialRevision,
200
316
  }
201
317
  }
@@ -203,18 +319,44 @@ export function createSessionTools({ facility, ctx = {}, logger, globalAllowedFo
203
319
  function resolveAllowedTools(subject, { globalAllowed, allowAgentTeam, catalog, defaultAllowed } = {}) {
204
320
  // Undefined means no main-agent whitelist; the existing child mask takes over.
205
321
  if (isDelegatedChild(subject)) return undefined
206
- const override = records.get(idOf(subject))
322
+ const override = records.get(parentRootId(subject))?.config
207
323
  return resolveEffectiveAllowedTools(override?.allowedTools ?? globalAllowed, {
208
324
  defaults: defaultAllowed, allowAgentTeam, availableTools: catalog,
209
325
  })
210
326
  }
211
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
+
212
352
  function state(sessionId) {
213
- const { active, allowedTools, revision } = getSessionOverride(sessionId)
353
+ const { active, revision } = getSessionOverride(sessionId)
354
+ const config = resolveSessionConfig(sessionId)
214
355
  return {
215
356
  sessionId,
216
357
  enabled: active,
217
- allowedTools: active ? allowedTools : [...globalAllowedFor()],
358
+ allowedTools: config.allowedTools,
359
+ config,
218
360
  revision,
219
361
  storageReady: storageReady && !stopping,
220
362
  }
@@ -247,6 +389,16 @@ export function createSessionTools({ facility, ctx = {}, logger, globalAllowedFo
247
389
  const before = getSessionOverride(sessionId)
248
390
  if (before.revision !== expectedRevision) return failure('REVISION_CONFLICT', 'Session tools revision changed; reload and try again')
249
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
+ }
250
402
  const key = encodeRecordKey(sessionId)
251
403
  try {
252
404
  const revision = parseRevision(before.revision + 1)
@@ -256,12 +408,11 @@ export function createSessionTools({ facility, ctx = {}, logger, globalAllowedFo
256
408
  records.delete(sessionId)
257
409
  clearedRevisions.set(sessionId, revision)
258
410
  } else {
259
- const row = parseRecord({ sessionId, allowedTools: value, revision, updatedAt: Date.now() })
411
+ const row = parseRecord({ sessionId, config: { ...previous?.config, ...changes }, revision, updatedAt: Date.now() })
260
412
  if (await table.put(key, row) === false) throw new Error('Session tools write was not confirmed')
261
413
  records.set(sessionId, row)
262
414
  clearedRevisions.delete(sessionId)
263
415
  }
264
- return state(sessionId)
265
416
  } catch (error) {
266
417
  if (error?.code === 'unknown-state') {
267
418
  storageReady = false
@@ -269,19 +420,35 @@ export function createSessionTools({ facility, ctx = {}, logger, globalAllowedFo
269
420
  }
270
421
  return failure('STORAGE_WRITE_FAILED', errorMessage(error))
271
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)
272
435
  })
273
436
  tail = next.then(() => {}, () => {})
274
437
  return next
275
438
  }
276
439
 
277
- function set(sessionId, allowedTools, expectedRevision) {
440
+ function setConfig(sessionId, config, expectedRevision) {
278
441
  try {
279
- return write('set', parseSessionId(sessionId), parseRevision(expectedRevision), parseNames(allowedTools))
442
+ return write('set', parseSessionId(sessionId), parseRevision(expectedRevision), parseSessionConfigPatch(config))
280
443
  } catch (error) {
281
444
  return Promise.resolve(failure('INVALID_ARGUMENT', errorMessage(error)))
282
445
  }
283
446
  }
284
447
 
448
+ function set(sessionId, allowedTools, expectedRevision) {
449
+ return setConfig(sessionId, { allowedTools }, expectedRevision)
450
+ }
451
+
285
452
  function clear(sessionId, expectedRevision) {
286
453
  try {
287
454
  return write('clear', parseSessionId(sessionId), parseRevision(expectedRevision))
@@ -297,7 +464,10 @@ export function createSessionTools({ facility, ctx = {}, logger, globalAllowedFo
297
464
  return closing
298
465
  }
299
466
 
300
- return { ready, close, get, set, clear, getSessionOverride, resolveAllowedTools }
467
+ return {
468
+ ready, close, get, set, setConfig, clear, getSessionOverride, resolveAllowedTools, resolveSessionConfig,
469
+ currentMainRoute, selectMainRoute, restoreMainRoute, resolveRootId: parentRootId,
470
+ }
301
471
  }
302
472
 
303
473
  export function mountSessionToolsRemote(ctx, controller) {
@@ -320,7 +490,9 @@ export function mountSessionToolsRemote(ctx, controller) {
320
490
  if (typeof typert?.register !== 'function' || typeof ctx.provide !== 'function') {
321
491
  return { available, error: 'Typert session tools Remote is unavailable', dispose }
322
492
  }
323
- const service = { get: controller.get, set: controller.set, clear: controller.clear }
493
+ const service = {
494
+ get: controller.get, set: controller.set, setConfig: controller.setConfig, clear: controller.clear,
495
+ }
324
496
  // Gateway checks the ordinary public property and the original object's identity.
325
497
  // bindTypertRemote would also add ctx.invocation for a service carrying a ctx;
326
498
  // this direct, closure-backed service has no ctx and needs no such accessor.
@@ -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, auditSummary: (value) => isText(value) || isObject(value),
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, expectedTargets: isTextList, batchId: isText, itemIndex: isCount,
49
+ writeScope: isTextList, batchId: isText, itemIndex: isCount,
47
50
  stageIndex: isCount, worktreeId: isText, leaseId: isText, attemptSeq: isCount, runId: isText,
48
- dispatchState: isId, stopReason: isText, baselineId: isText, auditState: isId,
49
- incomplete: isBoolean, auditDeliveredVia: isText, startedAt: isTime, endedAt: isTime,
51
+ dispatchState: isId, stopReason: isText, leaseState: isId,
52
+ startedAt: isTime, endedAt: isTime,
50
53
  updatedAt: isTime, retry: isObject, watchCursor: isObject,
51
- gitBaseline: isObject, auditSummary: isText, violations: isListOf(isObject), wakeActionKey: isText,
52
- truncatedViolations: isCount, disposedAt: isTime, auditedAt: isTime, releasedAt: isTime,
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, baselineId: isText,
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
- if (!TERMINAL_DISPATCH_STATES.has(record.dispatchState) || record.auditState === 'pending' ||
404
- (record.auditState === 'failed' && !record.auditDeliveredVia) || protectedChildren.has(id)) return false
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)