@xmodelin/dsh-collab-sessions 0.0.2 → 0.0.4

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 CHANGED
@@ -23,6 +23,17 @@ import {
23
23
  findForeignSessionAccessInCommand, findSuspiciousSearchPattern, inboxCount,
24
24
  canonicalPath, configureFileLocks, isDirectory, isSessionId, listInbox, markRead, migrateSessionArchive, mkdirp, readJson, sendMessage, writeJson,
25
25
  } from './lib/layout.js'
26
+ import { TEXT_OUTPUT, NO_PARAMETERS, SEND_PARAMETERS, INBOX_PARAMETERS, TASK_OPEN_PARAMETERS, TASK_CREATE_PARAMETERS, TASK_ASSIGN_PARAMETERS, TASK_ID_PARAMETERS, TASK_LIST_PARAMETERS, TASK_REJECT_PARAMETERS, TASK_PROGRESS_PARAMETERS, TASK_COMPLETE_PARAMETERS, TASK_FAIL_PARAMETERS, TASK_CLOSE_PARAMETERS, DELIVERY_LIST_PARAMETERS, DELIVERY_MANIFEST_PARAMETERS, REQUEST_DELIVER_PARAMETERS, REQUEST_SUBMIT_PARAMETERS, REQUEST_LIST_PARAMETERS, REQUEST_ACCEPT_PARAMETERS, REQUEST_REJECT_PARAMETERS, REQUEST_CANCEL_PARAMETERS, REQUEST_HEARTBEAT_PARAMETERS } from './lib/tool-schemas.js'
27
+ import { COLLAB_PRESET as PRESET, SUPERVISOR_PRESET as SUPERVISOR, COLLAB_PRESETS } from './lib/presets.js'
28
+ import { subtaskAliases } from './lib/task-aliases.js'
29
+ import { createDeliveryManifestService } from './lib/delivery-manifest.js'
30
+ import { AuditLog } from './lib/audit.js'
31
+ import { cancelBoundTask } from './lib/cancel-request.js'
32
+ import { createPanelApi } from './lib/panel-api.js'
33
+ import { collectHealth } from './lib/health.js'
34
+ import { createAccessPolicy } from './lib/access-policy.js'
35
+ import { promptText } from './lib/prompt.js'
36
+ import { taskDetail, taskLine } from './lib/task-views.js'
26
37
 
27
38
  /** Cordis plugin name used by Loader diagnostics. */
28
39
  export const name = 'dsh-collab-sessions'
@@ -30,230 +41,11 @@ export const name = 'dsh-collab-sessions'
30
41
  /** Services required for session discovery, tools, prompts, and the working directory. */
31
42
  export const inject = ['tools', 'agents', 'systemPrompt', 'workingDirectory', 'commands']
32
43
 
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
44
  const MAX_MESSAGE_BYTES = 64 * 1024
42
45
 
43
46
  /** Upper bound for one session's configured base prompt. */
44
47
  const MAX_BASE_PROMPT = 16 * 1024
45
48
 
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
49
  function describeError(error) {
258
50
  return error instanceof Error ? error.message : String(error)
259
51
  }
@@ -263,106 +55,6 @@ function iso(time) {
263
55
  }
264
56
 
265
57
  /** 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
58
  function resolveOriginalCwd(ctx, session) {
367
59
  const headerCwd = session?.header?.cwd
368
60
  if (typeof headerCwd === 'string' && headerCwd.length > 0) return headerCwd
@@ -410,6 +102,7 @@ export function apply(ctx, config = {}) {
410
102
  : 24 * 60 * 60 * 1000
411
103
  const perSessionSandbox = config.perSessionSandbox !== false && process.platform !== 'win32'
412
104
  const registry = new SessionRegistry(registryPath)
105
+ const audit = new AuditLog(path.join(path.dirname(registryPath), 'audit.jsonl'))
413
106
  const auth = new AuthorizationStore(
414
107
  typeof config.authorizationPath === 'string' && config.authorizationPath.length > 0
415
108
  ? config.authorizationPath
@@ -442,20 +135,25 @@ export function apply(ctx, config = {}) {
442
135
  const deliveryInFlight = new Set()
443
136
  let noticeFlushInFlight = false
444
137
  /** Human-facing authorization operations shared by the UI Remote and commands. */
138
+ const isKnownCollab = (id) => collabSessions.has(id)
139
+ || registry.get(id)?.preset === PRESET
140
+ || registry.get(id)?.preset === SUPERVISOR
445
141
  const collabAdmin = {
142
+ isKnownCollab,
143
+ audit: (limit = 100) => audit.tail(limit),
446
144
  listAuth: () => ({
447
- pairs: auth.listPairs(),
448
- pending: auth.listPending(),
145
+ pairs: auth.listPairs().filter(pair => isKnownCollab(pair.a) && isKnownCollab(pair.b)),
146
+ pending: auth.listPending().filter(grant => isKnownCollab(grant.from) && isKnownCollab(grant.to)),
449
147
  }),
450
148
  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')
149
+ if (!isKnownCollab(a) || !isKnownCollab(b)) throw new Error('authorization requires two known collaboration sessions')
454
150
  auth.authorize(a, b, 'ui')
151
+ audit.append('authorization.authorize', { a, b })
455
152
  return collabAdmin.listAuth()
456
153
  },
457
154
  revoke: (a, b) => {
458
155
  auth.revoke(a, b)
156
+ audit.append('authorization.revoke', { a, b })
459
157
  return collabAdmin.listAuth()
460
158
  },
461
159
  }
@@ -667,7 +365,7 @@ export function apply(ctx, config = {}) {
667
365
  collabSessions.add(agent.id)
668
366
  sessionPresets.set(agent.id, effectivePreset)
669
367
  for (const task of tasks.listForWorker(agent.id)) {
670
- const project = tasks.project(task.taskId)
368
+ const project = tasks.task(task.taskId)
671
369
  bindDeliverySandbox(agent.id, deliveryRoot(task.taskId), project?.status === 'open')
672
370
  }
673
371
  return true
@@ -759,7 +457,42 @@ export function apply(ctx, config = {}) {
759
457
  }
760
458
  }
761
459
 
762
- const deliveryRoot = (projectId) => path.join(sharedRoot, projectId ?? 'default', 'artifacts')
460
+ const MAX_DELIVERY_LIST_FILES = 2000
461
+ const listDeliveryFiles = (root, base = root, out = []) => {
462
+ if (out.length >= MAX_DELIVERY_LIST_FILES) { out.truncated = true; return out }
463
+ let entries
464
+ try { entries = fs.readdirSync(root, { withFileTypes: true }) } catch { return out }
465
+ for (const entry of entries) {
466
+ if (out.length >= MAX_DELIVERY_LIST_FILES) { out.truncated = true; break }
467
+ const full = path.join(root, entry.name)
468
+ if (entry.isDirectory()) {
469
+ listDeliveryFiles(full, base, out)
470
+ continue
471
+ }
472
+ if (!entry.isFile()) continue
473
+ let stat
474
+ try { stat = fs.statSync(full) } catch { continue }
475
+ out.push({
476
+ path: path.relative(base, full),
477
+ size: stat.size,
478
+ modifiedAt: stat.mtimeMs,
479
+ })
480
+ }
481
+ return out
482
+ }
483
+ const { buildDeliveryManifest, publishDeliveryAlias } = createDeliveryManifestService({
484
+ sharedRoot,
485
+ tasks,
486
+ fs,
487
+ path,
488
+ crypto,
489
+ mkdirp,
490
+ writeJson,
491
+ listDeliveryFiles,
492
+ warn,
493
+ maxFiles: MAX_DELIVERY_LIST_FILES,
494
+ })
495
+ const deliveryRoot = (taskId) => path.join(sharedRoot, taskId ?? 'default', 'artifacts')
763
496
 
764
497
  const peersText = (self) => {
765
498
  const entries = registry.list().filter(entry => entry.sessionId !== self.sessionId && COLLAB_PRESETS.has(entry.preset))
@@ -1133,10 +866,6 @@ export function apply(ctx, config = {}) {
1133
866
  }
1134
867
  })
1135
868
 
1136
- const taskLine = (task) => (
1137
- `- ${task.id} [${task.status}] worker=${task.worker ?? 'unassigned'} task=${task.taskId ?? '-'} title=${JSON.stringify(task.title)}`
1138
- )
1139
-
1140
869
  /** Turn number for one executing tool call, when the session event is known. */
1141
870
  const turnForCall = (exec) => {
1142
871
  const found = callTurns.get(String(exec?.callId))
@@ -1145,114 +874,12 @@ export function apply(ctx, config = {}) {
1145
874
  return found.turn
1146
875
  }
1147
876
 
1148
- const taskDetail = (task) => ({
1149
- id: task.id,
1150
- subtaskId: task.id,
1151
- taskId: task.taskId,
1152
- supervisor: task.supervisor,
1153
- worker: task.worker,
1154
- title: task.title,
1155
- instruction: task.instruction,
1156
- inputs: task.inputs,
1157
- acceptance: task.acceptance,
1158
- status: task.status,
1159
- attempts: task.attempts,
1160
- createdTurn: task.createdTurn,
1161
- assignedTurn: task.assignedTurn,
1162
- capabilityVersion: task.capabilityVersion,
1163
- result: task.result,
1164
- failure: task.failure,
1165
- history: task.history,
1166
- })
1167
-
1168
877
  const deliveryDirFor = (task) => deliveryRoot(task.taskId)
1169
878
 
1170
- /** Build the canonical project manifest with path/bytes/sha256/mode. */
1171
- const buildDeliveryManifest = (projectId) => {
1172
- const project = tasks.project(projectId)
1173
- if (project === undefined) throw new Error('unknown project')
1174
- const root = deliveryRoot(projectId)
1175
- const listed = listDeliveryFiles(root)
1176
- if (listed.truncated === true) throw new Error(`delivery has more than ${MAX_DELIVERY_LIST_FILES} files; split the project`)
1177
- const files = listed.sort((left, right) => left.path.localeCompare(right.path)).map(file => {
1178
- const full = path.join(root, file.path)
1179
- const before = fs.statSync(full)
1180
- const content = fs.readFileSync(full)
1181
- const after = fs.statSync(full)
1182
- if (before.size !== after.size || before.mtimeMs !== after.mtimeMs) {
1183
- throw new Error(`delivery file changed while hashing: ${file.path}`)
1184
- }
1185
- const hash = crypto.createHash('sha256').update(content).digest('hex')
1186
- return {
1187
- path: file.path.split(path.sep).join('/'),
1188
- bytes: after.size,
1189
- sha256: hash,
1190
- mode: `0${(after.mode & 0o777).toString(8)}`,
1191
- }
1192
- })
1193
- const manifest = {
1194
- generatedAt: new Date().toISOString(),
1195
- root,
1196
- files,
1197
- }
1198
- const projectDir = path.join(sharedRoot, projectId)
1199
- mkdirp(projectDir, 0o755)
1200
- const manifestPath = path.join(projectDir, 'manifest.json')
1201
- const temporary = `${manifestPath}.${crypto.randomBytes(4).toString('hex')}.tmp`
1202
- writeJson(temporary, manifest, 0o644)
1203
- fs.renameSync(temporary, manifestPath)
1204
- return manifest
1205
- }
1206
-
1207
-
1208
- const MAX_DELIVERY_LIST_FILES = 2000
1209
- /** Publish an opaque delivery alias so the requester never receives projectId. */
1210
- const publishDeliveryAlias = (projectId, deliveryId) => {
1211
- const target = path.join(sharedRoot, projectId, 'artifacts')
1212
- const aliasRoot = path.join(sharedRoot, '.deliveries', deliveryId)
1213
- const alias = path.join(aliasRoot, 'artifacts')
1214
- mkdirp(aliasRoot, 0o755)
1215
- try {
1216
- const existing = fs.lstatSync(alias)
1217
- if (existing.isSymbolicLink() && fs.realpathSync(alias) === fs.realpathSync(target)) return alias
1218
- fs.rmSync(alias, { recursive: true, force: true })
1219
- } catch { /* alias does not exist yet */ }
1220
- try {
1221
- fs.symlinkSync(target, alias, 'dir')
1222
- return alias
1223
- } catch (error) {
1224
- warn(`delivery alias could not be published: ${describeError(error)}`)
1225
- return target
1226
- }
1227
- }
1228
-
1229
- const listDeliveryFiles = (root, base = root, out = []) => {
1230
- if (out.length >= MAX_DELIVERY_LIST_FILES) { out.truncated = true; return out }
1231
- let entries
1232
- try { entries = fs.readdirSync(root, { withFileTypes: true }) } catch { return out }
1233
- for (const entry of entries) {
1234
- if (out.length >= MAX_DELIVERY_LIST_FILES) { out.truncated = true; break }
1235
- const full = path.join(root, entry.name)
1236
- if (entry.isDirectory()) {
1237
- listDeliveryFiles(full, base, out)
1238
- continue
1239
- }
1240
- if (!entry.isFile()) continue
1241
- let stat
1242
- try { stat = fs.statSync(full) } catch { continue }
1243
- out.push({
1244
- path: path.relative(base, full),
1245
- size: stat.size,
1246
- modifiedAt: stat.mtimeMs,
1247
- })
1248
- }
1249
- return out
1250
- }
1251
-
1252
879
  const reconcileRequestProjectBindings = () => {
1253
880
  for (const request of requests.list().sort((left, right) => left.createdAt - right.createdAt)) {
1254
881
  if (request.status !== 'accepted' || typeof request.taskId !== 'string') continue
1255
- const project = tasks.project(request.taskId)
882
+ const project = tasks.task(request.taskId)
1256
883
  if (project === undefined) continue
1257
884
  if ((project.requestId ?? null) === null) {
1258
885
  try {
@@ -1323,9 +950,24 @@ export function apply(ctx, config = {}) {
1323
950
  return lines.join('\n')
1324
951
  },
1325
952
  },
953
+ {
954
+ name: 'collab_task_open',
955
+ description: 'Open the parent task for one requirement. Create subtasks under the returned taskId.',
956
+ parameters: TASK_OPEN_PARAMETERS,
957
+ output: TEXT_OUTPUT,
958
+ when: ({ agent }) => isSupervisorSession(agent.id),
959
+ execute: (args, exec) => {
960
+ const self = requireSupervisor(exec)
961
+ const title = String(args?.title ?? '').trim()
962
+ if (title.length === 0) throw new Error('task title must not be empty')
963
+ const task = tasks.createTask({ supervisor: self.sessionId, title })
964
+ audit.append('task.opened', { taskId: task.id, supervisor: self.sessionId, title })
965
+ return JSON.stringify({ task: TaskStore.taskSummary(task) })
966
+ },
967
+ },
1326
968
  {
1327
969
  name: 'collab_task_create',
1328
- description: 'Create a subtask for a functional worker. Omit taskId to create the parent task for this requirement.',
970
+ description: 'Create a subtask under an existing parent task opened with collab_task_open.',
1329
971
  parameters: TASK_CREATE_PARAMETERS,
1330
972
  output: TEXT_OUTPUT,
1331
973
  when: ({ agent }) => isSupervisorSession(agent.id),
@@ -1340,17 +982,11 @@ export function apply(ctx, config = {}) {
1340
982
  if (mentionsSharedCopy) {
1341
983
  throw new Error('do not create copy-out tasks; workers receive a canonical deliveryDir and publish artifacts there')
1342
984
  }
1343
- let taskId = typeof args?.taskId === 'string' && args.taskId.trim().length > 0
1344
- ? args.taskId.trim()
1345
- : (typeof args?.projectId === 'string' && args.projectId.trim().length > 0 ? args.projectId.trim() : undefined)
1346
- if (taskId === undefined) {
1347
- const task = tasks.createTask({ supervisor: self.sessionId, title })
1348
- taskId = task.id
1349
- } else {
1350
- const task = tasks.task(taskId)
1351
- if (task === undefined || task.supervisor !== self.sessionId) throw new Error(`unknown task: ${taskId}`)
1352
- if (task.status !== 'open') throw new Error('task is closed')
1353
- }
985
+ const taskId = String(args?.taskId ?? '').trim()
986
+ if (taskId.length === 0) throw new Error('taskId is required; call collab_task_open first')
987
+ const task = tasks.task(taskId)
988
+ if (task === undefined || task.supervisor !== self.sessionId) throw new Error(`unknown task: ${taskId}`)
989
+ if (task.status !== 'open') throw new Error('task is closed')
1354
990
  const subtask = tasks.createSubtask({
1355
991
  supervisor: self.sessionId,
1356
992
  worker: null,
@@ -1384,7 +1020,7 @@ export function apply(ctx, config = {}) {
1384
1020
  if (!auth.isAuthorized(self.sessionId, worker)) {
1385
1021
  throw new Error('未授权:请在“协同授权”页授权双方。')
1386
1022
  }
1387
- const project = task.taskId === null ? undefined : tasks.project(task.taskId)
1023
+ const project = task.taskId === null ? undefined : tasks.task(task.taskId)
1388
1024
  if (project !== undefined && project.status !== 'open') throw new Error('project is closed')
1389
1025
  const otherActive = tasks.listForWorker(worker)
1390
1026
  .filter(entry => entry.id !== subtaskId && !['done', 'failed', 'cancelled'].includes(entry.status))
@@ -1394,6 +1030,7 @@ export function apply(ctx, config = {}) {
1394
1030
  mkdirp(deliveryDir, 0o755)
1395
1031
  bindDeliverySandbox(worker, deliveryDir)
1396
1032
  const assigned = tasks.assign(subtaskId, worker, turnForCall(exec), effectiveCapability(relationship)?.version ?? null)
1033
+ audit.append('task.assigned', { taskId: assigned.id, supervisor: self.sessionId, worker })
1397
1034
  const payload = {
1398
1035
  type: 'collab-task/assign',
1399
1036
  version: 1,
@@ -1462,6 +1099,7 @@ export function apply(ctx, config = {}) {
1462
1099
  throw new Error('task is already bound to another request')
1463
1100
  }
1464
1101
  const acceptedAt = Date.now()
1102
+ audit.append('request.accepted', { requestId: request.id, taskId, supervisor: self.sessionId })
1465
1103
  const accepted = requests.accept(request.id, {
1466
1104
  taskId,
1467
1105
  subtaskIds: assigned.map(subtask => subtask.id),
@@ -1648,7 +1286,12 @@ export function apply(ctx, config = {}) {
1648
1286
  const task = tasks.task(taskId)
1649
1287
  if (task === undefined || task.supervisor !== self.sessionId) throw new Error('unknown task')
1650
1288
  const owned = tasks.listForSupervisor(self.sessionId).filter(subtask => subtask.taskId === taskId)
1289
+ const active = owned.filter(subtask => !['done', 'cancelled'].includes(subtask.status))
1290
+ if (active.length > 0) {
1291
+ throw new Error(`task still has ${String(active.length)} active subtask(s); complete or cancel them before closing`)
1292
+ }
1651
1293
  const closed = tasks.closeTask(taskId)
1294
+ audit.append('task.closed', { taskId, supervisor: self.sessionId })
1652
1295
  for (const task of owned) {
1653
1296
  if (task.worker !== null) releaseDeliverySandbox(task.worker, deliveryRoot(taskId))
1654
1297
  }
@@ -1758,6 +1401,7 @@ export function apply(ctx, config = {}) {
1758
1401
  deliveredAt: Date.now(),
1759
1402
  ...(supersedes === null ? {} : { supersedes }),
1760
1403
  })
1404
+ audit.append('delivery.published', { requestId: request.id, taskId: request.taskId, deliveryId })
1761
1405
  clearExecutionTimer(request.id)
1762
1406
  return JSON.stringify({ requestId: request.id, status: recorded.status, files: manifest.files.length, deliveryId, delivery })
1763
1407
  } finally {
@@ -1810,6 +1454,7 @@ export function apply(ctx, config = {}) {
1810
1454
  details: args?.details,
1811
1455
  artifacts: args?.artifacts,
1812
1456
  })
1457
+ audit.append('task.completed', { taskId: completed.id, worker: self.sessionId })
1813
1458
  const delivery = await sendTaskNotice(self, completed.supervisor, {
1814
1459
  type: 'collab-task/result',
1815
1460
  version: 1,
@@ -1911,6 +1556,9 @@ export function apply(ctx, config = {}) {
1911
1556
  const cancelled = requests.cancel(request.id, self.sessionId)
1912
1557
  clearRequestTimer(request.id)
1913
1558
  clearExecutionTimer(request.id)
1559
+ if (request.taskId !== null) {
1560
+ cancelBoundTask(tasks, request.taskId, worker => releaseDeliverySandbox(worker, deliveryRoot(request.taskId)))
1561
+ }
1914
1562
  try {
1915
1563
  await sendTaskNotice(self, request.supervisor, {
1916
1564
  type: 'collab-task/request-cancelled',
@@ -1924,6 +1572,25 @@ export function apply(ctx, config = {}) {
1924
1572
  },
1925
1573
  ]
1926
1574
 
1575
+ taskTools.push({
1576
+ name: 'collab_task_list',
1577
+ description: 'List parent tasks for this supervisor.',
1578
+ parameters: TASK_LIST_PARAMETERS,
1579
+ output: TEXT_OUTPUT,
1580
+ when: ({ agent }) => isSupervisorSession(agent.id),
1581
+ isConcurrencySafe: () => true,
1582
+ execute: (args, exec) => {
1583
+ const self = requireSupervisor(exec)
1584
+ const status = typeof args?.status === 'string' && args.status.trim().length > 0 ? args.status.trim() : undefined
1585
+ const list = tasks.listTasks(self.sessionId)
1586
+ .filter(task => status === undefined || task.status === status)
1587
+ .map(task => TaskStore.taskSummary(task))
1588
+ return list.length === 0 ? 'No tasks.' : JSON.stringify(list)
1589
+ },
1590
+ })
1591
+
1592
+ taskTools.push(...subtaskAliases(taskTools))
1593
+
1927
1594
  const tools = [
1928
1595
  {
1929
1596
  name: 'collab_info',
@@ -1933,6 +1600,27 @@ export function apply(ctx, config = {}) {
1933
1600
  isConcurrencySafe: () => true,
1934
1601
  execute: (_args, exec) => infoText(requireSelf(exec)),
1935
1602
  },
1603
+ {
1604
+ name: 'collab_doctor',
1605
+ description: 'Read-only collaboration health summary: registry, relationships, grants, tasks, requests, and audit availability.',
1606
+ parameters: NO_PARAMETERS,
1607
+ output: TEXT_OUTPUT,
1608
+ when: ({ agent }) => collabSessions.has(agent.id),
1609
+ isConcurrencySafe: () => true,
1610
+ execute: (_args, exec) => {
1611
+ const self = requireSelf(exec)
1612
+ return JSON.stringify(collectHealth({
1613
+ sessionId: self.sessionId,
1614
+ registryEntries: registry.list(),
1615
+ relationships: relationships.list(),
1616
+ grants: auth.listGrants(),
1617
+ tasks: tasks.listTasks(self.sessionId),
1618
+ requests: requests.list(),
1619
+ auditEntries: collabAdmin.audit(1).length,
1620
+ isSupervisor: isSupervisorSession(self.sessionId),
1621
+ }))
1622
+ },
1623
+ },
1936
1624
  {
1937
1625
  name: 'collab_peers',
1938
1626
  description: 'List other collaboration sessions with their role, session id, authorization, and online state.',
@@ -2023,9 +1711,15 @@ export function apply(ctx, config = {}) {
2023
1711
  const a = parts[1]
2024
1712
  const b = parts[2]
2025
1713
  if (!isSessionId(a) || !isSessionId(b) || a === b) return { kind: 'error', text: usage }
2026
- if (action === 'authorize') auth.authorize(a, b, invocation.agent.id)
2027
- else if (action === 'grant') auth.grant(a, b, invocation.agent.id)
2028
- else auth.revoke(a, b)
1714
+ if (action === 'revoke') {
1715
+ auth.revoke(a, b)
1716
+ } else {
1717
+ if (!collabAdmin.isKnownCollab(a) || !collabAdmin.isKnownCollab(b)) {
1718
+ return { kind: 'error', text: 'authorization requires two known collaboration sessions' }
1719
+ }
1720
+ if (action === 'authorize') auth.authorize(a, b, invocation.agent.id)
1721
+ else auth.grant(a, b, invocation.agent.id)
1722
+ }
2029
1723
  return { kind: 'success', text: statePayload() }
2030
1724
  }
2031
1725
  return { kind: 'error', text: usage }
@@ -2275,6 +1969,7 @@ export function apply(ctx, config = {}) {
2275
1969
  return { relationship: view(relationship), authorized: true }
2276
1970
  }
2277
1971
  collabAdmin.panel = panel
1972
+ Object.assign(collabAdmin, createPanelApi(panel))
2278
1973
 
2279
1974
  for (const definition of tools) {
2280
1975
  const { when, ...tool } = definition
@@ -2292,68 +1987,16 @@ export function apply(ctx, config = {}) {
2292
1987
  const currentCwd = exec.agent.session === undefined ? undefined : ctx.workingDirectory.get(exec.agent.session)
2293
1988
  const selfWorkdir = currentCwd ?? self?.workdir
2294
1989
  if (typeof selfWorkdir !== 'string') return undefined
2295
- const comparablePath = (value) => {
2296
- const resolved = path.resolve(value)
2297
- return process.platform === 'win32' ? resolved.toLowerCase() : resolved
2298
- }
2299
- const pathInside = (candidate, root) => {
2300
- const resolvedCandidate = comparablePath(candidate)
2301
- const resolvedRoot = comparablePath(root)
2302
- return resolvedCandidate === resolvedRoot || resolvedCandidate.startsWith(`${resolvedRoot}${path.sep}`)
2303
- }
2304
- const canonicalSharedRoot = canonicalPath(sharedRoot)
2305
- const projectIdFromShared = (resolved) => {
2306
- if (!pathInside(resolved, canonicalSharedRoot)) return undefined
2307
- const relative = path.relative(canonicalSharedRoot, resolved).split(path.sep).filter(Boolean)
2308
- if (relative.length < 2 || relative[1] !== 'artifacts') return undefined
2309
- return relative[0]
2310
- }
2311
- const deliveryAccessFor = (candidate, write) => {
2312
- if (typeof candidate !== 'string' || candidate.length === 0) return false
2313
- const resolved = canonicalPath(path.resolve(selfWorkdir, candidate))
2314
- const projectId = projectIdFromShared(resolved)
2315
- if (projectId === undefined) return false
2316
- const project = tasks.project(projectId)
2317
- if (project === undefined) return false
2318
- if (isSupervisorSession(sessionId)) return project.supervisor === sessionId && write !== true
2319
- if (isManagedWorker(sessionId)) {
2320
- if (write && project.status !== 'open') return false
2321
- return tasks.listForWorker(sessionId).some(task => (
2322
- task.taskId === projectId && task.supervisor === project.supervisor
2323
- ))
2324
- }
2325
- if (write) return false
2326
- return requests.listForRequester(sessionId).some(request => (
2327
- request.taskId === projectId
2328
- && (request.status === 'delivered' || (request.status === 'accepted' && request.delivery !== null))
2329
- && project.requestId === request.id
2330
- && request.delivery !== null
2331
- ))
2332
- }
2333
- const sharedAccessDenied = (candidates, write) => {
2334
- for (const candidate of candidates) {
2335
- if (typeof candidate !== 'string' || candidate.length === 0) continue
2336
- const lexical = path.resolve(selfWorkdir, candidate)
2337
- const resolved = canonicalPath(lexical)
2338
- if (!pathInside(lexical, sharedRoot) && !pathInside(resolved, canonicalSharedRoot)) continue
2339
- if (pathInside(lexical, sharedRoot) && !pathInside(resolved, canonicalSharedRoot)) return { path: lexical }
2340
- if (deliveryAccessFor(candidate, write)) continue
2341
- return { path: lexical }
2342
- }
2343
- return undefined
2344
- }
2345
- const managedWriteAllowed = (candidate) => {
2346
- if (!isManagedWorker(sessionId)) return true
2347
- if (typeof candidate !== 'string' || candidate.length === 0) return false
2348
- const resolved = canonicalPath(path.resolve(selfWorkdir, candidate))
2349
- if (deliveryAccessFor(candidate, true)) return true
2350
- const layoutWorkdir = self?.workdir ?? selfWorkdir
2351
- for (const own of [path.join(layoutWorkdir, 'private'), path.join(layoutWorkdir, 'comm')]) {
2352
- if (pathInside(resolved, canonicalPath(own))) return true
2353
- }
2354
- return false
2355
- }
2356
- const allowedDeliveryPaths = (candidates, write) => candidates.filter(candidate => !deliveryAccessFor(candidate, write))
1990
+ const { deliveryAccessFor, sharedAccessDenied, managedWriteAllowed, allowedDeliveryPaths } = createAccessPolicy({
1991
+ sharedRoot,
1992
+ sessionId,
1993
+ selfWorkdir,
1994
+ layoutWorkdir: self?.workdir ?? selfWorkdir,
1995
+ tasks,
1996
+ requests,
1997
+ isSupervisorSession,
1998
+ isManagedWorker,
1999
+ })
2357
2000
 
2358
2001
  const byId = new Map()
2359
2002
  for (const entry of registry.list()) {
@@ -2531,10 +2174,28 @@ export function apply(ctx, config = {}) {
2531
2174
  return () => clearInterval(timer)
2532
2175
  }, 'collab:notice-outbox')
2533
2176
 
2177
+ const pruneInvalidCollabState = () => {
2178
+ for (const grant of auth.listGrants()) {
2179
+ const from = registry.get(grant.from)
2180
+ const to = registry.get(grant.to)
2181
+ if ((from !== undefined && from.preset !== PRESET && from.preset !== SUPERVISOR)
2182
+ || (to !== undefined && to.preset !== PRESET && to.preset !== SUPERVISOR)) {
2183
+ try { auth.revoke(grant.from, grant.to) } catch (error) { warn(`could not prune invalid grant ${grant.from} -> ${grant.to}: ${describeError(error)}`) }
2184
+ }
2185
+ }
2186
+ for (const relationship of relationships.list()) {
2187
+ const worker = registry.get(relationship.worker)
2188
+ if (worker !== undefined && worker.preset !== PRESET) {
2189
+ try { relationships.remove(relationship.supervisor, relationship.worker) } catch (error) { warn(`could not prune invalid relationship: ${describeError(error)}`) }
2190
+ }
2191
+ }
2192
+ }
2193
+
2534
2194
  installPerSessionSandbox()
2535
2195
  try { tasks.migrate() } catch (error) { warn(`task state migration failed: ${describeError(error)}`) }
2536
2196
  try { requests.migrate() } catch (error) { warn(`request state migration failed: ${describeError(error)}`) }
2537
2197
  refreshRegistry()
2198
+ pruneInvalidCollabState()
2538
2199
  reconcileRequestProjectBindings()
2539
2200
  pruneDeliveryAliases()
2540
2201
  sweepRequestTimeouts()