@sshirkit/dsh-orchestrator 1.0.0 → 1.0.2

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.
@@ -0,0 +1,344 @@
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 RECORD_FIELDS = ['sessionId', 'allowedTools', 'revision', 'updatedAt']
11
+ const STATE_FIELDS = ['sessionId', 'enabled', 'allowedTools', 'revision', 'storageReady']
12
+ const ownersKey = Symbol.for('@sshirkit/dsh-orchestrator/session-tools-domain-owners')
13
+ const owners = globalThis[ownersKey] ??= new WeakMap()
14
+ const cordisOriginal = Symbol.for('cordis.original')
15
+
16
+ function reserveDomain(facility) {
17
+ const key = facility[cordisOriginal] ?? facility
18
+ const previous = owners.get(key)
19
+ let release
20
+ const hold = new Promise((resolve) => { release = resolve })
21
+ const tail = Promise.resolve(previous).then(() => hold)
22
+ owners.set(key, tail)
23
+ void tail.then(() => {
24
+ if (owners.get(key) === tail) owners.delete(key)
25
+ })
26
+ return { previous, release }
27
+ }
28
+
29
+ function nonempty(value, field) {
30
+ if (typeof value !== 'string' || value.trim() === '') {
31
+ throw new TypeError(`${field} must be a non-empty string`)
32
+ }
33
+ return value
34
+ }
35
+
36
+ const parseSessionId = (value) => nonempty(value, 'sessionId')
37
+
38
+ function parseNames(value) {
39
+ if (!Array.isArray(value)) throw new TypeError('allowedTools must be an array')
40
+ const names = new Set()
41
+ for (const name of value) names.add(nonempty(name, 'tool name'))
42
+ return [...names]
43
+ }
44
+
45
+ function parseRevision(value) {
46
+ if (!Number.isSafeInteger(value) || value < 0) {
47
+ throw new TypeError('revision must be a non-negative safe integer')
48
+ }
49
+ return value
50
+ }
51
+
52
+ function fields(value, names) {
53
+ if (value === null || typeof value !== 'object' || Array.isArray(value) ||
54
+ Object.keys(value).length !== names.length || !names.every((key) => Object.hasOwn(value, key))) {
55
+ throw new TypeError(`expected record with fields ${names.join(', ')}`)
56
+ }
57
+ }
58
+
59
+ 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')
63
+ if (!Number.isSafeInteger(value.updatedAt) || value.updatedAt < 0) throw new TypeError('invalid updatedAt')
64
+ return {
65
+ sessionId: parseSessionId(value.sessionId),
66
+ allowedTools,
67
+ revision: parseRevision(value.revision),
68
+ updatedAt: value.updatedAt,
69
+ }
70
+ }
71
+
72
+ function parseResult(value) {
73
+ if (value?.ok === false) {
74
+ fields(value, ['ok', 'error'])
75
+ fields(value.error, ['code', 'message'])
76
+ nonempty(value.error.code, 'error code')
77
+ nonempty(value.error.message, 'error message')
78
+ return value
79
+ }
80
+ fields(value, STATE_FIELDS)
81
+ if (typeof value.enabled !== 'boolean' || typeof value.storageReady !== 'boolean') {
82
+ throw new TypeError('enabled and storageReady must be booleans')
83
+ }
84
+ parseSessionId(value.sessionId)
85
+ parseNames(value.allowedTools)
86
+ parseRevision(value.revision)
87
+ return value
88
+ }
89
+
90
+ /** Client mirror lives in the host's non-ESM web bundle. Keep contract parity tested. */
91
+ export function createSessionToolsDescriptors() {
92
+ const codec = (typeSymbol, parse) => ({ mode: 'strict', typeSymbol, create: () => ({ parse }) })
93
+ const parameter = (name, typeSymbol, parse) => ({
94
+ name, wire: name, source: 'json', codec: codec(typeSymbol, parse),
95
+ })
96
+ const session = parameter('sessionId', 'SessionId', parseSessionId)
97
+ const names = parameter('allowedTools', 'OrchestratorToolNames', parseNames)
98
+ const revision = parameter('expectedRevision', 'OrchestratorToolsRevision', parseRevision)
99
+ const result = codec('OrchestratorSessionToolsResult', parseResult)
100
+ return Object.entries({ get: [session], set: [session, names, revision], clear: [session, revision] })
101
+ .map(([method, parameters]) => ({
102
+ id: `${SESSION_TOOLS_PACKAGE}/${SESSION_TOOLS_NAMESPACE}/${method}`,
103
+ service: SESSION_TOOLS_NAMESPACE,
104
+ namespace: SESSION_TOOLS_NAMESPACE,
105
+ method,
106
+ invocation: { kind: 'direct' },
107
+ parameters,
108
+ result,
109
+ }))
110
+ }
111
+
112
+ const domainSpec = {
113
+ name: SESSION_TOOLS_DOMAIN,
114
+ version: 1,
115
+ layout: 'single',
116
+ tables: { [SESSION_TOOLS_TABLE]: { valueSchema: { parse: parseRecord } } },
117
+ }
118
+
119
+ const errorMessage = (error) => typeof error?.message === 'string' ? error.message : String(error)
120
+ const failure = (code, message) => ({ ok: false, error: { code, message } })
121
+ const isMissing = (error) => ['SESSION_QUERY_SESSION_NOT_FOUND', 'not-found', 'session-not-found'].includes(error?.code)
122
+
123
+ function optionalService(ctx, name) {
124
+ try {
125
+ return ctx.get?.(name) ?? ctx[name]
126
+ } catch {
127
+ return undefined
128
+ }
129
+ }
130
+
131
+ /** A live lookup wins; cold sessions can still be addressed by their durable ID. */
132
+ async function checkSession(ctx, id) {
133
+ const sessions = optionalService(ctx, 'sessions')
134
+ const liveLookup = typeof sessions?.get === 'function' || typeof sessions?.has === 'function'
135
+ if (typeof sessions?.get === 'function' ? await sessions.get(id) : await sessions?.has?.(id)) return true
136
+ const query = optionalService(ctx, 'sessionQuery')
137
+ if (typeof query?.inspectSession === 'function') {
138
+ try {
139
+ return Boolean(await query.inspectSession(id, () => true))
140
+ } catch (error) {
141
+ if (isMissing(error)) return false
142
+ throw error
143
+ }
144
+ }
145
+ return liveLookup ? false : undefined
146
+ }
147
+
148
+ function idOf(subject) {
149
+ return typeof subject === 'string' ? subject : subject?.session?.id ?? subject?.sessionId
150
+ }
151
+
152
+ export function createSessionTools({ facility, ctx = {}, logger, globalAllowedFor = () => [] } = {}) {
153
+ const records = new Map()
154
+ const clearedRevisions = new Map()
155
+ // No tombstones on disk: a new incarnation chooses a different token for an absent row,
156
+ // so a stale client cannot reuse the pre-clear token after a restart (ABA).
157
+ const initialRevision = randomInt(1, 2 ** 48 - 1)
158
+ const reservation = typeof facility?.open === 'function' ? reserveDomain(facility) : undefined
159
+ let domain
160
+ let table
161
+ let storageReady = false
162
+ let stopping = false
163
+ let tail = Promise.resolve()
164
+ let closing
165
+ let storageError = 'Session tools storage is unavailable'
166
+
167
+ const warn = (message) => {
168
+ try { logger?.warn?.(`orchestrator: ${message}`) } catch { /* Diagnostics cannot stop teardown. */ }
169
+ }
170
+
171
+ const ready = (async () => {
172
+ if (!reservation) return
173
+ await reservation.previous
174
+ if (stopping) return
175
+ try {
176
+ domain = await facility.open(domainSpec)
177
+ const opened = domain.table(SESSION_TOOLS_TABLE)
178
+ const hydrated = new Map()
179
+ for (const [key, value] of opened.entries()) {
180
+ const row = parseRecord(value)
181
+ if (encodeRecordKey(row.sessionId) !== key) throw new Error('Session tools record key does not match its sessionId')
182
+ hydrated.set(row.sessionId, row)
183
+ }
184
+ if (stopping) return
185
+ for (const [id, row] of hydrated) records.set(id, row)
186
+ table = opened
187
+ storageReady = true
188
+ } catch (error) {
189
+ storageError = errorMessage(error)
190
+ warn(`session tools storage could not open: ${storageError}`)
191
+ }
192
+ })()
193
+
194
+ function getSessionOverride(sessionId) {
195
+ const row = records.get(sessionId)
196
+ return {
197
+ active: row !== undefined,
198
+ allowedTools: row ? [...row.allowedTools] : [],
199
+ revision: row?.revision ?? clearedRevisions.get(sessionId) ?? initialRevision,
200
+ }
201
+ }
202
+
203
+ function resolveAllowedTools(subject, { globalAllowed, allowAgentTeam, catalog, defaultAllowed } = {}) {
204
+ // Undefined means no main-agent whitelist; the existing child mask takes over.
205
+ if (isDelegatedChild(subject)) return undefined
206
+ const override = records.get(idOf(subject))
207
+ return resolveEffectiveAllowedTools(override?.allowedTools ?? globalAllowed, {
208
+ defaults: defaultAllowed, allowAgentTeam, availableTools: catalog,
209
+ })
210
+ }
211
+
212
+ function state(sessionId) {
213
+ const { active, allowedTools, revision } = getSessionOverride(sessionId)
214
+ return {
215
+ sessionId,
216
+ enabled: active,
217
+ allowedTools: active ? allowedTools : [...globalAllowedFor()],
218
+ revision,
219
+ storageReady: storageReady && !stopping,
220
+ }
221
+ }
222
+
223
+ async function validateSession(sessionId) {
224
+ try {
225
+ if (await checkSession(ctx, sessionId) === false) return failure('SESSION_NOT_FOUND', 'Session does not exist')
226
+ } catch (error) {
227
+ return failure('SESSION_LOOKUP_FAILED', errorMessage(error))
228
+ }
229
+ return undefined
230
+ }
231
+
232
+ async function get(sessionId) {
233
+ try { parseSessionId(sessionId) } catch (error) {
234
+ return failure('INVALID_ARGUMENT', errorMessage(error))
235
+ }
236
+ await ready
237
+ return await validateSession(sessionId) ?? state(sessionId)
238
+ }
239
+
240
+ function write(operation, sessionId, expectedRevision, value) {
241
+ if (stopping) return Promise.resolve(failure('STORAGE_UNAVAILABLE', storageError))
242
+ const next = tail.then(async () => {
243
+ await ready
244
+ if (!storageReady || stopping) return failure('STORAGE_UNAVAILABLE', storageError)
245
+ const invalidSession = await validateSession(sessionId)
246
+ if (invalidSession) return invalidSession
247
+ const before = getSessionOverride(sessionId)
248
+ if (before.revision !== expectedRevision) return failure('REVISION_CONFLICT', 'Session tools revision changed; reload and try again')
249
+ if (operation === 'clear' && !before.active) return state(sessionId)
250
+ const key = encodeRecordKey(sessionId)
251
+ try {
252
+ const revision = parseRevision(before.revision + 1)
253
+ if (operation === 'clear') {
254
+ parseRecord(records.get(sessionId))
255
+ if (await table.delete(key) === false) throw new Error('Session tools deletion was not confirmed')
256
+ records.delete(sessionId)
257
+ clearedRevisions.set(sessionId, revision)
258
+ } else {
259
+ const row = parseRecord({ sessionId, allowedTools: value, revision, updatedAt: Date.now() })
260
+ if (await table.put(key, row) === false) throw new Error('Session tools write was not confirmed')
261
+ records.set(sessionId, row)
262
+ clearedRevisions.delete(sessionId)
263
+ }
264
+ return state(sessionId)
265
+ } catch (error) {
266
+ if (error?.code === 'unknown-state') {
267
+ storageReady = false
268
+ storageError = errorMessage(error)
269
+ }
270
+ return failure('STORAGE_WRITE_FAILED', errorMessage(error))
271
+ }
272
+ })
273
+ tail = next.then(() => {}, () => {})
274
+ return next
275
+ }
276
+
277
+ function set(sessionId, allowedTools, expectedRevision) {
278
+ try {
279
+ return write('set', parseSessionId(sessionId), parseRevision(expectedRevision), parseNames(allowedTools))
280
+ } catch (error) {
281
+ return Promise.resolve(failure('INVALID_ARGUMENT', errorMessage(error)))
282
+ }
283
+ }
284
+
285
+ function clear(sessionId, expectedRevision) {
286
+ try {
287
+ return write('clear', parseSessionId(sessionId), parseRevision(expectedRevision))
288
+ } catch (error) {
289
+ return Promise.resolve(failure('INVALID_ARGUMENT', errorMessage(error)))
290
+ }
291
+ }
292
+
293
+ function close() {
294
+ if (closing) return closing
295
+ stopping = true
296
+ closing = Promise.all([ready, tail]).then(() => domain?.close()).finally(() => reservation?.release())
297
+ return closing
298
+ }
299
+
300
+ return { ready, close, get, set, clear, getSessionOverride, resolveAllowedTools }
301
+ }
302
+
303
+ export function mountSessionToolsRemote(ctx, controller) {
304
+ let unprovide
305
+ let unregister
306
+ let available = false
307
+ let error
308
+ let closing
309
+ const dispose = () => {
310
+ available = false
311
+ if (closing) return closing
312
+ const release = (disposer) => {
313
+ try { return Promise.resolve(disposer?.()) } catch (error) { return Promise.reject(error) }
314
+ }
315
+ closing = Promise.all([release(unregister), release(unprovide)])
316
+ return closing
317
+ }
318
+ try {
319
+ const typert = optionalService(ctx, 'typert')
320
+ if (typeof typert?.register !== 'function' || typeof ctx.provide !== 'function') {
321
+ return { available, error: 'Typert session tools Remote is unavailable', dispose }
322
+ }
323
+ const service = { get: controller.get, set: controller.set, clear: controller.clear }
324
+ // Gateway checks the ordinary public property and the original object's identity.
325
+ // bindTypertRemote would also add ctx.invocation for a service carrying a ctx;
326
+ // this direct, closure-backed service has no ctx and needs no such accessor.
327
+ service.typertRemote = Object.freeze({
328
+ service, serviceKey: SESSION_TOOLS_NAMESPACE, namespace: SESSION_TOOLS_NAMESPACE,
329
+ })
330
+ unprovide = ctx.provide(SESSION_TOOLS_NAMESPACE, service)
331
+ unregister = typert.register({
332
+ package: SESSION_TOOLS_PACKAGE,
333
+ face: 'host',
334
+ schemas: [],
335
+ model: { services: [], events: [], objects: [] },
336
+ invocations: createSessionToolsDescriptors(),
337
+ })
338
+ available = true
339
+ } catch (cause) {
340
+ error = errorMessage(cause)
341
+ void dispose().catch(() => {})
342
+ }
343
+ return { get available() { return available }, error, dispose }
344
+ }
@@ -26,6 +26,7 @@
26
26
  import { DELEGATE_STATUS_TOOL_NAME, DELEGATE_TOOL, ORCHESTRATE_TOOL } from './api.js'
27
27
  import { viewNames } from './catalog.js'
28
28
  import { isDelegatedChild, resolveEffectiveAllowedTools } from './gate.js'
29
+ import { TEAM_SHARED_GOAL_RULE } from './rules.js'
29
30
  import { RUN_CODE_TOOL } from './run-code-guard.js'
30
31
 
31
32
  export { DEFAULT_BLOCKED_NATIVE_TOOLS, NATIVE_TEAM_TOOLS, resolveEffectiveAllowedTools } from './gate.js'
@@ -78,14 +79,17 @@ function nameOf(definition) {
78
79
  * is the dispatch switch and `workerDeny` the names a delegated child must not see.
79
80
  * `delegate_status` and `worktree_manage` are root-only in either mode, including with a
80
81
  * custom deny list.
81
- * `allowAgentTeam` is a boolean or live getter for the optional root task board. The call
82
- * returns a disposer that restores the original `definitions`; a second install on the same
82
+ * `allowAgentTeam` gates Team tools for the main agent, and `isNativeTeamEnabled(scope)`
83
+ * reads the host's root mode for guidance only. The call returns a disposer that restores
84
+ * the original `definitions`; a second install on the same
83
85
  * service hands back the first disposer instead of stacking wrappers.
84
86
  */
85
87
  export function installToolSurface({
86
88
  tools,
87
89
  allowed,
90
+ describeDelegate,
88
91
  allowAgentTeam = true,
92
+ isNativeTeamEnabled = () => false,
89
93
  enabled = () => true,
90
94
  workerDeny = [DELEGATE_TOOL, ORCHESTRATE_TOOL],
91
95
  disabledDeny = [DELEGATE_TOOL, ORCHESTRATE_TOOL],
@@ -136,11 +140,12 @@ export function installToolSurface({
136
140
  return hidden
137
141
  }
138
142
 
139
- const mainSurface = (list, present) => {
143
+ const mainSurface = (list, present, scope) => {
140
144
  // The plugin entry supplies the shipped defaults via `allowed`; omitted values share the gate's empty base.
141
- const allow = new Set(resolveEffectiveAllowedTools(liveAllowed(), { allowAgentTeam: liveAllowAgentTeam() }))
145
+ const allowedForScope = resolveEffectiveAllowedTools(liveAllowed(scope), { allowAgentTeam: liveAllowAgentTeam() })
146
+ const allow = new Set(allowedForScope)
142
147
  const shadowed = shadowedOf(present)
143
- return list.filter((definition) => {
148
+ const visible = list.filter((definition) => {
144
149
  const name = nameOf(definition)
145
150
  if (name === '') return true
146
151
  // `run_code` is the PTC transport: delegate/orchestrate are SDK functions inside it,
@@ -149,6 +154,23 @@ export function installToolSurface({
149
154
  if (name === RUN_CODE_TOOL) return true
150
155
  return allow.has(name) && !shadowed.has(name)
151
156
  })
157
+ const visibleNames = new Set(visible.map(nameOf))
158
+ // A registered tool is not necessarily admitted to this step. Use the filtered list,
159
+ // not the catalog. Emit the guidance once, even when both dispatch tools are present.
160
+ const teamGuideTool = visibleNames.has('team_task_create') && isNativeTeamEnabled(scope)
161
+ ? (visibleNames.has(DELEGATE_TOOL) ? DELEGATE_TOOL : ORCHESTRATE_TOOL)
162
+ : undefined
163
+ return visible.map((definition) => {
164
+ const name = nameOf(definition)
165
+ const describe = name === DELEGATE_TOOL && typeof describeDelegate === 'function'
166
+ if (!describe && name !== teamGuideTool) return definition
167
+ let description = describe ? describeDelegate(allowedForScope) : definition.description
168
+ if (name === teamGuideTool) description = `${description} ${TEAM_SHARED_GOAL_RULE}`
169
+ return Object.defineProperties(Object.create(Object.getPrototypeOf(definition)), {
170
+ ...Object.getOwnPropertyDescriptors(definition),
171
+ description: { value: description, enumerable: true, configurable: true },
172
+ })
173
+ })
152
174
  }
153
175
 
154
176
  const workerSurface = (list, present) => {
@@ -178,7 +200,7 @@ export function installToolSurface({
178
200
  })
179
201
  }
180
202
  const present = presentNames(service, scope, list)
181
- return delegated ? workerSurface(list, present) : mainSurface(list, present)
203
+ return delegated ? workerSurface(list, present) : mainSurface(list, present, scope)
182
204
  }
183
205
 
184
206
  const dispose = () => {
package/package.json CHANGED
@@ -1,11 +1,12 @@
1
1
  {
2
2
  "name": "@sshirkit/dsh-orchestrator",
3
- "version": "1.0.0",
3
+ "version": "1.0.2",
4
4
  "publishConfig": {
5
5
  "access": "public",
6
6
  "registry": "https://registry.npmjs.org/"
7
7
  },
8
8
  "description": "Main agent that plans and delegates work; orchestrate fans out with pipelines and structured results; long-running workers are supervised by reading session logs",
9
+ "icon": "./docs/images/plugin-icon.png",
9
10
  "type": "module",
10
11
  "exports": {
11
12
  ".": "./lib/index.js",