@aeondave/pi-persona 1.17.3 → 1.17.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.
Files changed (84) hide show
  1. package/AGENTS.md +44 -36
  2. package/CHANGELOG.md +76 -1
  3. package/README.md +23 -13
  4. package/docs/ARCHITECTURE.md +97 -37
  5. package/docs/COLLABORATION.md +110 -0
  6. package/docs/EXPERIENCE.md +33 -8
  7. package/docs/README.md +12 -0
  8. package/docs/REFERENCE.md +65 -14
  9. package/package.json +12 -6
  10. package/src/agents/agent.ts +6 -0
  11. package/src/bridge.ts +25 -8
  12. package/src/bus/broker/client.ts +119 -21
  13. package/src/bus/broker/host.ts +123 -8
  14. package/src/bus/broker/messages.ts +31 -4
  15. package/src/bus/contact.ts +113 -38
  16. package/src/bus/peers.ts +15 -0
  17. package/src/bus/result-reader.ts +88 -0
  18. package/src/core/brief.ts +14 -4
  19. package/src/core/capabilities.ts +1 -1
  20. package/src/core/leg-thinking.ts +57 -0
  21. package/src/core/ownership.ts +1 -2
  22. package/src/core/pi-compat.ts +5 -12
  23. package/src/core/session-runs.ts +1 -1
  24. package/src/core/types.ts +1 -1
  25. package/src/engine/adapter.ts +83 -19
  26. package/src/engine/async.ts +49 -10
  27. package/src/engine/child.ts +10 -2
  28. package/src/engine/inproc.ts +87 -46
  29. package/src/engine/result-grant.ts +62 -0
  30. package/src/engine/session-tools.ts +6 -0
  31. package/src/engine/stream.ts +6 -0
  32. package/src/engine/worktree.ts +17 -7
  33. package/src/exocom/collaboration-delivery.ts +29 -0
  34. package/src/exocom/collaboration.ts +148 -0
  35. package/src/exocom/envelope.ts +43 -4
  36. package/src/exocom/gate.ts +7 -2
  37. package/src/exocom/install.ts +45 -17
  38. package/src/exocom/ledger.ts +58 -8
  39. package/src/exocom/plane.ts +32 -1
  40. package/src/exocom/profile.ts +40 -0
  41. package/src/exocom/registry.ts +5 -0
  42. package/src/exocom/status.ts +11 -1
  43. package/src/exocom/write-guard.ts +7 -0
  44. package/src/extension/broker-host.ts +61 -9
  45. package/src/extension/engine.ts +20 -21
  46. package/src/extension/hooks.ts +952 -938
  47. package/src/extension/identity.ts +41 -75
  48. package/src/extension/results.ts +136 -0
  49. package/src/extension/shared.ts +17 -0
  50. package/src/extension.ts +2963 -2873
  51. package/src/loader.ts +11 -3
  52. package/src/orchestration/flow-journal.ts +7 -1
  53. package/src/orchestration/flow-run.ts +122 -19
  54. package/src/orchestration/flow.ts +11 -0
  55. package/src/orchestration/roster.ts +71 -23
  56. package/src/orchestration/sdk.ts +44 -6
  57. package/src/orchestration/types.ts +10 -0
  58. package/src/persona/model-participants.ts +20 -7
  59. package/src/persona/orchestrate.ts +2 -0
  60. package/src/persona/persona.ts +1 -1
  61. package/src/results/archive.ts +281 -0
  62. package/src/results/record.ts +166 -0
  63. package/src/results/retrieval.ts +142 -0
  64. package/src/results/types.ts +128 -0
  65. package/src/telemetry/contract.ts +1 -1
  66. package/src/tools/council.ts +40 -23
  67. package/src/tools/delegate-tool.ts +50 -14
  68. package/src/tools/delegate.ts +13 -6
  69. package/src/tools/exocom-collaboration-input.ts +168 -0
  70. package/src/tools/exocom-collaboration.ts +315 -0
  71. package/src/tools/exocom-profile.ts +102 -0
  72. package/src/tools/exocom.ts +20 -3
  73. package/src/tools/flow.ts +24 -8
  74. package/src/tools/intercom-tool.ts +98 -14
  75. package/src/tools/models.ts +15 -0
  76. package/src/tools/monitor.ts +20 -1
  77. package/src/tools/read-result.ts +52 -0
  78. package/src/tools/timer.ts +23 -2
  79. package/src/ui/agent-overlay.ts +11 -3
  80. package/src/ui/agent-tree.ts +43 -1
  81. package/src/ui/literal-tool-result.ts +1 -1
  82. package/src/ui/model-picker.ts +1 -1
  83. package/src/ui/orchestration-launch.ts +49 -0
  84. package/src/ui/session-cards.ts +191 -14
@@ -31,13 +31,20 @@ export interface ExocomAnswer {
31
31
  }
32
32
  export interface ExocomProgress {
33
33
  kind: "progress"; work_key: string; from_session: string; from_name: string;
34
- note: string; msg_id: string; ts: string; signature?: string;
34
+ note: string; msg_id: string; ts: string; signature?: string; task_id?: string;
35
35
  }
36
36
  export interface ExocomRelease {
37
37
  kind: "release"; work_key: string; from_session: string; from_name: string;
38
38
  msg_id: string; ts: string; signature?: string;
39
39
  }
40
- export type ExocomSemanticFrame = ExocomClaim | ExocomAsk | ExocomAnswer | ExocomProgress | ExocomRelease;
40
+ interface CollaborationFrame { work_key: string; from_session: string; from_name: string; msg_id: string; ts: string; signature?: string; }
41
+ export interface ExocomTaskCreate extends CollaborationFrame { kind: "task_create"; description: string; write_set: string[]; }
42
+ export interface ExocomTaskTake extends CollaborationFrame { kind: "task_take"; task_id: string; }
43
+ export interface ExocomTaskFinish extends CollaborationFrame { kind: "task_finish"; task_id: string; outcome: "done" | "abandoned"; note: string; }
44
+ export interface ExocomOffer extends CollaborationFrame { kind: "offer"; task_id: string; offer_id: string; to_session?: string; expires_at: string; }
45
+ export interface ExocomPublish extends CollaborationFrame { kind: "publish"; task_id: string; title: string; excerpt: string; }
46
+ export type ExocomCollaborationFrame = ExocomTaskCreate | ExocomTaskTake | ExocomTaskFinish | ExocomOffer | ExocomPublish;
47
+ export type ExocomSemanticFrame = ExocomClaim | ExocomAsk | ExocomAnswer | ExocomProgress | ExocomRelease | ExocomCollaborationFrame;
41
48
  export type ExocomFrame = ExocomMessage | ExocomBye | ExocomAck | ExocomNack | ExocomSemanticFrame;
42
49
 
43
50
  const str = (v: unknown): v is string => typeof v === "string";
@@ -73,10 +80,27 @@ export function isSemanticFrame(v: unknown): v is ExocomSemanticFrame {
73
80
  case "progress":
74
81
  return token(o.work_key) && token(o.from_session) && metadata(o.from_name, 256)
75
82
  && bounded(o.note, 4_096) && token(o.msg_id) && timestamp(o.ts)
76
- && optionalBounded(o.signature, 512);
83
+ && optionalBounded(o.signature, 512) && (o.task_id === undefined || token(o.task_id));
77
84
  case "release":
78
85
  return token(o.work_key) && token(o.from_session) && metadata(o.from_name, 256)
79
86
  && token(o.msg_id) && timestamp(o.ts) && optionalBounded(o.signature, 512);
87
+ case "task_create":
88
+ case "task_take":
89
+ case "task_finish":
90
+ case "offer":
91
+ case "publish": {
92
+ if (!token(o.work_key) || !token(o.from_session) || !metadata(o.from_name, 256)
93
+ || !token(o.msg_id) || !timestamp(o.ts) || !optionalBounded(o.signature, 512)) return false;
94
+ if (o.kind === "task_create") return bounded(o.description, 2_048) && Array.isArray(o.write_set)
95
+ && (o.write_set.length === 0 || writeSet(o.write_set));
96
+ if (!token(o.task_id)) return false;
97
+ if (o.kind === "task_finish") return (o.outcome === "done" || o.outcome === "abandoned") && bounded(o.note, 4_096);
98
+ if (o.kind === "offer") return token(o.offer_id) && (o.to_session === undefined || token(o.to_session))
99
+ && timestamp(o.expires_at) && Date.parse(o.expires_at) > Date.parse(o.ts)
100
+ && Date.parse(o.expires_at) - Date.parse(o.ts) <= 86_400_000;
101
+ if (o.kind === "publish") return bounded(o.title, 160) && bounded(o.excerpt, 4_096) && Buffer.byteLength(o.excerpt, "utf8") <= 8_192;
102
+ return true;
103
+ }
80
104
  default:
81
105
  return false;
82
106
  }
@@ -102,6 +126,11 @@ export function isExocomFrame(v: unknown): v is ExocomFrame {
102
126
  case "answer":
103
127
  case "progress":
104
128
  case "release":
129
+ case "task_create":
130
+ case "task_take":
131
+ case "task_finish":
132
+ case "offer":
133
+ case "publish":
105
134
  return isSemanticFrame(v);
106
135
  default: return false;
107
136
  }
@@ -127,9 +156,19 @@ export function frameSigningPayload(frame: ExocomFrame): string {
127
156
  frame.ok, frame.evidence, frame.ts]);
128
157
  case "progress":
129
158
  return JSON.stringify([frame.kind, frame.msg_id, frame.work_key, frame.from_session, frame.from_name,
130
- frame.note, frame.ts]);
159
+ frame.note, frame.ts, frame.task_id ?? null]);
131
160
  case "release":
132
161
  return JSON.stringify([frame.kind, frame.msg_id, frame.work_key, frame.from_session, frame.from_name, frame.ts]);
162
+ case "task_create":
163
+ return JSON.stringify([frame.kind, frame.msg_id, frame.work_key, frame.from_session, frame.from_name, frame.description, frame.write_set, frame.ts]);
164
+ case "task_take":
165
+ return JSON.stringify([frame.kind, frame.msg_id, frame.work_key, frame.task_id, frame.from_session, frame.from_name, frame.ts]);
166
+ case "task_finish":
167
+ return JSON.stringify([frame.kind, frame.msg_id, frame.work_key, frame.task_id, frame.from_session, frame.from_name, frame.outcome, frame.note, frame.ts]);
168
+ case "offer":
169
+ return JSON.stringify([frame.kind, frame.msg_id, frame.offer_id, frame.work_key, frame.task_id, frame.from_session, frame.from_name, frame.to_session ?? null, frame.expires_at, frame.ts]);
170
+ case "publish":
171
+ return JSON.stringify([frame.kind, frame.msg_id, frame.work_key, frame.task_id, frame.from_session, frame.from_name, frame.title, frame.excerpt, frame.ts]);
133
172
  }
134
173
  }
135
174
 
@@ -1,6 +1,11 @@
1
1
  /** Identity metadata does not claim work or settle asks. Persona denials still apply first. */
2
2
  const ALLOWED = new Set(["exocom_name", "exocom_answer", "exocom_decline", "exocom_status", "read", "grep", "find", "ls"]);
3
3
 
4
- export function constrainedTurnAllows(toolName: string): boolean {
5
- return ALLOWED.has(toolName);
4
+ export function constrainedTurnAllows(toolName: string, input?: unknown): boolean {
5
+ if (ALLOWED.has(toolName)) return true;
6
+ if (!input || typeof input !== "object") return false;
7
+ const action = (input as { action?: unknown }).action;
8
+ return (toolName === "exocom_task" && (action === "list" || action === "get"))
9
+ || (toolName === "exocom_publish" && action === "read")
10
+ || (toolName === "exocom_profile" && action === "get");
6
11
  }
@@ -27,6 +27,7 @@ import {
27
27
  sanitizePeerField,
28
28
  sendPersonaFollowUp,
29
29
  shouldReportHeartbeatFailure,
30
+ toastCause,
30
31
  type ExocomQueuedToast,
31
32
  } from "../extension/shared.ts";
32
33
  import { SeenMessages, SenderBudget } from "./guards.ts";
@@ -54,6 +55,9 @@ import type { ExocomSemanticFrame } from "./envelope.ts";
54
55
  import { prune as pruneExocom, type RegistryEntry } from "./registry.ts";
55
56
  import { registerExocomTools } from "../tools/exocom.ts";
56
57
  import { registerExocomWorkTools } from "../tools/exocom-work.ts";
58
+ import { registerExocomCollaborationTools } from "../tools/exocom-collaboration.ts";
59
+ import { registerExocomProfileTool } from "../tools/exocom-profile.ts";
60
+ import { collaborationWriteIntent, deliverCollaborationOffer } from "./collaboration-delivery.ts";
57
61
  import type { SessionIdentity } from "../extension/identity.ts";
58
62
  import { WriteWarnings } from "./write-guard.ts";
59
63
 
@@ -237,28 +241,23 @@ export function installExocom(pi: ExtensionAPI, host: ExocomHost): ExocomInstall
237
241
  }
238
242
 
239
243
  function telemetrySessionId(ctx: ExtensionContext): string {
240
- return (ctx as ExtensionContext & { sessionManager?: { getSessionId?: () => string } }).sessionManager?.getSessionId?.() ?? `legacy-${process.pid}`;
244
+ return ctx.sessionManager.getSessionId();
241
245
  }
242
246
 
243
247
  function currentTelemetryInstance(ctx: ExtensionContext): InstanceDescriptor {
244
- const runtimeCtx = ctx as ExtensionContext & {
245
- sessionManager?: { getSessionId?: () => string };
246
- isIdle?: () => boolean;
247
- getContextUsage?: () => { percent?: number } | undefined;
248
- };
249
248
  const personaName = host.controller.activePersona?.name ?? "";
250
249
  const displayName = exocomSelfStatusLabel(host.identity.chosen, host.identity.name, personaName);
251
250
  return {
252
251
  displayName,
253
252
  persona: host.controller.activePersona?.name ?? "",
254
253
  model: ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : "",
255
- status: runtimeCtx.isIdle?.() === true ? "idle" : "active",
254
+ status: ctx.isIdle() ? "idle" : "active",
256
255
  pid: process.pid,
257
256
  // Clamped HERE, not merely in the producer's `sanitizeInstance`: that one runs only for
258
257
  // `instance.started`, so an out-of-range reading would ride `instance.updated` and
259
258
  // `instance.heartbeat` out to consumers, where the contract rejects the WHOLE event over
260
259
  // the one bad field.
261
- contextPercent: Math.max(0, Math.min(100, Math.round(runtimeCtx.getContextUsage?.()?.percent ?? 0))),
260
+ contextPercent: Math.max(0, Math.min(100, Math.round(ctx.getContextUsage()?.percent ?? 0))),
262
261
  exocomEnabled: exocomPlane !== undefined,
263
262
  color: exocomColorFor(displayName),
264
263
  };
@@ -412,7 +411,7 @@ export function installExocom(pi: ExtensionAPI, host: ExocomHost): ExocomInstall
412
411
  exocomSeen = new SeenMessages({ ttlMs: EXOCOM.SEEN_TTL_MS });
413
412
  exocomLedgerFile = ledgerPath(agentDir, hash);
414
413
  exocomWaitNotifier = new IdleCoalescingNotifier<string>({
415
- isIdle: () => canDeliverPersonaNotification(host.orchestrating, host.processingDeferredOrchestration, host.lastCtx?.isIdle?.() === true),
414
+ isIdle: () => canDeliverPersonaNotification(host.orchestrating, host.processingDeferredOrchestration, host.lastCtx?.isIdle() === true),
416
415
  deliver: (message) => sendPersonaFollowUp(pi, message, "pi-persona"),
417
416
  render: (items) => items.join("\n\n"),
418
417
  setTimer: (fn, ms) => { const h = setTimeout(fn, ms); h.unref?.(); return h; },
@@ -423,7 +422,7 @@ export function installExocom(pi: ExtensionAPI, host: ExocomHost): ExocomInstall
423
422
  // pi.sendMessage (a distinct, labellable custom message) rather than pi.sendUserMessage
424
423
  // (mirrors the bridge's own `sendFollowUp` for inbound cross-process text).
425
424
  exocomNotifier = new IdleCoalescingNotifier<string>({
426
- isIdle: () => canDeliverPersonaNotification(host.orchestrating, host.processingDeferredOrchestration, host.lastCtx?.isIdle?.() === true),
425
+ isIdle: () => canDeliverPersonaNotification(host.orchestrating, host.processingDeferredOrchestration, host.lastCtx?.isIdle() === true),
427
426
  deliver: (message) => sendPersonaFollowUp(pi, message, "exocom_received"),
428
427
  // A burst of independent peers must not turn one idle wake into an unbounded model
429
428
  // payload. Each item is already attributed and peer-fenced by buildInboundDelivery;
@@ -536,7 +535,7 @@ export function installExocom(pi: ExtensionAPI, host: ExocomHost): ExocomInstall
536
535
  if (!plane) throw new Error("exocom is not active for this persona");
537
536
  if (!exocomLedgerFile) throw new Error("exocom ledger is not available");
538
537
  let target: DisplayPeer | undefined;
539
- if (frame.kind === "ask") {
538
+ if (frame.kind === "ask" || (frame.kind === "offer" && frame.to_session !== undefined)) {
540
539
  target = plane.listPeers().find((peer) => peer.session_id === frame.to_session);
541
540
  if (!target) throw new Error(`exocom: unknown peer session "${frame.to_session}"`);
542
541
  } else if (frame.kind === "answer") {
@@ -550,7 +549,14 @@ export function installExocom(pi: ExtensionAPI, host: ExocomHost): ExocomInstall
550
549
  }
551
550
  }
552
551
  const prune = currentLedgerPruneOptions();
553
- const applied = commitLedgerEvent(exocomLedgerFile, frame, prune ? { prune } : {});
552
+ if (collaborationWriteIntent(frame, currentLedgerState())
553
+ && (exocomScope?.joined === true || (host.controller.capabilities && !canCallTool(host.controller.capabilities, "exocom_claim")))) {
554
+ throw new Error("exocom: this session cannot claim write paths in the selected scope");
555
+ }
556
+ const applied = commitLedgerEvent(exocomLedgerFile, frame, {
557
+ ...(prune ? { prune } : {}),
558
+ canClaim: exocomScope?.joined !== true && (!host.controller.capabilities || canCallTool(host.controller.capabilities, "exocom_claim")),
559
+ });
554
560
  if (!applied.ok) throw new Error(`exocom: ${applied.error}`);
555
561
  if (applied.duplicate === true) return { msg_id: frame.msg_id };
556
562
  // Claims/progress/releases are authoritative in the shared ledger and need no postcard.
@@ -562,7 +568,7 @@ export function installExocom(pi: ExtensionAPI, host: ExocomHost): ExocomInstall
562
568
  } catch { /* the durable result is still recoverable from the ledger */ }
563
569
  return { msg_id: frame.msg_id, peerWakeDeferred: true };
564
570
  }
565
- if (target && (frame.kind === "ask" || frame.kind === "answer")) {
571
+ if (target && (frame.kind === "ask" || frame.kind === "answer" || frame.kind === "offer")) {
566
572
  try {
567
573
  await plane.sendSemantic(target.target, frame);
568
574
  } catch {
@@ -657,7 +663,7 @@ export function installExocom(pi: ExtensionAPI, host: ExocomHost): ExocomInstall
657
663
  exocomNotifier?.notify(decision.deliver);
658
664
  // Never inject peer text into a live model turn. A compact human-only toast makes
659
665
  // receipt visible while a long tool loop keeps the follow-up idle-gated.
660
- if (host.lastCtx?.isIdle?.() !== true) {
666
+ if (host.lastCtx?.isIdle() !== true) {
661
667
  exocomToastNotifier?.notify({ label, inReplyTo: msg.in_reply_to });
662
668
  }
663
669
  }
@@ -692,7 +698,15 @@ export function installExocom(pi: ExtensionAPI, host: ExocomHost): ExocomInstall
692
698
  return { accepted: false, reason: error instanceof Error ? error.message : "ledger unavailable" };
693
699
  }
694
700
  const label = exocomPlane?.humanDisplayLabelFor(fromEntry) ?? fromEntry.session_id;
695
- if (frame.kind === "ask") {
701
+ if (fromEntry.workspace_id !== undefined && fromEntry.workspace_id !== scope.scopeWorkspaceId && collaborationWriteIntent(frame, state)) {
702
+ exocomSeen?.forget(frame.from_session, frame.msg_id);
703
+ return { accepted: false, reason: "external-workspace peers cannot take write tasks in the selected scope" };
704
+ }
705
+ if (frame.kind === "offer") {
706
+ const delivery = deliverCollaborationOffer(frame, state, sessionId, label, Date.now());
707
+ if (!delivery.accepted) { exocomSeen?.forget(frame.from_session, frame.msg_id); return delivery; }
708
+ if (delivery.notice) exocomNotifier?.notify(delivery.notice);
709
+ } else if (frame.kind === "ask") {
696
710
  if (frame.to_session !== sessionId) {
697
711
  exocomSeen?.forget(frame.from_session, frame.msg_id);
698
712
  return { accepted: false, reason: "ask addressed to another session" };
@@ -740,7 +754,7 @@ export function installExocom(pi: ExtensionAPI, host: ExocomHost): ExocomInstall
740
754
  if (shouldReportHeartbeatFailure(exocomHeartbeatFailures)) {
741
755
  try {
742
756
  host.lastCtx?.ui.notify(
743
- `exocom: heartbeat failed ${exocomHeartbeatFailures}× in a row (${message}) — peers drop this instance from the pool until it recovers.`,
757
+ `exocom: heartbeat failed ${exocomHeartbeatFailures}× in a row (${toastCause(message)}) — peers drop this instance from the pool until it recovers.`,
744
758
  "warning",
745
759
  );
746
760
  } catch {
@@ -775,6 +789,19 @@ export function installExocom(pi: ExtensionAPI, host: ExocomHost): ExocomInstall
775
789
  ledger: () => currentLedgerState(),
776
790
  labelFor: peerLabelFor,
777
791
  });
792
+ registerExocomCollaborationTools(pi, {
793
+ getPlane: () => exocomPlane,
794
+ sessionId: () => sessionId, name: () => host.identity.name, now: () => Date.now(),
795
+ canClaim: () => exocomScope?.joined !== true,
796
+ canCallTool: (name) => !host.controller.capabilities || canCallTool(host.controller.capabilities, name),
797
+ resolveTarget: (target) => {
798
+ if (!exocomPlane) throw new Error("exocom is not active for this persona");
799
+ return exocomPlane.resolvePeer(target).session_id;
800
+ },
801
+ dispatch: dispatchSemantic, ledger: currentLedgerState, labelFor: peerLabelFor,
802
+ targetForSession: (id) => exocomPlane?.listPeers().find((peer) => peer.session_id === id)?.target,
803
+ });
804
+ registerExocomProfileTool(pi, () => exocomPlane);
778
805
  } catch (err) {
779
806
  // `plane.start()` may have bound its server before a later registry write failed.
780
807
  // Teardown while the reference is still owned; this also cancels notifier/timers.
@@ -783,7 +810,7 @@ export function installExocom(pi: ExtensionAPI, host: ExocomHost): ExocomInstall
783
810
  let surfacedInUi = false;
784
811
  if (ctx.hasUI) {
785
812
  try {
786
- ctx.ui.notify(`exocom failed to start: ${message}`, "error");
813
+ ctx.ui.notify(`exocom failed to start: ${toastCause(message)}`, "error");
787
814
  surfacedInUi = true;
788
815
  } catch {
789
816
  /* the session may already be tearing down; stderr remains available */
@@ -891,6 +918,7 @@ export function installExocom(pi: ExtensionAPI, host: ExocomHost): ExocomInstall
891
918
  const workKeys = new Set([
892
919
  ...state.claims.filter((claim) => claim.from_session === exocomSessionId).map((claim) => claim.work_key),
893
920
  ...state.asks.filter((ask) => ask.from_session === exocomSessionId).map((ask) => ask.work_key),
921
+ ...(state.collaboration?.tasks.filter((task) => !task.finished && (task.taken?.from_session ?? task.created.from_session) === exocomSessionId).map((task) => task.created.work_key) ?? []),
894
922
  ]);
895
923
  for (const work_key of workKeys) {
896
924
  const prune = currentLedgerPruneOptions();
@@ -8,7 +8,8 @@ import { dirname } from "node:path";
8
8
 
9
9
  import { attributePeer } from "../core/fence.ts";
10
10
  import { findWriteSetOverlaps, writeSetPathError } from "../core/ownership.ts";
11
- import { isSemanticFrame, truncateForInject, type ExocomAsk, type ExocomClaim, type ExocomSemanticFrame } from "./envelope.ts";
11
+ import { frameSigningPayload, isSemanticFrame, truncateForInject, type ExocomAsk, type ExocomClaim, type ExocomSemanticFrame } from "./envelope.ts";
12
+ import { applyCollaborationEvent, collaborationStatus, emptyCollaboration, parseCollaboration, pruneCollaboration, releaseCollaboration, retainedCollaborationEvent, type CollaborationState } from "./collaboration.ts";
12
13
 
13
14
  export type LedgerEvent = ExocomSemanticFrame;
14
15
 
@@ -33,6 +34,8 @@ export interface LedgerState {
33
34
  /** Accepted ask ids, including completed asks, so ids cannot be recycled in this retained ledger window. */
34
35
  askIds: string[];
35
36
  seen: string[];
37
+ /** Optional only for older in-memory callers; current snapshots retain the bounded peer-work state. */
38
+ collaboration?: CollaborationState;
36
39
  }
37
40
 
38
41
  export type ApplyResult =
@@ -56,7 +59,7 @@ export const LEDGER_LIMITS = {
56
59
  } as const;
57
60
 
58
61
  export function emptyLedger(): LedgerState {
59
- return { claims: [], asks: [], answers: [], askIds: [], seen: [] };
62
+ return { claims: [], asks: [], answers: [], askIds: [], seen: [], collaboration: emptyCollaboration() };
60
63
  }
61
64
 
62
65
  function remember(state: LedgerState, msgId: string): LedgerState {
@@ -99,8 +102,31 @@ export function applyLedgerEvent(state: LedgerState, event: LedgerEvent): ApplyR
99
102
  }
100
103
  return { ok: false, error: "malformed ledger event" };
101
104
  }
105
+ const retained = retainedCollaborationEvent(state.collaboration ?? emptyCollaboration(), event.msg_id);
106
+ if (retained) return frameSigningPayload(retained) === frameSigningPayload(event)
107
+ ? { ok: true, state, duplicate: true } : { ok: false, error: "msg_id conflicts with a retained collaboration fact" };
102
108
  if (state.seen.includes(event.msg_id)) return { ok: true, state, duplicate: true };
103
109
  switch (event.kind) {
110
+ case "task_create":
111
+ case "task_take":
112
+ case "task_finish":
113
+ case "offer":
114
+ case "publish": {
115
+ const collaboration = state.collaboration ?? emptyCollaboration();
116
+ const applied = applyCollaborationEvent(collaboration, event);
117
+ if (!applied.ok) return applied;
118
+ let claims = state.claims;
119
+ const task = collaboration.tasks.find((candidate) => candidate.created.work_key === event.work_key);
120
+ if (event.kind === "task_take" && task?.created.write_set.length) {
121
+ if (claims.some((claim) => claim.work_key === event.work_key && claim.from_session === event.from_session)) return { ok: false, error: "task pickup conflicts with an existing owned claim on this work_key" };
122
+ const claimed = applyLedgerEvent(state, { kind: "claim", work_key: event.work_key, from_session: event.from_session, from_name: event.from_name,
123
+ write_set: [...task.created.write_set], slice: task.created.description.slice(0, 256), msg_id: event.msg_id, ts: event.ts });
124
+ if (!claimed.ok) return claimed;
125
+ claims = claimed.state.claims;
126
+ }
127
+ if (event.kind === "task_finish" && task?.taken) claims = claims.filter((claim) => claim.msg_id !== task.taken!.msg_id);
128
+ return { ok: true, state: remember({ ...state, claims, collaboration: applied.state }, event.msg_id) };
129
+ }
104
130
  case "claim": {
105
131
  if (state.claims.length >= LEDGER_LIMITS.maxClaims) return { ok: false, error: "ledger claim limit reached" };
106
132
  for (const path of event.write_set) {
@@ -138,12 +164,18 @@ export function applyLedgerEvent(state: LedgerState, event: LedgerEvent): ApplyR
138
164
  case "release": {
139
165
  const owned = state.claims.filter((claim) => claim.work_key === event.work_key && claim.from_session === event.from_session);
140
166
  const outbound = state.asks.filter((ask) => ask.work_key === event.work_key && ask.from_session === event.from_session);
141
- if (owned.length === 0 && outbound.length === 0) return { ok: false, error: "release: no owned claim or outbound ask on that work_key" };
167
+ const collaboration = state.collaboration ?? emptyCollaboration();
168
+ const ownsTask = collaboration.tasks.some((task) => task.created.work_key === event.work_key && !task.finished && !task.stale
169
+ && (task.taken?.from_session ?? task.created.from_session) === event.from_session);
170
+ if (owned.length === 0 && outbound.length === 0 && !ownsTask) return { ok: false, error: "release: no owned claim or outbound ask on that work_key" };
142
171
  const claims = state.claims.filter((claim) => !(claim.work_key === event.work_key && claim.from_session === event.from_session));
143
172
  const asks = state.asks.filter((ask) => !(ask.work_key === event.work_key && ask.from_session === event.from_session));
144
- return { ok: true, state: remember({ ...state, claims, asks }, event.msg_id) };
173
+ return { ok: true, state: remember({ ...state, claims, asks, collaboration: releaseCollaboration(collaboration, event.from_session, event.work_key, Date.parse(event.ts)) }, event.msg_id) };
174
+ }
175
+ case "progress": {
176
+ const applied = applyCollaborationEvent(state.collaboration ?? emptyCollaboration(), event);
177
+ return applied.ok ? { ok: true, state: remember({ ...state, collaboration: applied.state }, event.msg_id) } : applied;
145
178
  }
146
- case "progress": return { ok: true, state: remember(state, event.msg_id) };
147
179
  }
148
180
  }
149
181
 
@@ -154,6 +186,7 @@ interface LedgerSnapshot {
154
186
  answers: LedgerAnswer[];
155
187
  ask_ids: string[];
156
188
  seen: string[];
189
+ collaboration?: CollaborationState;
157
190
  }
158
191
 
159
192
  function token(value: unknown): value is string {
@@ -216,7 +249,15 @@ function parseSnapshot(raw: unknown): LedgerState | undefined {
216
249
  }
217
250
  const requiredAskIds = new Set(state.askIds);
218
251
  if (![...requiredAskIds].every((askId) => snapshot.ask_ids!.includes(askId))) return undefined;
219
- return { ...state, askIds: [...snapshot.ask_ids], seen: [...snapshot.seen] };
252
+ const collaboration = snapshot.collaboration === undefined ? emptyCollaboration() : parseCollaboration(snapshot.collaboration);
253
+ if (!collaboration) return undefined;
254
+ for (const task of collaboration.tasks) {
255
+ if (collaborationStatus(task) !== "taken" || !task.created.write_set.length) continue;
256
+ const claim = state.claims.find((candidate) => candidate.msg_id === task.taken?.msg_id);
257
+ if (!claim || claim.from_session !== task.taken?.from_session || claim.work_key !== task.created.work_key
258
+ || JSON.stringify(claim.write_set) !== JSON.stringify(task.created.write_set)) return undefined;
259
+ }
260
+ return { ...state, collaboration, askIds: [...snapshot.ask_ids], seen: [...snapshot.seen] };
220
261
  }
221
262
 
222
263
  function snapshotOf(state: LedgerState): LedgerSnapshot {
@@ -227,6 +268,7 @@ function snapshotOf(state: LedgerState): LedgerSnapshot {
227
268
  answers: state.answers,
228
269
  ask_ids: state.askIds,
229
270
  seen: state.seen,
271
+ collaboration: state.collaboration ?? emptyCollaboration(),
230
272
  };
231
273
  }
232
274
 
@@ -246,6 +288,8 @@ export function parseLedger(text: string): LedgerState {
246
288
  state = restored;
247
289
  continue;
248
290
  }
291
+ if (raw && typeof raw === "object" && typeof (raw as { kind?: unknown }).kind === "string"
292
+ && (raw as { kind: string }).kind.startsWith("ledger_snapshot_")) throw new Error("unsupported ledger snapshot version");
249
293
  if (!isSemanticFrame(raw)) continue;
250
294
  const result = applyLedgerEvent(state, raw);
251
295
  if (result.ok) state = result.state;
@@ -276,7 +320,7 @@ export function pruneLedger(state: LedgerState, options: LedgerPruneOptions): Le
276
320
  const asks = state.asks.filter((ask) => options.liveSessions.has(ask.from_session) && options.liveSessions.has(ask.to_session));
277
321
  const answers = state.answers.filter((answer) => isFresh(answer.ts, now, ttlMs)).slice(-LEDGER_LIMITS.maxResults);
278
322
  const askIds = [...new Set([...asks.map((ask) => ask.ask_id), ...answers.map((answer) => answer.ask_id)])];
279
- return { ...state, claims, asks, answers, askIds };
323
+ return { ...state, claims, asks, answers, askIds, collaboration: pruneCollaboration(state.collaboration ?? emptyCollaboration(), now, ttlMs, (session) => options.liveSessions.has(session)) };
280
324
  }
281
325
 
282
326
  /** The pending asks a prune dropped (a party left the pool) — the ids a waiter must be woken for. */
@@ -565,6 +609,8 @@ export function appendLedgerEvent(path: string, event: LedgerEvent): void {
565
609
  export interface LedgerCommitOptions {
566
610
  /** Applied under the same transaction lock before validating the new event. */
567
611
  prune?: LedgerPruneOptions;
612
+ /** Authoritative write admission, evaluated against the locked task definition (not a preflight read). */
613
+ canClaim?: boolean;
568
614
  /** Test/operations override; defaults to half the maximum journal size. */
569
615
  compactAtBytes?: number;
570
616
  /** Fault-injection seam for short-write and Windows replacement regression tests. */
@@ -578,7 +624,8 @@ export interface LedgerFileIO {
578
624
 
579
625
  function pruningChanged(before: LedgerState, after: LedgerState): boolean {
580
626
  return before.claims.length !== after.claims.length || before.asks.length !== after.asks.length
581
- || before.answers.length !== after.answers.length || before.askIds.length !== after.askIds.length;
627
+ || before.answers.length !== after.answers.length || before.askIds.length !== after.askIds.length
628
+ || JSON.stringify(before.collaboration) !== JSON.stringify(after.collaboration);
582
629
  }
583
630
 
584
631
  export function commitLedgerEvent(path: string, event: LedgerEvent, options: LedgerCommitOptions = {}): ApplyResult {
@@ -588,6 +635,9 @@ export function commitLedgerEvent(path: string, event: LedgerEvent, options: Led
588
635
  const sizeBeforeRecovery = recoverIncompleteTrailingRecordLocked(path);
589
636
  const loaded = loadLedger(path);
590
637
  const pruned = options.prune ? pruneLedger(loaded, options.prune) : loaded;
638
+ const writes = event.kind === "claim" || event.kind === "task_create" ? event.write_set.length > 0
639
+ : event.kind === "task_take" && (pruned.collaboration?.tasks.find((task) => task.created.work_key === event.work_key)?.created.write_set.length ?? 0) > 0;
640
+ if (options.canClaim === false && writes) return { ok: false, error: "this session cannot claim write paths in the selected scope" };
591
641
  const result = applyLedgerEvent(pruned, event);
592
642
  const compactAt = Number.isFinite(options.compactAtBytes) && options.compactAtBytes !== undefined
593
643
  ? Math.max(1, Math.floor(options.compactAtBytes)) : Math.floor(LEDGER_LIMITS.maxBytes / 2);
@@ -33,6 +33,7 @@ import { createFrameReader, encodeFrame } from "../bus/broker/framing.ts";
33
33
  import { frameSigningPayload, isExocomFrame, isSemanticFrame, nextHops, parseExocomArtifactDescriptor, truncateForInject, type AgentCard, type ExocomAck, type ExocomArtifactDescriptor, type ExocomBye, type ExocomFrame, type ExocomMessage, type ExocomNack, type ExocomSemanticFrame } from "./envelope.ts";
34
34
  import { EXOCOM } from "./limits.ts";
35
35
  import { exocomRoot } from "./paths.ts";
36
+ import { normalizeExocomProfile, type ExocomProfile } from "./profile.ts";
36
37
  import { isAlive, normalizePeerName, prune, readAll, removeEntryIfMatches, writeEntry, type RegistryEntry, type RegistryOwnership } from "./registry.ts";
37
38
 
38
39
  export interface ExocomIdentity {
@@ -398,6 +399,9 @@ export class ExocomPlane {
398
399
  private server: net.Server | undefined;
399
400
  private readonly unlinkEndpoint: () => void;
400
401
  private endpointOwned = false;
402
+ private profile: ExocomProfile | undefined;
403
+ /** Last successfully published metadata, so editing a profile cannot restore startup labels. */
404
+ private presence: RegistryEntry | undefined;
401
405
  /** Ownership of the registry entry successfully written by this plane. A plane
402
406
  * may share a session_id with a replacement, so session_id alone is not enough
403
407
  * to clean up safely. */
@@ -443,6 +447,17 @@ export class ExocomPlane {
443
447
  return normalizePeerName(this.deps.identity.name);
444
448
  }
445
449
 
450
+ /** The plane owns this transient, optional self-report for its live session. */
451
+ getProfile(): ExocomProfile | undefined {
452
+ return this.profile ? { ...this.profile, capabilities: [...this.profile.capabilities] } : undefined;
453
+ }
454
+
455
+ /** Update the live registry immediately; `undefined` withdraws the entire self-report. */
456
+ setProfile(profile: ExocomProfile | undefined): void {
457
+ this.profile = profile === undefined ? undefined : normalizeExocomProfile(profile);
458
+ if (this.registeredOwnership) this.heartbeat({ ...(this.presence ?? this.buildEntry()), heartbeat_at: new Date(this.now()).toISOString() });
459
+ }
460
+
446
461
  /** Messages this instance has successfully `send()`'d TO the given peer (ack settled), keyed by
447
462
  * the peer's session_id — 0 for a peer never sent to. The plane is the SINGLE source of these
448
463
  * counters — the widget reads them, it never keeps its own. */
@@ -480,6 +495,7 @@ export class ExocomPlane {
480
495
  prune(agentDir, hash, { now: this.now(), staleMs: EXOCOM.STALE_AFTER_MS });
481
496
  const entry = this.buildEntry();
482
497
  writeEntry(agentDir, hash, entry);
498
+ this.presence = entry;
483
499
  this.registeredOwnership = {
484
500
  session_id: entry.session_id,
485
501
  endpoint: entry.endpoint,
@@ -524,6 +540,7 @@ export class ExocomPlane {
524
540
  workspace_code: identity.workspace.code,
525
541
  workspace_label: identity.workspace.label,
526
542
  } : {}),
543
+ ...(this.profile ? { profile: this.getProfile()! } : {}),
527
544
  };
528
545
  }
529
546
 
@@ -535,8 +552,15 @@ export class ExocomPlane {
535
552
  * key exists only in this process. `session_id` is ours by construction, never the caller's. */
536
553
  heartbeat(entry: Omit<RegistryEntry, "public_key">): void {
537
554
  const { agentDir, hash, identity } = this.deps;
538
- const owned = { ...entry, session_id: identity.session_id, public_key: this.publicKey };
555
+ const { profile: _callerProfile, ...entryWithoutProfile } = entry;
556
+ const owned = {
557
+ ...entryWithoutProfile,
558
+ session_id: identity.session_id,
559
+ public_key: this.publicKey,
560
+ ...(this.profile ? { profile: this.getProfile()! } : {}),
561
+ };
539
562
  writeEntry(agentDir, hash, owned);
563
+ this.presence = owned;
540
564
  this.registeredOwnership = { session_id: owned.session_id, endpoint: owned.endpoint, public_key: owned.public_key };
541
565
  }
542
566
 
@@ -864,6 +888,11 @@ export class ExocomPlane {
864
888
  return;
865
889
  }
866
890
  case "claim":
891
+ case "task_create":
892
+ case "task_take":
893
+ case "task_finish":
894
+ case "offer":
895
+ case "publish":
867
896
  case "ask":
868
897
  case "answer":
869
898
  case "progress":
@@ -1112,5 +1141,7 @@ export class ExocomPlane {
1112
1141
  // spill. In a scope where Exocom is never enabled again, that is never: sweeping on the
1113
1142
  // way out bounds the retention without touching anything still inside its TTL.
1114
1143
  this.cleanupArtifacts();
1144
+ this.profile = undefined;
1145
+ this.presence = undefined;
1115
1146
  }
1116
1147
  }
@@ -0,0 +1,40 @@
1
+ /** Self-reported presence only; these fields carry no identity or authorization. */
2
+ export interface ExocomProfile {
3
+ capabilities: readonly string[];
4
+ availability?: "available" | "busy" | "away";
5
+ }
6
+
7
+ const UNSAFE_PROFILE_TEXT = /[\u0000-\u001f\u007f-\u009f\u2028\u2029\u200b-\u200f\u202a-\u202e\u2060-\u206f<>]/g;
8
+ const AVAILABILITIES = new Set(["available", "busy", "away"]);
9
+
10
+ function normalizeCapability(value: unknown): string | undefined {
11
+ if (typeof value !== "string") return undefined;
12
+ const clean = Array.from(value.normalize("NFKC").replace(UNSAFE_PROFILE_TEXT, " ").replace(/\s+/g, " ").trim())
13
+ .slice(0, 48).join("");
14
+ return clean || undefined;
15
+ }
16
+
17
+ /** Normalize untrusted registry or tool data into the bounded, display-safe profile contract. */
18
+ export function normalizeExocomProfile(value: unknown): ExocomProfile | undefined {
19
+ if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
20
+ const input = value as Record<string, unknown>;
21
+ const capabilities: string[] = [];
22
+ const seen = new Set<string>();
23
+ if (Array.isArray(input.capabilities)) {
24
+ for (const value of input.capabilities) {
25
+ const capability = normalizeCapability(value);
26
+ if (!capability || seen.has(capability.toLowerCase())) continue;
27
+ seen.add(capability.toLowerCase());
28
+ capabilities.push(capability);
29
+ if (capabilities.length === 8) break;
30
+ }
31
+ }
32
+ const availability = typeof input.availability === "string" && AVAILABILITIES.has(input.availability)
33
+ ? input.availability as ExocomProfile["availability"]
34
+ : undefined;
35
+ if (capabilities.length === 0 && availability === undefined) return undefined;
36
+ return {
37
+ capabilities,
38
+ ...(availability ? { availability } : {}),
39
+ };
40
+ }
@@ -2,6 +2,7 @@
2
2
  import { createHash, randomUUID } from "node:crypto";
3
3
  import { existsSync, lstatSync, linkSync, mkdirSync, readdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
4
4
  import { agentsDir, registryPath } from "./paths.ts";
5
+ import { normalizeExocomProfile, type ExocomProfile } from "./profile.ts";
5
6
 
6
7
  export interface RegistryEntry {
7
8
  /** `name` is display-only — NOT unique, NOT a lookup key. The registry FILE is keyed by
@@ -16,6 +17,8 @@ export interface RegistryEntry {
16
17
  workspace_id?: string;
17
18
  workspace_code?: string;
18
19
  workspace_label?: string;
20
+ /** Optional self-reported presence; it is descriptive and never grants capability. */
21
+ profile?: ExocomProfile;
19
22
  }
20
23
 
21
24
  /** The fields that prove which process owns a registry slot. `session_id` is the
@@ -57,6 +60,7 @@ export function normalizeRegistryEntry(value: unknown): RegistryEntry | undefine
57
60
  const contextPct = typeof e.context_pct === "number" && Number.isFinite(e.context_pct) ? Math.max(0, Math.min(100, e.context_pct)) : 0;
58
61
  const inbox = typeof e.inbox === "number" && Number.isFinite(e.inbox) ? Math.max(0, Math.min(1_000_000, Math.floor(e.inbox))) : 0;
59
62
  const publicKey = opaqueString(e.public_key, 256);
63
+ const profile = normalizeExocomProfile(e.profile);
60
64
  const hasWorkspaceMetadata = e.workspace_id !== undefined || e.workspace_code !== undefined || e.workspace_label !== undefined;
61
65
  let workspace: Pick<RegistryEntry, "workspace_id" | "workspace_code" | "workspace_label"> = {};
62
66
  if (hasWorkspaceMetadata) {
@@ -83,6 +87,7 @@ export function normalizeRegistryEntry(value: unknown): RegistryEntry | undefine
83
87
  inbox,
84
88
  heartbeat_at: new Date(Date.parse(heartbeatAt)).toISOString(),
85
89
  ...(publicKey && /^[A-Za-z0-9+/]+={0,2}$/.test(publicKey) ? { public_key: publicKey } : {}),
90
+ ...(profile ? { profile } : {}),
86
91
  ...workspace,
87
92
  };
88
93
  }
@@ -20,6 +20,7 @@ import type { LedgerAsk, LedgerClaim, LedgerState } from "./ledger.ts";
20
20
  import { formatDuration } from "../core/time.ts";
21
21
  import { fencePeer } from "../core/fence.ts";
22
22
  import { renderWriteSet, untrusted, UNTRUSTED_MAX } from "./untrusted.ts";
23
+ import { collaborationOfferStatus, collaborationStatus } from "./collaboration.ts";
23
24
 
24
25
  /** No section may hand the model an unbounded ledger — a long-lived scope with many claims stays
25
26
  * one bounded read, same discipline as the pending-ask block and the peer roster. */
@@ -72,8 +73,12 @@ export function formatLedgerStatus(
72
73
  const peerClaims = state.claims.filter((claim) => claim.from_session !== self).sort(byTsAscending);
73
74
  const asksForYou = state.asks.filter((ask) => ask.to_session === self).sort(byTsAscending);
74
75
  const yourAsks = state.asks.filter((ask) => ask.from_session === self).sort(byTsAscending);
76
+ const collaboration = state.collaboration;
77
+ const tasks = collaboration?.tasks ?? [];
78
+ const offers = collaboration?.offers ?? [];
79
+ const evidence = collaboration?.evidence ?? [];
75
80
 
76
- if (ownClaims.length === 0 && peerClaims.length === 0 && asksForYou.length === 0 && yourAsks.length === 0) {
81
+ if (ownClaims.length === 0 && peerClaims.length === 0 && asksForYou.length === 0 && yourAsks.length === 0 && tasks.length === 0 && offers.length === 0 && evidence.length === 0) {
77
82
  return "nothing claimed or pending";
78
83
  }
79
84
 
@@ -82,5 +87,10 @@ export function formatLedgerStatus(
82
87
  section("peer claims", peerClaims.map((claim) => claimRow(claim, self, labelFor, now)), { fence: true }),
83
88
  section("asks waiting for you", asksForYou.map((ask) => askRow(ask, ask.from_session, labelFor, now)), { fence: true }),
84
89
  section("your open asks", yourAsks.map((ask) => askRow(ask, ask.to_session, labelFor, now))),
90
+ ...(tasks.length ? [section("shared tasks (exocom_task list for detail)", tasks.map((task) =>
91
+ `${task.created.work_key} · ${collaborationStatus(task)} · ${resolveLabel(task.taken?.from_session ?? task.created.from_session, labelFor)}`), { fence: true })] : []),
92
+ ...(offers.length ? [section("optional invitations", offers.map((offer) =>
93
+ `${offer.offer_id} · task ${offer.work_key} · ${collaborationOfferStatus(offer, tasks, now)} · ${offer.to_session ? resolveLabel(offer.to_session, labelFor) : "open invitation"}`), { fence: true })] : []),
94
+ ...(evidence.length ? [`${evidence.length} retained evidence excerpt(s); discover with exocom_publish { action: "read", work_key: "<task>" }.`] : []),
85
95
  ].join("\n\n");
86
96
  }
@@ -64,6 +64,13 @@ export function writeWarningReason(path: string, claim: LedgerClaim, label: stri
64
64
  return `exocom: ${path} is inside ${who}'s open claim — coordinate with exocom_ask or claim it; call the tool again to proceed (this warning shows once per path)\n${fencePeer(`${slice}: ${writeSet}`)}`;
65
65
  }
66
66
 
67
+ /** The operator-TOAST variant of the same warning: its single authoritative line, sanitized and
68
+ * bounded. The fenced peer-authored detail below the newline stays model-facing (the tool
69
+ * result); a toast is one line and never carries the claim block. */
70
+ export function writeWarningToastReason(path: string, claim: LedgerClaim, label: string): string {
71
+ return untrusted(writeWarningReason(path, claim, label).split("\n")[0] ?? "", 300);
72
+ }
73
+
67
74
  /** Warn-once memory for the write guard. A bare unbounded set would grow for the life of the
68
75
  * install on a long session with many distinct claim+path pairs; caps at `maxEntries` (like the
69
76
  * sibling `SeenMessages` in guards.ts) and drops the oldest insertion first once exceeded. */