@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,28 @@
1
+ import type { ToolSpec, ToolInvoker } from '@agenticprimitives/orchestration';
2
+ import type { Address } from '@agenticprimitives/types';
3
+ import { type StandingDeps } from './standing.js';
4
+ export declare const INVITATIONS_LIST_TOOL: ToolSpec;
5
+ export interface InvitationsDeps extends StandingDeps {
6
+ survey?: (subject: string) => Promise<Array<{
7
+ recordType: string;
8
+ updatedAt?: string;
9
+ }>>;
10
+ readRecords?: (subject: string, recordTypes: string[]) => Promise<Record<string, unknown>>;
11
+ nameOf?: (address: string) => Promise<string | null>;
12
+ }
13
+ export type InvitationStatus = 'waiting' | 'accepted' | 'declined' | 'expired';
14
+ export interface InvitationRow {
15
+ kind: 'email' | 'agent';
16
+ status: InvitationStatus;
17
+ /** The agent invited (for an emailed invitation: the one their Home would deploy, or did). */
18
+ agent?: string;
19
+ name?: string | null;
20
+ /** For an emailed invitation: the hash the record keeps — never the address itself. */
21
+ emailHash?: string;
22
+ invitedBy?: string;
23
+ createdAt?: number;
24
+ expiresAt?: number;
25
+ answeredAt?: number;
26
+ }
27
+ export declare function invitationsListInvoker(deps: InvitationsDeps, addressee: Address, principal?: Address): ToolInvoker;
28
+ //# sourceMappingURL=invitations-read.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"invitations-read.d.ts","sourceRoot":"","sources":["../src/invitations-read.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,kCAAkC,CAAC;AAC9E,OAAO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import { deriveStanding } from './standing.js';
2
+ import { subjectOfRead } from './self-only.js';
3
+ import { rosterRows } from './directory-rows.js';
4
+ export const INVITATIONS_LIST_TOOL = {
5
+ id: 'organization.invitations.list',
6
+ description: 'ANSWERS A QUESTION about INVITATIONS to an organization, team, circle or church: which invitations are '
7
+ + 'outstanding, whether someone has accepted, is still waiting, declined ("not interested"), or the invitation '
8
+ + 'expired. Use for "did carol accept", "status of the invitation to bob@example.org", "who has not joined yet", '
9
+ + '"any invitations declined". NOT the member list (organization.membership.list) and NOT an act. '
10
+ + 'Args: org (the organization — name or address; omit for the agent being asked), who (optional — an email, '
11
+ + 'a name or an address to look for).',
12
+ inputSchema: {
13
+ type: 'object',
14
+ properties: {
15
+ org: { type: 'string', description: 'The organization, EXACTLY as the ask names it — a name (calvary.org) or an address. Never leave a named one out; omit it only when an organization is asked about itself.' },
16
+ who: { type: 'string', description: 'Optional: the invitee — an email address, an agent name, or an address.' },
17
+ },
18
+ },
19
+ subject: 'org',
20
+ establishes: 'lookup',
21
+ };
22
+ const lc = (s) => s.toLowerCase();
23
+ const isAddr = (v) => typeof v === 'string' && /^0x[0-9a-f]{40}$/i.test(v);
24
+ async function sha256Hex(s) {
25
+ const buf = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(s));
26
+ return [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, '0')).join('');
27
+ }
28
+ export function invitationsListInvoker(deps, addressee, principal) {
29
+ return async (_toolId, args, ctx) => {
30
+ // Spec 366 R3 — only at its own subject: no organization at a person's own agent asks, another
31
+ // agent's organization refuses; the other agent answers for its own invitations.
32
+ const sub = subjectOfRead(args, addressee, principal, { toolId: _toolId, arg: 'org', noun: 'organization', stepRef: ctx?.step?.id, selfKind: deps.addresseeKind });
33
+ if ('refused' in sub)
34
+ return { count: 0, invitations: [], refused: sub.refused };
35
+ const org = sub.subject;
36
+ const who = String(args.who ?? '').trim().toLowerCase();
37
+ if (!principal)
38
+ return { count: 0, invitations: [], refused: 'this agent does not know who is asking' };
39
+ const standing = await deriveStanding(deps, { principal, subject: org }).catch(() => null);
40
+ if (!standing || standing.relation === 'none') {
41
+ return { count: 0, invitations: [], refused: `invitations are private, and ${standing?.because ?? 'this agent cannot read your links'} — only someone who belongs there can see them` };
42
+ }
43
+ if (!deps.survey || !deps.readRecords || !deps.readSubjectRecord)
44
+ return { count: 0, invitations: [], refused: 'this agent cannot read the organization’s invitations' };
45
+ const inventory = await deps.survey(org).catch(() => []);
46
+ const keys = inventory.map((r) => r.recordType);
47
+ const inviteKeys = keys.filter((k) => k.startsWith('org.invite:')).slice(0, 200);
48
+ const memberKeys = new Set(keys.filter((k) => k.startsWith('org.membership:member:')).map((k) => lc(k.slice('org.membership:member:'.length))));
49
+ const bodies = inviteKeys.length ? await deps.readRecords(org, inviteKeys).catch(() => ({})) : {};
50
+ const listed = new Set(rosterRows(await deps.readSubjectRecord(org, 'directory.data').catch(() => null)).map((r) => lc(r.agent)));
51
+ const joined = (agent) => memberKeys.has(lc(agent)) || listed.has(lc(agent));
52
+ const now = Date.now();
53
+ const rows = [];
54
+ for (const k of inviteKeys) {
55
+ const rec = (bodies[k] ?? null);
56
+ if (!rec || typeof rec !== 'object')
57
+ continue;
58
+ if (k.startsWith('org.invite:agent:')) {
59
+ const agent = lc(k.slice('org.invite:agent:'.length));
60
+ if (!isAddr(agent))
61
+ continue;
62
+ const status = rec.status === 'declined' ? 'declined' : joined(agent) ? 'accepted' : 'waiting';
63
+ rows.push({ kind: 'agent', status, agent, name: (typeof rec.displayName === 'string' ? rec.displayName : null), ...(typeof rec.invitedBy === 'string' ? { invitedBy: rec.invitedBy } : {}), ...(typeof rec.createdAt === 'number' ? { createdAt: rec.createdAt } : {}), ...(typeof rec.declinedAt === 'number' ? { answeredAt: rec.declinedAt } : {}) });
64
+ }
65
+ else {
66
+ const delegate = lc(String(rec.memberAccessDelegation?.delegate ?? rec.agent ?? ''));
67
+ const agent = isAddr(delegate) ? delegate : undefined;
68
+ const expired = typeof rec.expiresAt === 'number' && rec.expiresAt < now && rec.status !== 'redeemed';
69
+ const status = rec.status === 'declined' ? 'declined' : rec.status === 'redeemed' || (agent && joined(agent)) ? 'accepted' : expired ? 'expired' : 'waiting';
70
+ rows.push({ kind: 'email', status, ...(agent ? { agent } : {}), ...(typeof rec.emailHash === 'string' ? { emailHash: rec.emailHash } : {}), ...(typeof rec.invitedBy === 'string' ? { invitedBy: rec.invitedBy } : {}), ...(typeof rec.createdAt === 'number' ? { createdAt: rec.createdAt } : {}), ...(typeof rec.expiresAt === 'number' ? { expiresAt: rec.expiresAt } : {}), ...(typeof (rec.declinedAt ?? rec.redeemedAt) === 'number' ? { answeredAt: (rec.declinedAt ?? rec.redeemedAt) } : {}) });
71
+ }
72
+ }
73
+ // Names, best-effort — an invitee with an agent is named as the estate knows them.
74
+ if (deps.nameOf)
75
+ await Promise.all(rows.filter((r) => r.agent && !r.name).map(async (r) => { r.name = (await deps.nameOf(r.agent).catch(() => null)) ?? null; }));
76
+ // WHO: an email is matched by its hash (the record never held the address), a name or address by the agent.
77
+ let chosen = rows;
78
+ if (who) {
79
+ const hash = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(who) ? await sha256Hex(who) : null;
80
+ chosen = rows.filter((r) => (hash && r.emailHash === hash) || (isAddr(who) && r.agent === lc(who)) || (r.name && lc(r.name) === who) || (r.name && lc(r.name).split('.')[0] === who));
81
+ }
82
+ const byStatus = {};
83
+ for (const r of chosen)
84
+ byStatus[r.status] = (byStatus[r.status] ?? 0) + 1;
85
+ return {
86
+ org, yourStanding: standing.relation, count: chosen.length, invitations: chosen, byStatus,
87
+ note: who && !chosen.length
88
+ ? `no invitation matching “${who}” is recorded for this organization — say so; do not infer that they were never invited by another route`
89
+ : 'answer per invitation: WHO (name if known, else the address; an emailed invitation with no agent yet is "by email") and its STATUS — waiting (not yet joined), accepted (joined), declined (they said they are not interested), or expired. Never call a waiting invitation a membership.',
90
+ };
91
+ };
92
+ }
93
+ //# sourceMappingURL=invitations-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AC,MAAM,CAAC,MAAM;gBACzB,CAAC,CAAC,2BAA2B,GAAG,0GAA0G;gBAC1I,CAAC,CAAC,2RAA2R;SAChS,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,24 @@
1
+ import type { ToolSpec, ToolInvoker } from '@agenticprimitives/orchestration';
2
+ import type { StructuredCall } from './structured-call.js';
3
+ import type { DiscoveryFetch } from './ask-discovery.js';
4
+ export declare const KB_QUESTION_TOOL: ToolSpec;
5
+ export interface KbQuestionDeps {
6
+ fetchDiscovery: DiscoveryFetch;
7
+ /** The one model call (see `structured-call.ts`). Absent ⇒ the tool is not offered. */
8
+ call?: StructuredCall;
9
+ }
10
+ /** Offered ONLY when a model is configured. A tool that silently degrades to a keyword search is a tool
11
+ * that answers a different question than the one it advertises (ADR-0013). */
12
+ export declare function kbQuestionAvailable(deps: {
13
+ call?: StructuredCall;
14
+ }): boolean;
15
+ /**
16
+ * Ask the knowledge base a question: ground → propose → validate at the endpoint → (one correction) → answer.
17
+ *
18
+ * Every outcome is REPORTED, never softened. A refusal after the correction comes back as a refusal with
19
+ * both queries; an empty graph comes back as empty with the query that produced it. Neither falls through
20
+ * to a keyword search — "nothing matches" and "I looked somewhere else instead" are different answers, and
21
+ * a tool that quietly swaps one for the other cannot be trusted with either (ADR-0013).
22
+ */
23
+ export declare function kbQuestionInvoker(deps: KbQuestionDeps): ToolInvoker;
24
+ //# sourceMappingURL=kb-question.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"kb-question.d.ts","sourceRoot":"","sources":["../src/kb-question.ts"],"names":[],"mappings":"AAyBA,OAAO,KAAK,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,kCAAkC,CAAC;AAC9E,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAEzD,eAAO,MAAM,gBAAgB,EAAE,QAgB9B,CAAC;AAEF,MAAM,WAAW,cAAc;IAC7B,cAAc,EAAE,cAAc,CAAC;IAC/B,uFAAuF;IACvF,IAAI,CAAC,EAAE,cAAc,CAAC;CACvB;AAED;+EAC+E;AAC/E,wBAAgB,mBAAmB,CAAC,IAAI,EAAE;IAAE,IAAI,CAAC,EAAE,cAAc,CAAA;CAAE,GAAG,OAAO,CAE5E;AAoFD;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,cAAc,GAAG,WAAW,CA+CnE"}
@@ -0,0 +1,139 @@
1
+ export const KB_QUESTION_TOOL = {
2
+ id: 'kb.question',
3
+ description: 'QUERIES THE PUBLIC DIRECTORY DIRECTLY to answer a question about it. USE THIS FOR ANY QUESTION ABOUT A '
4
+ + 'KIND OR A GROUP — "what organizations are out there", "how many teams are there", "list the people", '
5
+ + '"which agents have X", "who operates Y" — and for anything that counts, lists, filters or relates. '
6
+ + 'find_agents cannot answer those: it matches search words against NAMES, so asking it for '
7
+ + '"organizations" returns nothing even when the directory holds dozens. Use find_agents only when the '
8
+ + 'ask NAMES a specific thing to look up. '
9
+ + 'It reads PUBLIC data only — never membership rosters, vault records or private relationships. '
10
+ + 'Args: question (the question, in plain words).',
11
+ inputSchema: {
12
+ type: 'object',
13
+ properties: { question: { type: 'string', description: 'The question to answer from the public directory, in plain words.' } },
14
+ required: ['question'],
15
+ },
16
+ };
17
+ /** Offered ONLY when a model is configured. A tool that silently degrades to a keyword search is a tool
18
+ * that answers a different question than the one it advertises (ADR-0013). */
19
+ export function kbQuestionAvailable(deps) {
20
+ return !!deps.call;
21
+ }
22
+ async function discovery(fetchDiscovery, path, init) {
23
+ const res = await fetchDiscovery(path, init);
24
+ if (!res)
25
+ throw new Error('the public agent directory is not reachable from this agent (no discovery binding)');
26
+ // A REFUSAL IS NOT A TRANSPORT FAILURE. The endpoint says why it will not run a query, and that sentence
27
+ // is the one thing that lets a second attempt be better than the first.
28
+ const body = (await res.json().catch(() => null));
29
+ if (!body)
30
+ throw new Error(`the public agent directory returned ${res.status}`);
31
+ return body;
32
+ }
33
+ /** The grounding, as the model sees it: terms that HAVE DATA, with how much. */
34
+ function groundingPrompt(schema) {
35
+ const term = (t) => ` <${t.iri}> (${t.count})${t.label ? ` — ${t.label}` : ''}${t.comment ? `: ${t.comment}` : ''}`;
36
+ return [
37
+ 'You write SPARQL CONSTRUCT queries against a public agent directory (an RDF store).',
38
+ '',
39
+ 'THE ONLY VOCABULARY THIS STORE HAS. The number is how many instances/uses exist — a term with data',
40
+ 'behind it. Any term not listed here does not exist here and will match nothing. Never invent an IRI,',
41
+ 'never use a vocabulary you know from elsewhere, and never guess a predicate because it "ought to"',
42
+ 'be called that.',
43
+ '',
44
+ 'CLASSES:',
45
+ ...schema.classes.map(term),
46
+ '',
47
+ 'PROPERTIES:',
48
+ ...schema.properties.map(term),
49
+ '',
50
+ 'NOTES:',
51
+ ...schema.notes.map((n) => ` - ${n}`),
52
+ '',
53
+ 'WORKED EXAMPLES:',
54
+ ...schema.examples.flatMap((e) => [` Q: ${e.question}`, ...e.query.split('\n').map((l) => ` ${l}`), '']),
55
+ 'RULES:',
56
+ ' - CONSTRUCT only. Not SELECT, not ASK, not DESCRIBE.',
57
+ ' - Always state a LIMIT.',
58
+ ' - No SERVICE, no GRAPH, no FROM — they are refused.',
59
+ ' - Write the question in the vocabulary. Do NOT embed the user\'s sentence in the query.',
60
+ ' - The CONSTRUCT template must include enough to answer: the subject, its name, and the properties asked about.',
61
+ ' - If the question cannot be answered from the vocabulary above, say so in `interpretation` and',
62
+ ' return an empty query. A query over terms that do not exist is worse than no answer.',
63
+ ].join('\n');
64
+ }
65
+ const PROPOSE_TOOL = {
66
+ name: 'propose_query',
67
+ description: 'Propose the CONSTRUCT query that answers the question, and state how you read the question.',
68
+ input_schema: {
69
+ type: 'object',
70
+ properties: {
71
+ interpretation: { type: 'string', description: 'What you understood the question to be asking, in one sentence.' },
72
+ query: { type: 'string', description: 'The SPARQL CONSTRUCT query. Empty string if the vocabulary cannot answer it.' },
73
+ },
74
+ required: ['interpretation', 'query'],
75
+ },
76
+ };
77
+ async function propose(call, system, question, priorRefusal) {
78
+ const messages = [{ role: 'user', content: question }];
79
+ if (priorRefusal) {
80
+ // THE ENDPOINT'S OWN WORDS go back, not a paraphrase. It knows why it refused; this loop does not.
81
+ messages.push({ role: 'assistant', content: priorRefusal.query }, { role: 'user', content: `That query was refused: ${priorRefusal.refusal}\nWrite one that the endpoint will run, answering the same question.` });
82
+ }
83
+ const input = (await call({ system, messages, tool: PROPOSE_TOOL, maxTokens: 1500 }));
84
+ return { interpretation: String(input.interpretation ?? ''), query: String(input.query ?? '').trim() };
85
+ }
86
+ /**
87
+ * Ask the knowledge base a question: ground → propose → validate at the endpoint → (one correction) → answer.
88
+ *
89
+ * Every outcome is REPORTED, never softened. A refusal after the correction comes back as a refusal with
90
+ * both queries; an empty graph comes back as empty with the query that produced it. Neither falls through
91
+ * to a keyword search — "nothing matches" and "I looked somewhere else instead" are different answers, and
92
+ * a tool that quietly swaps one for the other cannot be trusted with either (ADR-0013).
93
+ */
94
+ export function kbQuestionInvoker(deps) {
95
+ return async (_toolId, args) => {
96
+ const question = String(args.question ?? '').trim();
97
+ if (!question)
98
+ return { refused: 'ask a question' };
99
+ if (!deps.call)
100
+ throw new Error('kb.question needs a configured model on this agent');
101
+ const schema = (await discovery(deps.fetchDiscovery, '/kb/schema'));
102
+ const system = groundingPrompt(schema);
103
+ const run = async (q) => (await discovery(deps.fetchDiscovery, '/kb/construct', {
104
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ query: q }),
105
+ }));
106
+ let proposal = await propose(deps.call, system, question);
107
+ if (!proposal.query) {
108
+ // The model said the vocabulary cannot answer it. That is an answer, and a better one than a query
109
+ // over terms that do not exist.
110
+ return { answered: false, interpretation: proposal.interpretation, reason: 'the directory does not hold what this question needs' };
111
+ }
112
+ let result = await run(proposal.query);
113
+ if (!result.ok) {
114
+ const first = { query: proposal.query, refusal: String(result.error ?? 'refused') };
115
+ proposal = await propose(deps.call, system, question, first);
116
+ result = proposal.query ? await run(proposal.query) : { ok: false, error: 'no second query proposed' };
117
+ if (!result.ok) {
118
+ return {
119
+ answered: false, interpretation: proposal.interpretation,
120
+ reason: `the directory refused the query: ${String(result.error ?? 'refused')}`,
121
+ attempted: [first.query, proposal.query].filter(Boolean),
122
+ };
123
+ }
124
+ }
125
+ // 357 W4 — the answer is framed: `{ @context, @graph }`. Read the graph; tolerate the older bare
126
+ // array so a mixed-deploy window does not blank an answer.
127
+ const jl = result.jsonld;
128
+ const graph = Array.isArray(jl) ? jl : Array.isArray(jl?.['@graph']) ? jl['@graph'] : [];
129
+ return {
130
+ answered: true,
131
+ interpretation: proposal.interpretation,
132
+ // The query travels with the answer (spec 357 §4). An answer whose query nobody can inspect is a claim.
133
+ query: result.query,
134
+ count: graph.length,
135
+ results: graph.slice(0, 50),
136
+ };
137
+ };
138
+ }
139
+ //# sourceMappingURL=kb-question.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"kb-question.js","sourceRoot":"","sources":["../src/kb-question.ts"],"names":[],"mappings":"AA6BA,MAAM,CAAC,MAAM,gBAAgB,GAAa;IACxC,EAAE,EAAE,aAAa;IACjB,WAAW,EACT,yGAAyG;UACvG,uGAAuG;UACvG,qGAAqG;UACrG,2FAA2F;UAC3F,sGAAsG;UACtG,yCAAyC;UACzC,gGAAgG;UAChG,gDAAgD;IACpD,WAAW,EAAE;QACX,IAAI,EAAE,QAAQ;QACd,UAAU,EAAE,EAAE,QAAQ,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,mEAAmE,EAAE,EAAE;QAC9H,QAAQ,EAAE,CAAC,UAAU,CAAC;KACvB;CACF,CAAC;AAQF;+EAC+E;AAC/E,MAAM,UAAU,mBAAmB,CAAC,IAA+B;IACjE,OAAO,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC;AACrB,CAAC;AASD,KAAK,UAAU,SAAS,CAAC,cAA8B,EAAE,I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,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,EAAE,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,QAAQ,CAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC1F,OAAO;YACL,QAAQ,EAAE,IAAI;YACd,cAAc,EAAE,QAAQ,CAAC,cAAc;YACvC,wGAAwG;YACxG,KAAK,EAAE,MAAM,CAAC,KAAK;YACnB,KAAK,EAAE,KAAK,CAAC,MAAM;YACnB,OAAO,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC;SAC5B,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,37 @@
1
+ import type { ToolSpec, ToolInvoker } from '@agenticprimitives/orchestration';
2
+ import type { Address } from '@agenticprimitives/types';
3
+ import { type StandingDeps } from './standing.js';
4
+ export declare const MEMBERSHIP_LIST_TOOL: ToolSpec;
5
+ export interface MembershipDeps extends StandingDeps {
6
+ /** REVERSE: the public directory name for an address (discovery, ADR-0040 facts). An invited member's
7
+ * row carries an address and no display name — the composer then wrote sentences ABOUT the missing
8
+ * names instead of answering with the members. Best-effort, read-only, never required. */
9
+ nameOf?: (address: string) => Promise<string | null>;
10
+ /** The org's own record INVENTORY (spec 356 §2.5) — how the invitation records are found without
11
+ * guessing member addresses. Absent ⇒ listings only, which hides everyone who joined by invite. */
12
+ survey?: (subject: string) => Promise<Array<{
13
+ recordType: string;
14
+ updatedAt?: string;
15
+ }>>;
16
+ /** Read those invitation records, one batched call. */
17
+ readRecords?: (subject: string, recordTypes: string[]) => Promise<Record<string, unknown>>;
18
+ /** The roster read, WITH its reason. Three states a bare `null` cannot tell apart: the organization
19
+ * never enabled its own storage (permanent, and someone can act on it), the read failed (transient),
20
+ * and the roster is genuinely empty. Reporting the first as the second sent people to retry something
21
+ * that will never start working. */
22
+ readSubjectRecordStatus?: (subject: string, recordType: string) => Promise<{
23
+ ok: boolean;
24
+ needsEnable?: boolean;
25
+ data: unknown;
26
+ error?: string;
27
+ }>;
28
+ }
29
+ /**
30
+ * The roster of an organization the asker is part of.
31
+ *
32
+ * Returns the members as the org itself records them. It does NOT fall back to a public search when the
33
+ * private read is empty: an organization with an empty roster and one this agent may not read are
34
+ * different answers, and blurring them is how a private tier stops meaning anything (ADR-0013).
35
+ */
36
+ export declare function membershipListInvoker(deps: MembershipDeps, addressee: Address, principal?: Address): ToolInvoker;
37
+ //# sourceMappingURL=membership-read.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"membership-read.d.ts","sourceRoot":"","sources":["../src/membership-read.ts"],"names":[],"mappings":"AAcA,OAAO,KAAK,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,kCAAkC,CAAC;AAC9E,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,0BAA0B,CAAC;AACxD,OAAO,EAAkB,KAAK,YAAY,EAAE,MAAM,eAAe,CAAC;AAIlE,eAAO,MAAM,oBAAoB,EAAE,QAkBlC,CAAC;AAIF,MAAM,WAAW,cAAe,SAAQ,YAAY;IAClD;;+FAE2F;IAC3F,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;IACrD;wGACoG;IACpG,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC,KAAK,CAAC;QAAE,UAAU,EAAE,MAAM,CAAC;QAAC,SAAS,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC,CAAC;IACzF,uDAAuD;IACvD,WAAW,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,KAAK,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;IAC3F;;;yCAGqC;IACrC,uBAAuB,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,KAAK,OAAO,CAAC;QAAE,EAAE,EAAE,OAAO,CAAC;QAAC,WAAW,CAAC,EAAE,OAAO,CAAC;QAAC,IAAI,EAAE,OAAO,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;CACnJ;AAED;;;;;;GAMG;AACH,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,cAAc,EAAE,SAAS,EAAE,OAAO,EAAE,SAAS,CAAC,EAAE,OAAO,GAAG,WAAW,CA6GhH"}
@@ -0,0 +1,143 @@
1
+ import { deriveStanding } from './standing.js';
2
+ import { subjectOfRead } from './self-only.js';
3
+ import { rosterRows, invitedMemberRows, membershipRows, mergeRoster } from './directory-rows.js';
4
+ export const MEMBERSHIP_LIST_TOOL = {
5
+ id: 'organization.membership.list',
6
+ description: 'ANSWERS A QUESTION: who belongs to an organization, team, circle or church — its members. Use this '
7
+ + 'whenever the ask is about members, membership, "who is in", "who belongs to" or a roster. The public '
8
+ + 'directory does NOT contain members, so it is never the right tool for this. '
9
+ + 'Args: org (the organization\'s name or address, exactly as the ask says it — always carried when the ask names one).',
10
+ inputSchema: {
11
+ type: 'object',
12
+ properties: { org: { type: 'string', description: 'The organization, EXACTLY as the ask names it — a name (calvary.org, alice-home-church.impact) or an address. Never invent one and never leave a named one out; omit it only when an organization is asked about itself.' } },
13
+ },
14
+ // Spec 358 W4 — this result ENUMERATES the org's members (`members[].agent`), which is what lets a
15
+ // plan fan out over it ("pay each member…"): a bounded, owner-recorded set the organization itself
16
+ // answers for. The relation is the T-box's, and the plan-shapes binding caps the fan-out.
17
+ enumerates: { relation: 'https://agenticprimitives.dev/ns/org#memberAgent' },
18
+ // Spec 366 — the organization ANSWERS for its own roster. Asked at a person's agent about another
19
+ // organization, the step is routed to that organization's agent; asked at the organization, it runs here.
20
+ subject: 'org',
21
+ };
22
+ /**
23
+ * The roster of an organization the asker is part of.
24
+ *
25
+ * Returns the members as the org itself records them. It does NOT fall back to a public search when the
26
+ * private read is empty: an organization with an empty roster and one this agent may not read are
27
+ * different answers, and blurring them is how a private tier stops meaning anything (ADR-0013).
28
+ */
29
+ export function membershipListInvoker(deps, addressee, principal) {
30
+ return async (_toolId, args, ctx) => {
31
+ // THE ORG ARRIVES RESOLVED. `org` is a declared party of this capability (`PARTY_ROLES`), so the
32
+ // harness has already turned the person's words into an address in THEIR private tier — or asked.
33
+ // What reaches this invoker is an address, or nothing (= the agent being asked). A name that still
34
+ // reaches here is refused BY NAME: the old behaviour here was `resolveName(raw) ?? addressee`, and
35
+ // that fallback is exactly how "how many members are in Missio Nexus" read the asker's own roster.
36
+ // And it runs only at its own subject (spec 366 R3, `subjectOfRead`): no organization at a person's
37
+ // own agent is a question, another agent's organization is a refusal — never a local read.
38
+ const sub = subjectOfRead(args, addressee, principal, { toolId: _toolId, arg: 'org', noun: 'organization', stepRef: ctx?.step?.id, selfKind: deps.addresseeKind });
39
+ if ('refused' in sub)
40
+ return { members: [], count: 0, refused: sub.refused };
41
+ const org = sub.subject;
42
+ if (!principal)
43
+ return { members: [], count: 0, refused: 'this agent does not know who is asking' };
44
+ const standing = await deriveStanding(deps, { principal, subject: org }).catch(() => null);
45
+ if (!standing || standing.relation === 'none') {
46
+ return {
47
+ members: [], count: 0,
48
+ refused: `membership is private, and ${standing?.because ?? 'this agent cannot read your links'} — only someone who belongs there can see the roster`,
49
+ };
50
+ }
51
+ if (!deps.readSubjectRecord)
52
+ return { members: [], count: 0, refused: 'this agent cannot read the roster' };
53
+ let doc = null;
54
+ if (deps.readSubjectRecordStatus) {
55
+ const r = await deps.readSubjectRecordStatus(org, 'directory.data').catch(() => ({ ok: false, data: null }));
56
+ if (r.needsEnable) {
57
+ return {
58
+ members: [], count: 0,
59
+ refused: 'this organization has no storage of its own yet, so it keeps no roster — a steward turns that on once at its Home, and the members list becomes readable here. Until then there is nothing to read, rather than something that failed.',
60
+ };
61
+ }
62
+ if (!r.ok)
63
+ return { members: [], count: 0, refused: 'the roster could not be read just now' };
64
+ doc = r.data;
65
+ }
66
+ else {
67
+ doc = await deps.readSubjectRecord(org, 'directory.data').catch(() => null);
68
+ // Unreadable is not empty. Saying "no members" here would invent an answer.
69
+ if (doc === null)
70
+ return { members: [], count: 0, refused: 'the roster could not be read just now' };
71
+ }
72
+ // ONE PARSER (`directory-rows.ts`). This read `doc.listings`, which is `undefined` for the ARRAY the
73
+ // DO actually writes — so it answered "0 members" for every organization whatever its roster held,
74
+ // and zero is plausible enough for a young org that nobody questioned it.
75
+ const published = rosterRows(doc);
76
+ // AND THE ORG'S OWN INVITATIONS. A listing is self-published; somebody who joined by invitation and
77
+ // never published one is a real member with no listing. The organization's `org.invite:agent:<sa>`
78
+ // records name them, in its own vault, written when it admitted them.
79
+ //
80
+ // INERT TODAY, AND DELIBERATELY LEFT IN PLACE. The survey rides the organization's OWN DO grant,
81
+ // whose per-record scope does not cover `org.invite:*` — so this finds nothing on the live estate
82
+ // even though the records are there (verified: 123 records in Missio Nexus's vault, one of them an
83
+ // invite, and the survey returns 122). That is per-record scope working, not failing. Reading them
84
+ // needs the STEWARD's delegation presented, the way the Home's own reader does it — see finding
85
+ // ORG-MEM-1. This runs the moment a caller supplies a survey that can see them, and asserts nothing
86
+ // in the meantime.
87
+ let invited = [];
88
+ if (deps.survey && deps.readRecords) {
89
+ const inventory = await deps.survey(org).catch(() => []);
90
+ const keys = inventory.map((r) => r.recordType);
91
+ // THE ROSTER PROPER first: the organization's own membership records (spec 325). These are inside
92
+ // the `vault:org.membership:*` scope its grant already carries, so unlike the invitations they are
93
+ // actually readable by the organization's own agent.
94
+ const memberKeys = keys.filter((rt) => rt.startsWith('org.membership:member:')).slice(0, 200);
95
+ const inviteKeys = keys.filter((rt) => rt.startsWith('org.invite:agent:')).slice(0, 100);
96
+ const wanted = [...memberKeys, ...inviteKeys];
97
+ if (wanted.length) {
98
+ const bodies = await deps.readRecords(org, wanted).catch(() => ({}));
99
+ invited = [...invitedMemberRows(inviteKeys, bodies), ...membershipRows(memberKeys, bodies)];
100
+ }
101
+ }
102
+ // A DECLINED invitation is an answer, not a member: it leaves the roster and lives in
103
+ // organization.invitations.list, where "who said no" is the question.
104
+ const members = mergeRoster(published, invited.filter((r) => r.status !== 'declined'))
105
+ .map((l) => ({
106
+ agent: l.agent,
107
+ name: l.name,
108
+ via: l.via,
109
+ ...(l.role ? { role: l.role } : {}),
110
+ ...(l.kin ? { kin: l.kin } : {}),
111
+ }))
112
+ .filter((m) => /^0x[0-9a-f]{40}$/.test(m.agent));
113
+ // NAME THE PEOPLE. An invitation row records an address; the public directory usually knows the
114
+ // name the estate calls that agent (nathan.me), and an answer that says "0x1dba…" — or worse,
115
+ // dwells on the names it does not have — is grounded and useless at once. Parallel, best-effort:
116
+ // a missing name stays null and the address is still the honest identifier.
117
+ if (deps.nameOf) {
118
+ await Promise.all(members.filter((m) => !m.name).map(async (m) => {
119
+ m.name = (await deps.nameOf(m.agent).catch(() => null)) ?? null;
120
+ }));
121
+ }
122
+ if (!members.length) {
123
+ // AN EMPTY ROSTER IS NOT AN EMPTY ORGANIZATION, and saying "no members" here would be confidently
124
+ // wrong: today a member appears in this record only by PUBLISHING their own signed listing, while
125
+ // everyone who joined by invitation is recorded on the organization's side at its Home and nowhere
126
+ // in its vault. The Home's Members panel shows the union of the two, so it can list people this read
127
+ // cannot see. Say that, rather than reporting the half we can reach as the whole.
128
+ return {
129
+ org, yourStanding: standing.relation, members, count: 0,
130
+ note: 'nobody has published a member listing in this organization\'s own records. Members who joined by invitation are held at its Home and are not in its vault yet, so the Members panel there may show people this cannot.',
131
+ };
132
+ }
133
+ return {
134
+ org, yourStanding: standing.relation, members, count: members.length,
135
+ // WHAT TO SAY, stated for the composer: the members ARE the answer. Rows without a directory name
136
+ // are identified by address — a fact, not a gap worth a sentence. The earlier phrasing led with
137
+ // "neither member has a display name on record", which is grounded, true, and an answer to a
138
+ // question nobody asked.
139
+ note: `answer by listing the members (name when present, else the 0x… address). Do not remark on missing display names.`,
140
+ };
141
+ };
142
+ }
143
+ //# sourceMappingURL=membership-read.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"membership-read.js","sourceRoot":"","sources":["../src/membership-read.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,cAAc,EAAqB,MAAM,eAAe,CAAC;AAClE,OAAO,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAC/C,OAAO,EAAE,UAAU,EAAE,iBAAiB,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAEjG,MAAM,CAAC,MAAM,oBAAoB,GAAa;IAC5C,EAAE,EAAE,8BAA8B;IAClC,WAAW,EACT,qGAAqG;UACnG,uGAAuG;UACvG,8EAA8E;UAC9E,sHAAsH;IAC1H,WAAW,EAAE;QACX,IAAI,EAAE,QAAQ;QACd,UAAU,EAAE,EAAE,GAAG,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,0NAA0N,EAAE,EAAE;KACjR;IACD,mGAAmG;IACnG,mGAAmG;IACnG,0FAA0F;IAC1F,UAAU,EAAE,EAAE,QAAQ,EAAE,kDAAkD,EAAE;IAC5E,kGAAkG;IAClG,0GAA0G;IAC1G,OAAO,EAAE,KAAK;CACf,CAAC;AAqBF;;;;;;GAMG;AACH,MAAM,UAAU,qBAAqB,CAAC,IAAoB,EAAE,SAAkB,EAAE,SAAmB;IACjG,OAAO,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,GAAG,EAAE,EAAE;QAClC,iGAAiG;QACjG,kGAAkG;QAClG,mGAAmG;QACnG,mGAAmG;QACnG,mGAAmG;QACnG,oGAAoG;QACpG,2FAA2F;QAC3F,MAAM,GAAG,GAAG,aAAa,CAAC,IAA+B,EAAE,SAAS,EAAE,SAAS,EAAE,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,EAAE,KAAK,EAAE,IAAI,EAAE,cAAc,EAAE,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,EAAE,QAAQ,EAAE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ives/types';
2
+ /** One thing the owner told the agent. Field names ARE the T-box's (apctx:preference*), so the record is
3
+ * readable BY the ontology, not interpreted into it. */
4
+ export interface LearnedPreferenceV1 {
5
+ type: 'ap.context.learned-preference.v1';
6
+ /** The shorthand the owner uses — matched against an ask, never against the world. */
7
+ trigger: string;
8
+ /** What it resolves to. An address for a "who do I mean" preference; free text otherwise. */
9
+ subject: string;
10
+ /** Human label for the subject, for evidence ("alice2.treasury"). */
11
+ subjectLabel?: string;
12
+ /** ISO. Age is shown so a person can judge a stale preference. */
13
+ learnedAt: string;
14
+ /** In the owner's own words, for the evidence line. */
15
+ saidAs?: string;
16
+ }
17
+ export declare const PREFERENCE_PREFIX = "preference:";
18
+ /** The key is derived from the trigger, so telling the agent the same shorthand twice UPDATES rather than
19
+ * accumulates — a person does not hold two contradictory memories of what "alice" means. */
20
+ export declare const preferenceKey: (trigger: string) => string;
21
+ export interface MemoryDeps {
22
+ /** Read the owner's preference records — the survey/decode selector, narrowed to `preference:*`. */
23
+ readPreferences?: (owner: string) => Promise<Array<{
24
+ recordType: string;
25
+ data: unknown;
26
+ }>>;
27
+ /** Write one, under the owner's own grant. */
28
+ writePreference?: (owner: string, key: string, record: LearnedPreferenceV1) => Promise<void>;
29
+ }
30
+ /** The owner's learned preferences, normalised. Absent dep ⇒ no memory, which narrows nothing. */
31
+ export declare function learnedPreferences(deps: MemoryDeps, owner: string): Promise<LearnedPreferenceV1[]>;
32
+ /** Does a learned preference answer to these words? Exact-trigger only: memory disambiguates a shorthand
33
+ * the owner defined, it does not fuzzy-match the world (that is resolution's job, and a loose memory
34
+ * match would quietly override a real agent with a remembered one). */
35
+ export declare function preferenceFor(prefs: LearnedPreferenceV1[], term: string): LearnedPreferenceV1 | null;
36
+ /** Record a preference. The owner is fixed by the caller (their session); nothing here takes it from an
37
+ * argument, so a person can only teach their OWN agent about their OWN shorthand. */
38
+ export declare function rememberPreference(deps: MemoryDeps, owner: Address, input: {
39
+ trigger: string;
40
+ subject: string;
41
+ subjectLabel?: string;
42
+ saidAs?: string;
43
+ now?: () => string;
44
+ }): Promise<{
45
+ ok: boolean;
46
+ key: string;
47
+ error?: string;
48
+ }>;
49
+ //# sourceMappingURL=memory.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"memory.d.ts","sourceRoot":"","sources":["../src/memory.ts"],"names":[],"mappings":"AAgBA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,0BAA0B,CAAC;AAExD;yDACyD;AACzD,MAAM,WAAW,mBAAmB;IAClC,IAAI,EAAE,kCAAkC,CAAC;IACzC,sFAAsF;IACtF,OAAO,EAAE,MAAM,CAAC;IAChB,6FAA6F;IAC7F,OAAO,EAAE,MAAM,CAAC;IAChB,qEAAqE;IACrE,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,kEAAkE;IAClE,SAAS,EAAE,MAAM,CAAC;IAClB,uDAAuD;IACvD,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,eAAO,MAAM,iBAAiB,gBAAgB,CAAC;AAC/C;6FAC6F;AAC7F,eAAO,MAAM,aAAa,YAAa,MAAM,KAAG,MACwE,CAAC;AAEzH,MAAM,WAAW,UAAU;IACzB,oGAAoG;IACpG,eAAe,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,KAAK,CAAC;QAAE,UAAU,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,OAAO,CAAA;KAAE,CAAC,CAAC,CAAC;IAC3F,8CAA8C;IAC9C,eAAe,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,mBAAmB,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CAC9F;AAED,kGAAkG;AAClG,wBAAsB,kBAAkB,CAAC,IAAI,EAAE,UAAU,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,mBAAmB,EAAE,CAAC,CAMxG;AAED;;wEAEwE;AACxE,wBAAgB,aAAa,CA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