@agenticprimitives/context 0.0.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +24 -0
  3. package/dist/affiliations-read.d.ts +19 -0
  4. package/dist/affiliations-read.d.ts.map +1 -0
  5. package/dist/affiliations-read.js +74 -0
  6. package/dist/affiliations-read.js.map +1 -0
  7. package/dist/ask-discovery.d.ts +15 -0
  8. package/dist/ask-discovery.d.ts.map +1 -0
  9. package/dist/ask-discovery.js +88 -0
  10. package/dist/ask-discovery.js.map +1 -0
  11. package/dist/confirmation.d.ts +59 -0
  12. package/dist/confirmation.d.ts.map +1 -0
  13. package/dist/confirmation.js +52 -0
  14. package/dist/confirmation.js.map +1 -0
  15. package/dist/conversation.d.ts +61 -0
  16. package/dist/conversation.d.ts.map +1 -0
  17. package/dist/conversation.js +66 -0
  18. package/dist/conversation.js.map +1 -0
  19. package/dist/directory-rows.d.ts +41 -0
  20. package/dist/directory-rows.d.ts.map +1 -0
  21. package/dist/directory-rows.js +121 -0
  22. package/dist/directory-rows.js.map +1 -0
  23. package/dist/entities.d.ts +65 -0
  24. package/dist/entities.d.ts.map +1 -0
  25. package/dist/entities.js +56 -0
  26. package/dist/entities.js.map +1 -0
  27. package/dist/grounded-composition.d.ts +14 -0
  28. package/dist/grounded-composition.d.ts.map +1 -0
  29. package/dist/grounded-composition.js +89 -0
  30. package/dist/grounded-composition.js.map +1 -0
  31. package/dist/grounded-types.d.ts +11 -0
  32. package/dist/grounded-types.d.ts.map +1 -0
  33. package/dist/grounded-types.js +2 -0
  34. package/dist/grounded-types.js.map +1 -0
  35. package/dist/index.d.ts +32 -0
  36. package/dist/index.d.ts.map +1 -0
  37. package/dist/index.js +31 -0
  38. package/dist/index.js.map +1 -0
  39. package/dist/instructions.d.ts +56 -0
  40. package/dist/instructions.d.ts.map +1 -0
  41. package/dist/instructions.js +61 -0
  42. package/dist/instructions.js.map +1 -0
  43. package/dist/invitations-read.d.ts +28 -0
  44. package/dist/invitations-read.d.ts.map +1 -0
  45. package/dist/invitations-read.js +93 -0
  46. package/dist/invitations-read.js.map +1 -0
  47. package/dist/kb-question.d.ts +24 -0
  48. package/dist/kb-question.d.ts.map +1 -0
  49. package/dist/kb-question.js +139 -0
  50. package/dist/kb-question.js.map +1 -0
  51. package/dist/membership-read.d.ts +37 -0
  52. package/dist/membership-read.d.ts.map +1 -0
  53. package/dist/membership-read.js +143 -0
  54. package/dist/membership-read.js.map +1 -0
  55. package/dist/memory.d.ts +49 -0
  56. package/dist/memory.d.ts.map +1 -0
  57. package/dist/memory.js +43 -0
  58. package/dist/memory.js.map +1 -0
  59. package/dist/name-match.d.ts +22 -0
  60. package/dist/name-match.d.ts.map +1 -0
  61. package/dist/name-match.js +109 -0
  62. package/dist/name-match.js.map +1 -0
  63. package/dist/party-resolution.d.ts +214 -0
  64. package/dist/party-resolution.d.ts.map +1 -0
  65. package/dist/party-resolution.js +687 -0
  66. package/dist/party-resolution.js.map +1 -0
  67. package/dist/private-context.d.ts +25 -0
  68. package/dist/private-context.d.ts.map +1 -0
  69. package/dist/private-context.js +134 -0
  70. package/dist/private-context.js.map +1 -0
  71. package/dist/provider.d.ts +45 -0
  72. package/dist/provider.d.ts.map +1 -0
  73. package/dist/provider.js +18 -0
  74. package/dist/provider.js.map +1 -0
  75. package/dist/relationship-rows.d.ts +14 -0
  76. package/dist/relationship-rows.d.ts.map +1 -0
  77. package/dist/relationship-rows.js +50 -0
  78. package/dist/relationship-rows.js.map +1 -0
  79. package/dist/self-only.d.ts +24 -0
  80. package/dist/self-only.d.ts.map +1 -0
  81. package/dist/self-only.js +48 -0
  82. package/dist/self-only.js.map +1 -0
  83. package/dist/standing.d.ts +75 -0
  84. package/dist/standing.d.ts.map +1 -0
  85. package/dist/standing.js +152 -0
  86. package/dist/standing.js.map +1 -0
  87. package/dist/structured-call.d.ts +16 -0
  88. package/dist/structured-call.d.ts.map +1 -0
  89. package/dist/structured-call.js +18 -0
  90. package/dist/structured-call.js.map +1 -0
  91. package/dist/tiers.d.ts +14 -0
  92. package/dist/tiers.d.ts.map +1 -0
  93. package/dist/tiers.js +2 -0
  94. package/dist/tiers.js.map +1 -0
  95. package/dist/vault-question.d.ts +75 -0
  96. package/dist/vault-question.d.ts.map +1 -0
  97. package/dist/vault-question.js +302 -0
  98. package/dist/vault-question.js.map +1 -0
  99. package/package.json +51 -0
  100. package/spec.md +20 -0
@@ -0,0 +1,687 @@
1
+ // WHO DID THEY MEAN? — resolving a person's words to an agent, in the tier where knowing them lives.
2
+ //
3
+ // "send 2 usdc from nathan to alice" is how people talk. `alice` is not a name the naming service knows
4
+ // (`unknown_tld`), it is a HUMAN REFERENCE, and turning one into an agent has three honest outcomes:
5
+ //
6
+ // certain one agent answers — use it.
7
+ // ambiguous several do. ASK which. Picking the first, the nearest or the best-scoring is how money
8
+ // reaches the wrong Alice, and no ranking makes that safe.
9
+ // unknown none does. ASK, and say where we looked.
10
+ //
11
+ // WHICH TIER, and why it changed. The first cut searched the PUBLIC directory, and that is wrong in a way
12
+ // that reads as helpful: a directory hit proves an agent EXISTS, never that this person knows them. Filling
13
+ // a payee from it means a stranger with a common label can be paid by a sentence that named a friend. Spec
14
+ // 352 §7 and 353 §3 are explicit — "Alice" resolves in the asker's PRIVATE tier or refuses, and a global
15
+ // people search is a different ask (279/338).
16
+ //
17
+ // So resolution now runs over `@agenticprimitives/context`: providers own a tier, the tier travels on every
18
+ // candidate, and a lookup that will bind an authority asks only the private ones. What remains public —
19
+ // `find_agents`, `get_agent` — answers QUESTIONS about who exists, which is a different thing a person can
20
+ // also want.
21
+ //
22
+ // The honest limit: the private tier reachable today is the asker's own relationships. Somebody known to
23
+ // them only through a shared org's roster is not found, and the person is asked rather than guessed at
24
+ // (spec 353 S3 / Ask-2 reaches rosters, which is a second private read against a different subject).
25
+ import { pronounOf, pronounRecall, chosenBefore } from './conversation.js';
26
+ import { labelForms, saidKind } from './name-match.js';
27
+ import { InputRequired } from '@agenticprimitives/orchestration';
28
+ import { resolveEntity } from './entities.js';
29
+ import { decide, PAYMENT_RECIPIENT, kinTermFor, walkChain } from '@agenticprimitives/ontology';
30
+ import { preferenceFor } from './memory.js';
31
+ import { VALUE_ARGS as ONTOLOGY_VALUE_ARGS, CLASS_FOR_SUFFIX, SUFFIX_FOR_CLASS } from '@agenticprimitives/ontology';
32
+ import { relationshipRows } from './relationship-rows.js';
33
+ /** The vault record type holding an asker's received resolution grants (spec 338). Declared HERE —
34
+ * the app's resolution-invitation module imports it back, so the key has one definition. */
35
+ export const RESOLUTION_GRANTS_RECORD = 'resolution.grants';
36
+ import { relationshipsProvider, rosterProvider } from './private-context.js';
37
+ /** The roots a bare label might live under, most-likely first. A person is the common case for "alice". */
38
+ export const PARTY_ROOTS = ['me', 'org', 'team', 'treasury', 'workspace', 'svc', 'circle', 'church', 'registry'];
39
+ /** The owner a candidate was reached THROUGH, when it was reached through one.
40
+ *
41
+ * Read off an EXPLICIT field, never off `provenance.subject`: for a private-tier read the subject is
42
+ * WHOSE TIER WAS READ, which for a held grant is the ASKER. Taking it as the owner named Nathan as the
43
+ * owner of Bob's treasury — the settle it fed then looked for a note from Nathan to himself, found none,
44
+ * and closed nothing, silently and plausibly. Provenance says where an answer came from; it does not say
45
+ * what the answer is about. */
46
+ function ownerOf(c) {
47
+ const owner = String(c.ownedBy ?? '').toLowerCase();
48
+ return /^0x[0-9a-f]{40}$/.test(owner) ? owner : undefined;
49
+ }
50
+ const isAddress = (v) => /^0[xX][0-9a-fA-F]{40}$/.test(v);
51
+ /** Arguments that move value — from the ontology binding (spec 355), where a party says whether getting
52
+ * it wrong can be undone. For these, settling for a different KIND of agent than the capability asked
53
+ * for is a question, not a resolution: a payment cannot be taken back. */
54
+ export const VALUE_ARGS = ONTOLOGY_VALUE_ARGS;
55
+ /**
56
+ * A bare label against the typed roots the asker could plausibly mean, resolved on chain.
57
+ *
58
+ * PRIVATE tier, deliberately: `alice.me` is not a search of everyone — it is the question "does the person
59
+ * I am acting for have an agent by this label", asked of a naming service that answers exactly. It is
60
+ * paired with `relationships`, which knows who they actually know; between them, a bare label that matches
61
+ * nothing they have a link to still surfaces if it is a well-known typed name, and ambiguity between the
62
+ * two is a question rather than a pick.
63
+ */
64
+ function typedRootProvider(resolveName) {
65
+ return {
66
+ source: 'naming',
67
+ tier: 'private',
68
+ async candidates(query) {
69
+ const label = query.term.trim().toLowerCase();
70
+ if (isAddress(label))
71
+ return [];
72
+ // A spoken name is words: "missio nexus organization" is registered, if at all, as `missio-nexus`
73
+ // or `missionexus` under a typed root — the kind word says which root to try first, and only that
74
+ // root when it was said.
75
+ const forms = label.includes('.') ? [label] : (/[^a-z0-9-]/.test(label) ? labelForms(label) : [label]);
76
+ const kind = saidKind(label);
77
+ const saidRoot = kind === 'organization' || kind === 'organisation' ? 'org' : kind;
78
+ const roots = saidRoot && PARTY_ROOTS.includes(saidRoot) ? [saidRoot] : PARTY_ROOTS;
79
+ const names = label.includes('.') ? [label] : forms.flatMap((f) => roots.map((r) => `${f}.${r}`));
80
+ const found = await Promise.all(names.map(async (name) => ({ name, agent: await resolveName(name).catch(() => null) })));
81
+ return found
82
+ .filter((f) => !!f.agent)
83
+ .map((f) => ({
84
+ agent: f.agent.toLowerCase(),
85
+ label: f.name,
86
+ name: f.name,
87
+ provenance: { tier: 'private', source: 'naming', ...(query.subject ? { subject: query.subject } : {}), match: label.includes('.') ? 'exact-name' : forms.length === 1 && forms[0] === label ? 'label' : 'close' },
88
+ }));
89
+ },
90
+ };
91
+ }
92
+ /** The providers a party lookup may consult, in order — private ones only. */
93
+ export function partyProviders(lookups) {
94
+ const providers = [];
95
+ if (lookups.readSubjectRecord) {
96
+ const tier = { readSubjectRecord: lookups.readSubjectRecord };
97
+ // Own links first: an agent the person keeps a link to is more certainly "theirs" than one they merely
98
+ // share a room with, and first-wins dedupe keeps that label when both find the same agent.
99
+ providers.push(relationshipsProvider(tier), rosterProvider(tier));
100
+ }
101
+ if (lookups.resolveName)
102
+ providers.push(typedRootProvider(lookups.resolveName));
103
+ return providers;
104
+ }
105
+ /** Every agent the asker could mean by these words. Exported for tests and for a surface that wants to
106
+ * show the same candidates the resolver saw. */
107
+ export async function partyCandidates(raw, lookups, subject) {
108
+ const outcome = await resolveEntity(partyProviders(lookups), { term: raw, tiers: ['private'], ...(subject ? { subject } : {}), limit: 8 });
109
+ if (outcome.outcome === 'certain')
110
+ return [outcome.candidate];
111
+ return outcome.outcome === 'ambiguous' ? outcome.candidates : [];
112
+ }
113
+ /**
114
+ * THE ASKER'S OWN AGENT OF A GIVEN TYPE — "pay from my treasury", without them having to say it.
115
+ *
116
+ * A person standing in their own realm says "send alice 20 USDC" and means the thing of theirs that holds
117
+ * money. What arrives is their PERSON address, because that is the realm they are standing in, and a
118
+ * person SA holds no USDC — so the ask died on a balance check against an account that was never meant to
119
+ * pay. The typed suffix already says which of their agents is the payer; this is that lookup, over their
120
+ * own tree only.
121
+ *
122
+ * Their own tier, and no widening: this answers "which of YOUR agents", never "which agent anywhere".
123
+ */
124
+ export async function ownAgentsOfType(subject, type, lookups) {
125
+ if (!lookups.readSubjectRecord)
126
+ return [];
127
+ const doc = await lookups.readSubjectRecord(subject, 'relationships.data');
128
+ const own = relationshipRows(doc).filter((r) => isOfType(r, type)).map((r) => asCandidate(r, type, subject, 'own-agent'));
129
+ // THE MARKS THEY PUT ON THEIR OWN ACCOUNTS live on the public `charteredUnder` edge, not in the vault
130
+ // row — so the private tier alone knows WHICH agents are theirs and not WHICH ONE they use. Reading the
131
+ // chain here is what lets the decision plane answer instead of asking (spec 363 §2); a candidate with
132
+ // no marks is unchanged, which is every candidate until somebody says otherwise.
133
+ const marked = await (lookups.charteredAgents?.(subject.toLowerCase(), type) ?? Promise.resolve([])).catch(() => []);
134
+ if (!marked.length)
135
+ return own;
136
+ const rolesByAgent = new Map(marked.filter((m) => m.roles?.length).map((m) => [m.agent.toLowerCase(), m.roles]));
137
+ return own.map((c) => (rolesByAgent.has(c.agent.toLowerCase()) ? { ...c, roles: rolesByAgent.get(c.agent.toLowerCase()) } : c));
138
+ }
139
+ /**
140
+ * Is this one of the person's agents of that kind?
141
+ *
142
+ * THE NAME IS NOT THE ONLY EVIDENCE, and relying on it lost seven treasuries. An UNNAMED agent has no
143
+ * suffix to read — that is the whole point of being unnamed — so its row's `kind` (`person-treasury`,
144
+ * `org-treasury`) is what says what it is. Reading only the suffix meant a person who had created every
145
+ * treasury without a name owned, as far as this resolver could tell, none at all.
146
+ */
147
+ function isOfType(r, type) {
148
+ if (r.name.toLowerCase().split('.').pop() === type)
149
+ return true;
150
+ const kind = (r.kind ?? '').toLowerCase();
151
+ return kind === type || kind.endsWith(`-${type}`);
152
+ }
153
+ /** A row as a candidate. An unnamed agent is labelled by WHAT it is, since it has nothing else. */
154
+ function asCandidate(r, type, subject, match) {
155
+ const named = r.name.includes('.');
156
+ return {
157
+ agent: r.agent,
158
+ label: named ? r.name : `unnamed ${type} · ${r.agent.slice(0, 8)}…${r.agent.slice(-4)}`,
159
+ ...(named ? { name: r.name } : {}),
160
+ provenance: { tier: 'private', source: 'relationships', subject, match },
161
+ };
162
+ }
163
+ /**
164
+ * THE AGENTS SOMEONE OWNS, of a given type — the relationship, not the name.
165
+ *
166
+ * "Send money to alice" means alice's TREASURY. Finding it by guessing the name `alice.treasury` was
167
+ * wrong in principle and wrong in fact: her treasury is called `alice2.treasury`, and a treasury's name
168
+ * has no obligation to resemble its owner's. What actually connects them is the OWNERSHIP relationship —
169
+ * resolve the person first, then ask what they hold.
170
+ *
171
+ * Read from the asker's own tree, where an agent records its parent. That covers everything they are
172
+ * linked to — their own treasuries, and those of the organizations they steward. It does NOT cover a
173
+ * stranger's: the link between alice.me and alice2.treasury lives in ALICE's private records
174
+ * (ADR-0025), and is in no public place today — not the relationship registry (no edges exist), not the
175
+ * directory (no owner field), not the naming service (whose "parent" is the TLD). Until a person's
176
+ * treasury is a public fact, nobody else can be routed to it, and the honest move is to ask.
177
+ */
178
+ export async function ownedAgentsOfType(owner, type, lookups, asker) {
179
+ const subject = asker ?? owner;
180
+ const low = owner.toLowerCase();
181
+ const seen = new Set();
182
+ const out = [];
183
+ /** Ways they HOLD that could not be used, and why — surfaced, never swallowed. */
184
+ const refusals = [];
185
+ // ON CHAIN FIRST (spec 355 W2): `ap:charteredUnder` edges are PUBLIC and chain-reproducible, so this is
186
+ // the half that works for a stranger — Nathan can be routed to Alice's treasury without reading
187
+ // anything of hers. Not a fallback chain: both sources answer the same question ("what does this agent
188
+ // hold of this kind"), and the CALLER decides what to do with one answer or several.
189
+ const chartered = await (lookups.charteredAgents?.(low, type) ?? Promise.resolve([])).catch(() => []);
190
+ for (const c of chartered) {
191
+ if (seen.has(c.agent))
192
+ continue;
193
+ seen.add(c.agent);
194
+ out.push({
195
+ agent: c.agent, label: c.name ?? c.agent, ...(c.name ? { name: c.name } : {}),
196
+ ownedBy: low,
197
+ provenance: { tier: 'public', source: 'chartered-under', subject: low, match: c.primary ? 'primary-payee' : 'owned-by' },
198
+ });
199
+ }
200
+ // A GRANT SOMEONE GAVE THEM. An unlisted agent is in no public place by its owner's choice, so the only
201
+ // way to reach it is that the owner told this person — a resolution grant they hold in their own vault
202
+ // (spec 338 / ADR-0056). It answers "where do I send it", never "may I spend it": the payment that
203
+ // follows still needs the asker's own mandate, judged by the verifier like any other.
204
+ if (lookups.readSubjectRecord && asker) {
205
+ const held = await lookups.readSubjectRecord(asker, RESOLUTION_GRANTS_RECORD).catch(() => null);
206
+ // CHECKED, not merely held: the record is in the asker's own vault, so the record is not the
207
+ // evidence — the issuer's signature inside it is. Without a verifier configured, a held grant is not
208
+ // trusted at all rather than trusted blindly.
209
+ const grants = lookups.verifyGrant
210
+ ? await lookups.verifyGrant(held, type, asker, lookups.session).catch(() => [])
211
+ : [];
212
+ for (const g of grants) {
213
+ if (!g.targetAgent) {
214
+ // THE GATE REFUSED, and that is worth saying. A reference without a projection is not a way in —
215
+ // but the holder can only act on it if they are told which of the four reasons it was (withdrawn,
216
+ // expired, issued to somebody else, or a plane that cannot answer). Carried on the candidate so
217
+ // the question that follows can name it.
218
+ if (g.refusedBecause)
219
+ refusals.push(`${g.ownerName ?? g.owner}: ${g.refusedBecause}`);
220
+ continue;
221
+ }
222
+ if (g.owner.toLowerCase() !== low || seen.has(g.targetAgent.toLowerCase()))
223
+ continue;
224
+ seen.add(g.targetAgent.toLowerCase());
225
+ out.push({
226
+ agent: g.targetAgent.toLowerCase(),
227
+ ownedBy: g.owner.toLowerCase(),
228
+ // It has NO NAME — that is why a grant was needed. Say whose it is instead.
229
+ // "alice.me's treasury" — the owner's name, because the target has none and an address alone
230
+ // does not tell the holder who they are about to pay.
231
+ label: g.label ?? (g.ownerName ? `${g.ownerName}'s ${type}` : `their ${type}`),
232
+ provenance: { tier: 'private', source: 'resolution-grant', subject: asker, match: 'granted' },
233
+ });
234
+ }
235
+ }
236
+ // Then the asker's own tier, which knows agents whose edge has not been recorded yet — every agent
237
+ // created before W2, and any whose owner chose not to publish the link.
238
+ if (lookups.readSubjectRecord) {
239
+ const doc = await lookups.readSubjectRecord(subject, 'relationships.data').catch(() => null);
240
+ for (const r of relationshipRows(doc)) {
241
+ if (r.parent?.toLowerCase() !== low || !isOfType(r, type) || seen.has(r.agent))
242
+ continue;
243
+ seen.add(r.agent);
244
+ out.push(asCandidate(r, type, subject, 'owned-by'));
245
+ }
246
+ }
247
+ // THEY SAID WHICH ONE — applied ACROSS every source, at the end.
248
+ //
249
+ // When the owner has marked a primary payee (`ap:primaryPayee`, spec 355), that IS the answer: asking
250
+ // the payer to choose between someone else's accounts puts the decision on the person who knows least
251
+ // about it. Narrowing only the chartered list left the question standing, because a grant and the
252
+ // asker's own tier then added the other treasuries straight back — the preference was declared, paid
253
+ // for with a signature, and changed nothing a payer could see.
254
+ //
255
+ // A grant naming a different treasury is a way to REACH that one, not an instruction to prefer it; and
256
+ // every other account of theirs stays reachable by name. This stops the question, nothing else.
257
+ const marked = out.filter((c) => c.provenance.match === 'primary-payee');
258
+ const result = marked.length === 1 ? marked : out;
259
+ // The refusals ride along so the caller can say them; they are not candidates and never become one.
260
+ return Object.assign(result, { refusals });
261
+ }
262
+ /** Where a candidate came from, said the way a person would say it. */
263
+ const FOUND_IN = {
264
+ relationships: 'you are linked to them',
265
+ roster: 'a member of one of your organizations',
266
+ naming: 'the naming service',
267
+ };
268
+ /**
269
+ * What tells two agents with the same name apart. Kind first (a person and a team called the same thing
270
+ * is the common case), then the address — truncated, because the middle of an address distinguishes
271
+ * nothing and a full one crowds out the parts that do.
272
+ */
273
+ /** `aphh:householdMember` — the basis the recipient decision reads. Bound by IRI like every other. */
274
+ const HOUSEHOLD_MEMBER_IRI = 'https://agenticprimitives.dev/ns/household#householdMember';
275
+ /** `aphh:householdPayee` — the CHAIN (`householdMember ∘ primaryPayee`), walked rather than re-written. */
276
+ const HOUSEHOLD_PAYEE_IRI = 'https://agenticprimitives.dev/ns/household#householdPayee';
277
+ /**
278
+ * The people in the asker's own household record. PRIVATE TIER — their vault, their copy, never
279
+ * published (ADR-0040 keeps it out of the KB because it is not derivable from chain state).
280
+ */
281
+ export async function householdMembers(subject, lookups) {
282
+ if (!lookups.readSubjectRecord)
283
+ return [];
284
+ const doc = await lookups.readSubjectRecord(subject, 'household.data').catch(() => null);
285
+ const d = doc;
286
+ // EVERY HOUSEHOLD THEY KEEP. A person can belong to more than one, so "my daughter" is looked for
287
+ // across all of them — and two households holding a Sarah is ambiguity the decision plane refuses to
288
+ // settle (exactly-one, spec 363), which sends the question back where it belongs. The legacy flat
289
+ // shape reads as the household called "home".
290
+ const rows = Array.isArray(d?.households)
291
+ ? d.households.flatMap((h) => (h.members ?? []).map((m) => ({ ...m, household: h.label ?? h.id ?? 'home' })))
292
+ : d?.members;
293
+ if (!Array.isArray(rows))
294
+ return [];
295
+ return rows
296
+ .map((r) => r)
297
+ .filter((r) => /^0x[0-9a-fA-F]{40}$/.test(String(r.agent ?? '')))
298
+ .map((r) => {
299
+ const kin = r.kin ? String(r.kin) : undefined;
300
+ const kinLabel = r.kinLabel ? String(r.kinLabel) : undefined;
301
+ return {
302
+ agent: String(r.agent).toLowerCase(),
303
+ ...(r.label ? { label: String(r.label) } : {}),
304
+ ...(kin ? { kin } : {}), ...(kinLabel ? { kinLabel } : {}),
305
+ ...(r.role ? { role: String(r.role) } : {}),
306
+ ...(r.household ? { household: String(r.household) } : {}),
307
+ ...(kin ? { kinWord: kin === 'other' ? (kinLabel ?? 'relative') : kin } : {}),
308
+ };
309
+ });
310
+ }
311
+ /**
312
+ * Does this member answer to the word the person used?
313
+ *
314
+ * Their household LABEL ("Sarah"), the first part of their name, or a KIN WORD — "my daughter", "wife".
315
+ * The kin words come from the T-box's own `skos:altLabel`s, which is why "daughter" and "son" both reach
316
+ * `aphh:child` without this file keeping a synonym table the ontology already has.
317
+ */
318
+ function matchesLabel(m, said) {
319
+ const word = said.toLowerCase().replace(/^(my|our)\s+/, '').trim();
320
+ if (!word)
321
+ return false;
322
+ if (m.label && m.label.toLowerCase() === word)
323
+ return true;
324
+ if (m.kinLabel && m.kinLabel.toLowerCase() === word)
325
+ return true;
326
+ if (m.kin && (m.kin === word || kinTermFor(word) === m.kin))
327
+ return true;
328
+ return false;
329
+ }
330
+ /**
331
+ * The choices a person is shown, richest first, each saying what it holds.
332
+ *
333
+ * ORDER IS NOT AN ANSWER. Ranking is a courtesy to the reader — the account that can actually pay is the
334
+ * one they are usually looking for — and the question is still asked, because spending from the fullest
335
+ * account is a guess about intent, not a fact about it. An account with nothing keeps its place in the
336
+ * list; it is merely last.
337
+ *
338
+ * Nothing here is fetched unless `valueHeld` is wired, and a lookup that fails annotates nothing rather
339
+ * than removing a candidate: a balance we could not read is not evidence the agent is not theirs.
340
+ */
341
+ export async function choicesFor(candidates, lookups,
342
+ /** What the act NEEDS, when the amount is already known. An account that cannot cover it is still the
343
+ * person's own and still offered — they may mean to fund it — but it is marked and it goes last.
344
+ * Offering an account that will fail as an equal choice is offering a wrong answer politely. */
345
+ needs) {
346
+ const base = candidates.map((c) => ({ value: c.agent, label: c.label, hint: candidateHint(c), amount: -1n, covers: true }));
347
+ if (!lookups.valueHeld)
348
+ return base.map(({ value, label, hint }) => ({ value, label, hint }));
349
+ const held = await Promise.all(candidates.map((c) => lookups.valueHeld(c.agent).catch(() => null)));
350
+ const rows = base.map((row, i) => {
351
+ const h = held[i];
352
+ if (!h)
353
+ return row;
354
+ const covers = !needs || h.amount >= needs.amount;
355
+ return {
356
+ ...row, amount: h.amount, covers,
357
+ hint: `${h.display}${covers ? '' : ` — not enough for ${needs.display}`} · ${row.hint}`,
358
+ };
359
+ });
360
+ // Stable within equal balances: the earlier candidate (a named one, typically) stays earlier.
361
+ return rows
362
+ .map((r, i) => ({ r, i }))
363
+ .sort((a, b) => {
364
+ // Accounts that can actually do it first, then by balance, then by the order they came in.
365
+ if (a.r.covers !== b.r.covers)
366
+ return a.r.covers ? -1 : 1;
367
+ if (a.r.amount !== b.r.amount)
368
+ return b.r.amount > a.r.amount ? 1 : -1;
369
+ return a.i - b.i;
370
+ })
371
+ .map(({ r }) => ({ value: r.value, label: r.label, hint: r.hint }));
372
+ }
373
+ export function candidateHint(c) {
374
+ const bits = [];
375
+ if (c.name && c.name !== c.label)
376
+ bits.push(c.name);
377
+ if (c.kind)
378
+ bits.push(c.kind);
379
+ bits.push(`${c.agent.slice(0, 8)}…${c.agent.slice(-4)}`);
380
+ const from = FOUND_IN[c.provenance.source];
381
+ if (from)
382
+ bits.push(from);
383
+ // A near name is SAID to be one: the person sees "closest to what you said" beside it before anything
384
+ // is signed, and can correct a resolution they did not mean.
385
+ if (c.provenance.match === 'close')
386
+ bits.push('closest to what you said');
387
+ return bits.join(' · ');
388
+ }
389
+ /**
390
+ * The address the person meant, or a question. `stepRef`/`toolId` place the question on the step that
391
+ * needs it; `argName` is what a resume will answer; `subject` is WHOSE tier this is.
392
+ */
393
+ async function rememberedChoice(lookups, where, value, candidates) {
394
+ if (!lookups.preferredChoice)
395
+ return null;
396
+ return lookups.preferredChoice({ word: value, capability: where.capabilityId ?? where.toolId, arg: where.argName }, candidates).catch(() => null);
397
+ }
398
+ export async function resolveParty(raw, lookups, where) {
399
+ const value = String(raw ?? '').trim();
400
+ if (isAddress(value)) {
401
+ lookups.onResolved?.({ arg: where.argName, raw: value, agent: value.toLowerCase() });
402
+ return value.toLowerCase();
403
+ }
404
+ // The role's word reads as a noun phrase ("being paid", "paying from"), which is right after "who is"
405
+ // and wrong after "should be": "which treasury should be being paid" is not a sentence anyone says.
406
+ const asVerb = (word) => word.replace(/^being /, '').replace(/^paying from$/, 'paid from');
407
+ const ask = (prompt, field, suggest, scope) => {
408
+ throw new InputRequired({ kind: 'data', stepRef: where.stepRef, toolId: where.toolId, prompt, fields: [field], ...(suggest ? { suggest } : {}), ...(scope ? { scope } : {}) });
409
+ };
410
+ if (!value)
411
+ ask(`Who is ${where.what}?`, { name: where.argName, label: where.what, type: 'text', required: true, hint: 'an agent name (alice.me) or address' });
412
+ // ── MEMORY FIRST (spec 358 W5) ────────────────────────────────────────────────────────────────
413
+ // A shorthand the owner DEFINED ("when I say alice, I mean alice2.treasury") resolves to what they said
414
+ // — before the directory, because the whole point of teaching it is that the general resolver got it
415
+ // wrong or ambiguous. It is not authority: it fills WHERE, and the mandate still decides. Exact-trigger
416
+ // only (memory.ts), and the resolved subject is announced as memory so the person sees WHY.
417
+ if (lookups.preferences) {
418
+ const pref = preferenceFor(await lookups.preferences().catch(() => []), value);
419
+ if (pref && isAddress(pref.subject)) {
420
+ lookups.onResolved?.({
421
+ arg: where.argName, raw: value, agent: pref.subject.toLowerCase(),
422
+ label: pref.subjectLabel ?? pref.subject,
423
+ hint: `remembered: you told me “${pref.saidAs ?? value}” means this${pref.learnedAt ? ` (${pref.learnedAt.slice(0, 10)})` : ''}`,
424
+ });
425
+ return pref.subject.toLowerCase();
426
+ }
427
+ }
428
+ // ── A PRONOUN MEANS WHO THEY JUST MEANT (spec 370 P7) ─────────────────────────────────────────────
429
+ // "Send him 2 USDC" after "send nathan 1 USDC": the resolver is handed the owner's own recent turns and
430
+ // takes the newest party that fits the pronoun and this role's kinds. Cited as memory, shown on the
431
+ // card before anything is signed; the mandate still decides.
432
+ if (lookups.recentParties && pronounOf(value)) {
433
+ const recalled = await lookups.recentParties().catch(() => []);
434
+ const hit = pronounRecall(value, recalled, where.types);
435
+ if (hit) {
436
+ lookups.onResolved?.({ arg: where.argName, raw: value, agent: hit.agent.toLowerCase(), label: hit.label ?? hit.agent, hint: `remembered from your last ask${hit.said ? ` (“${hit.said}”)` : ''}: “${hit.raw}”` });
437
+ return hit.agent.toLowerCase();
438
+ }
439
+ }
440
+ // ── THE PEOPLE THEY LIVE WITH, FIRST (spec 363 W4) ───────────────────────────────────────────────
441
+ //
442
+ // "Send sarah 20" means the Sarah in your house before it means one of four in a directory — that is
443
+ // how first names work, and it is also the more private reading: the household is the asker's OWN
444
+ // record (ADR-0025), so nothing leaves their tier and no directory learns who they asked about.
445
+ //
446
+ // The DECISION PLANE decides (`payment.recipient`): exactly one household member answering to the word
447
+ // IS the answer, and it is CITED — "they are in your household" — so a person can correct a resolution
448
+ // they did not expect. Two members with the same first name is ambiguity, and it falls through to the
449
+ // ordinary resolver rather than being settled by a coin toss.
450
+ //
451
+ // It never EXCLUDES anyone: somebody outside the household is simply not the first reading of a bare
452
+ // first name, and naming them in full still reaches them.
453
+ if (where.consults?.includes(PAYMENT_RECIPIENT.id) && where.subject && lookups.readSubjectRecord && !value.includes('.') && !isAddress(value)) {
454
+ const members = await householdMembers(where.subject, lookups).catch(() => []);
455
+ const named = members.filter((m) => matchesLabel(m, value));
456
+ const chosen = decide(PAYMENT_RECIPIENT, named.map((m) => ({ value: m, satisfies: [HOUSEHOLD_MEMBER_IRI] })));
457
+ // WHEN THE ARGUMENT WANTS AN ACCOUNT, WALK THE DECLARED CHAIN (spec 363 W3). `aphh:householdPayee`
458
+ // IS `householdMember ∘ primaryPayee` — the household says who they are, their own mark says where
459
+ // their money goes — and walking the axiom is what stops this file growing its own two-step beside
460
+ // the one the ontology already states. No chain, or nothing at the end of it: fall through to the
461
+ // ordinary resolution, which asks. It composes two preferences and no permission.
462
+ if (chosen && where.types?.includes('treasury')) {
463
+ const landed = await walkChain(HOUSEHOLD_PAYEE_IRI, where.subject, async (link, from) => {
464
+ if (link === HOUSEHOLD_MEMBER_IRI)
465
+ return from.toLowerCase() === where.subject.toLowerCase() ? [chosen.value.agent] : [];
466
+ // `ap:primaryPayee` — the account THEY marked, read from the public edge like any other payer's.
467
+ const marked = await (lookups.charteredAgents?.(from, 'treasury') ?? Promise.resolve([])).catch(() => []);
468
+ return marked.filter((c) => c.primary).map((c) => c.agent);
469
+ }).catch(() => []);
470
+ if (landed.length === 1) {
471
+ lookups.onResolved?.({
472
+ arg: where.argName, raw: value, agent: landed[0].toLowerCase(),
473
+ label: `${chosen.value.label ?? value}'s account`,
474
+ hint: chosen.value.kinWord ? `your ${chosen.value.kinWord}'s treasury` : 'their treasury',
475
+ because: `${chosen.because}, and it is the account they marked`, ruleId: chosen.ruleId, pointId: PAYMENT_RECIPIENT.id,
476
+ });
477
+ return landed[0].toLowerCase();
478
+ }
479
+ }
480
+ if (chosen) {
481
+ // THE VALUE RAIL (spec 373). When the argument wants an ACCOUNT, a household member is not the
482
+ // answer — she is who the money is FOR. This branch used to fall through to her, and on 2026-09-08
483
+ // it paid `carol.me`: the `householdPayee` chain landed on nothing because she had marked no
484
+ // account, and the person was returned as though that were the same thing. It is a question.
485
+ if (where.types?.length && !where.types.includes('me')) {
486
+ const who = chosen.value.label ?? value;
487
+ ask(`${who} is in your household, and money moves between treasuries — ${who} has not marked an account to be paid into. Which treasury should be paid?`, { name: where.argName, label: where.what, type: 'address', required: true, hint: `a treasury name (${String(who).toLowerCase().split(' ')[0]}.treasury) or its address — or ask ${who} to mark one` });
488
+ }
489
+ lookups.onResolved?.({
490
+ arg: where.argName, raw: value, agent: chosen.value.agent,
491
+ label: chosen.value.label ?? value,
492
+ hint: chosen.value.kinWord ? `your ${chosen.value.kinWord}` : 'in your household',
493
+ because: chosen.because, ruleId: chosen.ruleId, pointId: PAYMENT_RECIPIENT.id,
494
+ });
495
+ return chosen.value.agent;
496
+ }
497
+ }
498
+ const outcome = await resolveEntity(partyProviders(lookups), {
499
+ term: value, tiers: ['private'], ...(where.subject ? { subject: where.subject } : {}), limit: 8,
500
+ });
501
+ // ── WHAT KIND OF AGENT THIS ARGUMENT IS ──────────────────────────────────────────────────────────
502
+ // "Send money to nathan" and "send nathan a message" are the same word; the difference lives in the
503
+ // CAPABILITY, and the typed suffix (ADR-0061) is what makes it decidable. Tiers, in the order a person
504
+ // means them: the first type anything answers to wins.
505
+ //
506
+ // This narrows and never picks. Two treasuries called nathan is still a question, and a capability whose
507
+ // preferred types match nothing gets asked with everything that DID answer — "nathan has no treasury"
508
+ // is an answer, not a licence to quietly pay some other Nathan.
509
+ if (where.types?.length && (outcome.outcome === 'ambiguous' || outcome.outcome === 'certain')) {
510
+ const all = outcome.outcome === 'ambiguous' ? outcome.candidates : [outcome.candidate];
511
+ const suffix = (c) => (c.name ?? c.label ?? '').toLowerCase().split('.').pop() ?? '';
512
+ /** Ways the asker HOLDS that the gate refused, with the reason — collected as the tiers are tried. */
513
+ const heldButRefused = [];
514
+ for (const [rank, type] of where.types.entries()) {
515
+ const tier = all.filter((c) => suffix(c) === type);
516
+ // A SUBSTITUTION IS NOT A RESOLUTION. "Send alice 20 USDC" asks for her treasury; when nothing
517
+ // answers to one, paying her PERSON agent instead is a different destination reached silently — and
518
+ // a payment to the wrong address is not a thing anyone can undo. So for arguments that move value,
519
+ // dropping past the first-choice type is a question, with the reason said plainly.
520
+ //
521
+ // Only for money: a message falling from `.me` to `.org` is the same conversation with the same
522
+ // person's organization, and asking about it would be noise.
523
+ // NOT OF THIS TYPE — so ask what the ones we DID find OWN. "Send money to alice" names the person;
524
+ // her treasury is a thing she HOLDS, and the two are connected by a relationship, not by their
525
+ // names resembling each other. Resolve the person, then follow the link.
526
+ if (!tier.length && rank === 0) {
527
+ const lists = await Promise.all(all.map((c) => ownedAgentsOfType(c.agent, type, lookups, where.subject).catch(() => [])));
528
+ // A WAY THEY HOLD THAT DID NOT WORK travels with the lists, so the question below can name it
529
+ // rather than reporting "nothing called bob is a treasury" to somebody holding a way to reach him.
530
+ for (const l of lists)
531
+ heldButRefused.push(...(l.refusals ?? []));
532
+ const owned = lists.flat().filter((c, i, xs) => xs.findIndex((y) => y.agent === c.agent) === i);
533
+ if (owned.length === 1) {
534
+ const c = owned[0];
535
+ lookups.onResolved?.({ arg: where.argName, raw: value, agent: c.agent, label: c.label, hint: candidateHint(c), ...(ownerOf(c) ? { ownedBy: ownerOf(c) } : {}) });
536
+ return c.agent.toLowerCase();
537
+ }
538
+ if (owned.length > 1) {
539
+ // Several of theirs. Which one is theirs to say — a person may hold more than one treasury and
540
+ // nothing about the ask distinguishes them.
541
+ ask(`Which ${type} should be ${asVerb(where.what)}?`, {
542
+ name: where.argName, label: where.what, type: 'choice', required: true,
543
+ choices: owned.map((c) => ({ value: c.agent, label: c.label, hint: candidateHint(c) })),
544
+ allowOther: true,
545
+ hint: `“${value}” holds ${owned.length} ${type}s — pick the one you mean`,
546
+ });
547
+ }
548
+ }
549
+ if (tier.length && rank > 0 && VALUE_ARGS.has(where.argName)) {
550
+ // A WAY THEY HOLD THAT DID NOT WORK is the most useful thing this question can say. Without it a
551
+ // person who was given a way to reach somebody an hour ago is told "nothing called bob is a
552
+ // treasury" — true, and it hides the one fact they could act on.
553
+ ask(heldButRefused.length
554
+ ? `You hold a way to reach ${value}'s ${where.types[0]}, but it could not be used — ${heldButRefused[0]}. Who should be ${where.what}?`
555
+ : `Nothing called “${value}” is a ${where.types[0]}. Who should be ${where.what}?`, {
556
+ name: where.argName, label: where.what, type: 'choice', required: true,
557
+ choices: all.map((c) => ({ value: c.agent, label: c.label, hint: candidateHint(c) })),
558
+ // The right answer is very often NOT in this list — that is the whole reason we are asking —
559
+ // so the person must be able to type it. Telling them to "give it in full" beside a list they
560
+ // cannot add to is a dead end with instructions on it.
561
+ allowOther: true,
562
+ hint: `a ${where.types[0]} may exist under another name — give it in full (e.g. ${value}2.${where.types[0]}) to send there instead`,
563
+ }, {
564
+ // THE WAY OUT OF THE DEAD END. Their ${where.types[0]} may exist and simply be unlisted — that
565
+ // is a choice its owner made, and the answer is to ask them, not to guess harder. Offered as a
566
+ // follow-up the person can send, because they should not have to know the phrasing.
567
+ //
568
+ // It carries the AMOUNT when the ask named one, so the request records what this was for and
569
+ // the payment can be finished in one press when the answer comes back. Without it the person
570
+ // has to remember, days later, what they were trying to send and to whom.
571
+ label: `Ask ${value} for a way to reach their ${where.types[0]}`,
572
+ message: where.pendingAmount
573
+ ? `ask ${value} for a way to pay their ${where.types[0]} so I can send ${where.pendingAmount} usdc`
574
+ : `ask ${value} for a way to pay their ${where.types[0]}`,
575
+ });
576
+ }
577
+ if (tier.length === 1) {
578
+ const c = tier[0];
579
+ lookups.onResolved?.({ arg: where.argName, raw: value, agent: c.agent.toLowerCase(), label: c.label, hint: candidateHint(c), ...(ownerOf(c) ? { ownedBy: ownerOf(c) } : {}) });
580
+ return c.agent.toLowerCase();
581
+ }
582
+ if (tier.length > 1) {
583
+ // THE ONE THEY CONFIRMED FOR THIS, DURABLY (spec 385): the scoped preference outranks the rolling
584
+ // window, revalidated against these candidates; evidence, never a grant.
585
+ const remembered = await rememberedChoice(lookups, where, value, tier);
586
+ if (remembered) {
587
+ lookups.onResolved?.({ arg: where.argName, raw: value, agent: remembered.agent.toLowerCase(), label: remembered.label ?? remembered.agent, hint: `remembered: you chose “${remembered.label ?? value}” for this before` });
588
+ return remembered.agent.toLowerCase();
589
+ }
590
+ // THE ONE THEY CHOSE LAST TIME (spec 370 P7): the same words, settled on one of these before.
591
+ const before = lookups.recentParties ? chosenBefore(value, tier, await lookups.recentParties().catch(() => [])) : null;
592
+ if (before) {
593
+ lookups.onResolved?.({ arg: where.argName, raw: value, agent: before.agent.toLowerCase(), label: before.label ?? before.agent, hint: `remembered: the “${value}” you chose last time` });
594
+ return before.agent.toLowerCase();
595
+ }
596
+ ask(`Which “${value}” do you mean?`, {
597
+ name: where.argName, label: where.what, type: 'choice', required: true,
598
+ choices: tier.map((c) => ({ value: c.agent, label: c.label, hint: candidateHint(c) })),
599
+ allowOther: true,
600
+ hint: `${tier.length} of them are what ${where.what} has to be — pick one, or give a full name`,
601
+ }, undefined, { word: value, capability: where.capabilityId ?? where.toolId, arg: where.argName });
602
+ }
603
+ }
604
+ }
605
+ if (outcome.outcome === 'certain') {
606
+ // ONE match is still a decision, and the person never made it. Report what "nathan" became so the
607
+ // surface can show it before a signature, rather than after — a certain resolution is the case where
608
+ // nobody is asked anything, which is exactly when a wrong one goes unnoticed.
609
+ const c = outcome.candidate;
610
+ // AND ONE MATCH OF THE WRONG KIND IS NOT A MATCH (spec 373). The type loop above narrows, asks and
611
+ // follows ownership — and when every one of those comes up empty it fell through to HERE, which
612
+ // returned the candidate whatever it was. That is how "send carol 1 usdc" put a person's agent on a
613
+ // payment card: `carol.me` was the only thing called carol, and being the only one is not being a
614
+ // treasury. Certain about the wrong kind of thing is a question, not an answer.
615
+ // WHAT KIND IT CLAIMS TO BE — and only a real claim counts. A typed NAME's suffix is a claim
616
+ // (`alice.me`); so is a `kind` the source recorded. A bare label is not: "Missio Nexus" split at its
617
+ // last dot is "missio nexus", which is a name, not a kind, and reading it as one asked "which org should
618
+ // be the organization?" of the one organization called that (caught live, 2026-09-08).
619
+ const knownSuffix = (v) => { const sfx = (v ?? '').toLowerCase().split('.').pop() ?? ''; return v?.includes('.') && sfx in CLASS_FOR_SUFFIX ? sfx : ''; };
620
+ const kindOf = (k) => { const low = (k ?? '').toLowerCase(); if (!low)
621
+ return ''; if (low in CLASS_FOR_SUFFIX)
622
+ return low; const byClass = Object.entries(SUFFIX_FOR_CLASS).find(([iri]) => iri.toLowerCase().endsWith(`#${low}agent`) || iri.toLowerCase().endsWith(`#${low}`)); return byClass?.[1] ?? { person: 'me', organization: 'org', service: 'svc' }[low] ?? ''; };
623
+ const certainSuffix = knownSuffix(c.name) || kindOf(c.kind);
624
+ if (where.types?.length && certainSuffix && !where.types.includes(certainSuffix)) {
625
+ const want = where.types[0];
626
+ ask(`“${value}” is ${c.label ?? c.agent}, ${certainSuffix === 'me' ? 'a person' : `a ${certainSuffix}`}${VALUE_ARGS.has(where.argName) ? ', and money moves between treasuries' : ''} — which ${want} should be ${asVerb(where.what)}?`, {
627
+ name: where.argName, label: where.what, type: 'address', required: true,
628
+ hint: `a ${want} name (${value}.${want}) or its address — nothing of theirs answered to one`,
629
+ }, {
630
+ label: `Ask ${value} for a way to reach their ${want}`,
631
+ message: where.pendingAmount
632
+ ? `ask ${value} for a way to pay their ${want} so I can send ${where.pendingAmount} usdc`
633
+ : `ask ${value} for a way to pay their ${want}`,
634
+ });
635
+ }
636
+ lookups.onResolved?.({ arg: where.argName, raw: value, agent: c.agent.toLowerCase(), label: c.label, hint: candidateHint(c), ...(ownerOf(c) ? { ownedBy: ownerOf(c) } : {}) });
637
+ return c.agent.toLowerCase();
638
+ }
639
+ if (outcome.outcome === 'unknown') {
640
+ // Say where we looked. "I could not find them" without that leaves a person correcting the wrong thing.
641
+ const said = {
642
+ relationships: 'the agents you are linked to',
643
+ roster: 'the members of your organizations',
644
+ naming: 'the naming service',
645
+ };
646
+ const where_ = [...new Set(outcome.looked.map((l) => said[l.source] ?? l.source))].join(', ');
647
+ ask(`I could not find “${value}”. Which agent do you mean?`, {
648
+ name: where.argName, label: where.what, type: 'text', required: true,
649
+ hint: `nothing in ${where_ || 'your own agents'} answers to “${value}” — give the full name (e.g. ${value}.me) or the address`,
650
+ });
651
+ }
652
+ // SEVERAL. Never pick: the person is the only one who knows which one they meant.
653
+ //
654
+ // And a list of four things all called "Nathan" is not a choice. Each one carries what tells it APART —
655
+ // its full name, what KIND of agent it is, its address, and WHERE we know it from — because the person
656
+ // is about to authorize something against one of them, and "the second Nathan" is not a thing anyone
657
+ // knows about themselves. There is deliberately no default and no highlighted best: ranking these would
658
+ // need a score, and a score is the thing this resolver refuses to invent (spec 353 §3, ADR-0013).
659
+ const candidates = outcome.outcome === 'ambiguous' ? outcome.candidates : [];
660
+ // Nothing of the RIGHT KIND, when a kind was asked for: say so, and show what does exist. A person who
661
+ // hears "nathan has no treasury" knows what to do next; one who is silently offered nathan.me for a
662
+ // payment does not.
663
+ const wanted = where.types?.length ? `nothing called “${value}” is ${where.types[0] === 'me' ? 'a person' : `a ${where.types[0]}`} — ` : '';
664
+ if (candidates.length > 1) {
665
+ const remembered = await rememberedChoice(lookups, where, value, candidates);
666
+ if (remembered) {
667
+ lookups.onResolved?.({ arg: where.argName, raw: value, agent: remembered.agent.toLowerCase(), label: remembered.label ?? remembered.agent, hint: `remembered: you chose “${remembered.label ?? value}” for this before` });
668
+ return remembered.agent.toLowerCase();
669
+ }
670
+ if (lookups.recentParties) {
671
+ const before = chosenBefore(value, candidates, await lookups.recentParties().catch(() => []));
672
+ if (before) {
673
+ lookups.onResolved?.({ arg: where.argName, raw: value, agent: before.agent.toLowerCase(), label: before.label ?? before.agent, hint: `remembered: the “${value}” you chose last time` });
674
+ return before.agent.toLowerCase();
675
+ }
676
+ }
677
+ }
678
+ ask(`Which “${value}” do you mean?`, {
679
+ name: where.argName, label: where.what, type: 'choice', required: true,
680
+ choices: candidates.map((c) => ({ value: c.agent, label: c.label, hint: candidateHint(c) })),
681
+ // Someone they know may not be among these, and knowing the full name is a real answer.
682
+ allowOther: true,
683
+ hint: `${wanted}${candidates.length} agents you know answer to “${value}” — pick one, or give a full name`,
684
+ }, undefined, { word: value, capability: where.capabilityId ?? where.toolId, arg: where.argName });
685
+ throw new Error('unreachable');
686
+ }
687
+ //# sourceMappingURL=party-resolution.js.map