@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,152 @@
1
+ // WHAT THIS PERSON IS TO THAT AGENT — spec 353 S5, derived and never asserted.
2
+ //
3
+ // The Ask reaches a point where it must say "this needs authority as Calvary". Whether the person in front
4
+ // of it can GIVE that authority is knowable, and saying nothing is the cruel option: they sign, the
5
+ // verifier reads the signature against an SA their credential does not custody, and the run comes back
6
+ // `not-live` — true, unhelpful, and after the fact.
7
+ //
8
+ // DERIVED, NOT ASSERTED. An app that told us "this person is a steward" would be supplying an
9
+ // authorization claim, which is the pattern ADR-0041 forbids and spec 353 §2 excludes from the scope
10
+ // payload on purpose. So standing comes from evidence the PERSON holds and the CHAIN confirms:
11
+ //
12
+ // self the subject IS them — nothing to check.
13
+ // steward they hold a stewardship delegation from that agent, in their own vault, which is
14
+ // ERC-1271-valid against it and unrevoked on chain. A delegation of the right SHAPE:
15
+ // governance targets and no vault-record scope, or a member's data grant could be replayed
16
+ // as stewardship (the SEC-C1 parity check the Home already makes).
17
+ // member they are in that agent's roster — standing to be there, not to authorize.
18
+ // none no link. Not a refusal by itself: the Ask still asks, and the chain still decides.
19
+ //
20
+ // AND IT IS NOT AUTHORITY. Standing shapes what we SAY before a ceremony — who can grant, and who to ask
21
+ // if it is not you. It is not consulted by any gate: a steward reading of this record grants nothing that
22
+ // the mandate and the chain would not have granted anyway (spec 353 §4).
23
+ import { relationshipRows } from './relationship-rows.js';
24
+ import { hashDelegation } from '@agenticprimitives/delegation';
25
+ const lc = (s) => s.toLowerCase();
26
+ /**
27
+ * What `principal` is to `subject`.
28
+ *
29
+ * Order matters and is not an optimisation: the stewardship wire is CHECKED before it is believed. A row
30
+ * in someone's own vault saying `relationship: 'steward'` is their own note about themselves — useful, and
31
+ * not evidence. The wire is the evidence, and it is only evidence once the chain agrees.
32
+ */
33
+ /** The stewardship check, built from the chain reads the mandate path already makes.
34
+ *
35
+ * SHAPE FIRST, and it is not a formality (SEC-C1 parity with the Home's `verifyStewardship`): a member's
36
+ * vault-record grant is also a real, signed, unrevoked delegation from the org to the person. What makes
37
+ * one of them stewardship is that it names GOVERNANCE targets and carries no record scope. Skip the shape
38
+ * check and every member holding a data grant reads as a steward.
39
+ */
40
+ export function chainStewardshipCheck(input) {
41
+ const low = (v) => (v ?? '').toLowerCase();
42
+ return async ({ org, person, wire }) => {
43
+ const w = wire;
44
+ if (!w?.signature || !Array.isArray(w.caveats))
45
+ return false;
46
+ if (low(w.delegator) !== low(org) || low(w.delegate) !== low(person))
47
+ return false;
48
+ const enf = (c) => low(c.enforcer);
49
+ const governance = !!input.allowedTargetsEnforcer && w.caveats.some((c) => enf(c) === low(input.allowedTargetsEnforcer));
50
+ const recordScope = !!input.vaultRecordScopeEnforcer && w.caveats.some((c) => enf(c) === low(input.vaultRecordScopeEnforcer));
51
+ if (!governance || recordScope)
52
+ return false;
53
+ if (!input.validator)
54
+ return false;
55
+ // A record in someone's vault is data, not a promise of a well-formed delegation. Hashing malformed
56
+ // input throws, and a throw here would take down an ask that was only ever asking a question.
57
+ let digest;
58
+ try {
59
+ digest = hashDelegation({ ...w, salt: BigInt(w.salt) }, input.chainId, input.delegationManager);
60
+ }
61
+ catch {
62
+ return false;
63
+ }
64
+ const valid = await input.readContract({
65
+ address: input.validator, abi: input.validatorAbi, functionName: 'isValidSig',
66
+ args: [org, digest, w.signature],
67
+ }).catch(() => false);
68
+ if (valid !== true)
69
+ return false;
70
+ // A revoked wire is not stewardship. An unreadable revocation state is not "probably fine" either:
71
+ // failing closed here costs a person one honest sentence, failing open costs them a wasted ceremony.
72
+ const revoked = await input.readContract({
73
+ address: input.delegationManager, abi: input.isRevokedAbi, functionName: 'isRevoked', args: [digest],
74
+ }).catch(() => true);
75
+ return revoked !== true;
76
+ };
77
+ }
78
+ export async function deriveStanding(deps, input) {
79
+ const subject = lc(input.subject);
80
+ if (lc(input.principal) === subject) {
81
+ return { subject, relation: 'self', because: 'this is your own agent', canGrant: true };
82
+ }
83
+ if (!deps.readSubjectRecord) {
84
+ return { subject, relation: 'none', because: 'this agent cannot read your links', canGrant: false };
85
+ }
86
+ // WHAT THEY PRESENTED, checked before anything is believed about it (spec 366 R2). A stewardship wire
87
+ // handed over by the asker is judged by the same chain reads as one found in their tree: delegator is
88
+ // this subject, delegate is them, governance shape, ERC-1271-valid, unrevoked. The first that verifies
89
+ // is stewardship; one that does not is simply not, never "steward, unverified".
90
+ const presented = input.presented ?? deps.context?.presented ?? [];
91
+ const routed = input.routed ?? deps.context?.routed ?? false;
92
+ for (const wire of presented) {
93
+ if (!wire || !deps.verifyStewardship)
94
+ continue;
95
+ const ok = await deps.verifyStewardship({ org: subject, person: input.principal, wire }).catch(() => false);
96
+ if (ok) {
97
+ const wireRef = deps.wireRefOf?.(wire) ?? null;
98
+ return { subject, relation: 'steward', because: 'you presented a stewardship grant from this agent, and it verifies on chain', canGrant: true, ...(wireRef ? { wireRef } : {}) };
99
+ }
100
+ }
101
+ let name = subject;
102
+ if (!routed) {
103
+ // NOT caught. "I could not read your links" and "you have no link" are opposite facts, and this function
104
+ // returns only the second — the caller reports the first as unavailable. Swallowing the read here would
105
+ // tell a steward, in confident words, that they have no standing in their own organization.
106
+ const tree = await deps.readSubjectRecord(input.principal, 'relationships.data');
107
+ const row = relationshipRows(tree).find((r) => r.agent === subject);
108
+ name = row?.name ?? subject;
109
+ // Their own row saying `relationship: 'steward'` is a note about themselves. The WIRE is the evidence.
110
+ if (row?.relationship === 'steward' && row.stewardshipDelegation && deps.verifyStewardship) {
111
+ const ok = await deps
112
+ .verifyStewardship({ org: subject, person: input.principal, wire: row.stewardshipDelegation })
113
+ .catch(() => false);
114
+ // A wire that does not verify is NOT downgraded quietly to "steward, unverified": it is not stewardship.
115
+ if (ok) {
116
+ const wireRef = deps.wireRefOf?.(row.stewardshipDelegation) ?? null;
117
+ return { subject, relation: 'steward', because: `you hold a stewardship grant from ${name}`, canGrant: true, ...(wireRef ? { wireRef } : {}) };
118
+ }
119
+ }
120
+ if (row) {
121
+ return { subject, relation: 'member', because: `you are linked to ${name}, but not as a steward`, canGrant: false };
122
+ }
123
+ }
124
+ // THE ORGANIZATION'S OWN RECORD OF THEM (spec 366 R1). A member admitted by invitation is written on the
125
+ // org's side at admission (`org.membership:member:<sa>`, in the org's own vault) — the org's word about
126
+ // who belongs, which is the evidence an org's agent should be gating on when a member's agent asks it a
127
+ // question, rather than on what the asker's own vault says about itself. Checked after the wire (a
128
+ // steward who is also a member is a steward) and before the published listing.
129
+ const admitted = await deps.readSubjectRecord(subject, `org.membership:member:${lc(input.principal)}`).catch(() => null);
130
+ if (admitted && typeof admitted === 'object') {
131
+ return { subject, relation: 'member', because: `${name} records you as a member, but not a steward`, canGrant: false };
132
+ }
133
+ // Not in their tree: they may still be in its roster (a member who keeps no link of their own). A roster
134
+ // we cannot read is likewise not an absence — `none` here must mean "looked everywhere, found nothing".
135
+ const dir = await deps.readSubjectRecord(subject, 'directory.data');
136
+ const listings = (dir?.listings ?? []);
137
+ if (listings.some((l) => lc(String(l.smartAgent ?? l.agent ?? '')) === lc(input.principal))) {
138
+ return { subject, relation: 'member', because: 'you are a member there, but not a steward', canGrant: false };
139
+ }
140
+ return { subject, relation: 'none', because: 'you have no link to that agent', canGrant: false };
141
+ }
142
+ /** The sentence to show when authority is needed as an agent the person cannot grant for. Names what they
143
+ * ARE and what would have to happen — "you cannot" without "and here is who can" is a dead end. */
144
+ export function standingNote(standing, capabilityWords) {
145
+ if (standing.canGrant)
146
+ return '';
147
+ if (standing.relation === 'member') {
148
+ return `This needs ${capabilityWords} as that agent, and ${standing.because} — a steward has to authorize it.`;
149
+ }
150
+ return `This needs ${capabilityWords} as that agent, and ${standing.because}.`;
151
+ }
152
+ //# sourceMappingURL=standing.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"standing.js","sourceRoot":"","sources":["../src/standing.ts"],"names":[],"mappings":"AAAA,+EAA+E;AAC/E,EAAE;AACF,2GAA2G;AAC3G,oGAAoG;AACpG,uGAAuG;AACvG,oDAAoD;AACpD,EAAE;AACF,8FAA8F;AAC9F,qGAAqG;AACrG,+FAA+F;AAC/F,EAAE;AACF,uDAAuD;AACvD,gGAAgG;AAChG,kGAAkG;AAClG,wGAAwG;AACxG,gFAAgF;AAChF,yFAAyF;AACzF,kGAAkG;AAClG,EAAE;AACF,yGAAyG;AACzG,0GAA0G;AAC1G,yEAAyE;AACzE,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,EAAE,cAAc,EAAmB,MAAM,+BAA+B,CAAC;AAiChF,MAAM,EAAE,GAAG,CAAC,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC;AAE1C;;;;;;GAMG;AACH;;;;;;GAMG;AACH,MAAM,UAAU,qBAAqB,CAAC,KASrC;IACC,MAAM,GAAG,GAAG,CAAC,CAAU,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,WAAW,EAAE,CAAC;IACpD,OAAO,KAAK,EAAE,EAAE,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,EAAE,EAAE;QACrC,MAAM,CAAC,GAAG,IAAgD,CAAC;QAC3D,IAAI,CAAC,CAAC,EAAE,SAAS,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC;YAAE,OAAO,KAAK,CAAC;QAC7D,IAAI,GAAG,CAAC,CAAC,CAAC,SAAS,CAAC,KAAK,GAAG,CAAC,GAAG,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,QAAQ,CAAC,KAAK,GAA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GAAG,GAAG,MAAM,IAAI,CAAC,iBAAiB,CAAC,OAAO,EAAE,gBAAgB,CAAC,CAAC;IACpE,MAAM,QAAQ,GAAG,CAAE,GAA4E,EAAE,QAAQ,IAAI,EAAE,CAAC,CAAC;IACjH,IAAI,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC,UAAU,IAAI,CAAC,CAAC,KAAK,IAAI,EAAE,CAAC,CAAC,KAAK,EAAE,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC;QAC5F,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,2CAA2C,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC;IAChH,CAAC;IACD,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,gCAAgC,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC;AACnG,CAAC;AAED;oGACoG;AACpG,MAAM,UAAU,YAAY,CAAC,QAAkB,EAAE,eAAuB;IACtE,IAAI,QAAQ,CAAC,QAAQ;QAAE,OAAO,EAAE,CAAC;IACjC,IAAI,QAAQ,CAAC,QAAQ,KAAK,QAAQ,EAAE,CAAC;QACnC,OAAO,cAAc,eAAe,uBAAuB,QAAQ,CAAC,OAAO,mCAAmC,CAAC;IACjH,CAAC;IACD,OAAO,cAAc,eAAe,uBAAuB,QAAQ,CAAC,OAAO,GAAG,CAAC;AACjF,CAAC"}
@@ -0,0 +1,16 @@
1
+ /** One forced structured call: the model must answer by invoking `tool`, and the tool's input is the
2
+ * entire result. Implementations MUST NOT add context of their own — the grounding is the caller's. */
3
+ export type StructuredCall = (input: {
4
+ system: string;
5
+ messages: Array<{
6
+ role: 'user' | 'assistant';
7
+ content: string;
8
+ }>;
9
+ tool: {
10
+ name: string;
11
+ description: string;
12
+ input_schema: Record<string, unknown>;
13
+ };
14
+ maxTokens?: number;
15
+ }) => Promise<Record<string, unknown>>;
16
+ //# sourceMappingURL=structured-call.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"structured-call.d.ts","sourceRoot":"","sources":["../src/structured-call.ts"],"names":[],"mappings":"AAiBA;wGACwG;AACxG,MAAM,MAAM,cAAc,GAAG,CAAC,KAAK,EAAE;IACnC,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,GAAG,WAAW,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACjE,IAAI,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,WAAW,EAAE,MAAM,CAAC;QAAC,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;KAAE,CAAC;IACnF,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB,KAAK,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC"}
@@ -0,0 +1,18 @@
1
+ // THE ONE MODEL CALL THIS PACKAGE MAKES, as a port — spec 358 W1.
2
+ //
3
+ // Two capabilities here ask a model to produce STRUCTURE over grounding this package assembled: a SPARQL
4
+ // query over the schema the store projected (kb-question), and a record selection over a vault's
5
+ // inventory (vault-question). Both are a single forced tool call: system + question in, one tool's input
6
+ // out. That shape is provider-neutral — every serious provider has function calling — so the port stays
7
+ // here and the vendor stays out.
8
+ //
9
+ // DEVIATION FROM SPEC 358 W1, stated: the spec suggested a `context-anthropic` adapter package. The port
10
+ // is one function; an adapter package for ten lines of wiring is boundary ceremony without boundary
11
+ // value. The app wires it over `@agenticprimitives/orchestration-anthropic`'s fetch client — the SAME
12
+ // place it already wires the planner — and that package remains the only vendor-touching one.
13
+ //
14
+ // NOT A PLANNER. This never chooses tools, never sees the run, never loops. It is a grounded translator:
15
+ // the caller supplies everything the model may know, and validation of what comes back happens at the
16
+ // endpoint that executes it (357 §3) or against the surveyed inventory (356 §2.5) — never here.
17
+ export {};
18
+ //# sourceMappingURL=structured-call.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"structured-call.js","sourceRoot":"","sources":["../src/structured-call.ts"],"names":[],"mappings":"AAAA,kEAAkE;AAClE,EAAE;AACF,yGAAyG;AACzG,iGAAiG;AACjG,yGAAyG;AACzG,wGAAwG;AACxG,iCAAiC;AACjC,EAAE;AACF,yGAAyG;AACzG,oGAAoG;AACpG,sGAAsG;AACtG,8FAA8F;AAC9F,EAAE;AACF,yGAAyG;AACzG,sGAAsG;AACtG,gGAAgG"}
@@ -0,0 +1,14 @@
1
+ export type ContextTier = 'private' | 'public';
2
+ /** Where a fact came from, precisely enough to say it out loud in a refusal or a disambiguation. */
3
+ export interface ContextProvenance {
4
+ tier: ContextTier;
5
+ /** The provider that produced it (`naming`, `relationships`, `roster`, `directory`) — a name a person
6
+ * could be told: "in your teams", "in the public directory". */
7
+ source: string;
8
+ /** For a private fact: WHOSE tier it came from. A private fact with no subject is a defect. */
9
+ subject?: string;
10
+ /** How it was matched (`exact-name`, `label`, `display-name`) — a search may fuzz; a caller deciding
11
+ * whether to trust a single hit needs to know which. */
12
+ match?: string;
13
+ }
14
+ //# sourceMappingURL=tiers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tiers.d.ts","sourceRoot":"","sources":["../src/tiers.ts"],"names":[],"mappings":"AAgBA,MAAM,MAAM,WAAW,GAAG,SAAS,GAAG,QAAQ,CAAC;AAE/C,oGAAoG;AACpG,MAAM,WAAW,iBAAiB;IAChC,IAAI,EAAE,WAAW,CAAC;IAClB;qEACiE;IACjE,MAAM,EAAE,MAAM,CAAC;IACf,+FAA+F;IAC/F,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;6DACyD;IACzD,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB"}
package/dist/tiers.js ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=tiers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tiers.js","sourceRoot":"","sources":["../src/tiers.ts"],"names":[],"mappings":""}
@@ -0,0 +1,75 @@
1
+ import type { ToolSpec, ToolInvoker } from '@agenticprimitives/orchestration';
2
+ import type { StructuredCall } from './structured-call.js';
3
+ import { askableRecordKinds, recordTypesForClass } from '@agenticprimitives/ontology';
4
+ export declare const VAULT_QUESTION_TOOL: ToolSpec;
5
+ /** One vault this asker may read, and WHY — the reason an answer has to be able to cite. */
6
+ export interface ReadableVault {
7
+ subject: string;
8
+ name?: string;
9
+ why: 'self' | 'stewardship';
10
+ }
11
+ export interface VaultQuestionDeps {
12
+ /** Every vault this asker may read. Derived (see the header); never a caller's list. */
13
+ readableVaults?: (asker: string) => Promise<ReadableVault[]>;
14
+ /** The inventory: record keys + timestamps, no plaintext (§2.5 phase one). */
15
+ survey?: (subject: string) => Promise<Array<{
16
+ recordType: string;
17
+ updatedAt?: string;
18
+ }>>;
19
+ /** The decode: exactly these keys, one batched call (§2.5 phase two). */
20
+ readRecords?: (subject: string, recordTypes: string[]) => Promise<Record<string, unknown>>;
21
+ }
22
+ export interface VaultQuestionModel {
23
+ /** The one model call (see `structured-call.ts`). Absent ⇒ the tool is not offered. */
24
+ call?: StructuredCall;
25
+ /**
26
+ * The most characters the INVENTORY listing may take in the choosing call — a provider's prompt budget,
27
+ * expressed by the app in chars. A steward of fifty agents holds hundreds of keys; listed whole they
28
+ * exceeded a metered host's per-request limit and the question failed after the planner had chosen it.
29
+ * Under a budget the newest keys are listed first (the freshly delivered record is the one a cap must not
30
+ * drop) and the answer's evidence says how many of how many were shown. Absent ⇒ up to 400 keys, as before.
31
+ */
32
+ inventoryBudgetChars?: number;
33
+ }
34
+ /** Offered only where the survey can be read AND a model can choose from it. Absent either, the tool is
35
+ * not listed — a listed tool the agent cannot run is a step that fails after the planner picks it. */
36
+ export declare function vaultQuestionAvailable(model: VaultQuestionModel, deps: VaultQuestionDeps): boolean;
37
+ /** The survey, as a person would read it: what is in there, by kind. Unbound keys are reported as
38
+ * `unclassified` rather than dropped — a record nothing binds is still a record they have, and hiding it
39
+ * would make the ontology's coverage look complete when it is not. */
40
+ export declare function surveyByKind(records: Array<{
41
+ recordType: string;
42
+ }>): Array<{
43
+ kind: string;
44
+ class?: string;
45
+ count: number;
46
+ examples: string[];
47
+ }>;
48
+ /**
49
+ * Ask the model WHICH records could answer — over the inventory, never over content.
50
+ *
51
+ * It sees keys, kinds and counts. It does not see a single decrypted record, because nothing has been
52
+ * decrypted yet: that is the whole point of doing this before the read rather than after it.
53
+ */
54
+ /** The inventory lines the choosing call is shown: newest first, and no more than the budget allows. */
55
+ export declare function inventoryLines(survey: ReadonlyArray<{
56
+ recordType: string;
57
+ updatedAt?: string;
58
+ ownerLabel: string;
59
+ }>, budgetChars?: number): {
60
+ lines: string[];
61
+ shown: number;
62
+ of: number;
63
+ };
64
+ /**
65
+ * The whole capability: survey → choose → decode → hand back what was read.
66
+ *
67
+ * The ANSWER is composed by the ordinary composer from these observations, exactly as for every other
68
+ * read. What this returns is evidence: the kinds present, which records were opened, and how the question
69
+ * was read — so the diagnostics pane can show a person which of their records an answer came from.
70
+ */
71
+ export declare function vaultQuestionInvoker(model: VaultQuestionModel, deps: VaultQuestionDeps, subject?: string, resolveName?: (name: string) => Promise<string | null>): ToolInvoker;
72
+ /** What kinds a question may be about — the binding's, never the model's. Exported for the vocabulary. */
73
+ export declare const VAULT_QUESTION_KINDS: typeof askableRecordKinds;
74
+ export { recordTypesForClass };
75
+ //# sourceMappingURL=vault-question.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vault-question.d.ts","sourceRoot":"","sources":["../src/vault-question.ts"],"names":[],"mappings":"AAmCA,OAAO,KAAK,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,kCAAkC,CAAC;AAC9E,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,EAAwB,kBAAkB,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC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GAAwG;AACxG,wBAAgB,cAAc,CAC5B,MAAM,EAAE,aAAa,CAAC;IAAE,UAAU,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,CAAC,EACrF,WAAW,CAAC,EAAE,MAAM,GACnB;IAAE,KAAK,EAAE,MAAM,EAAE,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,MAAM,CAAA;CAAE,CAUhD;AA0CD;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CAClC,KAAK,EAAE,kBAAkB,EACzB,IAAI,EAAE,iBAAiB,EACvB,OAAO,CAAC,EAAE,MAAM,EAChB,WAAW,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,GACrD,WAAW,CA8Kb;AAED,0GAA0G;AAC1G,eAAO,MAAM,oBAAoB,2BAAqB,CAAC;AACvD,OAAO,EAAE,mBAAmB,EAAE,CAAC"}
@@ -0,0 +1,302 @@
1
+ import { bindingForRecordType, askableRecordKinds, recordTypesForClass } from '@agenticprimitives/ontology';
2
+ export const VAULT_QUESTION_TOOL = {
3
+ id: 'vault.records.query',
4
+ description: 'ANSWERS A QUESTION ABOUT PRIVATE RECORDS the asker may read — their own, and those of any '
5
+ + 'organization they STEWARD. Use this for "what am I working on", "what endeavors do I have", "what '
6
+ + 'artifacts does the org hold", "what requests am I waiting on". '
7
+ + 'It never reads the public directory (use find_agents / kb.question for anything public), and never '
8
+ + 'a vault the asker has no stewardship delegation for. '
9
+ + 'It READS ONLY: it never sends, pays, creates or changes anything. '
10
+ + 'IF THE ASK NAMES WHOSE RECORDS TO LOOK IN, PASS `subject`. Without it this looks in the asker\'s own '
11
+ + 'records and those of orgs they steward — which will answer a question about somebody else with the '
12
+ + 'WRONG PERSON\'S data. If they may not read that subject you get a refusal, which is the right answer. '
13
+ + 'Args: question (in plain words); subject (optional — whose records to look in, a name or address).',
14
+ inputSchema: {
15
+ type: 'object',
16
+ properties: {
17
+ question: { type: 'string', description: 'The question about the records, in plain words.' },
18
+ subject: { type: 'string', description: 'Optional — the organization whose records to look in (name or address). Omit for everything the asker may read.' },
19
+ },
20
+ required: ['question'],
21
+ },
22
+ };
23
+ /** Offered only where the survey can be read AND a model can choose from it. Absent either, the tool is
24
+ * not listed — a listed tool the agent cannot run is a step that fails after the planner picks it. */
25
+ export function vaultQuestionAvailable(model, deps) {
26
+ return !!model.call && !!deps.survey && !!deps.readRecords;
27
+ }
28
+ /** How many vaults one question may survey. A question is answered from a few; surveying everything a
29
+ * steward can reach turns one ask into a fan-out across an estate. */
30
+ const MAX_SUBJECTS = 5;
31
+ /** The survey, as a person would read it: what is in there, by kind. Unbound keys are reported as
32
+ * `unclassified` rather than dropped — a record nothing binds is still a record they have, and hiding it
33
+ * would make the ontology's coverage look complete when it is not. */
34
+ export function surveyByKind(records) {
35
+ const groups = new Map();
36
+ for (const r of records) {
37
+ const b = bindingForRecordType(r.recordType);
38
+ const key = b?.class ?? 'unclassified';
39
+ const g = groups.get(key) ?? { kind: b?.plural ?? 'unclassified records', ...(b ? { class: b.class } : {}), count: 0, examples: [] };
40
+ g.count += 1;
41
+ if (g.examples.length < 3)
42
+ g.examples.push(r.recordType);
43
+ groups.set(key, g);
44
+ }
45
+ return [...groups.values()].sort((a, b) => b.count - a.count);
46
+ }
47
+ const SELECT_TOOL = {
48
+ name: 'choose_records',
49
+ description: 'Choose which of the listed records to open in order to answer the question.',
50
+ input_schema: {
51
+ type: 'object',
52
+ properties: {
53
+ interpretation: { type: 'string', description: 'What you understood the question to be asking, in one sentence.' },
54
+ recordTypes: { type: 'array', items: { type: 'string' }, description: 'The exact record keys to open. Empty if none of them can answer it.' },
55
+ },
56
+ required: ['interpretation', 'recordTypes'],
57
+ },
58
+ };
59
+ /**
60
+ * Ask the model WHICH records could answer — over the inventory, never over content.
61
+ *
62
+ * It sees keys, kinds and counts. It does not see a single decrypted record, because nothing has been
63
+ * decrypted yet: that is the whole point of doing this before the read rather than after it.
64
+ */
65
+ /** The inventory lines the choosing call is shown: newest first, and no more than the budget allows. */
66
+ export function inventoryLines(survey, budgetChars) {
67
+ const newestFirst = [...survey].sort((a, b) => String(b.updatedAt ?? '').localeCompare(String(a.updatedAt ?? '')));
68
+ const lines = [];
69
+ let used = 0;
70
+ for (const r of newestFirst.slice(0, 400)) {
71
+ const line = ` ${r.ownerLabel} :: ${r.recordType}${r.updatedAt ? ` (updated ${r.updatedAt})` : ''}`;
72
+ if (budgetChars !== undefined && used + line.length + 1 > budgetChars)
73
+ break;
74
+ lines.push(line);
75
+ used += line.length + 1;
76
+ }
77
+ return { lines, shown: lines.length, of: survey.length };
78
+ }
79
+ async function chooseRecords(call, question, survey, budgetChars) {
80
+ const byKind = surveyByKind(survey);
81
+ const inventory = inventoryLines(survey, budgetChars);
82
+ const system = [
83
+ "You are choosing which of a person's OWN private records to open to answer their question.",
84
+ 'You are shown the INVENTORY only — record keys and what kind of thing each is. Nothing has been',
85
+ 'decrypted, and you are not being asked what the records say.',
86
+ '',
87
+ 'WHAT IS IN THIS VAULT:',
88
+ ...byKind.map((g) => ` ${g.count.toString().padStart(4)} × ${g.kind}${g.class ? ` (${g.class})` : ''} — e.g. ${g.examples.join(', ')}`),
89
+ '',
90
+ inventory.shown < inventory.of
91
+ ? `THE ${inventory.shown} NEWEST RECORD KEYS of ${inventory.of}, as owner :: key — choose keys in exactly that form (older ones are not listed):`
92
+ : 'EVERY RECORD KEY, as owner :: key — choose keys in exactly that form:',
93
+ ...inventory.lines,
94
+ '',
95
+ 'RULES:',
96
+ ' - Choose the FEWEST keys that can answer the question. Opening a record is a real read of private data.',
97
+ ' - Choose EXACT keys from the list. A key that is not listed does not exist.',
98
+ ' - At most 25.',
99
+ ' - If nothing listed can answer it, return an empty list and say so in `interpretation`. That is a',
100
+ ' better answer than opening records at random.',
101
+ ].join('\n');
102
+ const input = (await call({
103
+ system, messages: [{ role: 'user', content: question }], tool: SELECT_TOOL, maxTokens: 1200,
104
+ }));
105
+ const known = new Set(survey.map((r) => `${r.ownerLabel} :: ${r.recordType}`));
106
+ return {
107
+ interpretation: String(input.interpretation ?? ''),
108
+ // ONLY KEYS THAT EXIST. A model naming a plausible key it did not see is the vault-side twin of
109
+ // inventing a predicate, and the read would simply return nothing while looking like it worked.
110
+ recordTypes: (Array.isArray(input.recordTypes) ? input.recordTypes.map(String) : []).filter((k) => known.has(k)).slice(0, 25),
111
+ inventory: { shown: inventory.shown, of: inventory.of },
112
+ };
113
+ }
114
+ /**
115
+ * The whole capability: survey → choose → decode → hand back what was read.
116
+ *
117
+ * The ANSWER is composed by the ordinary composer from these observations, exactly as for every other
118
+ * read. What this returns is evidence: the kinds present, which records were opened, and how the question
119
+ * was read — so the diagnostics pane can show a person which of their records an answer came from.
120
+ */
121
+ export function vaultQuestionInvoker(model, deps, subject, resolveName) {
122
+ return async (_toolId, args) => {
123
+ const question = String(args.question ?? '').trim();
124
+ const named = String(args.subject ?? '').trim();
125
+ if (!question)
126
+ return { refused: 'ask a question' };
127
+ if (!subject)
128
+ return { refused: 'this agent does not know who is asking' };
129
+ if (!deps.survey || !deps.readRecords)
130
+ throw new Error('vault.records.query is not configured on this agent');
131
+ // WHOSE VAULTS — derived, never taken from the ask. Absent the dep, this is their own and nothing else:
132
+ // a missing derivation must narrow, never widen.
133
+ const readable = deps.readableVaults
134
+ ? await deps.readableVaults(subject)
135
+ : [{ subject, why: 'self' }];
136
+ if (!readable.length)
137
+ return { refused: 'you have no records this agent may read' };
138
+ // A NAMED SUBJECT IS CHECKED, NOT TRUSTED. Refused BY NAME with what is readable — because "you may
139
+ // not read that" and "that has none of those" are different answers, and only one of them is about
140
+ // the question they asked.
141
+ let scope = readable;
142
+ if (named) {
143
+ // MATCHED AGAINST WHAT THEY MAY READ, in every form they might say it: the address, the registered
144
+ // name, or what the thing is CALLED in their own links ("Missio Nexus"). The readable set is the
145
+ // authority on both questions — what they may read, and what it is called to them — so a display
146
+ // name must not fall through to a refusal just because it is not a registered name. It did: "what
147
+ // artifacts does missio nexus hold" was refused for a vault its steward may plainly read.
148
+ const norm = (v) => v.toLowerCase().replace(/[^a-z0-9]/g, '');
149
+ const wanted = /^0x[0-9a-fA-F]{40}$/.test(named)
150
+ ? named.toLowerCase()
151
+ : ((resolveName ? await resolveName(named.toLowerCase()).catch(() => null) : null) ?? '').toLowerCase();
152
+ const hit = readable.find((v) => v.subject === wanted)
153
+ ?? readable.find((v) => v.name && norm(v.name) === norm(named))
154
+ // A prefix match last, and only when it is UNAMBIGUOUS: "missio" for one Missio Nexus is a name;
155
+ // for two it is a question, and answering it by picking one reads the wrong vault.
156
+ ?? (readable.filter((v) => v.name && norm(v.name).startsWith(norm(named))).length === 1
157
+ ? readable.find((v) => v.name && norm(v.name).startsWith(norm(named)))
158
+ : undefined);
159
+ if (!hit) {
160
+ return {
161
+ answered: false,
162
+ reason: `you have no stewardship of “${named}”, so this agent cannot read its records`,
163
+ readable: readable.map((v) => ({ name: v.name ?? v.subject, why: v.why })),
164
+ };
165
+ }
166
+ scope = [hit];
167
+ }
168
+ // One predicate, used twice: to scope the surveys AND to answer from them (FP1 below).
169
+ const inventoryQuestion = /\b(what|which|how many)\b.*\b(kinds?|types?|records?)\b/i.test(question)
170
+ && !/\b(say|contain|inside|about|show me the)\b/i.test(question);
171
+ // FIRST PERSON MEANS SELF — but only for the INVENTORY question ("what kinds of records do I
172
+ // hold"), where "my vault" is the explicit subject. A content question ("what payment receipts do
173
+ // I have") stays estate-wide: the receipts live in the asker's TREASURY's vault, and self-scoping
174
+ // it would answer "none" while their own treasury holds them — a plausible falsehood, the exact
175
+ // defect class spec 358 exists to prevent. An estate-wide inventory question still says so.
176
+ if (!named && inventoryQuestion && /\b(i|my|me)\b/i.test(question) && !/\b(organi[sz]ations?|orgs?|teams?|estate|steward|all)\b/i.test(question)) {
177
+ const self = scope.find((v) => v.why === 'self');
178
+ if (self)
179
+ scope = [self];
180
+ }
181
+ scope = scope.slice(0, MAX_SUBJECTS);
182
+ // PHASE ONE — the inventory of each vault in scope. Metadata only; nothing decrypted.
183
+ const label = (v) => v.name ?? v.subject;
184
+ const surveys = await Promise.all(scope.map(async (v) => ({
185
+ vault: v,
186
+ rows: await deps.survey(v.subject).catch(() => []),
187
+ })));
188
+ const flat = surveys.flatMap(({ vault, rows }) => rows.map((r) => ({ ...r, owner: vault.subject, ownerLabel: label(vault) })));
189
+ if (!flat.length) {
190
+ return {
191
+ answered: true, count: 0, results: {},
192
+ interpretation: scope.length === 1 ? `${label(scope[0])} holds no records` : 'none of those vaults hold records',
193
+ looked: scope.map((v) => ({ subject: label(v), why: v.why })),
194
+ };
195
+ }
196
+ // ── THE ONTOLOGY-DRIVEN FAST PATHS (the latency program). The pipeline's cost is three SEQUENTIAL
197
+ // model calls — the planner's, this tool's chooseRecords, and the composer's — and the middle one is
198
+ // only needed when the QUESTION does not already name what to open. Two cases where it does:
199
+ //
200
+ // FP1 — an INVENTORY question ("what kinds of records do I hold") is answered from the survey alone:
201
+ // the survey IS the answer, grouped by the ontology's own kinds, and opening records to answer "what
202
+ // kinds are there" would decrypt content nobody asked about.
203
+ if (inventoryQuestion) {
204
+ const kinds = surveyByKind(flat);
205
+ return {
206
+ answered: true, count: flat.length,
207
+ interpretation: 'the kinds of records held, from the inventory — nothing was decrypted',
208
+ kinds: kinds.map((k) => ({ kind: k.kind, count: k.count })),
209
+ looked: scope.map((v) => ({ subject: label(v), why: v.why })),
210
+ note: 'answer by listing the kinds and their counts.',
211
+ };
212
+ }
213
+ //
214
+ // FP2 — the question names ONE modelled kind by its own word ("receipts", "artifacts", "messages"):
215
+ // the vault-record bindings are the vocabulary (spec 355 — the ontology says what things are CALLED),
216
+ // so a single unambiguous label match selects every record of that kind deterministically. Two kinds
217
+ // matching is a real question again and the model chooses, as before.
218
+ const qNorm = question.toLowerCase();
219
+ const kindHits = new Map();
220
+ // NEWEST FIRST before any cap. The 25-record cap sliced the survey in storage order, so a freshly
221
+ // delivered message could be exactly the record the cap dropped — and "none of your messages mention
222
+ // it" about the one that arrived a minute ago is the plausible-falsehood class again (spec 358).
223
+ const byRecency = [...flat].sort((a, b) => String(b.updatedAt ?? '').localeCompare(String(a.updatedAt ?? '')));
224
+ for (const row of byRecency) {
225
+ const b = bindingForRecordType(row.recordType);
226
+ if (!b || (b.role ?? 'entity') !== 'entity')
227
+ continue;
228
+ for (const word of [b.label, b.plural]) {
229
+ if (word.length >= 5 && qNorm.includes(word.toLowerCase())) {
230
+ kindHits.set(b.class, [...(kindHits.get(b.class) ?? []), `${row.ownerLabel} :: ${row.recordType}`]);
231
+ break;
232
+ }
233
+ }
234
+ }
235
+ let chosen;
236
+ if (kindHits.size === 1) {
237
+ const [cls, keys] = [...kindHits.entries()][0];
238
+ chosen = { interpretation: `every record of the one kind the question names (${cls.split(/[#/]/).pop()})`, recordTypes: [...new Set(keys)].slice(0, 25) };
239
+ }
240
+ else {
241
+ // PHASE TWO — the model picks candidates from the INVENTORY. Nothing has been decrypted.
242
+ if (!model.call)
243
+ throw new Error('vault.records.query needs a configured model on this agent');
244
+ chosen = await chooseRecords(model.call, question, flat, model.inventoryBudgetChars);
245
+ }
246
+ const kinds = surveyByKind(flat);
247
+ if (!chosen.recordTypes.length) {
248
+ return {
249
+ answered: false, interpretation: chosen.interpretation,
250
+ ...(chosen.inventory ? { inventory: chosen.inventory } : {}),
251
+ reason: 'none of those records hold what this question needs',
252
+ kinds: kinds.map((k) => ({ kind: k.kind, count: k.count })),
253
+ looked: scope.map((v) => ({ subject: label(v), why: v.why })),
254
+ };
255
+ }
256
+ // PHASE THREE — decode, per owner, one batched call each. Grouped because the GRANT is per subject:
257
+ // a batch cannot straddle two vaults, and pretending otherwise would be a cross-principal read.
258
+ const byOwner = new Map();
259
+ for (const key of chosen.recordTypes) {
260
+ const sep = key.indexOf(' :: ');
261
+ if (sep < 0)
262
+ continue;
263
+ const row = flat.find((f) => f.ownerLabel === key.slice(0, sep) && f.recordType === key.slice(sep + 4));
264
+ if (!row)
265
+ continue;
266
+ byOwner.set(row.owner, [...(byOwner.get(row.owner) ?? []), row.recordType]);
267
+ }
268
+ const results = {};
269
+ const opened = [];
270
+ for (const [owner, recordTypes] of byOwner) {
271
+ const vault = scope.find((v) => v.subject === owner);
272
+ const records = await deps.readRecords(owner, recordTypes).catch(() => ({}));
273
+ for (const [rt, data] of Object.entries(records)) {
274
+ // Qualified in the RESULT too: a record means something different depending on whose it is, and an
275
+ // answer that merges two vaults into one bag cannot say which.
276
+ results[`${vault ? label(vault) : owner} :: ${rt}`] = data;
277
+ opened.push(`${vault ? label(vault) : owner} :: ${rt}`);
278
+ }
279
+ }
280
+ return {
281
+ answered: true,
282
+ // WHOSE RECORDS THESE ARE, first and in words. Everything below is about these agents and nobody
283
+ // else; an answer that names a different person is contradicting its own evidence.
284
+ recordsOf: scope.map((v) => label(v)),
285
+ interpretation: chosen.interpretation,
286
+ // HOW MUCH OF THE INVENTORY THE CHOOSER SAW — under a provider budget, the newest N of M keys; an answer
287
+ // about an older record can then say it was not among what was looked through.
288
+ ...(chosen.inventory ? { inventory: chosen.inventory } : {}),
289
+ // WHOSE RECORDS, AND WHY THEY WERE READABLE. The citation an answer has to be able to make: "as a
290
+ // steward of Missio Nexus" is the difference between an answer and an assertion (spec 356 §2.2).
291
+ looked: scope.map((v) => ({ subject: label(v), why: v.why })),
292
+ query: `records opened: ${opened.join(', ')}`,
293
+ count: opened.length,
294
+ kinds: kinds.map((k) => ({ kind: k.kind, count: k.count })),
295
+ results,
296
+ };
297
+ };
298
+ }
299
+ /** What kinds a question may be about — the binding's, never the model's. Exported for the vocabulary. */
300
+ export const VAULT_QUESTION_KINDS = askableRecordKinds;
301
+ export { recordTypesForClass };
302
+ //# sourceMappingURL=vault-question.js.map