@tpsdev-ai/flair 0.62.0 → 0.63.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 (257) hide show
  1. package/README.md +14 -13
  2. package/SECURITY.md +73 -43
  3. package/config.yaml +11 -11
  4. package/dist/bridges/runtime/execute.js +1 -0
  5. package/dist/bridges/runtime/import-runner.js +4 -0
  6. package/dist/bridges/types.js +1 -0
  7. package/dist/build-info.json +3 -3
  8. package/dist/cli.js +309 -205
  9. package/dist/commands/agent.js +325 -137
  10. package/dist/commands/attention.js +2 -0
  11. package/dist/commands/backup-approval.js +218 -0
  12. package/dist/commands/backup.js +37 -33
  13. package/dist/commands/bootstrap.js +5 -1
  14. package/dist/commands/bridge.js +10 -0
  15. package/dist/commands/deploy.js +37 -7
  16. package/dist/commands/doctor.js +206 -42
  17. package/dist/commands/export.js +144 -15
  18. package/dist/commands/federation.js +653 -68
  19. package/dist/commands/grant.js +5 -6
  20. package/dist/commands/help.js +25 -0
  21. package/dist/commands/idp.js +14 -19
  22. package/dist/commands/import.js +167 -34
  23. package/dist/commands/init.js +380 -164
  24. package/dist/commands/integrity.js +5 -6
  25. package/dist/commands/keys.js +12 -8
  26. package/dist/commands/mcp.js +157 -79
  27. package/dist/commands/memory.js +38 -17
  28. package/dist/commands/migrate-harness-memory.js +9 -3
  29. package/dist/commands/orgevent.js +5 -10
  30. package/dist/commands/principal.js +32 -39
  31. package/dist/commands/quality.js +26 -3
  32. package/dist/commands/reembed.js +468 -111
  33. package/dist/commands/rem.js +484 -65
  34. package/dist/commands/restore.js +352 -44
  35. package/dist/commands/search.js +2 -0
  36. package/dist/commands/service.js +109 -2
  37. package/dist/commands/soul.js +0 -6
  38. package/dist/commands/status.js +165 -124
  39. package/dist/commands/test.js +4 -1
  40. package/dist/commands/upgrade.js +53 -22
  41. package/dist/commands/workspace.js +7 -8
  42. package/dist/deploy.js +59 -3
  43. package/dist/doctor-client.js +9 -25
  44. package/dist/fabric-upgrade.js +12 -2
  45. package/dist/federation/presence-send.js +139 -0
  46. package/dist/federation/scheduler.js +148 -12
  47. package/dist/federation-verify.js +269 -177
  48. package/dist/install/clients.js +171 -35
  49. package/dist/keystore.js +77 -10
  50. package/dist/lib/agent-id-rule.js +44 -2
  51. package/dist/lib/agent-key-file.js +509 -0
  52. package/dist/lib/agent-rotation-lock.js +249 -0
  53. package/dist/lib/atomic-write.js +3 -3
  54. package/dist/lib/auth-resolve.js +1040 -64
  55. package/dist/lib/backup-approval-store.js +612 -0
  56. package/dist/lib/backup-artifact.js +343 -0
  57. package/dist/lib/config-critical-section.js +212 -25
  58. package/dist/lib/connect-phase.js +33 -0
  59. package/dist/lib/daemon-liveness.js +2 -1
  60. package/dist/lib/federation-pair-access.js +4 -0
  61. package/dist/lib/federation-retry-queue.js +283 -0
  62. package/dist/lib/federation-retry-row.js +101 -0
  63. package/dist/lib/instruction-event-contract.js +17 -0
  64. package/dist/lib/instruction-event-doctor.js +102 -0
  65. package/dist/lib/key-dir.js +203 -0
  66. package/dist/lib/launchd-management.js +21 -6
  67. package/dist/lib/local-instance-pair.js +8 -1
  68. package/dist/lib/mcp-enable.js +14 -15
  69. package/dist/lib/memory-attributes.js +2 -0
  70. package/dist/lib/memory-provider-timeout.js +33 -0
  71. package/dist/lib/mqtt-config.js +132 -0
  72. package/dist/lib/mqtt-listener-doctor.js +104 -0
  73. package/dist/lib/node-alias-path.js +50 -2
  74. package/dist/lib/open-live-row.js +20 -0
  75. package/dist/lib/ops-url.js +52 -0
  76. package/dist/lib/promotion-content-hash.js +20 -0
  77. package/dist/lib/remote-admin-pass.js +157 -0
  78. package/dist/lib/restore-archive.js +760 -0
  79. package/dist/lib/restore-verify.js +1 -1
  80. package/dist/lib/scheduler-platform.js +13 -0
  81. package/dist/lib/service-repoint.js +13 -4
  82. package/dist/lib/skill-assignment-preflight.js +159 -0
  83. package/dist/lib/skill-seed.js +125 -10
  84. package/dist/lib/skill-tombstone-doctor.js +133 -0
  85. package/dist/lib/soul-scope-fields.js +26 -0
  86. package/dist/lib/terminal-text.js +32 -0
  87. package/dist/lib/uninstall-purge.js +266 -11
  88. package/dist/lib/upgrade-prior-liveness.js +2 -1
  89. package/dist/mcp-client-assertion.js +7 -14
  90. package/dist/memory-id-checkpoint.js +28 -7
  91. package/dist/mqtt-off-deploy.js +550 -0
  92. package/dist/rem/promote-policy.js +3 -3
  93. package/dist/rem/restore.js +302 -26
  94. package/dist/rem/runner.js +220 -58
  95. package/dist/rem/scheduler.js +21 -4
  96. package/dist/resources/A2AAdapter.js +131 -178
  97. package/dist/resources/AdminMemory.js +2 -0
  98. package/dist/resources/AdminMemoryCandidates.js +116 -0
  99. package/dist/resources/Agent.js +155 -45
  100. package/dist/resources/AgentCard.js +4 -0
  101. package/dist/resources/AgentKeyRegister.js +56 -22
  102. package/dist/resources/AgentReadPosition.js +7 -0
  103. package/dist/resources/AgentSeed.js +232 -107
  104. package/dist/resources/AutoPromoteCandidates.js +413 -84
  105. package/dist/resources/Credential.js +6 -8
  106. package/dist/resources/Federation.js +219 -57
  107. package/dist/resources/FederationRetry.js +4 -4
  108. package/dist/resources/InstructionVersion.js +1 -1
  109. package/dist/resources/MCPClientMetadata.js +6 -3
  110. package/dist/resources/Memory.js +1348 -271
  111. package/dist/resources/MemoryArchive.js +149 -64
  112. package/dist/resources/MemoryBootstrap.js +12 -22
  113. package/dist/resources/MemoryCandidate.js +16 -2
  114. package/dist/resources/MemoryConsolidate.js +2 -2
  115. package/dist/resources/MemoryFeed.js +360 -147
  116. package/dist/resources/MemoryMaintenance.js +290 -72
  117. package/dist/resources/MemoryPurge.js +138 -22
  118. package/dist/resources/MemoryReflect.js +68 -14
  119. package/dist/resources/MemoryReindex.js +91 -13
  120. package/dist/resources/Message.js +11 -2
  121. package/dist/resources/OAuth.js +156 -39
  122. package/dist/resources/OAuthClient.js +1 -1
  123. package/dist/resources/OrgEvent.js +292 -29
  124. package/dist/resources/OrgEventCatchup.js +7 -0
  125. package/dist/resources/OrgEventMaintenance.js +48 -10
  126. package/dist/resources/PairingToken.js +1 -1
  127. package/dist/resources/Presence.js +31 -11
  128. package/dist/resources/PromoteMemoryCandidate.js +8 -2
  129. package/dist/resources/RecordUsage.js +2 -4
  130. package/dist/resources/Soul.js +2 -0
  131. package/dist/resources/SoulFeed.js +2 -1
  132. package/dist/resources/WorkspaceLatest.js +4 -0
  133. package/dist/resources/XAA.js +36 -10
  134. package/dist/resources/a2a-stream.js +313 -0
  135. package/dist/resources/a2a-url.js +4 -5
  136. package/dist/resources/agent-admin.js +10 -1
  137. package/dist/resources/agent-auth.js +98 -68
  138. package/dist/resources/agent-read-position-lib.js +4 -1
  139. package/dist/resources/agent-status-guard.js +9 -7
  140. package/dist/resources/auth-middleware.js +166 -42
  141. package/dist/resources/authority-field-guard.js +9 -11
  142. package/dist/resources/auto-promote-lib.js +8 -5
  143. package/dist/resources/basic-auth-header.js +21 -0
  144. package/dist/resources/bm25-index-service.js +4 -5
  145. package/dist/resources/dedup-cluster.js +6 -1
  146. package/dist/resources/embeddings-provider.js +25 -0
  147. package/dist/resources/federation-classify.js +89 -0
  148. package/dist/resources/federation-retry-lib.js +6 -81
  149. package/dist/resources/health.js +75 -19
  150. package/dist/resources/host-pointer/registry.js +29 -0
  151. package/dist/resources/host-pointer-adapter.js +1 -0
  152. package/dist/resources/in-process-api.js +74 -11
  153. package/dist/resources/in-process.js +24 -22
  154. package/dist/resources/instruction-version-record.js +251 -7
  155. package/dist/resources/internal-authority.js +13 -0
  156. package/dist/resources/mcp-client-metadata-fields.js +4 -0
  157. package/dist/resources/mcp-handler.js +146 -13
  158. package/dist/resources/mcp-oauth-flag.js +12 -14
  159. package/dist/resources/mcp-oauth.js +446 -53
  160. package/dist/resources/mcp-tool-scopes.js +69 -0
  161. package/dist/resources/mcp-tools.js +70 -22
  162. package/dist/resources/memory-declared-attributes.js +1 -0
  163. package/dist/resources/memory-embed-hash.js +56 -0
  164. package/dist/resources/memory-host-source.js +5 -2
  165. package/dist/resources/memory-reflect-lib.js +1 -1
  166. package/dist/resources/memory-write-lock.js +202 -23
  167. package/dist/resources/memory-write-response.js +1 -1
  168. package/dist/resources/memory-write-transaction.js +243 -0
  169. package/dist/resources/migration-boot.js +17 -12
  170. package/dist/resources/migrations/boot-progress.js +25 -0
  171. package/dist/resources/migrations/data-dir.js +16 -3
  172. package/dist/resources/migrations/dir-safety.js +60 -2
  173. package/dist/resources/migrations/embedding-stamp.js +315 -49
  174. package/dist/resources/migrations/graph-heal.js +9 -2
  175. package/dist/resources/migrations/ledger.js +5 -2
  176. package/dist/resources/migrations/lock.js +867 -80
  177. package/dist/resources/migrations/progress.js +71 -10
  178. package/dist/resources/migrations/runner.js +212 -18
  179. package/dist/resources/migrations/state.js +36 -1
  180. package/dist/resources/migrations/status.js +2 -13
  181. package/dist/resources/migrations/synthetic-test-migration.js +78 -12
  182. package/dist/resources/migrations/types.js +26 -1
  183. package/dist/resources/migrations/visibility-backfill.js +111 -70
  184. package/dist/resources/oauth-discovery.js +0 -5
  185. package/dist/resources/object-body-guard.js +12 -5
  186. package/dist/resources/org-event-reserved.js +92 -0
  187. package/dist/resources/org-event-write-fault.js +19 -0
  188. package/dist/resources/owner-field-guard.js +1 -1
  189. package/dist/resources/owner-scoped-write-policy.js +65 -21
  190. package/dist/resources/owner-scoped-writes.js +37 -6
  191. package/dist/resources/path-id-rewrite.js +76 -0
  192. package/dist/resources/presence-internal.js +5 -5
  193. package/dist/resources/promotion-binding.js +43 -0
  194. package/dist/resources/promotion-stamp.js +124 -33
  195. package/dist/resources/protocol-context.js +189 -0
  196. package/dist/resources/record-type-kit.js +2 -4
  197. package/dist/resources/request-target.js +28 -1
  198. package/dist/resources/request-transaction.js +11 -1
  199. package/dist/resources/seed-reservation.js +1 -2
  200. package/dist/resources/semantic-retrieval-core.js +7 -6
  201. package/dist/resources/server-row-validation.js +71 -0
  202. package/dist/resources/skill-manifest.js +4 -3
  203. package/dist/resources/skill-version-write.js +400 -27
  204. package/dist/resources/skill-write-fault.js +6 -3
  205. package/dist/resources/skill-write-policy.js +2 -1
  206. package/dist/resources/soul-write-policy.js +26 -7
  207. package/dist/resources/table-helpers.js +1 -1
  208. package/dist/resources/table-subscription-policy.js +518 -85
  209. package/dist/resources/table-subscriptions.js +20 -7
  210. package/dist/resources/txn-pause-point.js +122 -5
  211. package/dist/resources/usage-recording.js +54 -46
  212. package/dist/resources/write-back.js +176 -11
  213. package/dist/resources/write-journal-context.js +5 -0
  214. package/dist/resources/write-journal.js +289 -0
  215. package/dist/src/keystore.js +77 -10
  216. package/dist/src/lib/agent-id-rule.js +44 -2
  217. package/dist/src/lib/atomic-write.js +3 -3
  218. package/dist/src/lib/federation-retry-row.js +101 -0
  219. package/dist/src/lib/instruction-event-contract.js +17 -0
  220. package/dist/src/lib/key-dir.js +203 -0
  221. package/dist/src/lib/memory-attributes.js +2 -0
  222. package/dist/src/lib/open-live-row.js +20 -0
  223. package/dist/src/lib/scheduler-platform.js +13 -0
  224. package/dist/src/lib/soul-scope-fields.js +26 -0
  225. package/dist/src/rem/promote-policy.js +3 -3
  226. package/dist/src/rem/scheduler.js +21 -4
  227. package/docs/access-control.md +39 -21
  228. package/docs/api-reference.md +161 -52
  229. package/docs/auth.md +69 -38
  230. package/docs/claude-code.md +3 -3
  231. package/docs/deploying-on-fabric.md +118 -2
  232. package/docs/deployment.md +17 -0
  233. package/docs/embedding-in-a-harper-app.md +23 -21
  234. package/docs/entity-vocabulary.md +7 -11
  235. package/docs/federation.md +29 -2
  236. package/docs/hosted-on-fabric.md +1 -1
  237. package/docs/integrations.md +11 -11
  238. package/docs/mcp-clients.md +7 -5
  239. package/docs/notes/mcp-agent-auth-consumer.md +4 -9
  240. package/docs/notes/mcp-oauth-model2.md +6 -6
  241. package/docs/openclaw.md +1 -1
  242. package/docs/quickstart-fabric.md +2 -2
  243. package/docs/quickstart.md +3 -3
  244. package/docs/releasing.md +13 -13
  245. package/docs/rem.md +24 -3
  246. package/docs/secrets-and-keys.md +9 -14
  247. package/docs/standalone-local.md +29 -2
  248. package/docs/supply-chain-policy.md +28 -20
  249. package/docs/the-team.md +2 -2
  250. package/docs/upgrade.md +29 -5
  251. package/package.json +18 -11
  252. package/schemas/agent.graphql +3 -3
  253. package/schemas/federation.graphql +10 -7
  254. package/schemas/memory.graphql +7 -2
  255. package/templates/bin/flair-rem-nightly.sh.tmpl +7 -1
  256. package/templates/launchd/start-flair-with-admin-pass.sh +188 -10
  257. package/dist/resources/soul-adk-guard.js +0 -68
@@ -3,8 +3,8 @@ import { randomUUID } from "node:crypto";
3
3
  import { resolveAgentAuth } from "./agent-auth.js";
4
4
  import { Memory } from "./Memory.js";
5
5
  import { MemoryCandidate } from "./MemoryCandidate.js";
6
- import { stampMemoryPromotion } from "./promotion-stamp.js";
7
- import { withComposedWriteTransaction } from "./request-transaction.js";
6
+ import { PromotionStampStaleRowError, stampMemoryPromotion } from "./promotion-stamp.js";
7
+ import { isJoinableTransaction, withComposedWriteTransaction } from "./request-transaction.js";
8
8
  import { derivePromotedTags, derivePromotedVisibility, validateHumanReviewerId } from "../src/rem/promote-policy.js";
9
9
  const error = (status, message) => new Response(JSON.stringify({ error: message }), {
10
10
  status, headers: { "content-type": "application/json" },
@@ -75,6 +75,12 @@ export class PromoteMemoryCandidate extends Resource {
75
75
  return result;
76
76
  await stampMemoryPromotion(memoryId, reviewerId, decidedAt, undefined, shared);
77
77
  return result;
78
+ }).catch((err) => {
79
+ if (!(err instanceof PromotionStampStaleRowError))
80
+ throw err;
81
+ if (isJoinableTransaction(ctx))
82
+ ctx.transaction.abort();
83
+ return error(409, "promotion_stamp_stale_row");
78
84
  });
79
85
  if (written instanceof Response && !written.ok)
80
86
  return written;
@@ -26,10 +26,8 @@
26
26
  * (resources/Memory.ts: "a non-admin agent may only write memories it
27
27
  * owns") would 403 every single legitimate call. Bypassing that check
28
28
  * instead would open the door to modifying ANY field on another agent's
29
- * memory through this surface — not just the count. So this endpoint does
30
- * the narrowest possible thing instead: a TARGETED `usageCount`-only
31
- * bump (read-full-record, merge just this one field, write — see
32
- * ./usage-recording.ts's recordUsageContribution()) against the RAW
29
+ * memory through this surface — not just the count. This endpoint increments
30
+ * `usageCount` with a commit marker against the RAW
33
31
  * `Memory` table object, entirely bypassing the `Memory` RESOURCE class
34
32
  * (and its ownership gate) — its own auth model is verified-agent +
35
33
  * within-org + the caller's READ SCOPE + explicitly NO ownership requirement.
@@ -147,6 +147,8 @@ export class Soul extends databases.flair.Soul {
147
147
  content.updatedAt = new Date().toISOString();
148
148
  this.validate?.(content, true);
149
149
  merged = { ...existing, ...content, id: rowId };
150
+ // The merged row decides: a patch that would leave or add a non-empty
151
+ // scopeTag or a non-empty tags array is refused.
150
152
  const learnedDenied = await refuseSoulWriteContent(merged);
151
153
  if (learnedDenied)
152
154
  return learnedDenied;
@@ -1,5 +1,6 @@
1
1
  import { Resource, databases } from 'harper';
2
2
  import { allowVerified } from './agent-auth.js';
3
+ import { subscribeInProcess } from './table-subscription-policy.js';
3
4
  export class FeedSouls extends Resource {
4
5
  // Self-authorize the subscription via the Ed25519 agent verify (auth reshape
5
6
  // removes the gate's admin elevation). FeedSouls extends Resource (not a Table),
@@ -8,7 +9,7 @@ export class FeedSouls extends Resource {
8
9
  return allowVerified(this.getContext?.());
9
10
  }
10
11
  async *connect(target, incomingMessages) {
11
- const subscription = await databases.flair.Soul.subscribe(target);
12
+ const subscription = await subscribeInProcess(databases.flair.Soul, target);
12
13
  if (!incomingMessages) {
13
14
  return subscription;
14
15
  }
@@ -6,6 +6,7 @@
6
6
  */
7
7
  import { Resource, databases } from "harper";
8
8
  import { allowVerified, resolveAgentAuth } from "./agent-auth.js";
9
+ import { refuseRewrittenAgentId } from "./path-id-rewrite.js";
9
10
  export class WorkspaceLatest extends Resource {
10
11
  // Self-authorize via the Ed25519 agent verify (auth reshape removes the gate's
11
12
  // admin elevation). Any verified agent may read; the path-vs-agent ownership
@@ -28,6 +29,9 @@ export class WorkspaceLatest extends Resource {
28
29
  if (!agentId) {
29
30
  return new Response(JSON.stringify({ error: "agentId required in path: GET /WorkspaceLatest/{agentId}" }), { status: 400, headers: { "Content-Type": "application/json" } });
30
31
  }
32
+ const rewritten = refuseRewrittenAgentId(this.getContext?.(), agentId);
33
+ if (rewritten)
34
+ return rewritten;
31
35
  // Auth: internal calls and admins pass unfiltered; a verified agent may only
32
36
  // read its own workspace state; anonymous is denied. allowRead() already
33
37
  // blocks anonymous HTTP, but this handler must fail closed on its own too.
@@ -9,7 +9,7 @@ import { invalidAgentIdMessage, isValidAgentId } from "../src/lib/agent-id-rule.
9
9
  import { credentialMapsPrincipal, credentialPrincipalId, isUsableCredential } from "../src/lib/credential-status-rule.js";
10
10
  import { withKeyLock } from "./key-lock.js";
11
11
  import { withOwnedTransaction } from "./request-transaction.js";
12
- import { CommittedRowChanged, confirmCommittedRow, sameStoredRow } from "./write-back.js";
12
+ import { CommittedRowChanged, confirmCommittedRow, sameStoredRow, verifyCommittedFields } from "./write-back.js";
13
13
  import { txnPausePoint } from "./txn-pause-point.js";
14
14
  import { claimIdJagJti, idJagReplayDeps, ReplayStoreUnavailable, reportReplayStoreGapsAtBoot } from "./replay-store.js";
15
15
  /**
@@ -199,7 +199,8 @@ async function resolveOrCreatePrincipalLocked(payload, idpConfig, ctx) {
199
199
  const displayName = payload.name ?? email ?? idpSubject;
200
200
  // Within one Harper process, the credential lookup and any JIT create run
201
201
  // in an owned transaction that commits before the subject lock releases.
202
- return withOwnedTransaction(ctx, async (owned) => {
202
+ let touchedCredential;
203
+ const principalId = await withOwnedTransaction(ctx, async (owned) => {
203
204
  // Look for existing credential with this IdP subject
204
205
  for await (const cred of databases.flair.Credential.search({
205
206
  conditions: [
@@ -230,20 +231,21 @@ async function resolveOrCreatePrincipalLocked(payload, idpConfig, ctx) {
230
231
  const pause = txnPausePoint("xaa-credential-touch");
231
232
  if (pause)
232
233
  await pause;
233
- // Update last used
234
- await databases.flair.Credential.put({
234
+ // Update last used with a fresh lastUsedAt. This handler does not retry
235
+ // the touch: a post-commit mismatch or an unreadable read-back refuses
236
+ // the grant.
237
+ const touchedRow = {
235
238
  ...cred,
236
239
  lastUsedAt: nowISO(),
237
- }, owned);
240
+ };
241
+ await databases.flair.Credential.put(touchedRow, owned);
238
242
  // A revoke or a delete committed while this touch was in flight (the
239
243
  // read above through the write above) refuses the grant rather than
240
244
  // being overwritten by the touch: re-read the COMMITTED row and abort
241
245
  // the touch unless it is still this matched, active credential
242
246
  // (resources/write-back.ts, confirmCommittedRow — the same confirmation
243
- // the write-back helper runs once its write is staged). A change
244
- // committed after this read and before the commit is not seen by it:
245
- // Harper has no compare-and-set on a table write, so that sliver is
246
- // outside what this grant can guarantee.
247
+ // the write-back helper runs once its write is staged). Post-commit
248
+ // verification refuses surviving differences in compared fields or identity.
247
249
  try {
248
250
  await confirmCommittedRow(databases.flair.Credential, cred.id, (committed) => committed != null && credentialMapsPrincipal(committed) &&
249
251
  sameStoredRow(committed, cred) &&
@@ -260,6 +262,17 @@ async function resolveOrCreatePrincipalLocked(payload, idpConfig, ctx) {
260
262
  }
261
263
  throw err;
262
264
  }
265
+ // Test-only: inert unless fault injection is enabled and armed. Holds the
266
+ // touch after its final pre-commit confirmation and before its owned
267
+ // transaction commits (flair#2656).
268
+ const commitPause = txnPausePoint("xaa-credential-touch-commit");
269
+ if (commitPause)
270
+ await commitPause;
271
+ // Harper assigns these timestamps; they are not staged application fields.
272
+ const touchedFields = { ...touchedRow };
273
+ delete touchedFields.__createdtime__;
274
+ delete touchedFields.__updatedtime__;
275
+ touchedCredential = { id: String(cred.id), identity: touchedRow, fields: touchedFields };
263
276
  return credentialPrincipalId(cred);
264
277
  }
265
278
  // No existing credential — JIT provision if enabled
@@ -309,6 +322,19 @@ async function resolveOrCreatePrincipalLocked(payload, idpConfig, ctx) {
309
322
  }, owned);
310
323
  return principalId;
311
324
  });
325
+ // flair#2656: the commit is not proof the touch landed. Answer the grant only
326
+ // when a fresh committed read shows the staged values on the same row
327
+ // identity; otherwise the grant is refused.
328
+ if (touchedCredential) {
329
+ const verdict = await verifyCommittedFields(databases.flair.Credential, touchedCredential.id, touchedCredential.identity, touchedCredential.fields);
330
+ if (verdict === "unreadable") {
331
+ throw new Error("the matched IdP credential could not be read back after the touch (outcome: unconfirmed); the jwt-bearer grant is refused");
332
+ }
333
+ if (verdict !== "shown") {
334
+ throw new Error("the matched IdP credential's committed state does not show this grant's staged values (outcome: unconfirmed); the jwt-bearer grant is refused");
335
+ }
336
+ }
337
+ return principalId;
312
338
  }
313
339
  /**
314
340
  * Base URL an ID-JAG is validated against: `FLAIR_PUBLIC_URL` when set,
@@ -421,7 +447,7 @@ export async function handleJwtBearerGrant(data, ctx) {
421
447
  export class IdpConfig extends databases.flair.IdpConfig {
422
448
  // Admin-only on every path (the "Admin-only" comment was previously unenforced —
423
449
  // a pure put() override with no auth check, so the non-rejecting gate let
424
- // anonymous through to Harper's handler). allowAdmin permits admin + internal.
450
+ // anonymous through to Harper's handler).
425
451
  allowRead() { return allowAdmin(this.getContext?.()); }
426
452
  allowCreate() { return allowAdmin(this.getContext?.()); }
427
453
  allowUpdate() { return allowAdmin(this.getContext?.()); }
@@ -0,0 +1,313 @@
1
+ /**
2
+ * a2a-stream.ts — the A2A `message/stream` event stream and the JSON-RPC
3
+ * envelope helpers the A2A adapter shares with it.
4
+ *
5
+ * Harper-free on purpose: the stream reads through a `readPage` function the
6
+ * caller supplies, so its lifecycle (opening cursor, polling, cancel, error
7
+ * frames) is pinned by test/unit/a2a-stream.test.ts without a store.
8
+ * resources/A2AAdapter.ts supplies a reader that runs OrgEventCatchup in
9
+ * process with the requesting caller's own context (see callerCatchupReader
10
+ * there); which events a read returns (targeting, expiry) is decided there.
11
+ *
12
+ * Cursor: the stream keeps its own position cursor, passed to each catch-up
13
+ * read as an explicit `after`, so it never moves the durable catch-up watermark
14
+ * and the watermark does not decide what the stream delivers (the catch-up read
15
+ * still looks the watermark up). It starts at streamOpeningPosition(): after
16
+ * every event created in or before the millisecond the stream opened, whatever
17
+ * the event's id. The opening comment and the first read are delayed until the
18
+ * clock has passed that millisecond; when Harper sends the response headers is
19
+ * Harper's, and is not tied to that delay.
20
+ *
21
+ * Wire format (Server-Sent Events):
22
+ * - an opening `: stream open` comment;
23
+ * - `event: org.event`, `data:` a JSON-RPC result `{ type: "event", event }`
24
+ * for each event a read returns, in catch-up position order, until the
25
+ * stream ends;
26
+ * - `event: task.status`, `data:` a JSON-RPC result `{ type: "task", task }`
27
+ * after an `org.event` frame when statusFromOrgEvent() finds a status for
28
+ * the event: from its detail, its `status` or `kind`, or words in its
29
+ * summary (the helper may infer `failed` from `error` in the summary);
30
+ * - `event: error`, `data:` a JSON-RPC error, sent once when a read is
31
+ * refused or fails while the stream is open; the stream then ends. A read
32
+ * that settles after the stream has ended sends nothing.
33
+ *
34
+ * The stream ends when the client disconnects or cancels (the pending poll is
35
+ * cleared and no further read starts), after `maxMs`, at an event whose task
36
+ * id is `taskId` and whose status is terminal (later events in that page are
37
+ * not sent), or after an error frame.
38
+ */
39
+ import { positionAfterTimestamp } from "./agent-read-position-lib.js";
40
+ export function rpcResult(id, result) {
41
+ return { jsonrpc: "2.0", id: id ?? null, result };
42
+ }
43
+ export function rpcError(id, code, message, data) {
44
+ return {
45
+ jsonrpc: "2.0",
46
+ id: id ?? null,
47
+ error: data === undefined ? { code, message } : { code, message, data },
48
+ };
49
+ }
50
+ export function orgEventWriteFailure(id, failure) {
51
+ return rpcError(id, -32000, "Server error", {
52
+ error: failure === "validator_missing" ? "org_event_validator_missing" : "org_event_row_invalid",
53
+ });
54
+ }
55
+ /** Does a Harper-parsed JSON tree hold a BigInt among its enumerable values,
56
+ * at any array or object depth? `JSON.stringify` throws on one, so an intake
57
+ * that must serialize a caller value asks this first and refuses with a
58
+ * caller error. */
59
+ export function containsBigInt(value) {
60
+ const pending = [value];
61
+ const seen = new Set();
62
+ while (pending.length > 0) {
63
+ const current = pending.pop();
64
+ if (typeof current === "bigint")
65
+ return true;
66
+ if (current === null || typeof current !== "object")
67
+ continue;
68
+ if (seen.has(current))
69
+ continue;
70
+ seen.add(current);
71
+ if (Array.isArray(current)) {
72
+ for (const item of current)
73
+ pending.push(item);
74
+ }
75
+ else {
76
+ for (const item of Object.values(current))
77
+ pending.push(item);
78
+ }
79
+ }
80
+ return false;
81
+ }
82
+ export function cleanText(value) {
83
+ return String(value ?? "").trim();
84
+ }
85
+ function parseJsonSafe(value) {
86
+ if (typeof value !== "string" || !value.trim())
87
+ return null;
88
+ try {
89
+ return JSON.parse(value);
90
+ }
91
+ catch {
92
+ return null;
93
+ }
94
+ }
95
+ function normalizeA2AStatus(statusRaw) {
96
+ const status = cleanText(statusRaw).toLowerCase();
97
+ if (!status)
98
+ return null;
99
+ if (status === "done" || status === "closed" || status === "complete" || status === "completed")
100
+ return "completed";
101
+ if (status === "failed" || status === "error")
102
+ return "failed";
103
+ if (status === "cancelled" || status === "canceled")
104
+ return "canceled";
105
+ if (status === "working" || status === "in_progress" || status === "open" || status === "active" || status === "todo") {
106
+ return "working";
107
+ }
108
+ return null;
109
+ }
110
+ function inferStatusFromText(textRaw) {
111
+ const text = cleanText(textRaw).toLowerCase();
112
+ if (!text)
113
+ return null;
114
+ if (text.includes("completed") || text.includes("complete") || text.includes("done"))
115
+ return "completed";
116
+ if (text.includes("failed") || text.includes("error"))
117
+ return "failed";
118
+ if (text.includes("cancelled") || text.includes("canceled"))
119
+ return "canceled";
120
+ if (text.includes("working") || text.includes("started") || text.includes("in progress"))
121
+ return "working";
122
+ return null;
123
+ }
124
+ export function taskIdFromEvent(event) {
125
+ const refId = cleanText(event?.refId);
126
+ if (refId.startsWith("bd://")) {
127
+ const taskId = cleanText(refId.slice("bd://".length));
128
+ if (taskId)
129
+ return taskId;
130
+ }
131
+ const detail = parseJsonSafe(event?.detail);
132
+ const fromDetail = cleanText(detail?.taskId ?? detail?.id ?? detail?.task?.id);
133
+ if (fromDetail)
134
+ return fromDetail;
135
+ return null;
136
+ }
137
+ export function statusFromOrgEvent(event) {
138
+ const detail = parseJsonSafe(event?.detail);
139
+ return (normalizeA2AStatus(detail?.status) ??
140
+ normalizeA2AStatus(detail?.task?.status) ??
141
+ normalizeA2AStatus(event?.status) ??
142
+ normalizeA2AStatus(event?.kind) ??
143
+ inferStatusFromText(event?.summary) ??
144
+ null);
145
+ }
146
+ const TERMINAL_STATUSES = new Set(["completed", "failed", "canceled"]);
147
+ /**
148
+ * The stream's opening cursor for a stream opened at `openMs`: the first
149
+ * position of the next millisecond. Every `${createdAt}\t${id}` position whose
150
+ * createdAt is in or before the opening millisecond sorts below it, whatever
151
+ * the id; every position in a later millisecond (with a non-empty id) sorts
152
+ * above it. A cursor of positionAfterTimestamp(<opening millisecond>) would
153
+ * still admit an event created earlier in that same millisecond.
154
+ */
155
+ export function streamOpeningPosition(openMs) {
156
+ return positionAfterTimestamp(new Date(openMs + 1).toISOString());
157
+ }
158
+ export const A2A_STREAM_POLL_MS = 2000;
159
+ export const A2A_STREAM_MAX_MS = 5 * 60 * 1000;
160
+ function isResponseLike(value) {
161
+ return (value != null &&
162
+ typeof value === "object" &&
163
+ typeof value.status === "number" &&
164
+ typeof value.json === "function");
165
+ }
166
+ async function refusalError(rpcId, response) {
167
+ let detail = null;
168
+ try {
169
+ const body = await response.json();
170
+ detail = body?.error ?? body ?? null;
171
+ }
172
+ catch {
173
+ detail = null;
174
+ }
175
+ if (response.status === 403)
176
+ return rpcError(rpcId, -32001, "Forbidden", { detail });
177
+ if (response.status === 401)
178
+ return rpcError(rpcId, -32001, "Unauthorized", { detail });
179
+ if (response.status === 400)
180
+ return rpcError(rpcId, -32602, "Invalid params", { detail });
181
+ return rpcError(rpcId, -32000, "Server error", { status: response.status, detail });
182
+ }
183
+ /**
184
+ * The `message/stream` body. Polls `readPage` from streamOpeningPosition(),
185
+ * draining every page (`hasMore`) on each poll, and schedules the next poll
186
+ * only after the current one finishes, so two reads never overlap.
187
+ */
188
+ export function orgEventStream(opts) {
189
+ const pollMs = opts.pollMs ?? A2A_STREAM_POLL_MS;
190
+ const maxMs = opts.maxMs ?? A2A_STREAM_MAX_MS;
191
+ const taskId = cleanText(opts.taskId) || null;
192
+ const encoder = new TextEncoder();
193
+ let controller = null;
194
+ let closed = false;
195
+ let pollTimer;
196
+ let maxTimer;
197
+ const now = opts.now ?? Date.now;
198
+ const openMs = now();
199
+ let after = streamOpeningPosition(openMs);
200
+ // Stop scheduling: no poll starts after this. A read already in flight
201
+ // finishes, sees `closed`, and writes nothing.
202
+ const stop = () => {
203
+ closed = true;
204
+ if (pollTimer !== undefined)
205
+ clearTimeout(pollTimer);
206
+ if (maxTimer !== undefined)
207
+ clearTimeout(maxTimer);
208
+ pollTimer = undefined;
209
+ maxTimer = undefined;
210
+ };
211
+ const end = () => {
212
+ if (closed)
213
+ return;
214
+ stop();
215
+ try {
216
+ controller?.close();
217
+ }
218
+ catch { /* already closed or cancelled */ }
219
+ };
220
+ const write = (chunk) => {
221
+ if (closed || !controller)
222
+ return;
223
+ try {
224
+ controller.enqueue(encoder.encode(chunk));
225
+ }
226
+ catch {
227
+ // The consumer is gone; nothing further can be delivered.
228
+ stop();
229
+ }
230
+ };
231
+ const frame = (name, payload) => write(`event: ${name}\ndata: ${JSON.stringify(payload)}\n\n`);
232
+ const fail = (payload) => {
233
+ frame("error", payload);
234
+ end();
235
+ };
236
+ const deliver = (event) => {
237
+ frame("org.event", rpcResult(opts.rpcId, { type: "event", event }));
238
+ const status = statusFromOrgEvent(event);
239
+ if (!status)
240
+ return false;
241
+ const eventTaskId = taskIdFromEvent(event);
242
+ frame("task.status", rpcResult(opts.rpcId, {
243
+ type: "task",
244
+ task: { id: eventTaskId ?? taskId, status },
245
+ }));
246
+ return taskId !== null && eventTaskId === taskId && TERMINAL_STATUSES.has(status);
247
+ };
248
+ const poll = async () => {
249
+ pollTimer = undefined;
250
+ if (closed)
251
+ return;
252
+ try {
253
+ for (;;) {
254
+ const page = await opts.readPage(after);
255
+ if (closed)
256
+ return;
257
+ if (isResponseLike(page)) {
258
+ const error = await refusalError(opts.rpcId, page);
259
+ if (!closed)
260
+ fail(error);
261
+ return;
262
+ }
263
+ if (!page || typeof page !== "object" || !Array.isArray(page.events)) {
264
+ fail(rpcError(opts.rpcId, -32000, "Server error", { detail: "the catch-up read returned no page" }));
265
+ return;
266
+ }
267
+ for (const event of page.events) {
268
+ if (deliver(event)) {
269
+ end();
270
+ return;
271
+ }
272
+ if (closed)
273
+ return;
274
+ }
275
+ if (typeof page.nextAfter === "string" && page.nextAfter)
276
+ after = page.nextAfter;
277
+ if (!page.hasMore || page.events.length === 0)
278
+ break;
279
+ }
280
+ }
281
+ catch (error) {
282
+ if (!closed)
283
+ fail(rpcError(opts.rpcId, -32000, "Server error", { detail: error?.message ?? String(error) }));
284
+ return;
285
+ }
286
+ if (!closed)
287
+ pollTimer = setTimeout(() => { void poll(); }, pollMs);
288
+ };
289
+ return new ReadableStream({
290
+ start(c) {
291
+ controller = c;
292
+ // Hold the opening comment and the first read until the clock has left
293
+ // the opening millisecond (when Harper sends the response headers is
294
+ // not tied to this delay).
295
+ const open = () => {
296
+ pollTimer = undefined;
297
+ if (closed)
298
+ return;
299
+ if (now() <= openMs) {
300
+ pollTimer = setTimeout(open, 1);
301
+ return;
302
+ }
303
+ write(": stream open\n\n");
304
+ maxTimer = setTimeout(end, maxMs);
305
+ pollTimer = setTimeout(() => { void poll(); }, 0);
306
+ };
307
+ open();
308
+ },
309
+ cancel() {
310
+ stop();
311
+ },
312
+ });
313
+ }
@@ -2,9 +2,8 @@
2
2
  //
3
3
  // A default local Flair install listens on DEFAULT_HTTP_PORT (19926, the
4
4
  // CLI's `DEFAULT_PORT` in src/cli.ts), NOT on 9926 (the legacy early-install
5
- // port). The A2A agent-card `url` and the streaming catch-up self-fetch must
6
- // reflect the REAL listening port, or a remote A2A peer that follows discovery
7
- // hits a dead port.
5
+ // port). The A2A agent-card `url` must reflect the REAL listening port, or a
6
+ // remote A2A peer that follows discovery hits a dead port.
8
7
  //
9
8
  // Kept free of any harper import so the resolution logic is
10
9
  // unit-testable without spinning up Harper (mirrors agentcard-fields.ts —
@@ -13,8 +12,8 @@
13
12
  import { harperPortValue } from "../src/lib/harper-port-value.js";
14
13
  // The CLI's DEFAULT_HTTP_PORT (src/cli.ts `DEFAULT_PORT`). Keep in sync.
15
14
  export const DEFAULT_HTTP_PORT = 19926;
16
- // Loopback base URL for in-process self-calls (e.g. the streaming catch-up
17
- // fetch). Points at the port Flair is ACTUALLY listening on, which Harper
15
+ // Loopback base URL on the port Flair is ACTUALLY listening on (the agent
16
+ // card's local-only fallback below). Reads the port Harper
18
17
  // exposes via HTTP_PORT in the runtime env — never the public/proxy URL.
19
18
  // `HTTP_PORT` is parsed through `harperPortValue` so a host-qualified value
20
19
  // (`127.0.0.1:19926`, `[::1]:19926`) yields a valid URL rather than a doubled
@@ -88,11 +88,20 @@ export const ADMIN_ROLE = "admin";
88
88
  *
89
89
  * Note this covers Agent RECORDS only. `FLAIR_ADMIN_AGENTS` is a separate,
90
90
  * env-configured admin source union-ed in by resources/agent-auth.ts's
91
- * getAdminAgents(); it names agent ids and never touches a record.
91
+ * agentIsAdmin(); it names agent ids and never touches a record.
92
92
  */
93
93
  export function agentRecordIsAdmin(record) {
94
94
  return record?.role === ADMIN_ROLE;
95
95
  }
96
+ /**
97
+ * The agent ids `FLAIR_ADMIN_AGENTS` names (comma-separated; entries trimmed,
98
+ * empty entries dropped), read from the environment on every call.
99
+ * resources/agent-auth.ts's agentIsAdmin() reads its environment half through
100
+ * this, and the federation merge reads the same set (flair#2665).
101
+ */
102
+ export function configuredAdminAgentIds(raw = process.env.FLAIR_ADMIN_AGENTS) {
103
+ return new Set((raw ?? "").split(",").map((s) => s.trim()).filter(Boolean));
104
+ }
96
105
  /**
97
106
  * Make a record about to be written self-consistent, so the two fields can
98
107
  * never be STORED disagreeing.