@ours.network/fleet 2.4.4 → 2.5.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.
Files changed (84) hide show
  1. package/README.md +29 -32
  2. package/dist/agent-ours/mcp-endpoint.d.ts +3 -0
  3. package/dist/agent-ours/mcp-endpoint.js +3 -0
  4. package/dist/agent-ours/service.d.ts +3 -0
  5. package/dist/agent-ours/service.js +19 -2
  6. package/dist/application/conversation-history.js +2 -2
  7. package/dist/application/fleet-query-service.js +4 -1
  8. package/dist/application/role-creation-service.js +0 -3
  9. package/dist/application/session-control.d.ts +3 -0
  10. package/dist/application/session-control.js +5 -0
  11. package/dist/application/types.d.ts +5 -0
  12. package/dist/build-info.json +4 -4
  13. package/dist/cli.js +2 -3
  14. package/dist/config.d.ts +9 -2
  15. package/dist/config.js +15 -4
  16. package/dist/docs.d.ts +5 -7
  17. package/dist/docs.js +38 -46
  18. package/dist/doctor.js +4 -6
  19. package/dist/file-delivery/store.d.ts +12 -0
  20. package/dist/file-delivery/store.js +24 -2
  21. package/dist/fleet-command-audit.js +3 -2
  22. package/dist/fleet-proxy.js +0 -1
  23. package/dist/harness/hermes-permissions.js +1 -1
  24. package/dist/harness/hermes-session.js +0 -1
  25. package/dist/init-wizard.js +2 -2
  26. package/dist/lifecycle-summary.d.ts +3 -2
  27. package/dist/lifecycle-summary.js +2 -3
  28. package/dist/notifications/status-producer.d.ts +37 -0
  29. package/dist/notifications/status-producer.js +146 -0
  30. package/dist/permissions.d.ts +2 -3
  31. package/dist/permissions.js +3 -3
  32. package/dist/preset-migration.js +12 -0
  33. package/dist/rooms-tasks/cli.js +2 -6
  34. package/dist/rooms-tasks/deletion.js +3 -0
  35. package/dist/rooms-tasks/member-overrides.d.ts +2 -1
  36. package/dist/rooms-tasks/member-overrides.js +1 -4
  37. package/dist/rooms-tasks/task-contributions.d.ts +15 -0
  38. package/dist/rooms-tasks/task-contributions.js +13 -2
  39. package/dist/runner.js +24 -8
  40. package/dist/session/acp.d.ts +9 -29
  41. package/dist/session/acp.js +31 -308
  42. package/dist/session/codex-app-server.d.ts +9 -6
  43. package/dist/session/codex-app-server.js +19 -58
  44. package/dist/session/control.d.ts +5 -0
  45. package/dist/session/control.js +19 -3
  46. package/dist/session/conversation-types.d.ts +3 -2
  47. package/dist/session/status-notice.d.ts +24 -0
  48. package/dist/session/status-notice.js +38 -0
  49. package/dist/session/types.d.ts +2 -0
  50. package/dist/spawn.d.ts +1 -2
  51. package/dist/spawn.js +2 -6
  52. package/dist/statuses/permission-projection.d.ts +53 -0
  53. package/dist/statuses/permission-projection.js +317 -0
  54. package/dist/statuses/status-answers.d.ts +31 -0
  55. package/dist/statuses/status-answers.js +85 -0
  56. package/dist/statuses/status-feed.d.ts +85 -0
  57. package/dist/statuses/status-feed.js +122 -0
  58. package/dist/statuses/status-kinds.d.ts +15 -0
  59. package/dist/statuses/status-kinds.js +12 -0
  60. package/dist/statuses/status-ledger.d.ts +21 -0
  61. package/dist/statuses/status-ledger.js +80 -0
  62. package/dist/statuses/status-routes.d.ts +43 -0
  63. package/dist/statuses/status-routes.js +140 -0
  64. package/dist/statuses/status-store.d.ts +257 -0
  65. package/dist/statuses/status-store.js +605 -0
  66. package/dist/statuses/status-tools.d.ts +21 -0
  67. package/dist/statuses/status-tools.js +126 -0
  68. package/dist/supervisor/manager.js +11 -0
  69. package/dist/web/resource-views.d.ts +3 -1
  70. package/dist/web/resource-views.js +6 -2
  71. package/dist/web/server.js +15 -0
  72. package/docs/acp-files.md +9 -7
  73. package/docs/validation/managed-cli-permissions.md +1 -1
  74. package/examples/fleet/agents/Alice.yaml +1 -1
  75. package/examples/fleet/agents/FleetCoordinator.yaml +1 -1
  76. package/examples/fleet.yaml +0 -1
  77. package/package.json +3 -3
  78. package/presets/fleet/agent_templates/Critic.yaml +1 -1
  79. package/presets/fleet/agent_templates/Developer.yaml +1 -1
  80. package/presets/fleet/agent_templates/Engineer.yaml +1 -1
  81. package/presets/fleet/agent_templates/LocalCoordinator.yaml +1 -1
  82. package/presets/fleet/agents/FleetCoordinator.yaml +1 -1
  83. package/presets/fleet.yaml +1 -1
  84. package/presets/manifest.json +1 -1
@@ -0,0 +1,317 @@
1
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { observeFleetResources } from '../application/resource-observer.js';
4
+ import { replaceFileAtomically } from '../atomic-file.js';
5
+ import { listAllStatuses, recordPermissionRequest, recordPermissionResolution, SESSION_ENDED_REASON, statusesDir, } from './status-store.js';
6
+ export { SESSION_ENDED_REASON } from './status-store.js';
7
+ /**
8
+ * Each session generation's author and mission, recorded when it starts (one runner = one generation). An entry is
9
+ * kept while any permission request of its generation may still need it, and dropped only after a complete
10
+ * reconciliation shows none does.
11
+ */
12
+ const BINDINGS_FILE = '.permission-bindings.json';
13
+ /** Missing file: no bindings yet. Unreadable or corrupt: an error, never "empty" (it must not be overwritten). */
14
+ export function readBindings(stateDir) {
15
+ let text;
16
+ try {
17
+ text = readFileSync(join(stateDir, BINDINGS_FILE), 'utf8');
18
+ }
19
+ catch (error) {
20
+ if (error.code === 'ENOENT')
21
+ return {};
22
+ throw error;
23
+ }
24
+ const value = JSON.parse(text);
25
+ if (!value || typeof value !== 'object' || Array.isArray(value))
26
+ throw new Error(`${BINDINGS_FILE} is not a binding map`);
27
+ return value;
28
+ }
29
+ function writeBindings(stateDir, bindings) {
30
+ replaceFileAtomically(join(stateDir, BINDINGS_FILE), JSON.stringify(bindings, null, 2) + '\n', 0o600, {}, { durable: true });
31
+ }
32
+ /**
33
+ * Every permission record in the role's conversation ledger, all generations, in order. Read-only. Coverage follows
34
+ * the store's own manifest: a generation it lists as failed (an append did not complete) is uncertain; a declared
35
+ * segment that is missing or unreadable, or a malformed record inside a segment, leaves every generation uncertain; a torn or malformed final record (a crash mid-append, or an append in progress)
36
+ * leaves uncertain the generation that wrote the segment's last complete record. Nothing may be inferred from the
37
+ * absence of a record in an uncertain generation.
38
+ */
39
+ export function permissionHistory(stateDir) {
40
+ const dir = join(stateDir, '.conversation');
41
+ const result = { events: [], uncertain: new Set(), gaps: [] };
42
+ if (!existsSync(dir))
43
+ return result;
44
+ const everything = (gap) => { result.uncertain = 'all'; result.gaps.push(gap); };
45
+ let declared = [];
46
+ const manifestPath = join(dir, 'manifest.json');
47
+ if (existsSync(manifestPath)) {
48
+ try {
49
+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
50
+ if (manifest.schemaVersion !== 1 || !Array.isArray(manifest.segments))
51
+ everything('the conversation manifest is not readable');
52
+ else {
53
+ declared = manifest.segments.filter((name) => typeof name === 'string');
54
+ // The store's own record that a generation's ledger coverage is unreliable (an append failed).
55
+ const failedGenerations = Array.isArray(manifest.failedGenerations) ? manifest.failedGenerations : [];
56
+ for (const generation of failedGenerations) {
57
+ if (typeof generation !== 'string') {
58
+ everything('the conversation manifest lists an unreadable failed generation');
59
+ continue;
60
+ }
61
+ if (result.uncertain !== 'all')
62
+ result.uncertain.add(generation);
63
+ result.gaps.push(`generation ${generation} has failed ledger appends`);
64
+ }
65
+ }
66
+ }
67
+ catch {
68
+ everything('the conversation manifest is not readable');
69
+ }
70
+ }
71
+ const segments = [...new Set([...declared, ...readdirSync(dir).filter(file => /^events-\d{6}\.jsonl$/.test(file))])].sort();
72
+ for (const name of segments) {
73
+ let text;
74
+ try {
75
+ text = readFileSync(join(dir, name), 'utf8');
76
+ }
77
+ catch (error) {
78
+ everything(`segment ${name} is ${error.code === 'ENOENT' ? 'missing' : 'unreadable'}`);
79
+ continue;
80
+ }
81
+ const lines = text.split('\n');
82
+ // A complete segment ends with a newline, so its last element is empty.
83
+ const last = lines.length - 1;
84
+ let lastGeneration;
85
+ lines.forEach((line, at) => {
86
+ if (!line && at === last)
87
+ return;
88
+ let event;
89
+ try {
90
+ event = JSON.parse(line);
91
+ }
92
+ catch {
93
+ event = undefined;
94
+ }
95
+ const complete = at < last && event && typeof event.sessionGeneration === 'string';
96
+ if (!complete) {
97
+ if (at === last || at === last - 1 && !lines[last]) {
98
+ if (lastGeneration && result.uncertain !== 'all')
99
+ result.uncertain.add(lastGeneration);
100
+ else if (!lastGeneration)
101
+ result.uncertain = 'all';
102
+ result.gaps.push(`segment ${name} ends in a torn record`);
103
+ }
104
+ else
105
+ everything(`segment ${name} has an unreadable record at line ${at + 1}`);
106
+ return;
107
+ }
108
+ lastGeneration = event.sessionGeneration;
109
+ if ((event.kind === 'permission.requested' || event.kind === 'permission.resolved') && typeof event.permissionId === 'string')
110
+ result.events.push(event);
111
+ });
112
+ }
113
+ return result;
114
+ }
115
+ const keyOf = (generation, permissionId) => `${generation}\u0000${permissionId}`;
116
+ const requestInput = (event) => {
117
+ const payload = event.payload;
118
+ return { sessionGeneration: event.sessionGeneration, permissionId: event.permissionId,
119
+ ...(event.toolCallId ? { toolCallId: event.toolCallId } : {}), ...(payload.title ? { title: payload.title } : {}),
120
+ options: payload.options ?? [], requestedAt: event.at };
121
+ };
122
+ const resolutionInput = (event) => {
123
+ const payload = event.payload;
124
+ return { sessionGeneration: event.sessionGeneration, permissionId: event.permissionId, decision: payload.decision,
125
+ decisionSource: payload.decisionSource, ...(payload.optionId ? { optionId: payload.optionId } : {}),
126
+ ...(payload.reason ? { reason: payload.reason } : {}), at: event.at };
127
+ };
128
+ /**
129
+ * Mirrors this role's harness permission requests as `permission` statuses (feed card + one push until resolved).
130
+ * Runs in the role's runner and reads only its own conversation's permission records; it never decides, expires or
131
+ * answers anything (answers use the existing permission route).
132
+ *
133
+ * The role's conversation ledger is the source of truth. Reconciliation reads the whole ledger: every request gets its
134
+ * status with the author and mission bound for its generation; a recorded native resolution is applied as recorded; a
135
+ * request with no resolution from an earlier generation (one runner's session, a new UUID per start, so its in-memory
136
+ * request ended with that process and the route refuses it) is ended — but only from a complete history. Live
137
+ * requests are never ended here.
138
+ *
139
+ * Reconciliation runs at start, and again whenever work is outstanding (a store write failed, or the history or
140
+ * bindings could not be read) and the status store, the conversation ledger or the bindings change — the existing
141
+ * resource observer,
142
+ * no timer — so a request the harness is blocked on still reaches the feed once storage is usable again.
143
+ */
144
+ export function startPermissionProjection(session, options, log) {
145
+ const live = session.conversationSnapshot?.().sessionGeneration;
146
+ if (!live || !session.subscribeConversation)
147
+ return { reconcile: () => true, stop() { } };
148
+ const current = options.binding();
149
+ let warned = false, outstanding = false;
150
+ const failed = (what, error) => {
151
+ outstanding = true;
152
+ if (!warned)
153
+ log(`permission status not recorded yet (${what}): ${error?.message ?? String(error)}`);
154
+ warned = true;
155
+ };
156
+ /** Make sure the live generation's binding is durable; false while it is not. */
157
+ const bindingRecorded = () => {
158
+ if (!current)
159
+ return true;
160
+ try {
161
+ const all = readBindings(options.stateDir);
162
+ if (!all[live])
163
+ writeBindings(options.stateDir, { ...all, [live]: { ...current, at: new Date().toISOString() } });
164
+ return true;
165
+ }
166
+ catch (error) {
167
+ failed('binding', error);
168
+ return false;
169
+ }
170
+ };
171
+ /** Reconcile from the ledger; true when everything is consistent. Idempotent; first records win. */
172
+ const reconcile = () => {
173
+ let history, bindings, known;
174
+ try {
175
+ history = permissionHistory(options.stateDir);
176
+ bindings = readBindings(options.stateDir);
177
+ known = new Map(listAllStatuses().filter(status => status.kind === 'permission' && status.permission)
178
+ .map(status => [keyOf(status.permission.session_generation, status.permission.permission_id), status]));
179
+ }
180
+ catch (error) {
181
+ failed('history', error);
182
+ return false;
183
+ }
184
+ const bindingFor = (generation) => {
185
+ if (generation === live && current)
186
+ return current;
187
+ const stored = bindings[generation];
188
+ return stored ? { identityCid: stored.identityCid, role: stored.role,
189
+ ...(stored.displayName ? { displayName: stored.displayName } : {}), ...(stored.taskId ? { taskId: stored.taskId } : {}) } : undefined;
190
+ };
191
+ const requests = new Map(), resolutions = new Map();
192
+ const uncertain = (generation) => history.uncertain === 'all' || history.uncertain.has(generation);
193
+ let complete = history.uncertain === 'all' ? false : history.uncertain.size === 0;
194
+ if (history.gaps.length)
195
+ failed('history', new Error(`incomplete conversation history: ${history.gaps.join('; ')}`));
196
+ for (const event of history.events) {
197
+ const key = keyOf(event.sessionGeneration, event.permissionId);
198
+ if (event.kind === 'permission.requested') {
199
+ if (!requests.has(key))
200
+ requests.set(key, event);
201
+ }
202
+ else if (!resolutions.has(key))
203
+ resolutions.set(key, event);
204
+ }
205
+ const needed = new Set([live]);
206
+ if (history.uncertain !== 'all')
207
+ for (const generation of history.uncertain)
208
+ needed.add(generation);
209
+ for (const [key, request] of requests) {
210
+ const generation = request.sessionGeneration;
211
+ try {
212
+ let status = known.get(key);
213
+ if (!status) {
214
+ const author = bindingFor(generation);
215
+ if (!author) {
216
+ complete = false;
217
+ log(`permission ${request.permissionId}: no recorded author for its session generation; not shown`);
218
+ continue;
219
+ }
220
+ status = recordPermissionRequest(author, requestInput(request));
221
+ }
222
+ const resolved = resolutions.get(key);
223
+ const cid = status.author.identity_cid;
224
+ // A recorded native resolution always applies (it also corrects an earlier synthetic ending).
225
+ if (resolved) {
226
+ recordPermissionResolution(cid, resolutionInput(resolved));
227
+ continue;
228
+ }
229
+ if (status.state === 'closed')
230
+ continue;
231
+ // An ending is inferred only from complete history of an earlier generation.
232
+ if (generation !== live && !uncertain(generation))
233
+ recordPermissionResolution(cid, { sessionGeneration: generation, permissionId: request.permissionId,
234
+ decision: 'cancelled', decisionSource: 'automatic', reason: SESSION_ENDED_REASON, at: new Date().toISOString() });
235
+ }
236
+ catch (error) {
237
+ complete = false;
238
+ needed.add(generation);
239
+ failed('reconcile', error);
240
+ }
241
+ }
242
+ // Only a complete pass may drop provenance: keep the live generation and any generation with unfinished work.
243
+ if (complete && history.uncertain !== 'all') {
244
+ const kept = Object.fromEntries(Object.entries(bindings).filter(([generation]) => needed.has(generation)));
245
+ if (Object.keys(kept).length !== Object.keys(bindings).length) {
246
+ try {
247
+ writeBindings(options.stateDir, kept);
248
+ }
249
+ catch (error) {
250
+ complete = false;
251
+ failed('bindings', error);
252
+ }
253
+ }
254
+ }
255
+ outstanding = !complete;
256
+ if (complete)
257
+ warned = false;
258
+ return complete;
259
+ };
260
+ // Changes the store could not take yet, retried in order.
261
+ const retained = [];
262
+ const flush = () => {
263
+ while (retained.length) {
264
+ try {
265
+ retained[0]();
266
+ retained.shift();
267
+ }
268
+ catch (error) {
269
+ failed('live', error);
270
+ return;
271
+ }
272
+ }
273
+ };
274
+ const handle = (event) => {
275
+ if (event.sessionGeneration === live && event.permissionId && current) {
276
+ const permissionEvent = event;
277
+ if (event.kind === 'permission.requested')
278
+ retained.push(() => recordPermissionRequest(current, requestInput(permissionEvent)));
279
+ else if (event.kind === 'permission.resolved')
280
+ retained.push(() => recordPermissionResolution(current.identityCid, resolutionInput(permissionEvent)));
281
+ }
282
+ flush();
283
+ };
284
+ const recover = () => {
285
+ if (!retained.length && !outstanding)
286
+ return;
287
+ flush();
288
+ if (!retained.length && bindingRecorded())
289
+ reconcile();
290
+ };
291
+ // A listener of the session's own conversation must never throw into the adapter.
292
+ const unsubscribe = session.subscribeConversation(event => {
293
+ try {
294
+ handle(event);
295
+ }
296
+ catch (error) {
297
+ failed('live', error);
298
+ }
299
+ });
300
+ const shutdown = new AbortController();
301
+ if (options.observe !== false)
302
+ observeFleetResources({ retryWatchFailures: true, paths: [statusesDir(), options.stateDir], roots: [] }, state => {
303
+ if (state.health === 'healthy') {
304
+ try {
305
+ recover();
306
+ }
307
+ catch (error) {
308
+ failed('recover', error);
309
+ }
310
+ }
311
+ }, shutdown.signal);
312
+ if (!current)
313
+ log('permission statuses unavailable: the session has no bound identity');
314
+ if (bindingRecorded())
315
+ reconcile();
316
+ return { reconcile: () => { flush(); return bindingRecorded() && reconcile(); }, stop: () => { unsubscribe(); shutdown.abort(); } };
317
+ }
@@ -0,0 +1,31 @@
1
+ import { type AnswerInput, type StatusRecord } from './status-store.js';
2
+ export interface AnswerDeliveryPort {
3
+ /** The identity CID currently bound to the role's managed session, or undefined when the agent no longer exists. */
4
+ identityCid(role: string): Promise<string | undefined>;
5
+ /**
6
+ * Admit a prompt with the existing idempotent browser-admission path, fenced by the receiving supervisor: it admits
7
+ * only while its own bound identity is `identityCid`. Returns the admission receipt.
8
+ */
9
+ submit(role: string, prompt: {
10
+ commandId: string;
11
+ text: string;
12
+ actor: string;
13
+ identityCid: string;
14
+ }): Promise<{
15
+ promptId: string;
16
+ }>;
17
+ }
18
+ export { answerPrompt } from './status-store.js';
19
+ export declare class StatusAnswerService {
20
+ private readonly port;
21
+ private readonly now;
22
+ /** One delivery attempt per status at a time: a concurrent answer/Try again joins the attempt in flight. */
23
+ private readonly inFlight;
24
+ constructor(port: AnswerDeliveryPort, now?: () => Date);
25
+ /** Accept the Owner's answer (first wins), then attempt delivery once. Replaying the same submission delivers nothing new. */
26
+ answer(statusId: string, input: AnswerInput, actor: string): Promise<StatusRecord>;
27
+ /** The Owner's Try again: only for an answer whose delivery is not confirmed. */
28
+ retry(statusId: string, actor: string): Promise<StatusRecord>;
29
+ private deliver;
30
+ private attempt;
31
+ }
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Answering a Fleet agent's question and delivering the answer to that agent.
3
+ *
4
+ * 1. Commit: the answer and `delivery=pending` are stored atomically (status-store `recordAnswer`).
5
+ * 2. Deliver: a fixed-template prompt is admitted into the author's current session through the existing
6
+ * idempotent browser admission. Its command ID derives from status ID + submission ID, so the session's own
7
+ * admission receipt deduplicates any repeated delivery. Admission is attempted only into a session whose bound
8
+ * identity CID equals the author CID.
9
+ * 3. Outcome: `delivered` with the admission's prompt ID, or `not_delivered(reason)`. There is no timer, background
10
+ * retry or delivery at session start: only the Owner's explicit Try again repeats the delivery step, and that
11
+ * repeat first hits the existing receipt, so an already admitted answer is never admitted twice.
12
+ */
13
+ import { FleetError } from '../application/errors.js';
14
+ import { answerPrompt, findStatus, recordAnswer, setAnswerDelivery, StatusError, } from './status-store.js';
15
+ export { answerPrompt } from './status-store.js';
16
+ function reasonOf(error) {
17
+ if (error instanceof FleetError) {
18
+ if (error.code === 'role_not_found')
19
+ return 'agent removed';
20
+ if (error.message.includes('identity_mismatch'))
21
+ return 'agent identity changed';
22
+ return `${error.code}: ${error.message}`.slice(0, 300);
23
+ }
24
+ return error instanceof Error ? error.message.slice(0, 300) : 'delivery failed';
25
+ }
26
+ export class StatusAnswerService {
27
+ port;
28
+ now;
29
+ /** One delivery attempt per status at a time: a concurrent answer/Try again joins the attempt in flight. */
30
+ inFlight = new Map();
31
+ constructor(port, now = () => new Date()) {
32
+ this.port = port;
33
+ this.now = now;
34
+ }
35
+ /** Accept the Owner's answer (first wins), then attempt delivery once. Replaying the same submission delivers nothing new. */
36
+ async answer(statusId, input, actor) {
37
+ const recorded = recordAnswer(statusId, input, this.now());
38
+ if (recorded.replayed)
39
+ return recorded.status;
40
+ return this.deliver(recorded.status, actor);
41
+ }
42
+ /** The Owner's Try again: only for an answer whose delivery is not confirmed. */
43
+ async retry(statusId, actor) {
44
+ const status = findStatus(statusId);
45
+ if (!status)
46
+ throw new StatusError('not_found', `status ${statusId} not found`);
47
+ if (!status.answer)
48
+ throw new StatusError('conflict', 'this question has no answer to deliver');
49
+ if (status.answer.delivery.state === 'delivered')
50
+ return status;
51
+ return this.deliver(status, actor);
52
+ }
53
+ deliver(status, actor) {
54
+ const running = this.inFlight.get(status.status_id);
55
+ if (running)
56
+ return running;
57
+ const attempt = this.attempt(status, actor).finally(() => this.inFlight.delete(status.status_id));
58
+ this.inFlight.set(status.status_id, attempt);
59
+ return attempt;
60
+ }
61
+ async attempt(status, actor) {
62
+ const answer = status.answer;
63
+ const commandId = answer.delivery.command_id;
64
+ const at = () => this.now().toISOString();
65
+ let cid;
66
+ try {
67
+ cid = await this.port.identityCid(status.author.role);
68
+ }
69
+ catch (error) {
70
+ return setAnswerDelivery(status.status_id, answer.submission_id, { state: 'not_delivered', command_id: commandId, at: at(), reason: reasonOf(error) });
71
+ }
72
+ // Routing uses the durable identity: a role ID reused by a different identity never receives the answer.
73
+ if (!cid)
74
+ return setAnswerDelivery(status.status_id, answer.submission_id, { state: 'not_delivered', command_id: commandId, at: at(), reason: 'agent removed' });
75
+ if (cid.toUpperCase() !== status.author.identity_cid)
76
+ return setAnswerDelivery(status.status_id, answer.submission_id, { state: 'not_delivered', command_id: commandId, at: at(), reason: 'agent identity changed' });
77
+ try {
78
+ const receipt = await this.port.submit(status.author.role, { commandId, text: answerPrompt(status, answer), actor, identityCid: status.author.identity_cid });
79
+ return setAnswerDelivery(status.status_id, answer.submission_id, { state: 'delivered', command_id: commandId, at: at(), prompt_id: receipt.promptId });
80
+ }
81
+ catch (error) {
82
+ return setAnswerDelivery(status.status_id, answer.submission_id, { state: 'not_delivered', command_id: commandId, at: at(), reason: reasonOf(error) });
83
+ }
84
+ }
85
+ }
@@ -0,0 +1,85 @@
1
+ import { type ContributionItem } from '../rooms-tasks/task-contributions.js';
2
+ import { type StatusRecord } from './status-store.js';
3
+ export type FeedScope = {
4
+ kind: 'global';
5
+ } | {
6
+ kind: 'agent';
7
+ identityCid: string;
8
+ } | {
9
+ kind: 'mission';
10
+ taskId: string;
11
+ };
12
+ export interface FeedItem {
13
+ source: 'fleet';
14
+ status_id: string;
15
+ kind: string;
16
+ title: string;
17
+ /** Projected items written by the local operator have no agent author. */
18
+ author?: {
19
+ identity_cid?: string;
20
+ role: string;
21
+ display_name?: string;
22
+ };
23
+ task_id?: string;
24
+ revision: number;
25
+ state: StatusRecord['state'] | 'cleared';
26
+ /**
27
+ * A Progress entry or the current To Review package, referred to, never copied: its full content and documents
28
+ * are read from the existing task routes, and its seen state is the task's read marker.
29
+ */
30
+ projected?: {
31
+ task_title: string;
32
+ mission_key?: string;
33
+ entry_id?: string;
34
+ };
35
+ answered: boolean;
36
+ /** A harness permission request: native identity, the harness's options and, once ended, its resolution. */
37
+ permission?: StatusRecord['permission'];
38
+ /** Where the accepted answer stands with the agent: every surface shows the same delivery state. */
39
+ answer_delivery?: {
40
+ state: 'pending' | 'delivered' | 'not_delivered';
41
+ at: string;
42
+ reason?: string;
43
+ };
44
+ /** An open question the Owner has not answered yet. */
45
+ awaits_owner: boolean;
46
+ seen: boolean;
47
+ created_at: string;
48
+ updated_at: string;
49
+ }
50
+ export declare const FEED_PAGE_MAX = 200;
51
+ export declare function feedScope(query: {
52
+ scope?: unknown;
53
+ agent?: unknown;
54
+ task?: unknown;
55
+ }): FeedScope;
56
+ /** A mission Progress entry or To Review package as a projected status; its ID and revision follow the task record. */
57
+ export declare function projectedItem(item: ContributionItem): FeedItem;
58
+ /**
59
+ * Mark a feed item seen at `revision`. Native statuses keep their own seen revision; Progress and To Review use the
60
+ * existing task read markers, so the task page and the Notifications screen see the same state.
61
+ */
62
+ export declare function markFeedItemSeen(statusId: string, revision: number): {
63
+ seen: boolean;
64
+ };
65
+ export declare function feedItem(status: StatusRecord): FeedItem;
66
+ /** One chronological page; `after` continues after a returned status ID. Totals cover the whole scope. */
67
+ export declare function listFeed(scope: FeedScope, options?: {
68
+ after?: string;
69
+ limit?: number;
70
+ }): {
71
+ items: FeedItem[];
72
+ next_after: string | null;
73
+ total: number;
74
+ unseen: number;
75
+ open_questions: string[];
76
+ opens_at: string | null;
77
+ caught_up: boolean;
78
+ /** Task records that could not be read: their Progress / To Review items are missing, so the feed is incomplete. */
79
+ unavailable_tasks: number;
80
+ /**
81
+ * Changes whenever any item in the scope changes, on this page or not. A live view of the first page therefore still
82
+ * signals a change to an item further back (for example its answer delivery), and a client reloads what it shows.
83
+ */
84
+ scope_version: string;
85
+ };
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Feed queries over Fleet's statuses: one chronological sequence (oldest first, D3) per scope.
3
+ *
4
+ * - global: every status;
5
+ * - agent: the statuses of one author identity CID;
6
+ * - mission: every status whose mission (taken from the author's task binding) is the task, of every kind,
7
+ * including questions; mission Progress and To Review are added by the task projection.
8
+ *
9
+ * Items are summaries; the full status is read by ID. The listing reports where the feed opens: the oldest unseen
10
+ * status, else the newest (caught up).
11
+ */
12
+ import { createHash } from 'node:crypto';
13
+ import { acknowledgeTaskProgress, acknowledgeTaskReview, TaskStateError } from '../rooms-tasks/task-state.js';
14
+ import { allTaskContributions } from '../rooms-tasks/task-contributions.js';
15
+ import { canonicalCid, listAllStatuses, markStatusSeen, statusAwaitsOwner, statusSeen, StatusError } from './status-store.js';
16
+ export const FEED_PAGE_MAX = 200;
17
+ const TASK_ID = /^[A-Za-z0-9_-]{1,120}$/;
18
+ export function feedScope(query) {
19
+ if (query.scope === undefined || query.scope === 'global') {
20
+ if (query.agent !== undefined || query.task !== undefined)
21
+ throw new StatusError('invalid_request', 'the global scope takes no agent or task');
22
+ return { kind: 'global' };
23
+ }
24
+ if (query.scope === 'agent') {
25
+ if (typeof query.agent !== 'string' || query.task !== undefined)
26
+ throw new StatusError('invalid_request', 'the agent scope needs agent=<identity CID>');
27
+ try {
28
+ return { kind: 'agent', identityCid: canonicalCid(query.agent) };
29
+ }
30
+ catch {
31
+ throw new StatusError('invalid_request', 'agent must be an identity CID');
32
+ }
33
+ }
34
+ if (query.scope === 'mission') {
35
+ if (typeof query.task !== 'string' || !TASK_ID.test(query.task) || query.agent !== undefined)
36
+ throw new StatusError('invalid_request', 'the mission scope needs task=<task ID>');
37
+ return { kind: 'mission', taskId: query.task };
38
+ }
39
+ throw new StatusError('invalid_request', 'scope must be global, agent or mission');
40
+ }
41
+ const inScope = (scope) => (item) => scope.kind === 'global' || (scope.kind === 'agent' ? item.author?.identity_cid === scope.identityCid : item.task_id === scope.taskId);
42
+ /** A mission Progress entry or To Review package as a projected status; its ID and revision follow the task record. */
43
+ export function projectedItem(item) {
44
+ const review = item.kind === 'review';
45
+ return {
46
+ source: 'fleet', status_id: review ? `review:${item.task_id}` : `progress:${item.task_id}:${item.entry_id}`, kind: item.kind,
47
+ title: item.excerpt, ...(item.author ? { author: item.author } : {}), task_id: item.task_id,
48
+ revision: review ? item.revision : 1, state: item.review_cleared ? 'cleared' : 'active',
49
+ answered: false, awaits_owner: false, seen: !item.unread, created_at: item.at, updated_at: item.at,
50
+ projected: { task_title: item.task_title, ...(item.mission_key ? { mission_key: item.mission_key } : {}), ...(review ? {} : { entry_id: item.entry_id }) },
51
+ };
52
+ }
53
+ const PROJECTED = /^(progress|review):([0-9a-z]{9}[0-9a-f]{8})(?::(.+))?$/;
54
+ /**
55
+ * Mark a feed item seen at `revision`. Native statuses keep their own seen revision; Progress and To Review use the
56
+ * existing task read markers, so the task page and the Notifications screen see the same state.
57
+ */
58
+ export function markFeedItemSeen(statusId, revision) {
59
+ const projected = PROJECTED.exec(statusId);
60
+ if (!projected)
61
+ return { seen: markStatusSeen(statusId, revision).seen };
62
+ const [, kind, taskId, entryId] = projected;
63
+ if ((kind === 'progress') !== (entryId !== undefined))
64
+ throw new StatusError('not_found', `status ${statusId} not found`);
65
+ try {
66
+ if (kind === 'progress') {
67
+ if (revision !== 1)
68
+ throw new StatusError('invalid_request', 'a Progress entry has revision 1');
69
+ acknowledgeTaskProgress(taskId, [entryId]);
70
+ }
71
+ else
72
+ acknowledgeTaskReview(taskId, revision);
73
+ }
74
+ catch (error) {
75
+ if (error instanceof TaskStateError)
76
+ throw new StatusError(/not found/.test(error.message) ? 'not_found' : 'conflict', error.message);
77
+ throw error;
78
+ }
79
+ const item = allTaskContributions().items.find(candidate => projectedItem(candidate).status_id === statusId);
80
+ if (!item)
81
+ throw new StatusError('not_found', `status ${statusId} not found`);
82
+ return { seen: !item.unread };
83
+ }
84
+ export function feedItem(status) {
85
+ return {
86
+ source: 'fleet', status_id: status.status_id, kind: status.kind, title: status.title, author: status.author,
87
+ ...(status.task_id ? { task_id: status.task_id } : {}), revision: status.revision, state: status.state,
88
+ answered: !!status.answer, ...(status.permission ? { permission: status.permission } : {}),
89
+ ...(status.answer ? { answer_delivery: { state: status.answer.delivery.state, at: status.answer.delivery.at,
90
+ ...(status.answer.delivery.state === 'not_delivered' ? { reason: status.answer.delivery.reason } : {}) } } : {}),
91
+ awaits_owner: statusAwaitsOwner(status), seen: statusSeen(status),
92
+ created_at: status.created_at, updated_at: status.updated_at,
93
+ };
94
+ }
95
+ /** One chronological page; `after` continues after a returned status ID. Totals cover the whole scope. */
96
+ export function listFeed(scope, options = {}) {
97
+ const limit = options.limit ?? 100;
98
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > FEED_PAGE_MAX)
99
+ throw new StatusError('invalid_request', `limit must be 1-${FEED_PAGE_MAX}`);
100
+ // One chronological sequence of native statuses and projected mission items.
101
+ const projected = allTaskContributions();
102
+ const all = [...listAllStatuses().map(feedItem), ...projected.items.map(projectedItem)].filter(inScope(scope))
103
+ .sort((a, b) => a.created_at.localeCompare(b.created_at) || a.status_id.localeCompare(b.status_id));
104
+ let start = 0;
105
+ if (options.after !== undefined) {
106
+ start = all.findIndex(item => item.status_id === options.after) + 1;
107
+ if (!start)
108
+ throw new StatusError('invalid_request', 'after must be a status ID in this scope');
109
+ }
110
+ const page = all.slice(start, start + limit);
111
+ const unseen = all.filter(item => !item.seen);
112
+ return {
113
+ items: page, next_after: start + page.length < all.length ? page.at(-1).status_id : null,
114
+ total: all.length, unseen: unseen.length,
115
+ open_questions: all.filter(item => item.awaits_owner).map(item => item.status_id),
116
+ opens_at: unseen[0]?.status_id ?? all.at(-1)?.status_id ?? null,
117
+ // Never "caught up" while mission content could not be loaded.
118
+ caught_up: unseen.length === 0 && projected.unavailable === 0,
119
+ unavailable_tasks: projected.unavailable,
120
+ scope_version: createHash('sha256').update(JSON.stringify(all)).digest('hex').slice(0, 32),
121
+ };
122
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Status kind registry. The envelope is fixed and the kind list is open: a client that does not know a kind renders
3
+ * the generic card. A new kind ships with its renderer, fallback, push template and publish validation together.
4
+ */
5
+ export interface StatusKindSpec {
6
+ /** Agents publish it through `status.publish`; otherwise it is projected from an existing Fleet record. */
7
+ readonly publishable: boolean;
8
+ /** The Owner can answer it in the feed or session. */
9
+ readonly answerable: boolean;
10
+ /** Push title template; `<Agent>`, `<Mission>` and `<title>` are filled by the producer. */
11
+ readonly push: string;
12
+ }
13
+ export declare const STATUS_KINDS: Readonly<Record<string, StatusKindSpec>>;
14
+ export declare const PUBLISHABLE_STATUS_KINDS: readonly string[];
15
+ export declare function statusKind(kind: string): StatusKindSpec | undefined;
@@ -0,0 +1,12 @@
1
+ export const STATUS_KINDS = Object.freeze({
2
+ update: { publishable: true, answerable: false, push: '<Agent>: <title>' },
3
+ question: { publishable: true, answerable: true, push: '<Agent> asks: <title>' },
4
+ alert: { publishable: true, answerable: false, push: '<Agent> needs attention: <title>' },
5
+ progress: { publishable: false, answerable: false, push: '<Agent> · <Mission> progress: <title>' },
6
+ review: { publishable: false, answerable: false, push: '<Mission> ready for review: <title>' },
7
+ permission: { publishable: false, answerable: true, push: '<Agent> needs permission: <title>' },
8
+ });
9
+ export const PUBLISHABLE_STATUS_KINDS = Object.freeze(Object.keys(STATUS_KINDS).filter(kind => STATUS_KINDS[kind].publishable));
10
+ export function statusKind(kind) {
11
+ return Object.prototype.hasOwnProperty.call(STATUS_KINDS, kind) ? STATUS_KINDS[kind] : undefined;
12
+ }