@xmodelin/dsh-collab-sessions 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js ADDED
@@ -0,0 +1,2583 @@
1
+ /**
2
+ * Host half of the collaboration-session plugin.
3
+ *
4
+ * The left sidebar entry creates a Session whose Agent preset is `collab`.
5
+ * For every such Agent this plugin prepares a per-session working directory
6
+ * (`comm/` + `private/`), registers model-facing collaboration tools scoped to
7
+ * that Agent, adds a prompt section describing the layout, and enforces the
8
+ * foreign-work-directory boundary for file and shell tools.
9
+ */
10
+ import crypto from 'node:crypto'
11
+ import fs from 'node:fs'
12
+ import path from 'node:path'
13
+
14
+ import { AuthorizationStore, authorizationPathFor } from './lib/auth.js'
15
+ import { NoticeStore } from './lib/notices.js'
16
+ import { RelationshipStore } from './lib/relationships.js'
17
+ import { applyPatchTargets, shellWriteTargets } from './lib/write-scope.js'
18
+ import { RequestStore } from './lib/requests.js'
19
+ import { TaskStore } from './lib/tasks.js'
20
+ import {
21
+ SUBDIR, SessionRegistry, credentialPath, defaultRegistryPath, discoverSiblingWorkdirs,
22
+ ensureSessionLayout, findForeignAncestorAccess, findForeignSessionAccess,
23
+ findForeignSessionAccessInCommand, findSuspiciousSearchPattern, inboxCount,
24
+ canonicalPath, configureFileLocks, isDirectory, isSessionId, listInbox, markRead, migrateSessionArchive, mkdirp, readJson, sendMessage, writeJson,
25
+ } from './lib/layout.js'
26
+
27
+ /** Cordis plugin name used by Loader diagnostics. */
28
+ export const name = 'dsh-collab-sessions'
29
+
30
+ /** Services required for session discovery, tools, prompts, and the working directory. */
31
+ export const inject = ['tools', 'agents', 'systemPrompt', 'workingDirectory', 'commands']
32
+
33
+ /** Agent preset id created by the sidebar entry and declared by the bundle patch. */
34
+ const PRESET = 'collab'
35
+
36
+ /** Coordinator preset; it shares the collaboration layout but not implementation tools. */
37
+ const SUPERVISOR = 'supervisor'
38
+
39
+ const COLLAB_PRESETS = new Set([PRESET, SUPERVISOR])
40
+
41
+ const MAX_MESSAGE_BYTES = 64 * 1024
42
+
43
+ /** Upper bound for one session's configured base prompt. */
44
+ const MAX_BASE_PROMPT = 16 * 1024
45
+
46
+ const TEXT_OUTPUT = {
47
+ schema: { type: 'string' },
48
+ render(_args, value) {
49
+ return [{ type: 'text', text: typeof value === 'string' ? value : JSON.stringify(value) }]
50
+ },
51
+ }
52
+
53
+ const NO_PARAMETERS = { type: 'object', properties: {} }
54
+
55
+ const SEND_PARAMETERS = {
56
+ type: 'object',
57
+ properties: {
58
+ target: { type: 'string', description: 'Exact target session id (session-...). Use collab_peers to find it.' },
59
+ message: { type: 'string', description: 'Message text for the target session.' },
60
+ },
61
+ required: ['target', 'message'],
62
+ additionalProperties: false,
63
+ }
64
+
65
+ const INBOX_PARAMETERS = {
66
+ type: 'object',
67
+ properties: {
68
+ peer: { type: 'string', description: 'Optional peer session id to read only that pair.' },
69
+ mark_read: { type: 'boolean', description: 'Whether to move read messages into the pair read directory. Defaults to true.' },
70
+ },
71
+ additionalProperties: false,
72
+ }
73
+
74
+ const TASK_CREATE_PARAMETERS = {
75
+ type: 'object',
76
+ properties: {
77
+ title: { type: 'string', description: 'Short task title.' },
78
+ instruction: { type: 'string', description: 'Self-contained instructions for the worker.' },
79
+ acceptance: { type: 'string', description: 'Acceptance criteria the supervisor will verify.' },
80
+ inputs: { type: 'object', description: 'Optional structured inputs for the worker.' },
81
+ taskId: { type: 'string', description: 'Optional parent task id; omitted creates the task for this requirement.' },
82
+ },
83
+ required: ['title', 'instruction'],
84
+ additionalProperties: false,
85
+ }
86
+
87
+ const TASK_ASSIGN_PARAMETERS = {
88
+ type: 'object',
89
+ properties: {
90
+ subtaskId: { type: 'string', description: 'Subtask id (subtask-...); taskId is accepted for legacy callers.' },
91
+ taskId: { type: 'string', description: 'Legacy subtask id alias.' },
92
+ worker: { type: 'string', description: 'Worker session id with an offer relationship.' },
93
+ },
94
+ required: ['worker'],
95
+ additionalProperties: false,
96
+ }
97
+
98
+ const TASK_ID_PARAMETERS = {
99
+ type: 'object',
100
+ properties: {
101
+ taskId: { type: 'string', description: 'Task id (task-...).' },
102
+ },
103
+ required: ['taskId'],
104
+ additionalProperties: false,
105
+ }
106
+
107
+ const TASK_LIST_PARAMETERS = {
108
+ type: 'object',
109
+ properties: {
110
+ status: { type: 'string', description: 'Optional status filter.' },
111
+ },
112
+ additionalProperties: false,
113
+ }
114
+
115
+ const TASK_REJECT_PARAMETERS = {
116
+ type: 'object',
117
+ properties: {
118
+ taskId: { type: 'string' },
119
+ reason: { type: 'string', description: 'Why the delivered result is rejected.' },
120
+ },
121
+ required: ['taskId', 'reason'],
122
+ additionalProperties: false,
123
+ }
124
+
125
+ const TASK_PROGRESS_PARAMETERS = {
126
+ type: 'object',
127
+ properties: {
128
+ taskId: { type: 'string' },
129
+ note: { type: 'string' },
130
+ },
131
+ required: ['taskId', 'note'],
132
+ additionalProperties: false,
133
+ }
134
+
135
+ const TASK_COMPLETE_PARAMETERS = {
136
+ type: 'object',
137
+ properties: {
138
+ taskId: { type: 'string' },
139
+ summary: { type: 'string', description: 'Concise result summary.' },
140
+ details: { type: 'string', description: 'Optional longer result details.' },
141
+ artifacts: {
142
+ type: 'array',
143
+ items: { type: 'string' },
144
+ description: 'Optional paths under the delivery subdirectory.',
145
+ },
146
+ },
147
+ required: ['taskId', 'summary'],
148
+ additionalProperties: false,
149
+ }
150
+
151
+ const TASK_FAIL_PARAMETERS = {
152
+ type: 'object',
153
+ properties: {
154
+ taskId: { type: 'string' },
155
+ reason: { type: 'string' },
156
+ },
157
+ required: ['taskId', 'reason'],
158
+ additionalProperties: false,
159
+ }
160
+
161
+ const TASK_CLOSE_PARAMETERS = {
162
+ type: 'object',
163
+ properties: {
164
+ taskId: { type: 'string' },
165
+ },
166
+ required: ['taskId'],
167
+ additionalProperties: false,
168
+ }
169
+
170
+ const DELIVERY_LIST_PARAMETERS = {
171
+ type: 'object',
172
+ properties: {
173
+ taskId: { type: 'string', description: 'Optional task id; omitted lists only this supervisor\'s tasks.' },
174
+ },
175
+ additionalProperties: false,
176
+ }
177
+
178
+ const DELIVERY_MANIFEST_PARAMETERS = {
179
+ type: 'object',
180
+ properties: {
181
+ taskId: { type: 'string' },
182
+ },
183
+ required: ['taskId'],
184
+ additionalProperties: false,
185
+ }
186
+
187
+ const REQUEST_DELIVER_PARAMETERS = {
188
+ type: 'object',
189
+ properties: {
190
+ requestId: { type: 'string' },
191
+ },
192
+ required: ['requestId'],
193
+ additionalProperties: false,
194
+ }
195
+
196
+
197
+ const REQUEST_SUBMIT_PARAMETERS = {
198
+ type: 'object',
199
+ properties: {
200
+ supervisor: { type: 'string', description: 'Target supervisor id. Required when more than one authorized supervisor is available.' },
201
+ title: { type: 'string', description: 'Short request title.' },
202
+ requirement: { type: 'string', description: 'Outcome-focused requirement and acceptance criteria. Do not name workers, projects, tasks, delivery paths, or internal scheduling.' },
203
+ },
204
+ required: ['title', 'requirement'],
205
+ additionalProperties: false,
206
+ }
207
+
208
+ const REQUEST_LIST_PARAMETERS = {
209
+ type: 'object',
210
+ properties: {
211
+ status: { type: 'string', description: 'Optional status filter.' },
212
+ },
213
+ additionalProperties: false,
214
+ }
215
+
216
+ const REQUEST_ACCEPT_PARAMETERS = {
217
+ type: 'object',
218
+ properties: {
219
+ requestId: { type: 'string' },
220
+ taskId: { type: 'string', description: 'Task containing the subtasks created for this request.' },
221
+ response: { type: 'string', description: 'Optional message for the requester.' },
222
+ },
223
+ required: ['requestId', 'taskId'],
224
+ additionalProperties: false,
225
+ }
226
+
227
+ const REQUEST_REJECT_PARAMETERS = {
228
+ type: 'object',
229
+ properties: {
230
+ requestId: { type: 'string' },
231
+ reason: { type: 'string', description: 'Why the registered capabilities cannot satisfy this request; name the missing capability.' },
232
+ },
233
+ required: ['requestId', 'reason'],
234
+ additionalProperties: false,
235
+ }
236
+
237
+ const REQUEST_CANCEL_PARAMETERS = {
238
+ type: 'object',
239
+ properties: {
240
+ requestId: { type: 'string' },
241
+ },
242
+ required: ['requestId'],
243
+ additionalProperties: false,
244
+ }
245
+
246
+ const REQUEST_HEARTBEAT_PARAMETERS = {
247
+ type: 'object',
248
+ properties: {
249
+ requestId: { type: 'string' },
250
+ note: { type: 'string', description: 'Optional progress note for the requester.' },
251
+ extendByMs: { type: 'number', description: 'Optional execution deadline extension in milliseconds, capped at seven days.' },
252
+ },
253
+ required: ['requestId'],
254
+ additionalProperties: false,
255
+ }
256
+
257
+ function describeError(error) {
258
+ return error instanceof Error ? error.message : String(error)
259
+ }
260
+
261
+ function iso(time) {
262
+ return typeof time === 'number' && Number.isFinite(time) ? new Date(time).toISOString() : 'unknown'
263
+ }
264
+
265
+ /** Prompt text visible only inside a collaboration session. */
266
+ function promptText(sessionId, layout, role, relationships, capabilityLines = []) {
267
+ const basePrompt = typeof layout.meta.basePrompt === 'string' ? layout.meta.basePrompt.trim() : ''
268
+ const baseSection = basePrompt.length === 0
269
+ ? []
270
+ : ['Session base prompt (role and constraints for this session; apply it to every turn):', basePrompt, '']
271
+ const header = [
272
+ ...baseSection,
273
+ `This is ${role === 'supervisor' ? 'supervisor' : 'collaboration'} session ${sessionId}.`,
274
+ `Its working directory is ${layout.workdir}; it contains exactly two collaboration directories:`,
275
+ `- comm/<peerSessionId>/ holds credential.json plus inbox/ (unread inbound), outbox/ (sent), archive/inbox/ (read inbound), and archive/outbox/ (explicitly archived sent).`,
276
+ `- private/ belongs only to this session; it is mode 0700.`,
277
+ `Never read, write, search, or infer another session's working directory (comm or private): the tool guard denies it.`,
278
+ `Recursive searches and shells rooted above another session's working directory are also refused; use the task tools instead.`,
279
+ `Workspace: ${layout.meta.originalCwd}.`,
280
+ '',
281
+ ]
282
+ if (role === 'supervisor') {
283
+ return [
284
+ ...header,
285
+ ...(capabilityLines.length === 0 ? [] : [
286
+ 'Current registered capabilities (live; re-check before decomposition):',
287
+ ...capabilityLines,
288
+ '',
289
+ ]),
290
+ 'You are the SUPERVISOR. You do not implement anything yourself.',
291
+ 'You only decompose requirements, assign tasks to registered functional sessions, verify results, retry/reject, and deliver.',
292
+ 'You have no shell, file, office, web, or edit tools. Never try to perform a task yourself.',
293
+ '',
294
+ 'Coordination tools:',
295
+ '- collab_inbox reads messages from any authorized peer, including task/request notifications. Call it at the start of every turn.',
296
+ '- collab_peers / collab_send are ordinary communication tools for authorized peers. Chat does not create or change tasks.',
297
+ '- collab_requests lists work requests. For each pending request, evaluate registered capabilities before accepting or rejecting.',
298
+ '- collab_capabilities lists the functional sessions registered to you, their capabilities, online/authorization state, and workload.',
299
+ '- collab_task_create creates a subtask; omitting taskId creates the parent task for the requirement.',
300
+ '- collab_task_assign assigns a task to a worker with an offer relationship and wakes it.',
301
+ '- collab_tasks / collab_task_result inspect progress and results.',
302
+ '- collab_task_retry / collab_task_reject / collab_task_cancel manage failures and revisions.',
303
+ '- collab_task_close closes a task after all its subtasks finish.',
304
+ '- collab_delivery_list lists the canonical shared delivery files (names/sizes/times).',
305
+ '- collab_delivery_manifest writes a task manifest with path, bytes, sha256, and mode.',
306
+ '- collab_request_deliver sends the sanitized manifest to an accepted requester.',
307
+ '',
308
+ 'How to work:',
309
+ '0. At the start of every turn, read collab_requests. For each pending request, evaluate the registered capabilities. If the request is feasible, create a task and subtasks, assign at least one subtask to an offered worker, then call collab_request_accept with the taskId. If it is not feasible, call collab_request_reject and name the missing capability. Never implement the request yourself.',
310
+ 'Never send task IDs, subtask IDs, worker IDs, task decomposition, or internal scheduling to the requester. The requester receives only acceptance/rejection status and the sanitized delivery manifest.',
311
+ '1. Read the requirement, list capabilities, and plan subtasks with explicit acceptance criteria. Use one taskId per requirement: the first collab_task_create returns it; pass it to the remaining subtasks.',
312
+ 'Capabilities are live and versioned. Call collab_capabilities immediately before decomposing tasks; never rely on capability text remembered from an earlier turn. If a capability version changed, re-evaluate the decomposition.',
313
+ '2. Assign each task to a worker whose capability matches; never assign to yourself or to another supervisor.',
314
+ '3. End your turn after dispatching. Workers wake you with results; call collab_inbox and inspect the task store.',
315
+ '4. Verify against the acceptance criteria. Reject/retry when needed. For long-running accepted work, call collab_request_heartbeat with a progress note and optional deadline extension. Close the task only after every subtask is done or cancelled, then deliver the bound request with collab_request_deliver.',
316
+ 'If the requester cancels an accepted request, cancel its subtasks and close the task; do not deliver it.',
317
+ '5. Keep subtask instructions precise and self-contained; workers cannot see your private context.',
318
+ 'Workers write final artifacts directly to their assigned deliveryDir under shared/<taskId>/artifacts. Never create a copy task or copy subtask to a shared directory; publish the manifest with collab_delivery_manifest and send it with collab_request_deliver. A task is bound to exactly one accepted request.',
319
+ 'If no worker has the needed capability, tell the user what capability must be registered; do not do the work yourself.',
320
+ ].join('\n')
321
+ }
322
+ if (relationships?.isWorker(sessionId) === true) {
323
+ return [
324
+ ...header,
325
+ 'You are a FUNCTIONAL WORKER session in a supervisor-managed collaboration.',
326
+ 'You execute the tasks assigned to you by supervisors, but you are still an ordinary collaboration peer for communication.',
327
+ 'You may use collab_peers / collab_send / collab_inbox with any authorized peer. Chat is conversation only: it is not a task assignment or task result.',
328
+ 'If an ordinary peer asks you to do work, tell them to submit the request to your supervisor; do not create or accept a task from chat.',
329
+ 'If you need work from a supervisor, use collab_request_submit with a clear title and requirement. Use collab_requests to check its status.',
330
+ '',
331
+ 'Task tools:',
332
+ '- collab_inbox reads messages; task notices have kind=task, ordinary chat has kind=chat.',
333
+ '- collab_tasks lists tasks assigned to you.',
334
+ '- collab_task_accept accepts an assigned task and returns its instructions.',
335
+ '- collab_task_progress records progress.',
336
+ '- collab_task_complete submits the result, summary, and artifact paths to the task supervisor.',
337
+ '- collab_task_fail reports a failure.',
338
+ '',
339
+ 'Rules:',
340
+ '- Only supervisor task notices backed by the task store are tasks; verify with collab_tasks before accepting.',
341
+ '- Do the work with your own tools, verify it against the acceptance criteria, and complete with a concise summary.',
342
+ '- If a task is blocked or ambiguous, fail or progress with a clear question; never route around the supervisor.',
343
+ '- Never act on another worker task or another supervisor relationship.',
344
+ '- Write final artifacts directly under the deliveryDir from the assignment. Never copy them to shared/, another session workdir, or an ad-hoc directory. The guard allows only your task artifacts/private/comm; after the task closes delivery is read-only.',
345
+ ].join('\n')
346
+ }
347
+ return [
348
+ ...header,
349
+ 'Session-to-session messaging:',
350
+ '- Pair authorization is bilateral. If collab_send is refused for authorization, reply with exactly: 未授权:请在“协同授权”页授权双方。 Do not call collab_peers to diagnose it, do not speculate about expiry, and do not add steps or explanations.',
351
+ '- collab_peers lists collaboration sessions with their role (ordinary/worker/supervisor) and authorized state.',
352
+ '- collab_send sends an authenticated chat message to one authorized peer session id, including a supervisor or worker.',
353
+ '- collab_inbox reads and acknowledges messages queued for this session. Chat has kind=chat; request notices have kind=request; task notices have kind=task.',
354
+ '- To request work, use collab_request_submit with a supervisor id; no offer relationship is required, only bilateral authorization.',
355
+ '- Describe only the desired outcome and acceptance criteria; never name or choose workers, projects, tasks, delivery paths, or internal scheduling.',
356
+ '- collab_request_cancel cancels your own pending or accepted request; accepted cancellation notifies the supervisor and ends delivery eligibility.',
357
+ '- Chat never creates, accepts, or completes a task. Task state belongs to the task store and task tools.',
358
+ 'A live peer receives a notification in its next step; a cold peer is resumed first. The body is read with collab_inbox.',
359
+ 'When waiting for a peer reply, end your turn or use wait_agent; a running Agent is steered into its next step, so the wait returns promptly.',
360
+ 'Reply with collab_send to the sender session id.',
361
+ 'Keep credentials in comm/<peer>/credential.json and never paste a token into a message or a private file.',
362
+ ].join('\n')
363
+ }
364
+
365
+ /** The original project directory is the immutable header cwd. */
366
+ function resolveOriginalCwd(ctx, session) {
367
+ const headerCwd = session?.header?.cwd
368
+ if (typeof headerCwd === 'string' && headerCwd.length > 0) return headerCwd
369
+ const current = ctx.workingDirectory.get(session)
370
+ const suffix = `${path.sep}${path.join(SUBDIR, 'sessions', session.id)}`
371
+ const resolved = path.resolve(current)
372
+ if (resolved.endsWith(suffix)) return resolved.slice(0, -suffix.length) || path.sep
373
+ return current
374
+ }
375
+
376
+ function wakeText(message) {
377
+ return [
378
+ `[collab] A message from collaboration session ${message.from} is queued (message id ${message.id}).`,
379
+ 'Call collab_inbox to read and acknowledge it. Reply with collab_send target "' + message.from + '".',
380
+ ].join('\n')
381
+ }
382
+
383
+ function makeWakeMessage(message) {
384
+ return {
385
+ id: crypto.randomUUID(),
386
+ role: 'user',
387
+ content: [{ type: 'text', text: wakeText(message) }],
388
+ source: { kind: 'collab-session', fromSessionId: message.from, messageId: message.id },
389
+ }
390
+ }
391
+
392
+ /** Register the plugin. */
393
+ export function apply(ctx, config = {}) {
394
+ configureFileLocks({
395
+ timeoutMs: config.lockTimeoutMs,
396
+ staleMs: config.lockStaleMs,
397
+ })
398
+ const dshHomePath = ctx.get('dshHomePath')
399
+ const registryPath = typeof config.registryPath === 'string' && config.registryPath.length > 0
400
+ ? config.registryPath
401
+ : (typeof dshHomePath === 'function' ? dshHomePath('collab', 'registry.json') : defaultRegistryPath())
402
+ const sharedRoot = typeof config.sharedRoot === 'string' && config.sharedRoot.length > 0
403
+ ? path.resolve(config.sharedRoot)
404
+ : path.join(path.dirname(registryPath), 'shared')
405
+ const requestTimeoutMs = Number.isFinite(Number(config.requestTimeoutMs))
406
+ ? Math.max(100, Number(config.requestTimeoutMs))
407
+ : 10 * 60 * 1000
408
+ const executionTimeoutMs = Number.isFinite(Number(config.executionTimeoutMs))
409
+ ? Math.max(100, Number(config.executionTimeoutMs))
410
+ : 24 * 60 * 60 * 1000
411
+ const perSessionSandbox = config.perSessionSandbox !== false && process.platform !== 'win32'
412
+ const registry = new SessionRegistry(registryPath)
413
+ const auth = new AuthorizationStore(
414
+ typeof config.authorizationPath === 'string' && config.authorizationPath.length > 0
415
+ ? config.authorizationPath
416
+ : authorizationPathFor(registryPath),
417
+ )
418
+ const relationships = new RelationshipStore(
419
+ typeof config.relationshipsPath === 'string' && config.relationshipsPath.length > 0
420
+ ? config.relationshipsPath
421
+ : path.join(path.dirname(registryPath), 'relationships.json'),
422
+ )
423
+ const tasks = new TaskStore(
424
+ typeof config.tasksPath === 'string' && config.tasksPath.length > 0
425
+ ? config.tasksPath
426
+ : path.join(path.dirname(registryPath), 'tasks.json'),
427
+ )
428
+ const requests = new RequestStore(
429
+ typeof config.requestsPath === 'string' && config.requestsPath.length > 0
430
+ ? config.requestsPath
431
+ : path.join(path.dirname(registryPath), 'requests.json'),
432
+ )
433
+ const notices = new NoticeStore(
434
+ typeof config.noticesPath === 'string' && config.noticesPath.length > 0
435
+ ? config.noticesPath
436
+ : path.join(path.dirname(registryPath), 'notices.json'),
437
+ )
438
+ const requestTimers = new Map()
439
+ const executionTimers = new Map()
440
+ const sandboxDeliveryRoots = new Map()
441
+ const sandboxReadRoots = new Map()
442
+ const deliveryInFlight = new Set()
443
+ let noticeFlushInFlight = false
444
+ /** Human-facing authorization operations shared by the UI Remote and commands. */
445
+ const collabAdmin = {
446
+ listAuth: () => ({
447
+ pairs: auth.listPairs(),
448
+ pending: auth.listPending(),
449
+ }),
450
+ authorize: (a, b) => {
451
+ const known = (id) => collabSessions.has(id)
452
+ || (registry.get(id)?.preset === 'collab' || registry.get(id)?.preset === 'supervisor')
453
+ if (!known(a) || !known(b)) throw new Error('authorization requires two known collaboration sessions')
454
+ auth.authorize(a, b, 'ui')
455
+ return collabAdmin.listAuth()
456
+ },
457
+ revoke: (a, b) => {
458
+ auth.revoke(a, b)
459
+ return collabAdmin.listAuth()
460
+ },
461
+ }
462
+ ctx.effect(() => {
463
+ const dispose = ctx.provide('collabAdmin', collabAdmin)
464
+ return () => { dispose() }
465
+ }, 'collab:admin-service')
466
+ /** Turn number of the current tool call, used to locate tasks in the chat. */
467
+ const callTurns = new Map()
468
+ /** Preset chosen for each collaboration session (collab or supervisor). */
469
+ const sessionPresets = new Map()
470
+ /** Session ids whose layout is ready and whose prompt section is installed. */
471
+ const collabSessions = new Set()
472
+ /** Per-agent prompt fibers, disposed with the agent or with this plugin. */
473
+ const promptFibers = new Map()
474
+
475
+ const warn = (message) => {
476
+ try { ctx.logger.warn(`[collab] ${message}`) } catch { console.warn(`[collab] ${message}`) }
477
+ }
478
+
479
+ const workspacePaths = () => {
480
+ const workspaces = ctx.get('workspaceRegistry')
481
+ if (workspaces === undefined) return []
482
+ try {
483
+ return workspaces.list().map(workspace => workspace.path)
484
+ } catch {
485
+ return []
486
+ }
487
+ }
488
+
489
+ const refreshRegistry = () => {
490
+ try { registry.scanWorkspaces(workspacePaths()) } catch (error) { warn(`registry scan failed: ${describeError(error)}`) }
491
+ }
492
+
493
+ const disposePrompt = (sessionId) => {
494
+ const entry = promptFibers.get(sessionId)
495
+ if (entry === undefined) return
496
+ promptFibers.delete(sessionId)
497
+ try {
498
+ const disposing = entry.fiber.dispose()
499
+ if (disposing !== undefined && typeof disposing.catch === 'function') {
500
+ void disposing.catch((error) => { warn(`prompt cleanup failed: ${describeError(error)}`) })
501
+ }
502
+ } catch (error) {
503
+ warn(`prompt cleanup failed: ${describeError(error)}`)
504
+ }
505
+ }
506
+
507
+ const installPrompt = (agent, layout, role = PRESET) => {
508
+ const previous = promptFibers.get(agent.id)
509
+ if (previous !== undefined) {
510
+ if (previous.agent === agent && previous.layout?.workdir === layout.workdir) return
511
+ disposePrompt(agent.id)
512
+ }
513
+ try {
514
+ const fiber = agent.ctx.inject(['systemPrompt'], (scope) => {
515
+ scope.systemPrompt.section({
516
+ name: 'collab:session',
517
+ order: scope.systemPrompt.getSectionOrder('TOOL_SUBAGENT'),
518
+ text: () => promptText(agent.id, layout, role, relationships, role === SUPERVISOR ? capabilityRoster(agent.id) : []),
519
+ })
520
+ })
521
+ promptFibers.set(agent.id, { agent, fiber, layout, role })
522
+ } catch (error) {
523
+ warn(`could not install the collaboration prompt for ${agent.id}: ${describeError(error)}`)
524
+ }
525
+ }
526
+
527
+ const bindDeliverySandbox = (sessionId, directory, writable = true) => {
528
+ const resolved = path.resolve(directory)
529
+ const reads = sandboxReadRoots.get(sessionId) ?? new Set()
530
+ reads.add(resolved)
531
+ sandboxReadRoots.set(sessionId, reads)
532
+ if (writable) {
533
+ const writes = sandboxDeliveryRoots.get(sessionId) ?? new Set()
534
+ writes.add(resolved)
535
+ sandboxDeliveryRoots.set(sessionId, writes)
536
+ }
537
+ try { mkdirp(directory, 0o755) } catch { /* the assignment will report a real mkdir failure */ }
538
+ }
539
+
540
+ const sharedRootVariants = () => {
541
+ const forward = sharedRoot.replaceAll('\\', '/')
542
+ return forward === sharedRoot ? [sharedRoot] : [sharedRoot, forward]
543
+ }
544
+ const commandMentionsSharedRoot = (command) => {
545
+ const text = process.platform === 'win32' ? String(command).toLowerCase() : String(command)
546
+ return sharedRootVariants().some(root => text.includes(process.platform === 'win32' ? root.toLowerCase() : root))
547
+ }
548
+ const sharedCommandAllowed = (command, sessionId) => {
549
+ if (!isManagedWorker(sessionId)) return false
550
+ const roots = [...(sandboxReadRoots.get(sessionId) ?? [])].map(root => canonicalPath(root))
551
+ if (roots.length === 0) return false
552
+ const text = String(command)
553
+ const haystack = process.platform === 'win32' ? text.toLowerCase() : text
554
+ const comparable = (value) => process.platform === 'win32' ? value.toLowerCase() : value
555
+ for (const root of sharedRootVariants()) {
556
+ const needle = process.platform === 'win32' ? root.toLowerCase() : root
557
+ let cursor = 0
558
+ while (true) {
559
+ const index = haystack.indexOf(needle, cursor)
560
+ if (index < 0) break
561
+ const token = text.slice(index).split(/[\s;&|"'`]+/u)[0]
562
+ const resolved = canonicalPath(token)
563
+ if (!roots.some(owned => comparable(resolved) === comparable(owned) || comparable(resolved).startsWith(`${comparable(owned)}${path.sep}`))) {
564
+ return false
565
+ }
566
+ cursor = index + needle.length
567
+ }
568
+ }
569
+ return true
570
+ }
571
+
572
+ const releaseDeliverySandbox = (sessionId, directory) => {
573
+ const roots = sandboxDeliveryRoots.get(sessionId)
574
+ if (roots === undefined) return
575
+ roots.delete(path.resolve(directory))
576
+ if (roots.size === 0) sandboxDeliveryRoots.delete(sessionId)
577
+ }
578
+
579
+ const installSandboxWrapper = (policy) => {
580
+ if (!perSessionSandbox) return
581
+ if (policy === undefined || typeof policy.resolve !== 'function') return
582
+ const original = policy.resolve.bind(policy)
583
+ const wrapped = (request = {}) => {
584
+ const resolved = original(request)
585
+ const session = request?.session
586
+ if (session === undefined || resolved.mode !== 'workspace-write') return resolved
587
+ const entry = registry.get(session.id)
588
+ if (entry === undefined) return resolved
589
+ const roots = sandboxDeliveryRoots.get(session.id)
590
+ const additional = roots === undefined
591
+ ? resolved.additionalWritableRoots
592
+ : [...new Set([...(resolved.additionalWritableRoots ?? []), ...roots])]
593
+ return {
594
+ ...resolved,
595
+ workspaceRoot: entry.workdir,
596
+ ...(additional === undefined || additional.length === 0 ? {} : { additionalWritableRoots: additional }),
597
+ }
598
+ }
599
+ try {
600
+ policy.resolve = wrapped
601
+ } catch (error) {
602
+ warn(`could not install per-session OS sandbox: ${describeError(error)}`)
603
+ return
604
+ }
605
+ ctx.effect(() => () => {
606
+ try { policy.resolve = original } catch { /* best effort */ }
607
+ }, 'collab:per-session-sandbox')
608
+ }
609
+
610
+ const installPerSessionSandbox = () => {
611
+ if (!perSessionSandbox) return
612
+ if (typeof ctx.inject === 'function') {
613
+ ctx.inject(['sandboxPolicy'], (scope) => {
614
+ installSandboxWrapper(scope.sandboxPolicy)
615
+ })
616
+ return
617
+ }
618
+ installSandboxWrapper(ctx.get('sandboxPolicy'))
619
+ }
620
+
621
+ const setupAgent = async (agent, { force = false, preset } = {}) => {
622
+ try {
623
+ const session = agent.session
624
+ if (session === undefined) return false
625
+ if (session.header?.origin === 'subagent') return false
626
+ // A reused blank Session records the requested preset as a durable
627
+ // `agent-preset/selected` event, so the header is not authoritative.
628
+ const currentPreset = ctx.get('agentPresets')?.presetForSession(session) ?? session.header?.agentPreset
629
+ const effectivePreset = force && typeof preset === 'string' ? preset : currentPreset
630
+ if (!COLLAB_PRESETS.has(effectivePreset)) return false
631
+ const role = effectivePreset === SUPERVISOR ? SUPERVISOR : PRESET
632
+ // The Session belongs to the Workspace it was created in; the plugin
633
+ // gives it a per-session working directory inside that Workspace.
634
+ const registeredOriginal = registry.get(agent.id)?.originalCwd
635
+ const originalCwd = typeof registeredOriginal === 'string'
636
+ ? registeredOriginal
637
+ : resolveOriginalCwd(ctx, session)
638
+ const layout = ensureSessionLayout({ originalCwd, sessionId: agent.id, preset: effectivePreset })
639
+ try {
640
+ registry.upsert({
641
+ sessionId: agent.id,
642
+ preset: effectivePreset,
643
+ originalCwd,
644
+ workdir: layout.workdir,
645
+ createdAt: layout.meta.createdAt,
646
+ updatedAt: Date.now(),
647
+ })
648
+ } catch (error) {
649
+ warn(`could not update the collaboration registry: ${describeError(error)}`)
650
+ }
651
+ // Move once. Later resumes must not undo a user- or model-initiated `cd`.
652
+ if (layout.meta.workingDirectorySet !== true) {
653
+ try {
654
+ const current = ctx.workingDirectory.get(session)
655
+ if (path.resolve(current) !== path.resolve(layout.workdir)) {
656
+ await ctx.workingDirectory.set(agent, layout.workdir)
657
+ }
658
+ layout.meta.workingDirectorySet = true
659
+ layout.meta.updatedAt = Date.now()
660
+ writeJson(path.join(layout.workdir, 'session.json'), layout.meta, 0o600)
661
+ } catch (error) {
662
+ warn(`could not move ${agent.id} into ${layout.workdir}: ${describeError(error)}`)
663
+ return false
664
+ }
665
+ }
666
+ installPrompt(agent, layout, role)
667
+ collabSessions.add(agent.id)
668
+ sessionPresets.set(agent.id, effectivePreset)
669
+ for (const task of tasks.listForWorker(agent.id)) {
670
+ const project = tasks.project(task.taskId)
671
+ bindDeliverySandbox(agent.id, deliveryRoot(task.taskId), project?.status === 'open')
672
+ }
673
+ return true
674
+ } catch (error) {
675
+ warn(`session setup failed for ${agent?.id}: ${describeError(error)}`)
676
+ return false
677
+ }
678
+ }
679
+
680
+ const requireSelf = (exec) => {
681
+ const sessionId = exec?.agent?.id
682
+ if (!isSessionId(sessionId)) throw new Error('collaboration tools require a live session')
683
+ let entry = registry.get(sessionId)
684
+ if (entry === undefined) {
685
+ refreshRegistry()
686
+ entry = registry.get(sessionId)
687
+ }
688
+ if (entry === undefined || !collabSessions.has(sessionId)) {
689
+ throw new Error('this session is not initialized as a collaboration session')
690
+ }
691
+ return entry
692
+ }
693
+
694
+ const isSupervisorSession = (sessionId) => sessionPresets.get(sessionId) === SUPERVISOR
695
+ const isManagedWorker = (sessionId) => relationships.isWorker(sessionId)
696
+
697
+ /** Communication is role-agnostic; inboxText filters by bilateral authorization. */
698
+ const inboxPeerAllowed = () => true
699
+
700
+ /** Deliver one task protocol message through the authenticated pair transport. */
701
+ const deliverTaskNotice = async (self, targetId, payload) => {
702
+ if (!auth.isAuthorized(self.sessionId, targetId)) {
703
+ throw new Error('未授权:请在“协同授权”页授权双方。')
704
+ }
705
+ const peer = registry.get(targetId)
706
+ if (peer === undefined) throw new Error(`unknown collaboration session: ${targetId}`)
707
+ if (typeof peer.workdir !== 'string' || !isDirectory(peer.workdir)) {
708
+ throw new Error(`target working directory is missing: ${String(peer.workdir)}`)
709
+ }
710
+ const message = sendMessage({
711
+ selfId: self.sessionId,
712
+ selfWorkdir: self.workdir,
713
+ peerId: peer.sessionId,
714
+ peerWorkdir: peer.workdir,
715
+ kind: String(payload?.type ?? '').includes('request') ? 'request' : 'task',
716
+ text: JSON.stringify(payload),
717
+ })
718
+ return wakePeer(peer.sessionId, message)
719
+ }
720
+
721
+ /** Queue before sending so a committed state change cannot lose its wake-up. */
722
+ const sendTaskNotice = async (self, targetId, payload) => {
723
+ const notice = notices.enqueue({ from: self.sessionId, to: targetId, payload })
724
+ try {
725
+ const delivery = await deliverTaskNotice(self, targetId, payload)
726
+ notices.remove(notice.id)
727
+ return delivery
728
+ } catch (error) {
729
+ notices.fail(notice.id, error)
730
+ warn(`notice ${notice.id} queued for ${targetId}: ${describeError(error)}`)
731
+ return `queued (${describeError(error)})`
732
+ }
733
+ }
734
+
735
+ const flushNotices = async () => {
736
+ if (noticeFlushInFlight) return
737
+ noticeFlushInFlight = true
738
+ try {
739
+ notices.prune()
740
+ for (const notice of notices.list()) {
741
+ // Let the originating send finish first; a crash leaves it eligible
742
+ // for the next sweep after the grace period.
743
+ if (notice.attempts === 0 && Date.now() - notice.createdAt < 30000) continue
744
+ const sender = registry.get(notice.from)
745
+ if (sender === undefined || typeof sender.workdir !== 'string') continue
746
+ try {
747
+ await deliverTaskNotice(
748
+ { sessionId: sender.sessionId, workdir: sender.workdir },
749
+ notice.to,
750
+ notice.payload,
751
+ )
752
+ notices.remove(notice.id)
753
+ } catch (error) {
754
+ notices.fail(notice.id, error)
755
+ }
756
+ }
757
+ } finally {
758
+ noticeFlushInFlight = false
759
+ }
760
+ }
761
+
762
+ const deliveryRoot = (projectId) => path.join(sharedRoot, projectId ?? 'default', 'artifacts')
763
+
764
+ const peersText = (self) => {
765
+ const entries = registry.list().filter(entry => entry.sessionId !== self.sessionId && COLLAB_PRESETS.has(entry.preset))
766
+ if (entries.length === 0) {
767
+ return 'No other collaboration sessions are registered yet. Create another one from the left sidebar entry.'
768
+ }
769
+ const lines = [`This session: ${self.sessionId}`, '']
770
+ for (const entry of entries) {
771
+ const online = ctx.agents.get(entry.sessionId) !== undefined
772
+ const credential = readJson(credentialPath(self.workdir, entry.sessionId)) !== undefined
773
+ const unread = inboxCount(self.workdir, entry.sessionId)
774
+ const authorized = auth.isAuthorized(self.sessionId, entry.sessionId)
775
+ const role = isSupervisorSession(entry.sessionId) ? 'supervisor' : (isManagedWorker(entry.sessionId) ? 'worker' : 'ordinary')
776
+ const title = typeof entry.title === 'string' && entry.title.length > 0 ? ` title=${JSON.stringify(entry.title)}` : ''
777
+ lines.push(
778
+ `- ${entry.sessionId} role=${role} ${online ? 'online' : 'offline'} authorized=${authorized ? 'yes' : 'no'} unread=${unread} credential=${credential ? 'yes' : 'no'}${title}`,
779
+ )
780
+ }
781
+ return lines.join('\n')
782
+ }
783
+
784
+ const infoText = (self) => {
785
+ const peers = registry.list().filter(entry => entry.sessionId !== self.sessionId)
786
+ const lines = [
787
+ `session id: ${self.sessionId}`,
788
+ `preset: ${self.preset}`,
789
+ `working directory: ${self.workdir} (other sessions are denied direct tool access)`,
790
+ `communication directory: ${path.join(self.workdir, 'comm')} (pair-shared files; direct tool access from other sessions is denied)`,
791
+ `private directory: ${path.join(self.workdir, 'private')} (session-only; mode 0700)`,
792
+ `original workspace: ${self.originalCwd}`,
793
+ '',
794
+ `known peers: ${peers.length}`,
795
+ ]
796
+ for (const peer of peers) {
797
+ const unread = inboxCount(self.workdir, peer.sessionId)
798
+ const online = ctx.agents.get(peer.sessionId) !== undefined
799
+ lines.push(`- ${peer.sessionId} ${online ? 'online' : 'offline'} unread=${unread}`)
800
+ }
801
+ return lines.join('\n')
802
+ }
803
+
804
+ const clearRequestTimer = (requestId) => {
805
+ const timer = requestTimers.get(requestId)
806
+ if (timer !== undefined) clearTimeout(timer)
807
+ requestTimers.delete(requestId)
808
+ }
809
+
810
+ const sendRequestExpiredNotice = async (request) => {
811
+ const supervisor = registry.get(request.supervisor)
812
+ if (supervisor === undefined) return
813
+ try {
814
+ await sendTaskNotice(
815
+ { sessionId: supervisor.sessionId, workdir: supervisor.workdir },
816
+ request.requester,
817
+ {
818
+ type: 'collab-task/request-expired',
819
+ version: 1,
820
+ requestId: request.id,
821
+ title: request.title,
822
+ reason: request.reason,
823
+ },
824
+ )
825
+ } catch (error) {
826
+ warn(`request expiry notice failed for ${request.id}: ${describeError(error)}`)
827
+ }
828
+ }
829
+
830
+ const expireRequest = async (requestId) => {
831
+ const request = requests.get(requestId)
832
+ if (request === undefined || request.status !== 'pending') {
833
+ clearRequestTimer(requestId)
834
+ return
835
+ }
836
+ clearRequestTimer(requestId)
837
+ const expired = requests.expire(requestId)
838
+ await sendRequestExpiredNotice(expired)
839
+ }
840
+
841
+ const scheduleRequestTimeout = (request) => {
842
+ clearRequestTimer(request.id)
843
+ if (request.status !== 'pending' || !Number.isFinite(request.expiresAt)) return
844
+ const delay = Math.max(0, request.expiresAt - Date.now())
845
+ const timer = setTimeout(() => {
846
+ requestTimers.delete(request.id)
847
+ void expireRequest(request.id).catch(error => {
848
+ warn(`request timeout failed for ${request.id}: ${describeError(error)}`)
849
+ })
850
+ }, delay)
851
+ timer.unref?.()
852
+ requestTimers.set(request.id, timer)
853
+ }
854
+
855
+ const sweepRequestTimeouts = () => {
856
+ const now = Date.now()
857
+ for (const request of requests.list()) {
858
+ if (request.status !== 'pending') {
859
+ clearRequestTimer(request.id)
860
+ continue
861
+ }
862
+ if (!Number.isFinite(request.expiresAt)) {
863
+ const updated = requests.update(request.id, (entry) => {
864
+ entry.expiresAt = entry.createdAt + requestTimeoutMs
865
+ }, now)
866
+ scheduleRequestTimeout(updated)
867
+ continue
868
+ }
869
+ if (request.expiresAt <= now) {
870
+ void expireRequest(request.id).catch(error => {
871
+ warn(`request expiry failed for ${request.id}: ${describeError(error)}`)
872
+ })
873
+ } else {
874
+ scheduleRequestTimeout(request)
875
+ }
876
+ }
877
+ }
878
+
879
+ const clearExecutionTimer = (requestId) => {
880
+ const timer = executionTimers.get(requestId)
881
+ if (timer !== undefined) clearTimeout(timer)
882
+ executionTimers.delete(requestId)
883
+ }
884
+
885
+ const sendRequestOverdueNotice = async (request) => {
886
+ const supervisor = registry.get(request.supervisor)
887
+ if (supervisor === undefined) return
888
+ try {
889
+ await sendTaskNotice(
890
+ { sessionId: supervisor.sessionId, workdir: supervisor.workdir },
891
+ request.requester,
892
+ {
893
+ type: 'collab-task/request-overdue',
894
+ version: 1,
895
+ requestId: request.id,
896
+ title: request.title,
897
+ deadline: request.executionDeadlineAt,
898
+ },
899
+ )
900
+ } catch (error) {
901
+ warn(`request overdue notice failed for ${request.id}: ${describeError(error)}`)
902
+ }
903
+ }
904
+
905
+ const markRequestOverdue = async (requestId) => {
906
+ const request = requests.get(requestId)
907
+ if (request === undefined || request.status !== 'accepted' || request.overdue === true) {
908
+ clearExecutionTimer(requestId)
909
+ return
910
+ }
911
+ clearExecutionTimer(requestId)
912
+ const overdue = requests.markOverdue(requestId)
913
+ await sendRequestOverdueNotice(overdue)
914
+ }
915
+
916
+ const scheduleExecutionDeadline = (request) => {
917
+ clearExecutionTimer(request.id)
918
+ if (request.status !== 'accepted' || request.overdue === true || !Number.isFinite(request.executionDeadlineAt)) return
919
+ const delay = Math.max(0, request.executionDeadlineAt - Date.now())
920
+ const timer = setTimeout(() => {
921
+ executionTimers.delete(request.id)
922
+ void markRequestOverdue(request.id).catch(error => {
923
+ warn(`execution deadline failed for ${request.id}: ${describeError(error)}`)
924
+ })
925
+ }, delay)
926
+ timer.unref?.()
927
+ executionTimers.set(request.id, timer)
928
+ }
929
+
930
+ const sweepExecutionDeadlines = () => {
931
+ const now = Date.now()
932
+ for (const request of requests.list()) {
933
+ if (request.status === 'delivered') {
934
+ clearExecutionTimer(request.id)
935
+ continue
936
+ }
937
+ if (request.status !== 'accepted') {
938
+ clearExecutionTimer(request.id)
939
+ continue
940
+ }
941
+ if (request.overdue === true) {
942
+ clearExecutionTimer(request.id)
943
+ continue
944
+ }
945
+ let deadline = request.executionDeadlineAt
946
+ if (!Number.isFinite(deadline)) {
947
+ const acceptedAt = Number.isFinite(request.resolvedAt) ? request.resolvedAt : request.updatedAt
948
+ const updated = requests.update(request.id, (entry) => {
949
+ entry.executionDeadlineAt = acceptedAt + executionTimeoutMs
950
+ }, now)
951
+ deadline = updated.executionDeadlineAt
952
+ }
953
+ if (deadline <= now) {
954
+ void markRequestOverdue(request.id).catch(error => {
955
+ warn(`execution deadline failed for ${request.id}: ${describeError(error)}`)
956
+ })
957
+ } else {
958
+ scheduleExecutionDeadline(request)
959
+ }
960
+ }
961
+ }
962
+
963
+ const wakePeer = async (targetId, message) => {
964
+ // Receiver gate: authorization can be revoked after the sender wrote the
965
+ // file, so delivery re-checks the current pair.
966
+ if (!auth.isAuthorized(message.from, targetId)) {
967
+ return 'blocked(未授权:请在“协同授权”页授权双方)'
968
+ }
969
+ let target = ctx.agents.get(targetId)
970
+ let resumed = false
971
+ if (target === undefined) {
972
+ try {
973
+ const handle = await ctx.agents.resume({ resumeSessionId: targetId })
974
+ target = handle.agent
975
+ resumed = true
976
+ } catch (error) {
977
+ // A concurrent wake may have resumed it between the lookup and here.
978
+ target = ctx.agents.get(targetId)
979
+ if (target === undefined) {
980
+ return `queued (target is not live and resume failed: ${describeError(error)})`
981
+ }
982
+ }
983
+ }
984
+ try {
985
+ const wake = makeWakeMessage(message)
986
+ // A running Agent (for example one inside wait_agent) must receive the
987
+ // notification in its NEXT STEP; followup would queue it for the next
988
+ // turn and leave wait_agent blocked until its timeout.
989
+ if (target.status === 'running' && typeof target.steer === 'function') {
990
+ target.steer(wake)
991
+ return 'delivered live (steered into the target\'s next step; the message stays queued until collab_inbox runs)'
992
+ }
993
+ if (typeof target.followup === 'function') {
994
+ target.followup(wake)
995
+ return resumed
996
+ ? 'delivered live (target resumed and woken; the message stays queued until collab_inbox runs)'
997
+ : 'delivered live (target woken; the message stays queued until collab_inbox runs)'
998
+ }
999
+ if (typeof target.inject === 'function') {
1000
+ target.inject(wake)
1001
+ return 'delivered to the live target inbox (the message stays queued until collab_inbox runs)'
1002
+ }
1003
+ return 'queued (target agent does not accept inbox messages)'
1004
+ } catch (error) {
1005
+ return `queued (live delivery failed: ${describeError(error)})`
1006
+ }
1007
+ }
1008
+
1009
+ const inboxText = (self, peer, markReadEnabled) => {
1010
+ const result = listInbox({ selfId: self.sessionId, selfWorkdir: self.workdir })
1011
+ const selected = peer === undefined ? result.messages : result.messages.filter(item => item.peerId === peer)
1012
+ const allowed = selected.filter(item => inboxPeerAllowed(self.sessionId, item.peerId))
1013
+ const authorized = allowed.filter(item => auth.isAuthorized(self.sessionId, item.peerId))
1014
+ const blocked = selected.length - authorized.length
1015
+ if (markReadEnabled) {
1016
+ for (const item of authorized) {
1017
+ try { markRead(item.file, self.workdir) } catch (error) { warn(`could not mark ${item.message.id} read: ${describeError(error)}`) }
1018
+ }
1019
+ }
1020
+ const lines = []
1021
+ if (authorized.length === 0) lines.push('No unread messages.')
1022
+ for (const item of authorized) {
1023
+ lines.push(
1024
+ `from: ${item.message.from}`,
1025
+ `kind: ${item.message.kind ?? 'chat'}`,
1026
+ `message id: ${item.message.id}`,
1027
+ `sent: ${iso(item.message.createdAt)}`,
1028
+ '---',
1029
+ item.message.text,
1030
+ '',
1031
+ )
1032
+ }
1033
+ if (blocked > 0) lines.push(`${blocked} message(s) blocked by authorization.`)
1034
+ if (result.rejected > 0) lines.push(`Quarantined ${result.rejected} invalid or oversized message file(s).`)
1035
+ if (result.truncated > 0) lines.push(`${result.truncated} more message file(s) were not read in this call.`)
1036
+ if (peer !== undefined && selected.length === 0 && result.messages.length > 0) {
1037
+ lines.push(`Other peers still have ${result.messages.length} queued message(s); omit peer to read them.`)
1038
+ }
1039
+ return lines.join('\n').trimEnd()
1040
+ }
1041
+
1042
+ const requireSupervisor = (exec) => {
1043
+ const sessionId = exec?.agent?.id
1044
+ if (!isSupervisorSession(sessionId)) throw new Error('this tool is available only to a supervisor session')
1045
+ return requireSelf(exec)
1046
+ }
1047
+
1048
+ const requireWorker = (exec) => {
1049
+ const sessionId = exec?.agent?.id
1050
+ if (!isManagedWorker(sessionId)) throw new Error('this tool is available only to a registered worker session')
1051
+ return requireSelf(exec)
1052
+ }
1053
+
1054
+ /** Stable short digest of one capability description. */
1055
+ const capabilityVersionOf = (name, description) => crypto
1056
+ .createHash('sha256')
1057
+ .update(`${name}\n${description}`)
1058
+ .digest('hex')
1059
+ .slice(0, 16)
1060
+
1061
+ /** Current worker-owned capability, derived from title and base prompt. */
1062
+ const liveCapability = (worker) => {
1063
+ const entry = registry.get(worker)
1064
+ if (entry === undefined) return null
1065
+ let description = ''
1066
+ let updatedAt = entry.updatedAt
1067
+ try {
1068
+ const meta = readJson(path.join(entry.workdir, 'session.json'))
1069
+ if (typeof meta?.basePrompt === 'string') description = meta.basePrompt
1070
+ if (typeof meta?.updatedAt === 'number') updatedAt = meta.updatedAt
1071
+ } catch { /* the worker may not have a readable session yet */ }
1072
+ const name = typeof entry.title === 'string' && entry.title.trim().length > 0 ? entry.title.trim() : worker
1073
+ return {
1074
+ name,
1075
+ description,
1076
+ version: capabilityVersionOf(name, description),
1077
+ updatedAt,
1078
+ source: 'live',
1079
+ }
1080
+ }
1081
+
1082
+ /** Effective capability: a human override if present, otherwise the live one. */
1083
+ const effectiveCapability = (relationship) => {
1084
+ if (relationship === null || relationship === undefined) return null
1085
+ const live = liveCapability(relationship.worker)
1086
+ const override = relationship.capabilityOverride
1087
+ if (override !== null && override !== undefined) {
1088
+ return {
1089
+ ...override,
1090
+ source: 'override',
1091
+ version: capabilityVersionOf(override.name, override.description ?? ''),
1092
+ live,
1093
+ changed: live !== null && relationship.capabilityVersion !== undefined
1094
+ ? live.version !== relationship.capabilityVersion
1095
+ : false,
1096
+ }
1097
+ }
1098
+ if (live === null) return null
1099
+ return {
1100
+ ...live,
1101
+ changed: relationship.capabilityVersion !== undefined
1102
+ ? live.version !== relationship.capabilityVersion
1103
+ : false,
1104
+ }
1105
+ }
1106
+
1107
+ /** Compact live capability lines injected into the supervisor prompt each turn. */
1108
+ const capabilityRoster = (supervisor) => relationships.listForSupervisor(supervisor)
1109
+ .filter(relationship => relationship.offer === true)
1110
+ .map(relationship => {
1111
+ const capability = effectiveCapability(relationship)
1112
+ const name = capability?.name ?? '(request-only)'
1113
+ const description = capability?.description ?? ''
1114
+ const source = capability?.source ?? 'none'
1115
+ const version = capability?.version ?? '-'
1116
+ return `- ${relationship.worker} capability=${JSON.stringify(name)} source=${source} version=${version}${capability?.changed === true ? ' changed=yes' : ''}${description.length === 0 ? '' : ` description=${JSON.stringify(description.slice(0, 500))}`}`
1117
+ })
1118
+
1119
+ const workerCandidates = (supervisor) => registry.list()
1120
+ .filter(entry => entry.sessionId !== supervisor && entry.preset !== SUPERVISOR)
1121
+ .map(entry => {
1122
+ const capability = liveCapability(entry.sessionId)
1123
+ return {
1124
+ sessionId: entry.sessionId,
1125
+ title: entry.title ?? null,
1126
+ online: ctx.agents.get(entry.sessionId) !== undefined,
1127
+ authorized: auth.isAuthorized(supervisor, entry.sessionId),
1128
+ basePrompt: capability?.description ?? '',
1129
+ capability,
1130
+ relationship: relationships.get(supervisor, entry.sessionId) ?? null,
1131
+ }
1132
+ })
1133
+
1134
+ const taskLine = (task) => (
1135
+ `- ${task.id} [${task.status}] worker=${task.worker ?? 'unassigned'} task=${task.taskId ?? '-'} title=${JSON.stringify(task.title)}`
1136
+ )
1137
+
1138
+ /** Turn number for one executing tool call, when the session event is known. */
1139
+ const turnForCall = (exec) => {
1140
+ const found = callTurns.get(String(exec?.callId))
1141
+ if (found === undefined) return undefined
1142
+ if (typeof exec?.agent?.id === 'string' && found.sessionId !== exec.agent.id) return undefined
1143
+ return found.turn
1144
+ }
1145
+
1146
+ const taskDetail = (task) => ({
1147
+ id: task.id,
1148
+ subtaskId: task.id,
1149
+ taskId: task.taskId,
1150
+ supervisor: task.supervisor,
1151
+ worker: task.worker,
1152
+ title: task.title,
1153
+ instruction: task.instruction,
1154
+ inputs: task.inputs,
1155
+ acceptance: task.acceptance,
1156
+ status: task.status,
1157
+ attempts: task.attempts,
1158
+ createdTurn: task.createdTurn,
1159
+ assignedTurn: task.assignedTurn,
1160
+ capabilityVersion: task.capabilityVersion,
1161
+ result: task.result,
1162
+ failure: task.failure,
1163
+ history: task.history,
1164
+ })
1165
+
1166
+ const deliveryDirFor = (task) => deliveryRoot(task.taskId)
1167
+
1168
+ /** Build the canonical project manifest with path/bytes/sha256/mode. */
1169
+ const buildDeliveryManifest = (projectId) => {
1170
+ const project = tasks.project(projectId)
1171
+ if (project === undefined) throw new Error('unknown project')
1172
+ const root = deliveryRoot(projectId)
1173
+ const listed = listDeliveryFiles(root)
1174
+ if (listed.truncated === true) throw new Error(`delivery has more than ${MAX_DELIVERY_LIST_FILES} files; split the project`)
1175
+ const files = listed.sort((left, right) => left.path.localeCompare(right.path)).map(file => {
1176
+ const full = path.join(root, file.path)
1177
+ const before = fs.statSync(full)
1178
+ const content = fs.readFileSync(full)
1179
+ const after = fs.statSync(full)
1180
+ if (before.size !== after.size || before.mtimeMs !== after.mtimeMs) {
1181
+ throw new Error(`delivery file changed while hashing: ${file.path}`)
1182
+ }
1183
+ const hash = crypto.createHash('sha256').update(content).digest('hex')
1184
+ return {
1185
+ path: file.path.split(path.sep).join('/'),
1186
+ bytes: after.size,
1187
+ sha256: hash,
1188
+ mode: `0${(after.mode & 0o777).toString(8)}`,
1189
+ }
1190
+ })
1191
+ const manifest = {
1192
+ generatedAt: new Date().toISOString(),
1193
+ root,
1194
+ files,
1195
+ }
1196
+ const projectDir = path.join(sharedRoot, projectId)
1197
+ mkdirp(projectDir, 0o755)
1198
+ const manifestPath = path.join(projectDir, 'manifest.json')
1199
+ const temporary = `${manifestPath}.${crypto.randomBytes(4).toString('hex')}.tmp`
1200
+ writeJson(temporary, manifest, 0o644)
1201
+ fs.renameSync(temporary, manifestPath)
1202
+ return manifest
1203
+ }
1204
+
1205
+
1206
+ const MAX_DELIVERY_LIST_FILES = 2000
1207
+ /** Publish an opaque delivery alias so the requester never receives projectId. */
1208
+ const publishDeliveryAlias = (projectId, deliveryId) => {
1209
+ const target = path.join(sharedRoot, projectId, 'artifacts')
1210
+ const aliasRoot = path.join(sharedRoot, '.deliveries', deliveryId)
1211
+ const alias = path.join(aliasRoot, 'artifacts')
1212
+ mkdirp(aliasRoot, 0o755)
1213
+ try {
1214
+ const existing = fs.lstatSync(alias)
1215
+ if (existing.isSymbolicLink() && fs.realpathSync(alias) === fs.realpathSync(target)) return alias
1216
+ fs.rmSync(alias, { recursive: true, force: true })
1217
+ } catch { /* alias does not exist yet */ }
1218
+ try {
1219
+ fs.symlinkSync(target, alias, 'dir')
1220
+ return alias
1221
+ } catch (error) {
1222
+ warn(`delivery alias could not be published: ${describeError(error)}`)
1223
+ return target
1224
+ }
1225
+ }
1226
+
1227
+ const listDeliveryFiles = (root, base = root, out = []) => {
1228
+ if (out.length >= MAX_DELIVERY_LIST_FILES) { out.truncated = true; return out }
1229
+ let entries
1230
+ try { entries = fs.readdirSync(root, { withFileTypes: true }) } catch { return out }
1231
+ for (const entry of entries) {
1232
+ if (out.length >= MAX_DELIVERY_LIST_FILES) { out.truncated = true; break }
1233
+ const full = path.join(root, entry.name)
1234
+ if (entry.isDirectory()) {
1235
+ listDeliveryFiles(full, base, out)
1236
+ continue
1237
+ }
1238
+ if (!entry.isFile()) continue
1239
+ let stat
1240
+ try { stat = fs.statSync(full) } catch { continue }
1241
+ out.push({
1242
+ path: path.relative(base, full),
1243
+ size: stat.size,
1244
+ modifiedAt: stat.mtimeMs,
1245
+ })
1246
+ }
1247
+ return out
1248
+ }
1249
+
1250
+ const reconcileRequestProjectBindings = () => {
1251
+ for (const request of requests.list().sort((left, right) => left.createdAt - right.createdAt)) {
1252
+ if (request.status !== 'accepted' || typeof request.taskId !== 'string') continue
1253
+ const project = tasks.project(request.taskId)
1254
+ if (project === undefined) continue
1255
+ if ((project.requestId ?? null) === null) {
1256
+ try {
1257
+ tasks.bindTask(project.id, request.id)
1258
+ } catch (error) {
1259
+ warn(`could not bind legacy request ${request.id} to project ${project.id}: ${describeError(error)}`)
1260
+ }
1261
+ }
1262
+ if (request.delivery !== null) {
1263
+ try { requests.markDelivered(request.id, request.delivery) } catch (error) {
1264
+ warn(`could not promote legacy delivery ${request.id}: ${describeError(error)}`)
1265
+ }
1266
+ }
1267
+ }
1268
+ }
1269
+
1270
+ const pruneDeliveryAliases = () => {
1271
+ const root = path.join(sharedRoot, '.deliveries')
1272
+ let entries
1273
+ try { entries = fs.readdirSync(root, { withFileTypes: true }) } catch { return }
1274
+ const active = new Set(
1275
+ requests.list()
1276
+ .map(request => request.delivery?.deliveryId)
1277
+ .filter(id => typeof id === 'string'),
1278
+ )
1279
+ const now = Date.now()
1280
+ for (const entry of entries) {
1281
+ if (!entry.isDirectory() && !entry.isSymbolicLink()) continue
1282
+ if (active.has(entry.name)) continue
1283
+ const target = path.join(root, entry.name)
1284
+ try {
1285
+ const age = now - fs.statSync(target).mtimeMs
1286
+ if (age > 7 * 24 * 60 * 60 * 1000) fs.rmSync(target, { recursive: true, force: true })
1287
+ } catch { /* alias may disappear concurrently */ }
1288
+ }
1289
+ }
1290
+
1291
+ const taskTools = [
1292
+ {
1293
+ name: 'collab_capabilities',
1294
+ description: 'List functional sessions registered to this supervisor, their capabilities, authorization, online state, and active task count.',
1295
+ parameters: NO_PARAMETERS,
1296
+ output: TEXT_OUTPUT,
1297
+ when: ({ agent }) => isSupervisorSession(agent.id),
1298
+ isConcurrencySafe: () => true,
1299
+ execute: (_args, exec) => {
1300
+ const self = requireSupervisor(exec)
1301
+ const relationshipsForSelf = relationships.listForSupervisor(self.sessionId)
1302
+ if (relationshipsForSelf.length === 0) return 'No functional sessions are registered to this supervisor yet.'
1303
+ const lines = [`supervisor: ${self.sessionId}`, '']
1304
+ for (const relationship of relationshipsForSelf) {
1305
+ if (relationship.offer !== true) continue
1306
+ const worker = registry.get(relationship.worker)
1307
+ const online = ctx.agents.get(relationship.worker) !== undefined
1308
+ const authorized = auth.isAuthorized(self.sessionId, relationship.worker)
1309
+ const active = tasks.activeCount(relationship.worker)
1310
+ const capability = effectiveCapability(relationship)
1311
+ const name = capability?.name ?? '(request-only)'
1312
+ const description = capability?.description ?? ''
1313
+ const source = capability?.source ?? 'none'
1314
+ const version = capability?.version ?? '-'
1315
+ const changed = capability?.changed === true ? 'yes' : 'no'
1316
+ lines.push(
1317
+ `- ${relationship.worker} capability=${JSON.stringify(name)} source=${source} version=${version} changed=${changed} offer=${relationship.offer ? 'yes' : 'no'} authorized=${authorized ? 'yes' : 'no'} ${online ? 'online' : 'offline'} active=${String(active)}${description.length === 0 ? '' : ` description=${JSON.stringify(description)}`}${worker?.title === undefined ? '' : ` title=${JSON.stringify(worker.title)}`}`,
1318
+ )
1319
+ }
1320
+ return lines.join('\n')
1321
+ },
1322
+ },
1323
+ {
1324
+ name: 'collab_task_create',
1325
+ description: 'Create a subtask for a functional worker. Omit taskId to create the parent task for this requirement.',
1326
+ parameters: TASK_CREATE_PARAMETERS,
1327
+ output: TEXT_OUTPUT,
1328
+ when: ({ agent }) => isSupervisorSession(agent.id),
1329
+ execute: (args, exec) => {
1330
+ const self = requireSupervisor(exec)
1331
+ const title = String(args?.title ?? '').trim()
1332
+ const instruction = String(args?.instruction ?? '')
1333
+ if (title.length === 0) throw new Error('task title must not be empty')
1334
+ if (instruction.trim().length === 0) throw new Error('task instruction must not be empty')
1335
+ const mentionsSharedCopy = (instruction.includes(sharedRoot) || instruction.includes('/shared/'))
1336
+ && /(?:cp|copy|rsync|ln|mv|复制|拷贝|共享目录)/iu.test(instruction)
1337
+ if (mentionsSharedCopy) {
1338
+ throw new Error('do not create copy-out tasks; workers receive a canonical deliveryDir and publish artifacts there')
1339
+ }
1340
+ let taskId = typeof args?.taskId === 'string' && args.taskId.trim().length > 0
1341
+ ? args.taskId.trim()
1342
+ : (typeof args?.projectId === 'string' && args.projectId.trim().length > 0 ? args.projectId.trim() : undefined)
1343
+ if (taskId === undefined) {
1344
+ const task = tasks.createTask({ supervisor: self.sessionId, title })
1345
+ taskId = task.id
1346
+ } else {
1347
+ const task = tasks.task(taskId)
1348
+ if (task === undefined || task.supervisor !== self.sessionId) throw new Error(`unknown task: ${taskId}`)
1349
+ if (task.status !== 'open') throw new Error('task is closed')
1350
+ }
1351
+ const subtask = tasks.createSubtask({
1352
+ supervisor: self.sessionId,
1353
+ worker: null,
1354
+ taskId,
1355
+ title,
1356
+ instruction,
1357
+ inputs: args?.inputs,
1358
+ acceptance: args?.acceptance,
1359
+ createdTurn: turnForCall(exec),
1360
+ })
1361
+ return JSON.stringify({ subtask: taskDetail(subtask), taskId })
1362
+ },
1363
+ },
1364
+ {
1365
+ name: 'collab_task_assign',
1366
+ description: 'Assign a task to a worker with an offer relationship. The worker is woken with the assignment.',
1367
+ parameters: TASK_ASSIGN_PARAMETERS,
1368
+ output: TEXT_OUTPUT,
1369
+ when: ({ agent }) => isSupervisorSession(agent.id),
1370
+ execute: async (args, exec) => {
1371
+ const self = requireSupervisor(exec)
1372
+ const subtaskId = String(args?.subtaskId ?? args?.taskId ?? '')
1373
+ const worker = String(args?.worker ?? '')
1374
+ const task = tasks.get(subtaskId)
1375
+ if (task === undefined || task.supervisor !== self.sessionId) throw new Error(`unknown subtask: ${subtaskId}`)
1376
+ const relationship = relationships.get(self.sessionId, worker)
1377
+ if (relationship === undefined || relationship.offer !== true) {
1378
+ throw new Error('worker is not registered to this supervisor with an offer capability')
1379
+ }
1380
+ if (!auth.isAuthorized(self.sessionId, worker)) {
1381
+ throw new Error('未授权:请在“协同授权”页授权双方。')
1382
+ }
1383
+ const project = task.taskId === null ? undefined : tasks.project(task.taskId)
1384
+ if (project !== undefined && project.status !== 'open') throw new Error('project is closed')
1385
+ const otherActive = tasks.listForWorker(worker)
1386
+ .filter(entry => entry.id !== subtaskId && !['done', 'failed', 'cancelled'].includes(entry.status))
1387
+ .length
1388
+ if (otherActive >= 1) throw new Error('worker already has an active task; capacity is 1')
1389
+ const deliveryDir = deliveryRoot(task.taskId)
1390
+ mkdirp(deliveryDir, 0o755)
1391
+ bindDeliverySandbox(worker, deliveryDir)
1392
+ const assigned = tasks.assign(subtaskId, worker, turnForCall(exec), effectiveCapability(relationship)?.version ?? null)
1393
+ const payload = {
1394
+ type: 'collab-task/assign',
1395
+ version: 1,
1396
+ taskId: assigned.taskId,
1397
+ subtaskId: assigned.id,
1398
+ supervisor: self.sessionId,
1399
+ title: assigned.title,
1400
+ instruction: assigned.instruction,
1401
+ inputs: assigned.inputs,
1402
+ acceptance: assigned.acceptance,
1403
+ deliveryDir,
1404
+ attempt: assigned.attempts,
1405
+ }
1406
+ const delivery = await sendTaskNotice(self, worker, payload)
1407
+ return [
1408
+ `assigned: ${assigned.id}`,
1409
+ `worker: ${worker}`,
1410
+ `status: ${assigned.status}`,
1411
+ `delivery: ${delivery}`,
1412
+ `deliveryDir: ${deliveryDir}`,
1413
+ ].join('\n')
1414
+ },
1415
+ },
1416
+ {
1417
+ name: 'collab_requests',
1418
+ description: 'List work requests. A supervisor sees requests sent to it; any requester session sees its own requests.',
1419
+ parameters: REQUEST_LIST_PARAMETERS,
1420
+ output: TEXT_OUTPUT,
1421
+ when: ({ agent }) => collabSessions.has(agent.id),
1422
+ isConcurrencySafe: () => true,
1423
+ execute: (args, exec) => {
1424
+ const self = requireSelf(exec)
1425
+ const status = typeof args?.status === 'string' && args.status.trim().length > 0 ? args.status.trim() : undefined
1426
+ const list = isSupervisorSession(self.sessionId)
1427
+ ? requests.listForSupervisor(self.sessionId, status).map(RequestStore.summary)
1428
+ : requests.listForRequester(self.sessionId, status).map(RequestStore.requesterSummary)
1429
+ if (list.length === 0) return 'No requests.'
1430
+ return JSON.stringify(list)
1431
+ },
1432
+ },
1433
+ {
1434
+ name: 'collab_request_accept',
1435
+ description: 'Accept a pending work request after the requested work has been decomposed into assigned tasks.',
1436
+ parameters: REQUEST_ACCEPT_PARAMETERS,
1437
+ output: TEXT_OUTPUT,
1438
+ when: ({ agent }) => isSupervisorSession(agent.id),
1439
+ execute: async (args, exec) => {
1440
+ const self = requireSupervisor(exec)
1441
+ const request = requests.get(String(args?.requestId ?? ''))
1442
+ if (request === undefined || request.supervisor !== self.sessionId) throw new Error('unknown request')
1443
+ if (request.status !== 'pending') throw new Error(`request is already ${request.status}`)
1444
+ const taskId = String(args?.taskId ?? args?.projectId ?? '')
1445
+ const task = tasks.task(taskId)
1446
+ if (task === undefined || task.supervisor !== self.sessionId) throw new Error('unknown task for this request')
1447
+ if (task.status !== 'open') throw new Error('task is closed')
1448
+ const assigned = tasks.listForSupervisor(self.sessionId).filter(subtask => (
1449
+ subtask.taskId === taskId
1450
+ && subtask.worker !== null
1451
+ && relationships.hasOffer(subtask.worker)
1452
+ && subtask.status !== 'cancelled'
1453
+ ))
1454
+ if (assigned.length === 0) throw new Error('assign at least one subtask to an offered worker before accepting')
1455
+ if (!auth.isAuthorized(self.sessionId, request.requester)) throw new Error('未授权:请在“协同授权”页授权双方。')
1456
+ const existingBinding = task.requestId ?? null
1457
+ if (existingBinding !== null && existingBinding !== request.id) {
1458
+ throw new Error('task is already bound to another request')
1459
+ }
1460
+ const acceptedAt = Date.now()
1461
+ const accepted = requests.accept(request.id, {
1462
+ taskId,
1463
+ subtaskIds: assigned.map(subtask => subtask.id),
1464
+ response: typeof args?.response === 'string' ? args.response : null,
1465
+ executionDeadlineAt: acceptedAt + executionTimeoutMs,
1466
+ }, acceptedAt)
1467
+ try {
1468
+ tasks.bindTask(taskId, request.id)
1469
+ } catch (error) {
1470
+ try { requests.reopen(request.id) } catch { /* preserve the binding failure */ }
1471
+ throw error
1472
+ }
1473
+ clearRequestTimer(request.id)
1474
+ scheduleExecutionDeadline(accepted)
1475
+ const payload = {
1476
+ type: 'collab-task/request-accepted',
1477
+ version: 1,
1478
+ requestId: accepted.id,
1479
+ title: accepted.title,
1480
+ status: accepted.status,
1481
+ }
1482
+ const delivery = await sendTaskNotice(self, request.requester, payload)
1483
+ return JSON.stringify({
1484
+ request: RequestStore.summary(accepted),
1485
+ tasks: assigned.map(task => TaskStore.summary(task)),
1486
+ delivery,
1487
+ })
1488
+ },
1489
+ },
1490
+ {
1491
+ name: 'collab_request_reject',
1492
+ description: 'Reject a pending work request with the missing capability or another concrete reason.',
1493
+ parameters: REQUEST_REJECT_PARAMETERS,
1494
+ output: TEXT_OUTPUT,
1495
+ when: ({ agent }) => isSupervisorSession(agent.id),
1496
+ execute: async (args, exec) => {
1497
+ const self = requireSupervisor(exec)
1498
+ const request = requests.get(String(args?.requestId ?? ''))
1499
+ if (request === undefined || request.supervisor !== self.sessionId) throw new Error('unknown request')
1500
+ if (request.status !== 'pending') throw new Error(`request is already ${request.status}`)
1501
+ if (!auth.isAuthorized(self.sessionId, request.requester)) throw new Error('未授权:请在“协同授权”页授权双方。')
1502
+ const rejected = requests.reject(request.id, String(args?.reason ?? ''))
1503
+ clearRequestTimer(request.id)
1504
+ const payload = {
1505
+ type: 'collab-task/request-rejected',
1506
+ version: 1,
1507
+ requestId: rejected.id,
1508
+ title: rejected.title,
1509
+ reason: rejected.reason,
1510
+ }
1511
+ const delivery = await sendTaskNotice(self, request.requester, payload)
1512
+ return JSON.stringify({ request: RequestStore.summary(rejected), delivery })
1513
+ },
1514
+ },
1515
+ {
1516
+ name: 'collab_request_heartbeat',
1517
+ description: 'Report progress on an accepted request and optionally extend its execution deadline.',
1518
+ parameters: REQUEST_HEARTBEAT_PARAMETERS,
1519
+ output: TEXT_OUTPUT,
1520
+ when: ({ agent }) => isSupervisorSession(agent.id),
1521
+ execute: async (args, exec) => {
1522
+ const self = requireSupervisor(exec)
1523
+ const request = requests.get(String(args?.requestId ?? ''))
1524
+ if (request === undefined || request.supervisor !== self.sessionId) throw new Error('unknown request')
1525
+ if (request.status !== 'accepted') throw new Error(`request is ${request.status}, not accepted`)
1526
+ if (!auth.isAuthorized(self.sessionId, request.requester)) throw new Error('未授权:请在“协同授权”页授权双方。')
1527
+ const updated = requests.heartbeat(request.id, {
1528
+ note: typeof args?.note === 'string' ? args.note : null,
1529
+ extendByMs: Number.isFinite(Number(args?.extendByMs)) ? Number(args.extendByMs) : 0,
1530
+ })
1531
+ scheduleExecutionDeadline(updated)
1532
+ const payload = {
1533
+ type: 'collab-task/request-progress',
1534
+ version: 1,
1535
+ requestId: updated.id,
1536
+ title: updated.title,
1537
+ deadline: updated.executionDeadlineAt,
1538
+ ...(typeof args?.note === 'string' && args.note.length > 0 ? { note: args.note } : {}),
1539
+ }
1540
+ const delivery = await sendTaskNotice(self, updated.requester, payload)
1541
+ return JSON.stringify({ request: RequestStore.summary(updated), delivery })
1542
+ },
1543
+ },
1544
+ {
1545
+ name: 'collab_tasks',
1546
+ description: 'List tasks for this supervisor or, for a worker, the tasks assigned to it.',
1547
+ parameters: TASK_LIST_PARAMETERS,
1548
+ output: TEXT_OUTPUT,
1549
+ when: ({ agent }) => isSupervisorSession(agent.id) || isManagedWorker(agent.id),
1550
+ isConcurrencySafe: () => true,
1551
+ execute: (args, exec) => {
1552
+ const self = requireSelf(exec)
1553
+ const status = typeof args?.status === 'string' && args.status.trim().length > 0 ? args.status.trim() : undefined
1554
+ const list = isSupervisorSession(self.sessionId)
1555
+ ? tasks.listForSupervisor(self.sessionId, status)
1556
+ : tasks.listForWorker(self.sessionId, status)
1557
+ if (list.length === 0) return 'No tasks.'
1558
+ return list.map(taskLine).join('\n')
1559
+ },
1560
+ },
1561
+ {
1562
+ name: 'collab_task_result',
1563
+ description: 'Read one task detail and result. Only tasks owned by this supervisor are returned.',
1564
+ parameters: TASK_ID_PARAMETERS,
1565
+ output: TEXT_OUTPUT,
1566
+ when: ({ agent }) => isSupervisorSession(agent.id),
1567
+ isConcurrencySafe: () => true,
1568
+ execute: (args, exec) => {
1569
+ const self = requireSupervisor(exec)
1570
+ const task = tasks.get(String(args?.taskId ?? ''))
1571
+ if (task === undefined || task.supervisor !== self.sessionId) throw new Error('unknown task')
1572
+ return JSON.stringify(taskDetail(task))
1573
+ },
1574
+ },
1575
+ {
1576
+ name: 'collab_task_retry',
1577
+ description: 'Reset a failed/cancelled/completed task to created so it can be assigned again.',
1578
+ parameters: TASK_ID_PARAMETERS,
1579
+ output: TEXT_OUTPUT,
1580
+ when: ({ agent }) => isSupervisorSession(agent.id),
1581
+ execute: (args, exec) => {
1582
+ const self = requireSupervisor(exec)
1583
+ const taskId = String(args?.taskId ?? '')
1584
+ const task = tasks.get(taskId)
1585
+ if (task === undefined || task.supervisor !== self.sessionId) throw new Error('unknown task')
1586
+ const retried = tasks.retry(taskId)
1587
+ return `retried: ${retried.id}\nstatus: ${retried.status}`
1588
+ },
1589
+ },
1590
+ {
1591
+ name: 'collab_task_reject',
1592
+ description: 'Reject a completed task, returning it to the worker with a revision instruction.',
1593
+ parameters: TASK_REJECT_PARAMETERS,
1594
+ output: TEXT_OUTPUT,
1595
+ when: ({ agent }) => isSupervisorSession(agent.id),
1596
+ execute: async (args, exec) => {
1597
+ const self = requireSupervisor(exec)
1598
+ const taskId = String(args?.taskId ?? '')
1599
+ const task = tasks.get(taskId)
1600
+ if (task === undefined || task.supervisor !== self.sessionId) throw new Error('unknown task')
1601
+ if (task.worker === null) throw new Error('task has no worker')
1602
+ const rejected = tasks.reject(taskId, String(args?.reason ?? ''))
1603
+ const payload = {
1604
+ type: 'collab-task/assign',
1605
+ version: 1,
1606
+ taskId: rejected.taskId,
1607
+ subtaskId: rejected.id,
1608
+ supervisor: self.sessionId,
1609
+ title: rejected.title,
1610
+ instruction: rejected.instruction,
1611
+ inputs: rejected.inputs,
1612
+ acceptance: rejected.acceptance,
1613
+ deliveryDir: deliveryDirFor(rejected),
1614
+ attempt: rejected.attempts,
1615
+ revision: String(args?.reason ?? ''),
1616
+ }
1617
+ await sendTaskNotice(self, rejected.worker, payload)
1618
+ return `rejected: ${rejected.id}\nstatus: ${rejected.status}`
1619
+ },
1620
+ },
1621
+ {
1622
+ name: 'collab_task_cancel',
1623
+ description: 'Cancel a task that has not completed.',
1624
+ parameters: TASK_ID_PARAMETERS,
1625
+ output: TEXT_OUTPUT,
1626
+ when: ({ agent }) => isSupervisorSession(agent.id),
1627
+ execute: (args, exec) => {
1628
+ const self = requireSupervisor(exec)
1629
+ const task = tasks.get(String(args?.taskId ?? ''))
1630
+ if (task === undefined || task.supervisor !== self.sessionId) throw new Error('unknown task')
1631
+ const cancelled = tasks.cancel(task.id)
1632
+ return `cancelled: ${cancelled.id}`
1633
+ },
1634
+ },
1635
+ {
1636
+ name: 'collab_task_close',
1637
+ description: 'Close a task after all its subtasks are done or cancelled.',
1638
+ parameters: TASK_CLOSE_PARAMETERS,
1639
+ output: TEXT_OUTPUT,
1640
+ when: ({ agent }) => isSupervisorSession(agent.id),
1641
+ execute: (args, exec) => {
1642
+ const self = requireSupervisor(exec)
1643
+ const taskId = String(args?.taskId ?? args?.projectId ?? '')
1644
+ const task = tasks.task(taskId)
1645
+ if (task === undefined || task.supervisor !== self.sessionId) throw new Error('unknown task')
1646
+ const owned = tasks.listForSupervisor(self.sessionId).filter(subtask => subtask.taskId === taskId)
1647
+ const closed = tasks.closeTask(taskId)
1648
+ for (const task of owned) {
1649
+ if (task.worker !== null) releaseDeliverySandbox(task.worker, deliveryRoot(taskId))
1650
+ }
1651
+ return `closed: ${closed.id}\nstatus: ${closed.status}`
1652
+ },
1653
+ },
1654
+ {
1655
+ name: 'collab_delivery_list',
1656
+ description: 'List canonical delivery files for this supervisor\'s tasks. Names, sizes, and times only; content is not read.',
1657
+ parameters: DELIVERY_LIST_PARAMETERS,
1658
+ output: TEXT_OUTPUT,
1659
+ when: ({ agent }) => isSupervisorSession(agent.id),
1660
+ isConcurrencySafe: () => true,
1661
+ execute: (args, exec) => {
1662
+ const self = requireSupervisor(exec)
1663
+ const taskId = typeof args?.taskId === 'string' && args.taskId.trim().length > 0
1664
+ ? args.taskId.trim()
1665
+ : (typeof args?.projectId === 'string' && args.projectId.trim().length > 0 ? args.projectId.trim() : undefined)
1666
+ if (taskId !== undefined) {
1667
+ const task = tasks.task(taskId)
1668
+ if (task === undefined || task.supervisor !== self.sessionId) throw new Error('unknown task')
1669
+ const files = listDeliveryFiles(path.join(sharedRoot, taskId, 'artifacts'))
1670
+ if (files.length === 0) return 'No delivery files.'
1671
+ const lines = files.map(file => `${file.path} ${String(file.size)}B ${iso(file.modifiedAt)}`)
1672
+ if (files.truncated === true) lines.push(`(truncated at ${MAX_DELIVERY_LIST_FILES} files)`)
1673
+ return lines.join('\n')
1674
+ }
1675
+ const lines = []
1676
+ for (const task of tasks.listTasks(self.sessionId)) {
1677
+ const files = listDeliveryFiles(path.join(sharedRoot, task.id, 'artifacts'))
1678
+ for (const file of files) {
1679
+ lines.push(`${task.id}/${file.path} ${String(file.size)}B ${iso(file.modifiedAt)}`)
1680
+ }
1681
+ if (files.truncated === true) lines.push(`${task.id}/(truncated at ${MAX_DELIVERY_LIST_FILES} files)`)
1682
+ }
1683
+ return lines.length === 0 ? 'No delivery files.' : lines.join('\n')
1684
+ },
1685
+ },
1686
+ {
1687
+ name: 'collab_delivery_manifest',
1688
+ description: 'Build and persist a canonical delivery manifest (path, bytes, sha256, mode) for a supervisor task.',
1689
+ parameters: DELIVERY_MANIFEST_PARAMETERS,
1690
+ output: TEXT_OUTPUT,
1691
+ when: ({ agent }) => isSupervisorSession(agent.id),
1692
+ execute: (args, exec) => {
1693
+ const self = requireSupervisor(exec)
1694
+ const taskId = String(args?.taskId ?? args?.projectId ?? '')
1695
+ const task = tasks.task(taskId)
1696
+ if (task === undefined || task.supervisor !== self.sessionId) throw new Error('unknown task')
1697
+ return JSON.stringify(buildDeliveryManifest(taskId))
1698
+ },
1699
+ },
1700
+ {
1701
+ name: 'collab_request_deliver',
1702
+ description: 'Send the sanitized delivery manifest for an accepted request to its requester. Does not expose task assignments, worker ids, or internal scheduling.',
1703
+ parameters: REQUEST_DELIVER_PARAMETERS,
1704
+ output: TEXT_OUTPUT,
1705
+ when: ({ agent }) => isSupervisorSession(agent.id),
1706
+ execute: async (args, exec) => {
1707
+ const self = requireSupervisor(exec)
1708
+ const request = requests.get(String(args?.requestId ?? ''))
1709
+ if (request === undefined || request.supervisor !== self.sessionId) throw new Error('unknown request')
1710
+ if (request.status !== 'accepted' && request.status !== 'delivered') {
1711
+ throw new Error(`request is ${request.status}, not delivery-ready`)
1712
+ }
1713
+ if (request.taskId === null) throw new Error('accepted request has no task')
1714
+ const task = tasks.task(request.taskId)
1715
+ if (task === undefined) throw new Error('request task no longer exists')
1716
+ if (task.requestId !== request.id) throw new Error('task is not bound to this request')
1717
+ if (task.status !== 'closed') throw new Error('close the task before delivery')
1718
+ const activeTasks = tasks.listForSupervisor(self.sessionId)
1719
+ .filter(subtask => subtask.taskId === task.id && !['done', 'cancelled'].includes(subtask.status))
1720
+ if (activeTasks.length > 0) throw new Error('all subtasks must be done or cancelled before delivery')
1721
+ if (deliveryInFlight.has(request.id)) throw new Error('delivery is already in progress')
1722
+ if (!auth.isAuthorized(self.sessionId, request.requester)) throw new Error('未授权:请在“协同授权”页授权双方。')
1723
+ deliveryInFlight.add(request.id)
1724
+ try {
1725
+ const manifest = buildDeliveryManifest(request.taskId)
1726
+ if (manifest.files.length === 0) throw new Error('delivery has no artifacts')
1727
+ const manifestSha256 = crypto.createHash('sha256').update(JSON.stringify(manifest.files)).digest('hex')
1728
+ const deliveryId = `delivery-${manifestSha256.slice(0, 16)}`
1729
+ if (request.delivery !== null && request.delivery.manifestSha256 === manifestSha256) {
1730
+ return JSON.stringify({
1731
+ requestId: request.id,
1732
+ alreadyDelivered: true,
1733
+ deliveryId: request.delivery.deliveryId,
1734
+ files: manifest.files.length,
1735
+ })
1736
+ }
1737
+ const supersedes = request.delivery === null ? null : request.delivery.deliveryId
1738
+ const publicRoot = publishDeliveryAlias(request.taskId, deliveryId)
1739
+ const payload = {
1740
+ type: 'collab-task/request-delivered',
1741
+ version: 1,
1742
+ requestId: request.id,
1743
+ title: request.title,
1744
+ deliveryId,
1745
+ manifestSha256,
1746
+ ...(supersedes === null ? {} : { supersedes }),
1747
+ root: publicRoot,
1748
+ files: manifest.files,
1749
+ }
1750
+ const delivery = await sendTaskNotice(self, request.requester, payload)
1751
+ const recorded = requests.markDelivered(request.id, {
1752
+ deliveryId,
1753
+ manifestSha256,
1754
+ deliveredAt: Date.now(),
1755
+ ...(supersedes === null ? {} : { supersedes }),
1756
+ })
1757
+ clearExecutionTimer(request.id)
1758
+ return JSON.stringify({ requestId: request.id, status: recorded.status, files: manifest.files.length, deliveryId, delivery })
1759
+ } finally {
1760
+ deliveryInFlight.delete(request.id)
1761
+ }
1762
+ },
1763
+ },
1764
+ {
1765
+ name: 'collab_task_accept',
1766
+ description: 'Accept an assigned task and return its instructions, acceptance criteria, and delivery directory.',
1767
+ parameters: TASK_ID_PARAMETERS,
1768
+ output: TEXT_OUTPUT,
1769
+ when: ({ agent }) => isManagedWorker(agent.id),
1770
+ execute: (args, exec) => {
1771
+ const self = requireWorker(exec)
1772
+ const task = tasks.get(String(args?.taskId ?? ''))
1773
+ if (task === undefined || task.worker !== self.sessionId) throw new Error('unknown task for this worker')
1774
+ const accepted = tasks.accept(task.id, self.sessionId)
1775
+ const deliveryDir = deliveryDirFor(accepted)
1776
+ bindDeliverySandbox(self.sessionId, deliveryDir)
1777
+ return JSON.stringify({ ...taskDetail(accepted), deliveryDir })
1778
+ },
1779
+ },
1780
+ {
1781
+ name: 'collab_task_progress',
1782
+ description: 'Record progress on an accepted task.',
1783
+ parameters: TASK_PROGRESS_PARAMETERS,
1784
+ output: TEXT_OUTPUT,
1785
+ when: ({ agent }) => isManagedWorker(agent.id),
1786
+ execute: (args, exec) => {
1787
+ const self = requireWorker(exec)
1788
+ const task = tasks.get(String(args?.taskId ?? ''))
1789
+ if (task === undefined || task.worker !== self.sessionId) throw new Error('unknown task for this worker')
1790
+ const progressed = tasks.progress(task.id, self.sessionId, String(args?.note ?? ''))
1791
+ return `progress: ${progressed.id}\nstatus: ${progressed.status}`
1792
+ },
1793
+ },
1794
+ {
1795
+ name: 'collab_task_complete',
1796
+ description: 'Complete a task and notify its supervisor with the result summary.',
1797
+ parameters: TASK_COMPLETE_PARAMETERS,
1798
+ output: TEXT_OUTPUT,
1799
+ when: ({ agent }) => isManagedWorker(agent.id),
1800
+ execute: async (args, exec) => {
1801
+ const self = requireWorker(exec)
1802
+ const task = tasks.get(String(args?.taskId ?? ''))
1803
+ if (task === undefined || task.worker !== self.sessionId) throw new Error('unknown task for this worker')
1804
+ const completed = tasks.complete(task.id, self.sessionId, {
1805
+ summary: args?.summary,
1806
+ details: args?.details,
1807
+ artifacts: args?.artifacts,
1808
+ })
1809
+ const delivery = await sendTaskNotice(self, completed.supervisor, {
1810
+ type: 'collab-task/result',
1811
+ version: 1,
1812
+ taskId: completed.id,
1813
+ status: 'done',
1814
+ })
1815
+ return [
1816
+ `completed: ${completed.id}`,
1817
+ `status: ${completed.status}`,
1818
+ `delivery: ${delivery}`,
1819
+ ].join('\n')
1820
+ },
1821
+ },
1822
+ {
1823
+ name: 'collab_task_fail',
1824
+ description: 'Report a task failure to its supervisor.',
1825
+ parameters: TASK_FAIL_PARAMETERS,
1826
+ output: TEXT_OUTPUT,
1827
+ when: ({ agent }) => isManagedWorker(agent.id),
1828
+ execute: async (args, exec) => {
1829
+ const self = requireWorker(exec)
1830
+ const task = tasks.get(String(args?.taskId ?? ''))
1831
+ if (task === undefined || task.worker !== self.sessionId) throw new Error('unknown task for this worker')
1832
+ const failed = tasks.fail(task.id, self.sessionId, String(args?.reason ?? ''))
1833
+ const delivery = await sendTaskNotice(self, failed.supervisor, {
1834
+ type: 'collab-task/result',
1835
+ version: 1,
1836
+ taskId: failed.id,
1837
+ status: 'failed',
1838
+ })
1839
+ return [
1840
+ `failed: ${failed.id}`,
1841
+ `status: ${failed.status}`,
1842
+ `delivery: ${delivery}`,
1843
+ ].join('\n')
1844
+ },
1845
+ },
1846
+ {
1847
+ name: 'collab_request_submit',
1848
+ description: 'Ask an authorized supervisor to evaluate and decompose work. No offer/worker relationship is required; bilateral authorization is enough.',
1849
+ parameters: REQUEST_SUBMIT_PARAMETERS,
1850
+ output: TEXT_OUTPUT,
1851
+ when: ({ agent }) => collabSessions.has(agent.id) && !isSupervisorSession(agent.id),
1852
+ execute: async (args, exec) => {
1853
+ const self = requireSelf(exec)
1854
+ const eligible = registry.list()
1855
+ .filter(entry => entry.preset === SUPERVISOR && auth.isAuthorized(self.sessionId, entry.sessionId))
1856
+ if (eligible.length === 0) {
1857
+ throw new Error('no authorized supervisor; authorize a supervisor pair in the authorization page first')
1858
+ }
1859
+ const targetId = typeof args?.supervisor === 'string' && args.supervisor.trim().length > 0
1860
+ ? args.supervisor.trim()
1861
+ : undefined
1862
+ let supervisor
1863
+ if (targetId !== undefined) {
1864
+ supervisor = eligible.find(candidate => candidate.sessionId === targetId)
1865
+ if (supervisor === undefined) throw new Error('target supervisor is not authorized for this session')
1866
+ } else if (eligible.length === 1) {
1867
+ supervisor = eligible[0]
1868
+ } else {
1869
+ throw new Error(`specify a supervisor: ${eligible.map(candidate => candidate.sessionId).join(', ')}`)
1870
+ }
1871
+ const now = Date.now()
1872
+ const request = requests.create({
1873
+ requester: self.sessionId,
1874
+ supervisor: supervisor.sessionId,
1875
+ title: String(args?.title ?? ''),
1876
+ requirement: String(args?.requirement ?? ''),
1877
+ createdTurn: turnForCall(exec),
1878
+ expiresAt: now + requestTimeoutMs,
1879
+ }, now)
1880
+ try {
1881
+ const delivery = await sendTaskNotice(self, supervisor.sessionId, {
1882
+ type: 'collab-task/request',
1883
+ version: 1,
1884
+ requestId: request.id,
1885
+ requester: self.sessionId,
1886
+ title: request.title,
1887
+ requirement: request.requirement,
1888
+ })
1889
+ scheduleRequestTimeout(request)
1890
+ return JSON.stringify({ request: RequestStore.requesterSummary(request), delivery })
1891
+ } catch (error) {
1892
+ try { requests.cancel(request.id, self.sessionId) } catch { /* preserve the original failure */ }
1893
+ throw error
1894
+ }
1895
+ },
1896
+ },
1897
+ {
1898
+ name: 'collab_request_cancel',
1899
+ description: 'Cancel one of your pending work requests.',
1900
+ parameters: REQUEST_CANCEL_PARAMETERS,
1901
+ output: TEXT_OUTPUT,
1902
+ when: ({ agent }) => collabSessions.has(agent.id) && !isSupervisorSession(agent.id),
1903
+ execute: async (args, exec) => {
1904
+ const self = requireSelf(exec)
1905
+ const request = requests.get(String(args?.requestId ?? ''))
1906
+ if (request === undefined || request.requester !== self.sessionId) throw new Error('unknown request')
1907
+ const cancelled = requests.cancel(request.id, self.sessionId)
1908
+ clearRequestTimer(request.id)
1909
+ clearExecutionTimer(request.id)
1910
+ try {
1911
+ await sendTaskNotice(self, request.supervisor, {
1912
+ type: 'collab-task/request-cancelled',
1913
+ version: 1,
1914
+ requestId: cancelled.id,
1915
+ title: cancelled.title,
1916
+ })
1917
+ } catch { /* cancellation remains effective even if the notice cannot be delivered */ }
1918
+ return JSON.stringify({ request: RequestStore.requesterSummary(cancelled) })
1919
+ },
1920
+ },
1921
+ ]
1922
+
1923
+ const tools = [
1924
+ {
1925
+ name: 'collab_info',
1926
+ description: 'Describe this collaboration session: its unique session id, communication and private directories, and known peers.',
1927
+ parameters: NO_PARAMETERS,
1928
+ output: TEXT_OUTPUT,
1929
+ isConcurrencySafe: () => true,
1930
+ execute: (_args, exec) => infoText(requireSelf(exec)),
1931
+ },
1932
+ {
1933
+ name: 'collab_peers',
1934
+ description: 'List other collaboration sessions with their role, session id, authorization, and online state.',
1935
+ when: ({ agent }) => collabSessions.has(agent.id),
1936
+ parameters: NO_PARAMETERS,
1937
+ output: TEXT_OUTPUT,
1938
+ isConcurrencySafe: () => true,
1939
+ execute: (_args, exec) => {
1940
+ const self = requireSelf(exec)
1941
+ refreshRegistry()
1942
+ return peersText(self)
1943
+ },
1944
+ },
1945
+ {
1946
+ name: 'collab_send',
1947
+ description: 'Send an authenticated chat message to another collaboration session. The pair must be explicitly authorized; the message is written under comm/<target>/outbox and the target inbox; a live target is woken with a notification and reads it through collab_inbox. Chat never changes task state.',
1948
+ when: ({ agent }) => collabSessions.has(agent.id),
1949
+ parameters: SEND_PARAMETERS,
1950
+ output: TEXT_OUTPUT,
1951
+ execute: async (args, exec) => {
1952
+ const self = requireSelf(exec)
1953
+ const targetId = String(args?.target ?? '').trim()
1954
+ const text = String(args?.message ?? '')
1955
+ if (!isSessionId(targetId)) throw new Error('target must be an exact session id such as session-<uuid>')
1956
+ if (targetId === self.sessionId) throw new Error('a collaboration session cannot send a message to itself')
1957
+ const targetEntry = registry.get(targetId)
1958
+ if (targetEntry === undefined || !COLLAB_PRESETS.has(targetEntry.preset)) {
1959
+ throw new Error('target must be a collaboration session')
1960
+ }
1961
+ if (!auth.isAuthorized(self.sessionId, targetId)) {
1962
+ throw new Error('未授权:请在“协同授权”页授权双方。')
1963
+ }
1964
+ if (text.trim().length === 0) throw new Error('message must not be empty')
1965
+ if (Buffer.byteLength(text) > MAX_MESSAGE_BYTES) throw new Error('message is larger than 64 KiB')
1966
+ refreshRegistry()
1967
+ const peer = registry.get(targetId)
1968
+ if (peer === undefined) throw new Error(`unknown collaboration session: ${targetId}`)
1969
+ const peerWorkdir = peer.workdir
1970
+ if (typeof peerWorkdir !== 'string' || !isDirectory(peerWorkdir)) {
1971
+ throw new Error(`target working directory is missing: ${String(peerWorkdir)}`)
1972
+ }
1973
+ const message = sendMessage({
1974
+ selfId: self.sessionId,
1975
+ selfWorkdir: self.workdir,
1976
+ peerId: peer.sessionId,
1977
+ peerWorkdir,
1978
+ kind: 'chat',
1979
+ text,
1980
+ })
1981
+ const delivery = await wakePeer(peer.sessionId, message)
1982
+ return [
1983
+ `sent: ${message.id}`,
1984
+ `from: ${self.sessionId}`,
1985
+ `to: ${peer.sessionId}`,
1986
+ `delivery: ${delivery}`,
1987
+ `credential: ${credentialPath(self.workdir, peer.sessionId)}`,
1988
+ ].join('\n')
1989
+ },
1990
+ },
1991
+ {
1992
+ name: 'collab_inbox',
1993
+ description: 'Read messages queued for this collaboration session. Only explicitly authorized pairs are returned; messages are authenticated with the pair credential, and reading acknowledges them by default.',
1994
+ parameters: INBOX_PARAMETERS,
1995
+ output: TEXT_OUTPUT,
1996
+ execute: (args, exec) => {
1997
+ const self = requireSelf(exec)
1998
+ const peer = typeof args?.peer === 'string' && args.peer.trim().length > 0 ? args.peer.trim() : undefined
1999
+ if (peer !== undefined && !isSessionId(peer)) throw new Error('peer must be an exact session id such as session-<uuid>')
2000
+ return inboxText(self, peer, args?.mark_read !== false)
2001
+ },
2002
+ },
2003
+ ...taskTools,
2004
+ ]
2005
+
2006
+ ctx.commands.register({
2007
+ name: 'collab-auth',
2008
+ description: 'List, authorize, or revoke collaboration session communication pairs.',
2009
+ recordInput: false,
2010
+ handler: (invocation) => {
2011
+ const usage = 'usage: /collab-auth [list | authorize <sessionA> <sessionB> | grant <from> <to> | revoke <sessionA> <sessionB>]'
2012
+ const parts = invocation.rawInput.trim().split(/\s+/u).filter(Boolean)
2013
+ const action = parts[0] ?? 'list'
2014
+ const statePayload = () => JSON.stringify({ pairs: auth.listPairs(), pending: auth.listPending() })
2015
+ if (action === 'list') {
2016
+ return { kind: 'success', text: statePayload() }
2017
+ }
2018
+ if (action === 'authorize' || action === 'grant' || action === 'revoke') {
2019
+ const a = parts[1]
2020
+ const b = parts[2]
2021
+ if (!isSessionId(a) || !isSessionId(b) || a === b) return { kind: 'error', text: usage }
2022
+ if (action === 'authorize') auth.authorize(a, b, invocation.agent.id)
2023
+ else if (action === 'grant') auth.grant(a, b, invocation.agent.id)
2024
+ else auth.revoke(a, b)
2025
+ return { kind: 'success', text: statePayload() }
2026
+ }
2027
+ return { kind: 'error', text: usage }
2028
+ },
2029
+ })
2030
+
2031
+ ctx.commands.register({
2032
+ name: 'collab-base',
2033
+ description: 'Read or set the current collaboration session base prompt.',
2034
+ recordInput: false,
2035
+ handler: (invocation) => {
2036
+ const usage = 'usage: /collab-base [get | set <base64>]'
2037
+ const parts = invocation.rawInput.trim().split(/\s+/u).filter(Boolean)
2038
+ const action = parts[0] ?? 'get'
2039
+ const sessionId = invocation.agent?.id
2040
+ if (!collabSessions.has(sessionId)) {
2041
+ return { kind: 'error', text: 'not a collaboration session' }
2042
+ }
2043
+ const entry = promptFibers.get(sessionId)
2044
+ if (entry === undefined) {
2045
+ return { kind: 'error', text: 'collaboration session is not initialized' }
2046
+ }
2047
+ const current = typeof entry.layout.meta.basePrompt === 'string' ? entry.layout.meta.basePrompt : ''
2048
+ if (action === 'get') {
2049
+ return { kind: 'success', text: JSON.stringify({ basePrompt: current }) }
2050
+ }
2051
+ if (action === 'set') {
2052
+ let text
2053
+ try {
2054
+ text = Buffer.from(parts[1] ?? '', 'base64').toString('utf8')
2055
+ } catch {
2056
+ return { kind: 'error', text: usage }
2057
+ }
2058
+ if (text.length > MAX_BASE_PROMPT) {
2059
+ return { kind: 'error', text: `base prompt exceeds ${String(MAX_BASE_PROMPT)} characters` }
2060
+ }
2061
+ entry.layout.meta.basePrompt = text
2062
+ entry.layout.meta.updatedAt = Date.now()
2063
+ try {
2064
+ writeJson(path.join(entry.layout.workdir, 'session.json'), entry.layout.meta, 0o600)
2065
+ } catch (error) {
2066
+ return { kind: 'error', text: `could not save base prompt: ${describeError(error)}` }
2067
+ }
2068
+ return { kind: 'success', text: JSON.stringify({ basePrompt: text }) }
2069
+ }
2070
+ return { kind: 'error', text: usage }
2071
+ },
2072
+ })
2073
+
2074
+ ctx.commands.register({
2075
+ name: 'collab-link',
2076
+ description: 'Manage supervisor-worker authorization and live/pinned capability.',
2077
+ recordInput: false,
2078
+ handler: (invocation) => {
2079
+ const supervisor = invocation.agent?.id
2080
+ if (!isSupervisorSession(supervisor)) return { kind: 'error', text: 'not a supervisor session' }
2081
+ const usage = 'usage: /collab-link [get | link <worker> <base64-json> | pin <worker> | live <worker> | unlink <worker>]'
2082
+ const view = relationship => relationship === undefined
2083
+ ? undefined
2084
+ : { ...relationship, capability: effectiveCapability(relationship) }
2085
+ const parts = invocation.rawInput.trim().split(/\s+/u).filter(Boolean)
2086
+ const action = parts[0] ?? 'get'
2087
+ if (action === 'get') {
2088
+ return {
2089
+ kind: 'success',
2090
+ text: JSON.stringify({
2091
+ relationships: relationships.listForSupervisor(supervisor).map(view),
2092
+ workers: workerCandidates(supervisor),
2093
+ }),
2094
+ }
2095
+ }
2096
+ if (action === 'link' || action === 'unlink' || action === 'pin' || action === 'live') {
2097
+ const worker = parts[1]
2098
+ if (!isSessionId(worker) || worker === supervisor) return { kind: 'error', text: usage }
2099
+ const entry = registry.get(worker)
2100
+ if (entry === undefined || entry.preset === SUPERVISOR) return { kind: 'error', text: 'worker must be a collaboration session' }
2101
+ if (action === 'unlink') {
2102
+ relationships.remove(supervisor, worker)
2103
+ auth.revoke(supervisor, worker)
2104
+ return { kind: 'success', text: JSON.stringify({ removed: true, worker, communicationRevoked: true }) }
2105
+ }
2106
+ const existing = relationships.get(supervisor, worker)
2107
+ if ((action === 'pin' || action === 'live') && existing === undefined) {
2108
+ return { kind: 'error', text: 'worker is not registered to this supervisor' }
2109
+ }
2110
+ if (action === 'pin' || action === 'live') {
2111
+ const live = liveCapability(worker)
2112
+ if (live === null) return { kind: 'error', text: 'worker session is unavailable' }
2113
+ try {
2114
+ const relationship = relationships.upsert({
2115
+ supervisor,
2116
+ worker,
2117
+ capabilityOverride: action === 'pin' ? live : null,
2118
+ capabilityVersion: live.version,
2119
+ offer: existing.offer,
2120
+ request: existing.request,
2121
+ createdBy: 'human',
2122
+ })
2123
+ return { kind: 'success', text: JSON.stringify({ relationship: view(relationship) }) }
2124
+ } catch (error) {
2125
+ return { kind: 'error', text: describeError(error) }
2126
+ }
2127
+ }
2128
+ let payload
2129
+ try {
2130
+ payload = JSON.parse(Buffer.from(parts[2] ?? '', 'base64').toString('utf8'))
2131
+ } catch {
2132
+ return { kind: 'error', text: 'link payload must be base64-encoded JSON' }
2133
+ }
2134
+ const live = liveCapability(worker)
2135
+ const override = payload?.override === true ? (payload?.capability ?? null) : undefined
2136
+ const offer = payload?.offer !== false
2137
+ try {
2138
+ const relationship = relationships.upsert({
2139
+ supervisor,
2140
+ worker,
2141
+ capabilityOverride: override,
2142
+ capabilityVersion: live?.version,
2143
+ offer,
2144
+ createdBy: 'human',
2145
+ })
2146
+ auth.authorize(supervisor, worker, 'relationship')
2147
+ return { kind: 'success', text: JSON.stringify({ relationship: view(relationship), authorized: true }) }
2148
+ } catch (error) {
2149
+ return { kind: 'error', text: describeError(error) }
2150
+ }
2151
+ }
2152
+ return { kind: 'error', text: usage }
2153
+ },
2154
+ })
2155
+
2156
+ ctx.commands.register({
2157
+ name: 'collab-board',
2158
+ description: 'Read the supervisor dashboard: relationships, tasks, subtasks, and worker candidates.',
2159
+ recordInput: false,
2160
+ handler: (invocation) => {
2161
+ const supervisor = invocation.agent?.id
2162
+ if (!isSupervisorSession(supervisor)) return { kind: 'error', text: 'not a supervisor session' }
2163
+ return {
2164
+ kind: 'success',
2165
+ text: JSON.stringify({
2166
+ relationships: relationships.listForSupervisor(supervisor).map(relationship => ({
2167
+ ...relationship,
2168
+ capability: effectiveCapability(relationship),
2169
+ })),
2170
+ workers: workerCandidates(supervisor),
2171
+ tasks: tasks.listTasks(supervisor).map(task => TaskStore.taskSummary(task)),
2172
+ subtasks: tasks.listForSupervisor(supervisor).map(subtask => TaskStore.summary(subtask)),
2173
+ requests: requests.listForSupervisor(supervisor).map(request => RequestStore.summary(request)),
2174
+ }),
2175
+ }
2176
+ },
2177
+ })
2178
+
2179
+ /** Management operations used by the UI Remote instead of slash commands. */
2180
+ const panel = (sessionId, operation, args) => {
2181
+ if (!isSessionId(sessionId) || !collabSessions.has(sessionId)) {
2182
+ throw new Error('not an initialized collaboration session')
2183
+ }
2184
+ const op = String(operation ?? '')
2185
+ const supervisor = isSupervisorSession(sessionId)
2186
+ if (op === 'board') {
2187
+ if (!supervisor) throw new Error('not a supervisor session')
2188
+ return {
2189
+ relationships: relationships.listForSupervisor(sessionId).map(relationship => ({
2190
+ ...relationship,
2191
+ capability: effectiveCapability(relationship),
2192
+ })),
2193
+ workers: workerCandidates(sessionId),
2194
+ tasks: tasks.listTasks(sessionId).map(task => TaskStore.taskSummary(task)),
2195
+ subtasks: tasks.listForSupervisor(sessionId).map(subtask => ({
2196
+ ...TaskStore.summary(subtask),
2197
+ workerTitle: registry.get(subtask.worker)?.title ?? null,
2198
+ })),
2199
+ requests: requests.listForSupervisor(sessionId).map(request => ({
2200
+ ...RequestStore.summary(request),
2201
+ requesterTitle: registry.get(request.requester)?.title ?? null,
2202
+ })),
2203
+ }
2204
+ }
2205
+ if (op === 'baseGet' || op === 'baseSet') {
2206
+ const entry = promptFibers.get(sessionId)
2207
+ if (entry === undefined) throw new Error('collaboration session is not initialized')
2208
+ if (op === 'baseGet') {
2209
+ return { basePrompt: typeof entry.layout.meta.basePrompt === 'string' ? entry.layout.meta.basePrompt : '' }
2210
+ }
2211
+ const value = typeof args?.value === 'string' ? args.value : ''
2212
+ if (value.length > MAX_BASE_PROMPT) throw new Error(`base prompt exceeds ${String(MAX_BASE_PROMPT)} characters`)
2213
+ entry.layout.meta.basePrompt = value
2214
+ entry.layout.meta.updatedAt = Date.now()
2215
+ writeJson(path.join(entry.layout.workdir, 'session.json'), entry.layout.meta, 0o600)
2216
+ return { basePrompt: value }
2217
+ }
2218
+ if (op !== 'link' && op !== 'unlink' && op !== 'pin' && op !== 'live') {
2219
+ throw new Error(`unknown panel operation: ${op}`)
2220
+ }
2221
+ if (!supervisor) throw new Error('not a supervisor session')
2222
+ const worker = typeof args?.worker === 'string' ? args.worker : ''
2223
+ if (!isSessionId(worker) || worker === sessionId) throw new Error('invalid worker id')
2224
+ const entry = registry.get(worker)
2225
+ if (entry === undefined || entry.preset === SUPERVISOR) throw new Error('worker must be a collaboration session')
2226
+ const view = relationship => relationship === undefined
2227
+ ? undefined
2228
+ : { ...relationship, capability: effectiveCapability(relationship) }
2229
+ if (op === 'unlink') {
2230
+ relationships.remove(sessionId, worker)
2231
+ auth.revoke(sessionId, worker)
2232
+ return { removed: true, worker, communicationRevoked: true }
2233
+ }
2234
+ const existing = relationships.get(sessionId, worker)
2235
+ if ((op === 'pin' || op === 'live') && existing === undefined) {
2236
+ throw new Error('worker is not registered to this supervisor')
2237
+ }
2238
+ if (op === 'pin' || op === 'live') {
2239
+ const live = liveCapability(worker)
2240
+ if (live === null) throw new Error('worker session is unavailable')
2241
+ const relationship = relationships.upsert({
2242
+ supervisor: sessionId,
2243
+ worker,
2244
+ capabilityOverride: op === 'pin' ? live : null,
2245
+ capabilityVersion: live.version,
2246
+ offer: existing.offer,
2247
+ request: existing.request,
2248
+ createdBy: 'human',
2249
+ })
2250
+ return { relationship: view(relationship) }
2251
+ }
2252
+ const payload = args?.payload !== null && typeof args?.payload === 'object' ? args.payload : {}
2253
+ const live = liveCapability(worker)
2254
+ const override = payload?.override === true ? (payload?.capability ?? null) : undefined
2255
+ const offer = payload?.offer !== false
2256
+ const relationship = relationships.upsert({
2257
+ supervisor: sessionId,
2258
+ worker,
2259
+ capabilityOverride: override,
2260
+ capabilityVersion: live?.version,
2261
+ offer,
2262
+ createdBy: 'human',
2263
+ })
2264
+ auth.authorize(sessionId, worker, 'relationship')
2265
+ return { relationship: view(relationship), authorized: true }
2266
+ }
2267
+ collabAdmin.panel = panel
2268
+
2269
+ for (const definition of tools) {
2270
+ const { when, ...tool } = definition
2271
+ ctx.tools.register(tool, {
2272
+ when: when ?? (({ agent }) => collabSessions.has(agent.id)),
2273
+ })
2274
+ }
2275
+
2276
+ ctx.tools.guard((exec) => {
2277
+ if (exec?.agent === undefined || !isSessionId(exec.agent.id)) return undefined
2278
+ const sessionId = exec.agent.id
2279
+ const self = registry.get(sessionId)
2280
+ // Relative paths resolve against the session's current directory, which may
2281
+ // differ from the collaboration layout after an explicit `cd`.
2282
+ const currentCwd = exec.agent.session === undefined ? undefined : ctx.workingDirectory.get(exec.agent.session)
2283
+ const selfWorkdir = currentCwd ?? self?.workdir
2284
+ if (typeof selfWorkdir !== 'string') return undefined
2285
+ const comparablePath = (value) => {
2286
+ const resolved = path.resolve(value)
2287
+ return process.platform === 'win32' ? resolved.toLowerCase() : resolved
2288
+ }
2289
+ const pathInside = (candidate, root) => {
2290
+ const resolvedCandidate = comparablePath(candidate)
2291
+ const resolvedRoot = comparablePath(root)
2292
+ return resolvedCandidate === resolvedRoot || resolvedCandidate.startsWith(`${resolvedRoot}${path.sep}`)
2293
+ }
2294
+ const canonicalSharedRoot = canonicalPath(sharedRoot)
2295
+ const projectIdFromShared = (resolved) => {
2296
+ if (!pathInside(resolved, canonicalSharedRoot)) return undefined
2297
+ const relative = path.relative(canonicalSharedRoot, resolved).split(path.sep).filter(Boolean)
2298
+ if (relative.length < 2 || relative[1] !== 'artifacts') return undefined
2299
+ return relative[0]
2300
+ }
2301
+ const deliveryAccessFor = (candidate, write) => {
2302
+ if (typeof candidate !== 'string' || candidate.length === 0) return false
2303
+ const resolved = canonicalPath(path.resolve(selfWorkdir, candidate))
2304
+ const projectId = projectIdFromShared(resolved)
2305
+ if (projectId === undefined) return false
2306
+ const project = tasks.project(projectId)
2307
+ if (project === undefined) return false
2308
+ if (isSupervisorSession(sessionId)) return project.supervisor === sessionId && write !== true
2309
+ if (isManagedWorker(sessionId)) {
2310
+ if (write && project.status !== 'open') return false
2311
+ return tasks.listForWorker(sessionId).some(task => (
2312
+ task.taskId === projectId && task.supervisor === project.supervisor
2313
+ ))
2314
+ }
2315
+ if (write) return false
2316
+ return requests.listForRequester(sessionId).some(request => (
2317
+ request.taskId === projectId
2318
+ && (request.status === 'delivered' || (request.status === 'accepted' && request.delivery !== null))
2319
+ && project.requestId === request.id
2320
+ && request.delivery !== null
2321
+ ))
2322
+ }
2323
+ const sharedAccessDenied = (candidates, write) => {
2324
+ for (const candidate of candidates) {
2325
+ if (typeof candidate !== 'string' || candidate.length === 0) continue
2326
+ const lexical = path.resolve(selfWorkdir, candidate)
2327
+ const resolved = canonicalPath(lexical)
2328
+ if (!pathInside(lexical, sharedRoot) && !pathInside(resolved, canonicalSharedRoot)) continue
2329
+ if (pathInside(lexical, sharedRoot) && !pathInside(resolved, canonicalSharedRoot)) return { path: lexical }
2330
+ if (deliveryAccessFor(candidate, write)) continue
2331
+ return { path: lexical }
2332
+ }
2333
+ return undefined
2334
+ }
2335
+ const managedWriteAllowed = (candidate) => {
2336
+ if (!isManagedWorker(sessionId)) return true
2337
+ if (typeof candidate !== 'string' || candidate.length === 0) return false
2338
+ const resolved = canonicalPath(path.resolve(selfWorkdir, candidate))
2339
+ if (deliveryAccessFor(candidate, true)) return true
2340
+ const layoutWorkdir = self?.workdir ?? selfWorkdir
2341
+ for (const own of [path.join(layoutWorkdir, 'private'), path.join(layoutWorkdir, 'comm')]) {
2342
+ if (pathInside(resolved, canonicalPath(own))) return true
2343
+ }
2344
+ return false
2345
+ }
2346
+ const allowedDeliveryPaths = (candidates, write) => candidates.filter(candidate => !deliveryAccessFor(candidate, write))
2347
+
2348
+ const byId = new Map()
2349
+ for (const entry of registry.list()) {
2350
+ if (typeof entry.workdir === 'string') byId.set(entry.sessionId, { sessionId: entry.sessionId, workdir: entry.workdir })
2351
+ }
2352
+ if (typeof self?.workdir === 'string') {
2353
+ for (const sibling of discoverSiblingWorkdirs(self.workdir)) {
2354
+ if (self?.workdir !== undefined && path.resolve(sibling.workdir) === path.resolve(self.workdir)) continue
2355
+ if (!byId.has(sibling.sessionId)) byId.set(sibling.sessionId, sibling)
2356
+ }
2357
+ }
2358
+ const roots = [...byId.values()]
2359
+ const options = { selfId: sessionId, selfWorkdir, selfLayoutWorkdir: self?.workdir, roots }
2360
+ const isCollabCaller = collabSessions.has(sessionId)
2361
+ const args = exec.arguments
2362
+ let hit
2363
+ switch (exec.name) {
2364
+ case 'bash':
2365
+ case 'pwsh': {
2366
+ const shellWorkdir = typeof args?.workdir === 'string' && args.workdir.length > 0
2367
+ ? path.resolve(selfWorkdir, args.workdir)
2368
+ : selfWorkdir
2369
+ // A collaboration shell whose cwd contains another session's work
2370
+ // directory could read it recursively; refuse that cwd. Normal project
2371
+ // sessions keep their full shell so the plugin does not break them.
2372
+ hit = (isCollabCaller ? findForeignAncestorAccess([shellWorkdir], options) : undefined)
2373
+ ?? findForeignSessionAccessInCommand(String(args?.command ?? ''), {
2374
+ ...options,
2375
+ selfWorkdir: shellWorkdir,
2376
+ checkAncestors: isCollabCaller,
2377
+ })
2378
+ if (hit === undefined && typeof args?.workdir === 'string') {
2379
+ hit = findForeignSessionAccess(allowedDeliveryPaths([args.workdir], true), options)
2380
+ }
2381
+ if (hit === undefined && isManagedWorker(sessionId)) {
2382
+ for (const target of shellWriteTargets(String(args?.command ?? ''), shellWorkdir)) {
2383
+ if (!managedWriteAllowed(target)) { hit = { workerWrite: target }; break }
2384
+ }
2385
+ }
2386
+ break
2387
+ }
2388
+ case 'working_directory':
2389
+ hit = findForeignSessionAccess(
2390
+ allowedDeliveryPaths([args?.cd].filter(value => typeof value === 'string'), true),
2391
+ options,
2392
+ )
2393
+ break
2394
+ case 'apply_patch': {
2395
+ const patch = String(args?.input ?? args?.patch ?? '')
2396
+ hit = findForeignSessionAccessInCommand(patch, options)
2397
+ if (hit === undefined && isManagedWorker(sessionId)) {
2398
+ for (const target of applyPatchTargets(patch, selfWorkdir)) {
2399
+ if (!managedWriteAllowed(target)) { hit = { workerWrite: target }; break }
2400
+ }
2401
+ }
2402
+ break
2403
+ }
2404
+ case 'office_render':
2405
+ case 'office_convert':
2406
+ case 'office_recalculate':
2407
+ hit = findForeignSessionAccess(
2408
+ allowedDeliveryPaths([args?.input].filter(value => typeof value === 'string'), true),
2409
+ options,
2410
+ )
2411
+ break
2412
+ case 'present':
2413
+ hit = findForeignSessionAccess(
2414
+ allowedDeliveryPaths(Array.isArray(args?.files) ? args.files.map(file => file?.path).filter(value => typeof value === 'string') : [], false),
2415
+ options,
2416
+ )
2417
+ break
2418
+ case 'read':
2419
+ case 'read_image':
2420
+ hit = findForeignSessionAccess(
2421
+ allowedDeliveryPaths([args?.path, args?.file_path, args?.filePath].filter(value => typeof value === 'string'), false),
2422
+ options,
2423
+ )
2424
+ break
2425
+ case 'write':
2426
+ case 'edit':
2427
+ hit = findForeignSessionAccess(
2428
+ allowedDeliveryPaths([args?.path, args?.file_path, args?.filePath].filter(value => typeof value === 'string'), true),
2429
+ options,
2430
+ )
2431
+ break
2432
+ case 'glob': {
2433
+ const globPath = typeof args?.path === 'string' ? args.path : selfWorkdir
2434
+ const pathAllowed = deliveryAccessFor(globPath, false)
2435
+ hit = findSuspiciousSearchPattern(String(args?.pattern ?? ''), options)
2436
+ ?? (isCollabCaller && !pathAllowed
2437
+ ? findForeignAncestorAccess([globPath].filter(value => typeof value === 'string'), options)
2438
+ : undefined)
2439
+ ?? findForeignSessionAccess(
2440
+ allowedDeliveryPaths([args?.path, args?.pattern].filter(value => typeof value === 'string'), false),
2441
+ options,
2442
+ )
2443
+ break
2444
+ }
2445
+ case 'grep': {
2446
+ const grepPath = typeof args?.path === 'string' ? args.path : selfWorkdir
2447
+ const pathAllowed = deliveryAccessFor(grepPath, false)
2448
+ hit = (isCollabCaller && !pathAllowed
2449
+ ? findForeignAncestorAccess([grepPath].filter(value => typeof value === 'string'), options)
2450
+ : undefined)
2451
+ ?? findSuspiciousSearchPattern(String(args?.pattern ?? ''), options)
2452
+ ?? findForeignSessionAccess(
2453
+ allowedDeliveryPaths([args?.path, args?.pattern].filter(value => typeof value === 'string'), false),
2454
+ options,
2455
+ )
2456
+ break
2457
+ }
2458
+ default:
2459
+ return undefined
2460
+ }
2461
+ if (hit === undefined) {
2462
+ const write = ['write', 'edit', 'apply_patch', 'working_directory', 'office_render', 'office_convert', 'office_recalculate'].includes(exec.name)
2463
+ const candidates = []
2464
+ if (typeof args?.path === 'string') candidates.push(args.path)
2465
+ if (typeof args?.file_path === 'string') candidates.push(args.file_path)
2466
+ if (typeof args?.filePath === 'string') candidates.push(args.filePath)
2467
+ if (typeof args?.input === 'string') candidates.push(args.input)
2468
+ if (typeof args?.cd === 'string') candidates.push(args.cd)
2469
+ if (Array.isArray(args?.files)) candidates.push(...args.files.map(file => file?.path).filter(value => typeof value === 'string'))
2470
+ if (exec.name === 'bash' || exec.name === 'pwsh') {
2471
+ const command = String(args?.command ?? '')
2472
+ const shellWorkdir = typeof args?.workdir === 'string' && args.workdir.length > 0
2473
+ ? path.resolve(selfWorkdir, args.workdir)
2474
+ : selfWorkdir
2475
+ if (commandMentionsSharedRoot(command)) {
2476
+ if (!sharedCommandAllowed(command, sessionId)) hit = { shared: sharedRoot }
2477
+ } else if (isManagedWorker(sessionId)) {
2478
+ hit = sharedAccessDenied([shellWorkdir], true)
2479
+ }
2480
+ if (hit === undefined && !sharedCommandAllowed(command, sessionId)
2481
+ && command.split(/\s+/u).some(token => /shared[\\/]/i.test(token))) {
2482
+ hit = { shared: path.join(sharedRoot, 'shared') }
2483
+ }
2484
+ }
2485
+ if (hit === undefined) hit = sharedAccessDenied(candidates, write)
2486
+ if (hit === undefined && isManagedWorker(sessionId) && ['write', 'edit'].includes(exec.name)) {
2487
+ for (const candidate of candidates) {
2488
+ if (!managedWriteAllowed(candidate)) { hit = { workerWrite: candidate }; break }
2489
+ }
2490
+ }
2491
+ }
2492
+ if (hit === undefined) return undefined
2493
+ if (hit.workerWrite !== undefined) {
2494
+ return {
2495
+ reason: `collab: managed worker may write only its assigned deliveryDir, private/, or comm/ (denied: ${hit.workerWrite})`,
2496
+ info: { name: 'CollabWorkerWriteScope', code: 'COLLAB_WORKER_WRITE_SCOPE' },
2497
+ }
2498
+ }
2499
+ if (hit.shared !== undefined) {
2500
+ return {
2501
+ reason: `collab: shared delivery path is not authorized for this session: ${hit.path ?? hit.shared}. Write only to the deliveryDir assigned by your task; use delivery tools for requester access.`,
2502
+ info: { name: 'CollabSharedDeliveryScope', code: 'COLLAB_SHARED_DELIVERY_SCOPE' },
2503
+ }
2504
+ }
2505
+ return {
2506
+ reason: `collab: session ${sessionId} may not access the work directory of session ${hit.sessionId}`,
2507
+ info: { name: 'CollabWorkdirScope', code: 'COLLAB_WORKDIR_SCOPE' },
2508
+ }
2509
+ })
2510
+
2511
+ ctx.effect(() => () => {
2512
+ for (const timer of requestTimers.values()) clearTimeout(timer)
2513
+ requestTimers.clear()
2514
+ for (const timer of executionTimers.values()) clearTimeout(timer)
2515
+ executionTimers.clear()
2516
+ }, 'collab:request-timeouts')
2517
+
2518
+ ctx.effect(() => {
2519
+ const timer = setInterval(() => { void flushNotices() }, 5000)
2520
+ timer.unref?.()
2521
+ return () => clearInterval(timer)
2522
+ }, 'collab:notice-outbox')
2523
+
2524
+ installPerSessionSandbox()
2525
+ try { tasks.migrate() } catch (error) { warn(`task state migration failed: ${describeError(error)}`) }
2526
+ try { requests.migrate() } catch (error) { warn(`request state migration failed: ${describeError(error)}`) }
2527
+ refreshRegistry()
2528
+ reconcileRequestProjectBindings()
2529
+ pruneDeliveryAliases()
2530
+ sweepRequestTimeouts()
2531
+ sweepExecutionDeadlines()
2532
+ void flushNotices()
2533
+ for (const entry of registry.list()) {
2534
+ try { migrateSessionArchive(entry.workdir) } catch (error) { warn(`archive migration failed for ${entry.sessionId}: ${describeError(error)}`) }
2535
+ }
2536
+ for (const agent of ctx.agents.list()) void setupAgent(agent)
2537
+ ctx.on('agent/created', async ({ agent }) => { await setupAgent(agent) })
2538
+ ctx.on('agent/disposed', ({ agent }) => {
2539
+ sandboxDeliveryRoots.delete(agent.id)
2540
+ sandboxReadRoots.delete(agent.id)
2541
+ collabSessions.delete(agent.id)
2542
+ sessionPresets.delete(agent.id)
2543
+ disposePrompt(agent.id)
2544
+ })
2545
+ ctx.on('agent-preset/selected', async (sessionId, selected) => {
2546
+ if (COLLAB_PRESETS.has(selected)) {
2547
+ const agent = ctx.agents.get(sessionId)
2548
+ if (agent !== undefined) await setupAgent(agent, { force: true, preset: selected })
2549
+ return
2550
+ }
2551
+ collabSessions.delete(sessionId)
2552
+ sessionPresets.delete(sessionId)
2553
+ disposePrompt(sessionId)
2554
+ })
2555
+ ctx.on('session/event', (session, event) => {
2556
+ if (event.type !== 'tool/call') return
2557
+ const callId = event.data?.callId
2558
+ const turn = event.data?.turn
2559
+ if (typeof callId !== 'string' || typeof turn !== 'number') return
2560
+ callTurns.set(callId, { sessionId: session.id, turn })
2561
+ if (callTurns.size > 2000) {
2562
+ const oldest = callTurns.keys().next().value
2563
+ if (oldest !== undefined) callTurns.delete(oldest)
2564
+ }
2565
+ })
2566
+
2567
+ ctx.on('session/event', (session, event) => {
2568
+ if (event.type !== 'session/title') return
2569
+ const entry = registry.get(session.id)
2570
+ if (entry === undefined) return
2571
+ const title = event.data?.title
2572
+ if (typeof title === 'string' && title.length > 0) {
2573
+ registry.upsert({ ...entry, title, updatedAt: Date.now() })
2574
+ }
2575
+ })
2576
+
2577
+ ctx.effect(() => () => {
2578
+ for (const sessionId of [...promptFibers.keys()]) disposePrompt(sessionId)
2579
+ collabSessions.clear()
2580
+ }, 'collab:agent-registrations')
2581
+ }
2582
+
2583
+ export { SUBDIR, SessionRegistry }