@talonic/mcp 0.1.103 → 0.1.105

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/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { Talonic, TalonicError } from '@talonic/node';
1
+ import { TalonicError, Talonic } from '@talonic/node';
2
2
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
3
  import { z } from 'zod';
4
4
  import { readFile } from 'fs/promises';
@@ -150,10 +150,10 @@ async function apiJson(getToken, baseUrl, method, path, opts = {}) {
150
150
  }
151
151
  async function apiForm(getToken, baseUrl, path, fields) {
152
152
  const form = new FormData();
153
- for (const [key, value] of Object.entries(fields)) {
153
+ for (const [key2, value] of Object.entries(fields)) {
154
154
  if (value === void 0) continue;
155
- if (Array.isArray(value)) for (const item of value) form.append(key, item);
156
- else form.append(key, value);
155
+ if (Array.isArray(value)) for (const item of value) form.append(key2, item);
156
+ else form.append(key2, value);
157
157
  }
158
158
  const res = await resolveFetch(getToken)(buildUrl(baseUrl, path), {
159
159
  method: "POST",
@@ -269,7 +269,7 @@ function registerWebhooksResource(server, getToken, baseUrl) {
269
269
  const results = {};
270
270
  const token = getToken();
271
271
  await Promise.all(
272
- WEBHOOK_INFO_ENDPOINTS.map(async ({ path, key }) => {
272
+ WEBHOOK_INFO_ENDPOINTS.map(async ({ path, key: key2 }) => {
273
273
  try {
274
274
  const res = await resolveFetch(getToken)(`${base}${path}`, {
275
275
  headers: {
@@ -278,15 +278,15 @@ function registerWebhooksResource(server, getToken, baseUrl) {
278
278
  }
279
279
  });
280
280
  if (res.ok) {
281
- results[key] = await res.json();
281
+ results[key2] = await res.json();
282
282
  } else {
283
- results[key] = {
283
+ results[key2] = {
284
284
  error: `HTTP ${res.status}`,
285
285
  message: await res.text().catch(() => "")
286
286
  };
287
287
  }
288
288
  } catch (err) {
289
- results[key] = {
289
+ results[key2] = {
290
290
  error: "fetch_failed",
291
291
  message: err instanceof Error ? err.message : String(err)
292
292
  };
@@ -453,14 +453,14 @@ var CARD_TOOL_KEYS = /* @__PURE__ */ new Set([
453
453
  "saveSchema",
454
454
  "createAccount"
455
455
  ]);
456
- function widgetToolMeta(key) {
457
- const uri = WIDGET_URIS[key];
458
- const status3 = TOOL_INVOCATION_STATUS[key];
456
+ function widgetToolMeta(key2) {
457
+ const uri = WIDGET_URIS[key2];
458
+ const status3 = TOOL_INVOCATION_STATUS[key2];
459
459
  const meta = {
460
460
  "openai/toolInvocation/invoking": status3.invoking,
461
461
  "openai/toolInvocation/invoked": status3.invoked
462
462
  };
463
- if (CARD_TOOL_KEYS.has(key)) {
463
+ if (CARD_TOOL_KEYS.has(key2)) {
464
464
  meta["ui"] = { resourceUri: uri };
465
465
  meta["openai/outputTemplate"] = uri;
466
466
  }
@@ -2366,18 +2366,18 @@ var WIDGET_REGISTRY = {
2366
2366
  html: getDecisionFailedWidgetHtml
2367
2367
  }
2368
2368
  };
2369
- function registerOne(server, key) {
2370
- const entry = WIDGET_REGISTRY[key];
2369
+ function registerOne(server, key2) {
2370
+ const entry = WIDGET_REGISTRY[key2];
2371
2371
  registerWidget(server, {
2372
2372
  name: entry.name,
2373
- uri: WIDGET_URIS[key],
2373
+ uri: WIDGET_URIS[key2],
2374
2374
  title: entry.title,
2375
- description: WIDGET_DESCRIPTIONS[key],
2375
+ description: WIDGET_DESCRIPTIONS[key2],
2376
2376
  html: entry.html()
2377
2377
  });
2378
2378
  }
2379
2379
  function registerWidgets(server) {
2380
- for (const key of Object.keys(WIDGET_REGISTRY)) registerOne(server, key);
2380
+ for (const key2 of Object.keys(WIDGET_REGISTRY)) registerOne(server, key2);
2381
2381
  }
2382
2382
  var DESCRIPTION = [
2383
2383
  "Extract structured, schema-validated JSON from a document: PDF, scan, image, DOCX, email, or photo. Returns the requested fields with per-field confidence scores and, with include_provenance, the page and source text each value came from.",
@@ -2970,8 +2970,8 @@ async function handleListSchemas(talonic) {
2970
2970
  const result = await talonic.schemas.list();
2971
2971
  const data = Array.isArray(result?.data) ? result.data.map((schema) => {
2972
2972
  const summary = {};
2973
- for (const [key, value] of Object.entries(schema)) {
2974
- if (!LIST_ITEM_OMIT.has(key)) summary[key] = value;
2973
+ for (const [key2, value] of Object.entries(schema)) {
2974
+ if (!LIST_ITEM_OMIT.has(key2)) summary[key2] = value;
2975
2975
  }
2976
2976
  return summary;
2977
2977
  }) : result?.data;
@@ -3879,10 +3879,10 @@ function handleImport(getToken, baseUrl, args) {
3879
3879
  if (!!args.all === !!args.document_ids?.length)
3880
3880
  return Promise.resolve(validationError("Pass either `all: true` or `document_ids`, not both."));
3881
3881
  if (args.all) {
3882
- const { query, contract_keys, only_priced, limit: limit2, dry_run } = args;
3882
+ const { query, contract_keys, only_priced, limit: limit3, dry_run } = args;
3883
3883
  return runTool(
3884
3884
  () => apiJson(getToken, baseUrl, "POST", "/v1/contracts/import/all", {
3885
- body: { query, contract_keys, only_priced, limit: limit2, dry_run }
3885
+ body: { query, contract_keys, only_priced, limit: limit3, dry_run }
3886
3886
  })
3887
3887
  );
3888
3888
  }
@@ -4035,7 +4035,7 @@ function handleSetTerm(getToken, baseUrl, args) {
4035
4035
  );
4036
4036
  }
4037
4037
  function registerContractsTools(server, getToken, baseUrl) {
4038
- const tools = [
4038
+ const tools2 = [
4039
4039
  [
4040
4040
  "talonic_contracts_register",
4041
4041
  "List contracts",
@@ -4158,7 +4158,7 @@ function registerContractsTools(server, getToken, baseUrl) {
4158
4158
  (a) => handleSetTerm(getToken, baseUrl, a)
4159
4159
  ]
4160
4160
  ];
4161
- for (const [name, title, description, inputSchema11, annotations, handler] of tools) {
4161
+ for (const [name, title, description, inputSchema11, annotations, handler] of tools2) {
4162
4162
  server.registerTool(
4163
4163
  name,
4164
4164
  { title, description, inputSchema: inputSchema11, annotations: { title, ...annotations } },
@@ -4322,7 +4322,7 @@ function handleRuns(getToken, baseUrl, args) {
4322
4322
  );
4323
4323
  }
4324
4324
  function registerApTools(server, getToken, baseUrl) {
4325
- const tools = [
4325
+ const tools2 = [
4326
4326
  [
4327
4327
  "talonic_ap_overview",
4328
4328
  "AP totals",
@@ -4388,7 +4388,7 @@ function registerApTools(server, getToken, baseUrl) {
4388
4388
  (a) => handleRuns(getToken, baseUrl, a)
4389
4389
  ]
4390
4390
  ];
4391
- for (const [name, title, description, inputSchema11, annotations, handler] of tools) {
4391
+ for (const [name, title, description, inputSchema11, annotations, handler] of tools2) {
4392
4392
  server.registerTool(
4393
4393
  name,
4394
4394
  { title, description, inputSchema: inputSchema11, annotations: { title, ...annotations } },
@@ -4871,15 +4871,15 @@ function handleGenerate(getToken, baseUrl, args, deps = {}) {
4871
4871
  dry_run: args.dry_run ?? false
4872
4872
  }
4873
4873
  });
4874
- const jobId = created.job?.id;
4875
- if (waitS === 0 || !jobId || created.job?.status !== "running") return created;
4874
+ const jobId2 = created.job?.id;
4875
+ if (waitS === 0 || !jobId2 || created.job?.status !== "running") return created;
4876
4876
  const polled = await pollUntilDone(
4877
4877
  created.job,
4878
4878
  () => apiJson(
4879
4879
  getToken,
4880
4880
  baseUrl,
4881
4881
  "GET",
4882
- `/v1/doc-gen/jobs/${jobId}`
4882
+ `/v1/doc-gen/jobs/${jobId2}`
4883
4883
  ),
4884
4884
  (job) => job?.status === "running",
4885
4885
  waitS,
@@ -4962,7 +4962,7 @@ async function handleFile(getToken, baseUrl, args, maxBytes = DOC_GEN_MAX_FILE_B
4962
4962
  }
4963
4963
  }
4964
4964
  function registerDocGenTools(server, getToken, baseUrl, opts = {}) {
4965
- const tools = [
4965
+ const tools2 = [
4966
4966
  [
4967
4967
  "talonic_doc_gen_status",
4968
4968
  "Document Generation status",
@@ -5095,7 +5095,7 @@ function registerDocGenTools(server, getToken, baseUrl, opts = {}) {
5095
5095
  (a) => handleFile(getToken, baseUrl, a)
5096
5096
  ]
5097
5097
  ];
5098
- for (const [name, title, description, inputSchema11, annotations, handler] of tools) {
5098
+ for (const [name, title, description, inputSchema11, annotations, handler] of tools2) {
5099
5099
  server.registerTool(
5100
5100
  name,
5101
5101
  { title, description, inputSchema: inputSchema11, annotations: { title, ...annotations } },
@@ -5117,8 +5117,10 @@ var write4 = (idempotent, destructive2 = false) => ({
5117
5117
  });
5118
5118
  var PARTIES_POLL_INTERVAL_MS = 5e3;
5119
5119
  var READ_MAX_WAIT_S = 600;
5120
+ var CONFIRM_MAX_ROLES = 200;
5120
5121
  var ROLES2 = [
5121
5122
  "partner",
5123
+ "our_party",
5122
5124
  "manager",
5123
5125
  "tenant",
5124
5126
  "previous_owner",
@@ -5129,29 +5131,18 @@ var ROLES2 = [
5129
5131
  var KINDS = ["person", "company", "owners_association", "unknown"];
5130
5132
  var SALUTATIONS = ["herr", "frau", "eheleute", "firma", "weg"];
5131
5133
  var ROLE_STATES = ["suggested", "confirmed", "rejected"];
5132
- var ISSUE_CODES = [
5133
- "no_partner",
5134
- "several_partners",
5135
- "reference_disagrees",
5136
- "kind_unknown",
5137
- "address_missing",
5138
- "manager_without_party",
5139
- "tenant_without_period",
5140
- "owner_change_open",
5141
- "cost_unit_disagrees",
5142
- "cost_unit_missing",
5143
- "not_read",
5144
- "read_failed",
5145
- "possible_duplicate"
5146
- ];
5147
- var ROLES_EXPLAINED = "Roles: partner (the contract partner), manager (Verwalter: acts for a company or an owners' association and is written to on its behalf; represents_id names the role it acts for), tenant (with enters_contract: true the tenant is the temporary partner for the lease period valid_from..valid_to), previous_owner / new_owner (an owner change: the new owner holds from the transfer date valid_from), contact, invoice_recipient.";
5134
+ var ROLES_EXPLAINED = "Roles: partner (the contract partner), our_party (our own company on the contract), manager (Verwalter: acts for a company or an owners' association and is written to on its behalf; represents_id names the role it acts for), tenant (with enters_contract: true the tenant is the temporary partner for the lease period valid_from..valid_to), previous_owner / new_owner (an owner change: the new owner holds from the transfer date valid_from), contact, invoice_recipient.";
5148
5135
  var COMPUTED_RULE = "The effective partner (the tenant entering the contract during its lease, else the partner) and the addressee (the effective partner's Verwalter when it has one, else the effective partner) are computed by the platform from the roles in force on the day; never set them yourself, fix the roles.";
5149
- var DECISION_RULE = "A read only makes suggestions and never overwrites a person's decision (a confirmed role stays, a rejected one never comes back). Confirming, rejecting and merging are a person's decisions: only do them when the user asked.";
5136
+ var DECISION_RULE = "Suggestions never overwrite a person's decision (a confirmed role stays, a rejected one never comes back). Confirming, rejecting and merging are a person's decisions: only do them when the user asked.";
5137
+ var CONTRACT_IS_A_ROW = "A contract is a row of a data product: `product_id` (contracts[].row.data_product_id from talonic_parties_contracts, or products[].id from talonic_parties_status) and `row_id` (contracts[].row.row_id).";
5150
5138
  var dateArg = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "a date YYYY-MM-DD").describe("ISO date YYYY-MM-DD.");
5151
- var contractIdArg2 = zUuid().describe(
5152
- "Contract id (from talonic_parties_contracts or talonic_parties_issues)."
5139
+ var productIdArg2 = zUuid().describe(
5140
+ "Data product of the contract (contracts[].row.data_product_id from talonic_parties_contracts)."
5153
5141
  );
5154
- var partyIdArg = zUuid().describe("Party id (from talonic_parties_search, _contract or _issues).");
5142
+ var rowIdArg2 = z.string().min(1).max(200).describe("The contract's row id in that product (contracts[].row.row_id).");
5143
+ var partyIdArg = zUuid().describe("Party id (from talonic_parties_search, _issues or _contract).");
5144
+ var limitArg = (max, dflt) => z.number().int().min(1).max(max).optional().describe(`At most this many (1-${max}, default ${dflt}).`);
5145
+ var offsetArg = z.number().int().min(0).max(1e6).optional().describe("Skip this many (paging; default 0).");
5155
5146
  function waitSeconds2(requested, max) {
5156
5147
  const n = Number.isFinite(requested) ? requested : 0;
5157
5148
  return Math.max(0, Math.min(max, Math.floor(n)));
@@ -5159,91 +5150,165 @@ function waitSeconds2(requested, max) {
5159
5150
  function defined(obj) {
5160
5151
  return Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== void 0));
5161
5152
  }
5153
+ var rowPath = (productId, rowId) => `/v1/parties/rows/${productId}/${encodeURIComponent(rowId)}`;
5154
+ async function waitUntil(probe, done, waitS, deps) {
5155
+ const sleep2 = deps.sleep ?? sleep;
5156
+ const now = deps.now ?? Date.now;
5157
+ const start = now();
5158
+ const deadline = start + waitS * 1e3;
5159
+ let last = await probe();
5160
+ let pollError;
5161
+ while (!done(last) && now() < deadline) {
5162
+ await sleep2(Math.min(PARTIES_POLL_INTERVAL_MS, deadline - now()));
5163
+ try {
5164
+ last = await probe();
5165
+ } catch (err) {
5166
+ pollError = err instanceof Error ? err.message : String(err);
5167
+ break;
5168
+ }
5169
+ }
5170
+ return {
5171
+ last,
5172
+ waited_ms: now() - start,
5173
+ still_running: pollError !== void 0 || !done(last),
5174
+ ...pollError ? { poll_error: pollError } : {}
5175
+ };
5176
+ }
5162
5177
  var STATUS_DESCRIPTION3 = [
5163
- "Contract Party Management at a glance: how many contracts, how many have confirmed parties, only suggestions, or no partner; active parties; open suggestions; and the parties-read queue.",
5164
- "USE WHEN: starting any parties work, or to report where things stand. The loop: talonic_parties_status \u2192 talonic_parties_read (dry_run first, then with wait_seconds) \u2192 talonic_parties_issues \u2192 talonic_parties_contract per flagged contract \u2192 talonic_parties_set_role / talonic_parties_confirm \u2192 talonic_parties_merge duplicates \u2192 talonic_parties_issues again.",
5165
- "NOT FOR: what to fix (talonic_parties_issues); one contract (talonic_parties_contract).",
5178
+ "Contract Party Management at a glance: whether it is set up, the data products whose rows are the contracts (with row counts), how many rows are filled, the document-read queue, the party count, how many parties need attention, when the last sync finished and the CRM directory's link counts.",
5179
+ "USE WHEN: starting any parties work, or to report where things stand. The loop: talonic_parties_status \u2192 talonic_parties_issues \u2192 talonic_parties_party per flagged party \u2192 talonic_parties_contract per contract \u2192 talonic_parties_set_role / talonic_parties_confirm \u2192 talonic_parties_merge duplicates \u2192 talonic_parties_issues again.",
5180
+ "NOT FOR: which parties need fixing (talonic_parties_issues); one contract (talonic_parties_contract).",
5166
5181
  "",
5167
5182
  "ARGS: none.",
5168
- "RETURNS: { contracts, contracts_confirmed, contracts_suggested, contracts_without_partner, parties, suggestions, reads { counts { pending, running, done, failed }, unread, failed } }."
5183
+ "RETURNS: { configured, first_fill, syncing, finding_fields, setup_errors[] { product_id, name, error }, products[] { id, name, rows }, rows, rows_read, reads { pending, running, done, failed }, parties, needs_attention, synced_at, directory { active, label, linked, pick, none } }."
5169
5184
  ].join("\n");
5170
5185
  function handleStatus2(getToken, baseUrl) {
5171
5186
  return runTool(() => apiJson(getToken, baseUrl, "GET", "/v1/parties/status"));
5172
5187
  }
5173
5188
  var ISSUES_DESCRIPTION4 = [
5174
- "The parties worklist: per contract what looks wrong today (no partner, several partners, the reference table names another partner, person-or-company unknown, no postal address, a Verwalter for a party no longer on the contract, a tenant entering the contract without a lease period, an owner change without a transfer date, cost unit disagreeing or missing, not read, read failed), plus parties that look like duplicates (same name, and postcode when both have one).",
5175
- "USE WHEN: after talonic_parties_read, deciding what to fix; open each flagged contract with talonic_parties_contract. Duplicates are merge candidates: never merged on their own (talonic_parties_merge, only when the user asked).",
5176
- "NOT FOR: the headline counts (talonic_parties_status); all contracts (talonic_parties_contracts).",
5189
+ "The parties worklist: every party that needs a person, because a problem on one of its contracts names it (no partner, several partners, the reference table names another partner, person-or-company unknown, no postal address, a Verwalter for a party no longer on the contract, a tenant entering the contract without a lease period, an owner change without a transfer date, an owners' association without a Verwalter, cost unit disagreeing or missing, not read, read failed, not in the CRM directory, several CRM matches, CRM address far from the contract's) or because it has a duplicate candidate.",
5190
+ "USE WHEN: deciding what to fix; open each party with talonic_parties_party (its contracts with their issues[] codes and details, and its duplicates[]). Duplicates are merge candidates: never merged on their own (talonic_parties_merge, only when the user asked).",
5191
+ "NOT FOR: the headline counts (talonic_parties_status); the whole register (talonic_parties_search).",
5177
5192
  "",
5178
- `ARGS: \`code\` (only this issue; one of ${ISSUE_CODES.join(", ")}).`,
5179
- "RETURNS: { contracts[] { contract_id, contract_key, title, issues[] { code, detail, role_ids[], party_ids[] } }, duplicates[] { name_key, party_ids[], names[] } }."
5193
+ "ARGS: `query` (name, street, postcode, town or email contains), `kind` person|company|owners_association|unknown, `product_id` (only contracts of that data product), `scope` all (default: every party) | partners (contract partners only), `limit` (1-5000, default 200), `offset`.",
5194
+ "RETURNS: { total, needs_attention, offset, limit, data[] { id, kind, display_name, street, postcode, town, email, phone, status, contracts, roles[], issues (problems plus duplicate candidates) } }."
5180
5195
  ].join("\n");
5181
5196
  var issuesInputSchema2 = {
5182
- code: z.enum(ISSUE_CODES).optional().describe("Only this issue code.")
5197
+ query: z.string().max(300).optional().describe("Name, address or email contains."),
5198
+ kind: z.enum(KINDS).optional().describe("Only parties of this kind."),
5199
+ product_id: zUuid().optional().describe("Only contracts of this data product."),
5200
+ scope: z.enum(["all", "partners"]).optional().describe("all (default): every party; partners: contract partners only."),
5201
+ limit: limitArg(5e3, 200),
5202
+ offset: offsetArg
5183
5203
  };
5184
5204
  function handleIssues4(getToken, baseUrl, args) {
5185
5205
  return runTool(
5186
- () => apiJson(getToken, baseUrl, "GET", "/v1/parties/issues", { params: { code: args.code } })
5187
- );
5188
- }
5189
- var CONTRACTS_DESCRIPTION = [
5190
- "List the workspace's contracts with their parties today: effective partner, addressee and Verwalter by name, the parties' state (confirmed: every role counted is confirmed; suggested: any is a suggestion; none: no partner), open suggestions and the read state.",
5191
- "USE WHEN: getting an overview, finding a contract by key, title or party name, or listing contracts still on suggestions (state: suggested) or without a partner (state: none).",
5192
- "NOT FOR: one contract's roles and evidence (talonic_parties_contract); what needs fixing (talonic_parties_issues).",
5193
- "",
5194
- "ARGS: `query` (contract key, title, counterparty, partner or Verwalter contains), `state` confirmed|suggested|none, `limit` (1-5000, default 500).",
5195
- "RETURNS: { total, data[] { id, contract_key, title, counterparty, status, partner, addressee, manager, state, suggestions, read } }."
5196
- ].join("\n");
5197
- var contractsInputSchema = {
5198
- query: z.string().optional().describe("Key, title, counterparty, partner or Verwalter contains."),
5199
- state: z.enum(["confirmed", "suggested", "none"]).optional().describe("Only contracts whose parties are in this state."),
5200
- limit: z.number().int().min(1).max(5e3).optional().describe("At most this many (default 500).")
5201
- };
5202
- function handleContracts(getToken, baseUrl, args) {
5203
- return runTool(
5204
- () => apiJson(getToken, baseUrl, "GET", "/v1/parties/contracts", {
5205
- params: { q: args.query, state: args.state, limit: args.limit }
5206
+ () => apiJson(getToken, baseUrl, "GET", "/v1/parties", {
5207
+ params: {
5208
+ attention: "true",
5209
+ scope: args.scope === "partners" ? void 0 : "all",
5210
+ q: args.query,
5211
+ kind: args.kind,
5212
+ product_id: args.product_id,
5213
+ limit: args.limit,
5214
+ offset: args.offset
5215
+ }
5206
5216
  })
5207
5217
  );
5208
5218
  }
5209
5219
  var CONTRACT_DESCRIPTION2 = [
5210
- "One contract's parties on a day: the computed view (partner, manager, tenant, previous and new owner, effective partner, addressee with its postal address lines, contacts, state), every role row with its party, state (suggested|confirmed|rejected), confidence and evidence (document quotes, reference table rows, a person's word), the issues, the cost unit (documents vs. contract register) and the read state.",
5211
- "USE WHEN: checking or fixing a flagged contract; you need role ids (roles[].id) for talonic_parties_set_role, or to answer who the partner is and where a letter goes.",
5220
+ "One contract's parties on a day: every role row with its party, state (suggested|confirmed|rejected), confidence and evidence (data fields, document quotes, reference table rows, a person's word); the computed view (partner, manager, tenant, previous and new owner, effective partner, addressee with its postal address lines, contacts, state); the issues; the document read's state; the cost unit the documents name.",
5221
+ "USE WHEN: checking or fixing a flagged contract; you need role ids (roles[].id) for talonic_parties_set_role or talonic_parties_confirm, or to answer who the partner is and where a letter goes.",
5222
+ CONTRACT_IS_A_ROW,
5212
5223
  ROLES_EXPLAINED,
5213
5224
  COMPUTED_RULE,
5214
- "NOT FOR: the list of contracts (talonic_parties_contracts); one party across contracts (talonic_parties_party).",
5225
+ "NOT FOR: one party's contracts (talonic_parties_contracts); the worklist (talonic_parties_issues).",
5215
5226
  "",
5216
- "ARGS: `contract_id`, `on` (YYYY-MM-DD; default today: the roles in force on that day).",
5217
- "RETURNS: { contract { id, contract_key, title, counterparty, status }, on, view { partner, manager, tenant, previous_owner, new_owner, effective_partner, addressee { ...party, role_id, role, state, valid_from, valid_to, address_lines[] }, contacts[], state }, roles[] { id, party_id, role, represents_id, valid_from, valid_to, enters_contract, state, confidence, evidence[], origin, decided_by, decided_at, note, party }, issues[], cost_unit { documents, quote, register[] }, reference_names[], read { status, read_at, error, notes, read_with } | null }."
5227
+ "ARGS: `product_id`, `row_id`, `on` (YYYY-MM-DD; default today: the roles in force on that day).",
5228
+ "RETURNS: { row { data_product_id, product_name, row_id, label, document_ids[] }, on, roles[] { id, party_id, role, represents_id, valid_from, valid_to, enters_contract, state, confidence, evidence[], origin, decided_by, decided_at, note, party }, view { partner, manager, tenant, previous_owner, new_owner, effective_partner, addressee { ...party, address_lines[] }, contacts[], state }, issues[] { code, detail, role_ids[], party_ids[] }, read { status, read_at, error, notes, read_with }, cost_unit { documents, quote } }."
5218
5229
  ].join("\n");
5219
5230
  var contractInputSchema2 = {
5220
- contract_id: contractIdArg2,
5231
+ product_id: productIdArg2,
5232
+ row_id: rowIdArg2,
5221
5233
  on: dateArg.optional().describe("The day to read the parties for (YYYY-MM-DD; default today).")
5222
5234
  };
5223
5235
  function handleContract2(getToken, baseUrl, args) {
5224
5236
  return runTool(
5225
- () => apiJson(getToken, baseUrl, "GET", `/v1/parties/contracts/${args.contract_id}`, {
5237
+ () => apiJson(getToken, baseUrl, "GET", rowPath(args.product_id, args.row_id), {
5226
5238
  params: { on: args.on }
5227
5239
  })
5228
5240
  );
5229
5241
  }
5242
+ var SECTION_PATHS = {
5243
+ contracts: (id) => `/v1/parties/${id}/contracts`,
5244
+ documents: (id) => `/v1/parties/${id}/documents`,
5245
+ history: (id) => `/v1/parties/${id}/history`
5246
+ };
5247
+ var SECTION_ARGS = "ARGS: `party_id`, `product_id` (only contracts of that data product), `limit` (1-500, default 50), `offset`.";
5248
+ var CONTRACTS_DESCRIPTION = [
5249
+ "One party's contracts, a page at a time: per contract the row (product_id, row_id, label, documents, read state), this party's roles on it with their evidence, the other parties' roles, the computed view and the contract's issues.",
5250
+ "USE WHEN: answering which contracts a party is on and in what role, or finding the product_id and row_id to open one contract with talonic_parties_contract or to add a role with talonic_parties_set_role.",
5251
+ "NOT FOR: one contract's full parties (talonic_parties_contract); the party's details (talonic_parties_party).",
5252
+ "",
5253
+ SECTION_ARGS,
5254
+ "RETURNS: { total, offset, limit, data[] { row { data_product_id, product_name, row_id, label, document_ids[], read }, roles[], others[] { ...role, party }, view, issues[] } }."
5255
+ ].join("\n");
5256
+ var DOCUMENTS_DESCRIPTION = [
5257
+ "The documents a party appears in, a page at a time: each document of its contracts with its filename, the contract's label and the quotes that name the party.",
5258
+ "USE WHEN: showing where a party comes from, or checking the evidence before confirming its roles.",
5259
+ "NOT FOR: the document itself (talonic_get_document); the party's contracts (talonic_parties_contracts).",
5260
+ "",
5261
+ SECTION_ARGS,
5262
+ "RETURNS: { total, offset, limit, data[] { document_id, filename, row_label, quotes[] } }."
5263
+ ].join("\n");
5264
+ var HISTORY_DESCRIPTION = [
5265
+ "A party's history, newest first, a page at a time: its names (aliases, former names), role dates on its contracts, its CRM directory link and the decisions people took.",
5266
+ "USE WHEN: the user asks what changed on a party, who decided something, or since when it holds a role.",
5267
+ "NOT FOR: its current details (talonic_parties_party).",
5268
+ "",
5269
+ SECTION_ARGS,
5270
+ "RETURNS: { total, offset, limit, data[] } (each entry a dated event with what changed and who did it)."
5271
+ ].join("\n");
5272
+ var sectionInputSchema = {
5273
+ party_id: partyIdArg,
5274
+ product_id: zUuid().optional().describe("Only contracts of this data product."),
5275
+ limit: limitArg(500, 50),
5276
+ offset: offsetArg
5277
+ };
5278
+ function handlePartySection(getToken, baseUrl, section, args) {
5279
+ return runTool(
5280
+ () => apiJson(getToken, baseUrl, "GET", SECTION_PATHS[section](args.party_id), {
5281
+ params: { product_id: args.product_id, limit: args.limit, offset: args.offset }
5282
+ })
5283
+ );
5284
+ }
5230
5285
  var SEARCH_DESCRIPTION = [
5231
- "Search the party register (people, companies, owners' associations): name, street, postcode, town, email or an external reference contains the query; each with how many contracts it holds a role on.",
5286
+ "Search the party register (people, companies, owners' associations): name (aliases included), street, postcode, town or email contains the query; each with how many contracts it is on, its roles and how many problems it has. By default the contract partners; `scope: all` lists every party (Verwalter, tenants, contacts too).",
5232
5287
  "USE WHEN: finding a party to add to a contract (its id for talonic_parties_set_role), checking whether a party already exists before creating one, or finding duplicates by name.",
5233
- "NOT FOR: one party with its roles (talonic_parties_party); a contract's parties (talonic_parties_contract).",
5288
+ "NOT FOR: the parties needing attention (talonic_parties_issues); one party in full (talonic_parties_party).",
5234
5289
  "",
5235
- "ARGS: `query`, `kind` person|company|owners_association|unknown, `limit` (1-1000, default 200).",
5236
- "RETURNS: { total, data[] { id, kind, display_name, salutation, title, first_name, last_name, company_name, legal_form, street, postcode, town, country, email, phone, preferred_channel, external_refs, status, contracts } }."
5290
+ "ARGS: `query`, `kind` person|company|owners_association|unknown, `product_id`, `scope` partners (default) | all, `limit` (1-5000, default 200), `offset`.",
5291
+ "RETURNS: { total, needs_attention, offset, limit, data[] { id, kind, display_name, salutation, title, first_name, last_name, company_name, legal_form, street, postcode, town, country, email, phone, preferred_channel, external_refs, status, contracts, roles[], issues } }."
5237
5292
  ].join("\n");
5238
5293
  var searchInputSchema = {
5239
- query: z.string().optional().describe("Name, address, email or external reference contains."),
5294
+ query: z.string().max(300).optional().describe("Name, address or email contains."),
5240
5295
  kind: z.enum(KINDS).optional().describe("Only parties of this kind."),
5241
- limit: z.number().int().min(1).max(1e3).optional().describe("At most this many (default 200).")
5296
+ product_id: zUuid().optional().describe("Only contracts of this data product."),
5297
+ scope: z.enum(["partners", "all"]).optional().describe("partners (default): contract partners; all: every party."),
5298
+ limit: limitArg(5e3, 200),
5299
+ offset: offsetArg
5242
5300
  };
5243
5301
  function handleSearch2(getToken, baseUrl, args) {
5244
5302
  return runTool(
5245
5303
  () => apiJson(getToken, baseUrl, "GET", "/v1/parties", {
5246
- params: { q: args.query, kind: args.kind, limit: args.limit }
5304
+ params: {
5305
+ q: args.query,
5306
+ kind: args.kind,
5307
+ product_id: args.product_id,
5308
+ scope: args.scope === "all" ? "all" : void 0,
5309
+ limit: args.limit,
5310
+ offset: args.offset
5311
+ }
5247
5312
  })
5248
5313
  );
5249
5314
  }
@@ -5266,16 +5331,18 @@ var PARTY_FIELD_KEYS = [
5266
5331
  "external_refs"
5267
5332
  ];
5268
5333
  var PARTY_DESCRIPTION = [
5269
- "Read, change or create one party. With `party_id` alone: the party with its roles on every contract, its contacts (members), the companies it is a contact of and the documents it appears in (with quotes). With `party_id` and fields: changes those fields (the rest stay). Without `party_id`: creates a party; `display_name` is required (kind and salutation are inferred from it when not given).",
5270
- "USE WHEN: checking a party; fixing its name, kind (person or company decides a letter's wording), salutation or postal address (issues kind_unknown, address_missing); creating a party the documents miss before adding it to a contract with talonic_parties_set_role. Search first (talonic_parties_search) so you do not create a duplicate.",
5271
- "NOT FOR: its role on a contract (talonic_parties_set_role); combining duplicates (talonic_parties_merge).",
5334
+ "Read, change or create one party. With `party_id` alone: the party with where its letters go and why, its contracts (with its roles, the other parties and each contract's issues), the documents it appears in, its contacts (members) and the companies it is a contact of, duplicate candidates, other names, history and its CRM directory link (with candidates to pick from). `overview: true` leaves the long lists out and counts them (page them with talonic_parties_contracts, _documents, _history). With `party_id` and fields: changes those fields (the rest stay; a person's value beats every other source). Without `party_id`: creates a party; `display_name` is required (kind and salutation are inferred from it when not given).",
5335
+ "USE WHEN: checking a flagged party; fixing its name, kind (person or company decides a letter's wording), salutation or postal address (issues kind_unknown, address_missing); creating a party the data misses before adding it to a contract with talonic_parties_set_role. Search first (talonic_parties_search) so you do not create a duplicate.",
5336
+ "NOT FOR: its role on a contract (talonic_parties_set_role); combining duplicates (talonic_parties_merge); other names (talonic_parties_names).",
5272
5337
  "",
5273
- "ARGS: `party_id` (omit to create); fields `kind` person|company|owners_association|unknown, `display_name`, `salutation` herr|frau|eheleute|firma|weg, `title`, `first_name`, `last_name`, `company_name`, `legal_form`, `street`, `postcode`, `town`, `country`, `email`, `phone`, `preferred_channel` post|email, `external_refs` { name: value } (null clears a text field).",
5274
- "RETURNS: read { party, merged_into, roles[] { ...role, contract }, members[] { id, function, party }, member_of[], documents[] { document_id, filename, quotes[] } }; change or create: the party."
5338
+ "ARGS: `party_id` (omit to create), `overview` (read only), `product_id` (read only: only contracts of that data product); fields `kind` person|company|owners_association|unknown, `display_name`, `salutation` herr|frau|eheleute|firma|weg, `title`, `first_name`, `last_name`, `company_name`, `legal_form`, `street`, `postcode`, `town`, `country`, `email`, `phone`, `preferred_channel` post|email, `external_refs` { name: value } (null clears a text field).",
5339
+ "RETURNS: read { party, merged_into, letters { party_id, display_name, address_lines[], reason_code, reason } | null, contracts[], documents[], members[] { id, function, party }, member_of[], duplicates[] { party_id, display_name, postcode, reason }, issues[], names[], history[], directory { active, link, entry, candidates[], crm_address, document_address }, directory_people[] } (overview: contracts without the long lists, plus counts { contracts, documents, history }); change or create: the party."
5275
5340
  ].join("\n");
5276
5341
  var nullableText = (max) => z.string().max(max).nullable().optional();
5277
5342
  var partyInputSchema = {
5278
5343
  party_id: partyIdArg.optional().describe("The party to read or change; omit to create one."),
5344
+ overview: z.boolean().optional().describe("Read: leave the long lists out and count them instead."),
5345
+ product_id: zUuid().optional().describe("Read: only contracts of this data product."),
5279
5346
  kind: z.enum(KINDS).optional().describe("Person, company, owners' association or unknown."),
5280
5347
  display_name: z.string().min(1).max(300).optional().describe("Name as printed; required to create."),
5281
5348
  salutation: z.enum(SALUTATIONS).nullable().optional().describe("Salutation; null clears it."),
@@ -5299,7 +5366,12 @@ function handleParty(getToken, baseUrl, args) {
5299
5366
  if (args.party_id) {
5300
5367
  const path = `/v1/parties/${args.party_id}`;
5301
5368
  return runTool(
5302
- () => changing ? apiJson(getToken, baseUrl, "PATCH", path, { body: fields }) : apiJson(getToken, baseUrl, "GET", path)
5369
+ () => changing ? apiJson(getToken, baseUrl, "PATCH", path, { body: fields }) : apiJson(getToken, baseUrl, "GET", path, {
5370
+ params: {
5371
+ view: args.overview ? "overview" : void 0,
5372
+ product_id: args.product_id
5373
+ }
5374
+ })
5303
5375
  );
5304
5376
  }
5305
5377
  if (typeof args.display_name !== "string" || !args.display_name.trim()) {
@@ -5310,18 +5382,20 @@ function handleParty(getToken, baseUrl, args) {
5310
5382
  return runTool(() => apiJson(getToken, baseUrl, "POST", "/v1/parties", { body: fields }));
5311
5383
  }
5312
5384
  var SET_ROLE_DESCRIPTION = [
5313
- "Add a role to a contract, or change one role row. With `contract_id`, `party_id` and `role`: adds the party in that role (confirmed unless `state` says suggested; a party already holding that role on the contract has that row updated). With `role_id`: changes that row: confirm or reject it (`state`), move it to another role or party, set the period, the Verwalter link or enters_contract. Any change by a person is a decision: an edited suggestion becomes confirmed unless `state` says otherwise.",
5385
+ "Add a role to a contract, or change one role row. With `product_id`, `row_id`, `party_id` and `role`: adds the party in that role (confirmed unless `state` says suggested; a party already holding that role on the contract has that row updated). With `role_id`: changes that row: confirm or reject it (`state`), move it to another role or party, set the period, the Verwalter link or enters_contract. Any change by a person is a decision: an edited suggestion becomes confirmed unless `state` says otherwise.",
5314
5386
  "USE WHEN: fixing a contract's parties after reading talonic_parties_contract: a partner missing (no_partner), two partners at once (reject the wrong one, or give the old one valid_to), a Verwalter for the right party (represents_id), a tenant entering the contract (enters_contract with valid_from / valid_to), an owner change (previous_owner, new_owner with valid_from = transfer date).",
5387
+ CONTRACT_IS_A_ROW,
5315
5388
  ROLES_EXPLAINED,
5316
5389
  COMPUTED_RULE,
5317
5390
  DECISION_RULE,
5318
- "NOT FOR: confirming many suggestions at once (talonic_parties_confirm); the party's own details (talonic_parties_party).",
5391
+ "NOT FOR: confirming several checked roles at once (talonic_parties_confirm); the party's own details (talonic_parties_party).",
5319
5392
  "",
5320
- "ARGS: add: `contract_id`, `party_id`, `role`; change: `role_id` (roles[].id from talonic_parties_contract) and optional `party_id`, `role`. Both: `state` suggested|confirmed|rejected, `represents_id` (another role id on the same contract; null clears), `valid_from`, `valid_to` (YYYY-MM-DD; null clears), `enters_contract` (tenant only), `note` (say where the decision comes from).",
5321
- "RETURNS: the role row { id, contract_id, party_id, role, represents_id, valid_from, valid_to, enters_contract, state, confidence, evidence[], origin, decided_by, decided_at, note }."
5393
+ "ARGS: add: `product_id`, `row_id`, `party_id`, `role`; change: `role_id` (roles[].id from talonic_parties_contract) and optional `party_id`, `role`. Both: `state` suggested|confirmed|rejected, `represents_id` (another role id on the same contract; null clears), `valid_from`, `valid_to` (YYYY-MM-DD; null clears), `enters_contract` (tenant only), `note` (say where the decision comes from).",
5394
+ "RETURNS: the role row { id, data_product_id, row_id, party_id, role, represents_id, valid_from, valid_to, enters_contract, state, confidence, evidence[], origin, decided_by, decided_at, note }."
5322
5395
  ].join("\n");
5323
5396
  var setRoleInputSchema = {
5324
- contract_id: contractIdArg2.optional().describe("Add: the contract to add the role to."),
5397
+ product_id: productIdArg2.optional().describe("Add: the contract's data product."),
5398
+ row_id: rowIdArg2.optional().describe("Add: the contract's row id in that product."),
5325
5399
  role_id: zUuid().optional().describe("Change: the role row (roles[].id from talonic_parties_contract)."),
5326
5400
  party_id: partyIdArg.optional().describe("Add: the party; change: move the row to this party."),
5327
5401
  role: z.enum(ROLES2).optional().describe("The role."),
@@ -5333,19 +5407,25 @@ var setRoleInputSchema = {
5333
5407
  note: z.string().max(1e3).nullable().optional().describe("Why; where the decision comes from.")
5334
5408
  };
5335
5409
  function handleSetRole(getToken, baseUrl, args) {
5336
- const { contract_id, role_id, ...rest } = args;
5410
+ const { product_id, row_id, role_id, ...rest } = args;
5337
5411
  const body = defined(rest);
5338
- if (!!contract_id === !!role_id) {
5412
+ const adding = product_id !== void 0 || row_id !== void 0;
5413
+ if (adding === !!role_id) {
5339
5414
  return Promise.resolve(
5340
- validationError("pass contract_id (with party_id and role) to add, or role_id to change.")
5415
+ validationError(
5416
+ "pass product_id and row_id (with party_id and role) to add, or role_id to change."
5417
+ )
5341
5418
  );
5342
5419
  }
5343
- if (contract_id) {
5420
+ if (adding) {
5421
+ if (!product_id || !row_id) {
5422
+ return Promise.resolve(validationError("adding a role needs both product_id and row_id."));
5423
+ }
5344
5424
  if (!args.party_id || !args.role) {
5345
5425
  return Promise.resolve(validationError("adding a role needs party_id and role."));
5346
5426
  }
5347
5427
  return runTool(
5348
- () => apiJson(getToken, baseUrl, "POST", `/v1/parties/contracts/${contract_id}/roles`, { body })
5428
+ () => apiJson(getToken, baseUrl, "POST", `${rowPath(product_id, row_id)}/roles`, { body })
5349
5429
  );
5350
5430
  }
5351
5431
  if (Object.keys(body).length === 0) {
@@ -5360,37 +5440,45 @@ function handleSetRole(getToken, baseUrl, args) {
5360
5440
  );
5361
5441
  }
5362
5442
  var CONFIRM_DESCRIPTION2 = [
5363
- "Confirm suggested roles in bulk: by default only high-confidence suggestions (a verified quote the contract register agrees with), optionally only of named contracts or roles. Confirming says a person checked them; it is the user's decision, so only call this when the user asked. Run with dry_run first and say how many it would confirm.",
5364
- "USE WHEN: the user asks to accept the suggestions (all, or of some contracts / roles).",
5443
+ `Confirm several suggested roles the user checked, by their ids (up to ${CONFIRM_MAX_ROLES}): each is confirmed on its own, so one refused role never blocks the others. Confirming says a person checked them; it is the user's decision, so only call this when the user asked, and say first how many you will confirm.`,
5444
+ "USE WHEN: the user accepts the suggestions of one or more contracts after you showed them (role ids from talonic_parties_contract roles[].id, or talonic_parties_contracts).",
5445
+ "There is no confirm-by-confidence across the workspace: pick the roles to confirm from the contracts you read.",
5365
5446
  DECISION_RULE,
5366
5447
  "NOT FOR: rejecting or fixing one role (talonic_parties_set_role).",
5367
5448
  "",
5368
- "ARGS: `contract_ids[]` (omit for all), `roles[]` (e.g. ['partner']), `min_confidence` high|medium|low (default high), `limit` (1-5000, default 500), `dry_run`.",
5369
- "RETURNS: { dry_run, confirmed, rows[] { id, contract_id, party_id, role, confidence } } (rows: the first 100)."
5449
+ `ARGS: \`role_ids[]\` (1-${CONFIRM_MAX_ROLES}), \`note\` (say where the decision comes from; recorded on each role).`,
5450
+ "RETURNS: { confirmed, failed, rows[] { role_id, ok, role? (the confirmed row), error? } }."
5370
5451
  ].join("\n");
5371
5452
  var confirmInputSchema2 = {
5372
- contract_ids: z.array(zUuid()).max(1e3).optional().describe("Only these contracts."),
5373
- roles: z.array(z.enum(ROLES2)).max(ROLES2.length).optional().describe("Only these roles."),
5374
- min_confidence: z.enum(["high", "medium", "low"]).optional().describe("Lowest confidence confirmed (default high)."),
5375
- limit: z.number().int().min(1).max(5e3).optional().describe("At most this many (default 500)."),
5376
- dry_run: z.boolean().optional().describe("Count only; nothing is confirmed.")
5453
+ role_ids: z.array(zUuid()).min(1).max(CONFIRM_MAX_ROLES).describe("The role rows to confirm (roles[].id from talonic_parties_contract)."),
5454
+ note: z.string().max(1e3).optional().describe("Why; where the decision comes from.")
5377
5455
  };
5378
5456
  function handleConfirm2(getToken, baseUrl, args) {
5379
- return runTool(
5380
- () => apiJson(getToken, baseUrl, "POST", "/v1/parties/roles/confirm", {
5381
- body: {
5382
- ...args.contract_ids ? { contract_ids: args.contract_ids } : {},
5383
- ...args.roles ? { roles: args.roles } : {},
5384
- min_confidence: args.min_confidence ?? "high",
5385
- ...args.limit ? { limit: args.limit } : {},
5386
- dry_run: args.dry_run ?? false
5457
+ const ids = [...new Set(args.role_ids ?? [])];
5458
+ if (!ids.length) return Promise.resolve(validationError("pass at least one role id."));
5459
+ return runTool(async () => {
5460
+ const rows = [];
5461
+ for (const id of ids) {
5462
+ try {
5463
+ const role = await apiJson(getToken, baseUrl, "PATCH", `/v1/parties/roles/${id}`, {
5464
+ body: { state: "confirmed", ...args.note !== void 0 ? { note: args.note } : {} }
5465
+ });
5466
+ rows.push({ role_id: id, ok: true, role });
5467
+ } catch (err) {
5468
+ rows.push({
5469
+ role_id: id,
5470
+ ok: false,
5471
+ error: err instanceof Error ? err.message : String(err)
5472
+ });
5387
5473
  }
5388
- })
5389
- );
5474
+ }
5475
+ const confirmed = rows.filter((r) => r.ok).length;
5476
+ return { confirmed, failed: rows.length - confirmed, rows };
5477
+ });
5390
5478
  }
5391
5479
  var MERGE_DESCRIPTION2 = [
5392
5480
  "Merge one party into another: every role and contact link moves to the survivor (`into`); a role the survivor already holds on the same contract keeps the survivor's row and takes the merged one's evidence. The merged party stays only as a pointer to the survivor. Cannot be undone; a person's decision, so only when the user asked. Run with dry_run first.",
5393
- "USE WHEN: talonic_parties_issues lists duplicates (same name and postcode) and the user confirms they are the same party.",
5481
+ "USE WHEN: talonic_parties_party lists duplicates[] and the user confirms they are the same party.",
5394
5482
  "NOT FOR: two different parties with similar names; moving one role to another party (talonic_parties_set_role with role_id and party_id).",
5395
5483
  "",
5396
5484
  "ARGS: `party_id` (the one that goes), `into` (the survivor), `dry_run`.",
@@ -5411,76 +5499,215 @@ function handleMerge2(getToken, baseUrl, args) {
5411
5499
  })
5412
5500
  );
5413
5501
  }
5502
+ var READ_STATES_BUSY = /* @__PURE__ */ new Set(["pending", "running"]);
5414
5503
  var READ_DESCRIPTION = [
5415
- "Read the parties from contract documents: queues contracts for the platform to read in the background (one model call per contract) and store every party and role it finds as a suggestion, with quotes. By default every contract not read yet (only_unread); `contract_ids` reads exactly those again. With `status: true` only reports the queue. Pass `wait_seconds` to wait until the queue is empty (polls the queue every 5 s).",
5416
- "USE WHEN: filling the app or after new contract documents arrived: run with dry_run first and say how many contracts it will read, then without dry_run and with wait_seconds; then talonic_parties_issues.",
5504
+ "Have one contract's documents read for its parties: the platform reads the documents in the background and adds every party and role it finds as a suggestion, with quotes, merged with what the contract's data already says. A read is extra work on the documents; ask for it only when the contract's data names too little (issues not_read, no_partner) or the user asked. A contract already queued or being read is not queued twice. With `status: true` only reports the read's state; without a contract, `status: true` reports the workspace's read queue. Pass `wait_seconds` to wait until the read is done or failed (polls every 5 s).",
5505
+ "USE WHEN: one contract's parties are missing or wrong and its data cannot fill them; then talonic_parties_contract to see the new suggestions.",
5506
+ CONTRACT_IS_A_ROW,
5417
5507
  DECISION_RULE,
5418
- "NOT FOR: one contract's parties (talonic_parties_contract).",
5508
+ "NOT FOR: filling every contract from the data products again (talonic_parties_sync); reading many contracts at once (ask for one at a time, only where needed).",
5419
5509
  "",
5420
- "ARGS: `status` (only the queue); or `contract_ids[]` (omit for all), `only_unread` (default true), `force` (read again although read), `limit` (1-5000, default 500), `dry_run`; `wait_seconds` (0-600, default 0; not with dry_run).",
5421
- "RETURNS: dry_run { dry_run, would_queue, skipped, contracts[] (first 50) }; queued { dry_run, queued, skipped }; status { contracts, counts { pending, running, done, failed }, unread, failed[] { contract_id, contract_key, error, attempts } }. After a wait also { status, waited_ms, still_running }."
5510
+ "ARGS: `product_id` + `row_id` (the contract), `status` (only report; nothing is queued), `wait_seconds` (0-600, default 0).",
5511
+ "RETURNS: queued { status: pending|running }; a contract's state { status, read_at, error, notes, read_with }; the queue (no contract) { reads { pending, running, done, failed }, rows, rows_read }. After a wait also { waited_ms, still_running } and `read` (the last state: done, failed with error, or still pending|running)."
5422
5512
  ].join("\n");
5423
5513
  var readInputSchema = {
5424
- status: z.boolean().optional().describe("Only report the read queue; nothing is queued."),
5425
- contract_ids: z.array(zUuid()).max(5e3).optional().describe("Only these contracts (read again when already read)."),
5426
- only_unread: z.boolean().optional().describe("All contracts: only those not read yet (default true)."),
5427
- force: z.boolean().optional().describe("Read again although already read."),
5428
- limit: z.number().int().min(1).max(5e3).optional().describe("Queue at most this many."),
5429
- dry_run: z.boolean().optional().describe("Count and list what would be read; nothing is queued."),
5430
- wait_seconds: z.number().min(0).max(READ_MAX_WAIT_S).optional().describe(`Seconds to wait for the queue to empty (0-${READ_MAX_WAIT_S}).`)
5431
- };
5432
- var busy = (s) => (s.counts?.["pending"] ?? 0) + (s.counts?.["running"] ?? 0) > 0;
5514
+ product_id: productIdArg2.optional().describe("The contract's data product."),
5515
+ row_id: rowIdArg2.optional().describe("The contract's row id in that product."),
5516
+ status: z.boolean().optional().describe("Only report; nothing is queued."),
5517
+ wait_seconds: z.number().min(0).max(READ_MAX_WAIT_S).optional().describe(`Seconds to wait for the read to finish (0-${READ_MAX_WAIT_S}).`)
5518
+ };
5519
+ var queueBusy = (s) => (s.reads?.["pending"] ?? 0) + (s.reads?.["running"] ?? 0) > 0;
5433
5520
  function handleRead(getToken, baseUrl, args, deps = {}) {
5434
5521
  const waitS = waitSeconds2(args.wait_seconds, READ_MAX_WAIT_S);
5435
- const readStatus = () => apiJson(getToken, baseUrl, "GET", "/v1/parties/read/status");
5522
+ const hasRow = !!args.product_id && !!args.row_id;
5523
+ if (!!args.product_id !== !!args.row_id) {
5524
+ return Promise.resolve(validationError("a contract needs both product_id and row_id."));
5525
+ }
5526
+ if (!hasRow && !args.status) {
5527
+ return Promise.resolve(
5528
+ validationError(
5529
+ "pass product_id and row_id to read one contract, or status: true for the read queue. To fill every contract from the data, use talonic_parties_sync."
5530
+ )
5531
+ );
5532
+ }
5533
+ if (!hasRow) {
5534
+ const queue = () => apiJson(getToken, baseUrl, "GET", "/v1/parties/status");
5535
+ return runTool(async () => {
5536
+ if (waitS === 0) {
5537
+ const s = await queue();
5538
+ return { reads: s.reads, rows: s.rows, rows_read: s.rows_read };
5539
+ }
5540
+ const w = await waitUntil(queue, (s) => !queueBusy(s), waitS, deps);
5541
+ return {
5542
+ reads: w.last.reads,
5543
+ rows: w.last.rows,
5544
+ rows_read: w.last.rows_read,
5545
+ waited_ms: w.waited_ms,
5546
+ still_running: w.still_running,
5547
+ ...w.poll_error ? { poll_error: w.poll_error } : {}
5548
+ };
5549
+ });
5550
+ }
5551
+ const path = rowPath(args.product_id, args.row_id);
5552
+ const rowRead = async () => (await apiJson(getToken, baseUrl, "GET", path)).read ?? null;
5436
5553
  return runTool(async () => {
5437
- let started = null;
5554
+ let queued = null;
5438
5555
  if (!args.status) {
5439
- started = await apiJson(
5440
- getToken,
5441
- baseUrl,
5442
- "POST",
5443
- "/v1/parties/read",
5444
- {
5445
- body: {
5446
- ...args.contract_ids ? { contract_ids: args.contract_ids } : {},
5447
- ...args.only_unread !== void 0 ? { only_unread: args.only_unread } : {},
5448
- ...args.force !== void 0 ? { force: args.force } : {},
5449
- ...args.limit ? { limit: args.limit } : {},
5450
- dry_run: args.dry_run ?? false
5451
- }
5452
- }
5453
- );
5454
- if (waitS === 0 || args.dry_run) return started;
5455
- }
5456
- const first = await readStatus();
5457
- if (waitS === 0) return first;
5458
- const sleep2 = deps.sleep ?? sleep;
5459
- const now = deps.now ?? Date.now;
5460
- const start = now();
5461
- const deadline = start + waitS * 1e3;
5462
- let status3 = first;
5463
- let pollError;
5464
- while (busy(status3) && now() < deadline) {
5465
- await sleep2(Math.min(PARTIES_POLL_INTERVAL_MS, deadline - now()));
5466
- try {
5467
- status3 = await readStatus();
5468
- } catch (err) {
5469
- pollError = err instanceof Error ? err.message : String(err);
5470
- break;
5471
- }
5556
+ queued = await apiJson(getToken, baseUrl, "POST", `${path}/read`);
5557
+ if (waitS === 0) return queued;
5558
+ } else if (waitS === 0) {
5559
+ return await rowRead() ?? { status: null };
5472
5560
  }
5473
- const stillRunning = pollError !== void 0 || busy(status3);
5561
+ const w = await waitUntil(rowRead, (r) => !READ_STATES_BUSY.has(r?.status ?? ""), waitS, deps);
5562
+ const failed = w.last?.status === "failed";
5563
+ return {
5564
+ ...queued ?? {},
5565
+ read: w.last,
5566
+ waited_ms: w.waited_ms,
5567
+ still_running: w.still_running,
5568
+ ...w.poll_error ? { poll_error: w.poll_error } : {},
5569
+ next: w.still_running ? "Still reading: call talonic_parties_read with status: true (and wait_seconds) later." : failed ? "The read failed (read.error); tell the user. The contract keeps what its data says." : "Read done: open the contract with talonic_parties_contract."
5570
+ };
5571
+ });
5572
+ }
5573
+ var SYNC_DESCRIPTION = [
5574
+ "Bring the contracts' parties in line with the workspace's data products now: every contract row is filled again from its data (mapped fields, the field registry, the Contracts app), new rows are registered and sure duplicates are merged. A full pass runs in the background; named `row_ids` are filled at once. Fills only make suggestions and never overwrite a person's decision. Pass `wait_seconds` to wait until the full pass finished (polls the status every 5 s).",
5575
+ "USE WHEN: new contracts or changed data should show now instead of at the next scheduled sync (every 15 minutes), or after the user changed group companies or the CRM directory.",
5576
+ "NOT FOR: reading one contract's documents (talonic_parties_read).",
5577
+ "",
5578
+ "ARGS: `row_ids[]` (only these contract rows, up to 5000; omit for a full pass), `wait_seconds` (0-600, default 0; full pass only).",
5579
+ "RETURNS: { started: true }; after a wait also { syncing, synced_at, rows, waited_ms, still_running }."
5580
+ ].join("\n");
5581
+ var syncInputSchema = {
5582
+ row_ids: z.array(z.string().min(1).max(200)).min(1).max(5e3).optional().describe("Only these contract rows (contracts[].row.row_id); omit for a full pass."),
5583
+ wait_seconds: z.number().min(0).max(READ_MAX_WAIT_S).optional().describe(`Seconds to wait for a full pass to finish (0-${READ_MAX_WAIT_S}).`)
5584
+ };
5585
+ function handleSync(getToken, baseUrl, args, deps = {}) {
5586
+ const waitS = waitSeconds2(args.wait_seconds, READ_MAX_WAIT_S);
5587
+ return runTool(async () => {
5588
+ const started = await apiJson(
5589
+ getToken,
5590
+ baseUrl,
5591
+ "POST",
5592
+ "/v1/parties/sync",
5593
+ { body: args.row_ids ? { row_ids: args.row_ids } : {} }
5594
+ );
5595
+ if (waitS === 0 || args.row_ids) return started;
5596
+ const w = await waitUntil(
5597
+ () => apiJson(getToken, baseUrl, "GET", "/v1/parties/status"),
5598
+ (s) => !s.syncing,
5599
+ waitS,
5600
+ deps
5601
+ );
5474
5602
  return {
5475
- ...started ?? {},
5476
- status: status3,
5477
- waited_ms: now() - start,
5478
- still_running: stillRunning,
5479
- ...pollError ? { poll_error: pollError } : {},
5480
- next: stillRunning ? "Still reading: call talonic_parties_read with status: true (and wait_seconds) later." : "Read done: open the worklist with talonic_parties_issues."
5603
+ ...started,
5604
+ syncing: w.last.syncing ?? false,
5605
+ synced_at: w.last.synced_at ?? null,
5606
+ rows: w.last.rows,
5607
+ waited_ms: w.waited_ms,
5608
+ still_running: w.still_running,
5609
+ ...w.poll_error ? { poll_error: w.poll_error } : {}
5481
5610
  };
5482
5611
  });
5483
5612
  }
5613
+ var NAMES_DESCRIPTION = [
5614
+ "A party's other names: add an alias or a former name (with the day it ended), confirm or reject a suggested name, or remove a name a person added. Other names make the party findable under them (talonic_parties_search) and keep documents with an old name on the same party.",
5615
+ "USE WHEN: the user says a party is also called X, was renamed (former name with valid_to), or a suggested name in talonic_parties_party names[] is right or wrong.",
5616
+ "NOT FOR: the party's printed name (talonic_parties_party display_name); two parties that are one (talonic_parties_merge).",
5617
+ "",
5618
+ "ARGS: add: `party_id`, `name`, `kind` alias|former, `valid_to` (former only, YYYY-MM-DD), `note`; decide: `name_id` (names[].id from talonic_parties_party) and `state` confirmed|rejected; remove: `name_id` and `remove: true` (names from the data are rejected instead).",
5619
+ "RETURNS: add / decide: the name { id, party_id, name, kind, valid_to, state, source, decided_by, decided_at }; remove: { deleted: true }."
5620
+ ].join("\n");
5621
+ var namesInputSchema = {
5622
+ party_id: partyIdArg.optional().describe("Add: the party."),
5623
+ name: z.string().min(1).max(300).optional().describe("Add: the other name."),
5624
+ kind: z.enum(["alias", "former"]).optional().describe("Add: alias (also called) or former (renamed)."),
5625
+ valid_to: dateArg.nullable().optional().describe("Add, former name: the day it ended."),
5626
+ note: z.string().max(500).nullable().optional().describe("Add: where this comes from."),
5627
+ name_id: zUuid().optional().describe("Decide or remove: the name (names[].id)."),
5628
+ state: z.enum(["confirmed", "rejected"]).optional().describe("Decide: confirmed or rejected."),
5629
+ remove: z.boolean().optional().describe("Remove: true deletes a name a person added.")
5630
+ };
5631
+ function handleNames(getToken, baseUrl, args) {
5632
+ if (args.name_id) {
5633
+ if (args.party_id || args.name !== void 0 || args.kind) {
5634
+ return Promise.resolve(
5635
+ validationError(
5636
+ "name_id goes with state (decide) or remove: true (remove), not with add fields."
5637
+ )
5638
+ );
5639
+ }
5640
+ if (!!args.remove === !!args.state) {
5641
+ return Promise.resolve(validationError("with name_id pass either state or remove: true."));
5642
+ }
5643
+ const path = `/v1/parties/names/${args.name_id}`;
5644
+ return runTool(
5645
+ () => args.remove ? apiJson(getToken, baseUrl, "DELETE", path) : apiJson(getToken, baseUrl, "PATCH", path, { body: { state: args.state } })
5646
+ );
5647
+ }
5648
+ if (!args.party_id || !args.name || !args.kind) {
5649
+ return Promise.resolve(
5650
+ validationError(
5651
+ "pass party_id, name and kind to add a name, or name_id to decide or remove one."
5652
+ )
5653
+ );
5654
+ }
5655
+ if (args.valid_to && args.kind !== "former") {
5656
+ return Promise.resolve(validationError("valid_to belongs to a former name only."));
5657
+ }
5658
+ return runTool(
5659
+ () => apiJson(getToken, baseUrl, "POST", `/v1/parties/${args.party_id}/names`, {
5660
+ body: defined({
5661
+ name: args.name,
5662
+ kind: args.kind,
5663
+ valid_to: args.valid_to,
5664
+ note: args.note
5665
+ })
5666
+ })
5667
+ );
5668
+ }
5669
+ var DIRECTORY_LINK_DESCRIPTION = [
5670
+ "Link a party to its entry in the workspace's CRM directory, or unlink it (`external_id: null`). A linked party shows the CRM's address, phone and parent company over the contract sources (a person's own edit still wins); a person's link or unlink is never redone by the automatic linking. The party's contracts are filled again with the new link.",
5671
+ "USE WHEN: talonic_parties_party shows directory.link.state pick (several CRM entries match: issue crm_pick) and the user names the right one from directory.candidates[], or a link is wrong.",
5672
+ "NOT FOR: which address letters use when the CRM's differs (talonic_parties_address_choice).",
5673
+ "",
5674
+ "ARGS: `party_id`, `external_id` (the CRM entry's id from directory.candidates[].external_id; null unlinks), `kind` company|contact (the entry's kind; default company).",
5675
+ "RETURNS: the party's directory link { state, kind, external_id, candidates[], odd_address, address_choice, decided_by }."
5676
+ ].join("\n");
5677
+ var directoryLinkInputSchema = {
5678
+ party_id: partyIdArg,
5679
+ external_id: z.string().min(1).max(100).nullable().describe("The CRM entry's id (directory.candidates[].external_id); null unlinks."),
5680
+ kind: z.enum(["company", "contact"]).optional().describe("The entry's kind (default company).")
5681
+ };
5682
+ function handleDirectoryLink(getToken, baseUrl, args) {
5683
+ if (args.external_id === void 0) {
5684
+ return Promise.resolve(validationError("pass external_id, or null to unlink."));
5685
+ }
5686
+ return runTool(
5687
+ () => apiJson(getToken, baseUrl, "POST", `/v1/parties/${args.party_id}/directory-link`, {
5688
+ body: defined({ external_id: args.external_id, kind: args.kind })
5689
+ })
5690
+ );
5691
+ }
5692
+ var ADDRESS_CHOICE_DESCRIPTION = [
5693
+ "Choose which address a linked party's letters use when the CRM's address is far from the contract's (issue crm_address_differs): `crm` or `document`. The party's contracts are filled again with the choice; the automatic linking never changes it.",
5694
+ "USE WHEN: talonic_parties_party shows directory.crm_address and directory.document_address and the user says which is right.",
5695
+ "NOT FOR: typing a new address (talonic_parties_party with street, postcode, town).",
5696
+ "",
5697
+ "ARGS: `party_id`, `choice` crm|document.",
5698
+ "RETURNS: the party's directory link { state, kind, external_id, odd_address, address_choice, decided_by }."
5699
+ ].join("\n");
5700
+ var addressChoiceInputSchema = {
5701
+ party_id: partyIdArg,
5702
+ choice: z.enum(["crm", "document"]).describe("crm: the CRM's address; document: the contract's.")
5703
+ };
5704
+ function handleAddressChoice(getToken, baseUrl, args) {
5705
+ return runTool(
5706
+ () => apiJson(getToken, baseUrl, "POST", `/v1/parties/${args.party_id}/address-choice`, {
5707
+ body: { choice: args.choice }
5708
+ })
5709
+ );
5710
+ }
5484
5711
  var MEMBERS_DESCRIPTION = [
5485
5712
  "Add a contact person to a company or an owners' association (with their function), or remove a contact link. A contact is always a person; the company is a company or an owners' association. Adding the same person again updates the function.",
5486
5713
  "USE WHEN: the user names the person to write to at a company (e.g. the WEG's Verwalter contact), or a contact left.",
@@ -5519,8 +5746,8 @@ function handleMembers(getToken, baseUrl, args) {
5519
5746
  );
5520
5747
  }
5521
5748
  var GROUP_COMPANIES_DESCRIPTION = [
5522
- "Read the workspace's own companies (the group: lead company, subsidiaries, sisters), or replace them all with `companies`. The read uses them to tell our side from the contract partner. Replacing deletes every company not in the new list: read first, change, send the whole list, and only when the user asked.",
5523
- "USE WHEN: a read takes one of our own companies for the partner, or setting up the workspace.",
5749
+ "Read the workspace's own companies (the group: lead company, subsidiaries, sisters), or replace them all with `companies`. They tell our side from the contract partner: our own companies never become a contract partner. Replacing deletes every company not in the new list: read first, change, send the whole list, and only when the user asked.",
5750
+ "USE WHEN: one of our own companies shows up as a contract partner, or setting up the workspace.",
5524
5751
  "NOT FOR: contract partners (talonic_parties_party).",
5525
5752
  "",
5526
5753
  "ARGS: none to read; `companies[] { name, parent? (another name in the list), relation? subsidiary|sister|parent }` to replace.",
@@ -5543,7 +5770,7 @@ function handleGroupCompanies(getToken, baseUrl, args) {
5543
5770
  );
5544
5771
  }
5545
5772
  function registerPartiesTools(server, getToken, baseUrl) {
5546
- const tools = [
5773
+ const tools2 = [
5547
5774
  [
5548
5775
  "talonic_parties_status",
5549
5776
  "Contract parties status",
@@ -5554,20 +5781,12 @@ function registerPartiesTools(server, getToken, baseUrl) {
5554
5781
  ],
5555
5782
  [
5556
5783
  "talonic_parties_issues",
5557
- "Contract parties worklist",
5784
+ "Parties needing attention",
5558
5785
  ISSUES_DESCRIPTION4,
5559
5786
  issuesInputSchema2,
5560
5787
  readOnly4,
5561
5788
  (a) => handleIssues4(getToken, baseUrl, a)
5562
5789
  ],
5563
- [
5564
- "talonic_parties_contracts",
5565
- "Contracts with their parties",
5566
- CONTRACTS_DESCRIPTION,
5567
- contractsInputSchema,
5568
- readOnly4,
5569
- (a) => handleContracts(getToken, baseUrl, a)
5570
- ],
5571
5790
  [
5572
5791
  "talonic_parties_contract",
5573
5792
  "One contract's parties",
@@ -5576,6 +5795,30 @@ function registerPartiesTools(server, getToken, baseUrl) {
5576
5795
  readOnly4,
5577
5796
  (a) => handleContract2(getToken, baseUrl, a)
5578
5797
  ],
5798
+ [
5799
+ "talonic_parties_contracts",
5800
+ "A party's contracts",
5801
+ CONTRACTS_DESCRIPTION,
5802
+ sectionInputSchema,
5803
+ readOnly4,
5804
+ (a) => handlePartySection(getToken, baseUrl, "contracts", a)
5805
+ ],
5806
+ [
5807
+ "talonic_parties_documents",
5808
+ "A party's documents",
5809
+ DOCUMENTS_DESCRIPTION,
5810
+ sectionInputSchema,
5811
+ readOnly4,
5812
+ (a) => handlePartySection(getToken, baseUrl, "documents", a)
5813
+ ],
5814
+ [
5815
+ "talonic_parties_history",
5816
+ "A party's history",
5817
+ HISTORY_DESCRIPTION,
5818
+ sectionInputSchema,
5819
+ readOnly4,
5820
+ (a) => handlePartySection(getToken, baseUrl, "history", a)
5821
+ ],
5579
5822
  [
5580
5823
  "talonic_parties_search",
5581
5824
  "Search parties",
@@ -5593,6 +5836,32 @@ function registerPartiesTools(server, getToken, baseUrl) {
5593
5836
  write4(false, true),
5594
5837
  (a) => handleParty(getToken, baseUrl, a)
5595
5838
  ],
5839
+ [
5840
+ "talonic_parties_names",
5841
+ "A party's other names",
5842
+ NAMES_DESCRIPTION,
5843
+ namesInputSchema,
5844
+ // Removing a name deletes it; rejecting overrides a suggestion: destructive.
5845
+ write4(true, true),
5846
+ (a) => handleNames(getToken, baseUrl, a)
5847
+ ],
5848
+ [
5849
+ "talonic_parties_directory_link",
5850
+ "Link a party to the CRM",
5851
+ DIRECTORY_LINK_DESCRIPTION,
5852
+ directoryLinkInputSchema,
5853
+ // Replaces or removes the party's link: destructive.
5854
+ write4(true, true),
5855
+ (a) => handleDirectoryLink(getToken, baseUrl, a)
5856
+ ],
5857
+ [
5858
+ "talonic_parties_address_choice",
5859
+ "Choose a party's letter address",
5860
+ ADDRESS_CHOICE_DESCRIPTION,
5861
+ addressChoiceInputSchema,
5862
+ write4(true),
5863
+ (a) => handleAddressChoice(getToken, baseUrl, a)
5864
+ ],
5596
5865
  [
5597
5866
  "talonic_parties_set_role",
5598
5867
  "Add or change a contract role",
@@ -5604,7 +5873,7 @@ function registerPartiesTools(server, getToken, baseUrl) {
5604
5873
  ],
5605
5874
  [
5606
5875
  "talonic_parties_confirm",
5607
- "Confirm suggested roles",
5876
+ "Confirm checked roles",
5608
5877
  CONFIRM_DESCRIPTION2,
5609
5878
  confirmInputSchema2,
5610
5879
  write4(true),
@@ -5620,12 +5889,20 @@ function registerPartiesTools(server, getToken, baseUrl) {
5620
5889
  ],
5621
5890
  [
5622
5891
  "talonic_parties_read",
5623
- "Read parties from contracts",
5892
+ "Read one contract's parties",
5624
5893
  READ_DESCRIPTION,
5625
5894
  readInputSchema,
5626
5895
  write4(true),
5627
5896
  (a) => handleRead(getToken, baseUrl, a)
5628
5897
  ],
5898
+ [
5899
+ "talonic_parties_sync",
5900
+ "Refresh parties from the data",
5901
+ SYNC_DESCRIPTION,
5902
+ syncInputSchema,
5903
+ write4(true),
5904
+ (a) => handleSync(getToken, baseUrl, a)
5905
+ ],
5629
5906
  [
5630
5907
  "talonic_parties_members",
5631
5908
  "Company contacts",
@@ -5645,7 +5922,7 @@ function registerPartiesTools(server, getToken, baseUrl) {
5645
5922
  (a) => handleGroupCompanies(getToken, baseUrl, a)
5646
5923
  ]
5647
5924
  ];
5648
- for (const [name, title, description, inputSchema11, annotations, handler] of tools) {
5925
+ for (const [name, title, description, inputSchema11, annotations, handler] of tools2) {
5649
5926
  server.registerTool(
5650
5927
  name,
5651
5928
  { title, description, inputSchema: inputSchema11, annotations: { title, ...annotations } },
@@ -5672,7 +5949,7 @@ var COMPANY_DESCRIPTION = "One portfolio company's KPI table: rows are KPIs (cAR
5672
5949
  var CONFLICTS_DESCRIPTION = "Every conflict across all portfolio companies: the same KPI for the same period reported with different values by different documents. Each conflict lists the distinct values, the documents stating each (filename, locator, quote) and a one-line explanation (restatement, draft vs final, or unexplained: ask the company). Use this for 'where does my portfolio contradict itself'.";
5673
5950
  var REFRESH_DESCRIPTION = "Read new or changed documents for KPIs (runs in the background, takes minutes, uses credits). Call only when the user asks to include new documents; then poll talonic_portfolio_companies until documents_read catches up.";
5674
5951
  function registerPortfolioTools(server, getToken, baseUrl) {
5675
- const tools = [
5952
+ const tools2 = [
5676
5953
  [
5677
5954
  "talonic_portfolio_companies",
5678
5955
  "Portfolio companies",
@@ -5715,7 +5992,7 @@ function registerPortfolioTools(server, getToken, baseUrl) {
5715
5992
  () => runTool(() => apiJson(getToken, baseUrl, "POST", "/v1/portfolio/refresh"))
5716
5993
  ]
5717
5994
  ];
5718
- for (const [name, title, description, inputSchema11, annotations, handler] of tools) {
5995
+ for (const [name, title, description, inputSchema11, annotations, handler] of tools2) {
5719
5996
  server.registerTool(
5720
5997
  name,
5721
5998
  { title, description, inputSchema: inputSchema11, annotations: { title, ...annotations } },
@@ -5750,7 +6027,7 @@ var RUNS_DESCRIPTION2 = "Runs across all processes, newest first: state (running
5750
6027
  var WAITING_DESCRIPTION = "Sign-offs and forms waiting for the caller (the person behind the key): per process and step, how many items wait. Use talonic_process_status to see the items, then talonic_process_sign.";
5751
6028
  var SIGN_DESCRIPTION = "Sign a sign-off step of a run for the caller: approve all waiting items, or only `items`. A step that offers choices needs `decision` (one of its choices). Allowed only where the caller is assigned to the step. Signing moves real work on: call only when the user decides.";
5752
6029
  var GET_DESCRIPTION2 = "One process with its draft: fields, steps (id, kind, name, settings) and the arrows between them. Use it to see step ids before talonic_process_change with step_id, or to read what a process does.";
5753
- var CREATE_DESCRIPTION2 = "Set up a new process as a DRAFT. Pass `description` in the user's own words (what comes in, what is read or checked, who decides, what goes out), or `workflow_json` with an exported n8n workflow to take it over. Nothing runs and nothing is sent until talonic_process_publish. The answer names what a person still has to choose (`stillOpen`, `questions`): tell the user those. Uses a model call for `description`.";
6030
+ var CREATE_DESCRIPTION2 = "Set up a new process as a DRAFT. Pass `description` in the user's own words (what comes in, what is read or checked, who decides, what goes out), or `workflow_json` with an exported n8n workflow to take it over. Nothing runs and nothing is sent until talonic_process_publish. The answer names what a person still has to choose (`stillOpen`, `questions`): tell the user those.";
5754
6031
  var CHANGE_DESCRIPTION = "Change a process draft from an instruction in plain words: add, remove or reorder steps, change who decides, what is sent, any setting. With `step_id` only that step's settings change. Touches the draft only; the live version stays until talonic_process_publish. If the answer is `needs_confirmation`, NOTHING was saved: the change means fewer people or checks look at items. Tell the user exactly those points and ask; call again with `confirmed: true` only after they said yes, never on a first call.";
5755
6032
  var CHECK_DESCRIPTION = "What a draft still needs before it can go live (`stillNeeded`, per step), every problem the check finds, and what publishing would change against the live version. Call before talonic_process_publish and tell the user what is open.";
5756
6033
  var TEST_RUN_DESCRIPTION = "Run the DRAFT on real documents in a test copy: nothing is delivered, emailed or called. Steps not set up yet end the test (`endsAt`). Returns `processId` of the test copy and `runId`; follow with talonic_process_status on that processId.";
@@ -5765,7 +6042,7 @@ var SETUP_DESCRIPTION = "What processes of this workspace can use: who a step ca
5765
6042
  var MAILBOX_OWNERSHIP_DESCRIPTION = "Say whether a connected mailbox is one person's own (`individual`: only that person may put it on a process) or the company's (`company`: everyone who builds processes may). A governance decision: call only when the user asks.";
5766
6043
  var ADDRESS_DESCRIPTION = "The address other systems send items to (a webhook). Without `make` it only says whether one exists; the address itself is shown once, when made. With `make: true` it makes one and returns `path` to post to. An existing address is replaced only with `replace: true`: the old one stops working AT ONCE and whatever sends to it stops getting through, so ask the user first. `test: true` is the address of the test copy.";
5767
6044
  function registerProcessesTools(server, getToken, baseUrl) {
5768
- const tools = [
6045
+ const tools2 = [
5769
6046
  [
5770
6047
  "talonic_process_list",
5771
6048
  "Processes",
@@ -6109,7 +6386,7 @@ function registerProcessesTools(server, getToken, baseUrl) {
6109
6386
  )
6110
6387
  ]
6111
6388
  ];
6112
- for (const [name, title, description, inputSchema11, annotations, handler] of tools) {
6389
+ for (const [name, title, description, inputSchema11, annotations, handler] of tools2) {
6113
6390
  server.registerTool(
6114
6391
  name,
6115
6392
  { title, description, inputSchema: inputSchema11, annotations: { title, ...annotations } },
@@ -6273,7 +6550,7 @@ function handleCrosswalk(getToken, baseUrl, args) {
6273
6550
  return runTool(() => apiJson(getToken, baseUrl, "GET", domainPath(args.domain, "/crosswalk")));
6274
6551
  }
6275
6552
  function registerMasterRecordsTools(server, getToken, baseUrl) {
6276
- const tools = [
6553
+ const tools2 = [
6277
6554
  [
6278
6555
  "talonic_master_records_config",
6279
6556
  "Read the Master Records configuration",
@@ -6339,7 +6616,7 @@ function registerMasterRecordsTools(server, getToken, baseUrl) {
6339
6616
  (a) => handleCrosswalk(getToken, baseUrl, a)
6340
6617
  ]
6341
6618
  ];
6342
- for (const [name, title, description, inputSchema11, annotations, handler] of tools) {
6619
+ for (const [name, title, description, inputSchema11, annotations, handler] of tools2) {
6343
6620
  server.registerTool(
6344
6621
  name,
6345
6622
  { title, description, inputSchema: inputSchema11, annotations: { title, ...annotations } },
@@ -6593,7 +6870,7 @@ function handleQuestions(getToken, baseUrl, args) {
6593
6870
  );
6594
6871
  }
6595
6872
  function registerSubmissionsTools(server, getToken, baseUrl) {
6596
- const tools = [
6873
+ const tools2 = [
6597
6874
  [
6598
6875
  "talonic_submissions_specs",
6599
6876
  "Submission target structures",
@@ -6683,7 +6960,7 @@ function registerSubmissionsTools(server, getToken, baseUrl) {
6683
6960
  (a) => handleExport(getToken, baseUrl, a)
6684
6961
  ]
6685
6962
  ];
6686
- for (const [name, title, description, inputSchema11, annotations, handler] of tools) {
6963
+ for (const [name, title, description, inputSchema11, annotations, handler] of tools2) {
6687
6964
  server.registerTool(
6688
6965
  name,
6689
6966
  { title, description, inputSchema: inputSchema11, annotations: { title, ...annotations } },
@@ -6702,7 +6979,7 @@ var readOnly9 = {
6702
6979
  idempotentHint: true,
6703
6980
  openWorldHint: false
6704
6981
  };
6705
- var DOCUMENTS_DESCRIPTION = [
6982
+ var DOCUMENTS_DESCRIPTION2 = [
6706
6983
  "Find contracts and invoices in the workspace to build a price baseline from.",
6707
6984
  "USE WHEN: picking the contract for talonic_price_baseline_extract or the invoice for talonic_price_baseline_compare.",
6708
6985
  "NOT FOR: general document search across all content (talonic_search).",
@@ -7223,7 +7500,7 @@ function handleAssume(getToken, baseUrl, args) {
7223
7500
  };
7224
7501
  return args.action === "create" ? runTool(() => apiJson(getToken, baseUrl, "POST", "/v1/price-baseline/assumptions", { body })) : runTool(() => apiJson(getToken, baseUrl, "PUT", path(args.assumption_id), { body }));
7225
7502
  }
7226
- var SYNC_DESCRIPTION = [
7503
+ var SYNC_DESCRIPTION2 = [
7227
7504
  "Sync external price data now (BEHG, Bundesbank, Destatis, EEX via Energy-Charts, DWD degree days), or change how often a series syncs.",
7228
7505
  "USE WHEN: talonic_price_baseline_indices `view: sync` shows a series as due, failed or stale, or a contract waits on a published value that should be out by now.",
7229
7506
  "NOT FOR: series with no feed, e.g. THE levies and grid tariffs (talonic_price_baseline_add_index_values); a backfill for a specific year range (talonic_price_baseline_refresh_indices).",
@@ -7231,13 +7508,13 @@ var SYNC_DESCRIPTION = [
7231
7508
  "ARGS: sync: `keys` (series keys; omit to sync every shared series whose interval has passed). Schedule: `key` with `sync_hours` (1\u20132160) and/or `active` (false pauses; a shared series changes for everyone).",
7232
7509
  "RETURNS: sync data[] { series, stored, error } (a failed series reports its error, never an empty success); schedule, the series definition. Values arriving replace any assumption standing in for them."
7233
7510
  ].join("\n");
7234
- var syncInputSchema = {
7511
+ var syncInputSchema2 = {
7235
7512
  keys: z.array(z.string().min(1)).max(50).optional().describe("Series keys to fetch now."),
7236
7513
  key: z.string().min(1).max(120).optional().describe("Series whose schedule to change."),
7237
7514
  sync_hours: z.number().int().min(1).max(2160).optional().describe("Sync interval in hours."),
7238
7515
  active: z.boolean().optional().describe("false pauses syncing.")
7239
7516
  };
7240
- function handleSync(getToken, baseUrl, args) {
7517
+ function handleSync2(getToken, baseUrl, args) {
7241
7518
  const schedule = args.key !== void 0 || args.sync_hours !== void 0 || args.active !== void 0;
7242
7519
  if (schedule) {
7243
7520
  if (args.keys?.length) {
@@ -7303,7 +7580,7 @@ function handleImport2(getToken, baseUrl, args) {
7303
7580
  );
7304
7581
  }
7305
7582
  function registerPriceBaselineTools(server, getToken, baseUrl) {
7306
- const write9 = (idempotent) => ({
7583
+ const write10 = (idempotent) => ({
7307
7584
  readOnlyHint: false,
7308
7585
  destructiveHint: false,
7309
7586
  idempotentHint: idempotent,
@@ -7313,7 +7590,7 @@ function registerPriceBaselineTools(server, getToken, baseUrl) {
7313
7590
  "talonic_price_baseline_documents",
7314
7591
  {
7315
7592
  title: "Find contracts and invoices",
7316
- description: DOCUMENTS_DESCRIPTION,
7593
+ description: DOCUMENTS_DESCRIPTION2,
7317
7594
  inputSchema: documentsInputSchema,
7318
7595
  annotations: readOnly9
7319
7596
  },
@@ -7325,7 +7602,7 @@ function registerPriceBaselineTools(server, getToken, baseUrl) {
7325
7602
  title: "Build or enrich a price model from a contract",
7326
7603
  description: EXTRACT_DESCRIPTION,
7327
7604
  inputSchema: extractInputSchema,
7328
- annotations: write9(false)
7605
+ annotations: write10(false)
7329
7606
  },
7330
7607
  async (args) => handleExtract2(getToken, baseUrl, args)
7331
7608
  );
@@ -7345,7 +7622,7 @@ function registerPriceBaselineTools(server, getToken, baseUrl) {
7345
7622
  title: "Edit or confirm a price model",
7346
7623
  description: UPDATE_DESCRIPTION,
7347
7624
  inputSchema: updateInputSchema,
7348
- annotations: write9(true)
7625
+ annotations: write10(true)
7349
7626
  },
7350
7627
  async (args) => handleUpdate(getToken, baseUrl, args)
7351
7628
  );
@@ -7375,7 +7652,7 @@ function registerPriceBaselineTools(server, getToken, baseUrl) {
7375
7652
  title: "Check an invoice against the contract",
7376
7653
  description: COMPARE_DESCRIPTION,
7377
7654
  inputSchema: compareInputSchema,
7378
- annotations: write9(false)
7655
+ annotations: write10(false)
7379
7656
  },
7380
7657
  async (args) => handleCompare(getToken, baseUrl, args)
7381
7658
  );
@@ -7405,7 +7682,7 @@ function registerPriceBaselineTools(server, getToken, baseUrl) {
7405
7682
  title: "Fetch public index values",
7406
7683
  description: REFRESH_DESCRIPTION2,
7407
7684
  inputSchema: refreshInputSchema,
7408
- annotations: { ...write9(true), openWorldHint: true }
7685
+ annotations: { ...write10(true), openWorldHint: true }
7409
7686
  },
7410
7687
  async (args) => handleRefresh(getToken, baseUrl, args)
7411
7688
  );
@@ -7415,7 +7692,7 @@ function registerPriceBaselineTools(server, getToken, baseUrl) {
7415
7692
  title: "Enter sourced index values",
7416
7693
  description: MANUAL_DESCRIPTION,
7417
7694
  inputSchema: manualInputSchema,
7418
- annotations: write9(true)
7695
+ annotations: write10(true)
7419
7696
  },
7420
7697
  async (args) => handleManual(getToken, baseUrl, args)
7421
7698
  );
@@ -7445,7 +7722,7 @@ function registerPriceBaselineTools(server, getToken, baseUrl) {
7445
7722
  title: "Answer an open contract input",
7446
7723
  description: ANSWER_DESCRIPTION,
7447
7724
  inputSchema: answerInputSchema,
7448
- annotations: write9(true)
7725
+ annotations: write10(true)
7449
7726
  },
7450
7727
  async (args) => handleAnswer(getToken, baseUrl, args)
7451
7728
  );
@@ -7465,7 +7742,7 @@ function registerPriceBaselineTools(server, getToken, baseUrl) {
7465
7742
  title: "Make, replace or withdraw an assumption",
7466
7743
  description: ASSUME_DESCRIPTION,
7467
7744
  inputSchema: assumeInputSchema,
7468
- annotations: { ...write9(false), destructiveHint: true }
7745
+ annotations: { ...write10(false), destructiveHint: true }
7469
7746
  },
7470
7747
  async (args) => handleAssume(getToken, baseUrl, args)
7471
7748
  );
@@ -7473,11 +7750,11 @@ function registerPriceBaselineTools(server, getToken, baseUrl) {
7473
7750
  "talonic_price_baseline_sync_series",
7474
7751
  {
7475
7752
  title: "Sync external price data",
7476
- description: SYNC_DESCRIPTION,
7477
- inputSchema: syncInputSchema,
7478
- annotations: { ...write9(true), openWorldHint: true }
7753
+ description: SYNC_DESCRIPTION2,
7754
+ inputSchema: syncInputSchema2,
7755
+ annotations: { ...write10(true), openWorldHint: true }
7479
7756
  },
7480
- async (args) => handleSync(getToken, baseUrl, args)
7757
+ async (args) => handleSync2(getToken, baseUrl, args)
7481
7758
  );
7482
7759
  server.registerTool(
7483
7760
  "talonic_price_baseline_imports",
@@ -7495,7 +7772,7 @@ function registerPriceBaselineTools(server, getToken, baseUrl) {
7495
7772
  title: "Import contracts from data capture",
7496
7773
  description: IMPORT_DESCRIPTION2,
7497
7774
  inputSchema: importInputSchema2,
7498
- annotations: write9(true)
7775
+ annotations: write10(true)
7499
7776
  },
7500
7777
  async (args) => handleImport2(getToken, baseUrl, args)
7501
7778
  );
@@ -7545,8 +7822,8 @@ var adminPayloadAccessInput = {
7545
7822
  function apiUrl(baseUrl, path, query) {
7546
7823
  const base = (baseUrl ?? DEFAULT_BASE3).replace(/\/$/, "");
7547
7824
  const url = new URL(`${base}${path}`);
7548
- for (const [key, value] of Object.entries(query ?? {})) {
7549
- if (value !== void 0 && value !== "") url.searchParams.set(key, String(value));
7825
+ for (const [key2, value] of Object.entries(query ?? {})) {
7826
+ if (value !== void 0 && value !== "") url.searchParams.set(key2, String(value));
7550
7827
  }
7551
7828
  return url.toString();
7552
7829
  }
@@ -7880,72 +8157,580 @@ function registerAppsTools(server, getToken, baseUrl) {
7880
8157
  async (args) => handleListApps(getToken, baseUrl, args)
7881
8158
  );
7882
8159
  }
7883
- var DECIDE_SCOPE = "apps:decide";
7884
- var TASK_STATUSES2 = [
7885
- "available",
7886
- "claimed",
7887
- "submitted",
7888
- "released",
7889
- "failed",
7890
- "timed_out",
7891
- "cancelled"
7892
- ];
7893
- var PACKAGE_PAGE_LIMIT_MAX = 2e3;
8160
+ var APP_MODES = ["rules", "assisted", "external", "autonomous"];
8161
+ var REVIEW_KINDS = ["resolution", "approval", "data_request", "judgment"];
8162
+ var REVIEW_STATUSES = ["open", "assigned", "resolved", "expired", "cancelled"];
8163
+ var VERDICT_OUTCOMES = ["passed", "failed", "indeterminate", "not_applicable"];
7894
8164
  var appId = zUuid().describe(
7895
- "Id of an External-mode app (from talonic_list_apps, where mode is 'external')."
8165
+ "App id: the UUID `id` from talonic_list_apps or talonic_create_app (not the app_\u2026 public id)."
7896
8166
  );
7897
- var taskId2 = zUuid().describe("Decision task UUID.");
7898
- var executionEpoch2 = z.number().int().min(1).max(2147483647).describe("Execution epoch returned by the successful claim. Stale epochs are rejected with 409.");
7899
- var status2 = z.enum(TASK_STATUSES2).optional().describe("Optional task-status filter.");
7900
- var listLimit = z.number().int().min(1).max(100).optional().describe("Page size (default 50).");
7901
- var cursor2 = z.string().min(1).optional().describe("Opaque cursor from pagination.next_cursor.");
7902
- var packageCursor = z.string().min(1).optional().describe(
7903
- "Opaque package cursor: package.first_cursor from the claim, then pagination.next_cursor. Omit for the first page."
8167
+ var runId = zUuid().describe(
8168
+ "App run UUID (run_id from talonic_run_app or talonic_list_app_runs)."
7904
8169
  );
7905
- var packageLimit = z.number().int().min(1).max(PACKAGE_PAGE_LIMIT_MAX).optional().describe(
7906
- `Records per page, 1 to ${PACKAGE_PAGE_LIMIT_MAX}. Defaults to the platform page size (package.page_size from the claim).`
8170
+ var reviewId = zUuid().describe("Human Review UUID (id from talonic_list_app_reviews).");
8171
+ var limit2 = z.number().int().min(1).max(200).optional().describe("Page size (default 50, max 200).");
8172
+ var offset = z.number().int().min(0).optional().describe("Rows to skip before the page.");
8173
+ var jsonObject = () => z.record(z.string(), z.json());
8174
+ var READ_ONLY3 = {
8175
+ readOnlyHint: true,
8176
+ destructiveHint: false,
8177
+ idempotentHint: true,
8178
+ openWorldHint: false
8179
+ };
8180
+ var MUTATING2 = {
8181
+ readOnlyHint: false,
8182
+ destructiveHint: false,
8183
+ idempotentHint: false,
8184
+ openWorldHint: false
8185
+ };
8186
+ var appPath = (id, suffix = "") => `/v1/apps/${encodeURIComponent(id)}${suffix}`;
8187
+ var runPath = (id, suffix = "") => `/v1/runs/${encodeURIComponent(id)}${suffix}`;
8188
+ var reviewPath = (id, suffix = "") => `/v1/reviews/${encodeURIComponent(id)}${suffix}`;
8189
+ var get = (t, b, path, params) => runTool(() => apiJson(t, b, "GET", path, params ? { params } : {}));
8190
+ var send = (t, b, method, path, body) => runTool(() => apiJson(t, b, method, path, body === void 0 ? {} : { body }));
8191
+ function defined2(o) {
8192
+ return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== void 0));
8193
+ }
8194
+ var handleGetApp = (t, b, a) => get(t, b, appPath(a.app_id));
8195
+ var handleCreateApp = (t, b, a) => send(t, b, "POST", "/v1/apps", defined2({ ...a }));
8196
+ var handleSaveAppDraft = (t, b, a) => send(t, b, "PATCH", appPath(a.app_id), { content: a.content });
8197
+ var handleListAppVersions = (t, b, a) => get(t, b, appPath(a.app_id, "/versions"));
8198
+ var handlePublishApp = (t, b, a) => send(t, b, "POST", appPath(a.app_id, `/versions/${a.version}/publish`));
8199
+ var handleSetAppEnabled = (t, b, a, enabled) => send(t, b, "POST", appPath(a.app_id, enabled ? "/enable" : "/disable"));
8200
+ var handleRunApp = (t, b, a) => send(
8201
+ t,
8202
+ b,
8203
+ "POST",
8204
+ appPath(a.app_id, "/runs"),
8205
+ defined2({ input: a.input ?? {}, dry_run: a.dry_run, idempotency_key: a.idempotency_key })
7907
8206
  );
7908
- var outcome = z.record(z.string(), z.json()).describe(
7909
- "The decision, shaped by output_contract from the claim: for a plain JSON Schema contract the object that schema validates; for a verdict_matrix contract { subjects: [{ subject_key, rule_outcomes, auto?, detail? }] }; for a record_set contract its fields-and-rows envelope."
8207
+ var handleListAppRuns = (t, b, a) => get(t, b, appPath(a.app_id, "/runs"), { limit: a.limit, offset: a.offset });
8208
+ async function handleGetAppRun(t, b, a) {
8209
+ return runTool(async () => {
8210
+ const run = await apiJson(t, b, "GET", runPath(a.run_id));
8211
+ if (!a.include_events) return run;
8212
+ const events = await apiJson(t, b, "GET", runPath(a.run_id, "/events"));
8213
+ return { run, events: events?.events ?? [] };
8214
+ });
8215
+ }
8216
+ var handleGetRunRecord = (t, b, a) => get(t, b, runPath(a.run_id, "/record"));
8217
+ var handleGetRunVerdicts = (t, b, a) => get(t, b, runPath(a.run_id, "/verdicts"), {
8218
+ rolled: a.rolled,
8219
+ auto: a.auto,
8220
+ rule: a.rule,
8221
+ status: a.status,
8222
+ limit: a.limit,
8223
+ cursor: a.cursor
8224
+ });
8225
+ var handleListAppReviews = (t, b, a) => get(t, b, "/v1/reviews", { ...a });
8226
+ var handleRaiseAppReview = (t, b, a) => {
8227
+ const { app_id, ...body } = a;
8228
+ return send(t, b, "POST", appPath(app_id, "/reviews"), defined2(body));
8229
+ };
8230
+ var handleResolveAppReview = (t, b, a) => send(
8231
+ t,
8232
+ b,
8233
+ "POST",
8234
+ reviewPath(a.review_id, "/resolve"),
8235
+ defined2({ values: a.values, feedback: a.feedback })
7910
8236
  );
7911
- var evidence = z.array(z.string().min(1).max(512)).max(1e4).describe(
7912
- "Provenance locators the decision relied on, each copied verbatim from the input package (or a db:/ref: locator the app holds a read grant on). Required; [] is accepted only when the app allows unevidenced decisions."
8237
+ var handleInterviewReview = (t, b, a) => send(
8238
+ t,
8239
+ b,
8240
+ "POST",
8241
+ reviewPath(a.review_id, "/interview"),
8242
+ defined2({ message: a.message, transcript: a.transcript })
7913
8243
  );
7914
- var rationale = z.string().min(1).max(4e3).describe(
7915
- "Short decision rationale (a summary, never private chain-of-thought), up to 4,000 characters."
8244
+ var handleListAppPrecedents = (t, b, a) => get(t, b, appPath(a.app_id, "/precedents"), {
8245
+ similar_to: a.similar_to ? JSON.stringify(a.similar_to) : void 0
8246
+ });
8247
+ var handleGetAppLogic = (t, b, a) => get(t, b, appPath(a.app_id, "/logic"));
8248
+ var handleGetAppFields = (t, b, a) => get(t, b, appPath(a.app_id, "/logic/fields"));
8249
+ var handleInterpretRules = (t, b, a) => send(
8250
+ t,
8251
+ b,
8252
+ "POST",
8253
+ appPath(a.app_id, "/logic/compile"),
8254
+ defined2({
8255
+ card_ids: a.card_ids && a.card_ids.length > 0 ? a.card_ids : void 0,
8256
+ guidance: a.guidance || void 0,
8257
+ locale: a.locale
8258
+ })
7916
8259
  );
7917
- var confidence = z.number().min(0).max(1).optional().describe("Optional confidence from 0 to 1.");
7918
- var serviceVersion = z.string().min(1).max(64).optional().describe("Optional build identifier of the deciding service; recorded as decided_by.label.");
7919
- var failReason = z.string().min(1).max(2e3).describe(
7920
- "Why the task cannot be decided, up to 2,000 characters. Recorded on the Human Review the fail raises."
8260
+ var handleProposeEdit = (t, b, a) => send(t, b, "POST", appPath(a.app_id, "/edit-proposals"), { instruction: a.instruction });
8261
+ var handleApplyEdit = (t, b, a) => send(t, b, "POST", appPath(a.app_id, "/edit-proposals/apply"), { ops: a.ops });
8262
+ var handleGetAcceptance = (t, b, a) => get(t, b, appPath(a.app_id, "/acceptance"));
8263
+ var handleSaveAcceptance = (t, b, a) => send(
8264
+ t,
8265
+ b,
8266
+ "PUT",
8267
+ appPath(a.app_id, "/acceptance"),
8268
+ defined2({ cases: a.cases, tolerance: a.tolerance })
7921
8269
  );
7922
- var listInput2 = { app_id: appId, status: status2, limit: listLimit, cursor: cursor2 };
7923
- var idInput2 = { task_id: taskId2 };
7924
- var packageInput = { task_id: taskId2, cursor: packageCursor, limit: packageLimit };
7925
- var epochInput = { task_id: taskId2, execution_epoch: executionEpoch2 };
7926
- var submitInput2 = {
7927
- task_id: taskId2,
7928
- execution_epoch: executionEpoch2,
7929
- outcome,
7930
- evidence,
7931
- rationale,
7932
- confidence,
7933
- service_version: serviceVersion
7934
- };
7935
- var failInput = { task_id: taskId2, execution_epoch: executionEpoch2, reason: failReason };
7936
- function taskPath(taskId3, suffix = "") {
7937
- return `/v1/decision-tasks/${encodeURIComponent(taskId3)}${suffix}`;
7938
- }
7939
- function handleListDecisionTasks(getToken, baseUrl, args) {
7940
- return runTool(
7941
- () => apiJson(
7942
- getToken,
7943
- baseUrl,
7944
- "GET",
7945
- `/v1/apps/${encodeURIComponent(args.app_id)}/decision-tasks`,
7946
- {
7947
- params: { status: args.status, limit: args.limit, cursor: args.cursor }
7948
- }
8270
+ var handleCheckAcceptance = (t, b, a) => get(t, b, appPath(a.app_id, "/acceptance/check"), { run_id: a.run_id });
8271
+ var BUILD_FLOW = "FLOW: talonic_create_app -> talonic_save_app_draft -> talonic_interpret_app_rules -> talonic_publish_app -> talonic_run_app (dry_run first) -> talonic_get_app_run / talonic_get_run_verdicts -> talonic_save_app_acceptance + talonic_check_app_acceptance -> talonic_enable_app.";
8272
+ var D = {
8273
+ get: [
8274
+ "Read one app's manifest: mode, active version, enabled state, contract (what it reads and acts on), output contract, thresholds, triggers, fallback.",
8275
+ "USE WHEN: inspecting an app before changing or running it. NOT FOR: the editable draft (talonic_get_app_logic) or listing apps (talonic_list_apps)."
8276
+ ].join("\n"),
8277
+ create: [
8278
+ "Create a new app. It starts disabled with no versions; the slug can no longer change once a version is published.",
8279
+ "USE WHEN: the user asks to set up a new app. ARGS: slug (lowercase letters, digits, hyphens, 3-64 chars), display_name, mode, optional one-sentence description.",
8280
+ "Modes: rules (decides from written rules), assisted (rules with people confirming), external (an outside agent decides through the decision-task tools), autonomous (finds candidate rules in the app's data).",
8281
+ "RETURNS: the manifest; use its `id` (UUID) with every other app tool.",
8282
+ BUILD_FLOW
8283
+ ].join("\n"),
8284
+ saveDraft: [
8285
+ "Create or replace the app's single draft version: logic (rule sentences, or the external connection), input bindings, output contract (JSON Schema 2020-12), thresholds, triggers, fallback. Drafts are the only versions that can change.",
8286
+ "USE WHEN: authoring configuration in full. For a plain-language change to an existing draft prefer talonic_propose_app_edit + talonic_apply_app_edit.",
8287
+ "ARGS: app_id, content (the full version content object; read the current one with talonic_get_app_logic). RETURNS: { version, status, content_hash }; pass version to talonic_publish_app."
8288
+ ].join("\n"),
8289
+ versions: [
8290
+ "List an app's versions, newest first: version number, status (draft, published, superseded), content hash, published_at.",
8291
+ "USE WHEN: you need the draft's version number for talonic_publish_app, or to see what is live."
8292
+ ].join("\n"),
8293
+ publish: [
8294
+ "Publish the app's draft: freezes it, makes it the active version (the previous one is superseded) and locks the slug on first publish.",
8295
+ "USE WHEN: the draft is tested (talonic_run_app with dry_run, talonic_check_app_acceptance) and the user wants it live. Publishing does not enable the app; call talonic_enable_app for triggers to fire.",
8296
+ "ARGS: app_id and the draft's version number (from talonic_save_app_draft or talonic_list_app_versions). A number that is not the current draft is HTTP 409."
8297
+ ].join("\n"),
8298
+ enable: [
8299
+ "Enable an app so its triggers fire and it can be run. Needs a published version. Enabling an app that acts on outside systems needs a workspace owner (HTTP 403 otherwise).",
8300
+ "USE WHEN: the user asks to switch the app on. ARGS: app_id."
8301
+ ].join("\n"),
8302
+ disable: [
8303
+ "Disable an app at once (the kill switch): triggers stop and open work is no longer offered. Past runs and records are kept.",
8304
+ "USE WHEN: the user asks to stop or pause an app. ARGS: app_id."
8305
+ ].join("\n"),
8306
+ run: [
8307
+ "Start one run of an app's active version and return it. A rules app usually finishes in the call with its decision; an external app stops at awaiting_decision until its decision task is submitted.",
8308
+ "USE WHEN: testing or executing an app. Set dry_run:true first: a full trace with no side effects (no actions, no webhooks to outside systems).",
8309
+ "ARGS: app_id, optional input object, dry_run, idempotency_key (reusing a key returns the existing run instead of starting another). Consumes credits.",
8310
+ "NEXT: talonic_get_app_run for status and decision; talonic_get_run_verdicts for per-subject results."
8311
+ ].join("\n"),
8312
+ listRuns: [
8313
+ "List an app's runs, newest first, with status, decision and who decided; `total` counts every run.",
8314
+ "ARGS: app_id, optional limit (max 200) and offset."
8315
+ ].join("\n"),
8316
+ getRun: [
8317
+ "Read one run: status, decision, decided_by, thresholds applied, reviews raised, timing.",
8318
+ "USE WHEN: checking a run you started or found. include_events:true adds the run's journal (every event in order).",
8319
+ "NOT FOR: Spec/pipeline runs (talonic_get_run). ARGS: run_id, optional include_events."
8320
+ ].join("\n"),
8321
+ record: [
8322
+ "Export a finished run's sealed decision record: the immutable, audit-ready result with its decision, who decided (rules, a person or an outside agent) and the evidence.",
8323
+ "USE WHEN: the user needs the final, auditable outcome. A run that has not finished has no record yet (HTTP 404). ARGS: run_id."
8324
+ ].join("\n"),
8325
+ verdicts: [
8326
+ "Read a batch run's per-subject results: a summary plus one row per subject with its overall outcome, the auto flag, and each rule's outcome with reasons and evidence.",
8327
+ "USE WHEN: inspecting what a run decided per record. Single-decision runs have none (HTTP 404; use talonic_get_app_run).",
8328
+ "ARGS: run_id; optional rolled (overall outcome), auto, rule + status (always together), limit (max 200), cursor (from `next`)."
8329
+ ].join("\n"),
8330
+ listReviews: [
8331
+ "List Human Reviews: questions apps raised for a person (approvals, missing data, judgment calls, exceptions), newest first, with `total`.",
8332
+ "USE WHEN: finding open reviews to answer, or checking the result of one already resolved (status 'resolved' shows its values). Omit app_id for the whole workspace.",
8333
+ "ARGS: optional app_id, status, kind, assignee_user_id, limit (max 200), offset."
8334
+ ].join("\n"),
8335
+ raiseReview: [
8336
+ "Ask a person a question on an app instead of guessing: a Human Review with a JSON Schema for the answer.",
8337
+ "USE WHEN: a decision needs a person's input. ARGS: app_id, kind (resolution | approval | data_request | judgment), question, input_contract (JSON Schema the answer must satisfy), optional run_id, context, team_id.",
8338
+ "NEXT: the answer arrives through talonic_resolve_app_review (or the web app); read it with talonic_list_app_reviews status 'resolved'."
8339
+ ].join("\n"),
8340
+ resolveReview: [
8341
+ "Answer a Human Review: values (validated against the review's input_contract) plus optional feedback that teaches the app (proposal_verdict correct | incorrect | partial, correction, generalize).",
8342
+ "USE WHEN: the user gives the answer. 'approval' reviews accept only a person's answer; an API key or agent is refused (HTTP 403). Needs operate access on the app.",
8343
+ "RETURNS: the resolved review with its values. ARGS: review_id, values, optional feedback."
8344
+ ].join("\n"),
8345
+ interview: [
8346
+ "Hold one turn of a guided conversation on an open Human Review: send the reviewer's message and the earlier turns (the server keeps no state); get back a follow-up question or a readback with proposed answer values.",
8347
+ "ready:true only when the proposed values satisfy the review's input contract. Nothing is submitted: finish with talonic_resolve_app_review.",
8348
+ "ARGS: review_id, message, optional transcript [{ role: user | assistant, text }]."
8349
+ ].join("\n"),
8350
+ precedents: [
8351
+ "List an app's precedents: past resolved reviews it reuses for similar future runs.",
8352
+ "ARGS: app_id, optional similar_to (match keys object) to narrow to similar cases. An app with none returns an empty list."
8353
+ ].join("\n"),
8354
+ getLogic: [
8355
+ "Read an app's logic: the editable draft and the active published version, including each rule with its interpretation state and plain-language readback.",
8356
+ "USE WHEN: before editing, or to get the draft's full content for talonic_save_app_draft."
8357
+ ].join("\n"),
8358
+ getFields: [
8359
+ "List the fields the app's rules can use, per bound data source. This is everything the app can see.",
8360
+ "USE WHEN: before writing or fixing rules, so they name fields that exist."
8361
+ ].join("\n"),
8362
+ interpret: [
8363
+ "Turn the draft's pending rule sentences into checkable rules against the app's fields, and save the draft.",
8364
+ "ARGS: app_id; optional card_ids (default: all pending), guidance (plain language, e.g. 'the city is in shipper_city_state') for rules that stayed pending, locale for the readbacks.",
8365
+ "RETURNS: the rules plus warnings saying why any rule stayed pending."
8366
+ ].join("\n"),
8367
+ proposeEdit: [
8368
+ "Turn a plain-language change request into typed edit operations on the app's rules (add, rewrite, delete, pause, resume, fallback, mode). Nothing is saved.",
8369
+ "USE WHEN: the user describes a change in words. Show the summary to the user, then apply the accepted ops with talonic_apply_app_edit."
8370
+ ].join("\n"),
8371
+ applyEdit: [
8372
+ "Apply accepted edit operations from talonic_propose_app_edit to the draft. They are re-checked against the current draft; changed rules are interpreted again and warnings returned.",
8373
+ "ARGS: app_id, ops (from the proposal, unchanged)."
8374
+ ].join("\n"),
8375
+ getAcceptance: [
8376
+ "Read the app's acceptance set: the labeled expected results a correct run must reproduce, and the accepted mismatch share. null when none is saved."
8377
+ ].join("\n"),
8378
+ saveAcceptance: [
8379
+ "Replace the app's acceptance set: the expected results a correct run must reproduce, plus tolerance (accepted mismatch share, 0 to 1). This is the app's definition of done.",
8380
+ "ARGS: app_id, cases (per subject: subject_key + expected_outcome and/or expected_auto; for single-decision apps: expected_decision), optional tolerance (default 0)."
8381
+ ].join("\n"),
8382
+ checkAcceptance: [
8383
+ "Score a run against the app's acceptance set by comparing recorded results: the same run always gets the same score. Returns score, pass/fail and each mismatch.",
8384
+ "USE WHEN: after talonic_run_app, to decide whether the app is ready to publish or still correct. ARGS: app_id, optional run_id (default: the latest completed run)."
8385
+ ].join("\n")
8386
+ };
8387
+ var acceptanceCase = z.object({
8388
+ subject_key: z.string().min(1).max(256).optional(),
8389
+ expected_outcome: z.enum(VERDICT_OUTCOMES).optional(),
8390
+ expected_auto: z.boolean().optional(),
8391
+ expected_decision: z.string().min(1).max(64).optional(),
8392
+ note: z.string().max(300).optional()
8393
+ }).describe(
8394
+ "One expected result: subject_key + expected_outcome (and/or expected_auto) for batch apps, or expected_decision for single-decision apps."
8395
+ );
8396
+ function registerAppsToolset(server, getToken, baseUrl) {
8397
+ const t = getToken;
8398
+ const b = baseUrl;
8399
+ const reg = (name, title, description, inputSchema11, annotations, handler) => server.registerTool(
8400
+ name,
8401
+ { title, description, inputSchema: inputSchema11, annotations: { title, ...annotations } },
8402
+ handler
8403
+ );
8404
+ reg(
8405
+ "talonic_create_app",
8406
+ "Create App",
8407
+ D.create,
8408
+ {
8409
+ slug: z.string().regex(/^[a-z0-9][a-z0-9-]{1,62}[a-z0-9]$/).describe("Lowercase letters, digits and hyphens, 3-64 chars."),
8410
+ display_name: z.string().min(1).max(200),
8411
+ mode: z.enum(APP_MODES),
8412
+ description: z.string().max(2e3).optional().describe("One sentence about the app.")
8413
+ },
8414
+ MUTATING2,
8415
+ (a) => handleCreateApp(t, b, a)
8416
+ );
8417
+ reg(
8418
+ "talonic_get_app",
8419
+ "Get App",
8420
+ D.get,
8421
+ { app_id: appId },
8422
+ READ_ONLY3,
8423
+ (a) => handleGetApp(t, b, a)
8424
+ );
8425
+ reg(
8426
+ "talonic_get_app_logic",
8427
+ "Get App Logic",
8428
+ D.getLogic,
8429
+ { app_id: appId },
8430
+ READ_ONLY3,
8431
+ (a) => handleGetAppLogic(t, b, a)
8432
+ );
8433
+ reg(
8434
+ "talonic_get_app_fields",
8435
+ "Get App Fields",
8436
+ D.getFields,
8437
+ { app_id: appId },
8438
+ READ_ONLY3,
8439
+ (a) => handleGetAppFields(t, b, a)
8440
+ );
8441
+ reg(
8442
+ "talonic_save_app_draft",
8443
+ "Save App Draft",
8444
+ D.saveDraft,
8445
+ { app_id: appId, content: jsonObject().describe("Full version content object.") },
8446
+ MUTATING2,
8447
+ (a) => handleSaveAppDraft(t, b, a)
8448
+ );
8449
+ reg(
8450
+ "talonic_interpret_app_rules",
8451
+ "Interpret App Rules",
8452
+ D.interpret,
8453
+ {
8454
+ app_id: appId,
8455
+ card_ids: z.array(z.string().min(1).max(128)).max(50).optional().describe("Rule card ids; omit for all pending."),
8456
+ guidance: z.string().max(1e3).optional().describe("Plain-language hint for stuck rules."),
8457
+ locale: z.string().max(10).optional().describe("Language of reasons and readbacks, e.g. de.")
8458
+ },
8459
+ MUTATING2,
8460
+ (a) => handleInterpretRules(t, b, a)
8461
+ );
8462
+ reg(
8463
+ "talonic_propose_app_edit",
8464
+ "Propose App Edit",
8465
+ D.proposeEdit,
8466
+ {
8467
+ app_id: appId,
8468
+ instruction: z.string().min(8).max(2e3).describe("The change, in plain language.")
8469
+ },
8470
+ { ...READ_ONLY3, idempotentHint: false },
8471
+ (a) => handleProposeEdit(t, b, a)
8472
+ );
8473
+ reg(
8474
+ "talonic_apply_app_edit",
8475
+ "Apply App Edit",
8476
+ D.applyEdit,
8477
+ {
8478
+ app_id: appId,
8479
+ ops: z.array(jsonObject()).min(1).max(20).describe("Accepted ops from the proposal.")
8480
+ },
8481
+ MUTATING2,
8482
+ (a) => handleApplyEdit(t, b, a)
8483
+ );
8484
+ reg(
8485
+ "talonic_list_app_versions",
8486
+ "List App Versions",
8487
+ D.versions,
8488
+ { app_id: appId },
8489
+ READ_ONLY3,
8490
+ (a) => handleListAppVersions(t, b, a)
8491
+ );
8492
+ reg(
8493
+ "talonic_publish_app",
8494
+ "Publish App",
8495
+ D.publish,
8496
+ { app_id: appId, version: z.number().int().min(1).describe("The draft's version number.") },
8497
+ MUTATING2,
8498
+ (a) => handlePublishApp(t, b, a)
8499
+ );
8500
+ reg(
8501
+ "talonic_enable_app",
8502
+ "Enable App",
8503
+ D.enable,
8504
+ { app_id: appId },
8505
+ MUTATING2,
8506
+ (a) => handleSetAppEnabled(t, b, a, true)
8507
+ );
8508
+ reg(
8509
+ "talonic_disable_app",
8510
+ "Disable App",
8511
+ D.disable,
8512
+ { app_id: appId },
8513
+ MUTATING2,
8514
+ (a) => handleSetAppEnabled(t, b, a, false)
8515
+ );
8516
+ reg(
8517
+ "talonic_get_app_acceptance",
8518
+ "Get App Acceptance Set",
8519
+ D.getAcceptance,
8520
+ { app_id: appId },
8521
+ READ_ONLY3,
8522
+ (a) => handleGetAcceptance(t, b, a)
8523
+ );
8524
+ reg(
8525
+ "talonic_save_app_acceptance",
8526
+ "Save App Acceptance Set",
8527
+ D.saveAcceptance,
8528
+ {
8529
+ app_id: appId,
8530
+ cases: z.array(acceptanceCase).min(1).max(2e3),
8531
+ tolerance: z.number().min(0).max(1).optional().describe("Accepted mismatch share (default 0).")
8532
+ },
8533
+ MUTATING2,
8534
+ (a) => handleSaveAcceptance(t, b, a)
8535
+ );
8536
+ reg(
8537
+ "talonic_check_app_acceptance",
8538
+ "Check App Acceptance",
8539
+ D.checkAcceptance,
8540
+ {
8541
+ app_id: appId,
8542
+ run_id: zUuid().optional().describe("Run to score; default the latest completed run.")
8543
+ },
8544
+ READ_ONLY3,
8545
+ (a) => handleCheckAcceptance(t, b, a)
8546
+ );
8547
+ reg(
8548
+ "talonic_run_app",
8549
+ "Run App",
8550
+ D.run,
8551
+ {
8552
+ app_id: appId,
8553
+ input: jsonObject().optional().describe("Run input, checked against the app's input schema."),
8554
+ dry_run: z.boolean().optional().describe("Full trace, no side effects."),
8555
+ idempotency_key: z.string().min(1).max(64).optional()
8556
+ },
8557
+ MUTATING2,
8558
+ (a) => handleRunApp(t, b, a)
8559
+ );
8560
+ reg(
8561
+ "talonic_list_app_runs",
8562
+ "List App Runs",
8563
+ D.listRuns,
8564
+ { app_id: appId, limit: limit2, offset },
8565
+ READ_ONLY3,
8566
+ (a) => handleListAppRuns(t, b, a)
8567
+ );
8568
+ reg(
8569
+ "talonic_get_app_run",
8570
+ "Get App Run",
8571
+ D.getRun,
8572
+ { run_id: runId, include_events: z.boolean().optional() },
8573
+ READ_ONLY3,
8574
+ (a) => handleGetAppRun(t, b, a)
8575
+ );
8576
+ reg(
8577
+ "talonic_get_run_record",
8578
+ "Get Run Record",
8579
+ D.record,
8580
+ { run_id: runId },
8581
+ READ_ONLY3,
8582
+ (a) => handleGetRunRecord(t, b, a)
8583
+ );
8584
+ reg(
8585
+ "talonic_get_run_verdicts",
8586
+ "Get Run Verdicts",
8587
+ D.verdicts,
8588
+ {
8589
+ run_id: runId,
8590
+ rolled: z.enum(VERDICT_OUTCOMES).optional().describe("Filter by overall outcome."),
8591
+ auto: z.boolean().optional().describe("Filter by the auto flag."),
8592
+ rule: z.string().min(1).max(128).optional().describe("Rule id; needs status."),
8593
+ status: z.enum(VERDICT_OUTCOMES).optional().describe("That rule's outcome; needs rule."),
8594
+ limit: limit2,
8595
+ cursor: z.string().min(1).max(512).optional().describe("`next` from the previous page.")
8596
+ },
8597
+ READ_ONLY3,
8598
+ (a) => handleGetRunVerdicts(t, b, a)
8599
+ );
8600
+ reg(
8601
+ "talonic_list_app_reviews",
8602
+ "List Human Reviews",
8603
+ D.listReviews,
8604
+ {
8605
+ app_id: appId.optional(),
8606
+ status: z.enum(REVIEW_STATUSES).optional(),
8607
+ kind: z.enum(REVIEW_KINDS).optional(),
8608
+ assignee_user_id: zUuid().optional().describe("Only reviews assigned to this user."),
8609
+ limit: limit2,
8610
+ offset
8611
+ },
8612
+ READ_ONLY3,
8613
+ (a) => handleListAppReviews(t, b, a)
8614
+ );
8615
+ reg(
8616
+ "talonic_raise_app_review",
8617
+ "Raise Human Review",
8618
+ D.raiseReview,
8619
+ {
8620
+ app_id: appId,
8621
+ run_id: runId.optional(),
8622
+ kind: z.enum(REVIEW_KINDS),
8623
+ question: z.string().min(1).max(4e3),
8624
+ context: jsonObject().optional(),
8625
+ input_contract: jsonObject().describe("JSON Schema the answer must satisfy."),
8626
+ team_id: zUuid().optional().describe("Review team to assign.")
8627
+ },
8628
+ MUTATING2,
8629
+ (a) => handleRaiseAppReview(t, b, a)
8630
+ );
8631
+ reg(
8632
+ "talonic_resolve_app_review",
8633
+ "Resolve Human Review",
8634
+ D.resolveReview,
8635
+ {
8636
+ review_id: reviewId,
8637
+ values: jsonObject().describe("Answer values matching the review's input_contract."),
8638
+ feedback: z.object({
8639
+ proposal_verdict: z.enum(["correct", "incorrect", "partial"]).optional(),
8640
+ correction: z.string().max(4e3).optional(),
8641
+ generalize: z.boolean().optional()
8642
+ }).optional().describe("Optional feedback that teaches the app.")
8643
+ },
8644
+ MUTATING2,
8645
+ (a) => handleResolveAppReview(t, b, a)
8646
+ );
8647
+ reg(
8648
+ "talonic_interview_app_review",
8649
+ "Interview Human Review",
8650
+ D.interview,
8651
+ {
8652
+ review_id: reviewId,
8653
+ message: z.string().min(1).max(4e3).describe("The reviewer's message for this turn."),
8654
+ transcript: z.array(z.object({ role: z.enum(["user", "assistant"]), text: z.string().max(2e3) })).max(20).optional().describe("Earlier turns, oldest first.")
8655
+ },
8656
+ { ...READ_ONLY3, idempotentHint: false },
8657
+ (a) => handleInterviewReview(t, b, a)
8658
+ );
8659
+ reg(
8660
+ "talonic_list_app_precedents",
8661
+ "List App Precedents",
8662
+ D.precedents,
8663
+ { app_id: appId, similar_to: jsonObject().optional().describe("Match keys of the case.") },
8664
+ READ_ONLY3,
8665
+ (a) => handleListAppPrecedents(t, b, a)
8666
+ );
8667
+ }
8668
+ var DECIDE_SCOPE = "apps:decide";
8669
+ var TASK_STATUSES2 = [
8670
+ "available",
8671
+ "claimed",
8672
+ "submitted",
8673
+ "released",
8674
+ "failed",
8675
+ "timed_out",
8676
+ "cancelled"
8677
+ ];
8678
+ var PACKAGE_PAGE_LIMIT_MAX = 2e3;
8679
+ var appId2 = zUuid().describe(
8680
+ "Id of an External-mode app (from talonic_list_apps, where mode is 'external')."
8681
+ );
8682
+ var taskId2 = zUuid().describe("Decision task UUID.");
8683
+ var executionEpoch2 = z.number().int().min(1).max(2147483647).describe("Execution epoch returned by the successful claim. Stale epochs are rejected with 409.");
8684
+ var status2 = z.enum(TASK_STATUSES2).optional().describe("Optional task-status filter.");
8685
+ var listLimit = z.number().int().min(1).max(100).optional().describe("Page size (default 50).");
8686
+ var cursor2 = z.string().min(1).optional().describe("Opaque cursor from pagination.next_cursor.");
8687
+ var packageCursor = z.string().min(1).optional().describe(
8688
+ "Opaque package cursor: package.first_cursor from the claim, then pagination.next_cursor. Omit for the first page."
8689
+ );
8690
+ var packageLimit = z.number().int().min(1).max(PACKAGE_PAGE_LIMIT_MAX).optional().describe(
8691
+ `Records per page, 1 to ${PACKAGE_PAGE_LIMIT_MAX}. Defaults to the platform page size (package.page_size from the claim).`
8692
+ );
8693
+ var outcome = z.record(z.string(), z.json()).describe(
8694
+ "The decision, shaped by output_contract from the claim: for a plain JSON Schema contract the object that schema validates; for a verdict_matrix contract { subjects: [{ subject_key, rule_outcomes, auto?, detail? }] }; for a record_set contract its fields-and-rows envelope."
8695
+ );
8696
+ var evidence = z.array(z.string().min(1).max(512)).max(1e4).describe(
8697
+ "Provenance locators the decision relied on, each copied verbatim from the input package (or a db:/ref: locator the app holds a read grant on). Required; [] is accepted only when the app allows unevidenced decisions."
8698
+ );
8699
+ var rationale = z.string().min(1).max(4e3).describe(
8700
+ "Short decision rationale (a summary, never private chain-of-thought), up to 4,000 characters."
8701
+ );
8702
+ var confidence = z.number().min(0).max(1).optional().describe("Optional confidence from 0 to 1.");
8703
+ var serviceVersion = z.string().min(1).max(64).optional().describe("Optional build identifier of the deciding service; recorded as decided_by.label.");
8704
+ var failReason = z.string().min(1).max(2e3).describe(
8705
+ "Why the task cannot be decided, up to 2,000 characters. Recorded on the Human Review the fail raises."
8706
+ );
8707
+ var listInput2 = { app_id: appId2, status: status2, limit: listLimit, cursor: cursor2 };
8708
+ var idInput2 = { task_id: taskId2 };
8709
+ var packageInput = { task_id: taskId2, cursor: packageCursor, limit: packageLimit };
8710
+ var epochInput = { task_id: taskId2, execution_epoch: executionEpoch2 };
8711
+ var submitInput2 = {
8712
+ task_id: taskId2,
8713
+ execution_epoch: executionEpoch2,
8714
+ outcome,
8715
+ evidence,
8716
+ rationale,
8717
+ confidence,
8718
+ service_version: serviceVersion
8719
+ };
8720
+ var failInput = { task_id: taskId2, execution_epoch: executionEpoch2, reason: failReason };
8721
+ function taskPath(taskId3, suffix = "") {
8722
+ return `/v1/decision-tasks/${encodeURIComponent(taskId3)}${suffix}`;
8723
+ }
8724
+ function handleListDecisionTasks(getToken, baseUrl, args) {
8725
+ return runTool(
8726
+ () => apiJson(
8727
+ getToken,
8728
+ baseUrl,
8729
+ "GET",
8730
+ `/v1/apps/${encodeURIComponent(args.app_id)}/decision-tasks`,
8731
+ {
8732
+ params: { status: args.status, limit: args.limit, cursor: args.cursor }
8733
+ }
7949
8734
  )
7950
8735
  );
7951
8736
  }
@@ -7994,12 +8779,12 @@ function handleFailDecisionTask(getToken, baseUrl, args) {
7994
8779
  })
7995
8780
  );
7996
8781
  }
7997
- var READ_ONLY3 = {
8782
+ var READ_ONLY4 = {
7998
8783
  readOnlyHint: true,
7999
8784
  destructiveHint: false,
8000
8785
  openWorldHint: false
8001
8786
  };
8002
- var MUTATING2 = {
8787
+ var MUTATING3 = {
8003
8788
  readOnlyHint: false,
8004
8789
  destructiveHint: false,
8005
8790
  openWorldHint: false
@@ -8069,9 +8854,9 @@ var DESCRIPTIONS2 = {
8069
8854
  };
8070
8855
  function registerDecisionTaskTools(server, getToken, baseUrl, options = {}) {
8071
8856
  const invocable = options.invocable !== false;
8072
- const metaFor = (key) => ({
8857
+ const metaFor = (key2) => ({
8073
8858
  _meta: {
8074
- ...widgetToolMeta(key),
8859
+ ...widgetToolMeta(key2),
8075
8860
  ...invocable ? {} : { "talonic/can_invoke": false, "talonic/required_scope": DECIDE_SCOPE }
8076
8861
  }
8077
8862
  });
@@ -8081,7 +8866,7 @@ function registerDecisionTaskTools(server, getToken, baseUrl, options = {}) {
8081
8866
  title: "List Decision Tasks",
8082
8867
  description: DESCRIPTIONS2.list,
8083
8868
  inputSchema: listInput2,
8084
- annotations: { title: "List Decision Tasks", ...READ_ONLY3 },
8869
+ annotations: { title: "List Decision Tasks", ...READ_ONLY4 },
8085
8870
  ...metaFor("listDecisionTasks")
8086
8871
  },
8087
8872
  async (args) => handleListDecisionTasks(getToken, baseUrl, args)
@@ -8092,7 +8877,7 @@ function registerDecisionTaskTools(server, getToken, baseUrl, options = {}) {
8092
8877
  title: "Claim Decision Task",
8093
8878
  description: DESCRIPTIONS2.claim,
8094
8879
  inputSchema: idInput2,
8095
- annotations: { title: "Claim Decision Task", ...MUTATING2 },
8880
+ annotations: { title: "Claim Decision Task", ...MUTATING3 },
8096
8881
  ...metaFor("claimDecisionTask")
8097
8882
  },
8098
8883
  async (args) => handleClaimDecisionTask(getToken, baseUrl, args)
@@ -8103,7 +8888,7 @@ function registerDecisionTaskTools(server, getToken, baseUrl, options = {}) {
8103
8888
  title: "Read Decision Package",
8104
8889
  description: DESCRIPTIONS2.package,
8105
8890
  inputSchema: packageInput,
8106
- annotations: { title: "Read Decision Package", ...READ_ONLY3 },
8891
+ annotations: { title: "Read Decision Package", ...READ_ONLY4 },
8107
8892
  ...metaFor("readDecisionPackage")
8108
8893
  },
8109
8894
  async (args) => handleReadDecisionPackage(getToken, baseUrl, args)
@@ -8114,7 +8899,7 @@ function registerDecisionTaskTools(server, getToken, baseUrl, options = {}) {
8114
8899
  title: "Heartbeat Decision Task",
8115
8900
  description: DESCRIPTIONS2.heartbeat,
8116
8901
  inputSchema: epochInput,
8117
- annotations: { title: "Heartbeat Decision Task", ...MUTATING2 },
8902
+ annotations: { title: "Heartbeat Decision Task", ...MUTATING3 },
8118
8903
  ...metaFor("heartbeatDecisionTask")
8119
8904
  },
8120
8905
  async (args) => handleHeartbeatDecisionTask(getToken, baseUrl, args)
@@ -8125,7 +8910,7 @@ function registerDecisionTaskTools(server, getToken, baseUrl, options = {}) {
8125
8910
  title: "Submit Decision Task",
8126
8911
  description: DESCRIPTIONS2.submit,
8127
8912
  inputSchema: submitInput2,
8128
- annotations: { title: "Submit Decision Task", ...MUTATING2 },
8913
+ annotations: { title: "Submit Decision Task", ...MUTATING3 },
8129
8914
  ...metaFor("submitDecisionTask")
8130
8915
  },
8131
8916
  async (args) => handleSubmitDecisionTask(getToken, baseUrl, args)
@@ -8136,7 +8921,7 @@ function registerDecisionTaskTools(server, getToken, baseUrl, options = {}) {
8136
8921
  title: "Release Decision Task",
8137
8922
  description: DESCRIPTIONS2.release,
8138
8923
  inputSchema: epochInput,
8139
- annotations: { title: "Release Decision Task", ...MUTATING2 },
8924
+ annotations: { title: "Release Decision Task", ...MUTATING3 },
8140
8925
  ...metaFor("releaseDecisionTask")
8141
8926
  },
8142
8927
  async (args) => handleReleaseDecisionTask(getToken, baseUrl, args)
@@ -8153,6 +8938,230 @@ function registerDecisionTaskTools(server, getToken, baseUrl, options = {}) {
8153
8938
  async (args) => handleFailDecisionTask(getToken, baseUrl, args)
8154
8939
  );
8155
8940
  }
8941
+
8942
+ // src/tools/mining-driver.ts
8943
+ var appId3 = zUuid().describe(
8944
+ "Id (UUID) of an autonomous app, from talonic_list_apps where mode is 'autonomous'."
8945
+ );
8946
+ var runId2 = zUuid().describe(
8947
+ "The round's run id (run_id from talonic_mining_list_rounds, or the decision task's run_id)."
8948
+ );
8949
+ var executionEpoch3 = z.number().int().min(1).max(2147483647).describe("execution_epoch from talonic_claim_decision_task. A stale epoch is HTTP 409.");
8950
+ var toolName = z.string().regex(/^[a-z][a-z0-9_]{0,63}$/).describe("A tool name from talonic_mining_list_round_tools.");
8951
+ var READ_ONLY5 = {
8952
+ readOnlyHint: true,
8953
+ destructiveHint: false,
8954
+ idempotentHint: true,
8955
+ openWorldHint: false
8956
+ };
8957
+ var MUTATING4 = {
8958
+ readOnlyHint: false,
8959
+ destructiveHint: false,
8960
+ idempotentHint: false,
8961
+ openWorldHint: false
8962
+ };
8963
+ var roundsPath = (app, suffix = "") => `/v1/apps/${encodeURIComponent(app)}/mining/rounds${suffix}`;
8964
+ var roundPath = (app, run, suffix = "") => roundsPath(app, `/${encodeURIComponent(run)}${suffix}`);
8965
+ var BUSY_BACKOFF_MS = [500, 1e3, 2e3, 4e3];
8966
+ var POLL_INTERVAL_MS = 2e3;
8967
+ var DEFAULT_WAIT_SECONDS = 25;
8968
+ var MAX_WAIT_SECONDS = 120;
8969
+ var realSleep = (ms) => new Promise((r) => setTimeout(r, ms));
8970
+ function isBusy(err) {
8971
+ if (!(err instanceof ApiHttpError) || err.status !== 409) return false;
8972
+ try {
8973
+ const body = JSON.parse(err.body);
8974
+ return (body.details?.refused ?? body.error?.details?.refused) === "busy";
8975
+ } catch {
8976
+ return /"refused"\s*:\s*"busy"/.test(err.body);
8977
+ }
8978
+ }
8979
+ var handleMiningListRounds = (t, b, a) => runTool(
8980
+ () => apiJson(t, b, "GET", roundsPath(a.app_id), { params: { limit: a.limit, offset: a.offset } })
8981
+ );
8982
+ var handleMiningGetRound = (t, b, a) => runTool(() => apiJson(t, b, "GET", roundPath(a.app_id, a.run_id)));
8983
+ var handleMiningStartRound = (t, b, a) => runTool(
8984
+ () => a.phase === "reconcile" ? apiJson(t, b, "POST", roundsPath(a.app_id, "/reconcile")) : apiJson(t, b, "POST", roundsPath(a.app_id), {
8985
+ body: {
8986
+ ...a.phase ? { phase: a.phase } : {},
8987
+ ...a.dry_run !== void 0 ? { dry_run: a.dry_run } : {}
8988
+ }
8989
+ })
8990
+ );
8991
+ var handleMiningListRoundTools = (t, b, a) => runTool(() => apiJson(t, b, "GET", roundPath(a.app_id, a.run_id, "/tools")));
8992
+ async function handleMiningCallRoundTool(t, b, a, timing = {}) {
8993
+ const sleep2 = timing.sleep ?? realSleep;
8994
+ const now = timing.now ?? Date.now;
8995
+ return runTool(async () => {
8996
+ const path = roundPath(a.app_id, a.run_id, `/tools/${encodeURIComponent(a.name)}`);
8997
+ const body = { execution_epoch: a.execution_epoch, input: a.input ?? {} };
8998
+ let answer;
8999
+ for (let attempt = 0; ; attempt++) {
9000
+ try {
9001
+ answer = await apiJson(t, b, "POST", path, { body });
9002
+ break;
9003
+ } catch (err) {
9004
+ const backoff = BUSY_BACKOFF_MS[attempt];
9005
+ if (!isBusy(err) || backoff === void 0) throw err;
9006
+ await sleep2(backoff);
9007
+ }
9008
+ }
9009
+ if (answer?.status !== "running" || !answer.call_id) return answer;
9010
+ const waitMs = Math.min(a.wait_seconds ?? DEFAULT_WAIT_SECONDS, MAX_WAIT_SECONDS) * 1e3;
9011
+ const deadline = now() + waitMs;
9012
+ const callId = answer.call_id;
9013
+ while (now() < deadline) {
9014
+ await sleep2(POLL_INTERVAL_MS);
9015
+ const polled = await apiJson(
9016
+ t,
9017
+ b,
9018
+ "GET",
9019
+ roundPath(a.app_id, a.run_id, `/tools/calls/${encodeURIComponent(callId)}`),
9020
+ { params: { execution_epoch: a.execution_epoch } }
9021
+ );
9022
+ if (polled?.status !== "running") return polled;
9023
+ }
9024
+ return {
9025
+ call_id: callId,
9026
+ status: "running",
9027
+ next_step: "The call is still running. Poll talonic_mining_get_round_tool_call with this call_id; heartbeat the task if its lease is close to expiring."
9028
+ };
9029
+ });
9030
+ }
9031
+ var handleMiningGetRoundToolCall = (t, b, a) => runTool(
9032
+ () => apiJson(
9033
+ t,
9034
+ b,
9035
+ "GET",
9036
+ roundPath(a.app_id, a.run_id, `/tools/calls/${encodeURIComponent(a.call_id)}`),
9037
+ {
9038
+ params: { execution_epoch: a.execution_epoch }
9039
+ }
9040
+ )
9041
+ );
9042
+ var DRIVER_FLOW = "FLOW for a round waiting for an outside driver: talonic_list_decision_tasks (the app's tasks) -> talonic_claim_decision_task (keep execution_epoch) -> talonic_read_decision_package (the round's brief and tools) -> talonic_mining_list_round_tools -> talonic_mining_call_round_tool, repeatedly, with talonic_heartbeat_decision_task before the lease ends -> talonic_submit_decision_task with outcome { summary, protocol_feedback }, evidence [] and a one-line rationale.";
9043
+ var AUTH_NOTE2 = "AUTH: a tlnc_ key needs a per-app 'decide' grant (plus 'read' for the round reads); an OAuth connector session needs the apps:decide scope and a live workspace role of senior_member or above. A 403 names what is missing: tell the user, do not retry.";
9044
+ var D2 = {
9045
+ listRounds: [
9046
+ "List an autonomous app's rule-finding rounds, newest first: phase, status, what each found, and for a round waiting for an outside driver its task state (claimed by whom, lease, deadline). `total` counts every round.",
9047
+ "USE WHEN: finding a round to drive or checking progress. ARGS: app_id, optional limit (max 200), offset."
9048
+ ].join("\n"),
9049
+ getRound: [
9050
+ "Read one rule-finding round: phase, status, budget, findings, candidate rules, summary, and the driver block for an externally driven round.",
9051
+ "ARGS: app_id, run_id."
9052
+ ].join("\n"),
9053
+ startRound: [
9054
+ "Start a rule-finding round on an autonomous app. Without phase the app's plan picks the next one; reconcile reviews rules whose candidates lapsed (needs configure access). dry_run re-grades without searching.",
9055
+ "USE WHEN: the user asks to look for new rules now. Only one externally driven round per app can be open (HTTP 409 with the open task otherwise).",
9056
+ "RETURNS: { run_id, status, phase, \u2026 }. A round with an outside driver then waits for a claim: see talonic_list_decision_tasks."
9057
+ ].join("\n"),
9058
+ listTools: [
9059
+ "List the tools you may call on a round you hold the claim on, with their inputs, the round's remaining budget and the retry rule for a busy round.",
9060
+ "USE WHEN: right after claiming the round's decision task, or to check remaining budget.",
9061
+ DRIVER_FLOW,
9062
+ AUTH_NOTE2
9063
+ ].join("\n"),
9064
+ callTool: [
9065
+ "Call one round tool by name with its input, as the current claimant. The call runs under the app's grants and the round's budgets; a tool's own error comes back as is_error:true with a reason, not as a failure of this call.",
9066
+ "Busy rounds are retried for you. A call that runs long is polled for up to wait_seconds (default 25, max 120); if it is still running you get its call_id: poll talonic_mining_get_round_tool_call.",
9067
+ "Do not call tools on one round in parallel. close_round is not a tool here: close the round with talonic_submit_decision_task.",
9068
+ "ARGS: app_id, run_id, execution_epoch, name, input (object, default {}), optional wait_seconds. A stale or foreign claim or an expired lease is HTTP 409: claim again.",
9069
+ AUTH_NOTE2
9070
+ ].join("\n"),
9071
+ getCall: [
9072
+ "Read a round tool call that was still running: status running | done, and its content and is_error once done. Only the round's current claimant can read it.",
9073
+ "ARGS: app_id, run_id, call_id, execution_epoch.",
9074
+ AUTH_NOTE2
9075
+ ].join("\n")
9076
+ };
9077
+ function registerMiningDriverTools(server, getToken, baseUrl, options = {}) {
9078
+ const t = getToken;
9079
+ const b = baseUrl;
9080
+ const decideMeta = options.invocable === false ? { _meta: { "talonic/can_invoke": false, "talonic/required_scope": DECIDE_SCOPE } } : {};
9081
+ server.registerTool(
9082
+ "talonic_mining_list_rounds",
9083
+ {
9084
+ title: "List Mining Rounds",
9085
+ description: D2.listRounds,
9086
+ inputSchema: {
9087
+ app_id: appId3,
9088
+ limit: z.number().int().min(1).max(200).optional(),
9089
+ offset: z.number().int().min(0).optional()
9090
+ },
9091
+ annotations: { title: "List Mining Rounds", ...READ_ONLY5 }
9092
+ },
9093
+ (a) => handleMiningListRounds(t, b, a)
9094
+ );
9095
+ server.registerTool(
9096
+ "talonic_mining_get_round",
9097
+ {
9098
+ title: "Get Mining Round",
9099
+ description: D2.getRound,
9100
+ inputSchema: { app_id: appId3, run_id: runId2 },
9101
+ annotations: { title: "Get Mining Round", ...READ_ONLY5 }
9102
+ },
9103
+ (a) => handleMiningGetRound(t, b, a)
9104
+ );
9105
+ server.registerTool(
9106
+ "talonic_mining_start_round",
9107
+ {
9108
+ title: "Start Mining Round",
9109
+ description: D2.startRound,
9110
+ inputSchema: {
9111
+ app_id: appId3,
9112
+ phase: z.enum(["discovery", "hypothesis", "reconcile"]).optional(),
9113
+ dry_run: z.boolean().optional()
9114
+ },
9115
+ annotations: { title: "Start Mining Round", ...MUTATING4 }
9116
+ },
9117
+ (a) => handleMiningStartRound(t, b, a)
9118
+ );
9119
+ server.registerTool(
9120
+ "talonic_mining_list_round_tools",
9121
+ {
9122
+ title: "List Round Tools",
9123
+ description: D2.listTools,
9124
+ inputSchema: { app_id: appId3, run_id: runId2 },
9125
+ annotations: { title: "List Round Tools", ...READ_ONLY5 },
9126
+ ...decideMeta
9127
+ },
9128
+ (a) => handleMiningListRoundTools(t, b, a)
9129
+ );
9130
+ server.registerTool(
9131
+ "talonic_mining_call_round_tool",
9132
+ {
9133
+ title: "Call Round Tool",
9134
+ description: D2.callTool,
9135
+ inputSchema: {
9136
+ app_id: appId3,
9137
+ run_id: runId2,
9138
+ execution_epoch: executionEpoch3,
9139
+ name: toolName,
9140
+ input: z.record(z.string(), z.json()).optional().describe("The tool's input object."),
9141
+ wait_seconds: z.number().int().min(0).max(MAX_WAIT_SECONDS).optional().describe(`Seconds to keep polling a long call (default ${DEFAULT_WAIT_SECONDS}).`)
9142
+ },
9143
+ annotations: { title: "Call Round Tool", ...MUTATING4 },
9144
+ ...decideMeta
9145
+ },
9146
+ (a) => handleMiningCallRoundTool(t, b, a)
9147
+ );
9148
+ server.registerTool(
9149
+ "talonic_mining_get_round_tool_call",
9150
+ {
9151
+ title: "Get Round Tool Call",
9152
+ description: D2.getCall,
9153
+ inputSchema: {
9154
+ app_id: appId3,
9155
+ run_id: runId2,
9156
+ call_id: zUuid().describe("call_id from talonic_mining_call_round_tool."),
9157
+ execution_epoch: executionEpoch3
9158
+ },
9159
+ annotations: { title: "Get Round Tool Call", ...READ_ONLY5 },
9160
+ ...decideMeta
9161
+ },
9162
+ (a) => handleMiningGetRoundToolCall(t, b, a)
9163
+ );
9164
+ }
8156
9165
  var DESCRIPTION11 = [
8157
9166
  "Get the OCR-converted markdown text of a document.",
8158
9167
  "",
@@ -8219,8 +9228,8 @@ async function handleToMarkdown(talonic, args, opts = {}) {
8219
9228
  retryable: false
8220
9229
  });
8221
9230
  }
8222
- let documentId = args.document_id;
8223
- if (!documentId) {
9231
+ let documentId3 = args.document_id;
9232
+ if (!documentId3) {
8224
9233
  const ingest = await talonic.extract({
8225
9234
  ...args.file_data !== void 0 ? {
8226
9235
  file: Buffer.from(args.file_data, "base64"),
@@ -8230,9 +9239,9 @@ async function handleToMarkdown(talonic, args, opts = {}) {
8230
9239
  ...args.file_url !== void 0 ? { file_url: args.file_url } : {},
8231
9240
  schema: INGEST_ONLY_SCHEMA
8232
9241
  });
8233
- documentId = ingest.document.id;
9242
+ documentId3 = ingest.document.id;
8234
9243
  }
8235
- const result = await talonic.documents.getMarkdown(documentId);
9244
+ const result = await talonic.documents.getMarkdown(documentId3);
8236
9245
  return jsonOk(result);
8237
9246
  } catch (err) {
8238
9247
  return toolError(err);
@@ -8455,18 +9464,22 @@ function unwrap(res) {
8455
9464
  }
8456
9465
  var documentIdsArg = z.array(zUuid()).max(1e3).optional().describe("Restrict to these document ids (hard filter, enforced server-side).");
8457
9466
  var FIND_DESCRIPTION = [
8458
- "Locate the REAL data behind a natural-language concept before querying anything: semantic + lexical retrieval that resolves a phrase ('payment volume per transaction', 'counterparty', 'Vertragslaufzeit') to the registry fields, values, documents and text passages that carry it \u2014 even when the field is captured under a different name.",
9467
+ "Locate the REAL data behind a natural-language concept before querying anything: resolves a phrase ('payment volume per transaction', 'counterparty', 'Vertragslaufzeit') by meaning and by its words to the fields, values, documents and text passages that carry it \u2014 even when the field is captured under a different name.",
8459
9468
  "",
8460
- "USE WHEN: the user asks about a concept and you are not sure which field holds it, when talonic_list_fields / talonic_search came back empty or ambiguous, or when the answer may live in document prose rather than a captured cell.",
9469
+ "USE WHEN: the user asks about a concept and you are not sure which field holds it, when talonic_list_fields / talonic_search came back empty or ambiguous, or when the answer may live in document prose rather than a captured cell. Pass `account` whenever the question names one portfolio company (an account from talonic_list_accounts), so another company's figures cannot come back.",
8461
9470
  "NOT FOR: reading a known field's values (talonic_field_values) or filtering by a known field (talonic_filter).",
8462
9471
  "",
8463
- "ARGS: `query` (the concept, in the user's words), optional `top_k` (1\u201325, default 10), `document_ids` (hard scope).",
8464
- "RETURNS: four ranked groups \u2014 FIELDS (canonical_name, field ids/keys, maturity/tier, occurrence_count, sample values with their documents), VALUES, DOCUMENTS and PASSAGES \u2014 every item a ready handle for the next call. Read-only, no LLM cost."
9472
+ "ARGS: `query` (the concept, in the user's words), optional `concepts[]` (several concepts resolved to fields in one call; fields only, no text search), `top_k` (1\u201325, default 10), `document_ids` (hard scope), `account` (one account by name or alias, e.g. 'Filu'; narrows like document_ids; an unknown name returns an error listing the accounts).",
9473
+ "RETURNS: four ranked groups \u2014 FIELDS (canonical_name, field ids/keys, maturity, occurrence_count, sample values with their documents), VALUES, DOCUMENTS and PASSAGES \u2014 every item a ready handle for the next call. Read-only."
8465
9474
  ].join("\n");
8466
9475
  var findDataInputSchema = {
8467
9476
  query: z.string().min(1).describe("The natural-language concept to locate."),
9477
+ concepts: z.array(z.string().min(1).max(300)).min(1).max(50).optional().describe("Several concepts resolved to fields in one call (fields only, no text search)."),
8468
9478
  top_k: z.number().int().min(1).max(25).optional().describe("Max results per group (default 10)."),
8469
- document_ids: documentIdsArg
9479
+ document_ids: documentIdsArg,
9480
+ account: z.string().min(1).max(200).optional().describe(
9481
+ "Only the documents of this account (portfolio company), by name or alias, e.g. 'Filu'."
9482
+ )
8470
9483
  };
8471
9484
  async function handleFindData(getToken, baseUrl, args) {
8472
9485
  return runTool(async () => {
@@ -8479,8 +9492,10 @@ async function handleFindData(getToken, baseUrl, args) {
8479
9492
  body: {
8480
9493
  args: {
8481
9494
  query: args.query,
9495
+ ...args.concepts?.length ? { concepts: args.concepts } : {},
8482
9496
  ...args.top_k !== void 0 ? { top_k: args.top_k } : {},
8483
- ...args.document_ids?.length ? { document_scope: args.document_ids } : {}
9497
+ ...args.document_ids?.length ? { document_scope: args.document_ids } : {},
9498
+ ...args.account?.trim() ? { account: args.account.trim() } : {}
8484
9499
  }
8485
9500
  }
8486
9501
  }
@@ -8509,7 +9524,7 @@ async function handleListAgentTools(getToken, baseUrl, args) {
8509
9524
  const onlyInvocable = args.only_invocable ?? true;
8510
9525
  const includeSchemas = args.include_schemas ?? true;
8511
9526
  const registry = (res.tools ?? []).filter((t) => !DEDICATED.has(t.name));
8512
- const tools = registry.filter((t) => !onlyInvocable || t.can_invoke).map((t) => {
9527
+ const tools2 = registry.filter((t) => !onlyInvocable || t.can_invoke).map((t) => {
8513
9528
  const item = {
8514
9529
  name: t.name,
8515
9530
  description: t.description,
@@ -8521,7 +9536,7 @@ async function handleListAgentTools(getToken, baseUrl, args) {
8521
9536
  return item;
8522
9537
  });
8523
9538
  return {
8524
- tools,
9539
+ tools: tools2,
8525
9540
  invocable_count: registry.filter((t) => t.can_invoke).length,
8526
9541
  totalCount: registry.length
8527
9542
  };
@@ -8689,7 +9704,7 @@ async function handleGetSpec(getToken, baseUrl, args) {
8689
9704
  return { ...spec, versions: versions.data ?? [] };
8690
9705
  });
8691
9706
  }
8692
- var READ_ONLY4 = {
9707
+ var READ_ONLY6 = {
8693
9708
  readOnlyHint: true,
8694
9709
  destructiveHint: false,
8695
9710
  idempotentHint: true,
@@ -8702,7 +9717,7 @@ function registerSpecTools(server, getToken, baseUrl) {
8702
9717
  title: "List pipelines",
8703
9718
  description: LIST_DESCRIPTION5,
8704
9719
  inputSchema: listSpecsInputSchema,
8705
- annotations: { title: "List pipelines", ...READ_ONLY4 },
9720
+ annotations: { title: "List pipelines", ...READ_ONLY6 },
8706
9721
  _meta: widgetToolMeta("listSpecs")
8707
9722
  },
8708
9723
  async (args) => handleListSpecs(getToken, baseUrl, args)
@@ -8713,7 +9728,7 @@ function registerSpecTools(server, getToken, baseUrl) {
8713
9728
  title: "Look up a pipeline",
8714
9729
  description: GET_DESCRIPTION4,
8715
9730
  inputSchema: getSpecInputSchema,
8716
- annotations: { title: "Look up a pipeline", ...READ_ONLY4 },
9731
+ annotations: { title: "Look up a pipeline", ...READ_ONLY6 },
8717
9732
  _meta: widgetToolMeta("getSpec")
8718
9733
  },
8719
9734
  async (args) => handleGetSpec(getToken, baseUrl, args)
@@ -8929,7 +9944,7 @@ async function handleGetRunResults(getToken, baseUrl, args) {
8929
9944
  return { run_kind: kind, ...body };
8930
9945
  });
8931
9946
  }
8932
- var READ_ONLY5 = {
9947
+ var READ_ONLY7 = {
8933
9948
  readOnlyHint: true,
8934
9949
  destructiveHint: false,
8935
9950
  idempotentHint: true,
@@ -8958,7 +9973,7 @@ function registerRunTools(server, getToken, baseUrl) {
8958
9973
  title: "Check run progress",
8959
9974
  description: GET_RUN_DESCRIPTION,
8960
9975
  inputSchema: runRefInputSchema,
8961
- annotations: { title: "Check run progress", ...READ_ONLY5 },
9976
+ annotations: { title: "Check run progress", ...READ_ONLY7 },
8962
9977
  _meta: widgetToolMeta("getRun")
8963
9978
  },
8964
9979
  async (args) => handleGetRun(getToken, baseUrl, args)
@@ -8969,7 +9984,7 @@ function registerRunTools(server, getToken, baseUrl) {
8969
9984
  title: "Read run results",
8970
9985
  description: RESULTS_DESCRIPTION,
8971
9986
  inputSchema: resultsInputSchema,
8972
- annotations: { title: "Read run results", ...READ_ONLY5 },
9987
+ annotations: { title: "Read run results", ...READ_ONLY7 },
8973
9988
  _meta: widgetToolMeta("getRunResults")
8974
9989
  },
8975
9990
  async (args) => handleGetRunResults(getToken, baseUrl, args)
@@ -9114,32 +10129,2133 @@ function registerAskTools(server, getToken, baseUrl) {
9114
10129
  );
9115
10130
  }
9116
10131
 
9117
- // package.json
9118
- var package_default = {
9119
- version: "0.1.103"};
9120
-
9121
- // src/version.ts
9122
- var VERSION = package_default.version;
9123
- var SERVER_NAME = "talonic";
9124
-
9125
- // src/server-factory.ts
9126
- function makeTaggedFetch(getClientName, baseFetch = fetch) {
9127
- return ((input, init) => {
9128
- try {
9129
- const headers = new Headers(init?.headers);
9130
- const cn = getClientName();
9131
- headers.set("user-agent", `talonic-mcp/${VERSION}${cn ? ` ${cn}` : ""}`);
9132
- return baseFetch(input, { ...init, headers });
9133
- } catch {
9134
- return baseFetch(input, init);
10132
+ // src/tools/_groups.ts
10133
+ var READ = {
10134
+ readOnlyHint: true,
10135
+ destructiveHint: false,
10136
+ idempotentHint: true,
10137
+ openWorldHint: false
10138
+ };
10139
+ var write9 = (idempotent, destructive2 = false) => ({
10140
+ readOnlyHint: false,
10141
+ destructiveHint: destructive2,
10142
+ idempotentHint: idempotent,
10143
+ openWorldHint: false
10144
+ });
10145
+ var camelToSnake = (s) => s.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`);
10146
+ function entries(map) {
10147
+ return Array.isArray(map) ? map.map((k) => [k, k]) : Object.entries(map);
10148
+ }
10149
+ function buildRequest(tool, args) {
10150
+ const space = tool.route.indexOf(" ");
10151
+ const method = tool.route.slice(0, space);
10152
+ const template = tool.route.slice(space + 1);
10153
+ const used = /* @__PURE__ */ new Set();
10154
+ const path = template.replace(/\{([A-Za-z0-9_]+)\}/g, (_m, name) => {
10155
+ const arg = camelToSnake(name);
10156
+ const value = args[arg];
10157
+ if (value === void 0 || value === null || value === "") {
10158
+ throw new Error(`Validation error: \`${arg}\` is required.`);
9135
10159
  }
10160
+ used.add(arg);
10161
+ return encodeURIComponent(String(value));
9136
10162
  });
10163
+ const params = {};
10164
+ for (const [arg, wire] of entries(tool.query ?? [])) {
10165
+ used.add(arg);
10166
+ const v = args[arg];
10167
+ if (v === void 0 || v === null) continue;
10168
+ params[wire] = Array.isArray(v) ? v.join(",") : v;
10169
+ }
10170
+ let body = void 0;
10171
+ if (tool.body === "rest") {
10172
+ const rest = {};
10173
+ for (const [k, v] of Object.entries(args)) if (!used.has(k) && v !== void 0) rest[k] = v;
10174
+ body = rest;
10175
+ } else if (tool.body) {
10176
+ const picked = {};
10177
+ for (const [arg, wire] of entries(tool.body)) {
10178
+ if (args[arg] !== void 0) picked[wire] = args[arg];
10179
+ }
10180
+ body = picked;
10181
+ } else if (method === "POST" || method === "PUT" || method === "PATCH") {
10182
+ body = {};
10183
+ }
10184
+ return { method, path, params, body };
9137
10185
  }
9138
- function buildServerInstructions(opts) {
10186
+ function runGroupTool(tool, ctx, args) {
10187
+ if (tool.handler) return tool.handler(ctx, args);
10188
+ return runTool(async () => {
10189
+ const req = buildRequest(tool, args);
10190
+ return apiJson(ctx.getToken, ctx.baseUrl, req.method, req.path, {
10191
+ params: req.params,
10192
+ ...req.body !== void 0 ? { body: req.body } : {}
10193
+ });
10194
+ });
10195
+ }
10196
+ function registerGroup(server, group, getToken, baseUrl) {
10197
+ const ctx = { getToken, baseUrl };
10198
+ for (const tool of group.tools) {
10199
+ server.registerTool(
10200
+ tool.name,
10201
+ {
10202
+ title: tool.title,
10203
+ description: tool.description,
10204
+ inputSchema: tool.inputSchema,
10205
+ annotations: { title: tool.title, ...tool.annotations }
10206
+ },
10207
+ async (args) => runGroupTool(tool, ctx, args ?? {})
10208
+ );
10209
+ }
10210
+ }
10211
+ function describe(parts) {
9139
10212
  return [
9140
- "Talonic turns unstructured documents (PDFs, scans, images, DOCX, emails) into",
9141
- "schema-validated JSON with per-field confidence scores and source provenance, and",
9142
- "answers questions about the documents in the user's Talonic workspace.",
10213
+ parts.what,
10214
+ `USE WHEN: ${parts.use}`,
10215
+ ...parts.not ? [`NOT FOR: ${parts.not}`] : [],
10216
+ "",
10217
+ `ARGS: ${parts.args ?? "none."}`,
10218
+ `RETURNS: ${parts.returns}`,
10219
+ ...parts.errors ? [`ERRORS: ${parts.errors}`] : []
10220
+ ].join("\n");
10221
+ }
10222
+ var SCOPES = [
10223
+ "extract",
10224
+ "read",
10225
+ "write",
10226
+ "operations",
10227
+ "billing",
10228
+ "delivery",
10229
+ "usage",
10230
+ "records_write"
10231
+ ];
10232
+ var LIST_KEYS = describe({
10233
+ what: "List the workspace's API keys: name, scopes, masked prefix, active state, last use, creation, revocation and expiry. Never returns a secret. A workspace owner sees every key; anyone else sees only the keys they created.",
10234
+ use: "auditing which keys exist, finding the id of a key to revoke, or checking a key's scopes and expiry.",
10235
+ not: "creating a key (talonic_create_api_key); the workspace's credits and limits (talonic_get_account).",
10236
+ returns: "{ data[] { id, name, scopes[], masked_prefix, is_active, last_used, created_at, revoked_at, expires_at } }."
10237
+ });
10238
+ var CREATE_KEY = describe({
10239
+ what: "Create a new API key for this workspace. The secret is returned ONCE in `key` and can never be read again: hand it to the user straight away, tell them to store it, and never repeat it, summarize it, write it to a file or log, or pass it to another tool. A new key can only carry scopes the calling credential already holds (a key cannot widen its own access); billing, usage and records_write are granted only by an owner in the app. Ask the user before creating a key.",
10240
+ use: "the user asks for a new or narrower key, e.g. a read-only key for a dashboard, or a key that expires.",
10241
+ not: "rotating by revoking (talonic_revoke_api_key, after the new key is in place).",
10242
+ args: "`name` (1-255 characters, shown in listings), `scopes` (optional subset of extract, read, write, operations, billing, delivery, usage, records_write; omitted = the calling credential's own scopes), `expires_at` (optional ISO-8601 in the future; enterprise workspaces cap keys at 90 days).",
10243
+ returns: "{ id, name, key (the secret, shown once), masked_prefix, scopes[], created_at, expires_at, warning }.",
10244
+ errors: "403 scope_not_grantable when a requested scope is not held by the calling credential; 403 when key creation is managed by Talonic for this workspace."
10245
+ });
10246
+ var REVOKE_KEY = describe({
10247
+ what: "Revoke an API key: it stops working at once and cannot be turned back on. Anything still using it fails from the next request. Confirm the key (name, masked prefix) with the user before calling. A workspace owner can revoke any key; anyone else only their own.",
10248
+ use: "the user asks to revoke, rotate out or disable a key.",
10249
+ not: "listing keys (talonic_list_api_keys).",
10250
+ args: "`key_id` (UUID from talonic_list_api_keys).",
10251
+ returns: "{ id, revoked: true }.",
10252
+ errors: "404 key_not_found when no active key with that id is yours to revoke."
10253
+ });
10254
+ var GET_ACCOUNT = describe({
10255
+ what: "The workspace's account snapshot: plan (`tier`), status, credit balance (EUR) with any monthly allowance, daily request limits per area and today's usage against them.",
10256
+ use: "checking plan, limits or today's request counts, e.g. before a large batch or after a 429.",
10257
+ not: "credit spend by function (talonic_get_usage); buying credits (talonic_get_billing_upgrade_link).",
10258
+ returns: "{ tier, status, email_domain, created_at, credits { balance, currency, monthly_allowance, tier_resets_at }, daily_limits { extract, platform, ingest, operations }, usage_today { extract, platform, ingest, operations } }."
10259
+ });
10260
+ var LIST_WEBHOOKS = describe({
10261
+ what: "List the workspace's webhook configurations: target URL, subscribed event types, active state, the source they are limited to (if any). Never returns signing secrets.",
10262
+ use: "checking where events are sent, or finding a webhook id to change or delete.",
10263
+ not: "the events themselves (talonic_list_events); valid event type names (talonic_list_webhook_event_types).",
10264
+ returns: "{ data[] { id, url, events[], is_active, source_connection_id, created_at, updated_at } }."
10265
+ });
10266
+ var GET_WEBHOOK = describe({
10267
+ what: "One webhook configuration by id.",
10268
+ use: "reading one webhook's URL, events and state before changing it.",
10269
+ not: "listing every webhook (talonic_list_webhooks).",
10270
+ args: "`id` (UUID).",
10271
+ returns: "{ id, url, events[], is_active, source_connection_id, created_at, updated_at }."
10272
+ });
10273
+ var CREATE_WEBHOOK = describe({
10274
+ what: "Create a webhook: Talonic POSTs the chosen events to `url`, signed with `secret` when one is given (X-Talonic-Signature: sha256=<hex> over the raw body). Ask the user for the URL and confirm it before calling.",
10275
+ use: "the user wants Talonic to notify their system, e.g. when an extraction completes or fails.",
10276
+ not: "changing an existing webhook (talonic_update_webhook).",
10277
+ args: "`url` (https URL that accepts POST), `events` (event types, default extraction.complete and extraction.failed; see talonic_list_webhook_event_types), `secret` (optional signing secret the receiver verifies), `source_connection_id` (optional: only events of that source), `is_active` (default true).",
10278
+ returns: "{ id, url, events[], is_active, source_connection_id, created_at, updated_at }."
10279
+ });
10280
+ var UPDATE_WEBHOOK = describe({
10281
+ what: "Change a webhook: its URL, events, signing secret or active state. Only the fields sent change. Setting is_active false pauses deliveries without deleting the webhook.",
10282
+ use: "pointing a webhook elsewhere, changing its events, rotating its secret, or pausing / resuming it.",
10283
+ not: "removing it for good (talonic_delete_webhook).",
10284
+ args: "`id` (UUID), and any of `url`, `events`, `secret`, `is_active`.",
10285
+ returns: "{ id, url, events[], is_active, source_connection_id, created_at, updated_at }."
10286
+ });
10287
+ var DELETE_WEBHOOK = describe({
10288
+ what: "Delete a webhook configuration for good: its target stops receiving events at once. Confirm with the user first; to pause instead, use talonic_update_webhook with is_active false.",
10289
+ use: "the user asks to remove a webhook.",
10290
+ not: "pausing (talonic_update_webhook).",
10291
+ args: "`id` (UUID).",
10292
+ returns: "{ deleted: true, id }."
10293
+ });
10294
+ var EVENT_TYPES = describe({
10295
+ what: "The event types a webhook can subscribe to, with what each one means. There is no re-delivery of a past webhook call: to catch up on events a receiver missed, read them with talonic_list_events from a saved cursor.",
10296
+ use: "choosing `events` for talonic_create_webhook or talonic_update_webhook.",
10297
+ not: "the events that happened (talonic_list_events).",
10298
+ returns: "{ data[] { event, description } }."
10299
+ });
10300
+ var UPGRADE_LINK = describe({
10301
+ what: "A link where a person buys credits. This tool never buys anything: it returns a URL for the user to open and pay. Present the link and tell the user a human must complete the purchase; credits arrive seconds after payment. A workspace billed through a marketplace gets the marketplace page instead.",
10302
+ use: "the workspace ran out of credits (HTTP 402) or the user asks how to buy more.",
10303
+ not: "checking the balance (talonic_get_balance) or prices (talonic_get_pricing).",
10304
+ args: "`pack` (optional: 10, 50, 250 or 1000 EUR; default 50).",
10305
+ returns: "{ url, provider (stripe | dashboard | aws_marketplace), requires_human: true, pack?, message }."
10306
+ });
10307
+ var webhookFields = {
10308
+ url: z.string().url().describe("Receiver URL (https) that accepts POST."),
10309
+ events: z.array(z.string().min(1)).min(1).describe("Event types to send."),
10310
+ secret: z.string().min(1).describe("Signing secret the receiver verifies."),
10311
+ is_active: z.boolean().describe("false pauses deliveries.")
10312
+ };
10313
+ var adminGroup = {
10314
+ key: "admin",
10315
+ label: "Workspace administration",
10316
+ docsSlug: "admin-tools",
10317
+ probe: { path: "/v1/account/keys" },
10318
+ tools: [
10319
+ {
10320
+ name: "talonic_list_api_keys",
10321
+ title: "List API keys",
10322
+ description: LIST_KEYS,
10323
+ route: "GET /v1/account/keys",
10324
+ inputSchema: {},
10325
+ annotations: READ
10326
+ },
10327
+ {
10328
+ name: "talonic_create_api_key",
10329
+ title: "Create an API key",
10330
+ description: CREATE_KEY,
10331
+ route: "POST /v1/account/keys",
10332
+ inputSchema: {
10333
+ name: z.string().min(1).max(255).describe("Label shown in listings."),
10334
+ scopes: z.array(z.enum(SCOPES)).min(1).optional().describe("Subset of the calling credential's scopes; omitted = the same scopes."),
10335
+ expires_at: z.string().optional().describe("When the key stops working, ISO-8601 in the future.")
10336
+ },
10337
+ annotations: write9(false),
10338
+ body: ["name", "scopes", "expires_at"]
10339
+ },
10340
+ {
10341
+ name: "talonic_revoke_api_key",
10342
+ title: "Revoke an API key",
10343
+ description: REVOKE_KEY,
10344
+ route: "DELETE /v1/account/keys/{keyId}",
10345
+ inputSchema: { key_id: zUuid().describe("The key, from talonic_list_api_keys.") },
10346
+ annotations: write9(true, true)
10347
+ },
10348
+ {
10349
+ name: "talonic_get_account",
10350
+ title: "Account snapshot",
10351
+ description: GET_ACCOUNT,
10352
+ route: "GET /v1/account",
10353
+ inputSchema: {},
10354
+ annotations: READ
10355
+ },
10356
+ {
10357
+ name: "talonic_list_webhooks",
10358
+ title: "List webhooks",
10359
+ description: LIST_WEBHOOKS,
10360
+ route: "GET /v1/webhooks",
10361
+ inputSchema: {},
10362
+ annotations: READ
10363
+ },
10364
+ {
10365
+ name: "talonic_get_webhook",
10366
+ title: "One webhook",
10367
+ description: GET_WEBHOOK,
10368
+ route: "GET /v1/webhooks/{id}",
10369
+ inputSchema: { id: zUuid().describe("The webhook id.") },
10370
+ annotations: READ
10371
+ },
10372
+ {
10373
+ name: "talonic_create_webhook",
10374
+ title: "Create a webhook",
10375
+ description: CREATE_WEBHOOK,
10376
+ route: "POST /v1/webhooks",
10377
+ inputSchema: {
10378
+ url: webhookFields.url,
10379
+ events: webhookFields.events.optional(),
10380
+ secret: webhookFields.secret.optional(),
10381
+ source_connection_id: zUuid().optional().describe("Only events of this source."),
10382
+ is_active: webhookFields.is_active.optional()
10383
+ },
10384
+ annotations: write9(false),
10385
+ body: ["url", "events", "secret", "source_connection_id", "is_active"]
10386
+ },
10387
+ {
10388
+ name: "talonic_update_webhook",
10389
+ title: "Change a webhook",
10390
+ description: UPDATE_WEBHOOK,
10391
+ route: "PATCH /v1/webhooks/{id}",
10392
+ inputSchema: {
10393
+ id: zUuid().describe("The webhook id."),
10394
+ url: webhookFields.url.optional(),
10395
+ events: webhookFields.events.optional(),
10396
+ secret: webhookFields.secret.optional(),
10397
+ is_active: webhookFields.is_active.optional()
10398
+ },
10399
+ annotations: write9(true),
10400
+ body: ["url", "events", "secret", "is_active"]
10401
+ },
10402
+ {
10403
+ name: "talonic_delete_webhook",
10404
+ title: "Delete a webhook",
10405
+ description: DELETE_WEBHOOK,
10406
+ route: "DELETE /v1/webhooks/{id}",
10407
+ inputSchema: { id: zUuid().describe("The webhook id.") },
10408
+ annotations: write9(true, true)
10409
+ },
10410
+ {
10411
+ name: "talonic_list_webhook_event_types",
10412
+ title: "Webhook event types",
10413
+ description: EVENT_TYPES,
10414
+ route: "GET /v1/webhooks/events",
10415
+ inputSchema: {},
10416
+ annotations: READ
10417
+ },
10418
+ {
10419
+ name: "talonic_get_billing_upgrade_link",
10420
+ title: "Buy-credits link",
10421
+ description: UPGRADE_LINK,
10422
+ route: "GET /v1/billing/upgrade-link",
10423
+ inputSchema: {
10424
+ pack: z.enum(["10", "50", "250", "1000"]).optional().describe("Credit pack in EUR.")
10425
+ },
10426
+ annotations: READ,
10427
+ query: ["pack"]
10428
+ }
10429
+ ]
10430
+ };
10431
+ var TIMESTAMP_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})$/i;
10432
+ var QUERY_ID_RE = /^[a-z][a-z0-9_]{0,63}$/;
10433
+ var OPS = [
10434
+ "eq",
10435
+ "neq",
10436
+ "in",
10437
+ "not_in",
10438
+ "is_null",
10439
+ "not_null",
10440
+ "gt",
10441
+ "gte",
10442
+ "lt",
10443
+ "lte",
10444
+ "contains_any",
10445
+ "contains_all"
10446
+ ];
10447
+ var CATALOG = describe({
10448
+ what: "What talonic_aggregate can count in this workspace: every dataset with its fields (type, groupable, the filter operators it takes, whether it is a cost field), the measures, the group-by time buckets, the document scope keys, the limits (window days, queries per request, list values, buckets) and whether this workspace may read cost fields. Reads no data and is free.",
10449
+ use: "before the first talonic_aggregate call of a conversation, or when talonic_aggregate answered 400 invalid_aggregate.",
10450
+ not: "the numbers themselves (talonic_aggregate).",
10451
+ returns: "{ datasets[] { name, description, kind entity|event, document_scope, defaults[], fields[] { name, description, type, groupable, cost, ops[] } }, measures, group_by { time[], max, max_buckets }, scope_keys[], limits { max_window_days, max_queries, max_list_values, statement_timeout_ms, concurrency }, cost_visible }."
10452
+ });
10453
+ var AGGREGATE = describe({
10454
+ what: "Workspace metrics in one request: counts, sums, averages, minimums, maximums, medians and percentiles over a time window, optionally grouped by up to three fields or by UTC hour / day. Returns numbers only, never rows. Counts only documents this credential may see.",
10455
+ use: "a monitoring or dashboard question: documents received or failed in a window, documents missing a value, app verdicts by state, average or median cost per document, deliveries by outcome.",
10456
+ not: "reading documents or values (talonic_search, talonic_field_values); credit spend by function (talonic_get_usage). Call talonic_aggregate_catalog first for the dataset and field names.",
10457
+ args: "`from`, `to` ISO-8601 WITH an offset (e.g. 2026-11-05T12:00:00Z), half-open [from, to), at most the catalog's max_window_days (31 by default). `scope` (optional, applies to every document query): document_ids, tags / system_tags {any|all}, source_connection_ids, document_types (ids or names), client_batch_ids, roots_only, attachments_only. `queries[]` (1 to the catalog's max_queries, 20 by default): `id` (lowercase letters, digits, underscore; unique), `dataset`, `measure` (one name, or a list), `of` (the numeric field for sum / avg / min / max / median / pNN), `where[]` {field, op, value}, `group_by[]`.",
10458
+ returns: "{ window { from, to }, as_of, results { <id>: { dataset, kind, value | values (+ n) | groups[] { key, value | values }, groups_total } } }. A count over no rows is 0; an average, minimum or percentile over no rows is null. Cost fields are in US dollars.",
10459
+ errors: "400 invalid_aggregate names the allowed datasets / fields / measures; 403 cost_not_visible for cost fields when the workspace may not see costs; 422 aggregate_timeout names the dataset (narrow the window or scope); 429 another aggregate of this workspace is running (wait, then retry once)."
10460
+ });
10461
+ var whereSchema = z.object({
10462
+ field: z.string().min(1).describe("A field of the query's dataset (talonic_aggregate_catalog)."),
10463
+ op: z.enum(OPS).describe("Filter operator; the catalog lists which ones each field takes."),
10464
+ value: z.unknown().optional().describe("Omitted for is_null / not_null; a list for in, not_in, contains_any, contains_all.")
10465
+ });
10466
+ var querySchema = z.object({
10467
+ id: z.string().describe("Result key: starts with a lowercase letter; letters, digits, underscore."),
10468
+ dataset: z.string().min(1).describe("A catalog dataset, e.g. documents, app_verdicts, deliveries."),
10469
+ measure: z.union([z.string(), z.array(z.string()).min(1)]).describe("One measure (returns value) or a list (returns values plus n)."),
10470
+ of: z.string().optional().describe("Numeric field for sum, avg, min, max, median, p1-p99."),
10471
+ where: z.array(whereSchema).max(50).optional(),
10472
+ group_by: z.array(z.string()).optional().describe("Up to 3 groupable fields, or hour / day (UTC).")
10473
+ });
10474
+ var aggregateInputSchema = {
10475
+ from: z.string().describe("Window start, inclusive, ISO-8601 with offset."),
10476
+ to: z.string().describe("Window end, exclusive, ISO-8601 with offset."),
10477
+ scope: z.record(z.string(), z.unknown()).optional().describe(
10478
+ "Document selectors applied to every query: document_ids, tags, system_tags, source_connection_ids, document_types, client_batch_ids, roots_only, attachments_only."
10479
+ ),
10480
+ queries: z.array(querySchema).min(1).describe("The numbers to compute; each result is keyed by its id.")
10481
+ };
10482
+ function checkAggregateArgs(args) {
10483
+ for (const key2 of ["from", "to"]) {
10484
+ const v = args[key2];
10485
+ if (typeof v !== "string" || !TIMESTAMP_RE.test(v)) {
10486
+ return `\`${key2}\` must be an ISO-8601 timestamp with an offset, e.g. 2026-11-05T12:00:00Z.`;
10487
+ }
10488
+ }
10489
+ if (Date.parse(args["to"]) <= Date.parse(args["from"])) {
10490
+ return "`to` must be after `from` (the window is [from, to)).";
10491
+ }
10492
+ const queries = args["queries"];
10493
+ if (!Array.isArray(queries) || queries.length === 0) return "`queries` needs at least one query.";
10494
+ const seen = /* @__PURE__ */ new Set();
10495
+ for (const q of queries) {
10496
+ if (typeof q?.id !== "string" || !QUERY_ID_RE.test(q.id)) {
10497
+ return `query id ${JSON.stringify(q?.id)} must start with a lowercase letter and hold only lowercase letters, digits and underscores.`;
10498
+ }
10499
+ if (seen.has(q.id)) return `query id "${q.id}" is used twice; each result needs its own id.`;
10500
+ seen.add(q.id);
10501
+ }
10502
+ return null;
10503
+ }
10504
+ var aggregateTool = {
10505
+ name: "talonic_aggregate",
10506
+ title: "Workspace metrics",
10507
+ description: AGGREGATE,
10508
+ route: "POST /v1/aggregate",
10509
+ inputSchema: aggregateInputSchema,
10510
+ annotations: READ,
10511
+ body: ["from", "to", "scope", "queries"],
10512
+ handler: (ctx, args) => {
10513
+ const refusal = checkAggregateArgs(args);
10514
+ if (refusal) return Promise.resolve(validationError(refusal));
10515
+ return runGroupTool({ ...aggregateTool, handler: void 0 }, ctx, args);
10516
+ }
10517
+ };
10518
+ var aggregateGroup = {
10519
+ key: "aggregate",
10520
+ label: "Workspace metrics",
10521
+ docsSlug: "aggregate-tools",
10522
+ probe: { path: "/v1/aggregate/catalog" },
10523
+ tools: [
10524
+ {
10525
+ name: "talonic_aggregate_catalog",
10526
+ title: "What workspace metrics can count",
10527
+ description: CATALOG,
10528
+ route: "GET /v1/aggregate/catalog",
10529
+ inputSchema: {},
10530
+ annotations: READ
10531
+ },
10532
+ aggregateTool
10533
+ ]
10534
+ };
10535
+ var COMPLIANCE_EXPORT_MAX_BYTES = 8 * 1024 * 1024;
10536
+ var docIds = (min, max, what) => z.array(zUuid()).min(min).max(max).describe(what);
10537
+ var pageArgs2 = {
10538
+ status: z.enum(["processing", "waiting", "completed", "error"]).optional().describe("Only evaluations with this status (an interrupted one shows error)."),
10539
+ limit: z.number().int().min(1).max(500).optional().describe("Page size; any of status / limit / offset asks for one page."),
10540
+ offset: z.number().int().min(0).optional().describe("Rows to skip, for paging.")
10541
+ };
10542
+ var epoch = z.number().int().min(1).describe("The execution_epoch talonic_compliance_claim_task returned.");
10543
+ async function handleComplianceExport(ctx, args, maxBytes = COMPLIANCE_EXPORT_MAX_BYTES) {
10544
+ const format = args["format"] ?? "xlsx";
10545
+ const params = { format, ...args["issues_only"] ? { issues: "true" } : {} };
10546
+ const path = "/v1/compliance/export";
10547
+ try {
10548
+ const file = await apiBinary(ctx.getToken, ctx.baseUrl, path, { params, maxBytes });
10549
+ const filename = file.filename ?? `compliance.${format}`;
10550
+ const meta = { filename, mime_type: file.mimeType, size: file.bytes.length, format };
10551
+ return {
10552
+ content: [
10553
+ { type: "text", text: JSON.stringify(meta) },
10554
+ {
10555
+ type: "resource",
10556
+ resource: {
10557
+ uri: buildUrl(ctx.baseUrl, path, params),
10558
+ mimeType: file.mimeType,
10559
+ blob: file.bytes.toString("base64")
10560
+ }
10561
+ }
10562
+ ],
10563
+ structuredContent: meta
10564
+ };
10565
+ } catch (err) {
10566
+ return toolError(err);
10567
+ }
10568
+ }
10569
+ var tools = [
10570
+ // ── Worklist and evidence ────────────────────────────────────────────────
10571
+ {
10572
+ name: "talonic_compliance_issues",
10573
+ title: "Compliance worklist",
10574
+ description: describe({
10575
+ what: "The worklist of failed checks: per document the rules it fails (and, with `unclear`, the rules whose verdict is unclear), with the framework each rule comes from.",
10576
+ use: "'what is not compliant', the starting point before opening one document's evaluation.",
10577
+ not: "the full verdict list with passes (talonic_compliance_list_evaluations); one document's reasons and quotes (talonic_compliance_get_document_evaluation).",
10578
+ args: "`unclear` (also list unclear verdicts).",
10579
+ returns: "{ data[] } one entry per document with its failing rules."
10580
+ }),
10581
+ route: "GET /v1/compliance/issues",
10582
+ inputSchema: {
10583
+ unclear: z.boolean().optional().describe("Also list rules whose verdict is unclear.")
10584
+ },
10585
+ annotations: READ,
10586
+ query: ["unclear"]
10587
+ },
10588
+ {
10589
+ name: "talonic_compliance_get_document_evaluation",
10590
+ title: "One document's compliance evaluation",
10591
+ description: describe({
10592
+ what: "A document's latest evaluation with every result: per rule the verdict (pass, fail, unclear, not_applicable), the reason, the quote from the document it rests on, whether it needs a person's check, and whether the evaluation is outdated.",
10593
+ use: "retrieving the evidence behind a failed check from talonic_compliance_issues, before deciding on a correction.",
10594
+ not: "a document set (talonic_compliance_get_set_evaluation).",
10595
+ args: "`document_id`.",
10596
+ returns: "{ evaluation } with its results; null when the document was never evaluated."
10597
+ }),
10598
+ route: "GET /v1/compliance/evaluations/documents/{documentId}",
10599
+ inputSchema: { document_id: zUuid().describe("The evaluated document.") },
10600
+ annotations: READ
10601
+ },
10602
+ {
10603
+ name: "talonic_compliance_list_evaluations",
10604
+ title: "Compliance evaluations",
10605
+ description: describe({
10606
+ what: "The latest evaluation of every document on the Evaluations list. Without paging arguments the whole list; with any of status / limit / offset one page with total and has_more.",
10607
+ use: "an overview of every evaluated document, or finding documents whose evaluation errored or is still running.",
10608
+ not: "only the failures (talonic_compliance_issues); counts only (talonic_compliance_evaluation_status).",
10609
+ args: "`status` processing|waiting|completed|error, `limit` 1-500, `offset`.",
10610
+ returns: "{ data[] } or a page { data[], total, has_more }."
10611
+ }),
10612
+ route: "GET /v1/compliance/evaluations",
10613
+ inputSchema: pageArgs2,
10614
+ annotations: READ,
10615
+ query: ["status", "limit", "offset"]
10616
+ },
10617
+ {
10618
+ name: "talonic_compliance_evaluation_status",
10619
+ title: "Compliance evaluation counts",
10620
+ description: describe({
10621
+ what: "Counts over the latest evaluations: processing, completed, error, outdated and failing.",
10622
+ use: "the headline ('how many documents fail'), or waiting until evaluations started with talonic_compliance_evaluate finish.",
10623
+ returns: "{ processing, completed, error, outdated, failing }."
10624
+ }),
10625
+ route: "GET /v1/compliance/evaluations/status",
10626
+ inputSchema: {},
10627
+ annotations: READ
10628
+ },
10629
+ {
10630
+ name: "talonic_compliance_export",
10631
+ title: "Export compliance verdicts",
10632
+ description: describe({
10633
+ what: `Download every verdict of the evaluated documents and document sets as a file (one row per rule and document or set: framework, rule, obligation, verdict, reason, quote, evaluated at, outdated), up to ${COMPLIANCE_EXPORT_MAX_BYTES / (1024 * 1024)} MB.`,
10634
+ use: "the user wants the results as a spreadsheet to share or file.",
10635
+ not: "reading results in the conversation (talonic_compliance_issues, talonic_compliance_get_document_evaluation).",
10636
+ args: "`format` xlsx (default) | csv, `issues_only` (only failed and unclear verdicts of the sets).",
10637
+ returns: "a text item { filename, mime_type, size, format } and a resource item { uri, mimeType, blob } with the file."
10638
+ }),
10639
+ route: "GET /v1/compliance/export",
10640
+ inputSchema: {
10641
+ format: z.enum(["xlsx", "csv"]).optional().describe("File format (default xlsx)."),
10642
+ issues_only: z.boolean().optional().describe("Only failed and unclear verdicts of the sets.")
10643
+ },
10644
+ annotations: READ,
10645
+ handler: (ctx, args) => handleComplianceExport(ctx, args)
10646
+ },
10647
+ // ── Evaluating ───────────────────────────────────────────────────────────
10648
+ {
10649
+ name: "talonic_compliance_evaluate",
10650
+ title: "Evaluate documents for compliance",
10651
+ description: describe({
10652
+ what: "Evaluate documents against every framework that is ON. Runs in the background; poll talonic_compliance_evaluation_status or talonic_compliance_get_document_evaluation.",
10653
+ use: "a document changed or a framework was switched ON and its verdicts are outdated; or after a correction, to check it took effect.",
10654
+ not: "documents not yet on the Evaluations list (talonic_compliance_add_documents adds and evaluates them).",
10655
+ args: "`document_ids` (1-500).",
10656
+ returns: "{ data[] } one started evaluation per document.",
10657
+ errors: "403 when the app is switched off for the workspace."
10658
+ }),
10659
+ route: "POST /v1/compliance/evaluations",
10660
+ inputSchema: { document_ids: docIds(1, 500, "Documents to evaluate.") },
10661
+ annotations: write9(false),
10662
+ body: ["document_ids"]
10663
+ },
10664
+ {
10665
+ name: "talonic_compliance_evaluate_all",
10666
+ title: "Evaluate every document that needs it",
10667
+ description: describe({
10668
+ what: "Evaluate every listed document whose evaluation is missing or outdated, oldest first. Run with dry_run first to see how many.",
10669
+ use: "bringing the whole list up to date after frameworks changed.",
10670
+ args: "`dry_run` (only count), `limit` 1-500 (the rest follow on the next call).",
10671
+ returns: "How many documents need it and how many were started."
10672
+ }),
10673
+ route: "POST /v1/compliance/evaluations/all",
10674
+ inputSchema: {
10675
+ dry_run: z.boolean().optional().describe("Only report how many would be evaluated."),
10676
+ limit: z.number().int().min(1).max(500).optional().describe("Evaluate at most this many.")
10677
+ },
10678
+ annotations: write9(false),
10679
+ body: ["dry_run", "limit"]
10680
+ },
10681
+ {
10682
+ name: "talonic_compliance_add_documents",
10683
+ title: "Add documents to compliance evaluations",
10684
+ description: describe({
10685
+ what: "Put workspace documents on the Evaluations list and evaluate them against the frameworks that are ON.",
10686
+ use: "the user wants documents checked that are not on the list yet.",
10687
+ args: "`document_ids` (1-500).",
10688
+ returns: "The documents added and the evaluations started."
10689
+ }),
10690
+ route: "POST /v1/compliance/evaluations/documents",
10691
+ inputSchema: { document_ids: docIds(1, 500, "Documents to add and evaluate.") },
10692
+ annotations: write9(true),
10693
+ body: ["document_ids"]
10694
+ },
10695
+ {
10696
+ name: "talonic_compliance_remove_document",
10697
+ title: "Take a document off the compliance list",
10698
+ description: describe({
10699
+ what: "Take a document off the Evaluations list together with its evaluations. The document itself stays in the workspace; adding it again re-evaluates it.",
10700
+ use: "a document was put on the list by mistake or no longer needs checking. Ask the user first.",
10701
+ args: "`document_id`.",
10702
+ returns: "Confirmation of the removal."
10703
+ }),
10704
+ route: "DELETE /v1/compliance/evaluations/documents/{documentId}",
10705
+ inputSchema: { document_id: zUuid().describe("The document to take off the list.") },
10706
+ annotations: write9(true, true)
10707
+ },
10708
+ // ── Frameworks ───────────────────────────────────────────────────────────
10709
+ {
10710
+ name: "talonic_compliance_list_frameworks",
10711
+ title: "Compliance frameworks",
10712
+ description: describe({
10713
+ what: "The frameworks (regulations, policies, contract standards held as workspace documents) with their status, whether each is ON, and their rule counts.",
10714
+ use: "which rules documents are checked against, or finding a framework's document_id.",
10715
+ not: "the rules themselves (talonic_compliance_framework_rules).",
10716
+ returns: "{ data[] } frameworks with document_id, name, status, active, rule counts."
10717
+ }),
10718
+ route: "GET /v1/compliance/frameworks",
10719
+ inputSchema: {},
10720
+ annotations: READ
10721
+ },
10722
+ {
10723
+ name: "talonic_compliance_framework_rules",
10724
+ title: "A framework's rules",
10725
+ description: describe({
10726
+ what: "The rules of one framework: code, text, obligation, section, what it applies to and its condition.",
10727
+ use: "explaining a failed verdict's rule, or picking rule ids for a rule set.",
10728
+ args: "`document_id` (the framework's document).",
10729
+ returns: "{ data[] } rules with their ids."
10730
+ }),
10731
+ route: "GET /v1/compliance/frameworks/{documentId}/rules",
10732
+ inputSchema: { document_id: zUuid().describe("The framework's document id.") },
10733
+ annotations: READ
10734
+ },
10735
+ {
10736
+ name: "talonic_compliance_add_frameworks",
10737
+ title: "Make documents compliance frameworks",
10738
+ description: describe({
10739
+ what: "Make existing workspace documents frameworks (a regulation, policy or standard to check other documents against). Their rules are then written from their text; switch a framework ON to check documents against it.",
10740
+ use: "the user uploaded a regulation or policy and wants documents checked against it.",
10741
+ args: "`document_ids` (1-50).",
10742
+ returns: "{ data[] } the new frameworks."
10743
+ }),
10744
+ route: "POST /v1/compliance/frameworks/from-documents",
10745
+ inputSchema: { document_ids: docIds(1, 50, "Workspace documents to make frameworks.") },
10746
+ annotations: write9(true),
10747
+ body: ["document_ids"]
10748
+ },
10749
+ {
10750
+ name: "talonic_compliance_set_framework_active",
10751
+ title: "Switch a framework ON or OFF",
10752
+ description: describe({
10753
+ what: "Turn a framework ON (its rules are in force for every evaluation) or OFF (they are not). Reversible; evaluations made before become outdated.",
10754
+ use: "a framework does not apply to the workspace's documents, or should now apply.",
10755
+ args: "`document_id`, `active`.",
10756
+ returns: "The framework with its new state."
10757
+ }),
10758
+ route: "POST /v1/compliance/frameworks/{documentId}/active",
10759
+ inputSchema: {
10760
+ document_id: zUuid().describe("The framework's document id."),
10761
+ active: z.boolean().describe("true = ON, false = OFF.")
10762
+ },
10763
+ annotations: write9(true),
10764
+ body: ["active"]
10765
+ },
10766
+ {
10767
+ name: "talonic_compliance_generate_rules",
10768
+ title: "Write a framework's rules again",
10769
+ description: describe({
10770
+ what: "Write the rules of a framework again from its text, replacing the current ones.",
10771
+ use: "a framework's rules are missing or the framework document was replaced. Ask the user first: rule sets that name the old rules lose them.",
10772
+ args: "`document_id`.",
10773
+ returns: "The framework with its status and rule counts."
10774
+ }),
10775
+ route: "POST /v1/compliance/frameworks/{documentId}/rules/generate",
10776
+ inputSchema: { document_id: zUuid().describe("The framework's document id.") },
10777
+ annotations: write9(false, true)
10778
+ },
10779
+ {
10780
+ name: "talonic_compliance_remove_framework",
10781
+ title: "Take a framework out of Compliance",
10782
+ description: describe({
10783
+ what: "Take a framework out of the app with its rules. The document stays in the workspace and can be made a framework again.",
10784
+ use: "the user no longer wants documents checked against it. Ask first; to pause it, switch it OFF instead.",
10785
+ args: "`document_id`.",
10786
+ returns: "Confirmation of the removal."
10787
+ }),
10788
+ route: "DELETE /v1/compliance/frameworks/{documentId}",
10789
+ inputSchema: { document_id: zUuid().describe("The framework's document id.") },
10790
+ annotations: write9(true, true)
10791
+ },
10792
+ // ── Discrepancy comparisons ──────────────────────────────────────────────
10793
+ {
10794
+ name: "talonic_compliance_list_comparisons",
10795
+ title: "Document comparisons",
10796
+ description: describe({
10797
+ what: "Comparisons of document batches for discrepancies (values that should agree across the documents but do not), newest first.",
10798
+ use: "finding an earlier comparison.",
10799
+ returns: "{ data[] } comparisons with id, status and counts."
10800
+ }),
10801
+ route: "GET /v1/compliance/discrepancy-runs",
10802
+ inputSchema: {},
10803
+ annotations: READ
10804
+ },
10805
+ {
10806
+ name: "talonic_compliance_get_comparison",
10807
+ title: "One document comparison",
10808
+ description: describe({
10809
+ what: "One comparison with every discrepancy found: the value, which documents disagree and where.",
10810
+ use: "reading the result of talonic_compliance_compare_documents.",
10811
+ args: "`run_id`.",
10812
+ returns: "The comparison with its status and discrepancies."
10813
+ }),
10814
+ route: "GET /v1/compliance/discrepancy-runs/{runId}",
10815
+ inputSchema: { run_id: zUuid().describe("The comparison id.") },
10816
+ annotations: READ
10817
+ },
10818
+ {
10819
+ name: "talonic_compliance_compare_documents",
10820
+ title: "Compare documents for discrepancies",
10821
+ description: describe({
10822
+ what: "Compare a batch of documents that belong together (an order, its invoice, its delivery note) for values that disagree. Runs in the background; read it with talonic_compliance_get_comparison.",
10823
+ use: "the user asks whether a set of documents is consistent.",
10824
+ args: "`document_ids` (2-50).",
10825
+ returns: "The new comparison with its id."
10826
+ }),
10827
+ route: "POST /v1/compliance/discrepancy-runs",
10828
+ inputSchema: { document_ids: docIds(2, 50, "The documents to compare.") },
10829
+ annotations: write9(false),
10830
+ body: ["document_ids"]
10831
+ },
10832
+ // ── Document sets ────────────────────────────────────────────────────────
10833
+ {
10834
+ name: "talonic_compliance_list_sets",
10835
+ title: "Compliance document sets",
10836
+ description: describe({
10837
+ what: "Document sets (documents judged as one whole, e.g. a contract with its annexes) with their documents and rule set.",
10838
+ use: "finding a set id, or checking which documents a set holds.",
10839
+ returns: "{ data[] } sets with id, name, documents, rule_set_id."
10840
+ }),
10841
+ route: "GET /v1/compliance/sets",
10842
+ inputSchema: {},
10843
+ annotations: READ
10844
+ },
10845
+ {
10846
+ name: "talonic_compliance_create_set",
10847
+ title: "Create a compliance document set",
10848
+ description: describe({
10849
+ what: "Create a document set picked by hand, judged against one rule set or, without one, every rule of the frameworks that are ON.",
10850
+ use: "documents only make sense together (a contract and its annexes).",
10851
+ args: "`name`, `document_ids` (2-100), `rule_set_id` (optional).",
10852
+ returns: "The new set."
10853
+ }),
10854
+ route: "POST /v1/compliance/sets",
10855
+ inputSchema: {
10856
+ name: z.string().min(1).max(200).describe("Set name."),
10857
+ document_ids: docIds(2, 100, "The set's documents."),
10858
+ rule_set_id: zUuid().nullable().optional().describe("Rule set to judge it against; omitted or null = every ON rule.")
10859
+ },
10860
+ annotations: write9(false),
10861
+ body: ["name", "document_ids", "rule_set_id"]
10862
+ },
10863
+ {
10864
+ name: "talonic_compliance_assembly_groups",
10865
+ title: "Groups to make compliance sets from",
10866
+ description: describe({
10867
+ what: "The assembly groups of the workspace's pipelines (documents grouped by a shared value, such as one order number) that sets can be made from.",
10868
+ use: "before talonic_compliance_create_sets_from_groups.",
10869
+ returns: "{ data[] } groups with pipeline_id, group_key and their documents."
10870
+ }),
10871
+ route: "GET /v1/compliance/sets/assembly-groups",
10872
+ inputSchema: {},
10873
+ annotations: READ
10874
+ },
10875
+ {
10876
+ name: "talonic_compliance_create_sets_from_groups",
10877
+ title: "Create compliance sets from groups",
10878
+ description: describe({
10879
+ what: "Create one document set per assembly group; the set follows the group as documents join it.",
10880
+ use: "every order (or case) should be judged as a whole.",
10881
+ args: "`groups[]` { pipeline_id, group_key } (1-100), `rule_set_id` (optional).",
10882
+ returns: "{ data[] } the new sets."
10883
+ }),
10884
+ route: "POST /v1/compliance/sets/from-assemblies",
10885
+ inputSchema: {
10886
+ groups: z.array(z.object({ pipeline_id: zUuid(), group_key: z.string().min(1).max(1e3) })).min(1).max(100).describe("Groups from talonic_compliance_assembly_groups."),
10887
+ rule_set_id: zUuid().nullable().optional().describe("Rule set to judge them against; omitted or null = every ON rule.")
10888
+ },
10889
+ annotations: write9(false),
10890
+ body: ["groups", "rule_set_id"]
10891
+ },
10892
+ {
10893
+ name: "talonic_compliance_update_set",
10894
+ title: "Edit a compliance document set",
10895
+ description: describe({
10896
+ what: "Rename a set, replace its documents (a group-following set becomes hand-picked) or change its rule set. Fields left out stay.",
10897
+ use: "a set is missing a document or should be judged against other rules.",
10898
+ args: "`set_id`, `name`, `document_ids` (2-100), `rule_set_id` (null = every ON rule).",
10899
+ returns: "The updated set."
10900
+ }),
10901
+ route: "PATCH /v1/compliance/sets/{setId}",
10902
+ inputSchema: {
10903
+ set_id: zUuid().describe("The set."),
10904
+ name: z.string().min(1).max(200).optional().describe("New set name."),
10905
+ document_ids: docIds(2, 100, "The set's documents (replaces them).").optional(),
10906
+ rule_set_id: zUuid().nullable().optional().describe("null = every ON rule; omitted = unchanged.")
10907
+ },
10908
+ annotations: write9(true),
10909
+ body: ["name", "document_ids", "rule_set_id"]
10910
+ },
10911
+ {
10912
+ name: "talonic_compliance_remove_set",
10913
+ title: "Remove a compliance document set",
10914
+ description: describe({
10915
+ what: "Remove a document set with its evaluations. The documents stay in the workspace.",
10916
+ use: "a set is no longer needed. Ask the user first.",
10917
+ args: "`set_id`.",
10918
+ returns: "Confirmation of the removal."
10919
+ }),
10920
+ route: "DELETE /v1/compliance/sets/{setId}",
10921
+ inputSchema: { set_id: zUuid().describe("The set.") },
10922
+ annotations: write9(true, true)
10923
+ },
10924
+ {
10925
+ name: "talonic_compliance_list_set_evaluations",
10926
+ title: "Compliance set evaluations",
10927
+ description: describe({
10928
+ what: "The latest evaluation of every document set. Without paging arguments the whole list; with any of status / limit / offset one page with total and has_more.",
10929
+ use: "an overview of how every set fares.",
10930
+ args: "`status` processing|waiting|completed|error, `limit` 1-500, `offset`.",
10931
+ returns: "{ data[] } or a page { data[], total, has_more }."
10932
+ }),
10933
+ route: "GET /v1/compliance/sets/evaluations",
10934
+ inputSchema: pageArgs2,
10935
+ annotations: READ,
10936
+ query: ["status", "limit", "offset"]
10937
+ },
10938
+ {
10939
+ name: "talonic_compliance_get_set_evaluation",
10940
+ title: "One set's compliance evaluation",
10941
+ description: describe({
10942
+ what: "A set's latest evaluation with every result: verdict, reason, and the quote with the member document it comes from.",
10943
+ use: "the evidence behind a set's failed check.",
10944
+ args: "`set_id`.",
10945
+ returns: "{ evaluation } with its results; null when never evaluated."
10946
+ }),
10947
+ route: "GET /v1/compliance/sets/{setId}/evaluation",
10948
+ inputSchema: { set_id: zUuid().describe("The set.") },
10949
+ annotations: READ
10950
+ },
10951
+ {
10952
+ name: "talonic_compliance_evaluate_sets",
10953
+ title: "Evaluate compliance document sets",
10954
+ description: describe({
10955
+ what: "Evaluate document sets, each as one whole, against their rule set. Runs in the background.",
10956
+ use: "a set changed or its verdicts are outdated.",
10957
+ args: "`set_ids` (1-100).",
10958
+ returns: "{ data[] } one started evaluation per set."
10959
+ }),
10960
+ route: "POST /v1/compliance/sets/evaluate",
10961
+ inputSchema: { set_ids: z.array(zUuid()).min(1).max(100).describe("Sets to evaluate.") },
10962
+ annotations: write9(false),
10963
+ body: ["set_ids"]
10964
+ },
10965
+ // ── Rule sets ────────────────────────────────────────────────────────────
10966
+ {
10967
+ name: "talonic_compliance_list_rule_sets",
10968
+ title: "Compliance rule sets",
10969
+ description: describe({
10970
+ what: "The workspace's rule sets: named selections of rules of the ON frameworks that a document set is judged against.",
10971
+ use: "finding a rule_set_id for a set.",
10972
+ returns: "{ data[] } rule sets with id, name, rule_ids."
10973
+ }),
10974
+ route: "GET /v1/compliance/rule-sets",
10975
+ inputSchema: {},
10976
+ annotations: READ
10977
+ },
10978
+ {
10979
+ name: "talonic_compliance_create_rule_set",
10980
+ title: "Create a compliance rule set",
10981
+ description: describe({
10982
+ what: "Create a named selection of rules (from talonic_compliance_framework_rules) to judge document sets against.",
10983
+ use: "only some rules apply to a kind of document set.",
10984
+ args: "`name`, `rule_ids` (1-1000).",
10985
+ returns: "The new rule set."
10986
+ }),
10987
+ route: "POST /v1/compliance/rule-sets",
10988
+ inputSchema: {
10989
+ name: z.string().min(1).max(200).describe("Rule set name."),
10990
+ rule_ids: z.array(zUuid()).min(1).max(1e3).describe("Rules of ON frameworks.")
10991
+ },
10992
+ annotations: write9(false),
10993
+ body: ["name", "rule_ids"]
10994
+ },
10995
+ {
10996
+ name: "talonic_compliance_update_rule_set",
10997
+ title: "Change a compliance rule set",
10998
+ description: describe({
10999
+ what: "Rename a rule set or replace its rules.",
11000
+ use: "a rule should be added to or dropped from what sets are judged against.",
11001
+ args: "`rule_set_id`, `name`, `rule_ids` (1-1000, replaces them).",
11002
+ returns: "The updated rule set."
11003
+ }),
11004
+ route: "PATCH /v1/compliance/rule-sets/{ruleSetId}",
11005
+ inputSchema: {
11006
+ rule_set_id: zUuid(),
11007
+ name: z.string().min(1).max(200).optional().describe("New rule set name."),
11008
+ rule_ids: z.array(zUuid()).min(1).max(1e3).optional().describe("The rules (replaces them).")
11009
+ },
11010
+ annotations: write9(true),
11011
+ body: ["name", "rule_ids"]
11012
+ },
11013
+ {
11014
+ name: "talonic_compliance_remove_rule_set",
11015
+ title: "Remove a compliance rule set",
11016
+ description: describe({
11017
+ what: "Remove a rule set. Sets that used it go back to every rule of the ON frameworks.",
11018
+ use: "a rule set is no longer needed. Ask the user first.",
11019
+ args: "`rule_set_id`.",
11020
+ returns: "Confirmation of the removal."
11021
+ }),
11022
+ route: "DELETE /v1/compliance/rule-sets/{ruleSetId}",
11023
+ inputSchema: { rule_set_id: zUuid() },
11024
+ annotations: write9(true, true)
11025
+ },
11026
+ // ── Who decides; the workspace agent's tasks ─────────────────────────────
11027
+ {
11028
+ name: "talonic_compliance_settings",
11029
+ title: "Who makes compliance decisions",
11030
+ description: describe({
11031
+ what: "Who makes the workspace's compliance decisions: `platform` (Talonic decides every verdict) or `external` (the workspace's own agent decides, through the compliance tasks).",
11032
+ use: "before working the task tools, or explaining why verdicts wait.",
11033
+ returns: "{ decider: platform | external }."
11034
+ }),
11035
+ route: "GET /v1/compliance/settings",
11036
+ inputSchema: {},
11037
+ annotations: READ
11038
+ },
11039
+ {
11040
+ name: "talonic_compliance_set_decider",
11041
+ title: "Switch who makes compliance decisions",
11042
+ description: describe({
11043
+ what: "Switch who makes the compliance decisions: `platform` or `external` (the workspace's own agent works the tasks). Reversible. The person behind the connection needs the Workspace settings permission.",
11044
+ use: "the user explicitly asks to hand decisions to their own agent, or back.",
11045
+ args: "`decider` platform|external.",
11046
+ returns: "The new setting.",
11047
+ errors: "403 without the Workspace settings permission."
11048
+ }),
11049
+ route: "PUT /v1/compliance/settings",
11050
+ inputSchema: {
11051
+ decider: z.enum(["platform", "external"]).describe("platform = Talonic decides; external = the workspace's own agent.")
11052
+ },
11053
+ annotations: write9(true),
11054
+ body: ["decider"]
11055
+ },
11056
+ {
11057
+ name: "talonic_compliance_list_tasks",
11058
+ title: "Compliance tasks for the workspace's agent",
11059
+ description: describe({
11060
+ what: "Decisions waiting for the workspace's own agent (only when the decider is external).",
11061
+ use: "an agent working the compliance decisions: pick a task, then talonic_compliance_claim_task.",
11062
+ args: "`status` open (default) | all, `limit` (default 100).",
11063
+ returns: "{ data[] } tasks with id, status, document or set, and lease state."
11064
+ }),
11065
+ route: "GET /v1/compliance/tasks",
11066
+ inputSchema: {
11067
+ status: z.enum(["open", "all"]).optional().describe("open (default) or all."),
11068
+ limit: z.number().int().min(1).max(1e3).optional().describe("Most tasks returned (default 100).")
11069
+ },
11070
+ annotations: READ,
11071
+ query: ["status", "limit"]
11072
+ },
11073
+ {
11074
+ name: "talonic_compliance_get_task",
11075
+ title: "One compliance task",
11076
+ description: describe({
11077
+ what: "One task's state (open, claimed, done) without its work package.",
11078
+ use: "checking a task before or after claiming it.",
11079
+ args: "`task_id`.",
11080
+ returns: "The task."
11081
+ }),
11082
+ route: "GET /v1/compliance/tasks/{taskId}",
11083
+ inputSchema: { task_id: zUuid() },
11084
+ annotations: READ
11085
+ },
11086
+ {
11087
+ name: "talonic_compliance_claim_task",
11088
+ title: "Claim a compliance task",
11089
+ description: describe({
11090
+ what: "Claim a task for this agent and read its work package: instructions, the input, and the JSON Schema the answer must match. The claim is a lease: renew it with talonic_compliance_heartbeat_task while working, hand it back with talonic_compliance_release_task, or answer with talonic_compliance_submit_task. A lapsed lease returns the task to open.",
11091
+ use: "starting work on one task from talonic_compliance_list_tasks.",
11092
+ args: "`task_id`.",
11093
+ returns: "{ task (with execution_epoch and the lease), instructions, input, output_schema, how_to_answer }. Keep execution_epoch for every later call.",
11094
+ errors: "409 when another agent holds the claim, the task is closed or not ready yet."
11095
+ }),
11096
+ route: "POST /v1/compliance/tasks/{taskId}/claim",
11097
+ inputSchema: { task_id: zUuid() },
11098
+ annotations: write9(false)
11099
+ },
11100
+ {
11101
+ name: "talonic_compliance_heartbeat_task",
11102
+ title: "Renew a compliance task claim",
11103
+ description: describe({
11104
+ what: "Renew the lease on a claimed task.",
11105
+ use: "work on a claimed task takes longer than its lease.",
11106
+ args: "`task_id`, `execution_epoch`.",
11107
+ returns: "The new lease expiry.",
11108
+ errors: "409 when the claim lapsed or was taken over (stop working on it)."
11109
+ }),
11110
+ route: "POST /v1/compliance/tasks/{taskId}/heartbeat",
11111
+ inputSchema: { task_id: zUuid(), execution_epoch: epoch },
11112
+ annotations: write9(true),
11113
+ body: ["execution_epoch"]
11114
+ },
11115
+ {
11116
+ name: "talonic_compliance_release_task",
11117
+ title: "Hand a compliance task back",
11118
+ description: describe({
11119
+ what: "Hand a claimed task back unanswered; it is open again for any agent.",
11120
+ use: "the agent cannot decide the task.",
11121
+ args: "`task_id`, `execution_epoch`.",
11122
+ returns: "The task, open again."
11123
+ }),
11124
+ route: "POST /v1/compliance/tasks/{taskId}/release",
11125
+ inputSchema: { task_id: zUuid(), execution_epoch: epoch },
11126
+ annotations: write9(true),
11127
+ body: ["execution_epoch"]
11128
+ },
11129
+ {
11130
+ name: "talonic_compliance_submit_task",
11131
+ title: "Answer a compliance task",
11132
+ description: describe({
11133
+ what: "Submit the answer to a claimed task. It is checked against the package's output_schema and stored exactly like a verdict Talonic makes itself.",
11134
+ use: "the agent has decided a claimed task.",
11135
+ args: "`task_id`, `execution_epoch`, `answer` (an object matching output_schema).",
11136
+ returns: "{ task, result }.",
11137
+ errors: "400 naming what is wrong when the answer does not match the schema; 409 without a live claim (lapsed, released or a stale epoch)."
11138
+ }),
11139
+ route: "POST /v1/compliance/tasks/{taskId}/submit",
11140
+ inputSchema: {
11141
+ task_id: zUuid(),
11142
+ execution_epoch: epoch,
11143
+ answer: z.record(z.string(), z.unknown()).describe("The answer, matching the package's output_schema.")
11144
+ },
11145
+ annotations: write9(false),
11146
+ body: ["execution_epoch", "answer"]
11147
+ }
11148
+ ];
11149
+ var complianceGroup = {
11150
+ key: "compliance",
11151
+ label: "Compliance",
11152
+ docsSlug: "compliance-tools",
11153
+ probe: { path: "/v1/compliance/settings" },
11154
+ tools
11155
+ };
11156
+ var paging = {
11157
+ page: z.number().int().min(1).max(1e6).optional().describe("Page number, from 1."),
11158
+ limit: z.number().int().min(1).optional().describe("Rows per page (the desk caps it).")
11159
+ };
11160
+ var key = (what) => z.string().min(1).max(2e3).describe(`${what} as the desk lists it (no control characters).`);
11161
+ var team = z.string().max(2e3).optional().describe("One team's work only; all teams when left out.");
11162
+ var contractDeskGroup = {
11163
+ key: "contract_desk",
11164
+ label: "Contract Desk",
11165
+ docsSlug: "contract-desk-tools",
11166
+ probe: { path: "/v1/contract-desk/status" },
11167
+ tools: [
11168
+ {
11169
+ name: "talonic_contract_desk_status",
11170
+ title: "Contract Desk status",
11171
+ description: describe({
11172
+ what: "Whether the Contract Desk is ready: when it was last refreshed, whether a refresh is running, and how many sites, contracts and open items it holds.",
11173
+ use: "first call of a session, or after talonic_contract_desk_refresh to see it finish.",
11174
+ not: "the work itself (talonic_contract_desk_todo).",
11175
+ returns: "the desk's state: last refresh time and outcome, a running refresh, counts."
11176
+ }),
11177
+ route: "GET /v1/contract-desk/status",
11178
+ inputSchema: {},
11179
+ annotations: READ
11180
+ },
11181
+ {
11182
+ name: "talonic_contract_desk_refresh",
11183
+ title: "Refresh the Contract Desk",
11184
+ description: describe({
11185
+ what: "Start a refresh of the Contract Desk from its source apps now. Answers at once; talonic_contract_desk_status shows it running and its outcome. Needs the `run` permission and the app switched on.",
11186
+ use: "the source apps changed (new contracts, decisions made elsewhere) and the desk should show it before the next scheduled refresh.",
11187
+ not: "reading anything (every read tool shows the last refresh).",
11188
+ returns: "the refresh that was started (or the one already running)."
11189
+ }),
11190
+ route: "POST /v1/contract-desk/rebuild",
11191
+ inputSchema: {},
11192
+ annotations: write9(true)
11193
+ },
11194
+ {
11195
+ name: "talonic_contract_desk_sites",
11196
+ title: "Contract Desk sites",
11197
+ description: describe({
11198
+ what: "One page of sites with their contracts and open work, and the counts of the three filters.",
11199
+ use: "finding a site by number or name, or listing the sites with work due now or without documents.",
11200
+ not: "one site's contracts and items (talonic_contract_desk_get_site).",
11201
+ args: "`q` (words that must each occur in the site's number, name, contracts or partners), `filter` all|now|nodoc, `page`, `limit`.",
11202
+ returns: "{ data[] sites, total, page, limit, counts { all, now, nodoc } }."
11203
+ }),
11204
+ route: "GET /v1/contract-desk/sites",
11205
+ inputSchema: {
11206
+ q: z.string().max(500).optional().describe("Search words."),
11207
+ filter: z.enum(["all", "now", "nodoc"]).optional().describe("all, now (work due now) or nodoc (no documents)."),
11208
+ ...paging
11209
+ },
11210
+ annotations: READ,
11211
+ query: ["q", "filter", "page", "limit"]
11212
+ },
11213
+ {
11214
+ name: "talonic_contract_desk_get_site",
11215
+ title: "One Contract Desk site",
11216
+ description: describe({
11217
+ what: "One site with its contracts and its site-level items.",
11218
+ use: "the user names a site, or after talonic_contract_desk_sites.",
11219
+ not: "one contract's values (talonic_contract_desk_get_contract).",
11220
+ args: "`key` the site key from talonic_contract_desk_sites.",
11221
+ returns: "the site, its contracts and its open items. 404 when the desk holds no such site."
11222
+ }),
11223
+ route: "GET /v1/contract-desk/sites/{key}",
11224
+ inputSchema: { key: key("The site key") },
11225
+ annotations: READ
11226
+ },
11227
+ {
11228
+ name: "talonic_contract_desk_contracts",
11229
+ title: "Contract Desk contracts",
11230
+ description: describe({
11231
+ what: "One page of contracts, searchable, for one partner or one site.",
11232
+ use: "finding a contract by number, name, partner, site or type.",
11233
+ not: "one contract's items and values (talonic_contract_desk_get_contract).",
11234
+ args: "`q` (words that must each occur in the contract's key, number, name, partner, site or type), `partner` (a partner_key, exact), `site` (a site key, exact), `page`, `limit`.",
11235
+ returns: "{ data[] contracts (crm_key, number, partner, site, type, open items), total, page, limit }."
11236
+ }),
11237
+ route: "GET /v1/contract-desk/contracts",
11238
+ inputSchema: {
11239
+ q: z.string().max(500).optional().describe("Search words."),
11240
+ partner: z.string().max(2e3).optional().describe("A partner_key, matched exactly."),
11241
+ site: z.string().max(2e3).optional().describe("A site key, matched exactly."),
11242
+ ...paging
11243
+ },
11244
+ annotations: READ,
11245
+ query: ["q", "partner", "site", "page", "limit"]
11246
+ },
11247
+ {
11248
+ name: "talonic_contract_desk_get_contract",
11249
+ title: "One Contract Desk contract",
11250
+ description: describe({
11251
+ what: "One contract with its items and values: where the documents and the CRM agree or differ, and what is open.",
11252
+ use: "the evidence for a contract, or before deciding several items on one contract.",
11253
+ not: "the decision screen of one item (talonic_contract_desk_get_decision).",
11254
+ args: "`id` the contract's crm_key.",
11255
+ returns: "the contract with its values, items and documents. 404 when the desk holds no such contract."
11256
+ }),
11257
+ route: "GET /v1/contract-desk/contracts/{id}",
11258
+ inputSchema: { id: key("The contract's crm_key") },
11259
+ annotations: READ
11260
+ },
11261
+ {
11262
+ name: "talonic_contract_desk_dashboard",
11263
+ title: "Contract Desk dashboard",
11264
+ description: describe({
11265
+ what: "The Dashboard: work to do now and this month, open work by team, due dates by week, the busiest sites, the first batch, and the history.",
11266
+ use: "the headline ('how much is open, what is due this week, which team is behind').",
11267
+ not: "the items themselves (talonic_contract_desk_todo).",
11268
+ args: "`team` (optional).",
11269
+ returns: "the dashboard figures for the team, or all teams."
11270
+ }),
11271
+ route: "GET /v1/contract-desk/dashboard",
11272
+ inputSchema: { team },
11273
+ annotations: READ,
11274
+ query: ["team"]
11275
+ },
11276
+ {
11277
+ name: "talonic_contract_desk_quality",
11278
+ title: "Contract Desk data quality",
11279
+ description: describe({
11280
+ what: "The Data quality page: the required values and how many are still open, the attributes with the most open values, the documents, and how well documents link to contracts.",
11281
+ use: "a data quality question across the contract portfolio.",
11282
+ not: "one contract's values (talonic_contract_desk_get_contract).",
11283
+ returns: "the quality figures."
11284
+ }),
11285
+ route: "GET /v1/contract-desk/quality",
11286
+ inputSchema: {},
11287
+ annotations: READ
11288
+ },
11289
+ {
11290
+ name: "talonic_contract_desk_todo",
11291
+ title: "Contract Desk to do list",
11292
+ description: describe({
11293
+ what: "The To do list: per section (now, this month, later, no date) its item count and first batches of similar items, plus the decisions made today.",
11294
+ use: "starting work: pick a batch, then list its items with talonic_contract_desk_todo_items.",
11295
+ not: "one batch's items (talonic_contract_desk_todo_items).",
11296
+ args: "`team` (optional).",
11297
+ returns: "{ sections[] { section, count, batches[] { key, team, kind, count, \u2026 }, more }, decided_today, \u2026 }."
11298
+ }),
11299
+ route: "GET /v1/contract-desk/todo",
11300
+ inputSchema: { team },
11301
+ annotations: READ,
11302
+ query: ["team"]
11303
+ },
11304
+ {
11305
+ name: "talonic_contract_desk_todo_items",
11306
+ title: "Items of a Contract Desk batch",
11307
+ description: describe({
11308
+ what: "One page of the open items of a batch from the To do list.",
11309
+ use: "after talonic_contract_desk_todo, to get the item ids to open and decide.",
11310
+ not: "the evidence of one item (talonic_contract_desk_get_decision).",
11311
+ args: "`batch` (the batch key from talonic_contract_desk_todo, unchanged), `page`, `limit`.",
11312
+ returns: "{ batch | null, data[] items { id, kind, contract, site, due_date, \u2026 }, total, page, limit }. batch is null when the key names no items any more."
11313
+ }),
11314
+ route: "GET /v1/contract-desk/todo/items",
11315
+ inputSchema: {
11316
+ batch: z.string().min(1).max(2e3).describe("The batch key from talonic_contract_desk_todo."),
11317
+ ...paging
11318
+ },
11319
+ annotations: READ,
11320
+ query: ["batch", "page", "limit"]
11321
+ },
11322
+ {
11323
+ name: "talonic_contract_desk_get_decision",
11324
+ title: "Evidence for one Contract Desk item",
11325
+ description: describe({
11326
+ what: "Everything the decision screen shows for one open item: the item, its contract and site, the question (for a value: what each document and the CRM say and the values to pick; for a key date: its day and the outcomes offered; for a process step: mark it handled), whether this connection may decide (`can_decide`), and the contract's letter if there is one.",
11327
+ use: "before talonic_contract_desk_decide, to show the user the evidence and the allowed actions.",
11328
+ not: "decided items (talonic_contract_desk_decisions).",
11329
+ args: "`id` the item id.",
11330
+ returns: "{ item, contract, site_name, can_decide, question { kind value|deadline|step, \u2026 } | null, letter }. question.mode `suggest` means the decision becomes a suggestion a colleague accepts. 404 unknown item; 409 gone when a decision already closed it."
11331
+ }),
11332
+ route: "GET /v1/contract-desk/items/{id}/decision",
11333
+ inputSchema: { id: zUuid().describe("The item id.") },
11334
+ annotations: READ
11335
+ },
11336
+ {
11337
+ name: "talonic_contract_desk_decide",
11338
+ title: "Decide a Contract Desk item",
11339
+ description: describe({
11340
+ what: "Decide one open item. The decision is recorded at the item's source app (set a value, report a value as missing to the CRM, mark a key date or step handled, record a notice outcome on the contract) and in the desk's log, under this connection. Run with dry_run first. Can be undone with talonic_contract_desk_undo while it is the item's latest decision.",
11341
+ use: "the user chose what an item should be after seeing talonic_contract_desk_get_decision.",
11342
+ not: "accepting a colleague's suggestion (done by a person in the app); changing teams (talonic_contract_desk_save_settings).",
11343
+ args: "`id` the item id; `action` set|crm_add|handled|notice_sent|renewal_declined|terminated (only those the item's question offers); `value` (for set only; may span lines); `note` (why, recorded at the source); `dry_run`.",
11344
+ returns: "{ status decided|suggested, dry_run, decision_id (null on a dry run), undoable, crm_report update|missing|null, revision }.",
11345
+ errors: "400 an action the item does not offer, set without a value, a value on another action; 403 without the edit permission; 409 the item changed."
11346
+ }),
11347
+ route: "POST /v1/contract-desk/items/{id}/decide",
11348
+ inputSchema: {
11349
+ id: zUuid().describe("The item id."),
11350
+ action: z.enum(["set", "crm_add", "handled", "notice_sent", "renewal_declined", "terminated"]).describe(
11351
+ "What to do; talonic_contract_desk_get_decision lists the ones this item offers."
11352
+ ),
11353
+ value: z.string().optional().describe("The value to record; only with action set."),
11354
+ note: z.string().optional().describe("Why, in a few words."),
11355
+ dry_run: z.boolean().optional().describe("Preview only; nothing is recorded.")
11356
+ },
11357
+ annotations: write9(false),
11358
+ body: ["action", "value", "note", "dry_run"]
11359
+ },
11360
+ {
11361
+ name: "talonic_contract_desk_decisions",
11362
+ title: "Contract Desk decisions",
11363
+ description: describe({
11364
+ what: "The Decided list: decisions newest first, with who, what, the item and contract, and whether each can still be undone; plus today's count.",
11365
+ use: "reviewing what was decided, finding a decision to undo, or one contract's history.",
11366
+ not: "open items (talonic_contract_desk_todo).",
11367
+ args: "`mine` (only this connection's person), `crm_key` (one contract), `page`, `limit`.",
11368
+ returns: "{ data[] { id, at, by_name, mine, kind, action, value, note, status, item, contract, undoable, undone_at }, total, page, limit, today }."
11369
+ }),
11370
+ route: "GET /v1/contract-desk/decisions",
11371
+ inputSchema: {
11372
+ mine: z.boolean().optional().describe("Only the decisions of this connection's person."),
11373
+ crm_key: z.string().max(2e3).optional().describe("One contract's decisions."),
11374
+ ...paging
11375
+ },
11376
+ annotations: READ,
11377
+ query: ["mine", "crm_key", "page", "limit"]
11378
+ },
11379
+ {
11380
+ name: "talonic_contract_desk_undo",
11381
+ title: "Undo a Contract Desk decision",
11382
+ description: describe({
11383
+ what: "Undo a decision at its source app and put the item back on the list. Only the latest decision of an item that is not open again can be undone.",
11384
+ use: "a decision was wrong; the id comes from talonic_contract_desk_decide (decision_id) or talonic_contract_desk_decisions.",
11385
+ not: "deciding again (talonic_contract_desk_decide after the undo).",
11386
+ args: "`id` the decision id.",
11387
+ returns: "the decision with undone_at set. 409 not_undoable otherwise."
11388
+ }),
11389
+ route: "POST /v1/contract-desk/decisions/{id}/undo",
11390
+ inputSchema: { id: zUuid().describe("The decision id.") },
11391
+ annotations: write9(false)
11392
+ },
11393
+ {
11394
+ name: "talonic_contract_desk_settings",
11395
+ title: "Contract Desk team setup",
11396
+ description: describe({
11397
+ what: "Which team gets which items: the team per item kind and per attribute, the defaults, the teams and kinds one can choose, and the attributes.",
11398
+ use: "before changing the setup, or to explain why an item went to a team.",
11399
+ not: "changing it (talonic_contract_desk_save_settings).",
11400
+ returns: "{ teams { kinds, fields }, defaults, choices { teams, kinds }, attributes[] }."
11401
+ }),
11402
+ route: "GET /v1/contract-desk/settings",
11403
+ inputSchema: {},
11404
+ annotations: READ
11405
+ },
11406
+ {
11407
+ name: "talonic_contract_desk_save_settings",
11408
+ title: "Change the Contract Desk team setup",
11409
+ description: describe({
11410
+ what: "Replace the whole team setup (the team per item kind and per attribute) and refresh the desk. Needs an Admin of the workspace.",
11411
+ use: "the user wants items routed to other teams. Read talonic_contract_desk_settings, change it, send it whole.",
11412
+ not: "partial edits: kinds and fields left out lose their team.",
11413
+ args: "`teams` { kinds { <kind>: <team> } for value, documents_missing, site_check, text_check, deadline; fields { <field_key>: <team> } }.",
11414
+ returns: "the saved setup. 400 for an unknown kind or team."
11415
+ }),
11416
+ route: "PUT /v1/contract-desk/settings",
11417
+ inputSchema: {
11418
+ teams: z.object({
11419
+ kinds: z.record(z.string(), z.string()).describe("<kind>: <team>."),
11420
+ fields: z.record(z.string(), z.string()).describe("<field_key>: <team>.")
11421
+ }).describe("The whole team setup.")
11422
+ },
11423
+ annotations: write9(true),
11424
+ body: ["teams"]
11425
+ }
11426
+ ]
11427
+ };
11428
+ var pipelineId2 = zUuid().optional().describe("The pipeline (talonic_customs_declaration_pipelines); default: the workspace's first.");
11429
+ var customsDeclarationGroup = {
11430
+ key: "customs_declaration",
11431
+ label: "Customs declaration",
11432
+ docsSlug: "customs-declaration-tools",
11433
+ probe: { path: "/v1/customs-declaration/pipelines" },
11434
+ tools: [
11435
+ {
11436
+ name: "talonic_customs_declaration_pipelines",
11437
+ title: "Customs declaration pipelines",
11438
+ description: describe({
11439
+ what: "The pipelines whose Spec compares transport documents with a filed customs declaration.",
11440
+ use: "finding the pipeline_id the other customs tools take, when the workspace has more than one.",
11441
+ returns: "{ data[] } pipelines with id and name."
11442
+ }),
11443
+ route: "GET /v1/customs-declaration/pipelines",
11444
+ inputSchema: {},
11445
+ annotations: READ
11446
+ },
11447
+ {
11448
+ name: "talonic_customs_declaration_issues",
11449
+ title: "Customs declaration worklist",
11450
+ description: describe({
11451
+ what: "The worklist: orders with a failing check, with the checks that fail (message and fields concerned) and the fields where documents and declaration differ or a value is missing.",
11452
+ use: "'which declarations are not ready to file', the starting point before opening an order.",
11453
+ not: "every order including ready ones (talonic_customs_declaration_orders).",
11454
+ args: "`pipeline_id` (optional).",
11455
+ returns: "{ pipeline, read, available, truncated, data[] { lrn, record_document_id, sender, receiver, checks[] { id, message, fields }, differs[] } }. truncated = more orders exist than were read."
11456
+ }),
11457
+ route: "GET /v1/customs-declaration/issues",
11458
+ inputSchema: { pipeline_id: pipelineId2 },
11459
+ annotations: READ,
11460
+ query: ["pipeline_id"]
11461
+ },
11462
+ {
11463
+ name: "talonic_customs_declaration_orders",
11464
+ title: "Customs declaration orders",
11465
+ description: describe({
11466
+ what: "Orders of a pipeline with their field-by-field comparison (document value, declared value, state match / mismatch / missing) and checks; the evidence for one order's issues.",
11467
+ use: "retrieving the evidence behind an issue (filter with `q` = its LRN), or listing orders ready to file.",
11468
+ args: "`pipeline_id`, `status` ready|review, `q` (LRN, sender, receiver or plates contains), `page` and `limit` (1-200; either asks for one page).",
11469
+ returns: "{ pipeline, read, available, items[] { lrn, ready, sender, receiver, plates, record_document_id, comparison[], checks[] }, page? { page, limit, total, filtered } }."
11470
+ }),
11471
+ route: "GET /v1/customs-declaration/declarations",
11472
+ inputSchema: {
11473
+ pipeline_id: pipelineId2,
11474
+ status: z.enum(["ready", "review"]).optional().describe("ready = every check passes; review = at least one fails."),
11475
+ q: z.string().max(200).optional().describe("LRN, sender, receiver or plates contains."),
11476
+ page: z.number().int().min(1).optional().describe("Page number (asks for one page)."),
11477
+ limit: z.number().int().min(1).max(200).optional().describe("Orders per page, at most 200 (default 50).")
11478
+ },
11479
+ annotations: READ,
11480
+ query: ["pipeline_id", "status", "q", "page", "limit"]
11481
+ }
11482
+ ]
11483
+ };
11484
+ var cursorArgs = {
11485
+ limit: z.number().int().min(1).max(100).optional().describe("Items per page (1-100, default 20)."),
11486
+ cursor: z.string().max(512).optional().describe("pagination.next_cursor of the previous page."),
11487
+ order: z.enum(["asc", "desc"]).optional().describe("By creation time; default desc (newest first)."),
11488
+ after: z.string().optional().describe("Only items created after this ISO-8601 timestamp."),
11489
+ before: z.string().optional().describe("Only items created before this ISO-8601 timestamp.")
11490
+ };
11491
+ var PAGE_QUERY = ["limit", "cursor", "order", "after", "before"];
11492
+ var PAGE_RETURNS = "pagination { total, limit, has_more, next_cursor }";
11493
+ var LIST_DOCUMENTS = describe({
11494
+ what: "List the workspace's documents, newest first, one page at a time, with filters. Only documents this connection may see are listed.",
11495
+ use: "browsing or counting documents by status, source, upload time or filename (e.g. 'which uploads failed today', 'the attachments of this email').",
11496
+ not: "finding documents by their content or a field value (talonic_search, talonic_filter); one document's details (talonic_get_document).",
11497
+ args: "`status` (e.g. completed, error, extracting), `source_id`, `source_type`, `search` (filename contains), `parent_id` (documents unpacked from one container: email attachments, archive members, packet parts), `relation` (why a document is nested, e.g. email_attachment), `top_level` (true: hide nested documents), `text_degraded` (true: only documents whose text could not be read verbatim), `after` / `before` (ISO-8601 creation time), `limit` 1-100 (default 20), `cursor`, `order` asc|desc.",
11498
+ returns: `{ data[] { id, filename, pages, size_bytes, mime_type, type_detected, status, error?, source { id, type }, parent?, field_count, created_at, links }, ${PAGE_RETURNS} }.`
11499
+ });
11500
+ var REEXTRACT = describe({
11501
+ what: "Read an existing document again and capture its values afresh, without uploading it again. Consumes credits like a new extraction. Answers at once with status processing; the document's earlier values are replaced when it finishes.",
11502
+ use: "the user asks to redo a document after its schema or setup changed, or a document came out wrong.",
11503
+ not: "extracting with a different schema now and returning the values (talonic_extract with document_id); a document that is still processing (wait, poll talonic_get_document).",
11504
+ args: "`document_id` (UUID).",
11505
+ returns: "{ id, status: 'processing', message, links }. Poll talonic_get_document until status is completed (or a failure status). Not idempotent and not deduplicated: on a timeout, check the document's status before calling again.",
11506
+ errors: "402 out of credits; 404 the document does not exist or this connection may not see it."
11507
+ });
11508
+ var DELETE_DOCUMENT = describe({
11509
+ what: "Delete one document from the workspace together with its captured values. Cannot be undone.",
11510
+ use: "the user explicitly asks to remove a specific document (a duplicate, a wrong upload, data that must go). Confirm the filename with the user before calling.",
11511
+ not: "hiding a document from a list or retagging it; deleting many documents at once without the user naming them.",
11512
+ args: "`document_id` (UUID).",
11513
+ returns: "{ deleted: true, id }.",
11514
+ errors: "404 the document does not exist, this connection may not see it, or it was only shared with the user (shared documents are read-only)."
11515
+ });
11516
+ var LIST_EXTRACTIONS = describe({
11517
+ what: "List extractions (one per document that has captured values), newest first, one page at a time.",
11518
+ use: "finding the documents with completed or failed captures in a time range, or the extraction of one document.",
11519
+ not: "the values of one extraction (talonic_get_extraction_data); searching by value (talonic_filter).",
11520
+ args: "`document_id` (UUID), `status` complete|failed, `after` / `before` (ISO-8601), `limit` 1-100, `cursor`, `order`.",
11521
+ returns: `{ data[] { id, document_id, status, field_count, created_at, links }, ${PAGE_RETURNS} }. An extraction's id equals its document's id.`
11522
+ });
11523
+ var GET_EXTRACTION = describe({
11524
+ what: "One extraction in full: its fields with values, types and confidence, and the document it belongs to.",
11525
+ use: "inspecting how a document's values were captured before correcting them.",
11526
+ not: "just the field \u2192 value map (talonic_get_extraction_data).",
11527
+ args: "`extraction_id` (UUID; the document id).",
11528
+ returns: "The extraction with its fields, confidence and links."
11529
+ });
11530
+ var GET_EXTRACTION_DATA = describe({
11531
+ what: "One extraction's values as a flat field \u2192 value map (JSON), or as a one-row CSV.",
11532
+ use: "handing a document's captured values to another system or comparing them with a source.",
11533
+ not: "confidence and field metadata (talonic_get_extraction); values across many documents (talonic_field_values).",
11534
+ args: "`extraction_id` (UUID; the document id), `format` json|csv (default json).",
11535
+ returns: "JSON: { <field>: value }. CSV: { format: 'csv', csv } (header row plus one value row)."
11536
+ });
11537
+ var CORRECT_EXTRACTION = describe({
11538
+ what: "Correct captured values of one extraction. Each correction is stored as a new version of the value, attributed to this connection; a value that a reviewer confirmed or that waits for approval is NOT overwritten and is reported in cells_skipped.",
11539
+ use: "the user tells you a captured value is wrong and gives the right one.",
11540
+ not: "changing which fields a schema has (talonic_update_schema); re-reading the whole document (talonic_reextract_document).",
11541
+ args: "`extraction_id` (UUID; the document id), `values` { <field_name>: corrected value } (only the fields to change).",
11542
+ returns: "The extraction, plus cells_written[] and cells_skipped[] (the corrections that were withheld, with why).",
11543
+ errors: "400 `values` is not an object; 403 a workspace-wide (master view) credential; 404 unknown or not visible."
11544
+ });
11545
+ var LIST_JOBS = describe({
11546
+ what: "List jobs (a schema run over a set of documents), newest first, one page at a time.",
11547
+ use: "checking what jobs exist, which are still running, or finding a job id.",
11548
+ not: "Spec runs (talonic_get_run); one job (talonic_get_job).",
11549
+ args: "`status` (e.g. pending, processing, completed, failed), `after` / `before` (ISO-8601), `limit` 1-100, `cursor`, `order`.",
11550
+ returns: `{ data[] { id, name, status, schema, document_count, created_at, completed_at, links }, ${PAGE_RETURNS} }.`
11551
+ });
11552
+ var GET_JOB = describe({
11553
+ what: "One job: status, progress, schema, timestamps, error if it failed.",
11554
+ use: "polling a job created with talonic_create_job until it completes.",
11555
+ not: "the job's extracted rows (talonic_get_job_results).",
11556
+ args: "`job_id` (UUID).",
11557
+ returns: "{ id, name, status, schema, document_count, created_at, completed_at, error?, links }."
11558
+ });
11559
+ var GET_JOB_RESULTS = describe({
11560
+ what: "A job's result rows: one row per document with the extracted values, row confidence and validation flags. Readable while the job still runs (rows appear as documents finish). Only documents this connection may see are included.",
11561
+ use: "reading what a job extracted, e.g. to build a table or check a few values.",
11562
+ not: "one document's values (talonic_get_extraction_data).",
11563
+ args: "`job_id` (UUID).",
11564
+ returns: "{ job_id, job_status, schema { id, name }, total_rows, data[] { id, document_id, filename, status, values, confidence, validation_flags } }."
11565
+ });
11566
+ var CREATE_JOB = describe({
11567
+ what: "Create and queue a job: run a saved schema over a set of documents and collect one row of values per document. Consumes credits per document processed.",
11568
+ use: "the user wants the same fields pulled from many existing documents into one table.",
11569
+ not: "one document (talonic_extract with document_id); running a configured Spec (talonic_run_spec).",
11570
+ args: "`schema_id` (UUID of a saved schema), `document_ids` (UUIDs) OR `all_documents: true` (every completed document of the workspace; confirm with the user and check the cost first, talonic_get_pricing), `name` (optional, at most 200 characters).",
11571
+ returns: "{ id, status: 'pending', message, links { self, results } }. Poll talonic_get_job; read rows with talonic_get_job_results. Not deduplicated: after a timeout, look for the job with talonic_list_jobs before creating another.",
11572
+ errors: "400 no completed documents; 402 out of credits; 404 unknown schema."
11573
+ });
11574
+ var CANCEL_JOB = describe({
11575
+ what: "Cancel a pending or running job. Documents already processed keep their rows; the job ends as failed with the error 'Cancelled via API'.",
11576
+ use: "the user wants to stop a job (wrong schema, wrong documents, too expensive).",
11577
+ args: "`job_id` (UUID).",
11578
+ returns: "The job with status failed. Safe to retry: a job that already ended (completed, failed or cancelled) answers 409 and is left unchanged.",
11579
+ errors: "404 unknown job; 409 the job already ended."
11580
+ });
11581
+ var UPDATE_SCHEMA = describe({
11582
+ what: "Change a saved schema: rename it, change its description, or REPLACE its field list. Sending `definition` or `fields` replaces every field: fields not resent are removed, so read it first (talonic_get_schema), change it, and send the whole list. Confirm removed fields with the user.",
11583
+ use: "the user wants to add, remove or retype fields of a saved schema, or rename it.",
11584
+ not: "creating a schema (talonic_save_schema); a schema managed by a Spec (refused with 409; change the Spec in the app instead).",
11585
+ args: "`schema_id` (UUID or SCH-\u2026 short id), `name` (at most 100 characters), `description` (null clears it), `definition` (JSON Schema: { properties { <field>: { type, description?, title? } }, required[] }) OR `fields[]` { field_name, display_name?, data_type?, description?, is_required? }.",
11586
+ returns: "The schema with its fields as a JSON Schema definition.",
11587
+ errors: "404 unknown schema; 409 the schema is managed by a Spec."
11588
+ });
11589
+ var DELETE_SCHEMA = describe({
11590
+ what: "Delete a saved schema. Cannot be undone. Documents already extracted with it keep their values.",
11591
+ use: "the user explicitly asks to remove a specific schema. Confirm the schema's name with the user before calling.",
11592
+ not: "a schema managed by a Spec (refused with 409).",
11593
+ args: "`schema_id` (UUID or SCH-\u2026 short id).",
11594
+ returns: "{ deleted: true, id }.",
11595
+ errors: "404 unknown schema; 409 the schema is managed by a Spec."
11596
+ });
11597
+ var documentId = { document_id: zUuid().describe("The document id.") };
11598
+ var extractionId = {
11599
+ extraction_id: zUuid().describe("The extraction id (the same as its document's id).")
11600
+ };
11601
+ var jobId = { job_id: zUuid().describe("The job id.") };
11602
+ var schemaId = {
11603
+ schema_id: z.string().min(1).max(64).describe("The schema's UUID or SCH-XXXXXXXX short id.")
11604
+ };
11605
+ var schemaFieldSchema = z.object({
11606
+ field_name: z.string().min(1).describe("Machine name of the field."),
11607
+ display_name: z.string().optional(),
11608
+ data_type: z.string().optional().describe("string (default), number, boolean, date, \u2026"),
11609
+ description: z.string().optional(),
11610
+ is_required: z.boolean().optional()
11611
+ });
11612
+ var getExtractionData = {
11613
+ name: "talonic_get_extraction_data",
11614
+ title: "One extraction's values",
11615
+ description: GET_EXTRACTION_DATA,
11616
+ route: "GET /v1/extractions/{extractionId}/data",
11617
+ inputSchema: {
11618
+ ...extractionId,
11619
+ format: z.enum(["json", "csv"]).optional().describe("json (default) or csv.")
11620
+ },
11621
+ annotations: READ,
11622
+ handler: async (ctx, args) => {
11623
+ const id = args["extraction_id"];
11624
+ if (args["format"] !== "csv") {
11625
+ return runGroupTool({ ...getExtractionData, handler: void 0 }, ctx, args);
11626
+ }
11627
+ return runTool(async () => {
11628
+ const url = buildUrl(ctx.baseUrl, `/v1/extractions/${encodeURIComponent(String(id))}/data`, {
11629
+ format: "csv"
11630
+ });
11631
+ const res = await resolveFetch(ctx.getToken)(url, {
11632
+ method: "GET",
11633
+ headers: { Authorization: `Bearer ${ctx.getToken()}`, Accept: "text/csv" }
11634
+ });
11635
+ if (!res.ok) throw await apiHttpError(res);
11636
+ return { format: "csv", csv: await res.text() };
11637
+ });
11638
+ }
11639
+ };
11640
+ var createJob = {
11641
+ name: "talonic_create_job",
11642
+ title: "Create a job over documents",
11643
+ description: CREATE_JOB,
11644
+ route: "POST /v1/jobs",
11645
+ inputSchema: {
11646
+ schema_id: zUuid().describe("UUID of the saved schema to run."),
11647
+ document_ids: z.array(zUuid()).min(1).max(1e4).optional().describe("The documents to process."),
11648
+ all_documents: z.boolean().optional().describe("true: every completed document of the workspace (instead of document_ids)."),
11649
+ name: z.string().max(200).optional().describe("A name for the job.")
11650
+ },
11651
+ annotations: write9(false),
11652
+ body: ["schema_id", "document_ids", "name"],
11653
+ handler: (ctx, args) => {
11654
+ const ids = args["document_ids"];
11655
+ const all = args["all_documents"] === true;
11656
+ if (ids?.length && all) {
11657
+ return Promise.resolve(
11658
+ validationError("pass `document_ids` or `all_documents: true`, not both.")
11659
+ );
11660
+ }
11661
+ if (!ids?.length && !all) {
11662
+ return Promise.resolve(
11663
+ validationError(
11664
+ "name the documents (`document_ids`) or pass `all_documents: true` to run over every completed document."
11665
+ )
11666
+ );
11667
+ }
11668
+ return runGroupTool({ ...createJob, handler: void 0 }, ctx, args);
11669
+ }
11670
+ };
11671
+ var dataManagementGroup = {
11672
+ key: "data_management",
11673
+ label: "Documents, extractions, jobs and schemas",
11674
+ docsSlug: "data-management-tools",
11675
+ probe: { path: "/v1/documents", params: { limit: 1 } },
11676
+ tools: [
11677
+ {
11678
+ name: "talonic_list_documents",
11679
+ title: "List documents",
11680
+ description: LIST_DOCUMENTS,
11681
+ route: "GET /v1/documents",
11682
+ inputSchema: {
11683
+ status: z.string().max(32).optional().describe("Only documents with this status."),
11684
+ source_id: zUuid().optional().describe("Only documents from this source."),
11685
+ source_type: z.string().max(64).optional().describe("Only documents from this kind of source."),
11686
+ search: z.string().max(200).optional().describe("Filename contains (case-insensitive)."),
11687
+ parent_id: zUuid().optional().describe("Only documents unpacked from this container document."),
11688
+ relation: z.string().max(32).optional().describe("Only nested documents of this kind, e.g. email_attachment."),
11689
+ top_level: z.boolean().optional().describe("true: hide documents nested in another."),
11690
+ text_degraded: z.boolean().optional().describe(
11691
+ "true: only documents whose text was not read verbatim; false: only those that were."
11692
+ ),
11693
+ ...cursorArgs
11694
+ },
11695
+ annotations: READ,
11696
+ query: [
11697
+ "status",
11698
+ "source_id",
11699
+ "source_type",
11700
+ "search",
11701
+ "parent_id",
11702
+ "relation",
11703
+ "top_level",
11704
+ "text_degraded",
11705
+ ...PAGE_QUERY
11706
+ ]
11707
+ },
11708
+ {
11709
+ name: "talonic_reextract_document",
11710
+ title: "Re-extract a document",
11711
+ description: REEXTRACT,
11712
+ route: "POST /v1/documents/{documentId}/re-extract",
11713
+ inputSchema: documentId,
11714
+ annotations: write9(false)
11715
+ },
11716
+ {
11717
+ name: "talonic_delete_document",
11718
+ title: "Delete a document",
11719
+ description: DELETE_DOCUMENT,
11720
+ route: "DELETE /v1/documents/{documentId}",
11721
+ inputSchema: documentId,
11722
+ annotations: write9(true, true)
11723
+ },
11724
+ {
11725
+ name: "talonic_list_extractions",
11726
+ title: "List extractions",
11727
+ description: LIST_EXTRACTIONS,
11728
+ route: "GET /v1/extractions",
11729
+ inputSchema: {
11730
+ document_id: zUuid().optional().describe("Only the extraction of this document."),
11731
+ status: z.enum(["complete", "failed"]).optional(),
11732
+ ...cursorArgs
11733
+ },
11734
+ annotations: READ,
11735
+ query: ["document_id", "status", ...PAGE_QUERY]
11736
+ },
11737
+ {
11738
+ name: "talonic_get_extraction",
11739
+ title: "One extraction",
11740
+ description: GET_EXTRACTION,
11741
+ route: "GET /v1/extractions/{extractionId}",
11742
+ inputSchema: extractionId,
11743
+ annotations: READ
11744
+ },
11745
+ getExtractionData,
11746
+ {
11747
+ name: "talonic_correct_extraction",
11748
+ title: "Correct extracted values",
11749
+ description: CORRECT_EXTRACTION,
11750
+ route: "PATCH /v1/extractions/{extractionId}/data",
11751
+ inputSchema: {
11752
+ ...extractionId,
11753
+ values: z.record(z.string(), z.unknown()).describe("{ <field_name>: corrected value } for the fields to change.")
11754
+ },
11755
+ annotations: write9(true),
11756
+ handler: (ctx, args) => {
11757
+ const values = args["values"];
11758
+ if (!values || typeof values !== "object" || Array.isArray(values)) {
11759
+ return Promise.resolve(validationError("`values` must be an object of field \u2192 value."));
11760
+ }
11761
+ if (Object.keys(values).length === 0) {
11762
+ return Promise.resolve(validationError("`values` names no field to correct."));
11763
+ }
11764
+ return runTool(
11765
+ () => apiJson(
11766
+ ctx.getToken,
11767
+ ctx.baseUrl,
11768
+ "PATCH",
11769
+ `/v1/extractions/${encodeURIComponent(String(args["extraction_id"]))}/data`,
11770
+ { body: values }
11771
+ )
11772
+ );
11773
+ }
11774
+ },
11775
+ {
11776
+ name: "talonic_list_jobs",
11777
+ title: "List jobs",
11778
+ description: LIST_JOBS,
11779
+ route: "GET /v1/jobs",
11780
+ inputSchema: {
11781
+ status: z.string().max(32).optional().describe("Only jobs with this status."),
11782
+ ...cursorArgs
11783
+ },
11784
+ annotations: READ,
11785
+ query: ["status", ...PAGE_QUERY]
11786
+ },
11787
+ {
11788
+ name: "talonic_get_job",
11789
+ title: "One job",
11790
+ description: GET_JOB,
11791
+ route: "GET /v1/jobs/{jobId}",
11792
+ inputSchema: jobId,
11793
+ annotations: READ
11794
+ },
11795
+ {
11796
+ name: "talonic_get_job_results",
11797
+ title: "A job's result rows",
11798
+ description: GET_JOB_RESULTS,
11799
+ route: "GET /v1/jobs/{jobId}/results",
11800
+ inputSchema: jobId,
11801
+ annotations: READ
11802
+ },
11803
+ createJob,
11804
+ {
11805
+ name: "talonic_cancel_job",
11806
+ title: "Cancel a job",
11807
+ description: CANCEL_JOB,
11808
+ route: "POST /v1/jobs/{jobId}/cancel",
11809
+ inputSchema: jobId,
11810
+ annotations: write9(true)
11811
+ },
11812
+ {
11813
+ name: "talonic_update_schema",
11814
+ title: "Change a saved schema",
11815
+ description: UPDATE_SCHEMA,
11816
+ route: "PUT /v1/schemas/{schemaId}",
11817
+ inputSchema: {
11818
+ ...schemaId,
11819
+ name: z.string().min(1).max(100).optional().describe("New name."),
11820
+ description: z.string().nullable().optional().describe("New description; null clears it."),
11821
+ definition: z.object({
11822
+ properties: z.record(z.string(), z.record(z.string(), z.unknown())),
11823
+ required: z.array(z.string()).optional()
11824
+ }).optional().describe("The complete new field list as a JSON Schema object. Replaces every field."),
11825
+ fields: z.array(schemaFieldSchema).min(1).optional().describe("The complete new field list as rows. Replaces every field.")
11826
+ },
11827
+ annotations: write9(true, true),
11828
+ body: ["name", "description", "definition", "fields"],
11829
+ handler: (ctx, args) => {
11830
+ if (args["definition"] !== void 0 && args["fields"] !== void 0) {
11831
+ return Promise.resolve(validationError("send `definition` or `fields`, not both."));
11832
+ }
11833
+ const changes = ["name", "description", "definition", "fields"].filter(
11834
+ (k) => args[k] !== void 0
11835
+ );
11836
+ if (changes.length === 0) {
11837
+ return Promise.resolve(
11838
+ validationError("nothing to change: pass name, description, definition or fields.")
11839
+ );
11840
+ }
11841
+ const req = buildRequest(
11842
+ {
11843
+ route: "PUT /v1/schemas/{schemaId}",
11844
+ body: ["name", "description", "definition", "fields"]
11845
+ },
11846
+ args
11847
+ );
11848
+ return runTool(
11849
+ () => apiJson(ctx.getToken, ctx.baseUrl, req.method, req.path, { body: req.body })
11850
+ );
11851
+ }
11852
+ },
11853
+ {
11854
+ name: "talonic_delete_schema",
11855
+ title: "Delete a saved schema",
11856
+ description: DELETE_SCHEMA,
11857
+ route: "DELETE /v1/schemas/{schemaId}",
11858
+ inputSchema: schemaId,
11859
+ annotations: write9(true, true)
11860
+ }
11861
+ ]
11862
+ };
11863
+ var LIST_EVENTS = describe({
11864
+ what: "Read the workspace's event feed: document extractions, run completions and failures, review verdicts and delivery outcomes, the same events webhooks are sent from. Only events about documents this credential may see are returned.",
11865
+ use: "catching up on what happened since a point in time or since a saved cursor (a poller, a missed webhook), or answering 'what finished / failed recently'.",
11866
+ not: "configuring webhooks (talonic_list_webhooks and its siblings, for workspace admins); workspace totals over a window (talonic_aggregate).",
11867
+ args: "`after` (an event id or a saved `next_cursor`: returns strictly newer events OLDEST FIRST; resume with the returned next_cursor), `since` (ISO-8601 lower bound on created_at), `event_type` (one type or a list), `limit` 1-200 (default 50), `offset` (newest-first listing only, ignored with `after`).",
11868
+ returns: "{ data[] { id, event_type, payload, created_at }, total, limit, offset, next_cursor }. next_cursor is null only at the end of the feed; on the newest-first listing it is the highest id on the page, so a poller can switch to `after` from there."
11869
+ });
11870
+ var eventsGroup = {
11871
+ key: "events",
11872
+ label: "Events",
11873
+ docsSlug: "events-tools",
11874
+ probe: { path: "/v1/events", params: { limit: 1 } },
11875
+ tools: [
11876
+ {
11877
+ name: "talonic_list_events",
11878
+ title: "Workspace event feed",
11879
+ description: LIST_EVENTS,
11880
+ route: "GET /v1/events",
11881
+ inputSchema: {
11882
+ after: z.string().max(64).optional().describe(
11883
+ "Resume point: a saved next_cursor or an event id. Returns newer events, oldest first."
11884
+ ),
11885
+ since: z.string().optional().describe("Only events created at or after this ISO-8601 timestamp."),
11886
+ event_type: z.union([z.string(), z.array(z.string())]).optional().describe("One event type, or several (sent comma-separated)."),
11887
+ limit: z.number().int().min(1).max(200).optional().describe("Events per page (default 50)."),
11888
+ offset: z.number().int().min(0).optional().describe("Events to skip on the newest-first listing; ignored with `after`.")
11889
+ },
11890
+ annotations: READ,
11891
+ query: ["after", "since", "event_type", "limit", "offset"]
11892
+ }
11893
+ ]
11894
+ };
11895
+ var moneyFoundGroup = {
11896
+ key: "money_found",
11897
+ label: "Money Found",
11898
+ docsSlug: "money-found-tools",
11899
+ probe: { path: "/v1/money-found/reviews" },
11900
+ tools: [
11901
+ {
11902
+ name: "talonic_money_found_ledger",
11903
+ title: "Money Found ledger",
11904
+ description: describe({
11905
+ what: "The whole lever ledger: per lever (a kind of recoverable amount, such as a charge the contract allows but the invoices leave off) its rows, each with its key, party and agreement, the amount, its `tier` (e.g. potential) and `state`, the explanation, and the quotes and documents it rests on, plus the ledger totals in the ledger currency.",
11906
+ use: "'how much money is there to recover', or finding one row (lever id and row key) and the evidence behind it.",
11907
+ not: "what to ask the customer for (talonic_money_found_evidence_requests).",
11908
+ returns: "{ currency, as_of, levers[] { id, name, rows[] { key, party, agreement, tier, state, detail, \u2026 } }, potential_total, resolved_total, estimated_total, held_for_review_total, not_finding_total, \u2026 }. Large; ask the user which lever or party matters before reading every row aloud."
11909
+ }),
11910
+ route: "GET /v1/money-found/levers",
11911
+ inputSchema: {},
11912
+ annotations: READ
11913
+ },
11914
+ {
11915
+ name: "talonic_money_found_evidence_requests",
11916
+ title: "Money Found evidence requests",
11917
+ description: describe({
11918
+ what: "What to ask the customer's receivables team for: the open potential rows that need a confirmation, grouped by cost unit and framework number, largest first, each item with its lever id and row key, invoice type, period, amount and the question to ask.",
11919
+ use: "preparing the request for confirmations that turn potential rows into owed ones.",
11920
+ not: "the ledger itself (talonic_money_found_ledger).",
11921
+ returns: "{ currency, groups[] { cost_unit, framework_number, customer, contracts[], total, items[] { lever_id, row_key, invoice_type, period, ask, amount, contract } } }."
11922
+ }),
11923
+ route: "GET /v1/money-found/evidence-requests",
11924
+ inputSchema: {},
11925
+ annotations: READ
11926
+ },
11927
+ {
11928
+ name: "talonic_money_found_reviews",
11929
+ title: "Money Found re-reviews",
11930
+ description: describe({
11931
+ what: "Re-reviews of contract price rows: per row its status (queued, running, done), the outcome, and the suggested price where a contract price was read again.",
11932
+ use: "after talonic_money_found_review_row or talonic_money_found_review_all, to read the outcome.",
11933
+ returns: "The re-reviews with their counts and suggested prices."
11934
+ }),
11935
+ route: "GET /v1/money-found/reviews",
11936
+ inputSchema: {},
11937
+ annotations: READ
11938
+ },
11939
+ {
11940
+ name: "talonic_money_found_review_row",
11941
+ title: "Re-review one Money Found row",
11942
+ description: describe({
11943
+ what: "Queue a re-review of one contract price row: its contract price is checked again against the documents; the ledger changes only when the review finds a different price.",
11944
+ use: "the user doubts a row's amount or its price, or a contract was replaced.",
11945
+ args: "`lever_id`, `key` (the row key from talonic_money_found_ledger).",
11946
+ returns: "{ review } the queued review.",
11947
+ errors: "404 when the lever or row does not exist; 403 when the app is switched off."
11948
+ }),
11949
+ route: "POST /v1/money-found/rows/{leverId}/{key}/review",
11950
+ inputSchema: {
11951
+ lever_id: z.string().min(1).max(200).describe("The lever id of the row."),
11952
+ key: z.string().min(1).max(1e3).describe("The row key.")
11953
+ },
11954
+ annotations: write9(true)
11955
+ },
11956
+ {
11957
+ name: "talonic_money_found_review_all",
11958
+ title: "Re-review every pending Money Found row",
11959
+ description: describe({
11960
+ what: "Queue a re-review of every contract price row not reviewed since its check changed.",
11961
+ use: "bringing the whole ledger up to date after many documents arrived.",
11962
+ returns: "How many reviews were queued."
11963
+ }),
11964
+ route: "POST /v1/money-found/reviews/run",
11965
+ inputSchema: {},
11966
+ annotations: write9(true)
11967
+ }
11968
+ ]
11969
+ };
11970
+ var folderId = zUuid().describe("The folder id (talonic_transport_folders_list or _worklist).");
11971
+ var documentId2 = zUuid().describe("The document id, from the folder's documents.");
11972
+ var loadKey = z.string().min(1).max(200).describe("The load key, from the folder's loads.");
11973
+ var DETAIL_RETURNS = "the folder as talonic_transport_folders_get returns it, after the change: { id, folder_key, status, loads[] { key, verdict complete|check|missing, flags[], comparison[], handover[], confirmed }, documents[] { id, type, status auto|manual|folder|internal|review|pending, load_key, suggested_load_key, candidates[] }, \u2026 }.";
11974
+ var HANDOVER_MAX_BYTES = 8 * 1024 * 1024;
11975
+ var handoverTool = {
11976
+ name: "talonic_transport_folders_handover",
11977
+ title: "Customer document set of a load",
11978
+ description: describe({
11979
+ what: "The customer document set of one load: one PDF with one document per required type (the copy the recipient confirmed where there is one), returned as an embedded PDF file (up to 8 MB), plus the archive filing values per document (`index`).",
11980
+ use: "the user wants the papers to send with the invoice for a load, usually after talonic_transport_folders_confirm_load.",
11981
+ not: "the folder's matching (talonic_transport_folders_get).",
11982
+ args: "`folder_id`, `load_key`.",
11983
+ returns: "a text item { filename, size, index[] } and a resource item { uri, mimeType application/pdf, blob }. 422 when the load has no document to hand over."
11984
+ }),
11985
+ route: "GET /v1/transport-folders/{folderId}/loads/{loadKey}/handover",
11986
+ inputSchema: { folder_id: folderId, load_key: loadKey },
11987
+ annotations: READ,
11988
+ handler: async (ctx, args) => {
11989
+ try {
11990
+ const req = buildRequest(handoverTool, args);
11991
+ const r = await apiJson(
11992
+ ctx.getToken,
11993
+ ctx.baseUrl,
11994
+ req.method,
11995
+ req.path
11996
+ );
11997
+ const meta = {
11998
+ filename: r.filename,
11999
+ size: Math.floor((r.pdf_base64?.length ?? 0) * 3 / 4),
12000
+ index: r.index
12001
+ };
12002
+ if (meta.size > HANDOVER_MAX_BYTES) {
12003
+ return toolError(
12004
+ new Error(
12005
+ `The document set is ${meta.size} bytes, over the ${HANDOVER_MAX_BYTES}-byte limit for a tool result. Download it from the Transport Folders app instead.`
12006
+ )
12007
+ );
12008
+ }
12009
+ const result = {
12010
+ content: [
12011
+ { type: "text", text: JSON.stringify(meta) },
12012
+ {
12013
+ type: "resource",
12014
+ resource: {
12015
+ uri: buildUrl(ctx.baseUrl, req.path),
12016
+ mimeType: "application/pdf",
12017
+ blob: r.pdf_base64
12018
+ }
12019
+ }
12020
+ ],
12021
+ structuredContent: meta
12022
+ };
12023
+ return result;
12024
+ } catch (err) {
12025
+ return toolError(err);
12026
+ }
12027
+ }
12028
+ };
12029
+ var transportFoldersGroup = {
12030
+ key: "transport_folders",
12031
+ label: "Transport Folders",
12032
+ docsSlug: "transport-folders-tools",
12033
+ probe: { path: "/v1/transport-folders/settings" },
12034
+ tools: [
12035
+ {
12036
+ name: "talonic_transport_folders_list",
12037
+ title: "Transport folders",
12038
+ description: describe({
12039
+ what: "Every transport folder (one scanned packet per transport) with its transport number, status (complete, check, missing, review, no_loads, processing) and load counts, and whether the app is set up.",
12040
+ use: "an overview of the folders, or finding one by transport number.",
12041
+ not: "only what needs a person (talonic_transport_folders_worklist); one folder's loads and documents (talonic_transport_folders_get).",
12042
+ returns: "{ configured, data[] { id, folder_key, status, loads, documents, \u2026 } }."
12043
+ }),
12044
+ route: "GET /v1/transport-folders",
12045
+ inputSchema: {},
12046
+ annotations: READ
12047
+ },
12048
+ {
12049
+ name: "talonic_transport_folders_worklist",
12050
+ title: "Transport Folders worklist",
12051
+ description: describe({
12052
+ what: "Everything that needs a person, across all folders: loads that are not complete and documents not assigned to a load.",
12053
+ use: "starting work; each entry names its folder for talonic_transport_folders_get.",
12054
+ not: "all folders (talonic_transport_folders_list).",
12055
+ returns: "{ loads[] { folder_id, load_key, verdict, flags, \u2026 }, documents[] { folder_id, document_id, type, suggested_load_key, \u2026 }, type_labels }."
12056
+ }),
12057
+ route: "GET /v1/transport-folders/worklist",
12058
+ inputSchema: {},
12059
+ annotations: READ
12060
+ },
12061
+ {
12062
+ name: "talonic_transport_folders_get",
12063
+ title: "One transport folder",
12064
+ description: describe({
12065
+ what: "One folder with its loads and matched documents: per load its verdict, what is missing, the record compared with the documents (naming the source document of each value) and whether it is confirmed; per document its type, the load it belongs to and why, or the candidate loads and a suggestion when it waits for a person.",
12066
+ use: "the evidence before assigning a document or confirming a load.",
12067
+ not: "where a value sits on the page (talonic_transport_folders_boxes).",
12068
+ args: "`folder_id`.",
12069
+ returns: DETAIL_RETURNS
12070
+ }),
12071
+ route: "GET /v1/transport-folders/{folderId}",
12072
+ inputSchema: { folder_id: folderId },
12073
+ annotations: READ
12074
+ },
12075
+ {
12076
+ name: "talonic_transport_folders_boxes",
12077
+ title: "Where a document's values sit",
12078
+ description: describe({
12079
+ what: "Where each captured value of one document sits on its pages (boxes as page fractions), as far as already located.",
12080
+ use: "pointing the user to the value on the scan.",
12081
+ not: "locating values that have no box yet (talonic_transport_folders_locate_document).",
12082
+ args: "`folder_id`, `document_id`.",
12083
+ returns: "{ document_id, pages[], boxes[] { field, value, page, x, y, w, h } }."
12084
+ }),
12085
+ route: "GET /v1/transport-folders/{folderId}/documents/{documentId}/boxes",
12086
+ inputSchema: { folder_id: folderId, document_id: documentId2 },
12087
+ annotations: READ
12088
+ },
12089
+ {
12090
+ name: "talonic_transport_folders_locate_document",
12091
+ title: "Locate a document's values",
12092
+ description: describe({
12093
+ what: "Find where each captured value of one document sits on its page images and keep the boxes. Does nothing when the values were already located. Needs the app switched on.",
12094
+ use: "talonic_transport_folders_boxes came back without boxes.",
12095
+ not: "a whole folder (talonic_transport_folders_locate_folder).",
12096
+ args: "`folder_id`, `document_id`.",
12097
+ returns: "the document's boxes, as talonic_transport_folders_boxes returns them."
12098
+ }),
12099
+ route: "POST /v1/transport-folders/{folderId}/documents/{documentId}/locate",
12100
+ inputSchema: { folder_id: folderId, document_id: documentId2 },
12101
+ annotations: write9(true)
12102
+ },
12103
+ {
12104
+ name: "talonic_transport_folders_locate_folder",
12105
+ title: "Locate a folder's values",
12106
+ description: describe({
12107
+ what: "Find where the captured values of every document of a folder sit on the page images. Documents already located are skipped. Needs the app switched on.",
12108
+ use: "before going through a folder's documents on screen.",
12109
+ not: "one document (talonic_transport_folders_locate_document).",
12110
+ args: "`folder_id`.",
12111
+ returns: "per document whether boxes are now stored."
12112
+ }),
12113
+ route: "POST /v1/transport-folders/{folderId}/locate",
12114
+ inputSchema: { folder_id: folderId },
12115
+ annotations: write9(true)
12116
+ },
12117
+ {
12118
+ name: "talonic_transport_folders_assign",
12119
+ title: "Assign a document to a load",
12120
+ description: describe({
12121
+ what: "Record which load a document belongs to, or that it belongs to no load (`load_key` null). A person's assignment wins over the matching. Undo with talonic_transport_folders_unassign.",
12122
+ use: "a document waits for review, or was matched to the wrong load.",
12123
+ not: "confirming the load (talonic_transport_folders_confirm_load).",
12124
+ args: "`folder_id`, `document_id`, `load_key` (a load of this folder, or null for no load).",
12125
+ returns: DETAIL_RETURNS,
12126
+ errors: "400 load_key is not a load of this folder; 404 document not in this folder."
12127
+ }),
12128
+ route: "POST /v1/transport-folders/{folderId}/documents/{documentId}/assign",
12129
+ inputSchema: {
12130
+ folder_id: folderId,
12131
+ document_id: documentId2,
12132
+ load_key: z.string().max(200).nullable().describe("The load the document belongs to; null = it belongs to no load.")
12133
+ },
12134
+ annotations: write9(true),
12135
+ body: ["load_key"]
12136
+ },
12137
+ {
12138
+ name: "talonic_transport_folders_unassign",
12139
+ title: "Withdraw a document's assignment",
12140
+ description: describe({
12141
+ what: "Withdraw a person's assignment of a document, so the matching decides again.",
12142
+ use: "an assignment made with talonic_transport_folders_assign was wrong.",
12143
+ args: "`folder_id`, `document_id`.",
12144
+ returns: DETAIL_RETURNS
12145
+ }),
12146
+ route: "DELETE /v1/transport-folders/{folderId}/documents/{documentId}/assign",
12147
+ inputSchema: { folder_id: folderId, document_id: documentId2 },
12148
+ annotations: write9(true)
12149
+ },
12150
+ {
12151
+ name: "talonic_transport_folders_confirm_load",
12152
+ title: "Confirm a load",
12153
+ description: describe({
12154
+ what: "Confirm a load as ready to invoice and hand its customer document set over. Records who confirmed and which documents. Needs the app switched on. Undo with talonic_transport_folders_unconfirm_load.",
12155
+ use: "the load's verdict is complete, or the user checked it and accepts it.",
12156
+ not: "getting the PDF (talonic_transport_folders_handover).",
12157
+ args: "`folder_id`, `load_key`.",
12158
+ returns: DETAIL_RETURNS
12159
+ }),
12160
+ route: "POST /v1/transport-folders/{folderId}/loads/{loadKey}/confirm",
12161
+ inputSchema: { folder_id: folderId, load_key: loadKey },
12162
+ annotations: write9(true)
12163
+ },
12164
+ {
12165
+ name: "talonic_transport_folders_unconfirm_load",
12166
+ title: "Withdraw a load's confirmation",
12167
+ description: describe({
12168
+ what: "Withdraw the confirmation of a load.",
12169
+ use: "a load was confirmed by mistake.",
12170
+ args: "`folder_id`, `load_key`.",
12171
+ returns: DETAIL_RETURNS
12172
+ }),
12173
+ route: "DELETE /v1/transport-folders/{folderId}/loads/{loadKey}/confirm",
12174
+ inputSchema: { folder_id: folderId, load_key: loadKey },
12175
+ annotations: write9(true)
12176
+ },
12177
+ handoverTool,
12178
+ {
12179
+ name: "talonic_transport_folders_settings",
12180
+ title: "Transport Folders settings",
12181
+ description: describe({
12182
+ what: "The app's settings (the Spec whose results describe the documents, the reference table holding the loads, the pattern that reads the transport number from a filename, matching overrides) and what they can be set to (the workspace's Specs and ready reference tables).",
12183
+ use: "setting up the app, or explaining why a folder has no loads.",
12184
+ not: "changing them (talonic_transport_folders_save_settings).",
12185
+ returns: "{ settings, pipelines[] { id, name, status }, reference_tables[] { id, name, row_count } }."
12186
+ }),
12187
+ route: "GET /v1/transport-folders/settings",
12188
+ inputSchema: {},
12189
+ annotations: READ
12190
+ },
12191
+ {
12192
+ name: "talonic_transport_folders_save_settings",
12193
+ title: "Change Transport Folders settings",
12194
+ description: describe({
12195
+ what: "Change the app's settings. Only the keys sent change; null clears one. Needs an Admin of the workspace.",
12196
+ use: "setting up the app or pointing it at another Spec or reference table.",
12197
+ args: "`pipeline_id` (from talonic_transport_folders_settings pipelines), `reference_data_id`, `folder_key_pattern` (a regular expression whose first group is the transport number), `matcher` (overrides of column names, field names, document type lists).",
12198
+ returns: "the settings and choices, as talonic_transport_folders_settings returns them. 400 for an invalid pattern."
12199
+ }),
12200
+ route: "PUT /v1/transport-folders/settings",
12201
+ inputSchema: {
12202
+ pipeline_id: zUuid().nullable().optional().describe("The Spec run whose results describe the documents."),
12203
+ reference_data_id: zUuid().nullable().optional().describe("The reference table holding the loads."),
12204
+ folder_key_pattern: z.string().max(200).nullable().optional().describe("Regular expression; its first group is the transport number in a filename."),
12205
+ matcher: z.record(z.string(), z.unknown()).nullable().optional().describe("Overrides of the matching defaults.")
12206
+ },
12207
+ annotations: write9(true),
12208
+ body: ["pipeline_id", "reference_data_id", "folder_key_pattern", "matcher"]
12209
+ }
12210
+ ]
12211
+ };
12212
+
12213
+ // src/tools/tool-groups.ts
12214
+ var TOOL_GROUPS = [
12215
+ dataManagementGroup,
12216
+ eventsGroup,
12217
+ aggregateGroup,
12218
+ adminGroup,
12219
+ contractDeskGroup,
12220
+ transportFoldersGroup,
12221
+ complianceGroup,
12222
+ moneyFoundGroup,
12223
+ customsDeclarationGroup
12224
+ ];
12225
+ TOOL_GROUPS.map((g) => g.key);
12226
+ function registerToolGroups(server, keys, getToken, baseUrl) {
12227
+ const wanted = new Set(keys);
12228
+ for (const group of TOOL_GROUPS) {
12229
+ if (wanted.has(group.key)) registerGroup(server, group, getToken, baseUrl);
12230
+ }
12231
+ }
12232
+
12233
+ // package.json
12234
+ var package_default = {
12235
+ version: "0.1.105"};
12236
+
12237
+ // src/version.ts
12238
+ var VERSION = package_default.version;
12239
+ var SERVER_NAME = "talonic";
12240
+
12241
+ // src/server-factory.ts
12242
+ function makeTaggedFetch(getClientName, baseFetch = fetch) {
12243
+ return ((input, init) => {
12244
+ try {
12245
+ const headers = new Headers(init?.headers);
12246
+ const cn = getClientName();
12247
+ headers.set("user-agent", `talonic-mcp/${VERSION}${cn ? ` ${cn}` : ""}`);
12248
+ return baseFetch(input, { ...init, headers });
12249
+ } catch {
12250
+ return baseFetch(input, init);
12251
+ }
12252
+ });
12253
+ }
12254
+ function buildServerInstructions(opts) {
12255
+ return [
12256
+ "Talonic turns unstructured documents (PDFs, scans, images, DOCX, emails) into",
12257
+ "schema-validated JSON with per-field confidence scores and source provenance, and",
12258
+ "answers questions about the documents in the user's Talonic workspace.",
9143
12259
  "Which tool for which question:",
9144
12260
  "(0) any question about what the documents contain (counts, totals, duplicates,",
9145
12261
  "comparisons, anomalies) -> talonic_ask FIRST, in one call; do not explore fields,",
@@ -9179,6 +12295,16 @@ function buildServerInstructions(opts) {
9179
12295
  "apps:decide consent and a senior_member role or above; on HTTP 403 tell the user",
9180
12296
  "which consent or role is missing instead of retrying."
9181
12297
  ] : [],
12298
+ ...opts.includeAppsToolset ? [
12299
+ "To build an app: talonic_create_app -> talonic_save_app_draft ->",
12300
+ "talonic_interpret_app_rules -> talonic_publish_app -> talonic_run_app (dry_run first) ->",
12301
+ "talonic_get_app_run or talonic_get_run_verdicts -> talonic_check_app_acceptance.",
12302
+ "Human Reviews: talonic_list_app_reviews -> talonic_resolve_app_review."
12303
+ ] : [],
12304
+ ...opts.includeMiningDriverTools ? [
12305
+ "A rule-finding round waiting for an outside driver is claimed and closed with the",
12306
+ "decision-task tools; in between, call its tools with talonic_mining_call_round_tool."
12307
+ ] : [],
9182
12308
  "Tools that change workspace data (saving schemas, app updates, decisions) should only",
9183
12309
  "be called when the user asked for that change. Every error ends with a 'Next step'",
9184
12310
  "line: follow it.",
@@ -9242,7 +12368,9 @@ function createServer(options) {
9242
12368
  instructions: buildServerInstructions({
9243
12369
  includeGenericExecutor: options.includeGenericExecutor !== false,
9244
12370
  includeAgentTaskTools: options.includeAgentTaskTools !== false,
9245
- includeDecisionTaskTools: options.includeDecisionTaskTools !== false
12371
+ includeDecisionTaskTools: options.includeDecisionTaskTools !== false,
12372
+ includeAppsToolset: options.includeAppsToolset === true,
12373
+ includeMiningDriverTools: options.includeMiningDriverTools === true
9246
12374
  })
9247
12375
  }
9248
12376
  );
@@ -9284,6 +12412,14 @@ function createServer(options) {
9284
12412
  invocable: options.decisionTasksInvocable !== false
9285
12413
  });
9286
12414
  }
12415
+ if (options.includeAppsToolset) {
12416
+ registerAppsToolset(server, rawToken, baseUrl);
12417
+ }
12418
+ if (options.includeMiningDriverTools) {
12419
+ registerMiningDriverTools(server, rawToken, baseUrl, {
12420
+ invocable: options.decisionTasksInvocable !== false
12421
+ });
12422
+ }
9287
12423
  if (options.includeGrowthTools) {
9288
12424
  registerGrowthTools(server, rawToken, baseUrl);
9289
12425
  }
@@ -9317,6 +12453,9 @@ function createServer(options) {
9317
12453
  if (options.includePriceBaselineTools) {
9318
12454
  registerPriceBaselineTools(server, rawToken, baseUrl);
9319
12455
  }
12456
+ if (options.toolGroups?.length) {
12457
+ registerToolGroups(server, options.toolGroups, rawToken, baseUrl);
12458
+ }
9320
12459
  registerSchemasResource(server, getTalonic);
9321
12460
  registerWebhooksResource(server, rawToken, baseUrl);
9322
12461
  registerWidgets(server);