@cohortapp/agent-sdk 2.18.37 → 2.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/maestro.mjs +3 -0
- package/docs/guides/billing-console-keys.md +16 -3
- package/lib/assurance/first-reply.mjs +31 -2
- package/lib/assurance/operator-plane-store.mjs +164 -0
- package/lib/assurance/operator-plane.mjs +689 -0
- package/lib/budget-guard.mjs +24 -1
- package/lib/cli/attention.mjs +300 -0
- package/lib/cli/seat-auth.mjs +86 -6
- package/lib/comms/send-gate.mjs +309 -2
- package/lib/org/awareness.mjs +15 -2
- package/lib/org/clause-match.mjs +470 -0
- package/lib/org/client.mjs +27 -1
- package/lib/org/escalation-chain.mjs +134 -0
- package/lib/org/first-run.mjs +263 -0
- package/lib/org/genesis-contract.mjs +271 -0
- package/lib/org/governance-runtime.mjs +409 -0
- package/lib/org/governance-store.mjs +238 -0
- package/lib/org/governance.mjs +326 -0
- package/lib/org/mesh.mjs +135 -0
- package/lib/org/protocol.checksum +1 -1
- package/lib/org/protocol.mjs +6 -0
- package/lib/org/tool-surface.mjs +28 -0
- package/lib/setup/enroll-from-cohort.mjs +11 -0
- package/lib/telemetry/alerts.mjs +12 -0
- package/lib/telemetry/collect.mjs +237 -1
- package/package.json +1 -1
- package/scripts/daemon/agent-daemon.mjs +41 -2
- package/scripts/daemon/assurance.mjs +482 -55
- package/scripts/daemon/cadence-consumer.mjs +17 -0
- package/scripts/daemon/context-compiler.mjs +25 -0
- package/scripts/daemon/deliver.mjs +71 -5
- package/scripts/fleet/closing-sweep.mjs +266 -0
|
@@ -0,0 +1,470 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* lib/org/clause-match.mjs — does a free-text decision-rights clause cover this
|
|
3
|
+
* tool call? (Genesis WS6, M2.)
|
|
4
|
+
*
|
|
5
|
+
* The server hands the seat its decision rights as PROSE: "Never move money
|
|
6
|
+
* without a human signature", "Write-offs over $500", "Never email a customer
|
|
7
|
+
* without approval". Nothing on the wire says which tool a clause is about, so
|
|
8
|
+
* matching is necessarily a heuristic. This module is that heuristic, kept pure
|
|
9
|
+
* so every rule is a table test.
|
|
10
|
+
*
|
|
11
|
+
* ── THE POSTURE: CONSERVATIVE, AND HONEST ABOUT IT ──────────────────────────
|
|
12
|
+
* A false BLOCK stops a colleague doing their job for a reason nobody wrote; a
|
|
13
|
+
* false ALLOW leaves the clause where it already is today — in the prompt. So:
|
|
14
|
+
*
|
|
15
|
+
* clear the clause's ACTION and every OBJECT it names are present in the
|
|
16
|
+
* call, the parties it names (customer, investor, "outside") are
|
|
17
|
+
* positively identified in the call, and the clause carries no
|
|
18
|
+
* condition the runtime cannot evaluate (a time, an "if", an amount
|
|
19
|
+
* the call does not state). Only a clear match may hard-block.
|
|
20
|
+
* weak the action matches but something is unproven: an object or party
|
|
21
|
+
* the call cannot confirm, an amount it does not carry, a condition.
|
|
22
|
+
* A weak match never blocks. It may route to an APPROVAL when the
|
|
23
|
+
* clause itself names approval as the way through ("…without
|
|
24
|
+
* approval"), because an approval costs a human a click, not the work.
|
|
25
|
+
* none the action does not match.
|
|
26
|
+
*
|
|
27
|
+
* What it deliberately does NOT do: synonyms beyond the small lexicon below,
|
|
28
|
+
* negation scope ("never X unless Y" other than the approval form), numbers in
|
|
29
|
+
* words ("five hundred"), currencies other than $/USD, or reads. A clause the
|
|
30
|
+
* lexicon cannot parse into at least one action concept is UNPARSEABLE and
|
|
31
|
+
* matches nothing — it stays a prompt line, exactly as before this module.
|
|
32
|
+
*
|
|
33
|
+
* PURE: no imports beyond nothing, no clock, no env, no I/O.
|
|
34
|
+
*
|
|
35
|
+
* @module lib/org/clause-match
|
|
36
|
+
*/
|
|
37
|
+
|
|
38
|
+
"use strict";
|
|
39
|
+
|
|
40
|
+
// ── Lexicon ──────────────────────────────────────────────────────────────────
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Action concepts. Each word (lower-case, matched on word boundaries) maps to
|
|
44
|
+
* one concept. Phrases are matched before single words so "move money" reads as
|
|
45
|
+
* `pay`, not as the generic `update`.
|
|
46
|
+
*/
|
|
47
|
+
const VERB_PHRASES = [
|
|
48
|
+
[/\bmov(?:e|es|ing)\s+(?:the\s+)?(?:money|funds|cash)\b/, "pay"],
|
|
49
|
+
[/\bsend(?:s|ing)?\s+(?:the\s+|any\s+)?(?:money|funds|cash|payments?)\b/, "pay"],
|
|
50
|
+
[/\bsign[- ]?off\b/, "approve"],
|
|
51
|
+
[/\bpress release\b/, "publish"],
|
|
52
|
+
[/\bpull request\b/, "merge"],
|
|
53
|
+
[/\bwrite[- ]?offs?\b/, "write_off"],
|
|
54
|
+
[/\bgrant access\b/, "share"],
|
|
55
|
+
[/\bgive access\b/, "share"],
|
|
56
|
+
];
|
|
57
|
+
|
|
58
|
+
const VERB_WORDS = {
|
|
59
|
+
send: "send", sends: "send", sending: "send", sent: "send",
|
|
60
|
+
email: "email", emails: "email", emailing: "email", "e-mail": "email", mail: "email",
|
|
61
|
+
message: "message", messages: "message", messaging: "message", dm: "message", dms: "message",
|
|
62
|
+
post: "message", posting: "message", reply: "message", replying: "message", chat: "message",
|
|
63
|
+
publish: "publish", publishing: "publish", tweet: "publish", announce: "publish", announcing: "publish",
|
|
64
|
+
delete: "delete", deletes: "delete", deleting: "delete", remove: "delete", removing: "delete",
|
|
65
|
+
destroy: "delete", erase: "delete", wipe: "delete", purge: "delete",
|
|
66
|
+
share: "share", sharing: "share", shared: "share",
|
|
67
|
+
pay: "pay", paying: "pay", payment: "pay", payments: "pay", wire: "pay", wiring: "pay",
|
|
68
|
+
transfer: "pay", transferring: "pay", disburse: "pay", refund: "pay", refunds: "pay",
|
|
69
|
+
payout: "pay", spend: "spend", spending: "spend", purchase: "spend", purchases: "spend",
|
|
70
|
+
buy: "spend", buying: "spend",
|
|
71
|
+
invoice: "invoice", invoices: "invoice", invoicing: "invoice", bill: "invoice", billing: "invoice",
|
|
72
|
+
charge: "invoice", charging: "invoice",
|
|
73
|
+
approve: "approve", approving: "approve", approval: "approve", sign: "approve", signing: "approve",
|
|
74
|
+
authorize: "approve", authorise: "approve",
|
|
75
|
+
commit: "commit", committing: "commit", agree: "commit", agreeing: "commit",
|
|
76
|
+
schedule: "schedule", scheduling: "schedule", book: "schedule", booking: "schedule",
|
|
77
|
+
invite: "schedule", inviting: "schedule",
|
|
78
|
+
merge: "merge", merging: "merge", push: "merge", pushing: "merge", deploy: "merge",
|
|
79
|
+
deploying: "merge", release: "merge", ship: "merge",
|
|
80
|
+
create: "create", creating: "create", open: "create", add: "create",
|
|
81
|
+
update: "update", edit: "update", editing: "update", change: "update", changing: "update",
|
|
82
|
+
modify: "update", move: "update",
|
|
83
|
+
hire: "hire", hiring: "hire", fire: "hire", firing: "hire", terminate: "hire", dismiss: "hire",
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Action concepts too generic to carry a match ALONE. "Never send anything
|
|
88
|
+
* after 6pm" overlaps every send; it is a weak match at best.
|
|
89
|
+
*/
|
|
90
|
+
const GENERIC_VERBS = new Set(["send", "create", "update"]);
|
|
91
|
+
|
|
92
|
+
/** Object concepts. */
|
|
93
|
+
const OBJECT_WORDS = {
|
|
94
|
+
money: "money", funds: "money", cash: "money", dollars: "money", usd: "money",
|
|
95
|
+
email: "email", emails: "email",
|
|
96
|
+
message: "message", messages: "message",
|
|
97
|
+
document: "document", documents: "document", doc: "document", docs: "document",
|
|
98
|
+
file: "document", files: "document", data: "document", record: "document", records: "document",
|
|
99
|
+
code: "code", repo: "code", repos: "code", repository: "code", repositories: "code",
|
|
100
|
+
branch: "code", production: "code", prod: "code",
|
|
101
|
+
meeting: "meeting", meetings: "meeting", calendar: "meeting", call: "meeting", calls: "meeting",
|
|
102
|
+
invoice: "invoice", invoices: "invoice", bill: "invoice", bills: "invoice",
|
|
103
|
+
decision: "decision", decisions: "decision",
|
|
104
|
+
deal: "deal", deals: "deal", contract: "deal", contracts: "deal", terms: "deal", agreement: "deal",
|
|
105
|
+
task: "task", tasks: "task",
|
|
106
|
+
image: "image", images: "image",
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Party concepts. `outside` is the one a call can satisfy from its recipients
|
|
111
|
+
* alone (an address outside the workspace domain IS outside). The named kinds
|
|
112
|
+
* need the tool itself to say so (books_invoice_send is addressed to a customer
|
|
113
|
+
* by definition); an arbitrary external address is not proof of a customer.
|
|
114
|
+
*/
|
|
115
|
+
const PARTY_WORDS = {
|
|
116
|
+
external: "outside", outside: "outside",
|
|
117
|
+
// `public` is its own party: an email to one outside address is not posting
|
|
118
|
+
// publicly, and no tool in the table can prove a public audience today.
|
|
119
|
+
public: "public", publicly: "public",
|
|
120
|
+
customer: "customer", customers: "customer", client: "customer", clients: "customer",
|
|
121
|
+
investor: "investor", investors: "investor",
|
|
122
|
+
press: "press", journalist: "press", journalists: "press", media: "press", reporter: "press", reporters: "press",
|
|
123
|
+
vendor: "vendor", vendors: "vendor", supplier: "vendor", suppliers: "vendor",
|
|
124
|
+
regulator: "regulator", regulators: "regulator",
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
const APPROVAL_QUALIFIER =
|
|
128
|
+
/\b(?:without|unless|absent)\s+(?:a\s+|an\s+|the\s+|their\s+|my\s+|prior\s+|explicit\s+|written\s+|human\s+|founder\s+|guardian\s+)*(?:approval|sign[- ]?off|signature|consent|review|permission|go[- ]ahead|ok|okay|approved|signed)\b|\bunless\s+(?:it\s+is\s+|it's\s+)?approved\b/;
|
|
129
|
+
|
|
130
|
+
const AMOUNT_QUALIFIER =
|
|
131
|
+
/\b(?:over|above|more than|greater than|exceeding|exceeds?|in excess of|beyond)\s*(?:\$|usd\s*)?\s*([\d][\d,]*(?:\.\d+)?)\s*(k|m|thousand|million)?\b|>\s*\$?\s*([\d][\d,]*(?:\.\d+)?)\s*(k|m)?/;
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Conditions this runtime cannot evaluate from a tool call. Any of them makes
|
|
135
|
+
* a match weak, never clear.
|
|
136
|
+
*/
|
|
137
|
+
const CONDITIONAL =
|
|
138
|
+
/\b(?:if|when|whenever|before|after|until|during|weekends?|overnight|at night|outside (?:of )?(?:business|working|office) hours|after hours)\b/;
|
|
139
|
+
|
|
140
|
+
// ── Parsing ──────────────────────────────────────────────────────────────────
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* @typedef {object} ParsedClause
|
|
144
|
+
* @property {string} text the clause as given
|
|
145
|
+
* @property {string[]} verbs action concepts
|
|
146
|
+
* @property {string[]} objects object concepts
|
|
147
|
+
* @property {string[]} parties party concepts
|
|
148
|
+
* @property {boolean} approvalWay the clause names approval as the way through
|
|
149
|
+
* @property {number|null} overMicros an amount threshold in µUSD, when stated
|
|
150
|
+
* @property {boolean} conditional carries a condition the runtime cannot evaluate
|
|
151
|
+
* @property {boolean} parseable at least one action concept was found
|
|
152
|
+
*/
|
|
153
|
+
|
|
154
|
+
/** @param {string} s */
|
|
155
|
+
function words(s) {
|
|
156
|
+
return s.toLowerCase().match(/[a-z][a-z'-]*|\$/g) || [];
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Parse one clause. Pure; never throws.
|
|
161
|
+
* @param {unknown} clause
|
|
162
|
+
* @returns {ParsedClause}
|
|
163
|
+
*/
|
|
164
|
+
export function parseClause(clause) {
|
|
165
|
+
const text = typeof clause === "string" ? clause.trim() : "";
|
|
166
|
+
const lc = text.toLowerCase();
|
|
167
|
+
const verbs = new Set();
|
|
168
|
+
const objects = new Set();
|
|
169
|
+
const parties = new Set();
|
|
170
|
+
|
|
171
|
+
let rest = lc;
|
|
172
|
+
for (const [re, concept] of VERB_PHRASES) {
|
|
173
|
+
if (re.test(rest)) {
|
|
174
|
+
verbs.add(concept);
|
|
175
|
+
if (concept === "pay") objects.add("money");
|
|
176
|
+
rest = rest.replace(re, " ");
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
// The approval qualifier is the WAY THROUGH, not an action: strip it before
|
|
180
|
+
// the word pass so "without approval" does not read as an `approve` action.
|
|
181
|
+
const approvalWay = APPROVAL_QUALIFIER.test(rest);
|
|
182
|
+
rest = rest.replace(new RegExp(APPROVAL_QUALIFIER.source, "g"), " ");
|
|
183
|
+
|
|
184
|
+
for (const w of words(rest)) {
|
|
185
|
+
if (Object.prototype.hasOwnProperty.call(VERB_WORDS, w)) verbs.add(VERB_WORDS[w]);
|
|
186
|
+
if (Object.prototype.hasOwnProperty.call(OBJECT_WORDS, w)) objects.add(OBJECT_WORDS[w]);
|
|
187
|
+
if (Object.prototype.hasOwnProperty.call(PARTY_WORDS, w)) parties.add(PARTY_WORDS[w]);
|
|
188
|
+
}
|
|
189
|
+
// "email" and "invoice" are both a verb and an object; as an object they add
|
|
190
|
+
// nothing the verb did not already say, and keeping them would make
|
|
191
|
+
// "Never email a customer" require an `email` OBJECT the call must echo.
|
|
192
|
+
for (const v of verbs) objects.delete(v);
|
|
193
|
+
if (verbs.has("pay") || verbs.has("spend")) objects.delete("money");
|
|
194
|
+
|
|
195
|
+
let overMicros = null;
|
|
196
|
+
const amt = AMOUNT_QUALIFIER.exec(lc);
|
|
197
|
+
if (amt) {
|
|
198
|
+
const raw = (amt[1] || amt[3] || "").replace(/,/g, "");
|
|
199
|
+
const unit = (amt[2] || amt[4] || "").toLowerCase();
|
|
200
|
+
const n = Number(raw);
|
|
201
|
+
if (Number.isFinite(n)) {
|
|
202
|
+
const mult = unit === "k" || unit === "thousand" ? 1e3 : unit === "m" || unit === "million" ? 1e6 : 1;
|
|
203
|
+
overMicros = Math.round(n * mult * 1e6);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
return {
|
|
208
|
+
text,
|
|
209
|
+
verbs: [...verbs],
|
|
210
|
+
objects: [...objects],
|
|
211
|
+
parties: [...parties],
|
|
212
|
+
approvalWay,
|
|
213
|
+
overMicros,
|
|
214
|
+
conditional: CONDITIONAL.test(rest),
|
|
215
|
+
parseable: verbs.size > 0,
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// ── The call side ────────────────────────────────────────────────────────────
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* @typedef {object} CallFacts
|
|
223
|
+
* @property {string[]} verbs action concepts the call performs
|
|
224
|
+
* @property {string[]} objects object concepts it touches
|
|
225
|
+
* @property {string[]} parties party concepts POSITIVELY identified
|
|
226
|
+
* @property {"internal"|"external"|"unknown"} audience who it reaches
|
|
227
|
+
* @property {number|null} amountMicros money the call states (spend estimate or amount moved)
|
|
228
|
+
*/
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* Tool-name tokens → concepts. Covers the curated names (`books_bill_approve`),
|
|
232
|
+
* the `org_rpc` method names (`books.billApprove` → split on case) and the
|
|
233
|
+
* granted integration tools (`plugin__github__create_pull_request`).
|
|
234
|
+
*/
|
|
235
|
+
const NAME_TOKEN_VERBS = {
|
|
236
|
+
send: "send", draft: null, approve: "approve", sign: "approve", delete: "delete", remove: "delete",
|
|
237
|
+
share: "share", grant: "share", create: "create", open: "create", update: "update", edit: "update",
|
|
238
|
+
move: "update", write: "update", merge: "merge", push: "merge", deploy: "merge", invite: "schedule",
|
|
239
|
+
rsvp: "schedule", schedule: "schedule", pay: "pay", invoice: "invoice", publish: "publish",
|
|
240
|
+
post: "message", reply: "message", lock: "update", assign: "update", comment: "message",
|
|
241
|
+
};
|
|
242
|
+
const NAME_TOKEN_OBJECTS = {
|
|
243
|
+
email: "email", messaging: "message", message: "message", voice: "message", files: "document",
|
|
244
|
+
file: "document", doc: "document", resource: "document", repository: "code", repositories: "code",
|
|
245
|
+
repo: "code", pull: "code", branch: "code", calendar: "meeting", huddle: "meeting", call: "meeting",
|
|
246
|
+
invoice: "invoice", bill: "invoice", decision: "decision", deal: "deal", crm: "deal",
|
|
247
|
+
task: "task", board: "task", image: "image", design: "image",
|
|
248
|
+
};
|
|
249
|
+
|
|
250
|
+
/** @param {string} name */
|
|
251
|
+
function nameTokens(name) {
|
|
252
|
+
return String(name || "")
|
|
253
|
+
.replace(/([a-z])([A-Z])/g, "$1_$2")
|
|
254
|
+
.toLowerCase()
|
|
255
|
+
.split(/[^a-z]+/)
|
|
256
|
+
.filter(Boolean);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** Per-tool facts the name cannot carry. */
|
|
260
|
+
const TOOL_FACTS = {
|
|
261
|
+
email_send: { verbs: ["email", "send", "message"], objects: [] },
|
|
262
|
+
email_draft_send: { verbs: ["email", "send", "message"], objects: [] },
|
|
263
|
+
messaging_send: { verbs: ["message", "send"], objects: ["message"], audience: "internal" },
|
|
264
|
+
messaging_send_voice_note: { verbs: ["message", "send"], objects: ["message"], audience: "internal" },
|
|
265
|
+
// An invoice ASKS for money; it does not move any. No `money` object, so
|
|
266
|
+
// "Never send money" cannot read an invoice as a payment.
|
|
267
|
+
books_invoice_send: { verbs: ["invoice", "send"], objects: ["invoice"], parties: ["customer"], audience: "external" },
|
|
268
|
+
books_invoice_draft: { verbs: ["invoice", "create"], objects: ["invoice"] },
|
|
269
|
+
books_bill_approve: { verbs: ["pay", "approve"], objects: ["invoice", "money"], parties: ["vendor"], audience: "external" },
|
|
270
|
+
decision_sign: { verbs: ["approve", "commit"], objects: ["decision"] },
|
|
271
|
+
design_generate_image: { verbs: ["spend", "create"], objects: ["image"] },
|
|
272
|
+
crm_move_stage: { verbs: ["update"], objects: ["deal"] },
|
|
273
|
+
calendar_create: { verbs: ["schedule", "create"], objects: ["meeting"] },
|
|
274
|
+
calendar_rsvp: { verbs: ["schedule"], objects: ["meeting"] },
|
|
275
|
+
};
|
|
276
|
+
|
|
277
|
+
/** @param {unknown} v @returns {string[]} */
|
|
278
|
+
function addressesOf(v) {
|
|
279
|
+
if (Array.isArray(v)) return v.flatMap(addressesOf);
|
|
280
|
+
if (typeof v === "string") return v.split(/[,;\s]+/).filter((s) => s.includes("@"));
|
|
281
|
+
if (v && typeof v === "object" && typeof v.email === "string") return [v.email];
|
|
282
|
+
return [];
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/**
|
|
286
|
+
* Who the call reaches, from its addresses. Any address outside the workspace
|
|
287
|
+
* domain makes it external; addresses all inside make it internal; no address
|
|
288
|
+
* (a thread reply, a member id) is unknown unless the tool fact says otherwise.
|
|
289
|
+
*
|
|
290
|
+
* @param {string[]} addrs
|
|
291
|
+
* @param {string|null} domain workspace email domain, lower-case, or null
|
|
292
|
+
*/
|
|
293
|
+
function audienceOf(addrs, domain) {
|
|
294
|
+
if (!addrs.length) return "unknown";
|
|
295
|
+
if (!domain) return "unknown";
|
|
296
|
+
const outside = addrs.some((a) => !a.toLowerCase().endsWith(`@${domain}`));
|
|
297
|
+
return outside ? "external" : "internal";
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** First finite, non-negative number among `vals`. */
|
|
301
|
+
function firstAmount(...vals) {
|
|
302
|
+
for (const v of vals) {
|
|
303
|
+
const n = Number(v);
|
|
304
|
+
if (v != null && v !== "" && Number.isFinite(n) && n >= 0) return n;
|
|
305
|
+
}
|
|
306
|
+
return null;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* The money a call STATES, in µUSD: a spend estimate (`budgetCents`,
|
|
311
|
+
* `estCostCents`, `costCents`, `estimatedCostMicros`) or an amount moved
|
|
312
|
+
* (`totalCents`, `amountCents`, `valueCents`). Null when it states none.
|
|
313
|
+
* ASSUMPTION (recorded in the WS6 report): these are the only cost-bearing
|
|
314
|
+
* fields the tool table carries; a call without one has no knowable cost.
|
|
315
|
+
* @param {object} input
|
|
316
|
+
* @returns {number|null}
|
|
317
|
+
*/
|
|
318
|
+
export function statedAmountMicros(input) {
|
|
319
|
+
const i = input && typeof input === "object" ? input : {};
|
|
320
|
+
const micros = firstAmount(i.estimatedCostMicros, i.costMicros);
|
|
321
|
+
if (micros != null) return Math.round(micros);
|
|
322
|
+
const cents = firstAmount(i.budgetCents, i.estCostCents, i.costCents, i.totalCents, i.amountCents, i.valueCents);
|
|
323
|
+
if (cents != null) return Math.round(cents * 10_000);
|
|
324
|
+
const usd = firstAmount(i.estimatedCostUsd, i.amountUsd);
|
|
325
|
+
return usd != null ? Math.round(usd * 1e6) : null;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* Describe a tool call in clause concepts. Pure.
|
|
330
|
+
* @param {string} name tool name (curated, integration, or an org_rpc method)
|
|
331
|
+
* @param {object} [input]
|
|
332
|
+
* @param {{workspaceDomain?: string|null}} [o]
|
|
333
|
+
* @returns {CallFacts}
|
|
334
|
+
*/
|
|
335
|
+
export function describeCall(name, input = {}, o = {}) {
|
|
336
|
+
const i = input && typeof input === "object" ? input : {};
|
|
337
|
+
// org_rpc: describe the METHOD it carries, not the escape hatch itself.
|
|
338
|
+
if (name === "org_rpc" && typeof i.method === "string") {
|
|
339
|
+
return describeCall(i.method, i.params && typeof i.params === "object" ? i.params : {}, o);
|
|
340
|
+
}
|
|
341
|
+
const verbs = new Set();
|
|
342
|
+
const objects = new Set();
|
|
343
|
+
const parties = new Set();
|
|
344
|
+
for (const t of nameTokens(name)) {
|
|
345
|
+
if (NAME_TOKEN_VERBS[t]) verbs.add(NAME_TOKEN_VERBS[t]);
|
|
346
|
+
if (NAME_TOKEN_OBJECTS[t]) objects.add(NAME_TOKEN_OBJECTS[t]);
|
|
347
|
+
}
|
|
348
|
+
// `books.billApprove` (an org_rpc method) and `books_bill_approve` (the
|
|
349
|
+
// curated tool) are the same action, so both resolve to one TOOL_FACTS key.
|
|
350
|
+
const key = String(name || "").replace(/([a-z])([A-Z])/g, "$1_$2").replace(/\./g, "_").toLowerCase();
|
|
351
|
+
const fact = TOOL_FACTS[name] || TOOL_FACTS[key] || null;
|
|
352
|
+
if (fact) {
|
|
353
|
+
for (const v of fact.verbs || []) verbs.add(v);
|
|
354
|
+
for (const ob of fact.objects || []) objects.add(ob);
|
|
355
|
+
for (const p of fact.parties || []) parties.add(p);
|
|
356
|
+
}
|
|
357
|
+
const domain = o.workspaceDomain ? String(o.workspaceDomain).toLowerCase().replace(/^@/, "") : null;
|
|
358
|
+
const addrs = addressesOf([i.to, i.cc, i.bcc, i.attendees, i.subjectEmail, i.email, i.recipient]);
|
|
359
|
+
let audience = audienceOf(addrs, domain);
|
|
360
|
+
if (audience === "unknown" && fact && fact.audience) audience = fact.audience;
|
|
361
|
+
if (audience === "external") parties.add("outside");
|
|
362
|
+
// A message body that reaches someone outside is still a message.
|
|
363
|
+
if (verbs.has("email")) objects.add("email");
|
|
364
|
+
return {
|
|
365
|
+
verbs: [...verbs],
|
|
366
|
+
objects: [...objects],
|
|
367
|
+
parties: [...parties],
|
|
368
|
+
audience,
|
|
369
|
+
amountMicros: statedAmountMicros(i),
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
// ── Matching ─────────────────────────────────────────────────────────────────
|
|
374
|
+
|
|
375
|
+
/**
|
|
376
|
+
* @typedef {object} ClauseMatch
|
|
377
|
+
* @property {"clear"|"weak"|"none"} strength
|
|
378
|
+
* @property {string} clause
|
|
379
|
+
* @property {boolean} approvalWay the clause names approval as the way through
|
|
380
|
+
* @property {string} why one plain sentence
|
|
381
|
+
*/
|
|
382
|
+
|
|
383
|
+
/**
|
|
384
|
+
* Match one clause against one call. Pure.
|
|
385
|
+
* @param {string|ParsedClause} clause
|
|
386
|
+
* @param {CallFacts} call
|
|
387
|
+
* @returns {ClauseMatch}
|
|
388
|
+
*/
|
|
389
|
+
export function matchClause(clause, call) {
|
|
390
|
+
const c = typeof clause === "string" ? parseClause(clause) : clause;
|
|
391
|
+
const out = (strength, why) => ({ strength, clause: c.text, approvalWay: c.approvalWay, why });
|
|
392
|
+
if (!c.parseable) return out("none", "the clause names no action this runtime recognises");
|
|
393
|
+
|
|
394
|
+
const callVerbs = new Set(call.verbs || []);
|
|
395
|
+
const sharedVerbs = c.verbs.filter((v) => callVerbs.has(v));
|
|
396
|
+
if (!sharedVerbs.length) return out("none", "the call does a different action");
|
|
397
|
+
|
|
398
|
+
const reasons = [];
|
|
399
|
+
let weak = false;
|
|
400
|
+
|
|
401
|
+
// Objects: every one the clause names must be in the call. None of them →
|
|
402
|
+
// the clause is about something else ("send money" vs a chat message).
|
|
403
|
+
const callObjects = new Set(call.objects || []);
|
|
404
|
+
if (c.objects.length) {
|
|
405
|
+
const hit = c.objects.filter((ob) => callObjects.has(ob));
|
|
406
|
+
if (!hit.length) return out("none", `the call does not touch ${c.objects.join("/")}`);
|
|
407
|
+
if (hit.length < c.objects.length) {
|
|
408
|
+
weak = true;
|
|
409
|
+
reasons.push(`it touches ${hit.join("/")} but not ${c.objects.filter((ob) => !callObjects.has(ob)).join("/")}`);
|
|
410
|
+
}
|
|
411
|
+
} else if (sharedVerbs.every((v) => GENERIC_VERBS.has(v))) {
|
|
412
|
+
weak = true;
|
|
413
|
+
reasons.push(`"${sharedVerbs.join("/")}" alone is too generic to be sure`);
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
// Parties: a known-internal call cannot reach a customer.
|
|
417
|
+
if (c.parties.length) {
|
|
418
|
+
if (call.audience === "internal") return out("none", "the call stays inside the workspace");
|
|
419
|
+
const callParties = new Set(call.parties || []);
|
|
420
|
+
const proven = c.parties.filter((p) => callParties.has(p));
|
|
421
|
+
if (proven.length < c.parties.length) {
|
|
422
|
+
weak = true;
|
|
423
|
+
reasons.push(
|
|
424
|
+
call.audience === "external"
|
|
425
|
+
? `it reaches someone outside, not provably a ${c.parties.filter((p) => !callParties.has(p)).join("/")}`
|
|
426
|
+
: `who it reaches is unknown`,
|
|
427
|
+
);
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
// Amounts: below the threshold is not covered; unknown is unproven.
|
|
432
|
+
if (c.overMicros != null) {
|
|
433
|
+
if (call.amountMicros == null) {
|
|
434
|
+
weak = true;
|
|
435
|
+
reasons.push("the clause has an amount threshold and the call states no amount");
|
|
436
|
+
} else if (call.amountMicros <= c.overMicros) {
|
|
437
|
+
return out("none", "the call's amount is under the clause's threshold");
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
if (c.conditional) {
|
|
442
|
+
weak = true;
|
|
443
|
+
reasons.push("the clause carries a condition this runtime cannot evaluate");
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
return weak
|
|
447
|
+
? out("weak", `possible match (${sharedVerbs.join("/")}): ${reasons.join("; ")}`)
|
|
448
|
+
: out(
|
|
449
|
+
"clear",
|
|
450
|
+
`the call does ${sharedVerbs.join("/")}${c.objects.length ? ` on ${c.objects.join("/")}` : ""}` +
|
|
451
|
+
`${c.parties.length ? ` reaching ${c.parties.map((p) => (p === "outside" ? "someone outside" : `a ${p}`)).join(" and ")}` : ""}`,
|
|
452
|
+
);
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/**
|
|
456
|
+
* Match every clause; return the matches that are not `none`, strongest first.
|
|
457
|
+
* @param {readonly string[]} clauses
|
|
458
|
+
* @param {CallFacts} call
|
|
459
|
+
* @returns {ClauseMatch[]}
|
|
460
|
+
*/
|
|
461
|
+
export function matchClauses(clauses, call) {
|
|
462
|
+
const rank = { clear: 0, weak: 1 };
|
|
463
|
+
return (Array.isArray(clauses) ? clauses : [])
|
|
464
|
+
.filter((c) => typeof c === "string" && c.trim())
|
|
465
|
+
.map((c) => matchClause(c, call))
|
|
466
|
+
.filter((m) => m.strength !== "none")
|
|
467
|
+
.sort((a, b) => rank[a.strength] - rank[b.strength]);
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
export const _internals = { nameTokens, audienceOf, addressesOf, VERB_WORDS, OBJECT_WORDS, PARTY_WORDS };
|
package/lib/org/client.mjs
CHANGED
|
@@ -331,7 +331,33 @@ export async function call(method, params, o = {}) {
|
|
|
331
331
|
const { base, token, orgId } = o;
|
|
332
332
|
if (!base) return errFrame("BAD_REQUEST", "missing base");
|
|
333
333
|
const def = methodDef(method);
|
|
334
|
-
if (!def)
|
|
334
|
+
if (!def) {
|
|
335
|
+
// A READ IS NOT A MISSING METHOD, AND THE TABLE THAT SAYS SO WAS ALREADY HERE.
|
|
336
|
+
//
|
|
337
|
+
// `decision.list`, `events`, `snapshot` and twelve others are GET read
|
|
338
|
+
// surfaces: they live in `READS`, are reached with `read(path)`, and have no
|
|
339
|
+
// entry in `METHODS` because they are not RPCs. Calling one through `call()`
|
|
340
|
+
// therefore found no `methodDef` and reported `NOT_FOUND: unknown method
|
|
341
|
+
// decision.list` — which is false. The method exists; the transport is wrong.
|
|
342
|
+
//
|
|
343
|
+
// Measured cost of the false wording: a seat read `decision.list` through
|
|
344
|
+
// `call()`, got an 82-byte NOT_FOUND body, did not check `ok`, and rendered
|
|
345
|
+
// the empty rows array as "those decisions are absent" — reporting a
|
|
346
|
+
// truncation defect in a reader that has none. A failed read became an
|
|
347
|
+
// observation about data, and two people chased it.
|
|
348
|
+
//
|
|
349
|
+
// `READS` was imported into this file and never read. The table that names
|
|
350
|
+
// the real cause was in scope, on line 37, at the moment the wrong cause was
|
|
351
|
+
// returned — which is the whole of this fix and the reason it is three lines.
|
|
352
|
+
if (Object.prototype.hasOwnProperty.call(READS, method)) {
|
|
353
|
+
return errFrame(
|
|
354
|
+
"BAD_REQUEST",
|
|
355
|
+
`${method} is a GET read surface, not an RPC — use read("${method}") instead of call(). ` +
|
|
356
|
+
`Its scope is ${READS[method]}.`,
|
|
357
|
+
);
|
|
358
|
+
}
|
|
359
|
+
return errFrame("NOT_FOUND", `unknown method ${method}`);
|
|
360
|
+
}
|
|
335
361
|
|
|
336
362
|
// Project the caller's params onto the names hq's zod schemas actually read.
|
|
337
363
|
// Pure + total; a method with no contract entry passes through unchanged.
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* lib/org/escalation-chain.mjs — who a seat's escalations and briefs reach
|
|
3
|
+
* (Genesis WS6, M3).
|
|
4
|
+
*
|
|
5
|
+
* Reports-to can be an AGENT. An escalation addressed to an agent manager is a
|
|
6
|
+
* message to a colleague who must escalate again, so the chain is walked UP
|
|
7
|
+
* until it reaches a person. The walk:
|
|
8
|
+
*
|
|
9
|
+
* self ──reportsTo──▶ m1 (agent) ──reportsTo──▶ m2 (agent) ──▶ h (human)
|
|
10
|
+
*
|
|
11
|
+
* Each hop is one `GET /api/v1/org/members/<memberId>` (hq resolves that route
|
|
12
|
+
* by slug OR id), read through the contract's `readAgentGovernance`. The edges
|
|
13
|
+
* collected are then handed to the contract's own `firstHumanUpChain`, so the
|
|
14
|
+
* loop rule is cohort's rule, not a second copy of it.
|
|
15
|
+
*
|
|
16
|
+
* Loop safety is belt and braces: the fetch walk stops on a repeat id and on
|
|
17
|
+
* MAX_DEPTH, and `firstHumanUpChain` refuses a cycle by itself. A loop, a dead
|
|
18
|
+
* end, or a fetch that fails yields `firstHuman:null` and a named reason; the
|
|
19
|
+
* caller falls back to the server's approver routing (the approval card), which
|
|
20
|
+
* is what an escalation got before this module.
|
|
21
|
+
*
|
|
22
|
+
* Old server (no `reportsTo` on the wire): returns `reason:"no_reports_to"` and
|
|
23
|
+
* nothing else changes — `awareness.escalateTo` keeps answering from the
|
|
24
|
+
* profile's supervisor / escalationPath exactly as before.
|
|
25
|
+
*
|
|
26
|
+
* @module lib/org/escalation-chain
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
"use strict";
|
|
30
|
+
|
|
31
|
+
import { join } from "node:path";
|
|
32
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
33
|
+
|
|
34
|
+
import { writeJsonAtomic } from "../fs-atomic.mjs";
|
|
35
|
+
import { firstHumanUpChain, readAgentGovernance } from "./genesis-contract.mjs";
|
|
36
|
+
|
|
37
|
+
export const CHAIN_STATE_REL = join("state", "org", "escalation-chain.json");
|
|
38
|
+
|
|
39
|
+
/** No real reporting line is deeper than this; past it, something is wrong. */
|
|
40
|
+
export const MAX_DEPTH = 8;
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* @typedef {object} ChainResult
|
|
44
|
+
* @property {string|null} firstHuman memberId of the first person up the chain
|
|
45
|
+
* @property {string[]} path memberIds walked, self excluded, in order
|
|
46
|
+
* @property {"resolved"|"no_reports_to"|"loop"|"dead_end"|"too_deep"|"lookup_failed"} reason
|
|
47
|
+
* @property {string|null} reportsTo the seat's direct manager memberId
|
|
48
|
+
*/
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Walk up from the seat to the first human.
|
|
52
|
+
*
|
|
53
|
+
* @param {object} o
|
|
54
|
+
* @param {string} o.selfId the seat's own memberId (or slug — used only as a node key)
|
|
55
|
+
* @param {{kind:"human"|"agent", memberId:string}|null} o.reportsTo the seat's own edge
|
|
56
|
+
* @param {(memberId: string) => Promise<{ok:true, reportsTo:{kind:string,memberId:string}|null}|{ok:false, error:string}>} o.lookup
|
|
57
|
+
* one hop: that member's own reportsTo
|
|
58
|
+
* @param {number} [o.maxDepth]
|
|
59
|
+
* @returns {Promise<ChainResult>}
|
|
60
|
+
*/
|
|
61
|
+
export async function walkToFirstHuman({ selfId, reportsTo, lookup, maxDepth = MAX_DEPTH }) {
|
|
62
|
+
const self = String(selfId || "self");
|
|
63
|
+
if (!reportsTo || !reportsTo.memberId) return { firstHuman: null, path: [], reason: "no_reports_to", reportsTo: null };
|
|
64
|
+
|
|
65
|
+
/** @type {Map<string, string|null>} */
|
|
66
|
+
const edges = new Map([[self, reportsTo.memberId]]);
|
|
67
|
+
/** @type {Map<string, string>} */
|
|
68
|
+
const kinds = new Map([[reportsTo.memberId, reportsTo.kind]]);
|
|
69
|
+
const path = [];
|
|
70
|
+
const seen = new Set([self]);
|
|
71
|
+
let cur = reportsTo.memberId;
|
|
72
|
+
let reason = "dead_end";
|
|
73
|
+
|
|
74
|
+
while (cur) {
|
|
75
|
+
if (seen.has(cur)) { reason = "loop"; break; }
|
|
76
|
+
seen.add(cur);
|
|
77
|
+
path.push(cur);
|
|
78
|
+
if (kinds.get(cur) === "human") { reason = "resolved"; break; }
|
|
79
|
+
if (path.length > maxDepth) { reason = "too_deep"; break; }
|
|
80
|
+
let hop;
|
|
81
|
+
try {
|
|
82
|
+
hop = await lookup(cur);
|
|
83
|
+
} catch (err) {
|
|
84
|
+
hop = { ok: false, error: err && err.message ? err.message : String(err) };
|
|
85
|
+
}
|
|
86
|
+
if (!hop || hop.ok === false) { reason = "lookup_failed"; break; }
|
|
87
|
+
const next = hop.reportsTo && hop.reportsTo.memberId ? hop.reportsTo : null;
|
|
88
|
+
edges.set(cur, next ? next.memberId : null);
|
|
89
|
+
if (!next) { reason = "dead_end"; break; }
|
|
90
|
+
if (!kinds.has(next.memberId)) kinds.set(next.memberId, next.kind);
|
|
91
|
+
cur = next.memberId;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const firstHuman = firstHumanUpChain({ memberId: self, edges, isHuman: (id) => kinds.get(id) === "human" });
|
|
95
|
+
return { firstHuman, path, reason: firstHuman ? "resolved" : reason === "resolved" ? "dead_end" : reason, reportsTo: reportsTo.memberId };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* The production `lookup`: one member profile over the org-data API.
|
|
100
|
+
* @param {{base:string, token:string, orgId:string}} conn
|
|
101
|
+
* @param {{fetchSelfProfileImpl?: Function, fetchImpl?: Function}} [deps]
|
|
102
|
+
*/
|
|
103
|
+
export function memberLookup(conn, deps = {}) {
|
|
104
|
+
return async (memberId) => {
|
|
105
|
+
const fetchSelf = deps.fetchSelfProfileImpl || (await import("./client.mjs")).fetchSelfProfile;
|
|
106
|
+
const frame = await fetchSelf({ base: conn.base, apiKey: conn.token, orgId: conn.orgId, agentId: memberId, fetchImpl: deps.fetchImpl });
|
|
107
|
+
if (!frame || !frame.ok) return { ok: false, error: (frame && frame.error && frame.error.code) || "lookup failed" };
|
|
108
|
+
return { ok: true, reportsTo: readAgentGovernance(frame.result).reportsTo };
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Persist the walk so pure readers (awareness, the ladder) can use it offline. */
|
|
113
|
+
export function persistChain(agentRoot, result, now = Date.now()) {
|
|
114
|
+
try {
|
|
115
|
+
writeJsonAtomic(join(agentRoot, CHAIN_STATE_REL), { ...result, resolvedAt: new Date(now).toISOString() });
|
|
116
|
+
return { ok: true };
|
|
117
|
+
} catch (err) {
|
|
118
|
+
return { ok: false, error: `could not write ${CHAIN_STATE_REL}: ${err && err.message ? err.message : err}` };
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Read the persisted walk. Null when never resolved. Never throws. */
|
|
123
|
+
export function loadChain(agentRoot) {
|
|
124
|
+
try {
|
|
125
|
+
const p = join(agentRoot || ".", CHAIN_STATE_REL);
|
|
126
|
+
if (!existsSync(p)) return null;
|
|
127
|
+
const v = JSON.parse(readFileSync(p, "utf8"));
|
|
128
|
+
return v && typeof v === "object" && "firstHuman" in v ? v : null;
|
|
129
|
+
} catch {
|
|
130
|
+
// An unreadable cache is a cache miss: the escalation falls back to the
|
|
131
|
+
// server's approver routing, which is the pre-WS6 behaviour.
|
|
132
|
+
return null;
|
|
133
|
+
}
|
|
134
|
+
}
|