@tpsdev-ai/flair 0.58.0 → 0.62.0

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 (268) hide show
  1. package/README.md +7 -6
  2. package/SECURITY.md +36 -0
  3. package/config.yaml +15 -1
  4. package/dist/bridges/builtins/mem0.js +63 -28
  5. package/dist/bridges/runtime/import-runner.js +12 -0
  6. package/dist/bridges/runtime/load-plugin.js +42 -13
  7. package/dist/bridges/runtime/yaml-loader.js +4 -2
  8. package/dist/build-info.json +3 -3
  9. package/dist/cli.js +1030 -343
  10. package/dist/commands/agent.js +384 -45
  11. package/dist/commands/attention.js +4 -3
  12. package/dist/commands/backup.js +202 -34
  13. package/dist/commands/bridge.js +172 -119
  14. package/dist/commands/deploy.js +37 -4
  15. package/dist/commands/doctor.js +601 -163
  16. package/dist/commands/export.js +54 -19
  17. package/dist/commands/federation.js +141 -21
  18. package/dist/commands/hook.js +155 -2
  19. package/dist/commands/idp.js +14 -1
  20. package/dist/commands/import.js +7 -3
  21. package/dist/commands/init.js +462 -193
  22. package/dist/commands/integrity.js +388 -0
  23. package/dist/commands/keys.js +247 -58
  24. package/dist/commands/mcp.js +146 -53
  25. package/dist/commands/memory.js +171 -21
  26. package/dist/commands/migrate-harness-memory.js +3 -2
  27. package/dist/commands/orgevent.js +46 -37
  28. package/dist/commands/presence.js +4 -3
  29. package/dist/commands/principal.js +426 -48
  30. package/dist/commands/quality.js +10 -1
  31. package/dist/commands/reembed.js +141 -17
  32. package/dist/commands/relationship.js +2 -1
  33. package/dist/commands/rem.js +56 -18
  34. package/dist/commands/restore.js +101 -61
  35. package/dist/commands/search.js +6 -4
  36. package/dist/commands/service.js +151 -38
  37. package/dist/commands/soul.js +4 -3
  38. package/dist/commands/status.js +43 -5
  39. package/dist/commands/test.js +3 -2
  40. package/dist/commands/upgrade.js +24 -1
  41. package/dist/commands/workspace.js +6 -3
  42. package/dist/component-env.js +31 -41
  43. package/dist/deploy.js +77 -1
  44. package/dist/doctor-client.js +529 -92
  45. package/dist/engine-version-contract.js +1 -0
  46. package/dist/engine-version.js +23 -3
  47. package/dist/federation-verify.js +4 -3
  48. package/dist/hook-install.js +670 -6
  49. package/dist/keystore.js +72 -0
  50. package/dist/lib/action-recall-runtime.js +328 -0
  51. package/dist/lib/agent-home-fields.js +132 -0
  52. package/dist/lib/agent-home.js +427 -0
  53. package/dist/lib/agent-id-rule.js +46 -0
  54. package/dist/lib/agent-roster.js +33 -0
  55. package/dist/lib/auth-resolve.js +49 -16
  56. package/dist/lib/capture-runtime.js +124 -0
  57. package/dist/lib/credential-status-rule.js +78 -0
  58. package/dist/lib/daemon-liveness.js +81 -8
  59. package/dist/lib/doctor-run.js +140 -35
  60. package/dist/lib/durability-copy.js +10 -0
  61. package/dist/lib/embedding-space-doctor.js +75 -0
  62. package/dist/lib/flair-agent-role.js +120 -0
  63. package/dist/lib/hub-url.js +12 -0
  64. package/dist/lib/init-admin-pass.js +88 -12
  65. package/dist/lib/init-listener-environ.js +1 -2
  66. package/dist/lib/init-occupied-listener.js +15 -111
  67. package/dist/lib/init-spawn-attribution.js +73 -0
  68. package/dist/lib/init-tcp-probe.js +33 -0
  69. package/dist/lib/instance-identity-row.js +20 -0
  70. package/dist/lib/launchd-management.js +27 -2
  71. package/dist/lib/listener-table.js +268 -0
  72. package/dist/lib/local-delete-instance.js +27 -0
  73. package/dist/lib/local-instance-pair.js +256 -0
  74. package/dist/lib/mcp-enable.js +1775 -338
  75. package/dist/lib/mcp-oauth-env-core.js +133 -0
  76. package/dist/lib/mcp-oauth-env.js +125 -0
  77. package/dist/lib/mcp-spec.js +17 -1
  78. package/dist/lib/memory-attributes.js +2 -0
  79. package/dist/lib/memory-id-policy.js +46 -0
  80. package/dist/lib/memory-integrity.js +309 -0
  81. package/dist/lib/memory-purge-response.js +20 -0
  82. package/dist/lib/ops-table-count.js +25 -0
  83. package/dist/lib/owned-pins.js +67 -10
  84. package/dist/lib/peer-status.js +27 -0
  85. package/dist/lib/principal-status.js +29 -0
  86. package/dist/lib/process-start-time.js +103 -7
  87. package/dist/lib/proto-safe-record.js +42 -0
  88. package/dist/lib/record-id-path.js +25 -0
  89. package/dist/lib/reembed-server-support.js +66 -0
  90. package/dist/lib/restore-verify.js +104 -0
  91. package/dist/lib/scheduler-platform.js +10 -6
  92. package/dist/lib/secret-keys.js +25 -0
  93. package/dist/lib/secrets-push.js +50 -22
  94. package/dist/lib/skill-seed-pending.js +24 -0
  95. package/dist/lib/skill-seed.js +365 -0
  96. package/dist/lib/stop-start-recovery.js +54 -0
  97. package/dist/lib/using-flair-skill.js +87 -0
  98. package/dist/mcp-client-assertion.js +112 -4
  99. package/dist/memory-id-checkpoint.js +326 -0
  100. package/dist/memory-node-compare.js +207 -0
  101. package/dist/packages/flair-mcp/src/secret-redaction.js +113 -0
  102. package/dist/rem/restore.js +6 -5
  103. package/dist/rem/runner.js +103 -44
  104. package/dist/resources/Agent.js +348 -8
  105. package/dist/resources/AgentKeyRegister.js +214 -0
  106. package/dist/resources/AgentKeyRegistration.js +28 -0
  107. package/dist/resources/AgentSeed.js +19 -4
  108. package/dist/resources/AutoPromoteCandidates.js +7 -1
  109. package/dist/resources/Credential.js +177 -2
  110. package/dist/resources/Federation.js +752 -132
  111. package/dist/resources/FederationRetry.js +140 -0
  112. package/dist/resources/InstructionVersion.js +220 -0
  113. package/dist/resources/Integration.js +300 -25
  114. package/dist/resources/Memory.js +2113 -604
  115. package/dist/resources/MemoryArchive.js +75 -42
  116. package/dist/resources/MemoryBootstrap.js +227 -64
  117. package/dist/resources/MemoryCandidate.js +21 -1
  118. package/dist/resources/MemoryDedupStats.js +30 -1
  119. package/dist/resources/MemoryFeed.js +327 -45
  120. package/dist/resources/MemoryGrant.js +21 -1
  121. package/dist/resources/MemoryMaintenance.js +129 -25
  122. package/dist/resources/MemoryPurge.js +232 -0
  123. package/dist/resources/MemoryReflect.js +7 -2
  124. package/dist/resources/MemoryReindex.js +24 -8
  125. package/dist/resources/Message.js +5 -3
  126. package/dist/resources/OAuth.js +186 -9
  127. package/dist/resources/OrgEvent.js +126 -3
  128. package/dist/resources/OrgSkillAssignment.js +209 -0
  129. package/dist/resources/Presence.js +144 -49
  130. package/dist/resources/PromoteMemoryCandidate.js +18 -7
  131. package/dist/resources/Relationship.js +23 -0
  132. package/dist/resources/SemanticSearch.js +63 -32
  133. package/dist/resources/Soul.js +189 -76
  134. package/dist/resources/TeamDirectory.js +35 -0
  135. package/dist/resources/WorkspaceState.js +21 -1
  136. package/dist/resources/XAA.js +212 -65
  137. package/dist/resources/agent-auth.js +40 -15
  138. package/dist/resources/agent-status-guard.js +63 -0
  139. package/dist/resources/auth-middleware.js +402 -162
  140. package/dist/resources/ed25519-auth.js +1 -1
  141. package/dist/resources/embedding-space-guard.js +366 -72
  142. package/dist/resources/engine-version-stamp-boot.js +53 -0
  143. package/dist/resources/federation-classify.js +94 -0
  144. package/dist/resources/federation-crypto.js +5 -5
  145. package/dist/resources/federation-retry-lib.js +135 -0
  146. package/dist/resources/flair-agent-role-boot.js +26 -0
  147. package/dist/resources/grant-visibility.js +135 -0
  148. package/dist/resources/harper-routing.js +83 -0
  149. package/dist/resources/health.js +130 -20
  150. package/dist/resources/host-source-citation.js +49 -0
  151. package/dist/resources/host-source-visibility.js +7 -6
  152. package/dist/resources/instance-create-lock.js +17 -0
  153. package/dist/resources/instance-identity.js +23 -0
  154. package/dist/resources/instruction-version-record.js +343 -0
  155. package/dist/resources/key-lock.js +31 -0
  156. package/dist/resources/mcp-handler.js +36 -8
  157. package/dist/resources/mcp-oauth-env-guard.js +36 -0
  158. package/dist/resources/mcp-oauth.js +26 -12
  159. package/dist/resources/mcp-tool-arguments.js +4 -6
  160. package/dist/resources/mcp-tools.js +150 -23
  161. package/dist/resources/memory-bootstrap-lib.js +5 -15
  162. package/dist/resources/memory-declared-attributes.js +3 -1
  163. package/dist/resources/memory-deletion-history.js +55 -0
  164. package/dist/resources/memory-durability.js +54 -0
  165. package/dist/resources/memory-embed-hash.js +88 -0
  166. package/dist/resources/memory-embedding-value.js +8 -0
  167. package/dist/resources/memory-host-source.js +27 -5
  168. package/dist/resources/memory-id-guard.js +75 -0
  169. package/dist/resources/memory-redaction.js +236 -0
  170. package/dist/resources/memory-supplied-vector.js +72 -0
  171. package/dist/resources/memory-write-lock.js +310 -0
  172. package/dist/resources/memory-write-response.js +139 -0
  173. package/dist/resources/migrations/data-dir.js +74 -16
  174. package/dist/resources/migrations/dir-safety.js +1 -1
  175. package/dist/resources/migrations/embedding-stamp.js +193 -79
  176. package/dist/resources/migrations/export.js +1 -0
  177. package/dist/resources/migrations/graph-heal.js +18 -25
  178. package/dist/resources/migrations/lock.js +7 -1
  179. package/dist/resources/migrations/snapshot.js +1 -0
  180. package/dist/resources/migrations/source-fields.js +5 -5
  181. package/dist/resources/migrations/synthetic-test-migration.js +14 -11
  182. package/dist/resources/migrations/visibility-backfill.js +29 -29
  183. package/dist/resources/multi-worker-guard.js +121 -0
  184. package/dist/resources/oauth-discovery.js +1 -0
  185. package/dist/resources/oauth-wellknown.js +8 -4
  186. package/dist/resources/object-body-guard.js +33 -0
  187. package/dist/resources/org-event-created-at.js +133 -0
  188. package/dist/resources/originator-instance.js +39 -7
  189. package/dist/resources/owner-delete-recheck.js +78 -0
  190. package/dist/resources/owner-field-guard.js +39 -5
  191. package/dist/resources/owner-scoped-write-policy.js +212 -0
  192. package/dist/resources/owner-scoped-writes.js +58 -0
  193. package/dist/resources/presence-receipt.js +236 -0
  194. package/dist/resources/promotion-stamp.js +47 -12
  195. package/dist/resources/record-owner-guard.js +74 -26
  196. package/dist/resources/record-types.js +17 -1
  197. package/dist/resources/relay-ops.js +78 -6
  198. package/dist/resources/replay-store.js +145 -21
  199. package/dist/resources/request-target.js +136 -0
  200. package/dist/resources/request-transaction.js +35 -0
  201. package/dist/resources/search-readiness.js +4 -1
  202. package/dist/resources/seed-ids.js +9 -0
  203. package/dist/resources/seed-reservation.js +117 -0
  204. package/dist/resources/semantic-retrieval-core.js +20 -9
  205. package/dist/resources/skill-manifest.js +190 -0
  206. package/dist/resources/skill-provenance.js +15 -10
  207. package/dist/resources/skill-subject.js +53 -0
  208. package/dist/resources/skill-version-write.js +432 -0
  209. package/dist/resources/skill-write-fault.js +17 -0
  210. package/dist/resources/skill-write-policy.js +67 -0
  211. package/dist/resources/skill-write.js +67 -7
  212. package/dist/resources/table-helpers.js +10 -7
  213. package/dist/resources/team-directory.js +248 -0
  214. package/dist/resources/tool-descriptors/index.js +69 -8
  215. package/dist/resources/txn-pause-point.js +118 -0
  216. package/dist/resources/usage-recording.js +171 -63
  217. package/dist/resources/write-back.js +218 -0
  218. package/dist/src/engine-version-contract.js +1 -0
  219. package/dist/src/keystore.js +72 -0
  220. package/dist/src/lib/agent-home-fields.js +132 -0
  221. package/dist/src/lib/agent-id-rule.js +46 -0
  222. package/dist/src/lib/agent-key-register.js +80 -0
  223. package/dist/src/lib/atomic-write.js +256 -0
  224. package/dist/src/lib/credential-status-rule.js +78 -0
  225. package/dist/src/lib/expired-by-agent.js +37 -0
  226. package/dist/src/lib/flair-agent-role.js +120 -0
  227. package/dist/src/lib/idp-mapping-rule.js +81 -0
  228. package/dist/src/lib/instance-identity-row.js +20 -0
  229. package/dist/src/lib/mcp-oauth-env-core.js +133 -0
  230. package/dist/src/lib/memory-attributes.js +2 -0
  231. package/dist/src/lib/memory-id-policy.js +46 -0
  232. package/dist/src/lib/principal-status.js +29 -0
  233. package/dist/src/lib/proto-safe-record.js +42 -0
  234. package/dist/src/lib/reembed-server-support.js +66 -0
  235. package/dist/src/lib/scheduler-platform.js +10 -6
  236. package/dist/src/lib/systemd-agent-id.js +38 -0
  237. package/docs/access-control.md +768 -0
  238. package/docs/api-reference.md +52 -13
  239. package/docs/auth.md +10 -12
  240. package/docs/bridges.md +11 -0
  241. package/docs/claude-code.md +34 -4
  242. package/docs/deepseek-harness.md +1 -1
  243. package/docs/deploying-on-fabric.md +70 -0
  244. package/docs/deployment.md +2 -0
  245. package/docs/embedding-in-a-harper-app.md +1 -1
  246. package/docs/federation.md +33 -2
  247. package/docs/hosted-on-fabric.md +43 -36
  248. package/docs/integrations.md +6 -6
  249. package/docs/mcp-clients.md +10 -5
  250. package/docs/n8n.md +17 -11
  251. package/docs/notes/mcp-agent-auth-consumer.md +12 -4
  252. package/docs/notes/mcp-oauth-model2.md +34 -5
  253. package/docs/quickstart-fabric.md +2 -2
  254. package/docs/quickstart.md +9 -1
  255. package/docs/releasing.md +34 -28
  256. package/docs/rem.md +8 -0
  257. package/docs/secrets-and-keys.md +19 -2
  258. package/docs/standalone-local.md +1 -0
  259. package/docs/supply-chain-policy.md +13 -3
  260. package/docs/upgrade.md +32 -6
  261. package/package.json +12 -6
  262. package/schemas/agent-key-registration.graphql +22 -0
  263. package/schemas/agent.graphql +3 -0
  264. package/schemas/federation.graphql +38 -1
  265. package/schemas/memory.graphql +115 -5
  266. package/schemas/oauth.graphql +27 -4
  267. package/schemas/schema.graphql +2 -0
  268. package/templates/launchd/start-flair-with-admin-pass.sh +89 -16
@@ -302,6 +302,20 @@ export function buildEd25519Auth(agentId, method, path, keyPath) {
302
302
  const sig = nodeCryptoSign(null, Buffer.from(payload), privKey).toString("base64");
303
303
  return `TPS-Ed25519 ${agentId}:${ts}:${nonce}:${sig}`;
304
304
  }
305
+ /** Join a Flair route to an optional base path before signing or sending it. */
306
+ export function requestUrl(baseUrl, path) {
307
+ const base = new URL(baseUrl);
308
+ if (base.search || base.hash || /[?#]$/.test(baseUrl)) {
309
+ throw new Error("Flair base URL must not contain a query or fragment");
310
+ }
311
+ const route = new URL(path, base.origin);
312
+ base.pathname = `${base.pathname.replace(/\/+$/, "")}${route.pathname}`;
313
+ base.search = route.search;
314
+ return base;
315
+ }
316
+ export function requestTarget(url) {
317
+ return `${url.pathname}${url.search}`;
318
+ }
305
319
  /**
306
320
  * Classify a throw from `buildEd25519Auth`.
307
321
  *
@@ -378,12 +392,16 @@ export function describeKeyLoadFailure(keyPath, kind, underlying) {
378
392
  *
379
393
  * Throws {@link KeyLoadError} if the key could not be loaded — a failure that
380
394
  * provably happened BEFORE any byte hit the network, so no caller need guess
381
- * whether the instance is reachable. Anything else thrown here is transport.
395
+ * whether the instance is reachable. A URL that cannot be built is refused
396
+ * before signing or sending. `fetch` can fail before transport (for example,
397
+ * request construction can reject an invalid header) or during transport;
398
+ * failures are not classified here.
382
399
  */
383
400
  export async function authFetch(baseUrl, agentId, keyPath, method, path, body) {
401
+ const url = requestUrl(baseUrl, path);
384
402
  let auth;
385
403
  try {
386
- auth = buildEd25519Auth(agentId, method, path, keyPath);
404
+ auth = buildEd25519Auth(agentId, method, requestTarget(url), keyPath);
387
405
  }
388
406
  catch (err) {
389
407
  throw KeyLoadError.from(keyPath, err);
@@ -391,7 +409,7 @@ export async function authFetch(baseUrl, agentId, keyPath, method, path, body) {
391
409
  const headers = { Authorization: auth };
392
410
  if (body !== undefined)
393
411
  headers["Content-Type"] = "application/json";
394
- return fetch(`${baseUrl}${path}`, {
412
+ return fetch(url.href, {
395
413
  method,
396
414
  headers,
397
415
  body: body !== undefined ? JSON.stringify(body) : undefined,
@@ -414,8 +432,8 @@ export function isLocalBase(base) {
414
432
  * agree on 204/empty-body handling, JSON parsing, and the no-credentials
415
433
  * 403 hint text.
416
434
  */
417
- export async function sendJsonRequest(baseUrl, method, path, body, authHeader, isLocal) {
418
- const res = await fetch(`${baseUrl}${path}`, {
435
+ export async function sendJsonRequest(url, method, body, authHeader, isLocal) {
436
+ const res = await fetch(url.href, {
419
437
  method,
420
438
  headers: {
421
439
  "content-type": "application/json",
@@ -454,7 +472,7 @@ export async function sendJsonRequest(baseUrl, method, path, body, authHeader, i
454
472
  * fails or none exist, so the caller can rethrow its ORIGINAL
455
473
  * no-credentials error rather than a floor-specific one.
456
474
  */
457
- export async function tryAgentKeyFloor(baseUrl, method, path, body, keysDir) {
475
+ export async function tryAgentKeyFloor(url, method, body, keysDir) {
458
476
  let keyFiles = [];
459
477
  try {
460
478
  keyFiles = readdirSync(keysDir).filter((f) => f.endsWith(".key")).sort();
@@ -462,13 +480,13 @@ export async function tryAgentKeyFloor(baseUrl, method, path, body, keysDir) {
462
480
  catch {
463
481
  // No keys dir at all — nothing to fall back to.
464
482
  }
465
- const isLocal = isLocalBase(baseUrl);
483
+ const isLocal = isLocalBase(url.origin);
466
484
  for (const kf of keyFiles) {
467
485
  const agentId = kf.replace(/\.key$/, "");
468
486
  const keyPath = join(keysDir, kf);
469
487
  try {
470
- const authHeader = buildEd25519Auth(agentId, method, path, keyPath);
471
- return await sendJsonRequest(baseUrl, method, path, body, authHeader, isLocal);
488
+ const authHeader = buildEd25519Auth(agentId, method, requestTarget(url), keyPath);
489
+ return await sendJsonRequest(url, method, body, authHeader, isLocal);
472
490
  }
473
491
  catch {
474
492
  // This key didn't work (unregistered, bad signature, network blip on
@@ -515,6 +533,8 @@ export function emitIdentityOverrideNotice(message, write = (s) => { process.std
515
533
  export function resetIdentityOverrideNotices() {
516
534
  emittedIdentityOverrides.clear();
517
535
  }
536
+ /** The Authorization scheme of an Ed25519 agent signature (buildEd25519Auth). */
537
+ const ED25519_SCHEME = "TPS-Ed25519 ";
518
538
  /**
519
539
  * The shared resolver: given a Flair REST call and whatever credential
520
540
  * material the caller already knows about, resolve auth across all 5 tiers
@@ -522,6 +542,8 @@ export function resetIdentityOverrideNotices() {
522
542
  * any non-2xx response (after the tier-5 floor has also been exhausted).
523
543
  */
524
544
  export async function authedRequest(method, path, body, opts) {
545
+ const url = requestUrl(opts.baseUrl, path);
546
+ const signedPath = requestTarget(url);
525
547
  const isLocal = opts.isLocal ?? isLocalBase(opts.baseUrl);
526
548
  const keysDir = opts.keysDir ?? defaultKeysDir();
527
549
  // One username for every Basic tier: flag > FLAIR_ADMIN_USER env > "admin"
@@ -531,6 +553,10 @@ export async function authedRequest(method, path, body, opts) {
531
553
  // Which tier supplied authHeader — drives the never-silent override notice
532
554
  // below (see describeIdentityOverride).
533
555
  let credSource;
556
+ if (opts.signedOnly && opts.explicitAdminPass) {
557
+ throw new Error("refusing to send an admin password to a target that may receive only an Ed25519 signature or no Authorization header " +
558
+ "(its instance is not proven); pass --agent <a registered agent id> instead");
559
+ }
534
560
  // Tier 1: explicit — caller-resolved flag material always wins.
535
561
  if (opts.explicitAdminPass) {
536
562
  authHeader = `Basic ${Buffer.from(`${adminUser}:${opts.explicitAdminPass}`).toString("base64")}`;
@@ -538,7 +564,7 @@ export async function authedRequest(method, path, body, opts) {
538
564
  }
539
565
  else if (opts.explicitKeyPath && opts.agentId) {
540
566
  try {
541
- authHeader = buildEd25519Auth(opts.agentId, method, path, opts.explicitKeyPath);
567
+ authHeader = buildEd25519Auth(opts.agentId, method, signedPath, opts.explicitKeyPath);
542
568
  credSource = "explicit-key";
543
569
  }
544
570
  catch (err) {
@@ -559,11 +585,12 @@ export async function authedRequest(method, path, body, opts) {
559
585
  `to a directory containing it). Refusing to fall back to FLAIR_ADMIN_PASS ` +
560
586
  `or the local admin-pass file.`);
561
587
  }
562
- authHeader = buildEd25519Auth(opts.agentId, method, path, keyPath);
588
+ authHeader = buildEd25519Auth(opts.agentId, method, signedPath, keyPath);
563
589
  credSource = "flag-agent";
564
590
  }
565
591
  // Tier 2: env — FLAIR_TOKEN (Bearer), else FLAIR_ADMIN_PASS/HDB_ADMIN_PASSWORD (Basic).
566
- if (!authHeader) {
592
+ // Skipped when only a signature may be sent.
593
+ if (!authHeader && !opts.signedOnly) {
567
594
  if (process.env.FLAIR_TOKEN) {
568
595
  authHeader = `Bearer ${process.env.FLAIR_TOKEN}`;
569
596
  credSource = "env-token";
@@ -581,7 +608,7 @@ export async function authedRequest(method, path, body, opts) {
581
608
  const keyPath = resolveKeyPath(opts.agentId);
582
609
  if (keyPath) {
583
610
  try {
584
- authHeader = buildEd25519Auth(opts.agentId, method, path, keyPath);
611
+ authHeader = buildEd25519Auth(opts.agentId, method, signedPath, keyPath);
585
612
  credSource = "pinned-agent";
586
613
  }
587
614
  catch (err) {
@@ -591,7 +618,8 @@ export async function authedRequest(method, path, body, opts) {
591
618
  }
592
619
  }
593
620
  // Tier 4: LOCAL TARGETS ONLY — the secure ~/.flair/admin-pass file.
594
- if (!authHeader) {
621
+ // Skipped when only a signature may be sent.
622
+ if (!authHeader && !opts.signedOnly) {
595
623
  try {
596
624
  const filePass = resolveLocalAdminPass(undefined, !isLocal);
597
625
  if (filePass) {
@@ -621,15 +649,20 @@ export async function authedRequest(method, path, body, opts) {
621
649
  if (notice)
622
650
  emitIdentityOverrideNotice(notice);
623
651
  }
652
+ // The last word for signedOnly: whatever resolved above, nothing but an
653
+ // agent signature leaves (flair#2526).
654
+ if (opts.signedOnly && authHeader !== undefined && !authHeader.startsWith(ED25519_SCHEME)) {
655
+ throw new Error("refusing to send a Basic or Bearer credential to a target that may receive only an Ed25519 signature or no Authorization header");
656
+ }
624
657
  try {
625
- return await sendJsonRequest(opts.baseUrl, method, path, body, authHeader, isLocal);
658
+ return await sendJsonRequest(url, method, body, authHeader, isLocal);
626
659
  }
627
660
  catch (err) {
628
661
  // Tier 5 — the floor. Only engages when NOTHING above resolved to
629
662
  // anything sendable (see module header for why a rejected credential
630
663
  // does not retry here).
631
664
  if (err instanceof ApiHttpError && err.noCredentials) {
632
- const floorResult = await tryAgentKeyFloor(opts.baseUrl, method, path, body, keysDir);
665
+ const floorResult = await tryAgentKeyFloor(url, method, body, keysDir);
633
666
  if (floorResult !== undefined)
634
667
  return floorResult;
635
668
  }
@@ -0,0 +1,124 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { createHash, randomBytes } from "node:crypto";
3
+ import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { buildCaptureHookCommand, captureFlushSpec } from "../doctor-client.js";
7
+ import { flairCliVersion } from "./mcp-spec.js";
8
+ import { hookArtifactForPackage, hookInstallRoot, isBuiltHookArtifact, plannedHookRuntime, provisionHookRuntime, resolveBunPath, resolveHookRuntime, } from "./action-recall-runtime.js";
9
+ export const CAPTURE_ARTIFACT = {
10
+ key: "capture",
11
+ artifactFile: "capture-hook.js",
12
+ binName: "flair-capture",
13
+ marker: "flair-capture-built",
14
+ runtimeFiles: ["capture-hook.js", "capture-spool.js", "capture.js", "env-guard.js", "secret-redaction.js", "record-id-path.js"],
15
+ envArtifact: "FLAIR_CAPTURE_ARTIFACT",
16
+ };
17
+ export function captureArtifactForPackage(packageDir) {
18
+ return hookArtifactForPackage(packageDir, CAPTURE_ARTIFACT);
19
+ }
20
+ export function captureInstallRoot(homeDir) {
21
+ return hookInstallRoot(homeDir, CAPTURE_ARTIFACT);
22
+ }
23
+ export function plannedCaptureRuntime(runtime, homeDir) {
24
+ return plannedHookRuntime(runtime, homeDir, CAPTURE_ARTIFACT);
25
+ }
26
+ export function provisionCaptureRuntime(runtime, homeDir, agentId, flairUrl) {
27
+ return provisionHookRuntime(runtime, homeDir, agentId, flairUrl, CAPTURE_ARTIFACT, probeCaptureRuntime);
28
+ }
29
+ function isSupportedExecutable(runtime) {
30
+ return resolveBunPath({ FLAIR_BUN_PATH: runtime.bunPath, PATH: "" }) === runtime.bunPath;
31
+ }
32
+ /** The secret shape the probe plants — a GitHub token the redactor recognizes. */
33
+ function probeSecret(nonce) {
34
+ return `ghp_${createHash("sha256").update(nonce).digest("hex").slice(0, 24)}`;
35
+ }
36
+ export function probeCaptureRuntime(runtime, agentId = "flair-probe", flairUrl = "http://localhost:19926", command) {
37
+ const failure = `capture self-test failed (${runtime.bunPath}, ${runtime.artifactPath})`;
38
+ if (!isSupportedExecutable(runtime) || !isBuiltHookArtifact(runtime.artifactPath, CAPTURE_ARTIFACT))
39
+ return failure;
40
+ let home;
41
+ try {
42
+ home = mkdtempSync(join(realpathSync(tmpdir()), "flair-capture-probe-"));
43
+ const nonce = randomBytes(16).toString("hex");
44
+ const secret = probeSecret(nonce);
45
+ const dir = join(home, ".flair", "capture");
46
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
47
+ const installedCommand = command ?? buildCaptureHookCommand(runtime.bunPath, runtime.artifactPath, agentId, flairUrl, captureFlushSpec());
48
+ const commandPath = join(home, "command.sh");
49
+ writeFileSync(commandPath, installedCommand, { mode: 0o600 });
50
+ const payload = JSON.stringify({
51
+ hook_event_name: "Stop",
52
+ session_id: "probe",
53
+ last_assistant_message: `Decision: use probe ${nonce} with token ${secret} for the archive.`,
54
+ });
55
+ const env = {
56
+ HOME: home,
57
+ USERPROFILE: home,
58
+ TMPDIR: home,
59
+ PATH: "/usr/bin:/bin",
60
+ BUN_INSTALL_AUTO: "disable",
61
+ FLAIR_CAPTURE_DIR: dir,
62
+ FLAIR_CAPTURE_NO_FLUSH: "1",
63
+ };
64
+ execFileSync("/bin/sh", [commandPath], { input: payload, encoding: "utf8", timeout: 2000, maxBuffer: 8192, cwd: home, env, stdio: ["pipe", "ignore", "ignore"] });
65
+ const spoolText = readFileSync(join(dir, `${agentId}.spool.json`), "utf-8");
66
+ const parsed = JSON.parse(spoolText);
67
+ const records = Array.isArray(parsed.records) ? parsed.records : [];
68
+ if (records.length !== 1)
69
+ return failure;
70
+ const content = typeof records[0]?.content === "string" ? records[0].content : "";
71
+ if (!content.includes(nonce))
72
+ return failure;
73
+ if (content.includes(secret))
74
+ return failure;
75
+ if (!content.includes("[redacted]"))
76
+ return failure;
77
+ writeFileSync(join(dir, `${agentId}.spool.json`), `${JSON.stringify({ v: 1, agentId, records: [] })}\n`, { mode: 0o600 });
78
+ execFileSync("/bin/sh", [commandPath], {
79
+ input: JSON.stringify({ hook_event_name: "Stop", session_id: "probe", last_assistant_message: "Routine turn; nothing to record." }),
80
+ encoding: "utf8", timeout: 2000, maxBuffer: 8192, cwd: home, env, stdio: ["pipe", "ignore", "ignore"],
81
+ });
82
+ const after = JSON.parse(readFileSync(join(dir, `${agentId}.spool.json`), "utf-8"));
83
+ if ((after.records ?? []).length !== 0)
84
+ return failure;
85
+ // A failed Bash call (PostToolUseFailure) and its later success
86
+ // (PostToolUse) must stage one redacted candidate.
87
+ const toolInput = { command: `probe-${nonce} run` };
88
+ for (const event of [
89
+ { hook_event_name: "PostToolUseFailure", session_id: "probe", tool_name: "Bash", tool_input: toolInput, error: `Error: token ${secret} rejected` },
90
+ { hook_event_name: "PostToolUse", session_id: "probe", tool_name: "Bash", tool_input: toolInput, tool_response: { stdout: "" } },
91
+ ]) {
92
+ execFileSync("/bin/sh", [commandPath], {
93
+ input: JSON.stringify(event), encoding: "utf8", timeout: 2000, maxBuffer: 8192, cwd: home, env, stdio: ["pipe", "ignore", "ignore"],
94
+ });
95
+ }
96
+ const paired = JSON.parse(readFileSync(join(dir, `${agentId}.spool.json`), "utf-8"));
97
+ const pairedRecords = Array.isArray(paired.records) ? paired.records : [];
98
+ if (pairedRecords.length !== 1)
99
+ return failure;
100
+ const pairedContent = typeof pairedRecords[0]?.content === "string" ? pairedRecords[0].content : "";
101
+ if (!pairedContent.includes(nonce) || pairedContent.includes(secret) || !pairedContent.includes("[redacted]"))
102
+ return failure;
103
+ return null;
104
+ }
105
+ catch {
106
+ return failure;
107
+ }
108
+ finally {
109
+ if (home) {
110
+ try {
111
+ rmSync(home, { recursive: true, force: true });
112
+ }
113
+ catch { }
114
+ }
115
+ }
116
+ }
117
+ export function isWorkingCaptureRuntime(runtime) {
118
+ return probeCaptureRuntime(runtime) === null;
119
+ }
120
+ export function resolveCaptureRuntime(opts) {
121
+ return resolveHookRuntime(opts, CAPTURE_ARTIFACT, probeCaptureRuntime);
122
+ }
123
+ /** Re-exported for callers that need the version the descriptor expects. */
124
+ export { flairCliVersion };
@@ -0,0 +1,78 @@
1
+ /**
2
+ * credential-status-rule.ts — the Credential-usability rule shared by the MCP
3
+ * credential resolver, the principal linker and the XAA jwt-bearer grant, from
4
+ * both the CLI (src/) and the server (resources/).
5
+ *
6
+ * A `Credential(kind:"idp")` is the mapping that turns an IdP subject into a
7
+ * flair principal. `resolveAgentFromSub` (resources/mcp-handler.ts) resolves a
8
+ * token subject through it at request time, `provisionIdpIdentityMapping`
9
+ * (src/lib/mcp-enable.ts) is the operator-facing layer that writes and
10
+ * maintains it (the MCP and XAA JIT provisioners also create one when their
11
+ * lookup finds none), and the XAA jwt-bearer grant (resources/XAA.ts,
12
+ * `resolveOrCreatePrincipalLocked`) resolves an ID-JAG subject through it.
13
+ * Before this module the resolver and the linker accepted every status except
14
+ * `"revoked"`, so a principal-bearing row with a missing, empty or unknown
15
+ * status was served as a live mapping; on the resolver's path a revoked row was
16
+ * also skipped, so it could re-create a principal when JIT provisioning was
17
+ * enabled. XAA already accepted only `"active"` (flair#2501). All three sites
18
+ * now use this module's shared rule for row usability.
19
+ *
20
+ * The rule is an ALLOWLIST: a credential is usable only when its `status` is
21
+ * exactly `"active"`. Missing, empty, `"revoked"` and any other value are not
22
+ * usable. All three sites apply `credentialMapsPrincipal`: the row must also
23
+ * name a principal, a non-empty string `principalId`. The schema requires
24
+ * `principalId` and Harper refuses a write that omits it, but it stores an
25
+ * empty string, and no site relies on the schema to exclude a row without one.
26
+ *
27
+ * Deliberately dependency-free (it imports nothing): the resource/CLI boundary
28
+ * guard (test/unit/resource-src-purity-1775.test.ts) requires every src/ module
29
+ * a resources/ file imports to emit no module loads, and src/ must never import
30
+ * harper.
31
+ */
32
+ /** The only `status` value a Credential is usable with. */
33
+ export const CREDENTIAL_STATUS_ACTIVE = "active";
34
+ /**
35
+ * Is `cred` a credential this rule accepts as usable? Exactly
36
+ * `status === "active"`. A null/undefined credential, a missing status, an
37
+ * empty string, `"revoked"` and any other value are all not usable.
38
+ */
39
+ export function isUsableCredential(cred) {
40
+ return cred?.status === CREDENTIAL_STATUS_ACTIVE;
41
+ }
42
+ /**
43
+ * The principal `cred` names: its `principalId` when that is a non-empty
44
+ * string, otherwise null. The resolver, the linker and XAA all decide "names
45
+ * no principal" with this one test.
46
+ */
47
+ export function credentialPrincipalId(cred) {
48
+ const principalId = cred?.principalId;
49
+ return typeof principalId === "string" && principalId !== "" ? principalId : null;
50
+ }
51
+ /**
52
+ * Does `cred` map a principal? It must be usable (`status === "active"`) and
53
+ * name a principal. Anything else maps nothing.
54
+ */
55
+ export function credentialMapsPrincipal(cred) {
56
+ return isUsableCredential(cred) && credentialPrincipalId(cred) !== null;
57
+ }
58
+ /** How a refusal names the status it found: the stored value, or that none was there. */
59
+ function credentialStatusPhrase(status) {
60
+ return status === undefined || status === null ? "no status" : `status ${JSON.stringify(status)}`;
61
+ }
62
+ /**
63
+ * The named refusal for a Credential that maps no principal: it names the
64
+ * actor (the named credential — pass the surrounding subject too when the
65
+ * caller has one), the state (the stored status, or that there is none, and,
66
+ * when applicable, that it names no principal) and the remedy (an operator
67
+ * re-links the subject, which writes an active mapping that names its
68
+ * principal). The resolver builds its JSON-RPC refusal from this, so that
69
+ * wording has one home.
70
+ */
71
+ export function credentialRefusal(actor, cred) {
72
+ const state = credentialPrincipalId(cred) === null
73
+ ? `${credentialStatusPhrase(cred?.status)} and names no principal`
74
+ : credentialStatusPhrase(cred?.status);
75
+ return (`forbidden: ${actor} has ${state}; a Credential is usable only when its status is "active" and it names a ` +
76
+ "principal, so it was not used and nothing was written. An operator must re-link the credential " +
77
+ "(`flair mcp enable`, or `flair principal link`) to write an active mapping.");
78
+ }
@@ -12,7 +12,7 @@
12
12
  * The fix is a classifier with FIVE states, not a boolean:
13
13
  *
14
14
  * RUNNING identity-verified pid alive + flair-identified /Health 2xx
15
- * NOT_RUNNING no pidfile, or verified dead + port refused
15
+ * NOT_RUNNING no live recorded/last-known pid + port refused
16
16
  * WEDGED identity-VERIFIED pid alive + not serving -> stop ACTS
17
17
  * DISAGREEMENT evidence conflicts, identity NOT verified -> stop REFUSES
18
18
  * UNKNOWN insufficient evidence to classify -> stop REFUSES
@@ -71,7 +71,7 @@ export function classifyDaemonState(ev, ctx) {
71
71
  if (ev.pidfile.kind === "unreadable") {
72
72
  return { state: "UNKNOWN", detail: ev.pidfile.reason };
73
73
  }
74
- const pid = ev.pidfile.kind === "present" ? ev.pidfile.pid : null;
74
+ const pid = ev.pidfile.kind === "present" ? ev.pidfile.pid : ev.lastKnownPid ?? null;
75
75
  const liveness = ev.pidLiveness;
76
76
  // THE INVARIANT: WEDGED is reachable only through a VERIFIED identity.
77
77
  // RUNNING requires flair-identified /Health — a foreign 200 is not RUNNING
@@ -83,8 +83,7 @@ export function classifyDaemonState(ev, ctx) {
83
83
  }
84
84
  return { state: "WEDGED", pid: ev.identity.pid };
85
85
  }
86
- // No live pid recorded (absent, or the recorded pid is gone).
87
- if (pid === null || liveness?.kind === "gone") {
86
+ if ((pid === null && liveness === null) || liveness?.kind === "gone") {
88
87
  if (ev.health.kind === "refused") {
89
88
  return { state: "NOT_RUNNING" };
90
89
  }
@@ -124,7 +123,7 @@ export function classifyDaemonState(ev, ctx) {
124
123
  if (liveness?.kind === "unknown") {
125
124
  return {
126
125
  state: "UNKNOWN",
127
- detail: `could not determine whether the recorded pid ${pid} is alive (${liveness.reason}) — refusing to act on it`,
126
+ detail: pid === null ? liveness.reason : `could not determine whether the recorded pid ${pid} is alive (${liveness.reason}) — refusing to act on it`,
128
127
  };
129
128
  }
130
129
  return { state: "UNKNOWN", detail: "could not determine whether Flair is running" };
@@ -171,6 +170,49 @@ export function verifyIdentity(input) {
171
170
  export function isStartTimeMatch(actualMs, recordedMs, toleranceMs = 2000) {
172
171
  return Math.abs(actualMs - recordedMs) <= toleranceMs;
173
172
  }
173
+ /**
174
+ * Does a flair#1454 sidecar's `startTimeMs` agree with a process's start
175
+ * second (flair#2056)? `startSecondMs` is the start time truncated to a whole
176
+ * second, in epoch ms. macOS reads the second `ps -o lstart=` reports; Linux
177
+ * derives it from `/proc` with a verified tick rate. They agree when they are
178
+ * within 2000 ms of each other, compared in milliseconds: a start
179
+ * second of 12 s against a sidecar of 14.5 s is 2500 ms and does not agree.
180
+ */
181
+ export function sidecarStartAgrees(startSecondMs, sidecarStartMs) {
182
+ return Math.abs(sidecarStartMs - startSecondMs) <= 2000;
183
+ }
184
+ /** A Harper entry path under an install tree: `…/node_modules/[@<scope>/]harper/dist/bin/harper.js`. */
185
+ const HARPER_ENTRY_PATH = /(^|\/)node_modules\/(@[^/]+\/)?harper\/dist\/bin\/harper\.js$/;
186
+ /** The relative entry Harper's own restart forks, from its package directory (LAUNCH_SERVICE_SCRIPTS.MAIN). */
187
+ const HARPER_RESTART_ENTRY = "dist/bin/harper.js";
188
+ /**
189
+ * Is this a Harper-shaped command line (flair#2056)? It shows what the process
190
+ * was started with, not that it serves anything.
191
+ *
192
+ * The first argument's basename is `node` or `bun`, and the second is a Harper
193
+ * entry path: `…/node_modules/harper/dist/bin/harper.js` or
194
+ * `…/node_modules/@<scope>/harper/dist/bin/harper.js` (what `flair start`, the
195
+ * launchd launcher and a systemd unit pass), or `dist/bin/harper.js` (what
196
+ * Harper's own restart forks). A second argument starting with `-`, or a Harper
197
+ * path in a later argument, does not match.
198
+ *
199
+ * `cmdline` is `/proc/<pid>/cmdline` (NUL-separated: the arguments exactly) or
200
+ * the line `ps -o command=` reports (arguments joined by spaces; split here on
201
+ * whitespace). From the `ps` line this does not establish which argument is the
202
+ * script: an argument containing a space can produce a matching line.
203
+ */
204
+ export function isHarperProcessCommandLine(cmdline) {
205
+ const args = cmdline.includes("\u0000") ? cmdline.split("\u0000") : cmdline.trim().split(/\s+/);
206
+ if (args.length < 2)
207
+ return false;
208
+ const exe = args[0].split("/").pop();
209
+ if (exe !== "node" && exe !== "bun")
210
+ return false;
211
+ const second = args[1];
212
+ if (second.startsWith("-"))
213
+ return false;
214
+ return second === HARPER_RESTART_ENTRY || HARPER_ENTRY_PATH.test(second);
215
+ }
174
216
  /**
175
217
  * Parse `/proc/<pid>/stat` field 22 (starttime, in clock ticks).
176
218
  *
@@ -189,12 +231,42 @@ export function parseProcStatStartTime(stat) {
189
231
  const starttime = Number(rest[19]);
190
232
  return Number.isFinite(starttime) ? starttime : null;
191
233
  }
234
+ /**
235
+ * Parse the state character (field 3) of `/proc/<pid>/stat`.
236
+ *
237
+ * Field 2 (comm) is parenthesised and may itself contain spaces and `)`
238
+ * characters, so the split is on the LAST `)` — the same rule
239
+ * `parseProcStatStartTime` uses. Returns null when no state follows the comm.
240
+ */
241
+ export function parseProcStatState(stat) {
242
+ const closeParen = stat.lastIndexOf(")");
243
+ if (closeParen < 0)
244
+ return null;
245
+ const rest = stat.slice(closeParen + 1).trim();
246
+ return rest.length > 0 ? rest[0] : null;
247
+ }
248
+ /**
249
+ * Whether a process-state character names an EXITED process (flair#2313).
250
+ *
251
+ * After signal 0 succeeds the pid exists — but an exited child its parent has
252
+ * not yet reaped is a zombie: it exists, it answers signal 0, and it is not a
253
+ * running process. The kernel reports it as state `Z` (Linux field 3 of
254
+ * `/proc/<pid>/stat`; Darwin the first character of `ps -o stat=`), so `Z` is
255
+ * exited.
256
+ *
257
+ * Every other value — including `null`, a state that could not be read — is
258
+ * NOT evidence of exit: a read failure must never report a live process as
259
+ * exited (fail safe).
260
+ */
261
+ export function isExitedState(state) {
262
+ return state === "Z";
263
+ }
192
264
  /**
193
265
  * Convert a `/proc/<pid>/stat` starttime (clock ticks since boot) to epoch ms,
194
266
  * given the system uptime in seconds and the current wall clock. Pure so the
195
267
  * arithmetic is testable without a live process.
196
268
  */
197
- export function procStartTimeToEpochMs(starttimeTicks, uptimeSeconds, nowMs, clkTck = 100) {
269
+ export function procStartTimeToEpochMs(starttimeTicks, uptimeSeconds, nowMs, clkTck) {
198
270
  const bootTimeMs = nowMs - uptimeSeconds * 1000;
199
271
  return bootTimeMs + (starttimeTicks / clkTck) * 1000;
200
272
  }
@@ -379,8 +451,9 @@ export function classifySidecarStaleness(sidecar, liveness) {
379
451
  * CONFIRMED gone AND a fresh O_NOFOLLOW read still names that same pid.
380
452
  *
381
453
  * `observedPid` is the pid the sidecar named when the stop was observed;
382
- * `observedPidLiveness` is that pid read AFTER the stop's wait — `gone` (ESRCH)
383
- * is the confirmation. A process that survived, one owned by another user
454
+ * `observedPidLiveness` is that pid read AFTER the stop's wait — `gone` (ESRCH,
455
+ * or a zombie whose state read reports it) is the confirmation. A process that
456
+ * survived, one owned by another user
384
457
  * (EPERM), or one whose liveness could not be read removes nothing.
385
458
  *
386
459
  * `sidecar` is a fresh O_NOFOLLOW read taken after the stop. A sidecar another