@xmodelin/dsh-collab-sessions 0.0.3 → 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
@@ -446,6 +139,8 @@ export function apply(ctx, config = {}) {
446
139
  || registry.get(id)?.preset === PRESET
447
140
  || registry.get(id)?.preset === SUPERVISOR
448
141
  const collabAdmin = {
142
+ isKnownCollab,
143
+ audit: (limit = 100) => audit.tail(limit),
449
144
  listAuth: () => ({
450
145
  pairs: auth.listPairs().filter(pair => isKnownCollab(pair.a) && isKnownCollab(pair.b)),
451
146
  pending: auth.listPending().filter(grant => isKnownCollab(grant.from) && isKnownCollab(grant.to)),
@@ -453,10 +148,12 @@ export function apply(ctx, config = {}) {
453
148
  authorize: (a, b) => {
454
149
  if (!isKnownCollab(a) || !isKnownCollab(b)) throw new Error('authorization requires two known collaboration sessions')
455
150
  auth.authorize(a, b, 'ui')
151
+ audit.append('authorization.authorize', { a, b })
456
152
  return collabAdmin.listAuth()
457
153
  },
458
154
  revoke: (a, b) => {
459
155
  auth.revoke(a, b)
156
+ audit.append('authorization.revoke', { a, b })
460
157
  return collabAdmin.listAuth()
461
158
  },
462
159
  }
@@ -668,7 +365,7 @@ export function apply(ctx, config = {}) {
668
365
  collabSessions.add(agent.id)
669
366
  sessionPresets.set(agent.id, effectivePreset)
670
367
  for (const task of tasks.listForWorker(agent.id)) {
671
- const project = tasks.project(task.taskId)
368
+ const project = tasks.task(task.taskId)
672
369
  bindDeliverySandbox(agent.id, deliveryRoot(task.taskId), project?.status === 'open')
673
370
  }
674
371
  return true
@@ -760,7 +457,42 @@ export function apply(ctx, config = {}) {
760
457
  }
761
458
  }
762
459
 
763
- 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')
764
496
 
765
497
  const peersText = (self) => {
766
498
  const entries = registry.list().filter(entry => entry.sessionId !== self.sessionId && COLLAB_PRESETS.has(entry.preset))
@@ -1134,10 +866,6 @@ export function apply(ctx, config = {}) {
1134
866
  }
1135
867
  })
1136
868
 
1137
- const taskLine = (task) => (
1138
- `- ${task.id} [${task.status}] worker=${task.worker ?? 'unassigned'} task=${task.taskId ?? '-'} title=${JSON.stringify(task.title)}`
1139
- )
1140
-
1141
869
  /** Turn number for one executing tool call, when the session event is known. */
1142
870
  const turnForCall = (exec) => {
1143
871
  const found = callTurns.get(String(exec?.callId))
@@ -1146,114 +874,12 @@ export function apply(ctx, config = {}) {
1146
874
  return found.turn
1147
875
  }
1148
876
 
1149
- const taskDetail = (task) => ({
1150
- id: task.id,
1151
- subtaskId: task.id,
1152
- taskId: task.taskId,
1153
- supervisor: task.supervisor,
1154
- worker: task.worker,
1155
- title: task.title,
1156
- instruction: task.instruction,
1157
- inputs: task.inputs,
1158
- acceptance: task.acceptance,
1159
- status: task.status,
1160
- attempts: task.attempts,
1161
- createdTurn: task.createdTurn,
1162
- assignedTurn: task.assignedTurn,
1163
- capabilityVersion: task.capabilityVersion,
1164
- result: task.result,
1165
- failure: task.failure,
1166
- history: task.history,
1167
- })
1168
-
1169
877
  const deliveryDirFor = (task) => deliveryRoot(task.taskId)
1170
878
 
1171
- /** Build the canonical project manifest with path/bytes/sha256/mode. */
1172
- const buildDeliveryManifest = (projectId) => {
1173
- const project = tasks.project(projectId)
1174
- if (project === undefined) throw new Error('unknown project')
1175
- const root = deliveryRoot(projectId)
1176
- const listed = listDeliveryFiles(root)
1177
- if (listed.truncated === true) throw new Error(`delivery has more than ${MAX_DELIVERY_LIST_FILES} files; split the project`)
1178
- const files = listed.sort((left, right) => left.path.localeCompare(right.path)).map(file => {
1179
- const full = path.join(root, file.path)
1180
- const before = fs.statSync(full)
1181
- const content = fs.readFileSync(full)
1182
- const after = fs.statSync(full)
1183
- if (before.size !== after.size || before.mtimeMs !== after.mtimeMs) {
1184
- throw new Error(`delivery file changed while hashing: ${file.path}`)
1185
- }
1186
- const hash = crypto.createHash('sha256').update(content).digest('hex')
1187
- return {
1188
- path: file.path.split(path.sep).join('/'),
1189
- bytes: after.size,
1190
- sha256: hash,
1191
- mode: `0${(after.mode & 0o777).toString(8)}`,
1192
- }
1193
- })
1194
- const manifest = {
1195
- generatedAt: new Date().toISOString(),
1196
- root,
1197
- files,
1198
- }
1199
- const projectDir = path.join(sharedRoot, projectId)
1200
- mkdirp(projectDir, 0o755)
1201
- const manifestPath = path.join(projectDir, 'manifest.json')
1202
- const temporary = `${manifestPath}.${crypto.randomBytes(4).toString('hex')}.tmp`
1203
- writeJson(temporary, manifest, 0o644)
1204
- fs.renameSync(temporary, manifestPath)
1205
- return manifest
1206
- }
1207
-
1208
-
1209
- const MAX_DELIVERY_LIST_FILES = 2000
1210
- /** Publish an opaque delivery alias so the requester never receives projectId. */
1211
- const publishDeliveryAlias = (projectId, deliveryId) => {
1212
- const target = path.join(sharedRoot, projectId, 'artifacts')
1213
- const aliasRoot = path.join(sharedRoot, '.deliveries', deliveryId)
1214
- const alias = path.join(aliasRoot, 'artifacts')
1215
- mkdirp(aliasRoot, 0o755)
1216
- try {
1217
- const existing = fs.lstatSync(alias)
1218
- if (existing.isSymbolicLink() && fs.realpathSync(alias) === fs.realpathSync(target)) return alias
1219
- fs.rmSync(alias, { recursive: true, force: true })
1220
- } catch { /* alias does not exist yet */ }
1221
- try {
1222
- fs.symlinkSync(target, alias, 'dir')
1223
- return alias
1224
- } catch (error) {
1225
- warn(`delivery alias could not be published: ${describeError(error)}`)
1226
- return target
1227
- }
1228
- }
1229
-
1230
- const listDeliveryFiles = (root, base = root, out = []) => {
1231
- if (out.length >= MAX_DELIVERY_LIST_FILES) { out.truncated = true; return out }
1232
- let entries
1233
- try { entries = fs.readdirSync(root, { withFileTypes: true }) } catch { return out }
1234
- for (const entry of entries) {
1235
- if (out.length >= MAX_DELIVERY_LIST_FILES) { out.truncated = true; break }
1236
- const full = path.join(root, entry.name)
1237
- if (entry.isDirectory()) {
1238
- listDeliveryFiles(full, base, out)
1239
- continue
1240
- }
1241
- if (!entry.isFile()) continue
1242
- let stat
1243
- try { stat = fs.statSync(full) } catch { continue }
1244
- out.push({
1245
- path: path.relative(base, full),
1246
- size: stat.size,
1247
- modifiedAt: stat.mtimeMs,
1248
- })
1249
- }
1250
- return out
1251
- }
1252
-
1253
879
  const reconcileRequestProjectBindings = () => {
1254
880
  for (const request of requests.list().sort((left, right) => left.createdAt - right.createdAt)) {
1255
881
  if (request.status !== 'accepted' || typeof request.taskId !== 'string') continue
1256
- const project = tasks.project(request.taskId)
882
+ const project = tasks.task(request.taskId)
1257
883
  if (project === undefined) continue
1258
884
  if ((project.requestId ?? null) === null) {
1259
885
  try {
@@ -1324,9 +950,24 @@ export function apply(ctx, config = {}) {
1324
950
  return lines.join('\n')
1325
951
  },
1326
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
+ },
1327
968
  {
1328
969
  name: 'collab_task_create',
1329
- 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.',
1330
971
  parameters: TASK_CREATE_PARAMETERS,
1331
972
  output: TEXT_OUTPUT,
1332
973
  when: ({ agent }) => isSupervisorSession(agent.id),
@@ -1341,17 +982,11 @@ export function apply(ctx, config = {}) {
1341
982
  if (mentionsSharedCopy) {
1342
983
  throw new Error('do not create copy-out tasks; workers receive a canonical deliveryDir and publish artifacts there')
1343
984
  }
1344
- let taskId = typeof args?.taskId === 'string' && args.taskId.trim().length > 0
1345
- ? args.taskId.trim()
1346
- : (typeof args?.projectId === 'string' && args.projectId.trim().length > 0 ? args.projectId.trim() : undefined)
1347
- if (taskId === undefined) {
1348
- const task = tasks.createTask({ supervisor: self.sessionId, title })
1349
- taskId = task.id
1350
- } else {
1351
- const task = tasks.task(taskId)
1352
- if (task === undefined || task.supervisor !== self.sessionId) throw new Error(`unknown task: ${taskId}`)
1353
- if (task.status !== 'open') throw new Error('task is closed')
1354
- }
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')
1355
990
  const subtask = tasks.createSubtask({
1356
991
  supervisor: self.sessionId,
1357
992
  worker: null,
@@ -1385,7 +1020,7 @@ export function apply(ctx, config = {}) {
1385
1020
  if (!auth.isAuthorized(self.sessionId, worker)) {
1386
1021
  throw new Error('未授权:请在“协同授权”页授权双方。')
1387
1022
  }
1388
- const project = task.taskId === null ? undefined : tasks.project(task.taskId)
1023
+ const project = task.taskId === null ? undefined : tasks.task(task.taskId)
1389
1024
  if (project !== undefined && project.status !== 'open') throw new Error('project is closed')
1390
1025
  const otherActive = tasks.listForWorker(worker)
1391
1026
  .filter(entry => entry.id !== subtaskId && !['done', 'failed', 'cancelled'].includes(entry.status))
@@ -1395,6 +1030,7 @@ export function apply(ctx, config = {}) {
1395
1030
  mkdirp(deliveryDir, 0o755)
1396
1031
  bindDeliverySandbox(worker, deliveryDir)
1397
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 })
1398
1034
  const payload = {
1399
1035
  type: 'collab-task/assign',
1400
1036
  version: 1,
@@ -1463,6 +1099,7 @@ export function apply(ctx, config = {}) {
1463
1099
  throw new Error('task is already bound to another request')
1464
1100
  }
1465
1101
  const acceptedAt = Date.now()
1102
+ audit.append('request.accepted', { requestId: request.id, taskId, supervisor: self.sessionId })
1466
1103
  const accepted = requests.accept(request.id, {
1467
1104
  taskId,
1468
1105
  subtaskIds: assigned.map(subtask => subtask.id),
@@ -1649,7 +1286,12 @@ export function apply(ctx, config = {}) {
1649
1286
  const task = tasks.task(taskId)
1650
1287
  if (task === undefined || task.supervisor !== self.sessionId) throw new Error('unknown task')
1651
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
+ }
1652
1293
  const closed = tasks.closeTask(taskId)
1294
+ audit.append('task.closed', { taskId, supervisor: self.sessionId })
1653
1295
  for (const task of owned) {
1654
1296
  if (task.worker !== null) releaseDeliverySandbox(task.worker, deliveryRoot(taskId))
1655
1297
  }
@@ -1759,6 +1401,7 @@ export function apply(ctx, config = {}) {
1759
1401
  deliveredAt: Date.now(),
1760
1402
  ...(supersedes === null ? {} : { supersedes }),
1761
1403
  })
1404
+ audit.append('delivery.published', { requestId: request.id, taskId: request.taskId, deliveryId })
1762
1405
  clearExecutionTimer(request.id)
1763
1406
  return JSON.stringify({ requestId: request.id, status: recorded.status, files: manifest.files.length, deliveryId, delivery })
1764
1407
  } finally {
@@ -1811,6 +1454,7 @@ export function apply(ctx, config = {}) {
1811
1454
  details: args?.details,
1812
1455
  artifacts: args?.artifacts,
1813
1456
  })
1457
+ audit.append('task.completed', { taskId: completed.id, worker: self.sessionId })
1814
1458
  const delivery = await sendTaskNotice(self, completed.supervisor, {
1815
1459
  type: 'collab-task/result',
1816
1460
  version: 1,
@@ -1912,6 +1556,9 @@ export function apply(ctx, config = {}) {
1912
1556
  const cancelled = requests.cancel(request.id, self.sessionId)
1913
1557
  clearRequestTimer(request.id)
1914
1558
  clearExecutionTimer(request.id)
1559
+ if (request.taskId !== null) {
1560
+ cancelBoundTask(tasks, request.taskId, worker => releaseDeliverySandbox(worker, deliveryRoot(request.taskId)))
1561
+ }
1915
1562
  try {
1916
1563
  await sendTaskNotice(self, request.supervisor, {
1917
1564
  type: 'collab-task/request-cancelled',
@@ -1925,6 +1572,25 @@ export function apply(ctx, config = {}) {
1925
1572
  },
1926
1573
  ]
1927
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
+
1928
1594
  const tools = [
1929
1595
  {
1930
1596
  name: 'collab_info',
@@ -1934,6 +1600,27 @@ export function apply(ctx, config = {}) {
1934
1600
  isConcurrencySafe: () => true,
1935
1601
  execute: (_args, exec) => infoText(requireSelf(exec)),
1936
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
+ },
1937
1624
  {
1938
1625
  name: 'collab_peers',
1939
1626
  description: 'List other collaboration sessions with their role, session id, authorization, and online state.',
@@ -2024,9 +1711,15 @@ export function apply(ctx, config = {}) {
2024
1711
  const a = parts[1]
2025
1712
  const b = parts[2]
2026
1713
  if (!isSessionId(a) || !isSessionId(b) || a === b) return { kind: 'error', text: usage }
2027
- if (action === 'authorize') auth.authorize(a, b, invocation.agent.id)
2028
- else if (action === 'grant') auth.grant(a, b, invocation.agent.id)
2029
- 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
+ }
2030
1723
  return { kind: 'success', text: statePayload() }
2031
1724
  }
2032
1725
  return { kind: 'error', text: usage }
@@ -2276,6 +1969,7 @@ export function apply(ctx, config = {}) {
2276
1969
  return { relationship: view(relationship), authorized: true }
2277
1970
  }
2278
1971
  collabAdmin.panel = panel
1972
+ Object.assign(collabAdmin, createPanelApi(panel))
2279
1973
 
2280
1974
  for (const definition of tools) {
2281
1975
  const { when, ...tool } = definition
@@ -2293,68 +1987,16 @@ export function apply(ctx, config = {}) {
2293
1987
  const currentCwd = exec.agent.session === undefined ? undefined : ctx.workingDirectory.get(exec.agent.session)
2294
1988
  const selfWorkdir = currentCwd ?? self?.workdir
2295
1989
  if (typeof selfWorkdir !== 'string') return undefined
2296
- const comparablePath = (value) => {
2297
- const resolved = path.resolve(value)
2298
- return process.platform === 'win32' ? resolved.toLowerCase() : resolved
2299
- }
2300
- const pathInside = (candidate, root) => {
2301
- const resolvedCandidate = comparablePath(candidate)
2302
- const resolvedRoot = comparablePath(root)
2303
- return resolvedCandidate === resolvedRoot || resolvedCandidate.startsWith(`${resolvedRoot}${path.sep}`)
2304
- }
2305
- const canonicalSharedRoot = canonicalPath(sharedRoot)
2306
- const projectIdFromShared = (resolved) => {
2307
- if (!pathInside(resolved, canonicalSharedRoot)) return undefined
2308
- const relative = path.relative(canonicalSharedRoot, resolved).split(path.sep).filter(Boolean)
2309
- if (relative.length < 2 || relative[1] !== 'artifacts') return undefined
2310
- return relative[0]
2311
- }
2312
- const deliveryAccessFor = (candidate, write) => {
2313
- if (typeof candidate !== 'string' || candidate.length === 0) return false
2314
- const resolved = canonicalPath(path.resolve(selfWorkdir, candidate))
2315
- const projectId = projectIdFromShared(resolved)
2316
- if (projectId === undefined) return false
2317
- const project = tasks.project(projectId)
2318
- if (project === undefined) return false
2319
- if (isSupervisorSession(sessionId)) return project.supervisor === sessionId && write !== true
2320
- if (isManagedWorker(sessionId)) {
2321
- if (write && project.status !== 'open') return false
2322
- return tasks.listForWorker(sessionId).some(task => (
2323
- task.taskId === projectId && task.supervisor === project.supervisor
2324
- ))
2325
- }
2326
- if (write) return false
2327
- return requests.listForRequester(sessionId).some(request => (
2328
- request.taskId === projectId
2329
- && (request.status === 'delivered' || (request.status === 'accepted' && request.delivery !== null))
2330
- && project.requestId === request.id
2331
- && request.delivery !== null
2332
- ))
2333
- }
2334
- const sharedAccessDenied = (candidates, write) => {
2335
- for (const candidate of candidates) {
2336
- if (typeof candidate !== 'string' || candidate.length === 0) continue
2337
- const lexical = path.resolve(selfWorkdir, candidate)
2338
- const resolved = canonicalPath(lexical)
2339
- if (!pathInside(lexical, sharedRoot) && !pathInside(resolved, canonicalSharedRoot)) continue
2340
- if (pathInside(lexical, sharedRoot) && !pathInside(resolved, canonicalSharedRoot)) return { path: lexical }
2341
- if (deliveryAccessFor(candidate, write)) continue
2342
- return { path: lexical }
2343
- }
2344
- return undefined
2345
- }
2346
- const managedWriteAllowed = (candidate) => {
2347
- if (!isManagedWorker(sessionId)) return true
2348
- if (typeof candidate !== 'string' || candidate.length === 0) return false
2349
- const resolved = canonicalPath(path.resolve(selfWorkdir, candidate))
2350
- if (deliveryAccessFor(candidate, true)) return true
2351
- const layoutWorkdir = self?.workdir ?? selfWorkdir
2352
- for (const own of [path.join(layoutWorkdir, 'private'), path.join(layoutWorkdir, 'comm')]) {
2353
- if (pathInside(resolved, canonicalPath(own))) return true
2354
- }
2355
- return false
2356
- }
2357
- 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
+ })
2358
2000
 
2359
2001
  const byId = new Map()
2360
2002
  for (const entry of registry.list()) {
@@ -2532,10 +2174,28 @@ export function apply(ctx, config = {}) {
2532
2174
  return () => clearInterval(timer)
2533
2175
  }, 'collab:notice-outbox')
2534
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
+
2535
2194
  installPerSessionSandbox()
2536
2195
  try { tasks.migrate() } catch (error) { warn(`task state migration failed: ${describeError(error)}`) }
2537
2196
  try { requests.migrate() } catch (error) { warn(`request state migration failed: ${describeError(error)}`) }
2538
2197
  refreshRegistry()
2198
+ pruneInvalidCollabState()
2539
2199
  reconcileRequestProjectBindings()
2540
2200
  pruneDeliveryAliases()
2541
2201
  sweepRequestTimeouts()