@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
@@ -0,0 +1,120 @@
1
+ /**
2
+ * flair-agent-role.ts — the `flair_agent` Harper role's grant spec, shared by
3
+ * the CLI (`ensureFlairAgentRole`, src/cli.ts) and the server's startup check
4
+ * (resources/flair-agent-role-boot.ts). No Harper imports.
5
+ */
6
+ // ─── flair_agent role ────────────────────────────────────────────────────────
7
+ //
8
+ // The auth reshape replaces the global gate's "verified agent borrows admin
9
+ // super_user" elevation with a real, least-privilege Harper role. After an
10
+ // agent's Ed25519 signature verifies, resources resolve the request to the
11
+ // shared `flair_agent`-roled user instead of admin. Critically: with no
12
+ // `super_user` and no operations grants, /sql and /graphql become NATIVELY 403
13
+ // for agents (the raw-query block the gate hand-rolled is now enforced by
14
+ // Harper itself).
15
+ // Harper 5.0.21 add_role requires an `attribute_permissions` array on EVERY table
16
+ // grant (empty = no attribute-level restriction, so the table-level CRUD applies);
17
+ // omitting it makes add_role reject the whole spec ("Missing 'attribute_permissions'
18
+ // array"). Validated live against a spawned Harper. This helper guarantees the
19
+ // array is never forgotten. Also: `cluster_user` is NOT a valid top-level key —
20
+ // Harper reads unrecognized top-level keys as database names ("database
21
+ // 'cluster_user' does not exist"); only super_user / structure_user are recognized.
22
+ const grant = (read, insert, update, del) => ({ read, insert, update, delete: del, attribute_permissions: [] });
23
+ /** Canonical permission spec for flair_agent (least-privilege; real @table names). */
24
+ export const FLAIR_AGENT_PERMISSION = {
25
+ super_user: false,
26
+ structure_user: false,
27
+ flair: {
28
+ tables: {
29
+ // Core agent-owned data — CRUD envelope.
30
+ Memory: grant(true, true, true, true),
31
+ MemoryCandidate: grant(true, true, true, true),
32
+ MemoryGrant: grant(true, true, true, true),
33
+ // Asset (images-in-Flair slice 1). Harper authorizes BEFORE Asset.post
34
+ // runs, so a de-elevated flair_agent needs the table grant or signed
35
+ // POST /Asset 403s as AccessViolation (Kern P0). CRUD envelope;
36
+ // owner-only + write-time size/MIME gates live in resources/Asset.ts.
37
+ Asset: grant(true, true, true, true),
38
+ Soul: grant(true, true, true, false),
39
+ OrgEvent: grant(true, true, true, true),
40
+ WorkspaceState: grant(true, true, true, true),
41
+ Relationship: grant(true, true, true, true),
42
+ // Flair Relay S1 (flair#1521). Harper authorizes BEFORE the resource
43
+ // methods run, so a de-elevated flair_agent needs the table grant OR it
44
+ // 403s on POST /Message before relaySend is reached (Kern P0-2). read =
45
+ // the party-scoped collection (Message.search); insert = send via post().
46
+ // update = FALSE (least privilege, Kern P0 blocker): the ack's write goes
47
+ // through the IN-PROCESS static accessor (relayConsume → deps.messages.put),
48
+ // which bypasses role gates entirely — the same raw-put seam Federation.ts
49
+ // relies on — so update:true is NOT needed for any legitimate path. Leaving
50
+ // it granted let PATCH /Message/<id> reach Table's update verb, whose
51
+ // authorize step consults update:true and PASSES for any de-elevated agent,
52
+ // bypassing Message.put()'s FORBIDDEN guard AND relayConsume's recipient-only
53
+ // check (Message has no patch() at the platform level → TableResource.patch
54
+ // runs update()+save() directly). delete = false: direct deletes are
55
+ // admin/internal only. Message.patch() also guards the verb in-resource.
56
+ Message: grant(true, true, false, false),
57
+ Integration: grant(true, true, true, true),
58
+ Credential: grant(true, true, true, true),
59
+ Presence: grant(true, true, true, false),
60
+ // MemoryUsage (flair#683): the usage-feedback dedup ledger. Read (own
61
+ // contributions, scoped in resources/MemoryUsage.ts) + insert (a fresh
62
+ // contribution row) only — NO update/delete. This is load-bearing, not
63
+ // just least-privilege tidiness: the dedup rule ("(agent, memory)
64
+ // contributes ≤ 1") is enforced by requiring a NEW ledger row before
65
+ // any usageCount bump; if an agent could delete its own row, it could
66
+ // re-trigger the /RecordUsage endpoint for the same memory indefinitely
67
+ // (create → count → delete → count again → repeat), defeating the cap
68
+ // entirely. See resources/MemoryUsage.ts's module doc.
69
+ MemoryUsage: grant(true, true, false, false),
70
+ // MemoryHitStat (flair#1528): internal search-hit ledger. No agent REST
71
+ // surface (@table without @export). Counts overlay onto Memory reads.
72
+ MemoryHitStat: grant(false, false, false, false),
73
+ // Agent: read for discovery, update own card; creation/removal is admin.
74
+ Agent: grant(true, false, true, false),
75
+ // Read-only reference data.
76
+ Instance: grant(true, false, false, false),
77
+ // flair#2141 S1: org-scope skill assignments. Agents read them; every
78
+ // write is operator/internal only (resources/OrgSkillAssignment.ts), so
79
+ // no write grant. The history table has no direct REST route.
80
+ OrgSkillAssignment: grant(true, false, false, false),
81
+ OrgSkillAssignmentHistory: grant(false, false, false, false),
82
+ // flair#2139 S1: instruction-version history. Read only — the resource
83
+ // itself denies every mutation verb to every principal, and the only
84
+ // application writer is the in-process append helper. See resources/InstructionVersion.ts.
85
+ InstructionVersion: grant(true, false, false, false),
86
+ // Federation / OAuth / IdP / internal — system + admin only; agents get none.
87
+ Peer: grant(false, false, false, false),
88
+ PairingToken: grant(false, false, false, false),
89
+ SyncLog: grant(false, false, false, false),
90
+ OAuthClient: grant(false, false, false, false),
91
+ OAuthToken: grant(false, false, false, false),
92
+ OAuthAuthCode: grant(false, false, false, false),
93
+ IdpConfig: grant(false, false, false, false),
94
+ IdJagReplay: grant(false, false, false, false),
95
+ },
96
+ },
97
+ };
98
+ export const FLAIR_AGENT_ROLE_NAME = "flair_agent";
99
+ /**
100
+ * Brings an existing `flair_agent` role to FLAIR_AGENT_PERMISSION (flair#2141
101
+ * S1): "updated" after an `alter_role`, "unchanged" when it already matches,
102
+ * "absent" when the instance has no such role (this never creates it). Throws
103
+ * when the role list cannot be read; nothing is written then.
104
+ */
105
+ export async function alignFlairAgentRole(op) {
106
+ const roles = await op({ operation: "list_roles" });
107
+ if (!Array.isArray(roles))
108
+ throw new Error("list_roles did not return a list of roles");
109
+ const existing = roles.find((r) => r?.role === FLAIR_AGENT_ROLE_NAME || r?.name === FLAIR_AGENT_ROLE_NAME);
110
+ if (!existing)
111
+ return "absent";
112
+ const permission = existing.permission ?? existing.role?.permission;
113
+ if (JSON.stringify(permission) === JSON.stringify(FLAIR_AGENT_PERMISSION))
114
+ return "unchanged";
115
+ // Harper's alter_role addresses the role by its `id`.
116
+ if (typeof existing.id !== "string" || existing.id.length === 0)
117
+ throw new Error("the flair_agent role has no id");
118
+ await op({ operation: "alter_role", id: existing.id, role: FLAIR_AGENT_ROLE_NAME, permission: FLAIR_AGENT_PERMISSION });
119
+ return "updated";
120
+ }
@@ -0,0 +1,81 @@
1
+ /**
2
+ * idp-mapping-rule.ts — which writes to an IdP identity mapping the Credential
3
+ * resource (resources/Credential.ts) reserves for an administrator or the
4
+ * server.
5
+ *
6
+ * An IdP identity mapping is a `Credential` row of kind "idp". The /mcp OAuth
7
+ * resolver (resources/mcp-handler.ts) resolves a token's subject to the
8
+ * principal named by the active idp row whose `idpSubject` is that subject,
9
+ * and the XAA jwt-bearer grant (resources/XAA.ts) resolves to the principal
10
+ * named by the active idp row whose `idpSubject` and `idpProvider` match the
11
+ * assertion and its IdP configuration ("active" is exactly the status
12
+ * src/lib/credential-status-rule.ts accepts). An administrator and trusted
13
+ * server code write those rows: the /mcp and XAA JIT provisioners in-process,
14
+ * and `flair mcp enable` / `flair principal link` through the operations API.
15
+ *
16
+ * Through the Credential resource, a caller that is neither an administrator
17
+ * nor trusted server code:
18
+ * - cannot create a kind:"idp" row;
19
+ * - cannot change a row's kind to or from "idp";
20
+ * - cannot change an idp row's principalId, idpProvider or idpSubject;
21
+ * - cannot change an idp row's status to anything but "revoked", so cannot
22
+ * reactivate one;
23
+ * - may relabel its own idp row, revoke it, and delete it (DELETE is the
24
+ * owner check's, not this rule's).
25
+ *
26
+ * Dependency-free (imports nothing): resources/ imports it, and the
27
+ * resource/CLI boundary guard (test/unit/resource-src-purity-1775.test.ts)
28
+ * requires such a module to emit no module loads.
29
+ */
30
+ /** The Credential kind that is an IdP identity mapping. */
31
+ export const IDP_KIND = "idp";
32
+ /** The named refusal for a write this rule does not allow the caller. */
33
+ export const IDP_MAPPING_ADMIN_ONLY = "idp_mapping_admin_only";
34
+ /** The refusal's message. It names the rule and carries nothing from the request. */
35
+ export const IDP_MAPPING_REFUSAL_MESSAGE = 'forbidden: only an administrator or the server creates an IdP identity mapping (a Credential of kind "idp"), ' +
36
+ "changes its kind or identity fields, or reactivates it; a principal may relabel, revoke or delete its own";
37
+ /**
38
+ * The fields of an idp row, besides `kind` and `status`, that the two
39
+ * resolvers use to decide which principal a subject resolves to: the subject
40
+ * they match on (and, for XAA, the provider), and the principal the row names.
41
+ */
42
+ export const IDP_MAPPING_IDENTITY_FIELDS = Object.freeze(["principalId", "idpProvider", "idpSubject"]);
43
+ /** The one status a non-admin may set on its own idp row. */
44
+ export const IDP_SELF_SERVICE_STATUS = "revoked";
45
+ /**
46
+ * Does `kind` name an idp row? Also true for a multi-valued kind that includes
47
+ * "idp", since an indexed attribute is matched per value.
48
+ */
49
+ export function namesIdpKind(kind) {
50
+ return kind === IDP_KIND || (Array.isArray(kind) && kind.includes(IDP_KIND));
51
+ }
52
+ /**
53
+ * Is the field exactly as it was? A null and an absent value differ here, so
54
+ * a write that sets an absent field to null, or removes a null one, changes
55
+ * it. (An array kind is compared by reference: an array the write supplies
56
+ * differs from the stored one even when it holds the same items.)
57
+ */
58
+ function sameValue(a, b) {
59
+ return a === b;
60
+ }
61
+ /**
62
+ * Would a write that turns `stored` into `next` create an IdP identity
63
+ * mapping, or change one in a way this rule reserves for administrators and
64
+ * the server? `stored` is the row before the write (null or undefined when
65
+ * the write creates it); `next` is the row as the write would store it. Pure.
66
+ */
67
+ export function isIdpMappingChange(stored, next) {
68
+ // Neither side is a mapping: not this rule's business.
69
+ if (!namesIdpKind(stored?.kind) && !namesIdpKind(next?.kind))
70
+ return false;
71
+ // No stored row: the write creates a mapping.
72
+ if (!stored || !next)
73
+ return true;
74
+ // The kind (to or from "idp") and the identity fields are fixed.
75
+ for (const field of ["kind", ...IDP_MAPPING_IDENTITY_FIELDS]) {
76
+ if (!sameValue(stored[field], next[field]))
77
+ return true;
78
+ }
79
+ // The status may stay as it is or become "revoked".
80
+ return !sameValue(stored.status, next.status) && next.status !== IDP_SELF_SERVICE_STATUS;
81
+ }
@@ -503,6 +503,26 @@ export async function probeInstanceIdentity(endpoint) {
503
503
  const roleNames = await readRoleNames(endpoint);
504
504
  return { rows, roleNames };
505
505
  }
506
+ export async function probeInstanceIds(endpoint) {
507
+ try {
508
+ const rows = await readInstanceRows(endpoint);
509
+ const ids = rows.map((r) => r.id);
510
+ try {
511
+ const parsed = await opsPost(endpoint, { operation: "sql", sql: "SELECT id FROM flair.Agent" }, "Agent read");
512
+ const agents = Array.isArray(parsed) ? parsed : Array.isArray(parsed?.results) ? parsed.results : null;
513
+ if (agents === null || agents.some((row) => typeof row?.id !== "string" || !row.id.trim())) {
514
+ throw new Error("Agent read returned no usable row list");
515
+ }
516
+ return { state: "read", ids, agentIds: agents.map((row) => row.id) };
517
+ }
518
+ catch (err) {
519
+ return { state: "read", ids, agentIds: null, agentReadReason: err instanceof Error ? err.message : String(err) };
520
+ }
521
+ }
522
+ catch (err) {
523
+ return { state: "unreadable", reason: err instanceof Error ? err.message : String(err) };
524
+ }
525
+ }
506
526
  /**
507
527
  * What a prune prints when it is about to delete rows (flair#1883 round 3).
508
528
  *
@@ -0,0 +1,133 @@
1
+ /** The provider whose block the shipped `config.yaml` declares. */
2
+ export const SHIPPED_IDP_PROVIDER = "github";
3
+ /** Suffixes of the three per-provider variables, matching `buildSecretsBundle`
4
+ * (src/lib/mcp-enable.ts) and the shipped `config.yaml`. */
5
+ export const IDP_CLIENT_ID_SUFFIX = "_CLIENT_ID";
6
+ export const IDP_CLIENT_SECRET_SUFFIX = "_CLIENT_SECRET";
7
+ export const IDP_REDIRECT_URI_SUFFIX = "_REDIRECT_URI";
8
+ /** `OAUTH_<PROVIDER>` — the prefix every IdP variable shares. */
9
+ export function idpEnvPrefix(provider = SHIPPED_IDP_PROVIDER) {
10
+ return `OAUTH_${provider.toUpperCase()}`;
11
+ }
12
+ /** The three variable NAMES for a provider. */
13
+ export function idpEnvNames(provider = SHIPPED_IDP_PROVIDER) {
14
+ const prefix = idpEnvPrefix(provider);
15
+ return {
16
+ clientId: `${prefix}${IDP_CLIENT_ID_SUFFIX}`,
17
+ clientSecret: `${prefix}${IDP_CLIENT_SECRET_SUFFIX}`,
18
+ redirectUri: `${prefix}${IDP_REDIRECT_URI_SUFFIX}`,
19
+ };
20
+ }
21
+ const PLACEHOLDER_RE = /^\$\{[^}]*\}$/;
22
+ /** Provider configuration checks treat blanks and whole-token `${VAR}` placeholders as missing. */
23
+ export function isUnresolvedEnvValue(value) {
24
+ if (value == null)
25
+ return true;
26
+ const trimmed = value.trim();
27
+ return trimmed === "" || PLACEHOLDER_RE.test(trimmed);
28
+ }
29
+ /** The strict read of `FLAIR_MCP_OAUTH` flair's own `/mcp` route uses
30
+ * (`resources/mcp-oauth-flag.ts`): 1/true/yes/on, case-insensitive. */
31
+ export function mcpOAuthEnabledIn(env) {
32
+ const raw = (env.FLAIR_MCP_OAUTH ?? "").trim().toLowerCase();
33
+ return raw === "1" || raw === "true" || raw === "yes" || raw === "on";
34
+ }
35
+ export function issuerFromEnv(env) {
36
+ const raw = env.FLAIR_MCP_ISSUER;
37
+ return isUnresolvedEnvValue(raw) ? null : raw.trim();
38
+ }
39
+ /**
40
+ * The locally inferred `FLAIR_MCP_OAUTH` for an instance, decided the way Harper's
41
+ * shipped `loadEnv` settings decide it: the component `.env` beside `config.yaml`
42
+ * (flair#1152 makes the on/off choice live there, not in the packed file),
43
+ * overlaid with the process environment, which wins.
44
+ *
45
+ * `envText` is the `.env` content or null when there is none; `overlay` is the
46
+ * environment to prefer (the operator's `process.env` for `flair doctor`). This
47
+ * decides only report severity. With no readable file, the overlay decides.
48
+ */
49
+ export function mcpOAuthEnabledFromComponentEnv(envText, overlay = {}) {
50
+ const env = { ...parseMcpComponentEnv(envText ?? "") };
51
+ for (const [key, value] of Object.entries(overlay))
52
+ if (value !== undefined)
53
+ env[key] = value;
54
+ return mcpOAuthEnabledIn(env);
55
+ }
56
+ export function validateRedirectIssuer(issuer) {
57
+ if (isUnresolvedEnvValue(issuer))
58
+ return { redirect: null, reason: "missing-issuer" };
59
+ let url;
60
+ try {
61
+ url = new URL(issuer);
62
+ }
63
+ catch {
64
+ return { redirect: null, reason: "invalid-origin" };
65
+ }
66
+ if (url.username || url.password || /^[a-z]+:\/\/[^/?#]*@/i.test(issuer.trim()))
67
+ return { redirect: null, reason: "origin-has-userinfo" };
68
+ if (issuer.includes("\\"))
69
+ return { redirect: null, reason: "origin-has-path" };
70
+ if (url.search)
71
+ return { redirect: null, reason: "origin-has-query" };
72
+ if (url.hash)
73
+ return { redirect: null, reason: "origin-has-fragment" };
74
+ const suffix = /^[a-z]+:\/\/[^/?#]+(.*)$/i.exec(issuer.trim())?.[1];
75
+ if (suffix !== "" && suffix !== "/")
76
+ return { redirect: null, reason: "origin-has-path" };
77
+ const loopback = url.hostname === "localhost" || url.hostname === "[::1]" || /^127\.\d+\.\d+\.\d+$/.test(url.hostname);
78
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) {
79
+ return { redirect: null, reason: "origin-requires-https" };
80
+ }
81
+ return { redirect: `${url.origin}/oauth` };
82
+ }
83
+ export function redirectUriForIssuer(issuer) {
84
+ return validateRedirectIssuer(issuer).redirect;
85
+ }
86
+ export function readMcpProviderReadiness(env, provider = SHIPPED_IDP_PROVIDER) {
87
+ const names = idpEnvNames(provider);
88
+ return {
89
+ credentialsPresent: !isUnresolvedEnvValue(env[names.clientId]) && !isUnresolvedEnvValue(env[names.clientSecret]),
90
+ redirectPresent: !isUnresolvedEnvValue(env[names.redirectUri]),
91
+ };
92
+ }
93
+ export function guardMcpOAuthEnv(env, provider = SHIPPED_IDP_PROVIDER) {
94
+ const names = idpEnvNames(provider);
95
+ if (!isUnresolvedEnvValue(env[names.redirectUri]))
96
+ return { degraded: false, neutralizedVars: [] };
97
+ const credVars = [names.clientId, names.clientSecret];
98
+ const credentialsPresent = credVars.every((k) => !isUnresolvedEnvValue(env[k]));
99
+ if (!credentialsPresent)
100
+ return { degraded: false, neutralizedVars: [] };
101
+ for (const k of credVars)
102
+ delete env[k];
103
+ return {
104
+ degraded: true,
105
+ reason: `${names.redirectUri} is not set, so the ${provider} OAuth provider cannot be configured`,
106
+ neutralizedVars: credVars,
107
+ };
108
+ }
109
+ export function describeMcpRedirectFinding(readiness) {
110
+ if (!readiness)
111
+ return { isIssue: false, message: "MCP OAuth redirect: cannot verify target configuration" };
112
+ if (!readiness.credentialsPresent || readiness.redirectPresent)
113
+ return null;
114
+ const names = idpEnvNames();
115
+ return {
116
+ isIssue: true,
117
+ message: `${names.redirectUri} is missing from the target's github OAuth configuration`,
118
+ fixHint: `set ${names.redirectUri} in the instance environment, or re-run: flair mcp enable; then restart`,
119
+ };
120
+ }
121
+ export function parseMcpComponentEnv(text) {
122
+ const assignments = /^\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?$/gm;
123
+ const values = {};
124
+ for (const match of text.replace(/\r\n?/g, "\n").matchAll(assignments)) {
125
+ let value = (match[2] ?? "").trim();
126
+ const quote = value[0];
127
+ value = value.replace(/^(['"`])([\s\S]*)\1$/gm, "$2");
128
+ if (quote === '"')
129
+ value = value.replace(/\\n/g, "\n").replace(/\\r/g, "\r");
130
+ values[match[1]] = value;
131
+ }
132
+ return values;
133
+ }
@@ -14,6 +14,7 @@ export const DECLARED_MEMORY_ATTRIBUTES = Object.freeze([
14
14
  "visibility",
15
15
  "embedding",
16
16
  "embeddingModel",
17
+ "embeddedContentHash",
17
18
  "tags",
18
19
  "durability",
19
20
  "source",
@@ -45,6 +46,7 @@ export const DECLARED_MEMORY_ATTRIBUTES = Object.freeze([
45
46
  "originatorInstanceId",
46
47
  "metadata",
47
48
  "entities",
49
+ "skillSubjectId",
48
50
  ]);
49
51
  /** Pre-existing UNDECLARED attributes the codebase deliberately stores on a
50
52
  * Memory row and must keep (the guard's job is the POINTER, not these).
@@ -0,0 +1,46 @@
1
+ /**
2
+ * memory-id-policy.ts — the Memory record-id rule for the `.content` selector
3
+ * (flair#2199). PURE: string/decoding logic only. Deliberately imports nothing
4
+ * (resources importing this compiled helper require it to be load-free).
5
+ */
6
+ export const MEMORY_CONTENT_SELECTOR_SUFFIX = ".content";
7
+ /**
8
+ * True when `id` is a Memory record id ending in the `.content` property
9
+ * suffix. Only a string can carry the suffix; a non-string id (Harper allows
10
+ * numeric ids) returns false.
11
+ */
12
+ export function endsWithContentSelectorSuffix(id) {
13
+ return typeof id === "string" && id.endsWith(MEMORY_CONTENT_SELECTOR_SUFFIX);
14
+ }
15
+ /**
16
+ * True when an id segment (the raw, still-percent-encoded last path segment of
17
+ * a Memory request) contains an encoded `/`, in any case (`%2F` / `%2f`).
18
+ */
19
+ export function idSegmentHasEncodedSlash(segment) {
20
+ // Match an encoded slash in the segment as sent, and in its DECODED form — so
21
+ // a `%2f`/`%2F` in any case, and a slash encoded one level deeper
22
+ // (`%252F`, whose decoded form still carries `%2f`), both count. Deciding on
23
+ // the decoded segment is the same decode-then-scan the property-suffix rule
24
+ // uses, so the two agree on how a segment is read.
25
+ return /%2f/i.test(segment) || /%2f/i.test(decodeMemoryIdSegment(segment));
26
+ }
27
+ /**
28
+ * Decode one path segment the way Harper decodes a request path before its
29
+ * property parse (`RequestTarget` decodes the path). Returns the raw segment
30
+ * when it is not valid percent-encoding, so a caller here never throws on it.
31
+ * Such a Memory request whose last segment ends in `.content` is refused by
32
+ * the auth middleware with the named 400 (`memory_id_content_suffix`) before
33
+ * any auth branch; another malformed segment is left to Harper's own path
34
+ * handling.
35
+ *
36
+ * Shared so the resource-layer guard and the auth middleware decode a URL-bound
37
+ * id the SAME way (flair#2199 follow-up).
38
+ */
39
+ export function decodeMemoryIdSegment(raw) {
40
+ try {
41
+ return decodeURIComponent(raw);
42
+ }
43
+ catch {
44
+ return raw;
45
+ }
46
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * principal-status.ts — the ONE "is this principal deactivated?" predicate
3
+ * (flair#2378).
4
+ *
5
+ * `Agent.status` is a principal's lifecycle state. The auth path decides it
6
+ * here: a principal is deactivated when `status` is present and is not exactly
7
+ * "active". An ABSENT (undefined) `status` means active.
8
+ *
9
+ * The human-readable `flair principal show` and `principal list` outputs call
10
+ * this function and read the principal as stored — `show` over REST, `list` from an
11
+ * unprojected row — so an absent `status` (active) stays distinct from an
12
+ * explicit `null`, which the gate treats as deactivated.
13
+ *
14
+ * Deliberately dependency-free (no `harper`, no resource) so both the CLI
15
+ * (`src/`) and the server (`resources/`) import it: `src/` must not import
16
+ * `resources/`, because those imports do not survive npm packaging.
17
+ */
18
+ /**
19
+ * True iff this principal is deactivated: its `status` is present and is not
20
+ * exactly the string "active". A null/undefined principal, or one whose
21
+ * `status` is undefined, is not deactivated.
22
+ */
23
+ export function isPrincipalDeactivated(agent) {
24
+ if (agent == null)
25
+ return false;
26
+ if (agent.status === undefined)
27
+ return false;
28
+ return agent.status !== "active";
29
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * proto-safe-record.ts — shared helper for these converted sites, copying own
3
+ * keys into a null-prototype record, entry by entry (flair#2235).
4
+ *
5
+ * Why this exists. A copy built with `Object.assign(target, source)` or an
6
+ * explicit `target[key] = value` loop goes through [[Set]]. For the key
7
+ * `__proto__` on a plain object that runs the inherited `Object.prototype`
8
+ * accessor instead of creating a key, so an own `__proto__` key is either
9
+ * turned into the copy's prototype (object value) or dropped (primitive
10
+ * value). A comparison or checkpoint that reads the copy then silently
11
+ * ignores a value the source carried (flair#2225, #2233).
12
+ *
13
+ * The copy here is built on `Object.create(null)` and each entry is defined as
14
+ * an OWN property with `Object.defineProperty`, so every own enumerable string
15
+ * key it copies survives, `__proto__` included, and the copy can never inherit
16
+ * a prototype it did not ask for.
17
+ */
18
+ /**
19
+ * Build a null-prototype record from `source`, own key by own key. Each key is
20
+ * defined as an own enumerable property, so `__proto__` is a data key and never
21
+ * the record's prototype. With `validate`, the first refused value throws a
22
+ * `TypeError` naming the key, with no record returned.
23
+ */
24
+ export function protoSafeRecord(source, options = {}) {
25
+ const src = source;
26
+ const keys = options.keys ?? Object.keys(src);
27
+ const out = Object.create(null);
28
+ for (const key of keys) {
29
+ const raw = src[key];
30
+ const refused = options.validate?.(raw, key);
31
+ if (refused !== undefined) {
32
+ throw new TypeError(`protoSafeRecord: refused value for "${key}": ${refused}`);
33
+ }
34
+ Object.defineProperty(out, key, {
35
+ value: options.map ? options.map(raw, key) : raw,
36
+ enumerable: true,
37
+ writable: true,
38
+ configurable: true,
39
+ });
40
+ }
41
+ return out;
42
+ }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * reembed-server-support.ts — the server-support check `flair reembed` runs
3
+ * before its first write (flair#2337).
4
+ *
5
+ * flair#2298 made the CLI re-embed a row by sending `PATCH /Memory/<id>` with
6
+ * `{"embedding": null, "embeddingModel": null}`; the server recognises that
7
+ * body and re-embeds the stored row. A server built before #2298 does not. A
8
+ * CLI newer than its server is a supported state (`flair upgrade
9
+ * --no-restart`, a bare npm install, an unrestarted service), so the CLI reads
10
+ * the server's advertised capabilities from `GET /Health` before any write and
11
+ * refuses when the token is absent or the response cannot be parsed.
12
+ *
13
+ * The parser and message builders are pure; the fetch adapter lives in
14
+ * src/commands/reembed.ts.
15
+ */
16
+ /**
17
+ * This build advertises this /Health capability for the re-embed PATCH.
18
+ * The shared constant aligns this build's CLI and server literals.
19
+ * A missing token is intentionally refused even if an intermediate server
20
+ * supports the PATCH.
21
+ */
22
+ export const MEMORY_REEMBED_PATCH_CAPABILITY = "memory-reembed-patch";
23
+ /**
24
+ * The capability names a /Health body advertises.
25
+ *
26
+ * - an array of strings — the advertised capabilities (empty when the field
27
+ * is absent: an older server, or a build from before #2337 added it);
28
+ * - `null` — the field is present but not a string array. The client cannot
29
+ * interpret this shape, so the caller must treat the read as unverified
30
+ * rather than as "no capabilities".
31
+ */
32
+ export function parseHealthCapabilities(body) {
33
+ if (typeof body !== "object" || body === null || Array.isArray(body))
34
+ return null;
35
+ const caps = body.capabilities;
36
+ if (caps === undefined)
37
+ return [];
38
+ if (!Array.isArray(caps) || caps.some((c) => typeof c !== "string"))
39
+ return null;
40
+ return caps;
41
+ }
42
+ /** The server version a /Health body reports, or null when it carries none. */
43
+ export function healthVersion(body) {
44
+ if (typeof body !== "object" || body === null)
45
+ return null;
46
+ const v = body.version;
47
+ return typeof v === "string" && v.length > 0 ? v : null;
48
+ }
49
+ /** The remedy both refusal messages end with. */
50
+ export const REEMBED_SUPPORT_REMEDY = "Restart or upgrade the server, then re-run `flair reembed`.";
51
+ /** The refusal for a server that answered but does not advertise the capability. */
52
+ export function reembedUnsupportedMessage(version) {
53
+ return [
54
+ "❌ flair reembed stopped before its first write: the server does not advertise the re-embed PATCH.",
55
+ ` Found: server version ${version ?? "unknown"}, with no "${MEMORY_REEMBED_PATCH_CAPABILITY}" capability.`,
56
+ ` ${REEMBED_SUPPORT_REMEDY}`,
57
+ ].join("\n");
58
+ }
59
+ /** The refusal for a failed or unparseable /Health read. */
60
+ export function reembedUnverifiedMessage(detail) {
61
+ return [
62
+ "❌ flair reembed stopped before its first write: could not confirm the server supports the re-embed PATCH.",
63
+ ` Found: ${detail}.`,
64
+ ` ${REEMBED_SUPPORT_REMEDY}`,
65
+ ].join("\n");
66
+ }
@@ -214,9 +214,11 @@ export function resolveNodeBin(explicit) {
214
214
  if (!process.versions.bun && process.execPath && isAbsolute(process.execPath)) {
215
215
  return process.execPath;
216
216
  }
217
- const r = spawnReport(["/bin/sh", "-c", "command -v node"], STATUS_CHECK_TIMEOUT_MS);
218
- const found = r.stdout.trim().split("\n")[0]?.trim() ?? "";
219
- if (r.code === 0 && found && isAbsolute(found) && existsSync(found))
217
+ const r = spawnSync("/bin/sh", ["-s"], {
218
+ input: "command -v node\n", encoding: "utf8", timeout: STATUS_CHECK_TIMEOUT_MS,
219
+ });
220
+ const found = r.stdout?.trim().split("\n")[0]?.trim() ?? "";
221
+ if (r.status === 0 && found && isAbsolute(found) && existsSync(found))
220
222
  return found;
221
223
  throw new Error("unable to resolve an absolute path to a node binary (not running under node, and `command -v node` " +
222
224
  "found nothing). The scheduler shim runs `<node> <flair-script>` with the node path baked in at " +
@@ -280,9 +282,11 @@ export function formatFlairBinWarning(baked, publicBin, enableCommand) {
280
282
  return lines;
281
283
  }
282
284
  function lookupPublicFlairBin() {
283
- const r = spawnReport(["/bin/sh", "-c", "command -v flair"], STATUS_CHECK_TIMEOUT_MS);
284
- const found = r.stdout.trim().split("\n")[0]?.trim() ?? "";
285
- if (r.code === 0 && found && isAbsolute(found) && existsSync(found))
285
+ const r = spawnSync("/bin/sh", ["-s"], {
286
+ input: "command -v flair\n", encoding: "utf8", timeout: STATUS_CHECK_TIMEOUT_MS,
287
+ });
288
+ const found = r.stdout?.trim().split("\n")[0]?.trim() ?? "";
289
+ if (r.status === 0 && found && isAbsolute(found) && existsSync(found))
286
290
  return found;
287
291
  return null;
288
292
  }
@@ -0,0 +1,38 @@
1
+ export function systemdAgentId(unit) {
2
+ let agent = null;
3
+ let section = null;
4
+ for (const raw of unit.split(/\r?\n/)) {
5
+ const line = raw.trim();
6
+ if (!line || /^[#;]/.test(line))
7
+ continue;
8
+ if (line.startsWith("[")) {
9
+ section = line.slice(1, -1);
10
+ continue;
11
+ }
12
+ if (section !== "Service")
13
+ continue;
14
+ if (line.endsWith("\\"))
15
+ return null;
16
+ const assignment = line.match(/^Environment\s*=\s*(.*)$/);
17
+ if (!assignment)
18
+ continue;
19
+ const value = assignment[1];
20
+ if (!value) {
21
+ agent = null;
22
+ continue;
23
+ }
24
+ const words = value.match(/"[^"\\]*"|'[^'\\]*'|[^\s"'\\]+/g);
25
+ if (!words || words.join(" ") !== value.replace(/\s+/g, " "))
26
+ return null;
27
+ for (const word of words) {
28
+ const token = /^["']/.test(word) ? word.slice(1, -1) : word;
29
+ if (!/^[A-Za-z_][A-Za-z0-9_]*=/.test(token))
30
+ return null;
31
+ if (token.startsWith("FLAIR_AGENT_ID=")) {
32
+ const id = token.slice("FLAIR_AGENT_ID=".length);
33
+ agent = /^[A-Za-z0-9._-]+$/.test(id) ? id : null;
34
+ }
35
+ }
36
+ }
37
+ return agent;
38
+ }