@ouro.bot/cli 0.1.0-alpha.1390 → 0.1.0-alpha.1393

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 (50) hide show
  1. package/changelog.json +12 -0
  2. package/deploy/unraid/sanctuary.ouro/bundle-meta.json +1 -1
  3. package/deploy/unraid/sanctuary.xml +1 -1
  4. package/dist/a2a/refusals.js +2 -0
  5. package/dist/a2a/server.js +268 -38
  6. package/dist/repertoire/guardrails.js +2 -0
  7. package/dist/senses/a2a-entry.js +6 -2
  8. package/dist/senses/inbound-journal.js +182 -0
  9. package/dist/senses/shared-turn.js +3 -1
  10. package/node_modules/@ouro.bot/friends/README.md +17 -4
  11. package/node_modules/@ouro.bot/friends/actions/generated/mcp.json +1105 -0
  12. package/node_modules/@ouro.bot/friends/changelog.json +72 -0
  13. package/node_modules/@ouro.bot/friends/dist/a2a-client/adapter.d.ts +1 -1
  14. package/node_modules/@ouro.bot/friends/dist/a2a-client/envelope-binding.d.ts +2 -2
  15. package/node_modules/@ouro.bot/friends/dist/a2a-client/envelope-binding.js +12 -8
  16. package/node_modules/@ouro.bot/friends/dist/channel.d.ts +5 -0
  17. package/node_modules/@ouro.bot/friends/dist/channel.js +12 -1
  18. package/node_modules/@ouro.bot/friends/dist/connect.js +8 -8
  19. package/node_modules/@ouro.bot/friends/dist/grant-store-file.d.ts +3 -0
  20. package/node_modules/@ouro.bot/friends/dist/grant-store-file.js +30 -9
  21. package/node_modules/@ouro.bot/friends/dist/grants.d.ts +5 -1
  22. package/node_modules/@ouro.bot/friends/dist/grants.js +22 -6
  23. package/node_modules/@ouro.bot/friends/dist/index.d.ts +3 -3
  24. package/node_modules/@ouro.bot/friends/dist/index.js +5 -2
  25. package/node_modules/@ouro.bot/friends/dist/link-identity.js +9 -9
  26. package/node_modules/@ouro.bot/friends/dist/mcp/bin.js +2 -1
  27. package/node_modules/@ouro.bot/friends/dist/mcp/dispatch.js +211 -16
  28. package/node_modules/@ouro.bot/friends/dist/mcp/run-main.js +24 -13
  29. package/node_modules/@ouro.bot/friends/dist/mcp/schemas.js +9 -431
  30. package/node_modules/@ouro.bot/friends/dist/mcp/server.js +2 -1
  31. package/node_modules/@ouro.bot/friends/dist/message.d.ts +19 -1
  32. package/node_modules/@ouro.bot/friends/dist/message.js +31 -1
  33. package/node_modules/@ouro.bot/friends/dist/mission-result.d.ts +7 -0
  34. package/node_modules/@ouro.bot/friends/dist/mission-result.js +14 -7
  35. package/node_modules/@ouro.bot/friends/dist/mission-store-file.js +8 -0
  36. package/node_modules/@ouro.bot/friends/dist/missions.js +6 -5
  37. package/node_modules/@ouro.bot/friends/dist/notes.js +4 -4
  38. package/node_modules/@ouro.bot/friends/dist/outcomes.js +1 -1
  39. package/node_modules/@ouro.bot/friends/dist/share.d.ts +6 -1
  40. package/node_modules/@ouro.bot/friends/dist/share.js +40 -4
  41. package/node_modules/@ouro.bot/friends/dist/store-file.js +28 -13
  42. package/node_modules/@ouro.bot/friends/dist/tokens.d.ts +3 -1
  43. package/node_modules/@ouro.bot/friends/dist/tokens.js +5 -2
  44. package/node_modules/@ouro.bot/friends/dist/trust-mutation.js +2 -2
  45. package/node_modules/@ouro.bot/friends/dist/types.d.ts +12 -0
  46. package/node_modules/@ouro.bot/friends/dist/util/safe-id.d.ts +1 -0
  47. package/node_modules/@ouro.bot/friends/dist/util/safe-id.js +10 -0
  48. package/node_modules/@ouro.bot/friends/package.json +2 -1
  49. package/npm-shrinkwrap.json +6 -6
  50. package/package.json +2 -2
@@ -1,5 +1,77 @@
1
1
  {
2
2
  "versions": [
3
+ {
4
+ "version": "0.1.0-alpha.30",
5
+ "changes": [
6
+ "A message can carry a signed approval answer, approvalAnswer { relayToken, decision }, where the only decision this version accepts is deny; a receiver refuses any other as malformed. It is held to the delegated rules (bound, at most 10 minutes old), refused alongside onBehalfOf, refused on any kind but message, and refused by receiveMessage when no verifier, or the TOFU one, is given."
7
+ ]
8
+ },
9
+ {
10
+ "version": "0.1.0-alpha.29",
11
+ "changes": [
12
+ "channel_caps answers unknown_channel, listing the channels friends knows, for a channel it has no capabilities for; a typo used to answer the defaults as if they were a real channel's, and a name like toString answered something that wasn't capabilities at all. The library exports isKnownChannel and knownChannels, and getChannelCapabilities gives the defaults for such a name. channel_caps now has an Ouro AX card."
13
+ ]
14
+ },
15
+ {
16
+ "version": "0.1.0-alpha.28",
17
+ "changes": [
18
+ "Missions say what they saved. record_mission answers invalid, and saves nothing, for an empty missionKey, a status other than active, succeeded, partial, failed or abandoned, or participants, learnings or outcomes that aren't a list of the shape each takes (a learning key of __proto__ included); a bogus status used to be reported as given but saved as active, and learnings that weren't JSON were dropped while the call answered ok. Participants with no agentId are told apart by agentName, so two of them are both kept. import_result answers noop, keeping the first, when a result for that request from that agent was already imported, where it used to answer imported. It lands a result under the requestId it correlated on, answers no_delegation for a requestId like constructor, and answers invalid for an envelope without subject.missionKey, a requestId, or a result with a summary whose requestId, if any, is the same. import_mission answers invalid for an envelope with no mission subject, or with learnings or outcomes it can't read, and import_coordination for one with no mission subject, an unknown intent or a task without a requestId, instead of failing. record_mission and import_result now have Ouro AX cards."
19
+ ]
20
+ },
21
+ {
22
+ "version": "0.1.0-alpha.27",
23
+ "changes": [
24
+ "link_identity is marked destructive, because a merge deletes the record it folds in. An empty externalId, or a provider other than aad, local, teams-conversation, imessage-handle, email-address, a2a-agent or telegram-user, now answers invalid and links nothing; both used to be saved and answer linked. The provider input lists the seven providers. link_identity now has an Ouro AX card."
25
+ ]
26
+ },
27
+ {
28
+ "version": "0.1.0-alpha.26",
29
+ "changes": [
30
+ "set_trust, onboard_agent and connect_to save the trust level they report. A level other than family, friend, acquaintance or stranger, including one that isn't text and a missing one for set_trust, now answers invalid and changes nothing; the store used to save it as friend while the answer and the audit line said otherwise. onboard_agent's trustLevel input lists the four levels, an empty name or agentId answers invalid instead of saving a nameless peer, and both are saved without surrounding spaces. connect_to by name links only when exactly one agent has that name; two of the same name answer needs_handle_or_introduction instead of linking the first. The three tools now have Ouro AX cards."
31
+ ]
32
+ },
33
+ {
34
+ "version": "0.1.0-alpha.25",
35
+ "changes": [
36
+ "record_interaction says what it did. A friend that doesn't exist answers not_found; it used to answer success. Usage that isn't an object whose output_tokens is a whole number of 0 or more, an outcome without a missionId and a result of success, partial or failed, or an outcome for someone who isn't an agent answers invalid and saves nothing; unreadable JSON there used to be ignored, and an outcome for a person used to answer recorded while the store dropped it. A successful call answers ok true, status recorded, with tokensAccumulated false when there were no output tokens to add. save_note, record_interaction, set_trust, link_identity and unlink_identity now work on a friend named rather than given by uuid: they write by the record's own id, which the file store used to refuse. A name two records share, or an empty friendId, now finds no friend rather than the first file read, so a write by name can't land on the wrong person. A link by name also never mistakes the record itself for a duplicate. The set_trust audit line names the record's id. record_interaction now has an Ouro AX card."
37
+ ]
38
+ },
39
+ {
40
+ "version": "0.1.0-alpha.24",
41
+ "changes": [
42
+ "Sharing tells the truth about grants and imports. revoke_share answers invalid for a grant id that isn't letters, digits, dots, underscores and hyphens starting with a letter or digit; a grant id like \"../<friend id>\" used to read a friend record as a grant, answer revoked and write a bogus grant file. The grant store reads, writes and deletes only files named directly inside _grants, names each grant by its file, and writes a revocation back to that file. Damage reads as less consent, never more: a grant file whose scope friends doesn't know is skipped (it used to read as an identity grant), any revokedAt revokes, and an expiresAt that isn't an ISO date, empty included, consents to nothing (it used to last forever). grant_share answers invalid for an expiresAt that isn't an ISO date, such as 2027-01-01 or 2027-01-01T00:00:00Z. import_profile lands an outcomes share's outcomes in the record's new importedOutcomes, under the agent that shared them, newest 256 per agent, with first-party outcomes untouched and damaged entries already in that slot dropped, and answers importedOutcomes, the number that landed; before, it answered imported and kept none. It answers invalid, instead of failing partway, for an envelope without a subject whose externalIds is a list of { provider, externalId }, notes that aren't a list of { key, value } (a key of __proto__ included), outcomes that aren't a list, or an empty fromAgentId. import_profile and revoke_share now have Ouro AX cards."
43
+ ]
44
+ },
45
+ {
46
+ "version": "0.1.0-alpha.23",
47
+ "changes": [
48
+ "A friend or mission id can no longer reach a file outside its store's directory. get_friend, and every tool that looks a friend up, now reads a record file directly only for an id made of letters, digits, dots, underscores and hyphens that starts with a letter or digit; any other id, such as \"../x\" or \"a/b\", is matched only as a name, so it answers not_found unless a friend has that name. It used to read any .json file the process could reach. A mission id like that names no mission, and the stores refuse to write or delete a friend or mission by it."
49
+ ]
50
+ },
51
+ {
52
+ "version": "0.1.0-alpha.22",
53
+ "changes": [
54
+ "friends-mcp now prints why it stopped, on stderr, before exiting 1: \"friends-mcp: missing-dir: ...\" when neither --dir nor FRIENDS_DIR names a directory (it used to exit silently), and \"friends-mcp: unknown-door: ...\" for any argument other than --dir <path>, which it used to ignore."
55
+ ]
56
+ },
57
+ {
58
+ "version": "0.1.0-alpha.21",
59
+ "changes": [
60
+ "An MCP call to a tool the server doesn't serve now answers with status unknown_door (ok false) and a message that points at tools/list; its error text is unchanged. A tool that throws (the store can't read or write, say) now answers with status tool_failed and the thrown message, as JSON, where it used to answer with the bare text \"Error: <message>\". Both are error results, as before."
61
+ ]
62
+ },
63
+ {
64
+ "version": "0.1.0-alpha.20",
65
+ "changes": [
66
+ "Release preflight's npm audit allows an advisory with no fixed version through audit-allowance.json, for an exact package version until a set date: today picomatch's ReDoS (GHSA-fc5q-39xc-vjpf), until 2026-12-17. Any other advisory, or an expired or incomplete allowance, still fails."
67
+ ]
68
+ },
69
+ {
70
+ "version": "0.1.0-alpha.19",
71
+ "changes": [
72
+ "Each MCP tool now carries annotations from its kind: reads say read-only; writes that remove something (unlink_identity, revoke_share) say destructive; tools that reach other agents (share_profile, grant_share, share_mission, coordinate, send_result) say destructive and open-world. Tool names, inputs and descriptions are unchanged, except that the provider and externalId inputs of link_identity and unlink_identity now have descriptions."
73
+ ]
74
+ },
3
75
  {
4
76
  "version": "0.1.0-alpha.18",
5
77
  "changes": [
@@ -78,7 +78,7 @@ export type ReceiveShareResult = {
78
78
  bindingId?: string;
79
79
  } | {
80
80
  state: "rejected";
81
- reason: "malformed_message" | "unseal_failed" | "recipient_mismatch" | "malformed_plaintext" | "sender_binding_mismatch" | "resolve_failed" | "retired_pin" | "replayed" | "in_flight" | "bad_signature" | "untrusted_source" | "signed_recipient_mismatch" | "signed_kind_mismatch" | "malformed_binding" | "stale_envelope" | "stale_delegation" | "unbound_delegation" | "unbound_envelope" | "import_failed";
81
+ reason: "malformed_message" | "unseal_failed" | "recipient_mismatch" | "malformed_plaintext" | "sender_binding_mismatch" | "resolve_failed" | "retired_pin" | "replayed" | "in_flight" | "bad_signature" | "untrusted_source" | "signed_recipient_mismatch" | "signed_kind_mismatch" | "malformed_binding" | "stale_envelope" | "stale_delegation" | "unbound_delegation" | "stale_approval_answer" | "unbound_approval_answer" | "unbound_envelope" | "import_failed";
82
82
  };
83
83
  export interface SeenLedgerLike {
84
84
  isSeen(nonce: string): boolean;
@@ -23,7 +23,7 @@ export interface EnvelopeBindingOptions {
23
23
  rejectUnboundEnvelopes?: boolean;
24
24
  /** Max envelope age for any kind. Default 7 days. */
25
25
  maxAgeMs?: number;
26
- /** Max envelope age when the envelope carries `onBehalfOf`. Default 10 minutes. */
26
+ /** Max envelope age when the envelope carries `onBehalfOf` or `approvalAnswer`. Default 10 minutes. */
27
27
  delegatedMaxAgeMs?: number;
28
28
  /** Max time an envelope's `issuedAt` may be ahead of the clock. Default 2 minutes. */
29
29
  maxFutureSkewMs?: number;
@@ -33,7 +33,7 @@ export interface CheckEnvelopeBindingInput extends EnvelopeBindingOptions {
33
33
  /** The ledger the `mid:<senderDid>:<id>` key is CHECKED against (never marked here). */
34
34
  seen: BindingSeenLedger;
35
35
  }
36
- export type EnvelopeBindingRejection = "malformed_binding" | "signed_recipient_mismatch" | "signed_kind_mismatch" | "stale_envelope" | "stale_delegation" | "unbound_delegation" | "unbound_envelope" | "replayed";
36
+ export type EnvelopeBindingRejection = "malformed_binding" | "signed_recipient_mismatch" | "signed_kind_mismatch" | "stale_envelope" | "stale_delegation" | "unbound_delegation" | "stale_approval_answer" | "unbound_approval_answer" | "unbound_envelope" | "replayed";
37
37
  export type EnvelopeBindingResult =
38
38
  /** `bindingId` and `seenKey` are present only when `bound`. `seenKey` is the
39
39
  * `mid:<senderDid>:<id>` ledger key: this function only CHECKS it, so the caller
@@ -34,14 +34,15 @@ function assertValidBindingOptions(options) {
34
34
  function checkEnvelopeBinding(opened, input) {
35
35
  assertValidBindingOptions(input);
36
36
  const envelope = opened.envelope;
37
- const delegated = envelope.onBehalfOf !== undefined;
37
+ // An approval answer is held to the delegated rules: it must be bound, and fresh within the short window.
38
+ const marker = envelope.onBehalfOf !== undefined ? "delegation" : envelope.approvalAnswer !== undefined ? "approval_answer" : null;
38
39
  const binding = envelope.binding;
39
40
  if (binding === undefined) {
40
- if (delegated)
41
- return { ok: false, reason: "unbound_delegation" };
41
+ if (marker)
42
+ return { ok: false, reason: `unbound_${marker}` };
42
43
  if (input.rejectUnboundEnvelopes === true)
43
44
  return { ok: false, reason: "unbound_envelope" };
44
- const fresh = checkFreshness(envelope, delegated, input);
45
+ const fresh = checkFreshness(envelope, marker, input);
45
46
  return fresh ?? { ok: true, bound: false };
46
47
  }
47
48
  if (!binding || typeof binding !== "object" || Array.isArray(binding))
@@ -57,7 +58,10 @@ function checkEnvelopeBinding(opened, input) {
57
58
  return { ok: false, reason: "signed_recipient_mismatch" };
58
59
  if (b.kind !== opened.friendsKind)
59
60
  return { ok: false, reason: "signed_kind_mismatch" };
60
- const stale = checkFreshness(envelope, delegated, input);
61
+ // Only a direct message may carry an approval answer; on any other kind the importers would drop it unseen.
62
+ if (envelope.approvalAnswer !== undefined && opened.friendsKind !== "message")
63
+ return { ok: false, reason: "malformed_binding" };
64
+ const stale = checkFreshness(envelope, marker, input);
61
65
  if (stale)
62
66
  return stale;
63
67
  const key = `mid:${opened.fromAgentId}:${b.id}`;
@@ -65,13 +69,13 @@ function checkEnvelopeBinding(opened, input) {
65
69
  return { ok: false, reason: "replayed" };
66
70
  return { ok: true, bound: true, bindingId: b.id, seenKey: key };
67
71
  }
68
- function checkFreshness(envelope, delegated, input) {
69
- const reason = delegated ? "stale_delegation" : "stale_envelope";
72
+ function checkFreshness(envelope, marker, input) {
73
+ const reason = marker ? `stale_${marker}` : "stale_envelope";
70
74
  const issuedAt = typeof envelope.issuedAt === "string" && ISO_WITH_ZONE.test(envelope.issuedAt) ? Date.parse(envelope.issuedAt) : Number.NaN;
71
75
  if (!Number.isFinite(issuedAt))
72
76
  return { ok: false, reason };
73
77
  const now = input.now === undefined ? Date.now() : typeof input.now === "number" ? input.now : input.now.getTime();
74
- const maxAge = delegated ? (input.delegatedMaxAgeMs ?? exports.DEFAULT_DELEGATED_MAX_AGE_MS) : (input.maxAgeMs ?? exports.DEFAULT_MAX_AGE_MS);
78
+ const maxAge = marker ? (input.delegatedMaxAgeMs ?? exports.DEFAULT_DELEGATED_MAX_AGE_MS) : (input.maxAgeMs ?? exports.DEFAULT_MAX_AGE_MS);
75
79
  const maxFuture = input.maxFutureSkewMs ?? exports.DEFAULT_MAX_FUTURE_SKEW_MS;
76
80
  if (now - issuedAt > maxAge || issuedAt - now > maxFuture)
77
81
  return { ok: false, reason };
@@ -2,6 +2,11 @@ import type { ChannelCapabilities, Channel } from "./types";
2
2
  export type Facing = "human" | "agent";
3
3
  export declare function channelToFacing(channel?: Channel | string): Facing;
4
4
  export declare function getChannelCapabilities(channel: string): ChannelCapabilities;
5
+ /** Whether friends has capabilities for this channel. Only the channel's own entry counts, so a name like "toString"
6
+ * isn't mistaken for one (#225). */
7
+ export declare function isKnownChannel(channel: string): boolean;
8
+ /** The channels friends has capabilities for, in declaration order. */
9
+ export declare function knownChannels(): string[];
5
10
  /** Whether the channel is remote (open or closed) vs local/internal. */
6
11
  export declare function isRemoteChannel(capabilities?: ChannelCapabilities): boolean;
7
12
  /**
@@ -4,6 +4,8 @@
4
4
  Object.defineProperty(exports, "__esModule", { value: true });
5
5
  exports.channelToFacing = channelToFacing;
6
6
  exports.getChannelCapabilities = getChannelCapabilities;
7
+ exports.isKnownChannel = isKnownChannel;
8
+ exports.knownChannels = knownChannels;
7
9
  exports.isRemoteChannel = isRemoteChannel;
8
10
  exports.getAlwaysOnSenseNames = getAlwaysOnSenseNames;
9
11
  const observability_1 = require("./observability");
@@ -137,7 +139,16 @@ function getChannelCapabilities(channel) {
137
139
  message: "channel capabilities lookup",
138
140
  meta: { channel },
139
141
  });
140
- return CHANNEL_CAPABILITIES[channel] ?? DEFAULT_CAPABILITIES;
142
+ return isKnownChannel(channel) ? CHANNEL_CAPABILITIES[channel] : DEFAULT_CAPABILITIES;
143
+ }
144
+ /** Whether friends has capabilities for this channel. Only the channel's own entry counts, so a name like "toString"
145
+ * isn't mistaken for one (#225). */
146
+ function isKnownChannel(channel) {
147
+ return Object.hasOwn(CHANNEL_CAPABILITIES, channel);
148
+ }
149
+ /** The channels friends has capabilities for, in declaration order. */
150
+ function knownChannels() {
151
+ return Object.keys(CHANNEL_CAPABILITIES);
141
152
  }
142
153
  /** Whether the channel is remote (open or closed) vs local/internal. */
143
154
  function isRemoteChannel(capabilities) {
@@ -64,22 +64,22 @@ async function resolvePeer(store, peer) {
64
64
  const existing = await findByName(store, peer.name);
65
65
  if (!existing)
66
66
  return null;
67
- const agentId = agentIdOf(existing);
68
- if (!agentId)
69
- return null;
70
- return { agentId, existing, name: peer.name };
67
+ return { agentId: agentIdOf(existing), existing, name: peer.name };
71
68
  }
72
69
  return null;
73
70
  }
74
- /** Case-insensitive name match over the store's records (the §3.3 name-fallback scan,
75
- * made store-agnostic by using listAll). Returns the first match, or null. A store with
76
- * no listAll yields null (best-effort, never a throw). */
71
+ /** Case-insensitive name match over the store's agent records (the §3.3 name-fallback
72
+ * scan, made store-agnostic by using listAll). Returns the one record of that name that
73
+ * carries an agent handle, or null when none does or more than one does: two agents of
74
+ * the same name are ambiguous, so the caller must pass a handle (#217). A store with no
75
+ * listAll yields null (best-effort, never a throw). */
77
76
  async function findByName(store, name) {
78
77
  if (typeof store.listAll !== "function")
79
78
  return null;
80
79
  const all = await store.listAll();
81
80
  const lower = name.toLowerCase();
82
- return all.find((f) => f.name.toLowerCase() === lower) ?? null;
81
+ const agents = all.filter((f) => f.name.toLowerCase() === lower && agentIdOf(f) !== undefined);
82
+ return agents.length === 1 ? agents[0] : null;
83
83
  }
84
84
  /**
85
85
  * Link a named peer into the calling agent's store from the owner's vantage. Composes:
@@ -11,6 +11,9 @@ export declare class FileGrantStore implements GrantStore {
11
11
  put(id: string, grant: ShareGrant): Promise<void>;
12
12
  delete(id: string): Promise<void>;
13
13
  listAll(): Promise<ShareGrant[]>;
14
+ /** A current ShareGrant from what is on disk, named by its file, or null when its scope isn't one friends knows.
15
+ * Damage reads as less consent, never more (#222): a corrupt scope is no grant, any revokedAt at all is a
16
+ * revocation, and an expiresAt is kept as text even when it isn't one, so isGrantEffective refuses it. */
14
17
  private normalize;
15
18
  private readJson;
16
19
  }
@@ -44,6 +44,7 @@ const fsPromises = __importStar(require("fs/promises"));
44
44
  const path = __importStar(require("path"));
45
45
  const observability_1 = require("./observability");
46
46
  const types_1 = require("./types");
47
+ const safe_id_1 = require("./util/safe-id");
47
48
  /** The sibling grants directory for a given friends directory: `<friendsDir>/_grants`.
48
49
  * The collection lives UNDER the friends dir (a reserved `_`-prefixed subdir) so a
49
50
  * single `--dir` still points the whole substrate at one place. */
@@ -63,13 +64,22 @@ class FileGrantStore {
63
64
  });
64
65
  }
65
66
  async get(id) {
67
+ // An id that would leave the grants directory names no grant (#222).
68
+ if (!(0, safe_id_1.isSafeRecordId)(id))
69
+ return null;
66
70
  const grant = await this.readJson(path.join(this.grantsPath, `${id}.json`));
67
- return grant ? this.normalize(grant) : null;
71
+ return grant ? this.normalize(grant, id) : null;
68
72
  }
69
73
  async put(id, grant) {
70
- await fsPromises.writeFile(path.join(this.grantsPath, `${id}.json`), JSON.stringify(this.normalize(grant), null, 2), "utf-8");
74
+ if (!(0, safe_id_1.isSafeRecordId)(id))
75
+ throw new Error("grant id is invalid");
76
+ if (!(0, types_1.isShareScope)(grant.scope))
77
+ throw new Error("grant scope is invalid");
78
+ await fsPromises.writeFile(path.join(this.grantsPath, `${id}.json`), JSON.stringify(this.normalize(grant, id), null, 2), "utf-8");
71
79
  }
72
80
  async delete(id) {
81
+ if (!(0, safe_id_1.isSafeRecordId)(id))
82
+ throw new Error("grant id is invalid");
73
83
  try {
74
84
  await fsPromises.unlink(path.join(this.grantsPath, `${id}.json`));
75
85
  }
@@ -91,27 +101,38 @@ class FileGrantStore {
91
101
  }
92
102
  const grants = [];
93
103
  for (const entry of entries) {
94
- if (!entry.endsWith(".json"))
104
+ const id = entry.slice(0, -".json".length);
105
+ // A file whose name isn't a grant id is no grant: revoke_share could never reach it.
106
+ if (!entry.endsWith(".json") || !(0, safe_id_1.isSafeRecordId)(id))
95
107
  continue;
96
108
  const raw = await this.readJson(path.join(this.grantsPath, entry));
97
109
  if (!raw)
98
110
  continue;
99
- grants.push(this.normalize(raw));
111
+ const grant = this.normalize(raw, id);
112
+ if (grant)
113
+ grants.push(grant);
100
114
  }
101
115
  return grants;
102
116
  }
103
- normalize(raw) {
117
+ /** A current ShareGrant from what is on disk, named by its file, or null when its scope isn't one friends knows.
118
+ * Damage reads as less consent, never more (#222): a corrupt scope is no grant, any revokedAt at all is a
119
+ * revocation, and an expiresAt is kept as text even when it isn't one, so isGrantEffective refuses it. */
120
+ normalize(raw, id) {
121
+ if (!(0, types_1.isShareScope)(raw.scope))
122
+ return null;
123
+ const revokedAt = raw.revokedAt;
124
+ const expiresAt = raw.expiresAt;
104
125
  return {
105
- id: raw.id,
126
+ id,
106
127
  // Fork D compat seam (a): on-disk schemaVersion-1 grants carry the legacy
107
128
  // `subjectFriendId`; newer ones carry `subjectKey`. Read both, persist
108
129
  // forward as `subjectKey` so the legacy field migrates on the next write.
109
130
  subjectKey: raw.subjectKey ?? raw.subjectFriendId ?? "",
110
131
  recipientAgentId: raw.recipientAgentId,
111
- scope: (0, types_1.isShareScope)(raw.scope) ? raw.scope : "identity",
132
+ scope: raw.scope,
112
133
  grantedAt: typeof raw.grantedAt === "string" ? raw.grantedAt : new Date().toISOString(),
113
- ...(typeof raw.expiresAt === "string" ? { expiresAt: raw.expiresAt } : {}),
114
- ...(typeof raw.revokedAt === "string" ? { revokedAt: raw.revokedAt } : {}),
134
+ ...(expiresAt !== undefined ? { expiresAt: typeof expiresAt === "string" ? expiresAt : JSON.stringify(expiresAt) } : {}),
135
+ ...(revokedAt !== undefined ? { revokedAt: String(revokedAt) } : {}),
115
136
  };
116
137
  }
117
138
  async readJson(filePath) {
@@ -1,5 +1,8 @@
1
1
  import type { GrantStore } from "./grant-store";
2
2
  import type { ShareGrant, ShareScope } from "./types";
3
+ /** Whether text is an ISO 8601 date, or date and time with a zone, that names a real moment. Date.parse alone takes
4
+ * "2099", "1" or "foo 2099" (#222 review). */
5
+ export declare function isIsoDate(text: string): boolean;
3
6
  /** Whether a grant currently consents: not revoked, and not past its expiry as
4
7
  * of `now`. The single source of truth for "effective", shared by the consent
5
8
  * policies and the audit listing. */
@@ -17,8 +20,9 @@ export interface GrantShareInput {
17
20
  export declare function grantShare(grants: GrantStore, input: GrantShareInput): Promise<ShareGrant>;
18
21
  export interface RevokeShareResult {
19
22
  ok: boolean;
20
- status: "revoked" | "not_found" | "noop";
23
+ status: "revoked" | "not_found" | "noop" | "invalid";
21
24
  grant?: ShareGrant;
25
+ message?: string;
22
26
  }
23
27
  /** Revoke a grant by id. Tombstones it (sets `revokedAt`) rather than deleting,
24
28
  * so the audit trail survives. Re-revoking an already-revoked grant is a noop. */
@@ -1,5 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isIsoDate = isIsoDate;
3
4
  exports.isGrantEffective = isGrantEffective;
4
5
  exports.grantShare = grantShare;
5
6
  exports.revokeShare = revokeShare;
@@ -14,14 +15,25 @@ exports.listShares = listShares;
14
15
  // permitted — this module owns their CRUD, not the permission decision.
15
16
  const node_crypto_1 = require("node:crypto");
16
17
  const observability_1 = require("./observability");
18
+ const safe_id_1 = require("./util/safe-id");
19
+ const ISO_DATE = /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])(T([01]\d|2[0-3]):[0-5]\d(:[0-5]\d(\.\d{1,9})?)?(Z|[+-]([01]\d|2[0-3]):[0-5]\d))?$/;
20
+ /** Whether text is an ISO 8601 date, or date and time with a zone, that names a real moment. Date.parse alone takes
21
+ * "2099", "1" or "foo 2099" (#222 review). */
22
+ function isIsoDate(text) {
23
+ return ISO_DATE.test(text) && !Number.isNaN(Date.parse(text));
24
+ }
17
25
  /** Whether a grant currently consents: not revoked, and not past its expiry as
18
26
  * of `now`. The single source of truth for "effective", shared by the consent
19
27
  * policies and the audit listing. */
20
28
  function isGrantEffective(grant, now = new Date()) {
21
- if (grant.revokedAt)
22
- return false;
23
- if (grant.expiresAt && Date.parse(grant.expiresAt) <= now.getTime())
29
+ // Any revokedAt revokes, even an empty one, and an expiry that isn't a date can't be honoured, so either way the
30
+ // grant consents to nothing (#222).
31
+ if (grant.revokedAt !== undefined)
24
32
  return false;
33
+ if (grant.expiresAt !== undefined) {
34
+ if (!isIsoDate(grant.expiresAt) || Date.parse(grant.expiresAt) <= now.getTime())
35
+ return false;
36
+ }
25
37
  return true;
26
38
  }
27
39
  /** Mint an explicit share grant. Returns the persisted ShareGrant. */
@@ -47,15 +59,19 @@ async function grantShare(grants, input) {
47
59
  /** Revoke a grant by id. Tombstones it (sets `revokedAt`) rather than deleting,
48
60
  * so the audit trail survives. Re-revoking an already-revoked grant is a noop. */
49
61
  async function revokeShare(grants, grantId) {
62
+ if (!(0, safe_id_1.isSafeRecordId)(grantId)) {
63
+ return { ok: false, status: "invalid", message: "a grant id is one grant_share or list_shares gave: letters, digits, dots, underscores and hyphens, starting with a letter or digit" };
64
+ }
50
65
  const grant = await grants.get(grantId);
51
66
  if (!grant) {
52
67
  return { ok: false, status: "not_found" };
53
68
  }
54
- if (grant.revokedAt) {
69
+ if (grant.revokedAt !== undefined) {
55
70
  return { ok: true, status: "noop", grant };
56
71
  }
57
- const revoked = { ...grant, revokedAt: new Date().toISOString() };
58
- await grants.put(revoked.id, revoked);
72
+ // The tombstone goes back where the grant was found, whatever id its contents carry.
73
+ const revoked = { ...grant, id: grantId, revokedAt: new Date().toISOString() };
74
+ await grants.put(grantId, revoked);
59
75
  (0, observability_1.emitNervesEvent)({
60
76
  component: "friends",
61
77
  event: "friends.share_revoked",
@@ -22,14 +22,14 @@ export { FileMissionStore, missionsDirFor } from "./mission-store-file";
22
22
  export { openFileBundle } from "./file-bundle";
23
23
  export type { FileBundle } from "./file-bundle";
24
24
  export { FriendResolver, machineOwnerUsername, isLocalMachineOwnerIdentity, _setMachineOwnerUsernameForTest, } from "./resolver";
25
- export { getChannelCapabilities, channelToFacing, isRemoteChannel, getAlwaysOnSenseNames, } from "./channel";
25
+ export { getChannelCapabilities, isKnownChannel, knownChannels, channelToFacing, isRemoteChannel, getAlwaysOnSenseNames, } from "./channel";
26
26
  export { describeTrustContext } from "./trust-explanation";
27
27
  export { assessStanding, explainStanding, DEFAULT_STANDING_RULE } from "./standing";
28
28
  export { upsertGroupContextParticipants } from "./group-context";
29
29
  export { accumulateFriendTokens } from "./tokens";
30
30
  export { applyFriendNote } from "./notes";
31
- export { prepareMessage, receiveMessage, MAX_MESSAGE_TEXT_CHARS, MAX_CONVERSATION_ID_CHARS } from "./message";
32
- export type { MessageEnvelope, ReceivedMessage, PrepareMessageInput, PrepareMessageResult, ReceiveMessageInput, ReceiveMessageOptions, ReceiveMessageResult } from "./message";
31
+ export { prepareMessage, receiveMessage, isApprovalAnswer, MAX_MESSAGE_TEXT_CHARS, MAX_CONVERSATION_ID_CHARS } from "./message";
32
+ export type { ApprovalAnswer, ApprovalDecision, MessageEnvelope, ReceivedMessage, PrepareMessageInput, PrepareMessageResult, ReceiveMessageInput, ReceiveMessageOptions, ReceiveMessageResult } from "./message";
33
33
  export { checkPinnedDelegationGrant } from "./delegation-grant";
34
34
  export type { PinnedDelegationGrant, PinnedDelegationGrantCheck } from "./delegation-grant";
35
35
  export { setFriendTrust } from "./trust-mutation";
@@ -6,8 +6,8 @@
6
6
  // multi-agent (a2a peer) aware, consumed through the FriendStore interface +
7
7
  // FriendResolver.
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.MemoryRosterStore = exports.DEFAULT_ROSTER_VERIFIER = exports.identityRosterVerifier = exports.rostersDirFor = exports.FileRosterStore = exports.findFriendByDid = exports.withMigratedIdentity = exports.resolveAgentIdentity = exports.authorizeConnect = exports.connectAgents = exports.upsertAgentPeer = exports.unlinkExternalId = exports.linkExternalId = exports.auditPathFor = exports.FileAuditSink = exports.MemoryAuditSink = exports.setFriendTrust = exports.checkPinnedDelegationGrant = exports.MAX_CONVERSATION_ID_CHARS = exports.MAX_MESSAGE_TEXT_CHARS = exports.receiveMessage = exports.prepareMessage = exports.applyFriendNote = exports.accumulateFriendTokens = exports.upsertGroupContextParticipants = exports.DEFAULT_STANDING_RULE = exports.explainStanding = exports.assessStanding = exports.describeTrustContext = exports.getAlwaysOnSenseNames = exports.isRemoteChannel = exports.channelToFacing = exports.getChannelCapabilities = exports._setMachineOwnerUsernameForTest = exports.isLocalMachineOwnerIdentity = exports.machineOwnerUsername = exports.FriendResolver = exports.openFileBundle = exports.missionsDirFor = exports.FileMissionStore = exports.grantsDirFor = exports.FileGrantStore = exports.FileFriendStore = exports.isCoordinationIntent = exports.isShareScope = exports.isIntegration = exports.isIdentityProvider = exports.isTrustedLevel = exports.IDENTITY_SCOPES = exports.TRUSTED_LEVELS = void 0;
10
- exports.setNervesEmitter = exports.emitNervesEvent = exports.isGrantEffective = exports.listShares = exports.revokeShare = exports.grantShare = exports.importMissionResult = exports.prepareMissionResult = exports.importCoordination = exports.prepareCoordination = exports.importMissionShare = exports.prepareMissionShare = exports.importProfileShare = exports.prepareProfileShare = exports.DEFAULT_AGENT_VERIFIER = exports.tofuVerifier = exports.DEFAULT_CONSENT_POLICY = exports.tieredPolicy = exports.trustImpliedPolicy = exports.strictPolicy = exports.resolveRoom = exports.whoami = exports.recordMission = exports.recordRelationshipOutcome = exports._resetRosterVerifierWarningForTest = exports.verifiedCandidate = exports.evaluateAccountMembership = void 0;
9
+ exports.rostersDirFor = exports.FileRosterStore = exports.findFriendByDid = exports.withMigratedIdentity = exports.resolveAgentIdentity = exports.authorizeConnect = exports.connectAgents = exports.upsertAgentPeer = exports.unlinkExternalId = exports.linkExternalId = exports.auditPathFor = exports.FileAuditSink = exports.MemoryAuditSink = exports.setFriendTrust = exports.checkPinnedDelegationGrant = exports.MAX_CONVERSATION_ID_CHARS = exports.MAX_MESSAGE_TEXT_CHARS = exports.isApprovalAnswer = exports.receiveMessage = exports.prepareMessage = exports.applyFriendNote = exports.accumulateFriendTokens = exports.upsertGroupContextParticipants = exports.DEFAULT_STANDING_RULE = exports.explainStanding = exports.assessStanding = exports.describeTrustContext = exports.getAlwaysOnSenseNames = exports.isRemoteChannel = exports.channelToFacing = exports.knownChannels = exports.isKnownChannel = exports.getChannelCapabilities = exports._setMachineOwnerUsernameForTest = exports.isLocalMachineOwnerIdentity = exports.machineOwnerUsername = exports.FriendResolver = exports.openFileBundle = exports.missionsDirFor = exports.FileMissionStore = exports.grantsDirFor = exports.FileGrantStore = exports.FileFriendStore = exports.isCoordinationIntent = exports.isShareScope = exports.isIntegration = exports.isIdentityProvider = exports.isTrustedLevel = exports.IDENTITY_SCOPES = exports.TRUSTED_LEVELS = void 0;
10
+ exports.setNervesEmitter = exports.emitNervesEvent = exports.isGrantEffective = exports.listShares = exports.revokeShare = exports.grantShare = exports.importMissionResult = exports.prepareMissionResult = exports.importCoordination = exports.prepareCoordination = exports.importMissionShare = exports.prepareMissionShare = exports.importProfileShare = exports.prepareProfileShare = exports.DEFAULT_AGENT_VERIFIER = exports.tofuVerifier = exports.DEFAULT_CONSENT_POLICY = exports.tieredPolicy = exports.trustImpliedPolicy = exports.strictPolicy = exports.resolveRoom = exports.whoami = exports.recordMission = exports.recordRelationshipOutcome = exports._resetRosterVerifierWarningForTest = exports.verifiedCandidate = exports.evaluateAccountMembership = exports.MemoryRosterStore = exports.DEFAULT_ROSTER_VERIFIER = exports.identityRosterVerifier = void 0;
11
11
  // -- Values --
12
12
  var types_1 = require("./types");
13
13
  Object.defineProperty(exports, "TRUSTED_LEVELS", { enumerable: true, get: function () { return types_1.TRUSTED_LEVELS; } });
@@ -34,6 +34,8 @@ Object.defineProperty(exports, "isLocalMachineOwnerIdentity", { enumerable: true
34
34
  Object.defineProperty(exports, "_setMachineOwnerUsernameForTest", { enumerable: true, get: function () { return resolver_1._setMachineOwnerUsernameForTest; } });
35
35
  var channel_1 = require("./channel");
36
36
  Object.defineProperty(exports, "getChannelCapabilities", { enumerable: true, get: function () { return channel_1.getChannelCapabilities; } });
37
+ Object.defineProperty(exports, "isKnownChannel", { enumerable: true, get: function () { return channel_1.isKnownChannel; } });
38
+ Object.defineProperty(exports, "knownChannels", { enumerable: true, get: function () { return channel_1.knownChannels; } });
37
39
  Object.defineProperty(exports, "channelToFacing", { enumerable: true, get: function () { return channel_1.channelToFacing; } });
38
40
  Object.defineProperty(exports, "isRemoteChannel", { enumerable: true, get: function () { return channel_1.isRemoteChannel; } });
39
41
  Object.defineProperty(exports, "getAlwaysOnSenseNames", { enumerable: true, get: function () { return channel_1.getAlwaysOnSenseNames; } });
@@ -53,6 +55,7 @@ Object.defineProperty(exports, "applyFriendNote", { enumerable: true, get: funct
53
55
  var message_1 = require("./message");
54
56
  Object.defineProperty(exports, "prepareMessage", { enumerable: true, get: function () { return message_1.prepareMessage; } });
55
57
  Object.defineProperty(exports, "receiveMessage", { enumerable: true, get: function () { return message_1.receiveMessage; } });
58
+ Object.defineProperty(exports, "isApprovalAnswer", { enumerable: true, get: function () { return message_1.isApprovalAnswer; } });
56
59
  Object.defineProperty(exports, "MAX_MESSAGE_TEXT_CHARS", { enumerable: true, get: function () { return message_1.MAX_MESSAGE_TEXT_CHARS; } });
57
60
  Object.defineProperty(exports, "MAX_CONVERSATION_ID_CHARS", { enumerable: true, get: function () { return message_1.MAX_CONVERSATION_ID_CHARS; } });
58
61
  var delegation_grant_1 = require("./delegation-grant");
@@ -45,7 +45,7 @@ async function linkExternalId(store, friendId, input) {
45
45
  // Only records in the same tenant as the target's claim are the interrupted merge's orphan.
46
46
  const targetTenant = current.externalIds.find((ext) => ext.provider === input.provider && ext.externalId === input.externalId)?.tenantId;
47
47
  const sameTenantHolds = (record) => record.externalIds.some((ext) => ext.provider === input.provider && ext.externalId === input.externalId && (ext.tenantId === targetTenant || ext.tenantId === undefined));
48
- orphans = (await store.listAll()).filter((record) => record.id !== friendId && sameTenantHolds(record));
48
+ orphans = (await store.listAll()).filter((record) => record.id !== current.id && sameTenantHolds(record));
49
49
  if (orphans.length === 0) {
50
50
  return { ok: true, status: "noop", message: "identity already linked", record: current };
51
51
  }
@@ -57,7 +57,7 @@ async function linkExternalId(store, friendId, input) {
57
57
  const orphan = (input.tenantId !== undefined
58
58
  ? heldIn(await store.findByExternalId(input.provider, input.externalId, input.tenantId), input.tenantId)
59
59
  : null) ?? heldIn(await store.findByExternalId(input.provider, input.externalId), undefined);
60
- orphans = orphan && orphan.id !== friendId ? [orphan] : [];
60
+ orphans = orphan && orphan.id !== current.id ? [orphan] : [];
61
61
  }
62
62
  // A link never moves authority or identity between different standings. An orphan
63
63
  // that holds any authority, was revoked, or sits at a different trust level than the
@@ -77,12 +77,12 @@ async function linkExternalId(store, friendId, input) {
77
77
  component: "friends",
78
78
  event: "friends.identity_link_refused",
79
79
  message: "refused to fold an orphan's other ids onto a record that holds authority",
80
- meta: { orphanId: orphan.id, targetId: friendId },
80
+ meta: { orphanId: orphan.id, targetId: current.id },
81
81
  });
82
82
  return {
83
83
  ok: false,
84
84
  status: "conflict_requires_operator",
85
- message: `external id is held by "${orphan.name}" (${orphan.id}), which carries other external ids; "${current.name}" (${friendId}) holds authority, so those ids cannot be folded onto it without an operator decision`,
85
+ message: `external id is held by "${orphan.name}" (${orphan.id}), which carries other external ids; "${current.name}" (${current.id}) holds authority, so those ids cannot be folded onto it without an operator decision`,
86
86
  };
87
87
  }
88
88
  if (orphan.capabilityProfileId !== undefined ||
@@ -95,12 +95,12 @@ async function linkExternalId(store, friendId, input) {
95
95
  component: "friends",
96
96
  event: "friends.identity_link_refused",
97
97
  message: "refused to merge a record with a different standing into another record",
98
- meta: { orphanId: orphan.id, targetId: friendId },
98
+ meta: { orphanId: orphan.id, targetId: current.id },
99
99
  });
100
100
  return {
101
101
  ok: false,
102
102
  status: "conflict_requires_operator",
103
- message: `external id is held by "${orphan.name}" (${orphan.id}), which has a capability profile, delegation grant, active or revoked admission, or a different trust level than "${current.name}" (${friendId}); it cannot be merged without an operator decision`,
103
+ message: `external id is held by "${orphan.name}" (${orphan.id}), which has a capability profile, delegation grant, active or revoked admission, or a different trust level than "${current.name}" (${current.id}); it cannot be merged without an operator decision`,
104
104
  };
105
105
  }
106
106
  }
@@ -126,7 +126,7 @@ async function linkExternalId(store, friendId, input) {
126
126
  // The target keeps its own trust. Write the merged target BEFORE deleting the
127
127
  // orphans, so a failure between the two steps leaves both records, not neither.
128
128
  const updated = { ...current, externalIds: mergedIds, notes: mergedNotes, updatedAt: now };
129
- await store.put(friendId, updated);
129
+ await store.put(updated.id, updated);
130
130
  for (const orphan of orphans)
131
131
  await store.delete(orphan.id);
132
132
  return { ok: true, status: orphans.length > 0 ? "merged" : "linked", record: updated };
@@ -150,8 +150,8 @@ async function unlinkExternalId(store, friendId, input) {
150
150
  // Drop the claim-journal entry first: if the record write then fails, the id is
151
151
  // still on the record and a retry works; the reverse order lets the journal
152
152
  // bring the id back on the next read.
153
- await store.releaseExternalId?.(friendId, current.externalIds[idx]);
153
+ await store.releaseExternalId?.(current.id, current.externalIds[idx]);
154
154
  const updated = { ...current, externalIds: filtered, updatedAt: new Date().toISOString() };
155
- await store.put(friendId, updated);
155
+ await store.put(updated.id, updated);
156
156
  return { ok: true, status: "unlinked", record: updated };
157
157
  }
@@ -10,7 +10,8 @@ const run_main_1 = require("./run-main");
10
10
  (0, run_main_1.runMain)(process.argv, process.env, {
11
11
  stdin: process.stdin,
12
12
  stdout: process.stdout,
13
- onError: () => {
13
+ onError: (message) => {
14
+ process.stderr.write(`friends-mcp: ${message}\n`);
14
15
  process.exitCode = 1;
15
16
  },
16
17
  });