@tpsdev-ai/flair 0.56.0 → 0.58.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 (153) hide show
  1. package/README.md +19 -20
  2. package/SECURITY.md +4 -1
  3. package/dist/build-info.json +3 -3
  4. package/dist/cli.js +1800 -293
  5. package/dist/commands/agent.js +22 -15
  6. package/dist/commands/bridge.js +40 -3
  7. package/dist/commands/doctor.js +214 -4
  8. package/dist/commands/federation.js +265 -38
  9. package/dist/commands/hook.js +10 -2
  10. package/dist/commands/init.js +179 -48
  11. package/dist/commands/memory.js +24 -2
  12. package/dist/commands/quality.js +26 -18
  13. package/dist/commands/service.js +137 -22
  14. package/dist/commands/status.js +114 -3
  15. package/dist/commands/upgrade.js +204 -84
  16. package/dist/doctor-client.js +50 -4
  17. package/dist/federation/scheduler.js +253 -4
  18. package/dist/install/clients.js +89 -23
  19. package/dist/install/global-bin-path.js +26 -6
  20. package/dist/lib/atomic-write.js +256 -0
  21. package/dist/lib/auth-resolve.js +46 -0
  22. package/dist/lib/daemon-liveness.js +61 -0
  23. package/dist/lib/doctor-run.js +5 -0
  24. package/dist/lib/embed-gpu-doctor.js +49 -26
  25. package/dist/lib/federation-memory-attributes.js +15 -0
  26. package/dist/lib/init-admin-pass.js +4 -2
  27. package/dist/lib/init-listener-environ.js +38 -0
  28. package/dist/lib/init-occupied-listener.js +165 -0
  29. package/dist/lib/instance-identity-row.js +580 -0
  30. package/dist/lib/launchd-domain-preflight.js +448 -0
  31. package/dist/lib/launchd-management.js +176 -6
  32. package/dist/lib/launchd-repair.js +95 -0
  33. package/dist/lib/memory-attributes.js +77 -0
  34. package/dist/lib/node-alias-path.js +95 -0
  35. package/dist/lib/npm-registry.js +119 -6
  36. package/dist/lib/owned-pins.js +20 -6
  37. package/dist/lib/redact-token-id.js +197 -0
  38. package/dist/lib/service-repoint-apply.js +267 -0
  39. package/dist/lib/service-repoint.js +575 -0
  40. package/dist/lib/toml-string-array.js +104 -0
  41. package/dist/lib/tree-divergence.js +716 -0
  42. package/dist/lib/upgrade-plain-tree.js +18 -8
  43. package/dist/lib/upgrade-prior-liveness.js +69 -0
  44. package/dist/lib/upgrade-rollback.js +116 -0
  45. package/dist/rem/runner.js +11 -0
  46. package/dist/resources/Agent.js +27 -14
  47. package/dist/resources/AgentSeed.js +39 -2
  48. package/dist/resources/Asset.js +3 -11
  49. package/dist/resources/Credential.js +4 -10
  50. package/dist/resources/Federation.js +299 -127
  51. package/dist/resources/Integration.js +8 -32
  52. package/dist/resources/Memory.js +623 -86
  53. package/dist/resources/MemoryArchive.js +9 -0
  54. package/dist/resources/MemoryBootstrap.js +23 -12
  55. package/dist/resources/MemoryCandidate.js +3 -11
  56. package/dist/resources/MemoryDedupStats.js +1 -1
  57. package/dist/resources/MemoryFeed.js +214 -5
  58. package/dist/resources/MemoryGrant.js +19 -40
  59. package/dist/resources/MemoryHostSource.js +90 -0
  60. package/dist/resources/MemoryMaintenance.js +121 -32
  61. package/dist/resources/MemoryReflect.js +4 -1
  62. package/dist/resources/MemoryReindex.js +7 -4
  63. package/dist/resources/MemoryUsage.js +55 -18
  64. package/dist/resources/Presence.js +18 -10
  65. package/dist/resources/RecordUsage.js +30 -40
  66. package/dist/resources/Relationship.js +170 -89
  67. package/dist/resources/SemanticSearch.js +44 -19
  68. package/dist/resources/Soul.js +31 -19
  69. package/dist/resources/XAA.js +7 -3
  70. package/dist/resources/agent-auth.js +16 -10
  71. package/dist/resources/auth-middleware.js +164 -50
  72. package/dist/resources/auto-promote-lib.js +4 -4
  73. package/dist/resources/bm25-index-service.js +246 -32
  74. package/dist/resources/bm25-status.js +132 -0
  75. package/dist/resources/bm25.js +13 -14
  76. package/dist/resources/ed25519-auth.js +11 -54
  77. package/dist/resources/embed-gpu.js +262 -47
  78. package/dist/resources/embeddings-boot.js +52 -17
  79. package/dist/resources/federation-classify.js +12 -0
  80. package/dist/resources/federation-cleanup.js +289 -51
  81. package/dist/resources/federation-crypto.js +65 -19
  82. package/dist/resources/health.js +105 -22
  83. package/dist/resources/host-pointer/registry.js +35 -0
  84. package/dist/resources/host-pointer-adapter.js +15 -0
  85. package/dist/resources/host-source-visibility.js +167 -0
  86. package/dist/resources/host-source.js +151 -0
  87. package/dist/resources/in-process-api.js +2 -1
  88. package/dist/resources/instance-create-lock.js +363 -0
  89. package/dist/resources/instance-identity-rows.js +43 -0
  90. package/dist/resources/instance-identity.js +97 -12
  91. package/dist/resources/mcp-handler.js +155 -51
  92. package/dist/resources/mcp-tool-arguments.js +83 -0
  93. package/dist/resources/mcp-tools.js +28 -25
  94. package/dist/resources/memory-consolidate-lib.js +3 -1
  95. package/dist/resources/memory-declared-attributes.js +103 -0
  96. package/dist/resources/memory-feed-lib.js +5 -1
  97. package/dist/resources/memory-host-source.js +163 -0
  98. package/dist/resources/memory-visibility.js +10 -7
  99. package/dist/resources/migrations/synthetic-test-migration.js +4 -1
  100. package/dist/resources/migrations/visibility-backfill.js +4 -1
  101. package/dist/resources/originator-instance.js +235 -0
  102. package/dist/resources/promotion-stamp.js +2 -0
  103. package/dist/resources/provenance.js +111 -11
  104. package/dist/resources/rate-limit.js +6 -4
  105. package/dist/resources/record-owner-guard.js +19 -0
  106. package/dist/resources/record-type-kit.js +44 -23
  107. package/dist/resources/record-types.js +6 -6
  108. package/dist/resources/relay-ops.js +28 -3
  109. package/dist/resources/replay-store.js +289 -0
  110. package/dist/resources/request-transaction.js +78 -0
  111. package/dist/resources/search-readiness.js +26 -22
  112. package/dist/resources/semantic-retrieval-core.js +103 -4
  113. package/dist/resources/table-helpers.js +33 -0
  114. package/dist/resources/table-patch-policy.js +109 -0
  115. package/dist/resources/table-patches.js +17 -0
  116. package/dist/resources/table-post-policy.js +138 -0
  117. package/dist/resources/table-posts.js +22 -0
  118. package/dist/resources/table-subscription-policy.js +135 -0
  119. package/dist/resources/table-subscriptions.js +19 -0
  120. package/dist/resources/tool-descriptors/index.js +15 -15
  121. package/dist/resources/trust-block.js +10 -3
  122. package/dist/resources/usage-recording.js +169 -41
  123. package/dist/src/lib/instance-identity-row.js +580 -0
  124. package/dist/src/lib/memory-attributes.js +77 -0
  125. package/dist/src/lib/redact-token-id.js +197 -0
  126. package/docs/api-reference.md +80 -16
  127. package/docs/auth.md +5 -5
  128. package/docs/claude-code.md +137 -6
  129. package/docs/deploying-on-fabric.md +6 -3
  130. package/docs/deployment.md +1 -1
  131. package/docs/embedding-in-a-harper-app.md +3 -3
  132. package/docs/federation.md +17 -10
  133. package/docs/hosted-on-fabric.md +4 -3
  134. package/docs/integrations.md +28 -19
  135. package/docs/mcp-clients.md +26 -32
  136. package/docs/n8n.md +8 -8
  137. package/docs/notes/mcp-oauth-model2.md +27 -18
  138. package/docs/openclaw.md +29 -28
  139. package/docs/quickstart.md +5 -0
  140. package/docs/releasing.md +134 -2
  141. package/docs/spoke-bringup.md +14 -11
  142. package/docs/standalone-local.md +2 -2
  143. package/docs/supply-chain-policy.md +28 -10
  144. package/docs/system-requirements.md +1 -1
  145. package/docs/troubleshooting.md +11 -0
  146. package/docs/upgrade.md +189 -63
  147. package/package.json +9 -5
  148. package/schemas/agent.graphql +9 -6
  149. package/schemas/federation.graphql +2 -11
  150. package/schemas/memory.graphql +106 -17
  151. package/schemas/replay.graphql +18 -0
  152. package/templates/launchd/start-flair-with-admin-pass.sh +22 -0
  153. package/dist/resources/federation-nonce-store.js +0 -195
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * mcp-handler.ts — the Model-2 custom MCP protocol handler.
3
3
  *
4
- * A minimal in-process MCP (JSON-RPC 2.0) handler serving the 12 curated flair
5
- * tools over Streamable HTTP. It is wrapped by `@harperfast/oauth`'s
4
+ * A minimal in-process MCP (JSON-RPC 2.0) handler serving the curated flair
5
+ * tools (resources/mcp-tools.ts's TOOLS) over Streamable HTTP. It is wrapped by `@harperfast/oauth`'s
6
6
  * `withMCPAuth` (see mcp-oauth.ts), which fails closed on any missing/invalid
7
7
  * Bearer token BEFORE this handler runs and, on success, sets
8
8
  * `request.mcp = { sub, client_id, aud, scope }` (verified RS256 JWT claims).
@@ -26,7 +26,10 @@
26
26
  import { databases } from "harper";
27
27
  import { randomBytes } from "node:crypto";
28
28
  import { TOOLS, listToolDefs } from "./mcp-tools.js";
29
+ import { checkToolArguments, withoutNullArguments } from "./mcp-tool-arguments.js";
29
30
  import { agentRecordIsAdmin } from "./agent-admin.js";
31
+ import { isPrincipalDeactivated } from "./agent-auth.js";
32
+ import { stampOriginatorOnCreate } from "./originator-instance.js";
30
33
  import { resolveVersion } from "./version.js";
31
34
  // The MCP protocol revision we implement (initialize handshake).
32
35
  const PROTOCOL_VERSION = "2025-06-18";
@@ -158,15 +161,35 @@ function jitProvisionEnabled() {
158
161
  * `undefined` — so existing callers/tests that don't pass one see the exact
159
162
  * same `{ agentId, isAdmin }` shape as before this field existed.
160
163
  *
164
+ * When a Credential maps the sub, the mapped principal must exist and be
165
+ * active — the rule the Ed25519 path applies (resources/agent-auth.ts,
166
+ * `isPrincipalDeactivated`) — and its record is read on every resolution, so a
167
+ * token minted while the principal was active stops resolving once the
168
+ * principal is deactivated. If that read fails, or the credential lookup itself
169
+ * fails, resolution is refused. An unreadable answer is never taken as
170
+ * "allowed", and never as "no mapping": JIT provisioning runs only for a
171
+ * subject the credential lookup answered for. Resolution writes nothing to an
172
+ * existing credential; the handler updates its `lastUsedAt`, best effort, after
173
+ * a tool has run (handleToolCall).
174
+ *
161
175
  * Returns:
162
- * - `{ agentId, isAdmin, clientId? }` when a Credential maps the sub to an Agent.
176
+ * - `{ agentId, isAdmin, clientId? }` when a Credential maps the sub to an
177
+ * existing, active Agent.
163
178
  * - null when no Credential maps the sub AND JIT-provisioning is disabled or
164
179
  * failed → the handler denies the tool call (sub is unresolvable).
180
+ *
181
+ * Throws `PrincipalRefusedError` (the handler returns its JSON-RPC error) when
182
+ * the mapped principal is deactivated or missing, or when the credential or
183
+ * principal could not be read.
165
184
  */
166
185
  export async function resolveAgentFromSub(sub, clientId) {
186
+ return (await resolveMapping(sub, clientId))?.agent ?? null;
187
+ }
188
+ async function resolveMapping(sub, clientId) {
167
189
  if (!sub)
168
190
  return null;
169
191
  // 1. Existing IdP credential → its principalId is the Agent id.
192
+ let mapped = null;
170
193
  try {
171
194
  for await (const cred of databases.flair.Credential.search({
172
195
  conditions: [
@@ -175,29 +198,33 @@ export async function resolveAgentFromSub(sub, clientId) {
175
198
  ],
176
199
  })) {
177
200
  if (cred?.principalId && cred.status !== "revoked") {
178
- // Touch lastUsedAt (best-effort; a failure here must not deny a valid call).
179
- try {
180
- await databases.flair.Credential.put({ ...cred, lastUsedAt: new Date().toISOString() });
181
- }
182
- catch { /* non-fatal */ }
183
- const resolved = { agentId: String(cred.principalId), isAdmin: await isAgentAdmin(cred.principalId) };
184
- if (clientId)
185
- resolved.clientId = clientId;
186
- return resolved;
201
+ mapped = cred;
202
+ break;
187
203
  }
188
204
  }
189
205
  }
190
- catch { /* Credential table empty / search error → fall through to JIT/deny */ }
206
+ catch {
207
+ throw new PrincipalRefusedError(-32000, "unavailable: the credential for this token's subject could not be read, so the call was refused. " +
208
+ "Retry; if this persists, an operator should check the flair server log.");
209
+ }
210
+ if (mapped) {
211
+ const principalId = String(mapped.principalId);
212
+ const principal = await requireActivePrincipal(principalId);
213
+ const resolved = { agentId: principalId, isAdmin: agentRecordIsAdmin(principal) };
214
+ if (clientId)
215
+ resolved.clientId = clientId;
216
+ return { agent: resolved, credential: mapped };
217
+ }
191
218
  // 2. No mapping. JIT-provision only behind the explicit trust anchor.
192
219
  if (!jitProvisionEnabled())
193
220
  return null;
194
221
  try {
195
- const principalId = await jitProvisionPrincipal(sub);
222
+ const { principalId, credential } = await jitProvisionPrincipal(sub);
196
223
  // A JIT-provisioned principal is a fresh, non-admin agent by construction.
197
224
  const resolved = { agentId: principalId, isAdmin: false };
198
225
  if (clientId)
199
226
  resolved.clientId = clientId;
200
- return resolved;
227
+ return { agent: resolved, credential };
201
228
  }
202
229
  catch {
203
230
  return null;
@@ -208,11 +235,15 @@ export async function resolveAgentFromSub(sub, clientId) {
208
235
  * token subject. Mirrors XAA.resolveOrCreatePrincipal's provisioning shape (the
209
236
  * `Credential.kind:"idp"` + `idpSubject` surface) but keyed on the MCP token sub.
210
237
  * The created agent is non-admin, `kind:"agent"`, unverified trust tier.
238
+ * Returns the principal id and the new credential, which is created without
239
+ * `lastUsedAt`.
211
240
  */
212
241
  async function jitProvisionPrincipal(sub) {
213
242
  const now = new Date().toISOString();
214
243
  const principalId = `agt_mcp_${sub.replace(/[^a-zA-Z0-9]/g, "_").slice(0, 24)}_${randomBytes(4).toString("hex")}`;
215
- await databases.flair.Agent.put({
244
+ // flair#1965 r2: this is a raw Agent create (it bypasses the Agent resource's
245
+ // post()), so stamp the local instance id here — every create path carries it.
246
+ const principalRow = {
216
247
  id: principalId,
217
248
  name: principalId,
218
249
  displayName: principalId,
@@ -226,8 +257,10 @@ async function jitProvisionPrincipal(sub) {
226
257
  admin: false,
227
258
  createdAt: now,
228
259
  updatedAt: now,
229
- });
230
- await databases.flair.Credential.put({
260
+ };
261
+ await stampOriginatorOnCreate(principalRow);
262
+ await databases.flair.Agent.put(principalRow);
263
+ const credential = {
231
264
  id: `cred_mcp_${randomBytes(8).toString("hex")}`,
232
265
  principalId,
233
266
  kind: "idp",
@@ -236,32 +269,57 @@ async function jitProvisionPrincipal(sub) {
236
269
  idpProvider: "mcp-oauth",
237
270
  idpSubject: sub,
238
271
  createdAt: now,
239
- lastUsedAt: now,
240
- });
241
- return principalId;
272
+ };
273
+ await databases.flair.Credential.put(credential);
274
+ return { principalId, credential };
275
+ }
276
+ /**
277
+ * A token subject whose principal may not call tools. `rpcCode` and the message
278
+ * are the JSON-RPC error the handler returns. The message names the principal
279
+ * when there is one, and says what an operator has to do, or that the caller
280
+ * should retry after a failed read.
281
+ */
282
+ export class PrincipalRefusedError extends Error {
283
+ rpcCode;
284
+ constructor(rpcCode, message) {
285
+ super(message);
286
+ this.name = "PrincipalRefusedError";
287
+ this.rpcCode = rpcCode;
288
+ }
242
289
  }
243
290
  /**
244
- * Is this Principal a flair admin? A MCP-OAuth agent is NON-admin unless an
245
- * operator has explicitly marked its Agent record admin — the MCP surface never
246
- * elevates on its own.
291
+ * Read the mapped principal for this call and require it to exist and be
292
+ * active (`isPrincipalDeactivated`, the predicate the Ed25519 path uses: a
293
+ * record with no `status` field counts as active).
294
+ * Returns the principal record; throws `PrincipalRefusedError` otherwise,
295
+ * including when the record cannot be read.
247
296
  *
248
- * flair#941: this used to OR the two admin fields together while the primary
249
- * HTTP gate (resources/agent-auth.ts's isAdmin) read only `role`, so the same
250
- * record could be an administrator here and an ordinary agent there. It now
251
- * resolves through the one shared predicate, so both surfaces answer
252
- * identically. A record carrying `admin: true` alone — which no flair write
253
- * path produces, and which was never an admin on the HTTP gate — is no longer
254
- * an admin here either; see resources/agent-admin.ts for the remedy. This
255
- * surface is gated behind FLAIR_MCP_OAUTH and is default-OFF.
297
+ * Admin status is read from the same record, through the one shared predicate
298
+ * (resources/agent-admin.ts, flair#941): a MCP-OAuth agent is NON-admin unless
299
+ * an operator has set its Agent record's `role` to "admin" — the MCP surface
300
+ * never elevates on its own. This surface is gated behind FLAIR_MCP_OAUTH and is
301
+ * default-OFF.
256
302
  */
257
- async function isAgentAdmin(principalId) {
303
+ async function requireActivePrincipal(principalId) {
304
+ let principal;
258
305
  try {
259
- const agent = await databases.flair.Agent.get(principalId);
260
- return agentRecordIsAdmin(agent);
306
+ principal = await databases.flair.Agent.get(principalId);
261
307
  }
262
308
  catch {
263
- return false;
309
+ throw new PrincipalRefusedError(-32000, `unavailable: the status of principal '${principalId}' could not be read, so the call was refused. ` +
310
+ "Retry; if this persists, an operator should check the flair server log.");
311
+ }
312
+ if (principal == null) {
313
+ throw new PrincipalRefusedError(-32001, `forbidden: this token's subject maps to principal '${principalId}', which does not exist. ` +
314
+ "An operator must map the subject to an existing principal: a full `flair mcp enable` run against " +
315
+ "this instance, with --principal <agent-id> and --idp-subject <subject>, writes that mapping in its " +
316
+ "identity-mapping step.");
317
+ }
318
+ if (isPrincipalDeactivated(principal)) {
319
+ throw new PrincipalRefusedError(-32001, `forbidden: principal '${principalId}' is deactivated, so this token can no longer call tools. ` +
320
+ "An operator must reactivate the principal (set its status to \"active\") to restore access.");
264
321
  }
322
+ return principal;
265
323
  }
266
324
  // ─── MCP protocol dispatch ───────────────────────────────────────────────────
267
325
  /**
@@ -342,28 +400,74 @@ async function handleToolCall(request, id, params) {
342
400
  // turn a server-verified, stable id into caller-forgeable data landing in
343
401
  // stored provenance. Absent/non-string client_id → omitted, not invented.
344
402
  const clientId = typeof request?.mcp?.client_id === "string" ? request.mcp.client_id : undefined;
345
- const agent = await resolveAgentFromSub(String(sub), clientId);
346
- if (!agent) {
403
+ // For a call that resolves through an existing credential mapping, the
404
+ // principal's status is read here, on every such call (resolveMapping): a
405
+ // deactivated or missing principal, or one whose status cannot be read, is
406
+ // refused with the actionable error it carries.
407
+ let mapping;
408
+ try {
409
+ mapping = await resolveMapping(String(sub), clientId);
410
+ }
411
+ catch (err) {
412
+ if (err instanceof PrincipalRefusedError)
413
+ return rpcError(id, err.rpcCode, err.message);
414
+ return rpcError(id, -32000, "unavailable: the token subject could not be resolved to a principal, so the call was refused. " +
415
+ "Retry; if this persists, an operator should check the flair server log.");
416
+ }
417
+ if (!mapping) {
347
418
  // Sub verified by the AS but not mapped to a flair Agent (and JIT disabled /
348
419
  // failed). Deny — do NOT fall back to anonymous or admin.
349
420
  return rpcError(id, -32001, "forbidden: token subject is not a provisioned flair agent");
350
421
  }
422
+ const agent = mapping.agent;
423
+ // The tool implementations are written for their declared argument types;
424
+ // a value of another type is refused before the tool runs, and a null
425
+ // optional argument is treated as absent rather than forwarded.
426
+ const argError = checkToolArguments(entry.def.inputSchema, params?.arguments);
427
+ if (argError)
428
+ return rpcError(id, -32602, `invalid arguments for ${toolName}: ${argError}`);
429
+ const toolArgs = withoutNullArguments(args);
430
+ let result;
351
431
  try {
352
- const result = await entry.impl(agent, args);
353
- // MCP tools/call result: content blocks. Surface the handler's JSON payload
354
- // as a text block (structuredContent carries the raw object for programmatic
355
- // clients). A handler-level error object (from unwrap of a Response) is
356
- // reported as an MCP tool error (isError) rather than a JSON-RPC error, so
357
- // the client sees the structured message.
358
- const text = typeof result === "string" ? result : JSON.stringify(result);
359
- const isError = !!(result && typeof result === "object" && "error" in result && "status" in result);
360
- return rpcResult(id, {
361
- content: [{ type: "text", text }],
362
- structuredContent: typeof result === "object" ? result : { value: result },
363
- isError,
364
- });
432
+ result = await entry.impl(agent, toolArgs);
365
433
  }
366
434
  catch (err) {
367
435
  return rpcError(id, -32000, `tool execution failed: ${err?.message ?? String(err)}`);
368
436
  }
437
+ // The tool has run and returned (a tool-level error result included): only
438
+ // now is the mapping credential, a JIT-provisioned one included, marked used.
439
+ // A refused call, rejected arguments, or a tool that throws leave `lastUsedAt`
440
+ // as it was. Best effort: a failed write is ignored and does not change the
441
+ // answer.
442
+ await touchLastUsed(mapping.credential);
443
+ // MCP tools/call result: content blocks. Surface the handler's JSON payload
444
+ // as a text block (structuredContent carries the raw object for programmatic
445
+ // clients). A handler-level error object (from unwrap of a Response) is
446
+ // reported as an MCP tool error (isError) rather than a JSON-RPC error, so
447
+ // the client sees the structured message.
448
+ const text = typeof result === "string" ? result : JSON.stringify(result);
449
+ const isError = !!(result && typeof result === "object" && "error" in result && "status" in result);
450
+ return rpcResult(id, {
451
+ content: [{ type: "text", text }],
452
+ structuredContent: typeof result === "object" ? result : { value: result },
453
+ isError,
454
+ });
455
+ }
456
+ /**
457
+ * Mark the mapping credential used, once a tool has run (best-effort). The
458
+ * update writes `lastUsedAt` alone, as a field-level patch from an internal
459
+ * context (no request, no user), and is skipped when a read just before it
460
+ * finds no stored credential row.
461
+ */
462
+ async function touchLastUsed(credential) {
463
+ const credentialId = credential?.id;
464
+ if (credentialId == null)
465
+ return;
466
+ try {
467
+ const Credential = databases.flair.Credential;
468
+ if ((await Credential.get(credentialId, {})) == null)
469
+ return;
470
+ await Credential.patch(credentialId, { lastUsedAt: new Date().toISOString() }, {});
471
+ }
472
+ catch { /* non-fatal: a failure here does not change the call's answer */ }
369
473
  }
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Runtime check of a native /mcp `tools/call` arguments object against the
3
+ * declared argument types and required properties of the tool's inputSchema,
4
+ * before the tool runs. JSON-RPC arguments are
5
+ * untyped at runtime; the tool implementations are written for the declared
6
+ * types, so a value of another type is refused here instead of reaching them.
7
+ *
8
+ * Checked at the top level of the schema (the native tools declare only
9
+ * top-level primitive, array and object properties):
10
+ * - the arguments are a plain object (or absent, meaning {});
11
+ * - every `required` property is present (not undefined or null);
12
+ * - every present, non-null property matches its declared `type` (string,
13
+ * number, integer, boolean, array, object; a type list allows any of them),
14
+ * and an array's items match `items.type` when it declares one;
15
+ * - when the schema declares an `id` argument, it is a non-empty string (ids
16
+ * address one record).
17
+ * Properties the schema does not declare, and enum values, are left to the
18
+ * tool, as before. withoutNullArguments() then drops null-valued properties so
19
+ * a tool never forwards a null where its schema declares a type.
20
+ */
21
+ function matches(value, type) {
22
+ switch (type) {
23
+ case "string": return typeof value === "string";
24
+ case "number": return typeof value === "number" && Number.isFinite(value);
25
+ case "integer": return typeof value === "number" && Number.isInteger(value);
26
+ case "boolean": return typeof value === "boolean";
27
+ case "array": return Array.isArray(value);
28
+ case "object": return typeof value === "object" && value !== null && !Array.isArray(value);
29
+ case "null": return value === null;
30
+ default: return true; // an undeclared or unknown type constrains nothing
31
+ }
32
+ }
33
+ function matchesAny(value, declared) {
34
+ if (declared === undefined)
35
+ return true;
36
+ const types = (Array.isArray(declared) ? declared : [declared]);
37
+ return types.some((t) => matches(value, t));
38
+ }
39
+ /** Returns a message naming the first non-conforming argument, or null. */
40
+ export function checkToolArguments(schema, args) {
41
+ const value = args === undefined ? {} : args;
42
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
43
+ return "arguments must be a JSON object";
44
+ }
45
+ const obj = value;
46
+ const props = schema?.properties ?? {};
47
+ for (const name of (schema?.required ?? [])) {
48
+ if (obj[name] === undefined || obj[name] === null)
49
+ return `missing required argument "${name}"`;
50
+ }
51
+ for (const [name, prop] of Object.entries(props)) {
52
+ const v = obj[name];
53
+ if (v === undefined || v === null)
54
+ continue;
55
+ if (!matchesAny(v, prop?.type)) {
56
+ const t = Array.isArray(prop.type) ? prop.type.join(" or ") : prop.type;
57
+ return `argument "${name}" must be of type ${t}`;
58
+ }
59
+ if (Array.isArray(v) && prop?.items?.type !== undefined) {
60
+ const bad = v.findIndex((item) => !matchesAny(item, prop.items.type));
61
+ if (bad >= 0)
62
+ return `argument "${name}" item ${bad} must be of type ${prop.items.type}`;
63
+ }
64
+ }
65
+ if ("id" in props && obj.id !== undefined && obj.id !== null
66
+ && (typeof obj.id !== "string" || obj.id.length === 0)) {
67
+ return `argument "id" must be a non-empty string`;
68
+ }
69
+ return null;
70
+ }
71
+ /** The arguments without null- or undefined-valued properties: an optional
72
+ * argument given as null is treated as absent (required ones were already
73
+ * checked to be present). Returns {} for absent arguments. */
74
+ export function withoutNullArguments(args) {
75
+ if (typeof args !== "object" || args === null || Array.isArray(args))
76
+ return {};
77
+ const out = {};
78
+ for (const [k, v] of Object.entries(args)) {
79
+ if (v !== null && v !== undefined)
80
+ out[k] = v;
81
+ }
82
+ return out;
83
+ }
@@ -1,6 +1,5 @@
1
1
  /**
2
- * mcp-tools.ts — the 12 curated flair tools for the Model-2 custom /mcp handler.
3
- *
2
+ * mcp-tools.ts — the 17 curated flair tools for the Model-2 custom /mcp handler.
4
3
  * Curated BY CONSTRUCTION: this module implements a fixed set of tools, each a
5
4
  * thin wrapper over the existing flair Resource handler. No business logic is
6
5
  * re-implemented — the wrapped handlers (Memory / SemanticSearch /
@@ -10,7 +9,7 @@
10
9
  * per-source scoping — see resources/AttentionQuery.ts's module doc), so the
11
10
  * MCP surface inherits the SAME security model as the signed-REST path. There
12
11
  * is no raw CRUD surface — the only way to reach the datastore through /mcp is
13
- * via one of these 14 semantic tools.
12
+ * via one of these 17 semantic tools.
14
13
  *
15
14
  * memory_search · memory_store · memory_update · memory_get · memory_delete ·
16
15
  * memory_basement · memory_restore · skill_store · skill_search · skill_get ·
@@ -363,8 +362,9 @@ function projectSkillCard(r) {
363
362
  * - the HNSW leg over the stored embedding — which for a skill row IS the
364
363
  * `trigger` embedding (#1543), so the task is ranked against "when to use";
365
364
  * - the 'query' inputType SemanticSearch already applies to the task string;
366
- * - resolveReadScope (own any-visibility + every non-private row) — NEVER
367
- * another agent's private skill.
365
+ * - Non-admin searches use resolveReadScope: own records at any visibility
366
+ * plus other agents' non-private records. Administrator searches can
367
+ * include private skills.
368
368
  * Identity is the RESOLVED agent; no body agentId is forwarded, so a caller can
369
369
  * never widen scope past its own read-scope (the SemanticSearch cross-agent
370
370
  * guard would 403 a mismatch anyway).
@@ -399,9 +399,9 @@ async function skillSearch(agent, args) {
399
399
  * skill_get — the full skill by id (flair#1546 component 2).
400
400
  *
401
401
  * A thin wrapper over Memory.get() — the SAME by-id read as memory_get, under
402
- * the SAME read-scope gate (makeByIdReadGate → resolveReadScope): a non-owner
403
- * cannot read another agent's PRIVATE skill (it 404s), exactly as a private
404
- * memory does. skill_get is the disclosure step after skill_search's catalog:
402
+ * the SAME read-scope gate (makeByIdReadGate → resolveReadScope): a non-admin
403
+ * caller cannot read another agent's private skill; administrators retain
404
+ * access, exactly as a private memory does. skill_get is the disclosure step after skill_search's catalog:
405
405
  * it returns the full procedure (`content`) + trigger + metadata.
406
406
  *
407
407
  * It is a SKILL tool, not a general reader: a readable id that is NOT a skill
@@ -542,10 +542,10 @@ async function memoryUpdate(agent, args) {
542
542
  // retrievable via memory_get and memory_search(includeArchived:true)). Restore
543
543
  // is the deliberate, GLOBAL inverse — it un-retires the memory for EVERY
544
544
  // session, not a session-local view (that is drawers, Deliverable B, which does
545
- // not exist yet). Both are writes scoped to the caller's own lane: the read
546
- // uses Memory.get()'s read-scope gate and the write uses Memory.put()'s
547
- // ownership gate (stampAttribution), so a caller can neither read nor write
548
- // another agent's memory here.
545
+ // not exist yet). Non-admin agent reads use Memory.get()'s owner-and-
546
+ // visibility scope; administrator and trusted internal reads are unfiltered.
547
+ // Mutating another agent's record requires administrator or trusted internal
548
+ // authority (Memory.put()'s stampAttribution gate).
549
549
  async function memoryBasement(agent, args) {
550
550
  const Cls = await handler("Memory");
551
551
  const id = args?.id;
@@ -597,7 +597,9 @@ async function memoryGet(agent, args) {
597
597
  // path the Ed25519 REST route takes: it loads the row, hands the override a
598
598
  // `RequestTarget` (never a bare string), and still dispatches through
599
599
  // Memory.get() → makeByIdReadGate → resolveReadScope, so the scope model is
600
- // unchanged (own + org-non-private only). See resources/in-process.ts:223.
600
+ // unchanged: non-admin agents can read their own and other agents'
601
+ // non-private records; administrator reads are unfiltered. See
602
+ // resources/in-process.ts:223.
601
603
  //
602
604
  // flair#744 slice 1 — opt-in inline trust block. The instance call passed
603
605
  // `includeTrust` as a 2nd positional opts arg to get(); the static form has
@@ -885,7 +887,7 @@ export const TOOLS = bindNativeTools({
885
887
  memory_search: {
886
888
  impl: memorySearch,
887
889
  contract: {
888
- summary: "{ results: MemoryRecord[] } — semantic hits scoped to the caller's own + granted memories; each hit carries content, never the raw embedding.",
890
+ summary: "{ results: MemoryRecord[] } — semantic hits subject to the caller's read scope; each hit carries content, never the raw embedding.",
889
891
  requiredFields: ["results"],
890
892
  fieldTypes: { results: "array" },
891
893
  invariants: {
@@ -921,8 +923,8 @@ export const TOOLS = bindNativeTools({
921
923
  impl: skillSearch,
922
924
  contract: {
923
925
  summary: "{ results: SkillCard[] } — the skill catalog (lightweight id/name/trigger/description/tags/agentId, " +
924
- "ranked by trigger match); the full procedure and the raw embedding are never on a card. Scoped to the " +
925
- "caller's own + non-private skills; another agent's private skill is never returned.",
926
+ "ranked by trigger match); the full procedure and the raw embedding are never on a card. Non-admin callers " +
927
+ "can retrieve their own and other agents' non-private skills; administrators can also retrieve private skills.",
926
928
  requiredFields: ["results"],
927
929
  fieldTypes: { results: "array" },
928
930
  invariants: {
@@ -938,13 +940,14 @@ export const TOOLS = bindNativeTools({
938
940
  impl: skillGet,
939
941
  contract: {
940
942
  summary: "The full skill record { id, agentId, content, trigger, tags, durability, metadata, createdAt, ... } for a " +
941
- "skill readable under the caller's read-scope — embedding + embeddingModel always stripped. A non-owner " +
942
- "cannot read another agent's private skill, and a readable non-skill id is not found (both 404).",
943
+ "skill readable under the caller's read-scope — embedding + embeddingModel always stripped. A non-admin " +
944
+ "caller cannot read another agent's private skill; administrators retain access. A readable non-skill id " +
945
+ "is reported as not found.",
943
946
  requiredFields: ["id", "agentId", "content", "createdAt"],
944
947
  fieldTypes: { id: "string", agentId: "string", content: "string" },
945
948
  forbiddenFields: INTERNAL_MEMORY_FIELDS,
946
949
  invariants: { fullyResolved: true },
947
- errorShape: { trigger: "get a non-skill / unreadable / another agent's private id (404)", fields: ["error", "status"] },
950
+ errorShape: { trigger: "get a non-skill or unreadable id (404)", fields: ["error", "status"] },
948
951
  },
949
952
  },
950
953
  memory_update: {
@@ -966,7 +969,7 @@ export const TOOLS = bindNativeTools({
966
969
  fieldTypes: { id: "string", archived: "boolean" },
967
970
  forbiddenFields: INTERNAL_MEMORY_FIELDS,
968
971
  invariants: { fullyResolved: true },
969
- errorShape: { trigger: "basementing a non-existent or non-owned id", fields: ["error", "status"] },
972
+ errorShape: { trigger: "basementing a non-existent, unreadable, or unauthorized id", fields: ["error", "status"] },
970
973
  },
971
974
  },
972
975
  memory_restore: {
@@ -977,24 +980,24 @@ export const TOOLS = bindNativeTools({
977
980
  fieldTypes: { id: "string", archived: "boolean" },
978
981
  forbiddenFields: INTERNAL_MEMORY_FIELDS,
979
982
  invariants: { fullyResolved: true },
980
- errorShape: { trigger: "restoring a non-existent or non-owned id", fields: ["error", "status"] },
983
+ errorShape: { trigger: "restoring a non-existent, unreadable, or unauthorized id", fields: ["error", "status"] },
981
984
  },
982
985
  },
983
986
  memory_get: {
984
987
  impl: memoryGet,
985
988
  contract: {
986
- summary: "The full memory record { id, agentId, content, durability, createdAt, ... } for the caller's own id — embedding + embeddingModel stripped by default.",
989
+ summary: "The full memory record { id, agentId, content, durability, createdAt, ... } for the requested ID, subject to the caller's read scope; embedding and embeddingModel are stripped by default.",
987
990
  requiredFields: ["id", "agentId", "content", "createdAt"],
988
991
  fieldTypes: { id: "string", agentId: "string", content: "string" },
989
992
  forbiddenFields: INTERNAL_MEMORY_FIELDS,
990
993
  invariants: { fullyResolved: true },
991
- errorShape: { trigger: "get a non-existent / unowned id (makeByIdReadGate 404)", fields: ["error", "status"] },
994
+ errorShape: { trigger: "get a non-existent or unreadable id (makeByIdReadGate 404)", fields: ["error", "status"] },
992
995
  },
993
996
  },
994
997
  memory_delete: {
995
998
  impl: memoryDelete,
996
999
  contract: {
997
- summary: "Deletes the caller's own memory at any durability tier (success echo is thin). Cross-owner deletion returns { error, status:403 } for a non-admin; a deleted row round-trips as gone via memory_get.",
1000
+ summary: "Deletes a memory by ID when authorized, at any durability tier (success echo is thin). Cross-owner deletion returns { error, status:403 } for a non-admin; a deleted row round-trips as gone via memory_get.",
998
1001
  invariants: { fullyResolved: true },
999
1002
  errorShape: { trigger: "a non-admin deletes another agent's memory", fields: ["error", "status"] },
1000
1003
  },
@@ -1166,7 +1169,7 @@ export const TOOLS = bindNativeTools({
1166
1169
  },
1167
1170
  },
1168
1171
  });
1169
- /** The tool definitions for a tools/list response (exactly the 12 curated tools). */
1172
+ /** The tool definitions for a tools/list response (exactly the 17 curated tools). */
1170
1173
  export function listToolDefs() {
1171
1174
  return Object.values(TOOLS).map((t) => t.def);
1172
1175
  }
@@ -4,6 +4,7 @@
4
4
  // runtime (`databases` / `Resource`, storage init) and can't run outside a live
5
5
  // Harper; this module has no Harper dependency, so
6
6
  // test/unit/memory-consolidate.test.ts exercises the real shipped code.
7
+ import { stripInlinePointerFields } from "./host-source-visibility.js";
7
8
  export function parseDuration(s) {
8
9
  const m = s.match(/^(\d+)([dhm])$/);
9
10
  if (!m)
@@ -30,7 +31,8 @@ export function parseDuration(s) {
30
31
  * freshly-created memory is never an archive candidate regardless of retrieval
31
32
  * count: archival only considers memories that have had a fair chance to be read.
32
33
  */
33
- export function evaluate(record, now, olderThanMs) {
34
+ export function evaluate(rawRecord, now, olderThanMs) {
35
+ const record = stripInlinePointerFields(rawRecord);
34
36
  const ageMs = record.createdAt ? now - new Date(record.createdAt).getTime() : 0;
35
37
  const count = record.retrievalCount ?? 0;
36
38
  const lastUse = record.lastRetrieved ?? record.createdAt;