@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.
@@ -3,7 +3,7 @@ import { createHash } from 'crypto';
3
3
  import { realpathSync } from 'fs';
4
4
  import { fileURLToPath } from 'url';
5
5
  import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
6
- import { Talonic, TalonicError } from '@talonic/node';
6
+ import { TalonicError, Talonic } from '@talonic/node';
7
7
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
8
8
  import { z } from 'zod';
9
9
  import { readFile } from 'fs/promises';
@@ -169,10 +169,10 @@ async function probeAccessState(token, baseUrl, path, accept = () => true, param
169
169
  }
170
170
  async function apiForm(getToken, baseUrl, path, fields) {
171
171
  const form = new FormData();
172
- for (const [key, value] of Object.entries(fields)) {
172
+ for (const [key2, value] of Object.entries(fields)) {
173
173
  if (value === void 0) continue;
174
- if (Array.isArray(value)) for (const item of value) form.append(key, item);
175
- else form.append(key, value);
174
+ if (Array.isArray(value)) for (const item of value) form.append(key2, item);
175
+ else form.append(key2, value);
176
176
  }
177
177
  const res = await resolveFetch(getToken)(buildUrl(baseUrl, path), {
178
178
  method: "POST",
@@ -288,7 +288,7 @@ function registerWebhooksResource(server, getToken, baseUrl) {
288
288
  const results = {};
289
289
  const token = getToken();
290
290
  await Promise.all(
291
- WEBHOOK_INFO_ENDPOINTS.map(async ({ path, key }) => {
291
+ WEBHOOK_INFO_ENDPOINTS.map(async ({ path, key: key2 }) => {
292
292
  try {
293
293
  const res = await resolveFetch(getToken)(`${base2}${path}`, {
294
294
  headers: {
@@ -297,15 +297,15 @@ function registerWebhooksResource(server, getToken, baseUrl) {
297
297
  }
298
298
  });
299
299
  if (res.ok) {
300
- results[key] = await res.json();
300
+ results[key2] = await res.json();
301
301
  } else {
302
- results[key] = {
302
+ results[key2] = {
303
303
  error: `HTTP ${res.status}`,
304
304
  message: await res.text().catch(() => "")
305
305
  };
306
306
  }
307
307
  } catch (err) {
308
- results[key] = {
308
+ results[key2] = {
309
309
  error: "fetch_failed",
310
310
  message: err instanceof Error ? err.message : String(err)
311
311
  };
@@ -472,22 +472,22 @@ var CARD_TOOL_KEYS = /* @__PURE__ */ new Set([
472
472
  "saveSchema",
473
473
  "createAccount"
474
474
  ]);
475
- function widgetToolMeta(key) {
476
- const uri = WIDGET_URIS[key];
477
- const status3 = TOOL_INVOCATION_STATUS[key];
475
+ function widgetToolMeta(key2) {
476
+ const uri = WIDGET_URIS[key2];
477
+ const status3 = TOOL_INVOCATION_STATUS[key2];
478
478
  const meta = {
479
479
  "openai/toolInvocation/invoking": status3.invoking,
480
480
  "openai/toolInvocation/invoked": status3.invoked
481
481
  };
482
- if (CARD_TOOL_KEYS.has(key)) {
482
+ if (CARD_TOOL_KEYS.has(key2)) {
483
483
  meta["ui"] = { resourceUri: uri };
484
484
  meta["openai/outputTemplate"] = uri;
485
485
  }
486
486
  return meta;
487
487
  }
488
488
  function widgetKeyForUri(uri) {
489
- for (const key of Object.keys(WIDGET_URIS)) {
490
- if (WIDGET_URIS[key] === uri) return key;
489
+ for (const key2 of Object.keys(WIDGET_URIS)) {
490
+ if (WIDGET_URIS[key2] === uri) return key2;
491
491
  }
492
492
  return void 0;
493
493
  }
@@ -2392,25 +2392,25 @@ var WIDGET_REGISTRY = {
2392
2392
  }
2393
2393
  };
2394
2394
  function getWidgetTemplateHtml(uri) {
2395
- const key = widgetKeyForUri(uri);
2396
- return key ? WIDGET_REGISTRY[key].html() : void 0;
2395
+ const key2 = widgetKeyForUri(uri);
2396
+ return key2 ? WIDGET_REGISTRY[key2].html() : void 0;
2397
2397
  }
2398
2398
  function getWidgetTemplateMeta(uri) {
2399
- const key = widgetKeyForUri(uri);
2400
- return key ? widgetMeta(WIDGET_DESCRIPTIONS[key]) : void 0;
2399
+ const key2 = widgetKeyForUri(uri);
2400
+ return key2 ? widgetMeta(WIDGET_DESCRIPTIONS[key2]) : void 0;
2401
2401
  }
2402
- function registerOne(server, key) {
2403
- const entry = WIDGET_REGISTRY[key];
2402
+ function registerOne(server, key2) {
2403
+ const entry = WIDGET_REGISTRY[key2];
2404
2404
  registerWidget(server, {
2405
2405
  name: entry.name,
2406
- uri: WIDGET_URIS[key],
2406
+ uri: WIDGET_URIS[key2],
2407
2407
  title: entry.title,
2408
- description: WIDGET_DESCRIPTIONS[key],
2408
+ description: WIDGET_DESCRIPTIONS[key2],
2409
2409
  html: entry.html()
2410
2410
  });
2411
2411
  }
2412
2412
  function registerWidgets(server) {
2413
- for (const key of Object.keys(WIDGET_REGISTRY)) registerOne(server, key);
2413
+ for (const key2 of Object.keys(WIDGET_REGISTRY)) registerOne(server, key2);
2414
2414
  }
2415
2415
  var DESCRIPTION = [
2416
2416
  "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.",
@@ -3003,8 +3003,8 @@ async function handleListSchemas(talonic) {
3003
3003
  const result = await talonic.schemas.list();
3004
3004
  const data = Array.isArray(result?.data) ? result.data.map((schema) => {
3005
3005
  const summary = {};
3006
- for (const [key, value] of Object.entries(schema)) {
3007
- if (!LIST_ITEM_OMIT.has(key)) summary[key] = value;
3006
+ for (const [key2, value] of Object.entries(schema)) {
3007
+ if (!LIST_ITEM_OMIT.has(key2)) summary[key2] = value;
3008
3008
  }
3009
3009
  return summary;
3010
3010
  }) : result?.data;
@@ -3912,10 +3912,10 @@ function handleImport(getToken, baseUrl, args) {
3912
3912
  if (!!args.all === !!args.document_ids?.length)
3913
3913
  return Promise.resolve(validationError("Pass either `all: true` or `document_ids`, not both."));
3914
3914
  if (args.all) {
3915
- const { query, contract_keys, only_priced, limit: limit2, dry_run } = args;
3915
+ const { query, contract_keys, only_priced, limit: limit3, dry_run } = args;
3916
3916
  return runTool(
3917
3917
  () => apiJson(getToken, baseUrl, "POST", "/v1/contracts/import/all", {
3918
- body: { query, contract_keys, only_priced, limit: limit2, dry_run }
3918
+ body: { query, contract_keys, only_priced, limit: limit3, dry_run }
3919
3919
  })
3920
3920
  );
3921
3921
  }
@@ -4068,7 +4068,7 @@ function handleSetTerm(getToken, baseUrl, args) {
4068
4068
  );
4069
4069
  }
4070
4070
  function registerContractsTools(server, getToken, baseUrl) {
4071
- const tools = [
4071
+ const tools2 = [
4072
4072
  [
4073
4073
  "talonic_contracts_register",
4074
4074
  "List contracts",
@@ -4191,7 +4191,7 @@ function registerContractsTools(server, getToken, baseUrl) {
4191
4191
  (a) => handleSetTerm(getToken, baseUrl, a)
4192
4192
  ]
4193
4193
  ];
4194
- for (const [name, title, description, inputSchema11, annotations, handler] of tools) {
4194
+ for (const [name, title, description, inputSchema11, annotations, handler] of tools2) {
4195
4195
  server.registerTool(
4196
4196
  name,
4197
4197
  { title, description, inputSchema: inputSchema11, annotations: { title, ...annotations } },
@@ -4355,7 +4355,7 @@ function handleRuns(getToken, baseUrl, args) {
4355
4355
  );
4356
4356
  }
4357
4357
  function registerApTools(server, getToken, baseUrl) {
4358
- const tools = [
4358
+ const tools2 = [
4359
4359
  [
4360
4360
  "talonic_ap_overview",
4361
4361
  "AP totals",
@@ -4421,7 +4421,7 @@ function registerApTools(server, getToken, baseUrl) {
4421
4421
  (a) => handleRuns(getToken, baseUrl, a)
4422
4422
  ]
4423
4423
  ];
4424
- for (const [name, title, description, inputSchema11, annotations, handler] of tools) {
4424
+ for (const [name, title, description, inputSchema11, annotations, handler] of tools2) {
4425
4425
  server.registerTool(
4426
4426
  name,
4427
4427
  { title, description, inputSchema: inputSchema11, annotations: { title, ...annotations } },
@@ -4904,15 +4904,15 @@ function handleGenerate(getToken, baseUrl, args, deps = {}) {
4904
4904
  dry_run: args.dry_run ?? false
4905
4905
  }
4906
4906
  });
4907
- const jobId = created.job?.id;
4908
- if (waitS === 0 || !jobId || created.job?.status !== "running") return created;
4907
+ const jobId2 = created.job?.id;
4908
+ if (waitS === 0 || !jobId2 || created.job?.status !== "running") return created;
4909
4909
  const polled = await pollUntilDone(
4910
4910
  created.job,
4911
4911
  () => apiJson(
4912
4912
  getToken,
4913
4913
  baseUrl,
4914
4914
  "GET",
4915
- `/v1/doc-gen/jobs/${jobId}`
4915
+ `/v1/doc-gen/jobs/${jobId2}`
4916
4916
  ),
4917
4917
  (job) => job?.status === "running",
4918
4918
  waitS,
@@ -4995,7 +4995,7 @@ async function handleFile(getToken, baseUrl, args, maxBytes = DOC_GEN_MAX_FILE_B
4995
4995
  }
4996
4996
  }
4997
4997
  function registerDocGenTools(server, getToken, baseUrl, opts = {}) {
4998
- const tools = [
4998
+ const tools2 = [
4999
4999
  [
5000
5000
  "talonic_doc_gen_status",
5001
5001
  "Document Generation status",
@@ -5128,7 +5128,7 @@ function registerDocGenTools(server, getToken, baseUrl, opts = {}) {
5128
5128
  (a) => handleFile(getToken, baseUrl, a)
5129
5129
  ]
5130
5130
  ];
5131
- for (const [name, title, description, inputSchema11, annotations, handler] of tools) {
5131
+ for (const [name, title, description, inputSchema11, annotations, handler] of tools2) {
5132
5132
  server.registerTool(
5133
5133
  name,
5134
5134
  { title, description, inputSchema: inputSchema11, annotations: { title, ...annotations } },
@@ -5150,8 +5150,10 @@ var write4 = (idempotent, destructive2 = false) => ({
5150
5150
  });
5151
5151
  var PARTIES_POLL_INTERVAL_MS = 5e3;
5152
5152
  var READ_MAX_WAIT_S = 600;
5153
+ var CONFIRM_MAX_ROLES = 200;
5153
5154
  var ROLES2 = [
5154
5155
  "partner",
5156
+ "our_party",
5155
5157
  "manager",
5156
5158
  "tenant",
5157
5159
  "previous_owner",
@@ -5162,29 +5164,18 @@ var ROLES2 = [
5162
5164
  var KINDS = ["person", "company", "owners_association", "unknown"];
5163
5165
  var SALUTATIONS = ["herr", "frau", "eheleute", "firma", "weg"];
5164
5166
  var ROLE_STATES = ["suggested", "confirmed", "rejected"];
5165
- var ISSUE_CODES = [
5166
- "no_partner",
5167
- "several_partners",
5168
- "reference_disagrees",
5169
- "kind_unknown",
5170
- "address_missing",
5171
- "manager_without_party",
5172
- "tenant_without_period",
5173
- "owner_change_open",
5174
- "cost_unit_disagrees",
5175
- "cost_unit_missing",
5176
- "not_read",
5177
- "read_failed",
5178
- "possible_duplicate"
5179
- ];
5180
- 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.";
5167
+ 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.";
5181
5168
  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.";
5182
- 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.";
5169
+ 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.";
5170
+ 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).";
5183
5171
  var dateArg = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "a date YYYY-MM-DD").describe("ISO date YYYY-MM-DD.");
5184
- var contractIdArg2 = zUuid().describe(
5185
- "Contract id (from talonic_parties_contracts or talonic_parties_issues)."
5172
+ var productIdArg2 = zUuid().describe(
5173
+ "Data product of the contract (contracts[].row.data_product_id from talonic_parties_contracts)."
5186
5174
  );
5187
- var partyIdArg = zUuid().describe("Party id (from talonic_parties_search, _contract or _issues).");
5175
+ var rowIdArg2 = z.string().min(1).max(200).describe("The contract's row id in that product (contracts[].row.row_id).");
5176
+ var partyIdArg = zUuid().describe("Party id (from talonic_parties_search, _issues or _contract).");
5177
+ var limitArg = (max, dflt) => z.number().int().min(1).max(max).optional().describe(`At most this many (1-${max}, default ${dflt}).`);
5178
+ var offsetArg = z.number().int().min(0).max(1e6).optional().describe("Skip this many (paging; default 0).");
5188
5179
  function waitSeconds2(requested, max) {
5189
5180
  const n = Number.isFinite(requested) ? requested : 0;
5190
5181
  return Math.max(0, Math.min(max, Math.floor(n)));
@@ -5192,91 +5183,165 @@ function waitSeconds2(requested, max) {
5192
5183
  function defined(obj) {
5193
5184
  return Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== void 0));
5194
5185
  }
5186
+ var rowPath = (productId, rowId) => `/v1/parties/rows/${productId}/${encodeURIComponent(rowId)}`;
5187
+ async function waitUntil(probe, done, waitS, deps) {
5188
+ const sleep2 = deps.sleep ?? sleep;
5189
+ const now = deps.now ?? Date.now;
5190
+ const start = now();
5191
+ const deadline = start + waitS * 1e3;
5192
+ let last = await probe();
5193
+ let pollError;
5194
+ while (!done(last) && now() < deadline) {
5195
+ await sleep2(Math.min(PARTIES_POLL_INTERVAL_MS, deadline - now()));
5196
+ try {
5197
+ last = await probe();
5198
+ } catch (err) {
5199
+ pollError = err instanceof Error ? err.message : String(err);
5200
+ break;
5201
+ }
5202
+ }
5203
+ return {
5204
+ last,
5205
+ waited_ms: now() - start,
5206
+ still_running: pollError !== void 0 || !done(last),
5207
+ ...pollError ? { poll_error: pollError } : {}
5208
+ };
5209
+ }
5195
5210
  var STATUS_DESCRIPTION3 = [
5196
- "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.",
5197
- "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.",
5198
- "NOT FOR: what to fix (talonic_parties_issues); one contract (talonic_parties_contract).",
5211
+ "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.",
5212
+ "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.",
5213
+ "NOT FOR: which parties need fixing (talonic_parties_issues); one contract (talonic_parties_contract).",
5199
5214
  "",
5200
5215
  "ARGS: none.",
5201
- "RETURNS: { contracts, contracts_confirmed, contracts_suggested, contracts_without_partner, parties, suggestions, reads { counts { pending, running, done, failed }, unread, failed } }."
5216
+ "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 } }."
5202
5217
  ].join("\n");
5203
5218
  function handleStatus2(getToken, baseUrl) {
5204
5219
  return runTool(() => apiJson(getToken, baseUrl, "GET", "/v1/parties/status"));
5205
5220
  }
5206
5221
  var ISSUES_DESCRIPTION4 = [
5207
- "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).",
5208
- "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).",
5209
- "NOT FOR: the headline counts (talonic_parties_status); all contracts (talonic_parties_contracts).",
5222
+ "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.",
5223
+ "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).",
5224
+ "NOT FOR: the headline counts (talonic_parties_status); the whole register (talonic_parties_search).",
5210
5225
  "",
5211
- `ARGS: \`code\` (only this issue; one of ${ISSUE_CODES.join(", ")}).`,
5212
- "RETURNS: { contracts[] { contract_id, contract_key, title, issues[] { code, detail, role_ids[], party_ids[] } }, duplicates[] { name_key, party_ids[], names[] } }."
5226
+ "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`.",
5227
+ "RETURNS: { total, needs_attention, offset, limit, data[] { id, kind, display_name, street, postcode, town, email, phone, status, contracts, roles[], issues (problems plus duplicate candidates) } }."
5213
5228
  ].join("\n");
5214
5229
  var issuesInputSchema2 = {
5215
- code: z.enum(ISSUE_CODES).optional().describe("Only this issue code.")
5230
+ query: z.string().max(300).optional().describe("Name, address or email contains."),
5231
+ kind: z.enum(KINDS).optional().describe("Only parties of this kind."),
5232
+ product_id: zUuid().optional().describe("Only contracts of this data product."),
5233
+ scope: z.enum(["all", "partners"]).optional().describe("all (default): every party; partners: contract partners only."),
5234
+ limit: limitArg(5e3, 200),
5235
+ offset: offsetArg
5216
5236
  };
5217
5237
  function handleIssues4(getToken, baseUrl, args) {
5218
5238
  return runTool(
5219
- () => apiJson(getToken, baseUrl, "GET", "/v1/parties/issues", { params: { code: args.code } })
5220
- );
5221
- }
5222
- var CONTRACTS_DESCRIPTION = [
5223
- "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.",
5224
- "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).",
5225
- "NOT FOR: one contract's roles and evidence (talonic_parties_contract); what needs fixing (talonic_parties_issues).",
5226
- "",
5227
- "ARGS: `query` (contract key, title, counterparty, partner or Verwalter contains), `state` confirmed|suggested|none, `limit` (1-5000, default 500).",
5228
- "RETURNS: { total, data[] { id, contract_key, title, counterparty, status, partner, addressee, manager, state, suggestions, read } }."
5229
- ].join("\n");
5230
- var contractsInputSchema = {
5231
- query: z.string().optional().describe("Key, title, counterparty, partner or Verwalter contains."),
5232
- state: z.enum(["confirmed", "suggested", "none"]).optional().describe("Only contracts whose parties are in this state."),
5233
- limit: z.number().int().min(1).max(5e3).optional().describe("At most this many (default 500).")
5234
- };
5235
- function handleContracts(getToken, baseUrl, args) {
5236
- return runTool(
5237
- () => apiJson(getToken, baseUrl, "GET", "/v1/parties/contracts", {
5238
- params: { q: args.query, state: args.state, limit: args.limit }
5239
+ () => apiJson(getToken, baseUrl, "GET", "/v1/parties", {
5240
+ params: {
5241
+ attention: "true",
5242
+ scope: args.scope === "partners" ? void 0 : "all",
5243
+ q: args.query,
5244
+ kind: args.kind,
5245
+ product_id: args.product_id,
5246
+ limit: args.limit,
5247
+ offset: args.offset
5248
+ }
5239
5249
  })
5240
5250
  );
5241
5251
  }
5242
5252
  var CONTRACT_DESCRIPTION2 = [
5243
- "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.",
5244
- "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.",
5253
+ "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.",
5254
+ "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.",
5255
+ CONTRACT_IS_A_ROW,
5245
5256
  ROLES_EXPLAINED,
5246
5257
  COMPUTED_RULE,
5247
- "NOT FOR: the list of contracts (talonic_parties_contracts); one party across contracts (talonic_parties_party).",
5258
+ "NOT FOR: one party's contracts (talonic_parties_contracts); the worklist (talonic_parties_issues).",
5248
5259
  "",
5249
- "ARGS: `contract_id`, `on` (YYYY-MM-DD; default today: the roles in force on that day).",
5250
- "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 }."
5260
+ "ARGS: `product_id`, `row_id`, `on` (YYYY-MM-DD; default today: the roles in force on that day).",
5261
+ "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 } }."
5251
5262
  ].join("\n");
5252
5263
  var contractInputSchema2 = {
5253
- contract_id: contractIdArg2,
5264
+ product_id: productIdArg2,
5265
+ row_id: rowIdArg2,
5254
5266
  on: dateArg.optional().describe("The day to read the parties for (YYYY-MM-DD; default today).")
5255
5267
  };
5256
5268
  function handleContract2(getToken, baseUrl, args) {
5257
5269
  return runTool(
5258
- () => apiJson(getToken, baseUrl, "GET", `/v1/parties/contracts/${args.contract_id}`, {
5270
+ () => apiJson(getToken, baseUrl, "GET", rowPath(args.product_id, args.row_id), {
5259
5271
  params: { on: args.on }
5260
5272
  })
5261
5273
  );
5262
5274
  }
5275
+ var SECTION_PATHS = {
5276
+ contracts: (id) => `/v1/parties/${id}/contracts`,
5277
+ documents: (id) => `/v1/parties/${id}/documents`,
5278
+ history: (id) => `/v1/parties/${id}/history`
5279
+ };
5280
+ var SECTION_ARGS = "ARGS: `party_id`, `product_id` (only contracts of that data product), `limit` (1-500, default 50), `offset`.";
5281
+ var CONTRACTS_DESCRIPTION = [
5282
+ "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.",
5283
+ "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.",
5284
+ "NOT FOR: one contract's full parties (talonic_parties_contract); the party's details (talonic_parties_party).",
5285
+ "",
5286
+ SECTION_ARGS,
5287
+ "RETURNS: { total, offset, limit, data[] { row { data_product_id, product_name, row_id, label, document_ids[], read }, roles[], others[] { ...role, party }, view, issues[] } }."
5288
+ ].join("\n");
5289
+ var DOCUMENTS_DESCRIPTION = [
5290
+ "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.",
5291
+ "USE WHEN: showing where a party comes from, or checking the evidence before confirming its roles.",
5292
+ "NOT FOR: the document itself (talonic_get_document); the party's contracts (talonic_parties_contracts).",
5293
+ "",
5294
+ SECTION_ARGS,
5295
+ "RETURNS: { total, offset, limit, data[] { document_id, filename, row_label, quotes[] } }."
5296
+ ].join("\n");
5297
+ var HISTORY_DESCRIPTION = [
5298
+ "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.",
5299
+ "USE WHEN: the user asks what changed on a party, who decided something, or since when it holds a role.",
5300
+ "NOT FOR: its current details (talonic_parties_party).",
5301
+ "",
5302
+ SECTION_ARGS,
5303
+ "RETURNS: { total, offset, limit, data[] } (each entry a dated event with what changed and who did it)."
5304
+ ].join("\n");
5305
+ var sectionInputSchema = {
5306
+ party_id: partyIdArg,
5307
+ product_id: zUuid().optional().describe("Only contracts of this data product."),
5308
+ limit: limitArg(500, 50),
5309
+ offset: offsetArg
5310
+ };
5311
+ function handlePartySection(getToken, baseUrl, section, args) {
5312
+ return runTool(
5313
+ () => apiJson(getToken, baseUrl, "GET", SECTION_PATHS[section](args.party_id), {
5314
+ params: { product_id: args.product_id, limit: args.limit, offset: args.offset }
5315
+ })
5316
+ );
5317
+ }
5263
5318
  var SEARCH_DESCRIPTION = [
5264
- "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.",
5319
+ "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).",
5265
5320
  "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.",
5266
- "NOT FOR: one party with its roles (talonic_parties_party); a contract's parties (talonic_parties_contract).",
5321
+ "NOT FOR: the parties needing attention (talonic_parties_issues); one party in full (talonic_parties_party).",
5267
5322
  "",
5268
- "ARGS: `query`, `kind` person|company|owners_association|unknown, `limit` (1-1000, default 200).",
5269
- "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 } }."
5323
+ "ARGS: `query`, `kind` person|company|owners_association|unknown, `product_id`, `scope` partners (default) | all, `limit` (1-5000, default 200), `offset`.",
5324
+ "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 } }."
5270
5325
  ].join("\n");
5271
5326
  var searchInputSchema = {
5272
- query: z.string().optional().describe("Name, address, email or external reference contains."),
5327
+ query: z.string().max(300).optional().describe("Name, address or email contains."),
5273
5328
  kind: z.enum(KINDS).optional().describe("Only parties of this kind."),
5274
- limit: z.number().int().min(1).max(1e3).optional().describe("At most this many (default 200).")
5329
+ product_id: zUuid().optional().describe("Only contracts of this data product."),
5330
+ scope: z.enum(["partners", "all"]).optional().describe("partners (default): contract partners; all: every party."),
5331
+ limit: limitArg(5e3, 200),
5332
+ offset: offsetArg
5275
5333
  };
5276
5334
  function handleSearch2(getToken, baseUrl, args) {
5277
5335
  return runTool(
5278
5336
  () => apiJson(getToken, baseUrl, "GET", "/v1/parties", {
5279
- params: { q: args.query, kind: args.kind, limit: args.limit }
5337
+ params: {
5338
+ q: args.query,
5339
+ kind: args.kind,
5340
+ product_id: args.product_id,
5341
+ scope: args.scope === "all" ? "all" : void 0,
5342
+ limit: args.limit,
5343
+ offset: args.offset
5344
+ }
5280
5345
  })
5281
5346
  );
5282
5347
  }
@@ -5299,16 +5364,18 @@ var PARTY_FIELD_KEYS = [
5299
5364
  "external_refs"
5300
5365
  ];
5301
5366
  var PARTY_DESCRIPTION = [
5302
- "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).",
5303
- "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.",
5304
- "NOT FOR: its role on a contract (talonic_parties_set_role); combining duplicates (talonic_parties_merge).",
5367
+ "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).",
5368
+ "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.",
5369
+ "NOT FOR: its role on a contract (talonic_parties_set_role); combining duplicates (talonic_parties_merge); other names (talonic_parties_names).",
5305
5370
  "",
5306
- "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).",
5307
- "RETURNS: read { party, merged_into, roles[] { ...role, contract }, members[] { id, function, party }, member_of[], documents[] { document_id, filename, quotes[] } }; change or create: the party."
5371
+ "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).",
5372
+ "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."
5308
5373
  ].join("\n");
5309
5374
  var nullableText = (max) => z.string().max(max).nullable().optional();
5310
5375
  var partyInputSchema = {
5311
5376
  party_id: partyIdArg.optional().describe("The party to read or change; omit to create one."),
5377
+ overview: z.boolean().optional().describe("Read: leave the long lists out and count them instead."),
5378
+ product_id: zUuid().optional().describe("Read: only contracts of this data product."),
5312
5379
  kind: z.enum(KINDS).optional().describe("Person, company, owners' association or unknown."),
5313
5380
  display_name: z.string().min(1).max(300).optional().describe("Name as printed; required to create."),
5314
5381
  salutation: z.enum(SALUTATIONS).nullable().optional().describe("Salutation; null clears it."),
@@ -5332,7 +5399,12 @@ function handleParty(getToken, baseUrl, args) {
5332
5399
  if (args.party_id) {
5333
5400
  const path = `/v1/parties/${args.party_id}`;
5334
5401
  return runTool(
5335
- () => changing ? apiJson(getToken, baseUrl, "PATCH", path, { body: fields }) : apiJson(getToken, baseUrl, "GET", path)
5402
+ () => changing ? apiJson(getToken, baseUrl, "PATCH", path, { body: fields }) : apiJson(getToken, baseUrl, "GET", path, {
5403
+ params: {
5404
+ view: args.overview ? "overview" : void 0,
5405
+ product_id: args.product_id
5406
+ }
5407
+ })
5336
5408
  );
5337
5409
  }
5338
5410
  if (typeof args.display_name !== "string" || !args.display_name.trim()) {
@@ -5343,18 +5415,20 @@ function handleParty(getToken, baseUrl, args) {
5343
5415
  return runTool(() => apiJson(getToken, baseUrl, "POST", "/v1/parties", { body: fields }));
5344
5416
  }
5345
5417
  var SET_ROLE_DESCRIPTION = [
5346
- "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.",
5418
+ "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.",
5347
5419
  "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).",
5420
+ CONTRACT_IS_A_ROW,
5348
5421
  ROLES_EXPLAINED,
5349
5422
  COMPUTED_RULE,
5350
5423
  DECISION_RULE,
5351
- "NOT FOR: confirming many suggestions at once (talonic_parties_confirm); the party's own details (talonic_parties_party).",
5424
+ "NOT FOR: confirming several checked roles at once (talonic_parties_confirm); the party's own details (talonic_parties_party).",
5352
5425
  "",
5353
- "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).",
5354
- "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 }."
5426
+ "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).",
5427
+ "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 }."
5355
5428
  ].join("\n");
5356
5429
  var setRoleInputSchema = {
5357
- contract_id: contractIdArg2.optional().describe("Add: the contract to add the role to."),
5430
+ product_id: productIdArg2.optional().describe("Add: the contract's data product."),
5431
+ row_id: rowIdArg2.optional().describe("Add: the contract's row id in that product."),
5358
5432
  role_id: zUuid().optional().describe("Change: the role row (roles[].id from talonic_parties_contract)."),
5359
5433
  party_id: partyIdArg.optional().describe("Add: the party; change: move the row to this party."),
5360
5434
  role: z.enum(ROLES2).optional().describe("The role."),
@@ -5366,19 +5440,25 @@ var setRoleInputSchema = {
5366
5440
  note: z.string().max(1e3).nullable().optional().describe("Why; where the decision comes from.")
5367
5441
  };
5368
5442
  function handleSetRole(getToken, baseUrl, args) {
5369
- const { contract_id, role_id, ...rest } = args;
5443
+ const { product_id, row_id, role_id, ...rest } = args;
5370
5444
  const body = defined(rest);
5371
- if (!!contract_id === !!role_id) {
5445
+ const adding = product_id !== void 0 || row_id !== void 0;
5446
+ if (adding === !!role_id) {
5372
5447
  return Promise.resolve(
5373
- validationError("pass contract_id (with party_id and role) to add, or role_id to change.")
5448
+ validationError(
5449
+ "pass product_id and row_id (with party_id and role) to add, or role_id to change."
5450
+ )
5374
5451
  );
5375
5452
  }
5376
- if (contract_id) {
5453
+ if (adding) {
5454
+ if (!product_id || !row_id) {
5455
+ return Promise.resolve(validationError("adding a role needs both product_id and row_id."));
5456
+ }
5377
5457
  if (!args.party_id || !args.role) {
5378
5458
  return Promise.resolve(validationError("adding a role needs party_id and role."));
5379
5459
  }
5380
5460
  return runTool(
5381
- () => apiJson(getToken, baseUrl, "POST", `/v1/parties/contracts/${contract_id}/roles`, { body })
5461
+ () => apiJson(getToken, baseUrl, "POST", `${rowPath(product_id, row_id)}/roles`, { body })
5382
5462
  );
5383
5463
  }
5384
5464
  if (Object.keys(body).length === 0) {
@@ -5393,37 +5473,45 @@ function handleSetRole(getToken, baseUrl, args) {
5393
5473
  );
5394
5474
  }
5395
5475
  var CONFIRM_DESCRIPTION2 = [
5396
- "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.",
5397
- "USE WHEN: the user asks to accept the suggestions (all, or of some contracts / roles).",
5476
+ `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.`,
5477
+ "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).",
5478
+ "There is no confirm-by-confidence across the workspace: pick the roles to confirm from the contracts you read.",
5398
5479
  DECISION_RULE,
5399
5480
  "NOT FOR: rejecting or fixing one role (talonic_parties_set_role).",
5400
5481
  "",
5401
- "ARGS: `contract_ids[]` (omit for all), `roles[]` (e.g. ['partner']), `min_confidence` high|medium|low (default high), `limit` (1-5000, default 500), `dry_run`.",
5402
- "RETURNS: { dry_run, confirmed, rows[] { id, contract_id, party_id, role, confidence } } (rows: the first 100)."
5482
+ `ARGS: \`role_ids[]\` (1-${CONFIRM_MAX_ROLES}), \`note\` (say where the decision comes from; recorded on each role).`,
5483
+ "RETURNS: { confirmed, failed, rows[] { role_id, ok, role? (the confirmed row), error? } }."
5403
5484
  ].join("\n");
5404
5485
  var confirmInputSchema2 = {
5405
- contract_ids: z.array(zUuid()).max(1e3).optional().describe("Only these contracts."),
5406
- roles: z.array(z.enum(ROLES2)).max(ROLES2.length).optional().describe("Only these roles."),
5407
- min_confidence: z.enum(["high", "medium", "low"]).optional().describe("Lowest confidence confirmed (default high)."),
5408
- limit: z.number().int().min(1).max(5e3).optional().describe("At most this many (default 500)."),
5409
- dry_run: z.boolean().optional().describe("Count only; nothing is confirmed.")
5486
+ role_ids: z.array(zUuid()).min(1).max(CONFIRM_MAX_ROLES).describe("The role rows to confirm (roles[].id from talonic_parties_contract)."),
5487
+ note: z.string().max(1e3).optional().describe("Why; where the decision comes from.")
5410
5488
  };
5411
5489
  function handleConfirm2(getToken, baseUrl, args) {
5412
- return runTool(
5413
- () => apiJson(getToken, baseUrl, "POST", "/v1/parties/roles/confirm", {
5414
- body: {
5415
- ...args.contract_ids ? { contract_ids: args.contract_ids } : {},
5416
- ...args.roles ? { roles: args.roles } : {},
5417
- min_confidence: args.min_confidence ?? "high",
5418
- ...args.limit ? { limit: args.limit } : {},
5419
- dry_run: args.dry_run ?? false
5490
+ const ids = [...new Set(args.role_ids ?? [])];
5491
+ if (!ids.length) return Promise.resolve(validationError("pass at least one role id."));
5492
+ return runTool(async () => {
5493
+ const rows = [];
5494
+ for (const id of ids) {
5495
+ try {
5496
+ const role = await apiJson(getToken, baseUrl, "PATCH", `/v1/parties/roles/${id}`, {
5497
+ body: { state: "confirmed", ...args.note !== void 0 ? { note: args.note } : {} }
5498
+ });
5499
+ rows.push({ role_id: id, ok: true, role });
5500
+ } catch (err) {
5501
+ rows.push({
5502
+ role_id: id,
5503
+ ok: false,
5504
+ error: err instanceof Error ? err.message : String(err)
5505
+ });
5420
5506
  }
5421
- })
5422
- );
5507
+ }
5508
+ const confirmed = rows.filter((r) => r.ok).length;
5509
+ return { confirmed, failed: rows.length - confirmed, rows };
5510
+ });
5423
5511
  }
5424
5512
  var MERGE_DESCRIPTION2 = [
5425
5513
  "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.",
5426
- "USE WHEN: talonic_parties_issues lists duplicates (same name and postcode) and the user confirms they are the same party.",
5514
+ "USE WHEN: talonic_parties_party lists duplicates[] and the user confirms they are the same party.",
5427
5515
  "NOT FOR: two different parties with similar names; moving one role to another party (talonic_parties_set_role with role_id and party_id).",
5428
5516
  "",
5429
5517
  "ARGS: `party_id` (the one that goes), `into` (the survivor), `dry_run`.",
@@ -5444,76 +5532,215 @@ function handleMerge2(getToken, baseUrl, args) {
5444
5532
  })
5445
5533
  );
5446
5534
  }
5535
+ var READ_STATES_BUSY = /* @__PURE__ */ new Set(["pending", "running"]);
5447
5536
  var READ_DESCRIPTION = [
5448
- "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).",
5449
- "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.",
5537
+ "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).",
5538
+ "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.",
5539
+ CONTRACT_IS_A_ROW,
5450
5540
  DECISION_RULE,
5451
- "NOT FOR: one contract's parties (talonic_parties_contract).",
5541
+ "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).",
5452
5542
  "",
5453
- "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).",
5454
- "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 }."
5543
+ "ARGS: `product_id` + `row_id` (the contract), `status` (only report; nothing is queued), `wait_seconds` (0-600, default 0).",
5544
+ "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)."
5455
5545
  ].join("\n");
5456
5546
  var readInputSchema = {
5457
- status: z.boolean().optional().describe("Only report the read queue; nothing is queued."),
5458
- contract_ids: z.array(zUuid()).max(5e3).optional().describe("Only these contracts (read again when already read)."),
5459
- only_unread: z.boolean().optional().describe("All contracts: only those not read yet (default true)."),
5460
- force: z.boolean().optional().describe("Read again although already read."),
5461
- limit: z.number().int().min(1).max(5e3).optional().describe("Queue at most this many."),
5462
- dry_run: z.boolean().optional().describe("Count and list what would be read; nothing is queued."),
5463
- 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}).`)
5464
- };
5465
- var busy = (s) => (s.counts?.["pending"] ?? 0) + (s.counts?.["running"] ?? 0) > 0;
5547
+ product_id: productIdArg2.optional().describe("The contract's data product."),
5548
+ row_id: rowIdArg2.optional().describe("The contract's row id in that product."),
5549
+ status: z.boolean().optional().describe("Only report; nothing is queued."),
5550
+ 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}).`)
5551
+ };
5552
+ var queueBusy = (s) => (s.reads?.["pending"] ?? 0) + (s.reads?.["running"] ?? 0) > 0;
5466
5553
  function handleRead(getToken, baseUrl, args, deps = {}) {
5467
5554
  const waitS = waitSeconds2(args.wait_seconds, READ_MAX_WAIT_S);
5468
- const readStatus = () => apiJson(getToken, baseUrl, "GET", "/v1/parties/read/status");
5555
+ const hasRow = !!args.product_id && !!args.row_id;
5556
+ if (!!args.product_id !== !!args.row_id) {
5557
+ return Promise.resolve(validationError("a contract needs both product_id and row_id."));
5558
+ }
5559
+ if (!hasRow && !args.status) {
5560
+ return Promise.resolve(
5561
+ validationError(
5562
+ "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."
5563
+ )
5564
+ );
5565
+ }
5566
+ if (!hasRow) {
5567
+ const queue = () => apiJson(getToken, baseUrl, "GET", "/v1/parties/status");
5568
+ return runTool(async () => {
5569
+ if (waitS === 0) {
5570
+ const s = await queue();
5571
+ return { reads: s.reads, rows: s.rows, rows_read: s.rows_read };
5572
+ }
5573
+ const w = await waitUntil(queue, (s) => !queueBusy(s), waitS, deps);
5574
+ return {
5575
+ reads: w.last.reads,
5576
+ rows: w.last.rows,
5577
+ rows_read: w.last.rows_read,
5578
+ waited_ms: w.waited_ms,
5579
+ still_running: w.still_running,
5580
+ ...w.poll_error ? { poll_error: w.poll_error } : {}
5581
+ };
5582
+ });
5583
+ }
5584
+ const path = rowPath(args.product_id, args.row_id);
5585
+ const rowRead = async () => (await apiJson(getToken, baseUrl, "GET", path)).read ?? null;
5469
5586
  return runTool(async () => {
5470
- let started = null;
5587
+ let queued = null;
5471
5588
  if (!args.status) {
5472
- started = await apiJson(
5473
- getToken,
5474
- baseUrl,
5475
- "POST",
5476
- "/v1/parties/read",
5477
- {
5478
- body: {
5479
- ...args.contract_ids ? { contract_ids: args.contract_ids } : {},
5480
- ...args.only_unread !== void 0 ? { only_unread: args.only_unread } : {},
5481
- ...args.force !== void 0 ? { force: args.force } : {},
5482
- ...args.limit ? { limit: args.limit } : {},
5483
- dry_run: args.dry_run ?? false
5484
- }
5485
- }
5486
- );
5487
- if (waitS === 0 || args.dry_run) return started;
5488
- }
5489
- const first = await readStatus();
5490
- if (waitS === 0) return first;
5491
- const sleep2 = deps.sleep ?? sleep;
5492
- const now = deps.now ?? Date.now;
5493
- const start = now();
5494
- const deadline = start + waitS * 1e3;
5495
- let status3 = first;
5496
- let pollError;
5497
- while (busy(status3) && now() < deadline) {
5498
- await sleep2(Math.min(PARTIES_POLL_INTERVAL_MS, deadline - now()));
5499
- try {
5500
- status3 = await readStatus();
5501
- } catch (err) {
5502
- pollError = err instanceof Error ? err.message : String(err);
5503
- break;
5504
- }
5589
+ queued = await apiJson(getToken, baseUrl, "POST", `${path}/read`);
5590
+ if (waitS === 0) return queued;
5591
+ } else if (waitS === 0) {
5592
+ return await rowRead() ?? { status: null };
5505
5593
  }
5506
- const stillRunning = pollError !== void 0 || busy(status3);
5594
+ const w = await waitUntil(rowRead, (r) => !READ_STATES_BUSY.has(r?.status ?? ""), waitS, deps);
5595
+ const failed = w.last?.status === "failed";
5596
+ return {
5597
+ ...queued ?? {},
5598
+ read: w.last,
5599
+ waited_ms: w.waited_ms,
5600
+ still_running: w.still_running,
5601
+ ...w.poll_error ? { poll_error: w.poll_error } : {},
5602
+ 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."
5603
+ };
5604
+ });
5605
+ }
5606
+ var SYNC_DESCRIPTION = [
5607
+ "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).",
5608
+ "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.",
5609
+ "NOT FOR: reading one contract's documents (talonic_parties_read).",
5610
+ "",
5611
+ "ARGS: `row_ids[]` (only these contract rows, up to 5000; omit for a full pass), `wait_seconds` (0-600, default 0; full pass only).",
5612
+ "RETURNS: { started: true }; after a wait also { syncing, synced_at, rows, waited_ms, still_running }."
5613
+ ].join("\n");
5614
+ var syncInputSchema = {
5615
+ 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."),
5616
+ 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}).`)
5617
+ };
5618
+ function handleSync(getToken, baseUrl, args, deps = {}) {
5619
+ const waitS = waitSeconds2(args.wait_seconds, READ_MAX_WAIT_S);
5620
+ return runTool(async () => {
5621
+ const started = await apiJson(
5622
+ getToken,
5623
+ baseUrl,
5624
+ "POST",
5625
+ "/v1/parties/sync",
5626
+ { body: args.row_ids ? { row_ids: args.row_ids } : {} }
5627
+ );
5628
+ if (waitS === 0 || args.row_ids) return started;
5629
+ const w = await waitUntil(
5630
+ () => apiJson(getToken, baseUrl, "GET", "/v1/parties/status"),
5631
+ (s) => !s.syncing,
5632
+ waitS,
5633
+ deps
5634
+ );
5507
5635
  return {
5508
- ...started ?? {},
5509
- status: status3,
5510
- waited_ms: now() - start,
5511
- still_running: stillRunning,
5512
- ...pollError ? { poll_error: pollError } : {},
5513
- next: stillRunning ? "Still reading: call talonic_parties_read with status: true (and wait_seconds) later." : "Read done: open the worklist with talonic_parties_issues."
5636
+ ...started,
5637
+ syncing: w.last.syncing ?? false,
5638
+ synced_at: w.last.synced_at ?? null,
5639
+ rows: w.last.rows,
5640
+ waited_ms: w.waited_ms,
5641
+ still_running: w.still_running,
5642
+ ...w.poll_error ? { poll_error: w.poll_error } : {}
5514
5643
  };
5515
5644
  });
5516
5645
  }
5646
+ var NAMES_DESCRIPTION = [
5647
+ "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.",
5648
+ "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.",
5649
+ "NOT FOR: the party's printed name (talonic_parties_party display_name); two parties that are one (talonic_parties_merge).",
5650
+ "",
5651
+ "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).",
5652
+ "RETURNS: add / decide: the name { id, party_id, name, kind, valid_to, state, source, decided_by, decided_at }; remove: { deleted: true }."
5653
+ ].join("\n");
5654
+ var namesInputSchema = {
5655
+ party_id: partyIdArg.optional().describe("Add: the party."),
5656
+ name: z.string().min(1).max(300).optional().describe("Add: the other name."),
5657
+ kind: z.enum(["alias", "former"]).optional().describe("Add: alias (also called) or former (renamed)."),
5658
+ valid_to: dateArg.nullable().optional().describe("Add, former name: the day it ended."),
5659
+ note: z.string().max(500).nullable().optional().describe("Add: where this comes from."),
5660
+ name_id: zUuid().optional().describe("Decide or remove: the name (names[].id)."),
5661
+ state: z.enum(["confirmed", "rejected"]).optional().describe("Decide: confirmed or rejected."),
5662
+ remove: z.boolean().optional().describe("Remove: true deletes a name a person added.")
5663
+ };
5664
+ function handleNames(getToken, baseUrl, args) {
5665
+ if (args.name_id) {
5666
+ if (args.party_id || args.name !== void 0 || args.kind) {
5667
+ return Promise.resolve(
5668
+ validationError(
5669
+ "name_id goes with state (decide) or remove: true (remove), not with add fields."
5670
+ )
5671
+ );
5672
+ }
5673
+ if (!!args.remove === !!args.state) {
5674
+ return Promise.resolve(validationError("with name_id pass either state or remove: true."));
5675
+ }
5676
+ const path = `/v1/parties/names/${args.name_id}`;
5677
+ return runTool(
5678
+ () => args.remove ? apiJson(getToken, baseUrl, "DELETE", path) : apiJson(getToken, baseUrl, "PATCH", path, { body: { state: args.state } })
5679
+ );
5680
+ }
5681
+ if (!args.party_id || !args.name || !args.kind) {
5682
+ return Promise.resolve(
5683
+ validationError(
5684
+ "pass party_id, name and kind to add a name, or name_id to decide or remove one."
5685
+ )
5686
+ );
5687
+ }
5688
+ if (args.valid_to && args.kind !== "former") {
5689
+ return Promise.resolve(validationError("valid_to belongs to a former name only."));
5690
+ }
5691
+ return runTool(
5692
+ () => apiJson(getToken, baseUrl, "POST", `/v1/parties/${args.party_id}/names`, {
5693
+ body: defined({
5694
+ name: args.name,
5695
+ kind: args.kind,
5696
+ valid_to: args.valid_to,
5697
+ note: args.note
5698
+ })
5699
+ })
5700
+ );
5701
+ }
5702
+ var DIRECTORY_LINK_DESCRIPTION = [
5703
+ "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.",
5704
+ "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.",
5705
+ "NOT FOR: which address letters use when the CRM's differs (talonic_parties_address_choice).",
5706
+ "",
5707
+ "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).",
5708
+ "RETURNS: the party's directory link { state, kind, external_id, candidates[], odd_address, address_choice, decided_by }."
5709
+ ].join("\n");
5710
+ var directoryLinkInputSchema = {
5711
+ party_id: partyIdArg,
5712
+ external_id: z.string().min(1).max(100).nullable().describe("The CRM entry's id (directory.candidates[].external_id); null unlinks."),
5713
+ kind: z.enum(["company", "contact"]).optional().describe("The entry's kind (default company).")
5714
+ };
5715
+ function handleDirectoryLink(getToken, baseUrl, args) {
5716
+ if (args.external_id === void 0) {
5717
+ return Promise.resolve(validationError("pass external_id, or null to unlink."));
5718
+ }
5719
+ return runTool(
5720
+ () => apiJson(getToken, baseUrl, "POST", `/v1/parties/${args.party_id}/directory-link`, {
5721
+ body: defined({ external_id: args.external_id, kind: args.kind })
5722
+ })
5723
+ );
5724
+ }
5725
+ var ADDRESS_CHOICE_DESCRIPTION = [
5726
+ "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.",
5727
+ "USE WHEN: talonic_parties_party shows directory.crm_address and directory.document_address and the user says which is right.",
5728
+ "NOT FOR: typing a new address (talonic_parties_party with street, postcode, town).",
5729
+ "",
5730
+ "ARGS: `party_id`, `choice` crm|document.",
5731
+ "RETURNS: the party's directory link { state, kind, external_id, odd_address, address_choice, decided_by }."
5732
+ ].join("\n");
5733
+ var addressChoiceInputSchema = {
5734
+ party_id: partyIdArg,
5735
+ choice: z.enum(["crm", "document"]).describe("crm: the CRM's address; document: the contract's.")
5736
+ };
5737
+ function handleAddressChoice(getToken, baseUrl, args) {
5738
+ return runTool(
5739
+ () => apiJson(getToken, baseUrl, "POST", `/v1/parties/${args.party_id}/address-choice`, {
5740
+ body: { choice: args.choice }
5741
+ })
5742
+ );
5743
+ }
5517
5744
  var MEMBERS_DESCRIPTION = [
5518
5745
  "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.",
5519
5746
  "USE WHEN: the user names the person to write to at a company (e.g. the WEG's Verwalter contact), or a contact left.",
@@ -5552,8 +5779,8 @@ function handleMembers(getToken, baseUrl, args) {
5552
5779
  );
5553
5780
  }
5554
5781
  var GROUP_COMPANIES_DESCRIPTION = [
5555
- "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.",
5556
- "USE WHEN: a read takes one of our own companies for the partner, or setting up the workspace.",
5782
+ "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.",
5783
+ "USE WHEN: one of our own companies shows up as a contract partner, or setting up the workspace.",
5557
5784
  "NOT FOR: contract partners (talonic_parties_party).",
5558
5785
  "",
5559
5786
  "ARGS: none to read; `companies[] { name, parent? (another name in the list), relation? subsidiary|sister|parent }` to replace.",
@@ -5576,7 +5803,7 @@ function handleGroupCompanies(getToken, baseUrl, args) {
5576
5803
  );
5577
5804
  }
5578
5805
  function registerPartiesTools(server, getToken, baseUrl) {
5579
- const tools = [
5806
+ const tools2 = [
5580
5807
  [
5581
5808
  "talonic_parties_status",
5582
5809
  "Contract parties status",
@@ -5587,20 +5814,12 @@ function registerPartiesTools(server, getToken, baseUrl) {
5587
5814
  ],
5588
5815
  [
5589
5816
  "talonic_parties_issues",
5590
- "Contract parties worklist",
5817
+ "Parties needing attention",
5591
5818
  ISSUES_DESCRIPTION4,
5592
5819
  issuesInputSchema2,
5593
5820
  readOnly4,
5594
5821
  (a) => handleIssues4(getToken, baseUrl, a)
5595
5822
  ],
5596
- [
5597
- "talonic_parties_contracts",
5598
- "Contracts with their parties",
5599
- CONTRACTS_DESCRIPTION,
5600
- contractsInputSchema,
5601
- readOnly4,
5602
- (a) => handleContracts(getToken, baseUrl, a)
5603
- ],
5604
5823
  [
5605
5824
  "talonic_parties_contract",
5606
5825
  "One contract's parties",
@@ -5609,6 +5828,30 @@ function registerPartiesTools(server, getToken, baseUrl) {
5609
5828
  readOnly4,
5610
5829
  (a) => handleContract2(getToken, baseUrl, a)
5611
5830
  ],
5831
+ [
5832
+ "talonic_parties_contracts",
5833
+ "A party's contracts",
5834
+ CONTRACTS_DESCRIPTION,
5835
+ sectionInputSchema,
5836
+ readOnly4,
5837
+ (a) => handlePartySection(getToken, baseUrl, "contracts", a)
5838
+ ],
5839
+ [
5840
+ "talonic_parties_documents",
5841
+ "A party's documents",
5842
+ DOCUMENTS_DESCRIPTION,
5843
+ sectionInputSchema,
5844
+ readOnly4,
5845
+ (a) => handlePartySection(getToken, baseUrl, "documents", a)
5846
+ ],
5847
+ [
5848
+ "talonic_parties_history",
5849
+ "A party's history",
5850
+ HISTORY_DESCRIPTION,
5851
+ sectionInputSchema,
5852
+ readOnly4,
5853
+ (a) => handlePartySection(getToken, baseUrl, "history", a)
5854
+ ],
5612
5855
  [
5613
5856
  "talonic_parties_search",
5614
5857
  "Search parties",
@@ -5626,6 +5869,32 @@ function registerPartiesTools(server, getToken, baseUrl) {
5626
5869
  write4(false, true),
5627
5870
  (a) => handleParty(getToken, baseUrl, a)
5628
5871
  ],
5872
+ [
5873
+ "talonic_parties_names",
5874
+ "A party's other names",
5875
+ NAMES_DESCRIPTION,
5876
+ namesInputSchema,
5877
+ // Removing a name deletes it; rejecting overrides a suggestion: destructive.
5878
+ write4(true, true),
5879
+ (a) => handleNames(getToken, baseUrl, a)
5880
+ ],
5881
+ [
5882
+ "talonic_parties_directory_link",
5883
+ "Link a party to the CRM",
5884
+ DIRECTORY_LINK_DESCRIPTION,
5885
+ directoryLinkInputSchema,
5886
+ // Replaces or removes the party's link: destructive.
5887
+ write4(true, true),
5888
+ (a) => handleDirectoryLink(getToken, baseUrl, a)
5889
+ ],
5890
+ [
5891
+ "talonic_parties_address_choice",
5892
+ "Choose a party's letter address",
5893
+ ADDRESS_CHOICE_DESCRIPTION,
5894
+ addressChoiceInputSchema,
5895
+ write4(true),
5896
+ (a) => handleAddressChoice(getToken, baseUrl, a)
5897
+ ],
5629
5898
  [
5630
5899
  "talonic_parties_set_role",
5631
5900
  "Add or change a contract role",
@@ -5637,7 +5906,7 @@ function registerPartiesTools(server, getToken, baseUrl) {
5637
5906
  ],
5638
5907
  [
5639
5908
  "talonic_parties_confirm",
5640
- "Confirm suggested roles",
5909
+ "Confirm checked roles",
5641
5910
  CONFIRM_DESCRIPTION2,
5642
5911
  confirmInputSchema2,
5643
5912
  write4(true),
@@ -5653,12 +5922,20 @@ function registerPartiesTools(server, getToken, baseUrl) {
5653
5922
  ],
5654
5923
  [
5655
5924
  "talonic_parties_read",
5656
- "Read parties from contracts",
5925
+ "Read one contract's parties",
5657
5926
  READ_DESCRIPTION,
5658
5927
  readInputSchema,
5659
5928
  write4(true),
5660
5929
  (a) => handleRead(getToken, baseUrl, a)
5661
5930
  ],
5931
+ [
5932
+ "talonic_parties_sync",
5933
+ "Refresh parties from the data",
5934
+ SYNC_DESCRIPTION,
5935
+ syncInputSchema,
5936
+ write4(true),
5937
+ (a) => handleSync(getToken, baseUrl, a)
5938
+ ],
5662
5939
  [
5663
5940
  "talonic_parties_members",
5664
5941
  "Company contacts",
@@ -5678,7 +5955,7 @@ function registerPartiesTools(server, getToken, baseUrl) {
5678
5955
  (a) => handleGroupCompanies(getToken, baseUrl, a)
5679
5956
  ]
5680
5957
  ];
5681
- for (const [name, title, description, inputSchema11, annotations, handler] of tools) {
5958
+ for (const [name, title, description, inputSchema11, annotations, handler] of tools2) {
5682
5959
  server.registerTool(
5683
5960
  name,
5684
5961
  { title, description, inputSchema: inputSchema11, annotations: { title, ...annotations } },
@@ -5705,7 +5982,7 @@ var COMPANY_DESCRIPTION = "One portfolio company's KPI table: rows are KPIs (cAR
5705
5982
  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'.";
5706
5983
  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.";
5707
5984
  function registerPortfolioTools(server, getToken, baseUrl) {
5708
- const tools = [
5985
+ const tools2 = [
5709
5986
  [
5710
5987
  "talonic_portfolio_companies",
5711
5988
  "Portfolio companies",
@@ -5748,7 +6025,7 @@ function registerPortfolioTools(server, getToken, baseUrl) {
5748
6025
  () => runTool(() => apiJson(getToken, baseUrl, "POST", "/v1/portfolio/refresh"))
5749
6026
  ]
5750
6027
  ];
5751
- for (const [name, title, description, inputSchema11, annotations, handler] of tools) {
6028
+ for (const [name, title, description, inputSchema11, annotations, handler] of tools2) {
5752
6029
  server.registerTool(
5753
6030
  name,
5754
6031
  { title, description, inputSchema: inputSchema11, annotations: { title, ...annotations } },
@@ -5783,7 +6060,7 @@ var RUNS_DESCRIPTION2 = "Runs across all processes, newest first: state (running
5783
6060
  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.";
5784
6061
  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.";
5785
6062
  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.";
5786
- 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`.";
6063
+ 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.";
5787
6064
  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.";
5788
6065
  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.";
5789
6066
  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.";
@@ -5798,7 +6075,7 @@ var SETUP_DESCRIPTION = "What processes of this workspace can use: who a step ca
5798
6075
  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.";
5799
6076
  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.";
5800
6077
  function registerProcessesTools(server, getToken, baseUrl) {
5801
- const tools = [
6078
+ const tools2 = [
5802
6079
  [
5803
6080
  "talonic_process_list",
5804
6081
  "Processes",
@@ -6142,7 +6419,7 @@ function registerProcessesTools(server, getToken, baseUrl) {
6142
6419
  )
6143
6420
  ]
6144
6421
  ];
6145
- for (const [name, title, description, inputSchema11, annotations, handler] of tools) {
6422
+ for (const [name, title, description, inputSchema11, annotations, handler] of tools2) {
6146
6423
  server.registerTool(
6147
6424
  name,
6148
6425
  { title, description, inputSchema: inputSchema11, annotations: { title, ...annotations } },
@@ -6306,7 +6583,7 @@ function handleCrosswalk(getToken, baseUrl, args) {
6306
6583
  return runTool(() => apiJson(getToken, baseUrl, "GET", domainPath(args.domain, "/crosswalk")));
6307
6584
  }
6308
6585
  function registerMasterRecordsTools(server, getToken, baseUrl) {
6309
- const tools = [
6586
+ const tools2 = [
6310
6587
  [
6311
6588
  "talonic_master_records_config",
6312
6589
  "Read the Master Records configuration",
@@ -6372,7 +6649,7 @@ function registerMasterRecordsTools(server, getToken, baseUrl) {
6372
6649
  (a) => handleCrosswalk(getToken, baseUrl, a)
6373
6650
  ]
6374
6651
  ];
6375
- for (const [name, title, description, inputSchema11, annotations, handler] of tools) {
6652
+ for (const [name, title, description, inputSchema11, annotations, handler] of tools2) {
6376
6653
  server.registerTool(
6377
6654
  name,
6378
6655
  { title, description, inputSchema: inputSchema11, annotations: { title, ...annotations } },
@@ -6626,7 +6903,7 @@ function handleQuestions(getToken, baseUrl, args) {
6626
6903
  );
6627
6904
  }
6628
6905
  function registerSubmissionsTools(server, getToken, baseUrl) {
6629
- const tools = [
6906
+ const tools2 = [
6630
6907
  [
6631
6908
  "talonic_submissions_specs",
6632
6909
  "Submission target structures",
@@ -6716,7 +6993,7 @@ function registerSubmissionsTools(server, getToken, baseUrl) {
6716
6993
  (a) => handleExport(getToken, baseUrl, a)
6717
6994
  ]
6718
6995
  ];
6719
- for (const [name, title, description, inputSchema11, annotations, handler] of tools) {
6996
+ for (const [name, title, description, inputSchema11, annotations, handler] of tools2) {
6720
6997
  server.registerTool(
6721
6998
  name,
6722
6999
  { title, description, inputSchema: inputSchema11, annotations: { title, ...annotations } },
@@ -6735,7 +7012,7 @@ var readOnly9 = {
6735
7012
  idempotentHint: true,
6736
7013
  openWorldHint: false
6737
7014
  };
6738
- var DOCUMENTS_DESCRIPTION = [
7015
+ var DOCUMENTS_DESCRIPTION2 = [
6739
7016
  "Find contracts and invoices in the workspace to build a price baseline from.",
6740
7017
  "USE WHEN: picking the contract for talonic_price_baseline_extract or the invoice for talonic_price_baseline_compare.",
6741
7018
  "NOT FOR: general document search across all content (talonic_search).",
@@ -7256,7 +7533,7 @@ function handleAssume(getToken, baseUrl, args) {
7256
7533
  };
7257
7534
  return args.action === "create" ? runTool(() => apiJson(getToken, baseUrl, "POST", "/v1/price-baseline/assumptions", { body })) : runTool(() => apiJson(getToken, baseUrl, "PUT", path(args.assumption_id), { body }));
7258
7535
  }
7259
- var SYNC_DESCRIPTION = [
7536
+ var SYNC_DESCRIPTION2 = [
7260
7537
  "Sync external price data now (BEHG, Bundesbank, Destatis, EEX via Energy-Charts, DWD degree days), or change how often a series syncs.",
7261
7538
  "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.",
7262
7539
  "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).",
@@ -7264,13 +7541,13 @@ var SYNC_DESCRIPTION = [
7264
7541
  "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).",
7265
7542
  "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."
7266
7543
  ].join("\n");
7267
- var syncInputSchema = {
7544
+ var syncInputSchema2 = {
7268
7545
  keys: z.array(z.string().min(1)).max(50).optional().describe("Series keys to fetch now."),
7269
7546
  key: z.string().min(1).max(120).optional().describe("Series whose schedule to change."),
7270
7547
  sync_hours: z.number().int().min(1).max(2160).optional().describe("Sync interval in hours."),
7271
7548
  active: z.boolean().optional().describe("false pauses syncing.")
7272
7549
  };
7273
- function handleSync(getToken, baseUrl, args) {
7550
+ function handleSync2(getToken, baseUrl, args) {
7274
7551
  const schedule = args.key !== void 0 || args.sync_hours !== void 0 || args.active !== void 0;
7275
7552
  if (schedule) {
7276
7553
  if (args.keys?.length) {
@@ -7336,7 +7613,7 @@ function handleImport2(getToken, baseUrl, args) {
7336
7613
  );
7337
7614
  }
7338
7615
  function registerPriceBaselineTools(server, getToken, baseUrl) {
7339
- const write9 = (idempotent) => ({
7616
+ const write10 = (idempotent) => ({
7340
7617
  readOnlyHint: false,
7341
7618
  destructiveHint: false,
7342
7619
  idempotentHint: idempotent,
@@ -7346,7 +7623,7 @@ function registerPriceBaselineTools(server, getToken, baseUrl) {
7346
7623
  "talonic_price_baseline_documents",
7347
7624
  {
7348
7625
  title: "Find contracts and invoices",
7349
- description: DOCUMENTS_DESCRIPTION,
7626
+ description: DOCUMENTS_DESCRIPTION2,
7350
7627
  inputSchema: documentsInputSchema,
7351
7628
  annotations: readOnly9
7352
7629
  },
@@ -7358,7 +7635,7 @@ function registerPriceBaselineTools(server, getToken, baseUrl) {
7358
7635
  title: "Build or enrich a price model from a contract",
7359
7636
  description: EXTRACT_DESCRIPTION,
7360
7637
  inputSchema: extractInputSchema,
7361
- annotations: write9(false)
7638
+ annotations: write10(false)
7362
7639
  },
7363
7640
  async (args) => handleExtract2(getToken, baseUrl, args)
7364
7641
  );
@@ -7378,7 +7655,7 @@ function registerPriceBaselineTools(server, getToken, baseUrl) {
7378
7655
  title: "Edit or confirm a price model",
7379
7656
  description: UPDATE_DESCRIPTION,
7380
7657
  inputSchema: updateInputSchema,
7381
- annotations: write9(true)
7658
+ annotations: write10(true)
7382
7659
  },
7383
7660
  async (args) => handleUpdate(getToken, baseUrl, args)
7384
7661
  );
@@ -7408,7 +7685,7 @@ function registerPriceBaselineTools(server, getToken, baseUrl) {
7408
7685
  title: "Check an invoice against the contract",
7409
7686
  description: COMPARE_DESCRIPTION,
7410
7687
  inputSchema: compareInputSchema,
7411
- annotations: write9(false)
7688
+ annotations: write10(false)
7412
7689
  },
7413
7690
  async (args) => handleCompare(getToken, baseUrl, args)
7414
7691
  );
@@ -7438,7 +7715,7 @@ function registerPriceBaselineTools(server, getToken, baseUrl) {
7438
7715
  title: "Fetch public index values",
7439
7716
  description: REFRESH_DESCRIPTION2,
7440
7717
  inputSchema: refreshInputSchema,
7441
- annotations: { ...write9(true), openWorldHint: true }
7718
+ annotations: { ...write10(true), openWorldHint: true }
7442
7719
  },
7443
7720
  async (args) => handleRefresh(getToken, baseUrl, args)
7444
7721
  );
@@ -7448,7 +7725,7 @@ function registerPriceBaselineTools(server, getToken, baseUrl) {
7448
7725
  title: "Enter sourced index values",
7449
7726
  description: MANUAL_DESCRIPTION,
7450
7727
  inputSchema: manualInputSchema,
7451
- annotations: write9(true)
7728
+ annotations: write10(true)
7452
7729
  },
7453
7730
  async (args) => handleManual(getToken, baseUrl, args)
7454
7731
  );
@@ -7478,7 +7755,7 @@ function registerPriceBaselineTools(server, getToken, baseUrl) {
7478
7755
  title: "Answer an open contract input",
7479
7756
  description: ANSWER_DESCRIPTION,
7480
7757
  inputSchema: answerInputSchema,
7481
- annotations: write9(true)
7758
+ annotations: write10(true)
7482
7759
  },
7483
7760
  async (args) => handleAnswer(getToken, baseUrl, args)
7484
7761
  );
@@ -7498,7 +7775,7 @@ function registerPriceBaselineTools(server, getToken, baseUrl) {
7498
7775
  title: "Make, replace or withdraw an assumption",
7499
7776
  description: ASSUME_DESCRIPTION,
7500
7777
  inputSchema: assumeInputSchema,
7501
- annotations: { ...write9(false), destructiveHint: true }
7778
+ annotations: { ...write10(false), destructiveHint: true }
7502
7779
  },
7503
7780
  async (args) => handleAssume(getToken, baseUrl, args)
7504
7781
  );
@@ -7506,11 +7783,11 @@ function registerPriceBaselineTools(server, getToken, baseUrl) {
7506
7783
  "talonic_price_baseline_sync_series",
7507
7784
  {
7508
7785
  title: "Sync external price data",
7509
- description: SYNC_DESCRIPTION,
7510
- inputSchema: syncInputSchema,
7511
- annotations: { ...write9(true), openWorldHint: true }
7786
+ description: SYNC_DESCRIPTION2,
7787
+ inputSchema: syncInputSchema2,
7788
+ annotations: { ...write10(true), openWorldHint: true }
7512
7789
  },
7513
- async (args) => handleSync(getToken, baseUrl, args)
7790
+ async (args) => handleSync2(getToken, baseUrl, args)
7514
7791
  );
7515
7792
  server.registerTool(
7516
7793
  "talonic_price_baseline_imports",
@@ -7528,7 +7805,7 @@ function registerPriceBaselineTools(server, getToken, baseUrl) {
7528
7805
  title: "Import contracts from data capture",
7529
7806
  description: IMPORT_DESCRIPTION2,
7530
7807
  inputSchema: importInputSchema2,
7531
- annotations: write9(true)
7808
+ annotations: write10(true)
7532
7809
  },
7533
7810
  async (args) => handleImport2(getToken, baseUrl, args)
7534
7811
  );
@@ -7578,8 +7855,8 @@ var adminPayloadAccessInput = {
7578
7855
  function apiUrl(baseUrl, path, query) {
7579
7856
  const base2 = (baseUrl ?? DEFAULT_BASE3).replace(/\/$/, "");
7580
7857
  const url = new URL(`${base2}${path}`);
7581
- for (const [key, value] of Object.entries(query ?? {})) {
7582
- if (value !== void 0 && value !== "") url.searchParams.set(key, String(value));
7858
+ for (const [key2, value] of Object.entries(query ?? {})) {
7859
+ if (value !== void 0 && value !== "") url.searchParams.set(key2, String(value));
7583
7860
  }
7584
7861
  return url.toString();
7585
7862
  }
@@ -7931,72 +8208,583 @@ function probeAgentTasksInUse(token, baseUrl) {
7931
8208
  { limit: 1 }
7932
8209
  );
7933
8210
  }
7934
- var DECIDE_SCOPE = "apps:decide";
7935
- function tokenHasDecideScope(token) {
7936
- if (token.startsWith("tlnc_")) return true;
7937
- const parts = token.split(".");
7938
- if (parts.length !== 3) return true;
7939
- try {
7940
- const payload = JSON.parse(Buffer.from(parts[1] ?? "", "base64url").toString("utf8"));
7941
- if (!Array.isArray(payload.scopes)) return true;
7942
- return payload.scopes.includes(DECIDE_SCOPE);
7943
- } catch {
7944
- return true;
7945
- }
7946
- }
7947
- var TASK_STATUSES2 = [
7948
- "available",
7949
- "claimed",
7950
- "submitted",
7951
- "released",
7952
- "failed",
7953
- "timed_out",
7954
- "cancelled"
7955
- ];
7956
- var PACKAGE_PAGE_LIMIT_MAX = 2e3;
8211
+ var APP_MODES = ["rules", "assisted", "external", "autonomous"];
8212
+ var REVIEW_KINDS = ["resolution", "approval", "data_request", "judgment"];
8213
+ var REVIEW_STATUSES = ["open", "assigned", "resolved", "expired", "cancelled"];
8214
+ var VERDICT_OUTCOMES = ["passed", "failed", "indeterminate", "not_applicable"];
7957
8215
  var appId = zUuid().describe(
7958
- "Id of an External-mode app (from talonic_list_apps, where mode is 'external')."
8216
+ "App id: the UUID `id` from talonic_list_apps or talonic_create_app (not the app_\u2026 public id)."
7959
8217
  );
7960
- var taskId2 = zUuid().describe("Decision task UUID.");
7961
- var executionEpoch2 = z.number().int().min(1).max(2147483647).describe("Execution epoch returned by the successful claim. Stale epochs are rejected with 409.");
7962
- var status2 = z.enum(TASK_STATUSES2).optional().describe("Optional task-status filter.");
7963
- var listLimit = z.number().int().min(1).max(100).optional().describe("Page size (default 50).");
7964
- var cursor2 = z.string().min(1).optional().describe("Opaque cursor from pagination.next_cursor.");
7965
- var packageCursor = z.string().min(1).optional().describe(
7966
- "Opaque package cursor: package.first_cursor from the claim, then pagination.next_cursor. Omit for the first page."
8218
+ var runId = zUuid().describe(
8219
+ "App run UUID (run_id from talonic_run_app or talonic_list_app_runs)."
7967
8220
  );
7968
- var packageLimit = z.number().int().min(1).max(PACKAGE_PAGE_LIMIT_MAX).optional().describe(
7969
- `Records per page, 1 to ${PACKAGE_PAGE_LIMIT_MAX}. Defaults to the platform page size (package.page_size from the claim).`
8221
+ var reviewId = zUuid().describe("Human Review UUID (id from talonic_list_app_reviews).");
8222
+ var limit2 = z.number().int().min(1).max(200).optional().describe("Page size (default 50, max 200).");
8223
+ var offset = z.number().int().min(0).optional().describe("Rows to skip before the page.");
8224
+ var jsonObject = () => z.record(z.string(), z.json());
8225
+ var READ_ONLY3 = {
8226
+ readOnlyHint: true,
8227
+ destructiveHint: false,
8228
+ idempotentHint: true,
8229
+ openWorldHint: false
8230
+ };
8231
+ var MUTATING2 = {
8232
+ readOnlyHint: false,
8233
+ destructiveHint: false,
8234
+ idempotentHint: false,
8235
+ openWorldHint: false
8236
+ };
8237
+ var appPath = (id, suffix = "") => `/v1/apps/${encodeURIComponent(id)}${suffix}`;
8238
+ var runPath = (id, suffix = "") => `/v1/runs/${encodeURIComponent(id)}${suffix}`;
8239
+ var reviewPath = (id, suffix = "") => `/v1/reviews/${encodeURIComponent(id)}${suffix}`;
8240
+ var get = (t, b, path, params) => runTool(() => apiJson(t, b, "GET", path, params ? { params } : {}));
8241
+ var send = (t, b, method, path, body) => runTool(() => apiJson(t, b, method, path, body === void 0 ? {} : { body }));
8242
+ function defined2(o) {
8243
+ return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== void 0));
8244
+ }
8245
+ var handleGetApp = (t, b, a) => get(t, b, appPath(a.app_id));
8246
+ var handleCreateApp = (t, b, a) => send(t, b, "POST", "/v1/apps", defined2({ ...a }));
8247
+ var handleSaveAppDraft = (t, b, a) => send(t, b, "PATCH", appPath(a.app_id), { content: a.content });
8248
+ var handleListAppVersions = (t, b, a) => get(t, b, appPath(a.app_id, "/versions"));
8249
+ var handlePublishApp = (t, b, a) => send(t, b, "POST", appPath(a.app_id, `/versions/${a.version}/publish`));
8250
+ var handleSetAppEnabled = (t, b, a, enabled) => send(t, b, "POST", appPath(a.app_id, enabled ? "/enable" : "/disable"));
8251
+ var handleRunApp = (t, b, a) => send(
8252
+ t,
8253
+ b,
8254
+ "POST",
8255
+ appPath(a.app_id, "/runs"),
8256
+ defined2({ input: a.input ?? {}, dry_run: a.dry_run, idempotency_key: a.idempotency_key })
7970
8257
  );
7971
- var outcome = z.record(z.string(), z.json()).describe(
7972
- "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."
8258
+ var handleListAppRuns = (t, b, a) => get(t, b, appPath(a.app_id, "/runs"), { limit: a.limit, offset: a.offset });
8259
+ async function handleGetAppRun(t, b, a) {
8260
+ return runTool(async () => {
8261
+ const run = await apiJson(t, b, "GET", runPath(a.run_id));
8262
+ if (!a.include_events) return run;
8263
+ const events = await apiJson(t, b, "GET", runPath(a.run_id, "/events"));
8264
+ return { run, events: events?.events ?? [] };
8265
+ });
8266
+ }
8267
+ var handleGetRunRecord = (t, b, a) => get(t, b, runPath(a.run_id, "/record"));
8268
+ var handleGetRunVerdicts = (t, b, a) => get(t, b, runPath(a.run_id, "/verdicts"), {
8269
+ rolled: a.rolled,
8270
+ auto: a.auto,
8271
+ rule: a.rule,
8272
+ status: a.status,
8273
+ limit: a.limit,
8274
+ cursor: a.cursor
8275
+ });
8276
+ var handleListAppReviews = (t, b, a) => get(t, b, "/v1/reviews", { ...a });
8277
+ var handleRaiseAppReview = (t, b, a) => {
8278
+ const { app_id, ...body } = a;
8279
+ return send(t, b, "POST", appPath(app_id, "/reviews"), defined2(body));
8280
+ };
8281
+ var handleResolveAppReview = (t, b, a) => send(
8282
+ t,
8283
+ b,
8284
+ "POST",
8285
+ reviewPath(a.review_id, "/resolve"),
8286
+ defined2({ values: a.values, feedback: a.feedback })
7973
8287
  );
7974
- var evidence = z.array(z.string().min(1).max(512)).max(1e4).describe(
7975
- "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."
8288
+ var handleInterviewReview = (t, b, a) => send(
8289
+ t,
8290
+ b,
8291
+ "POST",
8292
+ reviewPath(a.review_id, "/interview"),
8293
+ defined2({ message: a.message, transcript: a.transcript })
7976
8294
  );
7977
- var rationale = z.string().min(1).max(4e3).describe(
7978
- "Short decision rationale (a summary, never private chain-of-thought), up to 4,000 characters."
8295
+ var handleListAppPrecedents = (t, b, a) => get(t, b, appPath(a.app_id, "/precedents"), {
8296
+ similar_to: a.similar_to ? JSON.stringify(a.similar_to) : void 0
8297
+ });
8298
+ var handleGetAppLogic = (t, b, a) => get(t, b, appPath(a.app_id, "/logic"));
8299
+ var handleGetAppFields = (t, b, a) => get(t, b, appPath(a.app_id, "/logic/fields"));
8300
+ var handleInterpretRules = (t, b, a) => send(
8301
+ t,
8302
+ b,
8303
+ "POST",
8304
+ appPath(a.app_id, "/logic/compile"),
8305
+ defined2({
8306
+ card_ids: a.card_ids && a.card_ids.length > 0 ? a.card_ids : void 0,
8307
+ guidance: a.guidance || void 0,
8308
+ locale: a.locale
8309
+ })
7979
8310
  );
7980
- var confidence = z.number().min(0).max(1).optional().describe("Optional confidence from 0 to 1.");
7981
- var serviceVersion = z.string().min(1).max(64).optional().describe("Optional build identifier of the deciding service; recorded as decided_by.label.");
7982
- var failReason = z.string().min(1).max(2e3).describe(
7983
- "Why the task cannot be decided, up to 2,000 characters. Recorded on the Human Review the fail raises."
8311
+ var handleProposeEdit = (t, b, a) => send(t, b, "POST", appPath(a.app_id, "/edit-proposals"), { instruction: a.instruction });
8312
+ var handleApplyEdit = (t, b, a) => send(t, b, "POST", appPath(a.app_id, "/edit-proposals/apply"), { ops: a.ops });
8313
+ var handleGetAcceptance = (t, b, a) => get(t, b, appPath(a.app_id, "/acceptance"));
8314
+ var handleSaveAcceptance = (t, b, a) => send(
8315
+ t,
8316
+ b,
8317
+ "PUT",
8318
+ appPath(a.app_id, "/acceptance"),
8319
+ defined2({ cases: a.cases, tolerance: a.tolerance })
7984
8320
  );
7985
- var listInput2 = { app_id: appId, status: status2, limit: listLimit, cursor: cursor2 };
7986
- var idInput2 = { task_id: taskId2 };
7987
- var packageInput = { task_id: taskId2, cursor: packageCursor, limit: packageLimit };
7988
- var epochInput = { task_id: taskId2, execution_epoch: executionEpoch2 };
7989
- var submitInput2 = {
7990
- task_id: taskId2,
7991
- execution_epoch: executionEpoch2,
7992
- outcome,
7993
- evidence,
7994
- rationale,
7995
- confidence,
7996
- service_version: serviceVersion
7997
- };
7998
- var failInput = { task_id: taskId2, execution_epoch: executionEpoch2, reason: failReason };
7999
- function taskPath(taskId3, suffix = "") {
8321
+ var handleCheckAcceptance = (t, b, a) => get(t, b, appPath(a.app_id, "/acceptance/check"), { run_id: a.run_id });
8322
+ 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.";
8323
+ var D = {
8324
+ get: [
8325
+ "Read one app's manifest: mode, active version, enabled state, contract (what it reads and acts on), output contract, thresholds, triggers, fallback.",
8326
+ "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)."
8327
+ ].join("\n"),
8328
+ create: [
8329
+ "Create a new app. It starts disabled with no versions; the slug can no longer change once a version is published.",
8330
+ "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.",
8331
+ "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).",
8332
+ "RETURNS: the manifest; use its `id` (UUID) with every other app tool.",
8333
+ BUILD_FLOW
8334
+ ].join("\n"),
8335
+ saveDraft: [
8336
+ "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.",
8337
+ "USE WHEN: authoring configuration in full. For a plain-language change to an existing draft prefer talonic_propose_app_edit + talonic_apply_app_edit.",
8338
+ "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."
8339
+ ].join("\n"),
8340
+ versions: [
8341
+ "List an app's versions, newest first: version number, status (draft, published, superseded), content hash, published_at.",
8342
+ "USE WHEN: you need the draft's version number for talonic_publish_app, or to see what is live."
8343
+ ].join("\n"),
8344
+ publish: [
8345
+ "Publish the app's draft: freezes it, makes it the active version (the previous one is superseded) and locks the slug on first publish.",
8346
+ "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.",
8347
+ "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."
8348
+ ].join("\n"),
8349
+ enable: [
8350
+ "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).",
8351
+ "USE WHEN: the user asks to switch the app on. ARGS: app_id."
8352
+ ].join("\n"),
8353
+ disable: [
8354
+ "Disable an app at once (the kill switch): triggers stop and open work is no longer offered. Past runs and records are kept.",
8355
+ "USE WHEN: the user asks to stop or pause an app. ARGS: app_id."
8356
+ ].join("\n"),
8357
+ run: [
8358
+ "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.",
8359
+ "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).",
8360
+ "ARGS: app_id, optional input object, dry_run, idempotency_key (reusing a key returns the existing run instead of starting another). Consumes credits.",
8361
+ "NEXT: talonic_get_app_run for status and decision; talonic_get_run_verdicts for per-subject results."
8362
+ ].join("\n"),
8363
+ listRuns: [
8364
+ "List an app's runs, newest first, with status, decision and who decided; `total` counts every run.",
8365
+ "ARGS: app_id, optional limit (max 200) and offset."
8366
+ ].join("\n"),
8367
+ getRun: [
8368
+ "Read one run: status, decision, decided_by, thresholds applied, reviews raised, timing.",
8369
+ "USE WHEN: checking a run you started or found. include_events:true adds the run's journal (every event in order).",
8370
+ "NOT FOR: Spec/pipeline runs (talonic_get_run). ARGS: run_id, optional include_events."
8371
+ ].join("\n"),
8372
+ record: [
8373
+ "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.",
8374
+ "USE WHEN: the user needs the final, auditable outcome. A run that has not finished has no record yet (HTTP 404). ARGS: run_id."
8375
+ ].join("\n"),
8376
+ verdicts: [
8377
+ "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.",
8378
+ "USE WHEN: inspecting what a run decided per record. Single-decision runs have none (HTTP 404; use talonic_get_app_run).",
8379
+ "ARGS: run_id; optional rolled (overall outcome), auto, rule + status (always together), limit (max 200), cursor (from `next`)."
8380
+ ].join("\n"),
8381
+ listReviews: [
8382
+ "List Human Reviews: questions apps raised for a person (approvals, missing data, judgment calls, exceptions), newest first, with `total`.",
8383
+ "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.",
8384
+ "ARGS: optional app_id, status, kind, assignee_user_id, limit (max 200), offset."
8385
+ ].join("\n"),
8386
+ raiseReview: [
8387
+ "Ask a person a question on an app instead of guessing: a Human Review with a JSON Schema for the answer.",
8388
+ "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.",
8389
+ "NEXT: the answer arrives through talonic_resolve_app_review (or the web app); read it with talonic_list_app_reviews status 'resolved'."
8390
+ ].join("\n"),
8391
+ resolveReview: [
8392
+ "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).",
8393
+ "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.",
8394
+ "RETURNS: the resolved review with its values. ARGS: review_id, values, optional feedback."
8395
+ ].join("\n"),
8396
+ interview: [
8397
+ "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.",
8398
+ "ready:true only when the proposed values satisfy the review's input contract. Nothing is submitted: finish with talonic_resolve_app_review.",
8399
+ "ARGS: review_id, message, optional transcript [{ role: user | assistant, text }]."
8400
+ ].join("\n"),
8401
+ precedents: [
8402
+ "List an app's precedents: past resolved reviews it reuses for similar future runs.",
8403
+ "ARGS: app_id, optional similar_to (match keys object) to narrow to similar cases. An app with none returns an empty list."
8404
+ ].join("\n"),
8405
+ getLogic: [
8406
+ "Read an app's logic: the editable draft and the active published version, including each rule with its interpretation state and plain-language readback.",
8407
+ "USE WHEN: before editing, or to get the draft's full content for talonic_save_app_draft."
8408
+ ].join("\n"),
8409
+ getFields: [
8410
+ "List the fields the app's rules can use, per bound data source. This is everything the app can see.",
8411
+ "USE WHEN: before writing or fixing rules, so they name fields that exist."
8412
+ ].join("\n"),
8413
+ interpret: [
8414
+ "Turn the draft's pending rule sentences into checkable rules against the app's fields, and save the draft.",
8415
+ "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.",
8416
+ "RETURNS: the rules plus warnings saying why any rule stayed pending."
8417
+ ].join("\n"),
8418
+ proposeEdit: [
8419
+ "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.",
8420
+ "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."
8421
+ ].join("\n"),
8422
+ applyEdit: [
8423
+ "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.",
8424
+ "ARGS: app_id, ops (from the proposal, unchanged)."
8425
+ ].join("\n"),
8426
+ getAcceptance: [
8427
+ "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."
8428
+ ].join("\n"),
8429
+ saveAcceptance: [
8430
+ "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.",
8431
+ "ARGS: app_id, cases (per subject: subject_key + expected_outcome and/or expected_auto; for single-decision apps: expected_decision), optional tolerance (default 0)."
8432
+ ].join("\n"),
8433
+ checkAcceptance: [
8434
+ "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.",
8435
+ "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)."
8436
+ ].join("\n")
8437
+ };
8438
+ var acceptanceCase = z.object({
8439
+ subject_key: z.string().min(1).max(256).optional(),
8440
+ expected_outcome: z.enum(VERDICT_OUTCOMES).optional(),
8441
+ expected_auto: z.boolean().optional(),
8442
+ expected_decision: z.string().min(1).max(64).optional(),
8443
+ note: z.string().max(300).optional()
8444
+ }).describe(
8445
+ "One expected result: subject_key + expected_outcome (and/or expected_auto) for batch apps, or expected_decision for single-decision apps."
8446
+ );
8447
+ function registerAppsToolset(server, getToken, baseUrl) {
8448
+ const t = getToken;
8449
+ const b = baseUrl;
8450
+ const reg = (name, title, description, inputSchema11, annotations, handler) => server.registerTool(
8451
+ name,
8452
+ { title, description, inputSchema: inputSchema11, annotations: { title, ...annotations } },
8453
+ handler
8454
+ );
8455
+ reg(
8456
+ "talonic_create_app",
8457
+ "Create App",
8458
+ D.create,
8459
+ {
8460
+ slug: z.string().regex(/^[a-z0-9][a-z0-9-]{1,62}[a-z0-9]$/).describe("Lowercase letters, digits and hyphens, 3-64 chars."),
8461
+ display_name: z.string().min(1).max(200),
8462
+ mode: z.enum(APP_MODES),
8463
+ description: z.string().max(2e3).optional().describe("One sentence about the app.")
8464
+ },
8465
+ MUTATING2,
8466
+ (a) => handleCreateApp(t, b, a)
8467
+ );
8468
+ reg(
8469
+ "talonic_get_app",
8470
+ "Get App",
8471
+ D.get,
8472
+ { app_id: appId },
8473
+ READ_ONLY3,
8474
+ (a) => handleGetApp(t, b, a)
8475
+ );
8476
+ reg(
8477
+ "talonic_get_app_logic",
8478
+ "Get App Logic",
8479
+ D.getLogic,
8480
+ { app_id: appId },
8481
+ READ_ONLY3,
8482
+ (a) => handleGetAppLogic(t, b, a)
8483
+ );
8484
+ reg(
8485
+ "talonic_get_app_fields",
8486
+ "Get App Fields",
8487
+ D.getFields,
8488
+ { app_id: appId },
8489
+ READ_ONLY3,
8490
+ (a) => handleGetAppFields(t, b, a)
8491
+ );
8492
+ reg(
8493
+ "talonic_save_app_draft",
8494
+ "Save App Draft",
8495
+ D.saveDraft,
8496
+ { app_id: appId, content: jsonObject().describe("Full version content object.") },
8497
+ MUTATING2,
8498
+ (a) => handleSaveAppDraft(t, b, a)
8499
+ );
8500
+ reg(
8501
+ "talonic_interpret_app_rules",
8502
+ "Interpret App Rules",
8503
+ D.interpret,
8504
+ {
8505
+ app_id: appId,
8506
+ card_ids: z.array(z.string().min(1).max(128)).max(50).optional().describe("Rule card ids; omit for all pending."),
8507
+ guidance: z.string().max(1e3).optional().describe("Plain-language hint for stuck rules."),
8508
+ locale: z.string().max(10).optional().describe("Language of reasons and readbacks, e.g. de.")
8509
+ },
8510
+ MUTATING2,
8511
+ (a) => handleInterpretRules(t, b, a)
8512
+ );
8513
+ reg(
8514
+ "talonic_propose_app_edit",
8515
+ "Propose App Edit",
8516
+ D.proposeEdit,
8517
+ {
8518
+ app_id: appId,
8519
+ instruction: z.string().min(8).max(2e3).describe("The change, in plain language.")
8520
+ },
8521
+ { ...READ_ONLY3, idempotentHint: false },
8522
+ (a) => handleProposeEdit(t, b, a)
8523
+ );
8524
+ reg(
8525
+ "talonic_apply_app_edit",
8526
+ "Apply App Edit",
8527
+ D.applyEdit,
8528
+ {
8529
+ app_id: appId,
8530
+ ops: z.array(jsonObject()).min(1).max(20).describe("Accepted ops from the proposal.")
8531
+ },
8532
+ MUTATING2,
8533
+ (a) => handleApplyEdit(t, b, a)
8534
+ );
8535
+ reg(
8536
+ "talonic_list_app_versions",
8537
+ "List App Versions",
8538
+ D.versions,
8539
+ { app_id: appId },
8540
+ READ_ONLY3,
8541
+ (a) => handleListAppVersions(t, b, a)
8542
+ );
8543
+ reg(
8544
+ "talonic_publish_app",
8545
+ "Publish App",
8546
+ D.publish,
8547
+ { app_id: appId, version: z.number().int().min(1).describe("The draft's version number.") },
8548
+ MUTATING2,
8549
+ (a) => handlePublishApp(t, b, a)
8550
+ );
8551
+ reg(
8552
+ "talonic_enable_app",
8553
+ "Enable App",
8554
+ D.enable,
8555
+ { app_id: appId },
8556
+ MUTATING2,
8557
+ (a) => handleSetAppEnabled(t, b, a, true)
8558
+ );
8559
+ reg(
8560
+ "talonic_disable_app",
8561
+ "Disable App",
8562
+ D.disable,
8563
+ { app_id: appId },
8564
+ MUTATING2,
8565
+ (a) => handleSetAppEnabled(t, b, a, false)
8566
+ );
8567
+ reg(
8568
+ "talonic_get_app_acceptance",
8569
+ "Get App Acceptance Set",
8570
+ D.getAcceptance,
8571
+ { app_id: appId },
8572
+ READ_ONLY3,
8573
+ (a) => handleGetAcceptance(t, b, a)
8574
+ );
8575
+ reg(
8576
+ "talonic_save_app_acceptance",
8577
+ "Save App Acceptance Set",
8578
+ D.saveAcceptance,
8579
+ {
8580
+ app_id: appId,
8581
+ cases: z.array(acceptanceCase).min(1).max(2e3),
8582
+ tolerance: z.number().min(0).max(1).optional().describe("Accepted mismatch share (default 0).")
8583
+ },
8584
+ MUTATING2,
8585
+ (a) => handleSaveAcceptance(t, b, a)
8586
+ );
8587
+ reg(
8588
+ "talonic_check_app_acceptance",
8589
+ "Check App Acceptance",
8590
+ D.checkAcceptance,
8591
+ {
8592
+ app_id: appId,
8593
+ run_id: zUuid().optional().describe("Run to score; default the latest completed run.")
8594
+ },
8595
+ READ_ONLY3,
8596
+ (a) => handleCheckAcceptance(t, b, a)
8597
+ );
8598
+ reg(
8599
+ "talonic_run_app",
8600
+ "Run App",
8601
+ D.run,
8602
+ {
8603
+ app_id: appId,
8604
+ input: jsonObject().optional().describe("Run input, checked against the app's input schema."),
8605
+ dry_run: z.boolean().optional().describe("Full trace, no side effects."),
8606
+ idempotency_key: z.string().min(1).max(64).optional()
8607
+ },
8608
+ MUTATING2,
8609
+ (a) => handleRunApp(t, b, a)
8610
+ );
8611
+ reg(
8612
+ "talonic_list_app_runs",
8613
+ "List App Runs",
8614
+ D.listRuns,
8615
+ { app_id: appId, limit: limit2, offset },
8616
+ READ_ONLY3,
8617
+ (a) => handleListAppRuns(t, b, a)
8618
+ );
8619
+ reg(
8620
+ "talonic_get_app_run",
8621
+ "Get App Run",
8622
+ D.getRun,
8623
+ { run_id: runId, include_events: z.boolean().optional() },
8624
+ READ_ONLY3,
8625
+ (a) => handleGetAppRun(t, b, a)
8626
+ );
8627
+ reg(
8628
+ "talonic_get_run_record",
8629
+ "Get Run Record",
8630
+ D.record,
8631
+ { run_id: runId },
8632
+ READ_ONLY3,
8633
+ (a) => handleGetRunRecord(t, b, a)
8634
+ );
8635
+ reg(
8636
+ "talonic_get_run_verdicts",
8637
+ "Get Run Verdicts",
8638
+ D.verdicts,
8639
+ {
8640
+ run_id: runId,
8641
+ rolled: z.enum(VERDICT_OUTCOMES).optional().describe("Filter by overall outcome."),
8642
+ auto: z.boolean().optional().describe("Filter by the auto flag."),
8643
+ rule: z.string().min(1).max(128).optional().describe("Rule id; needs status."),
8644
+ status: z.enum(VERDICT_OUTCOMES).optional().describe("That rule's outcome; needs rule."),
8645
+ limit: limit2,
8646
+ cursor: z.string().min(1).max(512).optional().describe("`next` from the previous page.")
8647
+ },
8648
+ READ_ONLY3,
8649
+ (a) => handleGetRunVerdicts(t, b, a)
8650
+ );
8651
+ reg(
8652
+ "talonic_list_app_reviews",
8653
+ "List Human Reviews",
8654
+ D.listReviews,
8655
+ {
8656
+ app_id: appId.optional(),
8657
+ status: z.enum(REVIEW_STATUSES).optional(),
8658
+ kind: z.enum(REVIEW_KINDS).optional(),
8659
+ assignee_user_id: zUuid().optional().describe("Only reviews assigned to this user."),
8660
+ limit: limit2,
8661
+ offset
8662
+ },
8663
+ READ_ONLY3,
8664
+ (a) => handleListAppReviews(t, b, a)
8665
+ );
8666
+ reg(
8667
+ "talonic_raise_app_review",
8668
+ "Raise Human Review",
8669
+ D.raiseReview,
8670
+ {
8671
+ app_id: appId,
8672
+ run_id: runId.optional(),
8673
+ kind: z.enum(REVIEW_KINDS),
8674
+ question: z.string().min(1).max(4e3),
8675
+ context: jsonObject().optional(),
8676
+ input_contract: jsonObject().describe("JSON Schema the answer must satisfy."),
8677
+ team_id: zUuid().optional().describe("Review team to assign.")
8678
+ },
8679
+ MUTATING2,
8680
+ (a) => handleRaiseAppReview(t, b, a)
8681
+ );
8682
+ reg(
8683
+ "talonic_resolve_app_review",
8684
+ "Resolve Human Review",
8685
+ D.resolveReview,
8686
+ {
8687
+ review_id: reviewId,
8688
+ values: jsonObject().describe("Answer values matching the review's input_contract."),
8689
+ feedback: z.object({
8690
+ proposal_verdict: z.enum(["correct", "incorrect", "partial"]).optional(),
8691
+ correction: z.string().max(4e3).optional(),
8692
+ generalize: z.boolean().optional()
8693
+ }).optional().describe("Optional feedback that teaches the app.")
8694
+ },
8695
+ MUTATING2,
8696
+ (a) => handleResolveAppReview(t, b, a)
8697
+ );
8698
+ reg(
8699
+ "talonic_interview_app_review",
8700
+ "Interview Human Review",
8701
+ D.interview,
8702
+ {
8703
+ review_id: reviewId,
8704
+ message: z.string().min(1).max(4e3).describe("The reviewer's message for this turn."),
8705
+ transcript: z.array(z.object({ role: z.enum(["user", "assistant"]), text: z.string().max(2e3) })).max(20).optional().describe("Earlier turns, oldest first.")
8706
+ },
8707
+ { ...READ_ONLY3, idempotentHint: false },
8708
+ (a) => handleInterviewReview(t, b, a)
8709
+ );
8710
+ reg(
8711
+ "talonic_list_app_precedents",
8712
+ "List App Precedents",
8713
+ D.precedents,
8714
+ { app_id: appId, similar_to: jsonObject().optional().describe("Match keys of the case.") },
8715
+ READ_ONLY3,
8716
+ (a) => handleListAppPrecedents(t, b, a)
8717
+ );
8718
+ }
8719
+ function probeAppsToolsetAccess(token, baseUrl) {
8720
+ return probeAccessState(token, baseUrl, "/v1/apps");
8721
+ }
8722
+ var DECIDE_SCOPE = "apps:decide";
8723
+ function tokenHasDecideScope(token) {
8724
+ if (token.startsWith("tlnc_")) return true;
8725
+ const parts = token.split(".");
8726
+ if (parts.length !== 3) return true;
8727
+ try {
8728
+ const payload = JSON.parse(Buffer.from(parts[1] ?? "", "base64url").toString("utf8"));
8729
+ if (!Array.isArray(payload.scopes)) return true;
8730
+ return payload.scopes.includes(DECIDE_SCOPE);
8731
+ } catch {
8732
+ return true;
8733
+ }
8734
+ }
8735
+ var TASK_STATUSES2 = [
8736
+ "available",
8737
+ "claimed",
8738
+ "submitted",
8739
+ "released",
8740
+ "failed",
8741
+ "timed_out",
8742
+ "cancelled"
8743
+ ];
8744
+ var PACKAGE_PAGE_LIMIT_MAX = 2e3;
8745
+ var appId2 = zUuid().describe(
8746
+ "Id of an External-mode app (from talonic_list_apps, where mode is 'external')."
8747
+ );
8748
+ var taskId2 = zUuid().describe("Decision task UUID.");
8749
+ var executionEpoch2 = z.number().int().min(1).max(2147483647).describe("Execution epoch returned by the successful claim. Stale epochs are rejected with 409.");
8750
+ var status2 = z.enum(TASK_STATUSES2).optional().describe("Optional task-status filter.");
8751
+ var listLimit = z.number().int().min(1).max(100).optional().describe("Page size (default 50).");
8752
+ var cursor2 = z.string().min(1).optional().describe("Opaque cursor from pagination.next_cursor.");
8753
+ var packageCursor = z.string().min(1).optional().describe(
8754
+ "Opaque package cursor: package.first_cursor from the claim, then pagination.next_cursor. Omit for the first page."
8755
+ );
8756
+ var packageLimit = z.number().int().min(1).max(PACKAGE_PAGE_LIMIT_MAX).optional().describe(
8757
+ `Records per page, 1 to ${PACKAGE_PAGE_LIMIT_MAX}. Defaults to the platform page size (package.page_size from the claim).`
8758
+ );
8759
+ var outcome = z.record(z.string(), z.json()).describe(
8760
+ "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."
8761
+ );
8762
+ var evidence = z.array(z.string().min(1).max(512)).max(1e4).describe(
8763
+ "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."
8764
+ );
8765
+ var rationale = z.string().min(1).max(4e3).describe(
8766
+ "Short decision rationale (a summary, never private chain-of-thought), up to 4,000 characters."
8767
+ );
8768
+ var confidence = z.number().min(0).max(1).optional().describe("Optional confidence from 0 to 1.");
8769
+ var serviceVersion = z.string().min(1).max(64).optional().describe("Optional build identifier of the deciding service; recorded as decided_by.label.");
8770
+ var failReason = z.string().min(1).max(2e3).describe(
8771
+ "Why the task cannot be decided, up to 2,000 characters. Recorded on the Human Review the fail raises."
8772
+ );
8773
+ var listInput2 = { app_id: appId2, status: status2, limit: listLimit, cursor: cursor2 };
8774
+ var idInput2 = { task_id: taskId2 };
8775
+ var packageInput = { task_id: taskId2, cursor: packageCursor, limit: packageLimit };
8776
+ var epochInput = { task_id: taskId2, execution_epoch: executionEpoch2 };
8777
+ var submitInput2 = {
8778
+ task_id: taskId2,
8779
+ execution_epoch: executionEpoch2,
8780
+ outcome,
8781
+ evidence,
8782
+ rationale,
8783
+ confidence,
8784
+ service_version: serviceVersion
8785
+ };
8786
+ var failInput = { task_id: taskId2, execution_epoch: executionEpoch2, reason: failReason };
8787
+ function taskPath(taskId3, suffix = "") {
8000
8788
  return `/v1/decision-tasks/${encodeURIComponent(taskId3)}${suffix}`;
8001
8789
  }
8002
8790
  function handleListDecisionTasks(getToken, baseUrl, args) {
@@ -8057,12 +8845,12 @@ function handleFailDecisionTask(getToken, baseUrl, args) {
8057
8845
  })
8058
8846
  );
8059
8847
  }
8060
- var READ_ONLY3 = {
8848
+ var READ_ONLY4 = {
8061
8849
  readOnlyHint: true,
8062
8850
  destructiveHint: false,
8063
8851
  openWorldHint: false
8064
8852
  };
8065
- var MUTATING2 = {
8853
+ var MUTATING3 = {
8066
8854
  readOnlyHint: false,
8067
8855
  destructiveHint: false,
8068
8856
  openWorldHint: false
@@ -8132,9 +8920,9 @@ var DESCRIPTIONS2 = {
8132
8920
  };
8133
8921
  function registerDecisionTaskTools(server, getToken, baseUrl, options = {}) {
8134
8922
  const invocable = options.invocable !== false;
8135
- const metaFor = (key) => ({
8923
+ const metaFor = (key2) => ({
8136
8924
  _meta: {
8137
- ...widgetToolMeta(key),
8925
+ ...widgetToolMeta(key2),
8138
8926
  ...invocable ? {} : { "talonic/can_invoke": false, "talonic/required_scope": DECIDE_SCOPE }
8139
8927
  }
8140
8928
  });
@@ -8144,7 +8932,7 @@ function registerDecisionTaskTools(server, getToken, baseUrl, options = {}) {
8144
8932
  title: "List Decision Tasks",
8145
8933
  description: DESCRIPTIONS2.list,
8146
8934
  inputSchema: listInput2,
8147
- annotations: { title: "List Decision Tasks", ...READ_ONLY3 },
8935
+ annotations: { title: "List Decision Tasks", ...READ_ONLY4 },
8148
8936
  ...metaFor("listDecisionTasks")
8149
8937
  },
8150
8938
  async (args) => handleListDecisionTasks(getToken, baseUrl, args)
@@ -8155,7 +8943,7 @@ function registerDecisionTaskTools(server, getToken, baseUrl, options = {}) {
8155
8943
  title: "Claim Decision Task",
8156
8944
  description: DESCRIPTIONS2.claim,
8157
8945
  inputSchema: idInput2,
8158
- annotations: { title: "Claim Decision Task", ...MUTATING2 },
8946
+ annotations: { title: "Claim Decision Task", ...MUTATING3 },
8159
8947
  ...metaFor("claimDecisionTask")
8160
8948
  },
8161
8949
  async (args) => handleClaimDecisionTask(getToken, baseUrl, args)
@@ -8166,7 +8954,7 @@ function registerDecisionTaskTools(server, getToken, baseUrl, options = {}) {
8166
8954
  title: "Read Decision Package",
8167
8955
  description: DESCRIPTIONS2.package,
8168
8956
  inputSchema: packageInput,
8169
- annotations: { title: "Read Decision Package", ...READ_ONLY3 },
8957
+ annotations: { title: "Read Decision Package", ...READ_ONLY4 },
8170
8958
  ...metaFor("readDecisionPackage")
8171
8959
  },
8172
8960
  async (args) => handleReadDecisionPackage(getToken, baseUrl, args)
@@ -8177,7 +8965,7 @@ function registerDecisionTaskTools(server, getToken, baseUrl, options = {}) {
8177
8965
  title: "Heartbeat Decision Task",
8178
8966
  description: DESCRIPTIONS2.heartbeat,
8179
8967
  inputSchema: epochInput,
8180
- annotations: { title: "Heartbeat Decision Task", ...MUTATING2 },
8968
+ annotations: { title: "Heartbeat Decision Task", ...MUTATING3 },
8181
8969
  ...metaFor("heartbeatDecisionTask")
8182
8970
  },
8183
8971
  async (args) => handleHeartbeatDecisionTask(getToken, baseUrl, args)
@@ -8188,7 +8976,7 @@ function registerDecisionTaskTools(server, getToken, baseUrl, options = {}) {
8188
8976
  title: "Submit Decision Task",
8189
8977
  description: DESCRIPTIONS2.submit,
8190
8978
  inputSchema: submitInput2,
8191
- annotations: { title: "Submit Decision Task", ...MUTATING2 },
8979
+ annotations: { title: "Submit Decision Task", ...MUTATING3 },
8192
8980
  ...metaFor("submitDecisionTask")
8193
8981
  },
8194
8982
  async (args) => handleSubmitDecisionTask(getToken, baseUrl, args)
@@ -8199,7 +8987,7 @@ function registerDecisionTaskTools(server, getToken, baseUrl, options = {}) {
8199
8987
  title: "Release Decision Task",
8200
8988
  description: DESCRIPTIONS2.release,
8201
8989
  inputSchema: epochInput,
8202
- annotations: { title: "Release Decision Task", ...MUTATING2 },
8990
+ annotations: { title: "Release Decision Task", ...MUTATING3 },
8203
8991
  ...metaFor("releaseDecisionTask")
8204
8992
  },
8205
8993
  async (args) => handleReleaseDecisionTask(getToken, baseUrl, args)
@@ -8216,6 +9004,236 @@ function registerDecisionTaskTools(server, getToken, baseUrl, options = {}) {
8216
9004
  async (args) => handleFailDecisionTask(getToken, baseUrl, args)
8217
9005
  );
8218
9006
  }
9007
+
9008
+ // src/tools/mining-driver.ts
9009
+ var appId3 = zUuid().describe(
9010
+ "Id (UUID) of an autonomous app, from talonic_list_apps where mode is 'autonomous'."
9011
+ );
9012
+ var runId2 = zUuid().describe(
9013
+ "The round's run id (run_id from talonic_mining_list_rounds, or the decision task's run_id)."
9014
+ );
9015
+ var executionEpoch3 = z.number().int().min(1).max(2147483647).describe("execution_epoch from talonic_claim_decision_task. A stale epoch is HTTP 409.");
9016
+ var toolName = z.string().regex(/^[a-z][a-z0-9_]{0,63}$/).describe("A tool name from talonic_mining_list_round_tools.");
9017
+ var READ_ONLY5 = {
9018
+ readOnlyHint: true,
9019
+ destructiveHint: false,
9020
+ idempotentHint: true,
9021
+ openWorldHint: false
9022
+ };
9023
+ var MUTATING4 = {
9024
+ readOnlyHint: false,
9025
+ destructiveHint: false,
9026
+ idempotentHint: false,
9027
+ openWorldHint: false
9028
+ };
9029
+ var roundsPath = (app, suffix = "") => `/v1/apps/${encodeURIComponent(app)}/mining/rounds${suffix}`;
9030
+ var roundPath = (app, run, suffix = "") => roundsPath(app, `/${encodeURIComponent(run)}${suffix}`);
9031
+ var BUSY_BACKOFF_MS = [500, 1e3, 2e3, 4e3];
9032
+ var POLL_INTERVAL_MS = 2e3;
9033
+ var DEFAULT_WAIT_SECONDS = 25;
9034
+ var MAX_WAIT_SECONDS = 120;
9035
+ var realSleep = (ms) => new Promise((r) => setTimeout(r, ms));
9036
+ function isBusy(err) {
9037
+ if (!(err instanceof ApiHttpError) || err.status !== 409) return false;
9038
+ try {
9039
+ const body = JSON.parse(err.body);
9040
+ return (body.details?.refused ?? body.error?.details?.refused) === "busy";
9041
+ } catch {
9042
+ return /"refused"\s*:\s*"busy"/.test(err.body);
9043
+ }
9044
+ }
9045
+ var handleMiningListRounds = (t, b, a) => runTool(
9046
+ () => apiJson(t, b, "GET", roundsPath(a.app_id), { params: { limit: a.limit, offset: a.offset } })
9047
+ );
9048
+ var handleMiningGetRound = (t, b, a) => runTool(() => apiJson(t, b, "GET", roundPath(a.app_id, a.run_id)));
9049
+ var handleMiningStartRound = (t, b, a) => runTool(
9050
+ () => a.phase === "reconcile" ? apiJson(t, b, "POST", roundsPath(a.app_id, "/reconcile")) : apiJson(t, b, "POST", roundsPath(a.app_id), {
9051
+ body: {
9052
+ ...a.phase ? { phase: a.phase } : {},
9053
+ ...a.dry_run !== void 0 ? { dry_run: a.dry_run } : {}
9054
+ }
9055
+ })
9056
+ );
9057
+ var handleMiningListRoundTools = (t, b, a) => runTool(() => apiJson(t, b, "GET", roundPath(a.app_id, a.run_id, "/tools")));
9058
+ async function handleMiningCallRoundTool(t, b, a, timing = {}) {
9059
+ const sleep2 = timing.sleep ?? realSleep;
9060
+ const now = timing.now ?? Date.now;
9061
+ return runTool(async () => {
9062
+ const path = roundPath(a.app_id, a.run_id, `/tools/${encodeURIComponent(a.name)}`);
9063
+ const body = { execution_epoch: a.execution_epoch, input: a.input ?? {} };
9064
+ let answer;
9065
+ for (let attempt = 0; ; attempt++) {
9066
+ try {
9067
+ answer = await apiJson(t, b, "POST", path, { body });
9068
+ break;
9069
+ } catch (err) {
9070
+ const backoff = BUSY_BACKOFF_MS[attempt];
9071
+ if (!isBusy(err) || backoff === void 0) throw err;
9072
+ await sleep2(backoff);
9073
+ }
9074
+ }
9075
+ if (answer?.status !== "running" || !answer.call_id) return answer;
9076
+ const waitMs = Math.min(a.wait_seconds ?? DEFAULT_WAIT_SECONDS, MAX_WAIT_SECONDS) * 1e3;
9077
+ const deadline = now() + waitMs;
9078
+ const callId = answer.call_id;
9079
+ while (now() < deadline) {
9080
+ await sleep2(POLL_INTERVAL_MS);
9081
+ const polled = await apiJson(
9082
+ t,
9083
+ b,
9084
+ "GET",
9085
+ roundPath(a.app_id, a.run_id, `/tools/calls/${encodeURIComponent(callId)}`),
9086
+ { params: { execution_epoch: a.execution_epoch } }
9087
+ );
9088
+ if (polled?.status !== "running") return polled;
9089
+ }
9090
+ return {
9091
+ call_id: callId,
9092
+ status: "running",
9093
+ 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."
9094
+ };
9095
+ });
9096
+ }
9097
+ var handleMiningGetRoundToolCall = (t, b, a) => runTool(
9098
+ () => apiJson(
9099
+ t,
9100
+ b,
9101
+ "GET",
9102
+ roundPath(a.app_id, a.run_id, `/tools/calls/${encodeURIComponent(a.call_id)}`),
9103
+ {
9104
+ params: { execution_epoch: a.execution_epoch }
9105
+ }
9106
+ )
9107
+ );
9108
+ 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.";
9109
+ 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.";
9110
+ var D2 = {
9111
+ listRounds: [
9112
+ "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.",
9113
+ "USE WHEN: finding a round to drive or checking progress. ARGS: app_id, optional limit (max 200), offset."
9114
+ ].join("\n"),
9115
+ getRound: [
9116
+ "Read one rule-finding round: phase, status, budget, findings, candidate rules, summary, and the driver block for an externally driven round.",
9117
+ "ARGS: app_id, run_id."
9118
+ ].join("\n"),
9119
+ startRound: [
9120
+ "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.",
9121
+ "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).",
9122
+ "RETURNS: { run_id, status, phase, \u2026 }. A round with an outside driver then waits for a claim: see talonic_list_decision_tasks."
9123
+ ].join("\n"),
9124
+ listTools: [
9125
+ "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.",
9126
+ "USE WHEN: right after claiming the round's decision task, or to check remaining budget.",
9127
+ DRIVER_FLOW,
9128
+ AUTH_NOTE2
9129
+ ].join("\n"),
9130
+ callTool: [
9131
+ "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.",
9132
+ "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.",
9133
+ "Do not call tools on one round in parallel. close_round is not a tool here: close the round with talonic_submit_decision_task.",
9134
+ "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.",
9135
+ AUTH_NOTE2
9136
+ ].join("\n"),
9137
+ getCall: [
9138
+ "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.",
9139
+ "ARGS: app_id, run_id, call_id, execution_epoch.",
9140
+ AUTH_NOTE2
9141
+ ].join("\n")
9142
+ };
9143
+ function registerMiningDriverTools(server, getToken, baseUrl, options = {}) {
9144
+ const t = getToken;
9145
+ const b = baseUrl;
9146
+ const decideMeta = options.invocable === false ? { _meta: { "talonic/can_invoke": false, "talonic/required_scope": DECIDE_SCOPE } } : {};
9147
+ server.registerTool(
9148
+ "talonic_mining_list_rounds",
9149
+ {
9150
+ title: "List Mining Rounds",
9151
+ description: D2.listRounds,
9152
+ inputSchema: {
9153
+ app_id: appId3,
9154
+ limit: z.number().int().min(1).max(200).optional(),
9155
+ offset: z.number().int().min(0).optional()
9156
+ },
9157
+ annotations: { title: "List Mining Rounds", ...READ_ONLY5 }
9158
+ },
9159
+ (a) => handleMiningListRounds(t, b, a)
9160
+ );
9161
+ server.registerTool(
9162
+ "talonic_mining_get_round",
9163
+ {
9164
+ title: "Get Mining Round",
9165
+ description: D2.getRound,
9166
+ inputSchema: { app_id: appId3, run_id: runId2 },
9167
+ annotations: { title: "Get Mining Round", ...READ_ONLY5 }
9168
+ },
9169
+ (a) => handleMiningGetRound(t, b, a)
9170
+ );
9171
+ server.registerTool(
9172
+ "talonic_mining_start_round",
9173
+ {
9174
+ title: "Start Mining Round",
9175
+ description: D2.startRound,
9176
+ inputSchema: {
9177
+ app_id: appId3,
9178
+ phase: z.enum(["discovery", "hypothesis", "reconcile"]).optional(),
9179
+ dry_run: z.boolean().optional()
9180
+ },
9181
+ annotations: { title: "Start Mining Round", ...MUTATING4 }
9182
+ },
9183
+ (a) => handleMiningStartRound(t, b, a)
9184
+ );
9185
+ server.registerTool(
9186
+ "talonic_mining_list_round_tools",
9187
+ {
9188
+ title: "List Round Tools",
9189
+ description: D2.listTools,
9190
+ inputSchema: { app_id: appId3, run_id: runId2 },
9191
+ annotations: { title: "List Round Tools", ...READ_ONLY5 },
9192
+ ...decideMeta
9193
+ },
9194
+ (a) => handleMiningListRoundTools(t, b, a)
9195
+ );
9196
+ server.registerTool(
9197
+ "talonic_mining_call_round_tool",
9198
+ {
9199
+ title: "Call Round Tool",
9200
+ description: D2.callTool,
9201
+ inputSchema: {
9202
+ app_id: appId3,
9203
+ run_id: runId2,
9204
+ execution_epoch: executionEpoch3,
9205
+ name: toolName,
9206
+ input: z.record(z.string(), z.json()).optional().describe("The tool's input object."),
9207
+ wait_seconds: z.number().int().min(0).max(MAX_WAIT_SECONDS).optional().describe(`Seconds to keep polling a long call (default ${DEFAULT_WAIT_SECONDS}).`)
9208
+ },
9209
+ annotations: { title: "Call Round Tool", ...MUTATING4 },
9210
+ ...decideMeta
9211
+ },
9212
+ (a) => handleMiningCallRoundTool(t, b, a)
9213
+ );
9214
+ server.registerTool(
9215
+ "talonic_mining_get_round_tool_call",
9216
+ {
9217
+ title: "Get Round Tool Call",
9218
+ description: D2.getCall,
9219
+ inputSchema: {
9220
+ app_id: appId3,
9221
+ run_id: runId2,
9222
+ call_id: zUuid().describe("call_id from talonic_mining_call_round_tool."),
9223
+ execution_epoch: executionEpoch3
9224
+ },
9225
+ annotations: { title: "Get Round Tool Call", ...READ_ONLY5 },
9226
+ ...decideMeta
9227
+ },
9228
+ (a) => handleMiningGetRoundToolCall(t, b, a)
9229
+ );
9230
+ }
9231
+ function probeMiningInUse(token, baseUrl) {
9232
+ return probeAccessState(token, baseUrl, "/v1/apps", (body) => {
9233
+ const apps = body?.apps;
9234
+ return Array.isArray(apps) && apps.some((a) => a?.mode === "autonomous");
9235
+ });
9236
+ }
8219
9237
  var DESCRIPTION11 = [
8220
9238
  "Get the OCR-converted markdown text of a document.",
8221
9239
  "",
@@ -8282,8 +9300,8 @@ async function handleToMarkdown(talonic, args, opts = {}) {
8282
9300
  retryable: false
8283
9301
  });
8284
9302
  }
8285
- let documentId = args.document_id;
8286
- if (!documentId) {
9303
+ let documentId3 = args.document_id;
9304
+ if (!documentId3) {
8287
9305
  const ingest = await talonic.extract({
8288
9306
  ...args.file_data !== void 0 ? {
8289
9307
  file: Buffer.from(args.file_data, "base64"),
@@ -8293,9 +9311,9 @@ async function handleToMarkdown(talonic, args, opts = {}) {
8293
9311
  ...args.file_url !== void 0 ? { file_url: args.file_url } : {},
8294
9312
  schema: INGEST_ONLY_SCHEMA
8295
9313
  });
8296
- documentId = ingest.document.id;
9314
+ documentId3 = ingest.document.id;
8297
9315
  }
8298
- const result = await talonic.documents.getMarkdown(documentId);
9316
+ const result = await talonic.documents.getMarkdown(documentId3);
8299
9317
  return jsonOk(result);
8300
9318
  } catch (err) {
8301
9319
  return toolError(err);
@@ -8518,18 +9536,22 @@ function unwrap(res) {
8518
9536
  }
8519
9537
  var documentIdsArg = z.array(zUuid()).max(1e3).optional().describe("Restrict to these document ids (hard filter, enforced server-side).");
8520
9538
  var FIND_DESCRIPTION = [
8521
- "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.",
9539
+ "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.",
8522
9540
  "",
8523
- "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.",
9541
+ "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.",
8524
9542
  "NOT FOR: reading a known field's values (talonic_field_values) or filtering by a known field (talonic_filter).",
8525
9543
  "",
8526
- "ARGS: `query` (the concept, in the user's words), optional `top_k` (1\u201325, default 10), `document_ids` (hard scope).",
8527
- "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."
9544
+ "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).",
9545
+ "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."
8528
9546
  ].join("\n");
8529
9547
  var findDataInputSchema = {
8530
9548
  query: z.string().min(1).describe("The natural-language concept to locate."),
9549
+ 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)."),
8531
9550
  top_k: z.number().int().min(1).max(25).optional().describe("Max results per group (default 10)."),
8532
- document_ids: documentIdsArg
9551
+ document_ids: documentIdsArg,
9552
+ account: z.string().min(1).max(200).optional().describe(
9553
+ "Only the documents of this account (portfolio company), by name or alias, e.g. 'Filu'."
9554
+ )
8533
9555
  };
8534
9556
  async function handleFindData(getToken, baseUrl, args) {
8535
9557
  return runTool(async () => {
@@ -8542,8 +9564,10 @@ async function handleFindData(getToken, baseUrl, args) {
8542
9564
  body: {
8543
9565
  args: {
8544
9566
  query: args.query,
9567
+ ...args.concepts?.length ? { concepts: args.concepts } : {},
8545
9568
  ...args.top_k !== void 0 ? { top_k: args.top_k } : {},
8546
- ...args.document_ids?.length ? { document_scope: args.document_ids } : {}
9569
+ ...args.document_ids?.length ? { document_scope: args.document_ids } : {},
9570
+ ...args.account?.trim() ? { account: args.account.trim() } : {}
8547
9571
  }
8548
9572
  }
8549
9573
  }
@@ -8572,7 +9596,7 @@ async function handleListAgentTools(getToken, baseUrl, args) {
8572
9596
  const onlyInvocable = args.only_invocable ?? true;
8573
9597
  const includeSchemas = args.include_schemas ?? true;
8574
9598
  const registry = (res.tools ?? []).filter((t) => !DEDICATED.has(t.name));
8575
- const tools = registry.filter((t) => !onlyInvocable || t.can_invoke).map((t) => {
9599
+ const tools2 = registry.filter((t) => !onlyInvocable || t.can_invoke).map((t) => {
8576
9600
  const item = {
8577
9601
  name: t.name,
8578
9602
  description: t.description,
@@ -8584,7 +9608,7 @@ async function handleListAgentTools(getToken, baseUrl, args) {
8584
9608
  return item;
8585
9609
  });
8586
9610
  return {
8587
- tools,
9611
+ tools: tools2,
8588
9612
  invocable_count: registry.filter((t) => t.can_invoke).length,
8589
9613
  totalCount: registry.length
8590
9614
  };
@@ -8752,7 +9776,7 @@ async function handleGetSpec(getToken, baseUrl, args) {
8752
9776
  return { ...spec, versions: versions.data ?? [] };
8753
9777
  });
8754
9778
  }
8755
- var READ_ONLY4 = {
9779
+ var READ_ONLY6 = {
8756
9780
  readOnlyHint: true,
8757
9781
  destructiveHint: false,
8758
9782
  idempotentHint: true,
@@ -8765,7 +9789,7 @@ function registerSpecTools(server, getToken, baseUrl) {
8765
9789
  title: "List pipelines",
8766
9790
  description: LIST_DESCRIPTION5,
8767
9791
  inputSchema: listSpecsInputSchema,
8768
- annotations: { title: "List pipelines", ...READ_ONLY4 },
9792
+ annotations: { title: "List pipelines", ...READ_ONLY6 },
8769
9793
  _meta: widgetToolMeta("listSpecs")
8770
9794
  },
8771
9795
  async (args) => handleListSpecs(getToken, baseUrl, args)
@@ -8776,7 +9800,7 @@ function registerSpecTools(server, getToken, baseUrl) {
8776
9800
  title: "Look up a pipeline",
8777
9801
  description: GET_DESCRIPTION4,
8778
9802
  inputSchema: getSpecInputSchema,
8779
- annotations: { title: "Look up a pipeline", ...READ_ONLY4 },
9803
+ annotations: { title: "Look up a pipeline", ...READ_ONLY6 },
8780
9804
  _meta: widgetToolMeta("getSpec")
8781
9805
  },
8782
9806
  async (args) => handleGetSpec(getToken, baseUrl, args)
@@ -8992,7 +10016,7 @@ async function handleGetRunResults(getToken, baseUrl, args) {
8992
10016
  return { run_kind: kind, ...body };
8993
10017
  });
8994
10018
  }
8995
- var READ_ONLY5 = {
10019
+ var READ_ONLY7 = {
8996
10020
  readOnlyHint: true,
8997
10021
  destructiveHint: false,
8998
10022
  idempotentHint: true,
@@ -9021,7 +10045,7 @@ function registerRunTools(server, getToken, baseUrl) {
9021
10045
  title: "Check run progress",
9022
10046
  description: GET_RUN_DESCRIPTION,
9023
10047
  inputSchema: runRefInputSchema,
9024
- annotations: { title: "Check run progress", ...READ_ONLY5 },
10048
+ annotations: { title: "Check run progress", ...READ_ONLY7 },
9025
10049
  _meta: widgetToolMeta("getRun")
9026
10050
  },
9027
10051
  async (args) => handleGetRun(getToken, baseUrl, args)
@@ -9032,7 +10056,7 @@ function registerRunTools(server, getToken, baseUrl) {
9032
10056
  title: "Read run results",
9033
10057
  description: RESULTS_DESCRIPTION,
9034
10058
  inputSchema: resultsInputSchema,
9035
- annotations: { title: "Read run results", ...READ_ONLY5 },
10059
+ annotations: { title: "Read run results", ...READ_ONLY7 },
9036
10060
  _meta: widgetToolMeta("getRunResults")
9037
10061
  },
9038
10062
  async (args) => handleGetRunResults(getToken, baseUrl, args)
@@ -9177,35 +10201,2139 @@ function registerAskTools(server, getToken, baseUrl) {
9177
10201
  );
9178
10202
  }
9179
10203
 
9180
- // package.json
9181
- var package_default = {
9182
- version: "0.1.103"};
9183
-
9184
- // src/version.ts
9185
- var VERSION = package_default.version;
9186
- var SERVER_NAME = "talonic";
9187
-
9188
- // src/server-factory.ts
9189
- function makeTaggedFetch(getClientName, baseFetch = fetch) {
9190
- return ((input, init) => {
9191
- try {
9192
- const headers = new Headers(init?.headers);
9193
- const cn = getClientName();
9194
- headers.set("user-agent", `talonic-mcp/${VERSION}${cn ? ` ${cn}` : ""}`);
9195
- return baseFetch(input, { ...init, headers });
9196
- } catch {
9197
- return baseFetch(input, init);
10204
+ // src/tools/_groups.ts
10205
+ var READ = {
10206
+ readOnlyHint: true,
10207
+ destructiveHint: false,
10208
+ idempotentHint: true,
10209
+ openWorldHint: false
10210
+ };
10211
+ var write9 = (idempotent, destructive2 = false) => ({
10212
+ readOnlyHint: false,
10213
+ destructiveHint: destructive2,
10214
+ idempotentHint: idempotent,
10215
+ openWorldHint: false
10216
+ });
10217
+ var camelToSnake = (s) => s.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`);
10218
+ function entries(map) {
10219
+ return Array.isArray(map) ? map.map((k) => [k, k]) : Object.entries(map);
10220
+ }
10221
+ function buildRequest(tool, args) {
10222
+ const space = tool.route.indexOf(" ");
10223
+ const method = tool.route.slice(0, space);
10224
+ const template = tool.route.slice(space + 1);
10225
+ const used = /* @__PURE__ */ new Set();
10226
+ const path = template.replace(/\{([A-Za-z0-9_]+)\}/g, (_m, name) => {
10227
+ const arg = camelToSnake(name);
10228
+ const value = args[arg];
10229
+ if (value === void 0 || value === null || value === "") {
10230
+ throw new Error(`Validation error: \`${arg}\` is required.`);
9198
10231
  }
10232
+ used.add(arg);
10233
+ return encodeURIComponent(String(value));
9199
10234
  });
10235
+ const params = {};
10236
+ for (const [arg, wire] of entries(tool.query ?? [])) {
10237
+ used.add(arg);
10238
+ const v = args[arg];
10239
+ if (v === void 0 || v === null) continue;
10240
+ params[wire] = Array.isArray(v) ? v.join(",") : v;
10241
+ }
10242
+ let body = void 0;
10243
+ if (tool.body === "rest") {
10244
+ const rest = {};
10245
+ for (const [k, v] of Object.entries(args)) if (!used.has(k) && v !== void 0) rest[k] = v;
10246
+ body = rest;
10247
+ } else if (tool.body) {
10248
+ const picked = {};
10249
+ for (const [arg, wire] of entries(tool.body)) {
10250
+ if (args[arg] !== void 0) picked[wire] = args[arg];
10251
+ }
10252
+ body = picked;
10253
+ } else if (method === "POST" || method === "PUT" || method === "PATCH") {
10254
+ body = {};
10255
+ }
10256
+ return { method, path, params, body };
9200
10257
  }
9201
- function buildServerInstructions(opts) {
9202
- return [
9203
- "Talonic turns unstructured documents (PDFs, scans, images, DOCX, emails) into",
9204
- "schema-validated JSON with per-field confidence scores and source provenance, and",
9205
- "answers questions about the documents in the user's Talonic workspace.",
9206
- "Which tool for which question:",
9207
- "(0) any question about what the documents contain (counts, totals, duplicates,",
9208
- "comparisons, anomalies) -> talonic_ask FIRST, in one call; do not explore fields,",
10258
+ function runGroupTool(tool, ctx, args) {
10259
+ if (tool.handler) return tool.handler(ctx, args);
10260
+ return runTool(async () => {
10261
+ const req = buildRequest(tool, args);
10262
+ return apiJson(ctx.getToken, ctx.baseUrl, req.method, req.path, {
10263
+ params: req.params,
10264
+ ...req.body !== void 0 ? { body: req.body } : {}
10265
+ });
10266
+ });
10267
+ }
10268
+ function registerGroup(server, group, getToken, baseUrl) {
10269
+ const ctx = { getToken, baseUrl };
10270
+ for (const tool of group.tools) {
10271
+ server.registerTool(
10272
+ tool.name,
10273
+ {
10274
+ title: tool.title,
10275
+ description: tool.description,
10276
+ inputSchema: tool.inputSchema,
10277
+ annotations: { title: tool.title, ...tool.annotations }
10278
+ },
10279
+ async (args) => runGroupTool(tool, ctx, args ?? {})
10280
+ );
10281
+ }
10282
+ }
10283
+ function probeGroup(group, token, baseUrl) {
10284
+ return probeAccessState(token, baseUrl, group.probe.path, () => true, group.probe.params ?? {});
10285
+ }
10286
+ function describe(parts) {
10287
+ return [
10288
+ parts.what,
10289
+ `USE WHEN: ${parts.use}`,
10290
+ ...parts.not ? [`NOT FOR: ${parts.not}`] : [],
10291
+ "",
10292
+ `ARGS: ${parts.args ?? "none."}`,
10293
+ `RETURNS: ${parts.returns}`,
10294
+ ...parts.errors ? [`ERRORS: ${parts.errors}`] : []
10295
+ ].join("\n");
10296
+ }
10297
+ var SCOPES = [
10298
+ "extract",
10299
+ "read",
10300
+ "write",
10301
+ "operations",
10302
+ "billing",
10303
+ "delivery",
10304
+ "usage",
10305
+ "records_write"
10306
+ ];
10307
+ var LIST_KEYS = describe({
10308
+ 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.",
10309
+ use: "auditing which keys exist, finding the id of a key to revoke, or checking a key's scopes and expiry.",
10310
+ not: "creating a key (talonic_create_api_key); the workspace's credits and limits (talonic_get_account).",
10311
+ returns: "{ data[] { id, name, scopes[], masked_prefix, is_active, last_used, created_at, revoked_at, expires_at } }."
10312
+ });
10313
+ var CREATE_KEY = describe({
10314
+ 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.",
10315
+ use: "the user asks for a new or narrower key, e.g. a read-only key for a dashboard, or a key that expires.",
10316
+ not: "rotating by revoking (talonic_revoke_api_key, after the new key is in place).",
10317
+ 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).",
10318
+ returns: "{ id, name, key (the secret, shown once), masked_prefix, scopes[], created_at, expires_at, warning }.",
10319
+ 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."
10320
+ });
10321
+ var REVOKE_KEY = describe({
10322
+ 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.",
10323
+ use: "the user asks to revoke, rotate out or disable a key.",
10324
+ not: "listing keys (talonic_list_api_keys).",
10325
+ args: "`key_id` (UUID from talonic_list_api_keys).",
10326
+ returns: "{ id, revoked: true }.",
10327
+ errors: "404 key_not_found when no active key with that id is yours to revoke."
10328
+ });
10329
+ var GET_ACCOUNT = describe({
10330
+ 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.",
10331
+ use: "checking plan, limits or today's request counts, e.g. before a large batch or after a 429.",
10332
+ not: "credit spend by function (talonic_get_usage); buying credits (talonic_get_billing_upgrade_link).",
10333
+ 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 } }."
10334
+ });
10335
+ var LIST_WEBHOOKS = describe({
10336
+ 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.",
10337
+ use: "checking where events are sent, or finding a webhook id to change or delete.",
10338
+ not: "the events themselves (talonic_list_events); valid event type names (talonic_list_webhook_event_types).",
10339
+ returns: "{ data[] { id, url, events[], is_active, source_connection_id, created_at, updated_at } }."
10340
+ });
10341
+ var GET_WEBHOOK = describe({
10342
+ what: "One webhook configuration by id.",
10343
+ use: "reading one webhook's URL, events and state before changing it.",
10344
+ not: "listing every webhook (talonic_list_webhooks).",
10345
+ args: "`id` (UUID).",
10346
+ returns: "{ id, url, events[], is_active, source_connection_id, created_at, updated_at }."
10347
+ });
10348
+ var CREATE_WEBHOOK = describe({
10349
+ 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.",
10350
+ use: "the user wants Talonic to notify their system, e.g. when an extraction completes or fails.",
10351
+ not: "changing an existing webhook (talonic_update_webhook).",
10352
+ 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).",
10353
+ returns: "{ id, url, events[], is_active, source_connection_id, created_at, updated_at }."
10354
+ });
10355
+ var UPDATE_WEBHOOK = describe({
10356
+ 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.",
10357
+ use: "pointing a webhook elsewhere, changing its events, rotating its secret, or pausing / resuming it.",
10358
+ not: "removing it for good (talonic_delete_webhook).",
10359
+ args: "`id` (UUID), and any of `url`, `events`, `secret`, `is_active`.",
10360
+ returns: "{ id, url, events[], is_active, source_connection_id, created_at, updated_at }."
10361
+ });
10362
+ var DELETE_WEBHOOK = describe({
10363
+ 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.",
10364
+ use: "the user asks to remove a webhook.",
10365
+ not: "pausing (talonic_update_webhook).",
10366
+ args: "`id` (UUID).",
10367
+ returns: "{ deleted: true, id }."
10368
+ });
10369
+ var EVENT_TYPES = describe({
10370
+ 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.",
10371
+ use: "choosing `events` for talonic_create_webhook or talonic_update_webhook.",
10372
+ not: "the events that happened (talonic_list_events).",
10373
+ returns: "{ data[] { event, description } }."
10374
+ });
10375
+ var UPGRADE_LINK = describe({
10376
+ 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.",
10377
+ use: "the workspace ran out of credits (HTTP 402) or the user asks how to buy more.",
10378
+ not: "checking the balance (talonic_get_balance) or prices (talonic_get_pricing).",
10379
+ args: "`pack` (optional: 10, 50, 250 or 1000 EUR; default 50).",
10380
+ returns: "{ url, provider (stripe | dashboard | aws_marketplace), requires_human: true, pack?, message }."
10381
+ });
10382
+ var webhookFields = {
10383
+ url: z.string().url().describe("Receiver URL (https) that accepts POST."),
10384
+ events: z.array(z.string().min(1)).min(1).describe("Event types to send."),
10385
+ secret: z.string().min(1).describe("Signing secret the receiver verifies."),
10386
+ is_active: z.boolean().describe("false pauses deliveries.")
10387
+ };
10388
+ var adminGroup = {
10389
+ key: "admin",
10390
+ label: "Workspace administration",
10391
+ docsSlug: "admin-tools",
10392
+ probe: { path: "/v1/account/keys" },
10393
+ tools: [
10394
+ {
10395
+ name: "talonic_list_api_keys",
10396
+ title: "List API keys",
10397
+ description: LIST_KEYS,
10398
+ route: "GET /v1/account/keys",
10399
+ inputSchema: {},
10400
+ annotations: READ
10401
+ },
10402
+ {
10403
+ name: "talonic_create_api_key",
10404
+ title: "Create an API key",
10405
+ description: CREATE_KEY,
10406
+ route: "POST /v1/account/keys",
10407
+ inputSchema: {
10408
+ name: z.string().min(1).max(255).describe("Label shown in listings."),
10409
+ scopes: z.array(z.enum(SCOPES)).min(1).optional().describe("Subset of the calling credential's scopes; omitted = the same scopes."),
10410
+ expires_at: z.string().optional().describe("When the key stops working, ISO-8601 in the future.")
10411
+ },
10412
+ annotations: write9(false),
10413
+ body: ["name", "scopes", "expires_at"]
10414
+ },
10415
+ {
10416
+ name: "talonic_revoke_api_key",
10417
+ title: "Revoke an API key",
10418
+ description: REVOKE_KEY,
10419
+ route: "DELETE /v1/account/keys/{keyId}",
10420
+ inputSchema: { key_id: zUuid().describe("The key, from talonic_list_api_keys.") },
10421
+ annotations: write9(true, true)
10422
+ },
10423
+ {
10424
+ name: "talonic_get_account",
10425
+ title: "Account snapshot",
10426
+ description: GET_ACCOUNT,
10427
+ route: "GET /v1/account",
10428
+ inputSchema: {},
10429
+ annotations: READ
10430
+ },
10431
+ {
10432
+ name: "talonic_list_webhooks",
10433
+ title: "List webhooks",
10434
+ description: LIST_WEBHOOKS,
10435
+ route: "GET /v1/webhooks",
10436
+ inputSchema: {},
10437
+ annotations: READ
10438
+ },
10439
+ {
10440
+ name: "talonic_get_webhook",
10441
+ title: "One webhook",
10442
+ description: GET_WEBHOOK,
10443
+ route: "GET /v1/webhooks/{id}",
10444
+ inputSchema: { id: zUuid().describe("The webhook id.") },
10445
+ annotations: READ
10446
+ },
10447
+ {
10448
+ name: "talonic_create_webhook",
10449
+ title: "Create a webhook",
10450
+ description: CREATE_WEBHOOK,
10451
+ route: "POST /v1/webhooks",
10452
+ inputSchema: {
10453
+ url: webhookFields.url,
10454
+ events: webhookFields.events.optional(),
10455
+ secret: webhookFields.secret.optional(),
10456
+ source_connection_id: zUuid().optional().describe("Only events of this source."),
10457
+ is_active: webhookFields.is_active.optional()
10458
+ },
10459
+ annotations: write9(false),
10460
+ body: ["url", "events", "secret", "source_connection_id", "is_active"]
10461
+ },
10462
+ {
10463
+ name: "talonic_update_webhook",
10464
+ title: "Change a webhook",
10465
+ description: UPDATE_WEBHOOK,
10466
+ route: "PATCH /v1/webhooks/{id}",
10467
+ inputSchema: {
10468
+ id: zUuid().describe("The webhook id."),
10469
+ url: webhookFields.url.optional(),
10470
+ events: webhookFields.events.optional(),
10471
+ secret: webhookFields.secret.optional(),
10472
+ is_active: webhookFields.is_active.optional()
10473
+ },
10474
+ annotations: write9(true),
10475
+ body: ["url", "events", "secret", "is_active"]
10476
+ },
10477
+ {
10478
+ name: "talonic_delete_webhook",
10479
+ title: "Delete a webhook",
10480
+ description: DELETE_WEBHOOK,
10481
+ route: "DELETE /v1/webhooks/{id}",
10482
+ inputSchema: { id: zUuid().describe("The webhook id.") },
10483
+ annotations: write9(true, true)
10484
+ },
10485
+ {
10486
+ name: "talonic_list_webhook_event_types",
10487
+ title: "Webhook event types",
10488
+ description: EVENT_TYPES,
10489
+ route: "GET /v1/webhooks/events",
10490
+ inputSchema: {},
10491
+ annotations: READ
10492
+ },
10493
+ {
10494
+ name: "talonic_get_billing_upgrade_link",
10495
+ title: "Buy-credits link",
10496
+ description: UPGRADE_LINK,
10497
+ route: "GET /v1/billing/upgrade-link",
10498
+ inputSchema: {
10499
+ pack: z.enum(["10", "50", "250", "1000"]).optional().describe("Credit pack in EUR.")
10500
+ },
10501
+ annotations: READ,
10502
+ query: ["pack"]
10503
+ }
10504
+ ]
10505
+ };
10506
+ var TIMESTAMP_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})$/i;
10507
+ var QUERY_ID_RE = /^[a-z][a-z0-9_]{0,63}$/;
10508
+ var OPS = [
10509
+ "eq",
10510
+ "neq",
10511
+ "in",
10512
+ "not_in",
10513
+ "is_null",
10514
+ "not_null",
10515
+ "gt",
10516
+ "gte",
10517
+ "lt",
10518
+ "lte",
10519
+ "contains_any",
10520
+ "contains_all"
10521
+ ];
10522
+ var CATALOG = describe({
10523
+ 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.",
10524
+ use: "before the first talonic_aggregate call of a conversation, or when talonic_aggregate answered 400 invalid_aggregate.",
10525
+ not: "the numbers themselves (talonic_aggregate).",
10526
+ 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 }."
10527
+ });
10528
+ var AGGREGATE = describe({
10529
+ 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.",
10530
+ 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.",
10531
+ 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.",
10532
+ 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[]`.",
10533
+ 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.",
10534
+ 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)."
10535
+ });
10536
+ var whereSchema = z.object({
10537
+ field: z.string().min(1).describe("A field of the query's dataset (talonic_aggregate_catalog)."),
10538
+ op: z.enum(OPS).describe("Filter operator; the catalog lists which ones each field takes."),
10539
+ value: z.unknown().optional().describe("Omitted for is_null / not_null; a list for in, not_in, contains_any, contains_all.")
10540
+ });
10541
+ var querySchema = z.object({
10542
+ id: z.string().describe("Result key: starts with a lowercase letter; letters, digits, underscore."),
10543
+ dataset: z.string().min(1).describe("A catalog dataset, e.g. documents, app_verdicts, deliveries."),
10544
+ measure: z.union([z.string(), z.array(z.string()).min(1)]).describe("One measure (returns value) or a list (returns values plus n)."),
10545
+ of: z.string().optional().describe("Numeric field for sum, avg, min, max, median, p1-p99."),
10546
+ where: z.array(whereSchema).max(50).optional(),
10547
+ group_by: z.array(z.string()).optional().describe("Up to 3 groupable fields, or hour / day (UTC).")
10548
+ });
10549
+ var aggregateInputSchema = {
10550
+ from: z.string().describe("Window start, inclusive, ISO-8601 with offset."),
10551
+ to: z.string().describe("Window end, exclusive, ISO-8601 with offset."),
10552
+ scope: z.record(z.string(), z.unknown()).optional().describe(
10553
+ "Document selectors applied to every query: document_ids, tags, system_tags, source_connection_ids, document_types, client_batch_ids, roots_only, attachments_only."
10554
+ ),
10555
+ queries: z.array(querySchema).min(1).describe("The numbers to compute; each result is keyed by its id.")
10556
+ };
10557
+ function checkAggregateArgs(args) {
10558
+ for (const key2 of ["from", "to"]) {
10559
+ const v = args[key2];
10560
+ if (typeof v !== "string" || !TIMESTAMP_RE.test(v)) {
10561
+ return `\`${key2}\` must be an ISO-8601 timestamp with an offset, e.g. 2026-11-05T12:00:00Z.`;
10562
+ }
10563
+ }
10564
+ if (Date.parse(args["to"]) <= Date.parse(args["from"])) {
10565
+ return "`to` must be after `from` (the window is [from, to)).";
10566
+ }
10567
+ const queries = args["queries"];
10568
+ if (!Array.isArray(queries) || queries.length === 0) return "`queries` needs at least one query.";
10569
+ const seen = /* @__PURE__ */ new Set();
10570
+ for (const q of queries) {
10571
+ if (typeof q?.id !== "string" || !QUERY_ID_RE.test(q.id)) {
10572
+ return `query id ${JSON.stringify(q?.id)} must start with a lowercase letter and hold only lowercase letters, digits and underscores.`;
10573
+ }
10574
+ if (seen.has(q.id)) return `query id "${q.id}" is used twice; each result needs its own id.`;
10575
+ seen.add(q.id);
10576
+ }
10577
+ return null;
10578
+ }
10579
+ var aggregateTool = {
10580
+ name: "talonic_aggregate",
10581
+ title: "Workspace metrics",
10582
+ description: AGGREGATE,
10583
+ route: "POST /v1/aggregate",
10584
+ inputSchema: aggregateInputSchema,
10585
+ annotations: READ,
10586
+ body: ["from", "to", "scope", "queries"],
10587
+ handler: (ctx, args) => {
10588
+ const refusal = checkAggregateArgs(args);
10589
+ if (refusal) return Promise.resolve(validationError(refusal));
10590
+ return runGroupTool({ ...aggregateTool, handler: void 0 }, ctx, args);
10591
+ }
10592
+ };
10593
+ var aggregateGroup = {
10594
+ key: "aggregate",
10595
+ label: "Workspace metrics",
10596
+ docsSlug: "aggregate-tools",
10597
+ probe: { path: "/v1/aggregate/catalog" },
10598
+ tools: [
10599
+ {
10600
+ name: "talonic_aggregate_catalog",
10601
+ title: "What workspace metrics can count",
10602
+ description: CATALOG,
10603
+ route: "GET /v1/aggregate/catalog",
10604
+ inputSchema: {},
10605
+ annotations: READ
10606
+ },
10607
+ aggregateTool
10608
+ ]
10609
+ };
10610
+ var COMPLIANCE_EXPORT_MAX_BYTES = 8 * 1024 * 1024;
10611
+ var docIds = (min, max, what) => z.array(zUuid()).min(min).max(max).describe(what);
10612
+ var pageArgs2 = {
10613
+ status: z.enum(["processing", "waiting", "completed", "error"]).optional().describe("Only evaluations with this status (an interrupted one shows error)."),
10614
+ limit: z.number().int().min(1).max(500).optional().describe("Page size; any of status / limit / offset asks for one page."),
10615
+ offset: z.number().int().min(0).optional().describe("Rows to skip, for paging.")
10616
+ };
10617
+ var epoch = z.number().int().min(1).describe("The execution_epoch talonic_compliance_claim_task returned.");
10618
+ async function handleComplianceExport(ctx, args, maxBytes = COMPLIANCE_EXPORT_MAX_BYTES) {
10619
+ const format = args["format"] ?? "xlsx";
10620
+ const params = { format, ...args["issues_only"] ? { issues: "true" } : {} };
10621
+ const path = "/v1/compliance/export";
10622
+ try {
10623
+ const file = await apiBinary(ctx.getToken, ctx.baseUrl, path, { params, maxBytes });
10624
+ const filename = file.filename ?? `compliance.${format}`;
10625
+ const meta = { filename, mime_type: file.mimeType, size: file.bytes.length, format };
10626
+ return {
10627
+ content: [
10628
+ { type: "text", text: JSON.stringify(meta) },
10629
+ {
10630
+ type: "resource",
10631
+ resource: {
10632
+ uri: buildUrl(ctx.baseUrl, path, params),
10633
+ mimeType: file.mimeType,
10634
+ blob: file.bytes.toString("base64")
10635
+ }
10636
+ }
10637
+ ],
10638
+ structuredContent: meta
10639
+ };
10640
+ } catch (err) {
10641
+ return toolError(err);
10642
+ }
10643
+ }
10644
+ var tools = [
10645
+ // ── Worklist and evidence ────────────────────────────────────────────────
10646
+ {
10647
+ name: "talonic_compliance_issues",
10648
+ title: "Compliance worklist",
10649
+ description: describe({
10650
+ 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.",
10651
+ use: "'what is not compliant', the starting point before opening one document's evaluation.",
10652
+ not: "the full verdict list with passes (talonic_compliance_list_evaluations); one document's reasons and quotes (talonic_compliance_get_document_evaluation).",
10653
+ args: "`unclear` (also list unclear verdicts).",
10654
+ returns: "{ data[] } one entry per document with its failing rules."
10655
+ }),
10656
+ route: "GET /v1/compliance/issues",
10657
+ inputSchema: {
10658
+ unclear: z.boolean().optional().describe("Also list rules whose verdict is unclear.")
10659
+ },
10660
+ annotations: READ,
10661
+ query: ["unclear"]
10662
+ },
10663
+ {
10664
+ name: "talonic_compliance_get_document_evaluation",
10665
+ title: "One document's compliance evaluation",
10666
+ description: describe({
10667
+ 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.",
10668
+ use: "retrieving the evidence behind a failed check from talonic_compliance_issues, before deciding on a correction.",
10669
+ not: "a document set (talonic_compliance_get_set_evaluation).",
10670
+ args: "`document_id`.",
10671
+ returns: "{ evaluation } with its results; null when the document was never evaluated."
10672
+ }),
10673
+ route: "GET /v1/compliance/evaluations/documents/{documentId}",
10674
+ inputSchema: { document_id: zUuid().describe("The evaluated document.") },
10675
+ annotations: READ
10676
+ },
10677
+ {
10678
+ name: "talonic_compliance_list_evaluations",
10679
+ title: "Compliance evaluations",
10680
+ description: describe({
10681
+ 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.",
10682
+ use: "an overview of every evaluated document, or finding documents whose evaluation errored or is still running.",
10683
+ not: "only the failures (talonic_compliance_issues); counts only (talonic_compliance_evaluation_status).",
10684
+ args: "`status` processing|waiting|completed|error, `limit` 1-500, `offset`.",
10685
+ returns: "{ data[] } or a page { data[], total, has_more }."
10686
+ }),
10687
+ route: "GET /v1/compliance/evaluations",
10688
+ inputSchema: pageArgs2,
10689
+ annotations: READ,
10690
+ query: ["status", "limit", "offset"]
10691
+ },
10692
+ {
10693
+ name: "talonic_compliance_evaluation_status",
10694
+ title: "Compliance evaluation counts",
10695
+ description: describe({
10696
+ what: "Counts over the latest evaluations: processing, completed, error, outdated and failing.",
10697
+ use: "the headline ('how many documents fail'), or waiting until evaluations started with talonic_compliance_evaluate finish.",
10698
+ returns: "{ processing, completed, error, outdated, failing }."
10699
+ }),
10700
+ route: "GET /v1/compliance/evaluations/status",
10701
+ inputSchema: {},
10702
+ annotations: READ
10703
+ },
10704
+ {
10705
+ name: "talonic_compliance_export",
10706
+ title: "Export compliance verdicts",
10707
+ description: describe({
10708
+ 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.`,
10709
+ use: "the user wants the results as a spreadsheet to share or file.",
10710
+ not: "reading results in the conversation (talonic_compliance_issues, talonic_compliance_get_document_evaluation).",
10711
+ args: "`format` xlsx (default) | csv, `issues_only` (only failed and unclear verdicts of the sets).",
10712
+ returns: "a text item { filename, mime_type, size, format } and a resource item { uri, mimeType, blob } with the file."
10713
+ }),
10714
+ route: "GET /v1/compliance/export",
10715
+ inputSchema: {
10716
+ format: z.enum(["xlsx", "csv"]).optional().describe("File format (default xlsx)."),
10717
+ issues_only: z.boolean().optional().describe("Only failed and unclear verdicts of the sets.")
10718
+ },
10719
+ annotations: READ,
10720
+ handler: (ctx, args) => handleComplianceExport(ctx, args)
10721
+ },
10722
+ // ── Evaluating ───────────────────────────────────────────────────────────
10723
+ {
10724
+ name: "talonic_compliance_evaluate",
10725
+ title: "Evaluate documents for compliance",
10726
+ description: describe({
10727
+ what: "Evaluate documents against every framework that is ON. Runs in the background; poll talonic_compliance_evaluation_status or talonic_compliance_get_document_evaluation.",
10728
+ use: "a document changed or a framework was switched ON and its verdicts are outdated; or after a correction, to check it took effect.",
10729
+ not: "documents not yet on the Evaluations list (talonic_compliance_add_documents adds and evaluates them).",
10730
+ args: "`document_ids` (1-500).",
10731
+ returns: "{ data[] } one started evaluation per document.",
10732
+ errors: "403 when the app is switched off for the workspace."
10733
+ }),
10734
+ route: "POST /v1/compliance/evaluations",
10735
+ inputSchema: { document_ids: docIds(1, 500, "Documents to evaluate.") },
10736
+ annotations: write9(false),
10737
+ body: ["document_ids"]
10738
+ },
10739
+ {
10740
+ name: "talonic_compliance_evaluate_all",
10741
+ title: "Evaluate every document that needs it",
10742
+ description: describe({
10743
+ what: "Evaluate every listed document whose evaluation is missing or outdated, oldest first. Run with dry_run first to see how many.",
10744
+ use: "bringing the whole list up to date after frameworks changed.",
10745
+ args: "`dry_run` (only count), `limit` 1-500 (the rest follow on the next call).",
10746
+ returns: "How many documents need it and how many were started."
10747
+ }),
10748
+ route: "POST /v1/compliance/evaluations/all",
10749
+ inputSchema: {
10750
+ dry_run: z.boolean().optional().describe("Only report how many would be evaluated."),
10751
+ limit: z.number().int().min(1).max(500).optional().describe("Evaluate at most this many.")
10752
+ },
10753
+ annotations: write9(false),
10754
+ body: ["dry_run", "limit"]
10755
+ },
10756
+ {
10757
+ name: "talonic_compliance_add_documents",
10758
+ title: "Add documents to compliance evaluations",
10759
+ description: describe({
10760
+ what: "Put workspace documents on the Evaluations list and evaluate them against the frameworks that are ON.",
10761
+ use: "the user wants documents checked that are not on the list yet.",
10762
+ args: "`document_ids` (1-500).",
10763
+ returns: "The documents added and the evaluations started."
10764
+ }),
10765
+ route: "POST /v1/compliance/evaluations/documents",
10766
+ inputSchema: { document_ids: docIds(1, 500, "Documents to add and evaluate.") },
10767
+ annotations: write9(true),
10768
+ body: ["document_ids"]
10769
+ },
10770
+ {
10771
+ name: "talonic_compliance_remove_document",
10772
+ title: "Take a document off the compliance list",
10773
+ description: describe({
10774
+ 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.",
10775
+ use: "a document was put on the list by mistake or no longer needs checking. Ask the user first.",
10776
+ args: "`document_id`.",
10777
+ returns: "Confirmation of the removal."
10778
+ }),
10779
+ route: "DELETE /v1/compliance/evaluations/documents/{documentId}",
10780
+ inputSchema: { document_id: zUuid().describe("The document to take off the list.") },
10781
+ annotations: write9(true, true)
10782
+ },
10783
+ // ── Frameworks ───────────────────────────────────────────────────────────
10784
+ {
10785
+ name: "talonic_compliance_list_frameworks",
10786
+ title: "Compliance frameworks",
10787
+ description: describe({
10788
+ what: "The frameworks (regulations, policies, contract standards held as workspace documents) with their status, whether each is ON, and their rule counts.",
10789
+ use: "which rules documents are checked against, or finding a framework's document_id.",
10790
+ not: "the rules themselves (talonic_compliance_framework_rules).",
10791
+ returns: "{ data[] } frameworks with document_id, name, status, active, rule counts."
10792
+ }),
10793
+ route: "GET /v1/compliance/frameworks",
10794
+ inputSchema: {},
10795
+ annotations: READ
10796
+ },
10797
+ {
10798
+ name: "talonic_compliance_framework_rules",
10799
+ title: "A framework's rules",
10800
+ description: describe({
10801
+ what: "The rules of one framework: code, text, obligation, section, what it applies to and its condition.",
10802
+ use: "explaining a failed verdict's rule, or picking rule ids for a rule set.",
10803
+ args: "`document_id` (the framework's document).",
10804
+ returns: "{ data[] } rules with their ids."
10805
+ }),
10806
+ route: "GET /v1/compliance/frameworks/{documentId}/rules",
10807
+ inputSchema: { document_id: zUuid().describe("The framework's document id.") },
10808
+ annotations: READ
10809
+ },
10810
+ {
10811
+ name: "talonic_compliance_add_frameworks",
10812
+ title: "Make documents compliance frameworks",
10813
+ description: describe({
10814
+ 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.",
10815
+ use: "the user uploaded a regulation or policy and wants documents checked against it.",
10816
+ args: "`document_ids` (1-50).",
10817
+ returns: "{ data[] } the new frameworks."
10818
+ }),
10819
+ route: "POST /v1/compliance/frameworks/from-documents",
10820
+ inputSchema: { document_ids: docIds(1, 50, "Workspace documents to make frameworks.") },
10821
+ annotations: write9(true),
10822
+ body: ["document_ids"]
10823
+ },
10824
+ {
10825
+ name: "talonic_compliance_set_framework_active",
10826
+ title: "Switch a framework ON or OFF",
10827
+ description: describe({
10828
+ what: "Turn a framework ON (its rules are in force for every evaluation) or OFF (they are not). Reversible; evaluations made before become outdated.",
10829
+ use: "a framework does not apply to the workspace's documents, or should now apply.",
10830
+ args: "`document_id`, `active`.",
10831
+ returns: "The framework with its new state."
10832
+ }),
10833
+ route: "POST /v1/compliance/frameworks/{documentId}/active",
10834
+ inputSchema: {
10835
+ document_id: zUuid().describe("The framework's document id."),
10836
+ active: z.boolean().describe("true = ON, false = OFF.")
10837
+ },
10838
+ annotations: write9(true),
10839
+ body: ["active"]
10840
+ },
10841
+ {
10842
+ name: "talonic_compliance_generate_rules",
10843
+ title: "Write a framework's rules again",
10844
+ description: describe({
10845
+ what: "Write the rules of a framework again from its text, replacing the current ones.",
10846
+ 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.",
10847
+ args: "`document_id`.",
10848
+ returns: "The framework with its status and rule counts."
10849
+ }),
10850
+ route: "POST /v1/compliance/frameworks/{documentId}/rules/generate",
10851
+ inputSchema: { document_id: zUuid().describe("The framework's document id.") },
10852
+ annotations: write9(false, true)
10853
+ },
10854
+ {
10855
+ name: "talonic_compliance_remove_framework",
10856
+ title: "Take a framework out of Compliance",
10857
+ description: describe({
10858
+ what: "Take a framework out of the app with its rules. The document stays in the workspace and can be made a framework again.",
10859
+ use: "the user no longer wants documents checked against it. Ask first; to pause it, switch it OFF instead.",
10860
+ args: "`document_id`.",
10861
+ returns: "Confirmation of the removal."
10862
+ }),
10863
+ route: "DELETE /v1/compliance/frameworks/{documentId}",
10864
+ inputSchema: { document_id: zUuid().describe("The framework's document id.") },
10865
+ annotations: write9(true, true)
10866
+ },
10867
+ // ── Discrepancy comparisons ──────────────────────────────────────────────
10868
+ {
10869
+ name: "talonic_compliance_list_comparisons",
10870
+ title: "Document comparisons",
10871
+ description: describe({
10872
+ what: "Comparisons of document batches for discrepancies (values that should agree across the documents but do not), newest first.",
10873
+ use: "finding an earlier comparison.",
10874
+ returns: "{ data[] } comparisons with id, status and counts."
10875
+ }),
10876
+ route: "GET /v1/compliance/discrepancy-runs",
10877
+ inputSchema: {},
10878
+ annotations: READ
10879
+ },
10880
+ {
10881
+ name: "talonic_compliance_get_comparison",
10882
+ title: "One document comparison",
10883
+ description: describe({
10884
+ what: "One comparison with every discrepancy found: the value, which documents disagree and where.",
10885
+ use: "reading the result of talonic_compliance_compare_documents.",
10886
+ args: "`run_id`.",
10887
+ returns: "The comparison with its status and discrepancies."
10888
+ }),
10889
+ route: "GET /v1/compliance/discrepancy-runs/{runId}",
10890
+ inputSchema: { run_id: zUuid().describe("The comparison id.") },
10891
+ annotations: READ
10892
+ },
10893
+ {
10894
+ name: "talonic_compliance_compare_documents",
10895
+ title: "Compare documents for discrepancies",
10896
+ description: describe({
10897
+ 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.",
10898
+ use: "the user asks whether a set of documents is consistent.",
10899
+ args: "`document_ids` (2-50).",
10900
+ returns: "The new comparison with its id."
10901
+ }),
10902
+ route: "POST /v1/compliance/discrepancy-runs",
10903
+ inputSchema: { document_ids: docIds(2, 50, "The documents to compare.") },
10904
+ annotations: write9(false),
10905
+ body: ["document_ids"]
10906
+ },
10907
+ // ── Document sets ────────────────────────────────────────────────────────
10908
+ {
10909
+ name: "talonic_compliance_list_sets",
10910
+ title: "Compliance document sets",
10911
+ description: describe({
10912
+ what: "Document sets (documents judged as one whole, e.g. a contract with its annexes) with their documents and rule set.",
10913
+ use: "finding a set id, or checking which documents a set holds.",
10914
+ returns: "{ data[] } sets with id, name, documents, rule_set_id."
10915
+ }),
10916
+ route: "GET /v1/compliance/sets",
10917
+ inputSchema: {},
10918
+ annotations: READ
10919
+ },
10920
+ {
10921
+ name: "talonic_compliance_create_set",
10922
+ title: "Create a compliance document set",
10923
+ description: describe({
10924
+ what: "Create a document set picked by hand, judged against one rule set or, without one, every rule of the frameworks that are ON.",
10925
+ use: "documents only make sense together (a contract and its annexes).",
10926
+ args: "`name`, `document_ids` (2-100), `rule_set_id` (optional).",
10927
+ returns: "The new set."
10928
+ }),
10929
+ route: "POST /v1/compliance/sets",
10930
+ inputSchema: {
10931
+ name: z.string().min(1).max(200).describe("Set name."),
10932
+ document_ids: docIds(2, 100, "The set's documents."),
10933
+ rule_set_id: zUuid().nullable().optional().describe("Rule set to judge it against; omitted or null = every ON rule.")
10934
+ },
10935
+ annotations: write9(false),
10936
+ body: ["name", "document_ids", "rule_set_id"]
10937
+ },
10938
+ {
10939
+ name: "talonic_compliance_assembly_groups",
10940
+ title: "Groups to make compliance sets from",
10941
+ description: describe({
10942
+ 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.",
10943
+ use: "before talonic_compliance_create_sets_from_groups.",
10944
+ returns: "{ data[] } groups with pipeline_id, group_key and their documents."
10945
+ }),
10946
+ route: "GET /v1/compliance/sets/assembly-groups",
10947
+ inputSchema: {},
10948
+ annotations: READ
10949
+ },
10950
+ {
10951
+ name: "talonic_compliance_create_sets_from_groups",
10952
+ title: "Create compliance sets from groups",
10953
+ description: describe({
10954
+ what: "Create one document set per assembly group; the set follows the group as documents join it.",
10955
+ use: "every order (or case) should be judged as a whole.",
10956
+ args: "`groups[]` { pipeline_id, group_key } (1-100), `rule_set_id` (optional).",
10957
+ returns: "{ data[] } the new sets."
10958
+ }),
10959
+ route: "POST /v1/compliance/sets/from-assemblies",
10960
+ inputSchema: {
10961
+ 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."),
10962
+ rule_set_id: zUuid().nullable().optional().describe("Rule set to judge them against; omitted or null = every ON rule.")
10963
+ },
10964
+ annotations: write9(false),
10965
+ body: ["groups", "rule_set_id"]
10966
+ },
10967
+ {
10968
+ name: "talonic_compliance_update_set",
10969
+ title: "Edit a compliance document set",
10970
+ description: describe({
10971
+ what: "Rename a set, replace its documents (a group-following set becomes hand-picked) or change its rule set. Fields left out stay.",
10972
+ use: "a set is missing a document or should be judged against other rules.",
10973
+ args: "`set_id`, `name`, `document_ids` (2-100), `rule_set_id` (null = every ON rule).",
10974
+ returns: "The updated set."
10975
+ }),
10976
+ route: "PATCH /v1/compliance/sets/{setId}",
10977
+ inputSchema: {
10978
+ set_id: zUuid().describe("The set."),
10979
+ name: z.string().min(1).max(200).optional().describe("New set name."),
10980
+ document_ids: docIds(2, 100, "The set's documents (replaces them).").optional(),
10981
+ rule_set_id: zUuid().nullable().optional().describe("null = every ON rule; omitted = unchanged.")
10982
+ },
10983
+ annotations: write9(true),
10984
+ body: ["name", "document_ids", "rule_set_id"]
10985
+ },
10986
+ {
10987
+ name: "talonic_compliance_remove_set",
10988
+ title: "Remove a compliance document set",
10989
+ description: describe({
10990
+ what: "Remove a document set with its evaluations. The documents stay in the workspace.",
10991
+ use: "a set is no longer needed. Ask the user first.",
10992
+ args: "`set_id`.",
10993
+ returns: "Confirmation of the removal."
10994
+ }),
10995
+ route: "DELETE /v1/compliance/sets/{setId}",
10996
+ inputSchema: { set_id: zUuid().describe("The set.") },
10997
+ annotations: write9(true, true)
10998
+ },
10999
+ {
11000
+ name: "talonic_compliance_list_set_evaluations",
11001
+ title: "Compliance set evaluations",
11002
+ description: describe({
11003
+ 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.",
11004
+ use: "an overview of how every set fares.",
11005
+ args: "`status` processing|waiting|completed|error, `limit` 1-500, `offset`.",
11006
+ returns: "{ data[] } or a page { data[], total, has_more }."
11007
+ }),
11008
+ route: "GET /v1/compliance/sets/evaluations",
11009
+ inputSchema: pageArgs2,
11010
+ annotations: READ,
11011
+ query: ["status", "limit", "offset"]
11012
+ },
11013
+ {
11014
+ name: "talonic_compliance_get_set_evaluation",
11015
+ title: "One set's compliance evaluation",
11016
+ description: describe({
11017
+ what: "A set's latest evaluation with every result: verdict, reason, and the quote with the member document it comes from.",
11018
+ use: "the evidence behind a set's failed check.",
11019
+ args: "`set_id`.",
11020
+ returns: "{ evaluation } with its results; null when never evaluated."
11021
+ }),
11022
+ route: "GET /v1/compliance/sets/{setId}/evaluation",
11023
+ inputSchema: { set_id: zUuid().describe("The set.") },
11024
+ annotations: READ
11025
+ },
11026
+ {
11027
+ name: "talonic_compliance_evaluate_sets",
11028
+ title: "Evaluate compliance document sets",
11029
+ description: describe({
11030
+ what: "Evaluate document sets, each as one whole, against their rule set. Runs in the background.",
11031
+ use: "a set changed or its verdicts are outdated.",
11032
+ args: "`set_ids` (1-100).",
11033
+ returns: "{ data[] } one started evaluation per set."
11034
+ }),
11035
+ route: "POST /v1/compliance/sets/evaluate",
11036
+ inputSchema: { set_ids: z.array(zUuid()).min(1).max(100).describe("Sets to evaluate.") },
11037
+ annotations: write9(false),
11038
+ body: ["set_ids"]
11039
+ },
11040
+ // ── Rule sets ────────────────────────────────────────────────────────────
11041
+ {
11042
+ name: "talonic_compliance_list_rule_sets",
11043
+ title: "Compliance rule sets",
11044
+ description: describe({
11045
+ what: "The workspace's rule sets: named selections of rules of the ON frameworks that a document set is judged against.",
11046
+ use: "finding a rule_set_id for a set.",
11047
+ returns: "{ data[] } rule sets with id, name, rule_ids."
11048
+ }),
11049
+ route: "GET /v1/compliance/rule-sets",
11050
+ inputSchema: {},
11051
+ annotations: READ
11052
+ },
11053
+ {
11054
+ name: "talonic_compliance_create_rule_set",
11055
+ title: "Create a compliance rule set",
11056
+ description: describe({
11057
+ what: "Create a named selection of rules (from talonic_compliance_framework_rules) to judge document sets against.",
11058
+ use: "only some rules apply to a kind of document set.",
11059
+ args: "`name`, `rule_ids` (1-1000).",
11060
+ returns: "The new rule set."
11061
+ }),
11062
+ route: "POST /v1/compliance/rule-sets",
11063
+ inputSchema: {
11064
+ name: z.string().min(1).max(200).describe("Rule set name."),
11065
+ rule_ids: z.array(zUuid()).min(1).max(1e3).describe("Rules of ON frameworks.")
11066
+ },
11067
+ annotations: write9(false),
11068
+ body: ["name", "rule_ids"]
11069
+ },
11070
+ {
11071
+ name: "talonic_compliance_update_rule_set",
11072
+ title: "Change a compliance rule set",
11073
+ description: describe({
11074
+ what: "Rename a rule set or replace its rules.",
11075
+ use: "a rule should be added to or dropped from what sets are judged against.",
11076
+ args: "`rule_set_id`, `name`, `rule_ids` (1-1000, replaces them).",
11077
+ returns: "The updated rule set."
11078
+ }),
11079
+ route: "PATCH /v1/compliance/rule-sets/{ruleSetId}",
11080
+ inputSchema: {
11081
+ rule_set_id: zUuid(),
11082
+ name: z.string().min(1).max(200).optional().describe("New rule set name."),
11083
+ rule_ids: z.array(zUuid()).min(1).max(1e3).optional().describe("The rules (replaces them).")
11084
+ },
11085
+ annotations: write9(true),
11086
+ body: ["name", "rule_ids"]
11087
+ },
11088
+ {
11089
+ name: "talonic_compliance_remove_rule_set",
11090
+ title: "Remove a compliance rule set",
11091
+ description: describe({
11092
+ what: "Remove a rule set. Sets that used it go back to every rule of the ON frameworks.",
11093
+ use: "a rule set is no longer needed. Ask the user first.",
11094
+ args: "`rule_set_id`.",
11095
+ returns: "Confirmation of the removal."
11096
+ }),
11097
+ route: "DELETE /v1/compliance/rule-sets/{ruleSetId}",
11098
+ inputSchema: { rule_set_id: zUuid() },
11099
+ annotations: write9(true, true)
11100
+ },
11101
+ // ── Who decides; the workspace agent's tasks ─────────────────────────────
11102
+ {
11103
+ name: "talonic_compliance_settings",
11104
+ title: "Who makes compliance decisions",
11105
+ description: describe({
11106
+ 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).",
11107
+ use: "before working the task tools, or explaining why verdicts wait.",
11108
+ returns: "{ decider: platform | external }."
11109
+ }),
11110
+ route: "GET /v1/compliance/settings",
11111
+ inputSchema: {},
11112
+ annotations: READ
11113
+ },
11114
+ {
11115
+ name: "talonic_compliance_set_decider",
11116
+ title: "Switch who makes compliance decisions",
11117
+ description: describe({
11118
+ 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.",
11119
+ use: "the user explicitly asks to hand decisions to their own agent, or back.",
11120
+ args: "`decider` platform|external.",
11121
+ returns: "The new setting.",
11122
+ errors: "403 without the Workspace settings permission."
11123
+ }),
11124
+ route: "PUT /v1/compliance/settings",
11125
+ inputSchema: {
11126
+ decider: z.enum(["platform", "external"]).describe("platform = Talonic decides; external = the workspace's own agent.")
11127
+ },
11128
+ annotations: write9(true),
11129
+ body: ["decider"]
11130
+ },
11131
+ {
11132
+ name: "talonic_compliance_list_tasks",
11133
+ title: "Compliance tasks for the workspace's agent",
11134
+ description: describe({
11135
+ what: "Decisions waiting for the workspace's own agent (only when the decider is external).",
11136
+ use: "an agent working the compliance decisions: pick a task, then talonic_compliance_claim_task.",
11137
+ args: "`status` open (default) | all, `limit` (default 100).",
11138
+ returns: "{ data[] } tasks with id, status, document or set, and lease state."
11139
+ }),
11140
+ route: "GET /v1/compliance/tasks",
11141
+ inputSchema: {
11142
+ status: z.enum(["open", "all"]).optional().describe("open (default) or all."),
11143
+ limit: z.number().int().min(1).max(1e3).optional().describe("Most tasks returned (default 100).")
11144
+ },
11145
+ annotations: READ,
11146
+ query: ["status", "limit"]
11147
+ },
11148
+ {
11149
+ name: "talonic_compliance_get_task",
11150
+ title: "One compliance task",
11151
+ description: describe({
11152
+ what: "One task's state (open, claimed, done) without its work package.",
11153
+ use: "checking a task before or after claiming it.",
11154
+ args: "`task_id`.",
11155
+ returns: "The task."
11156
+ }),
11157
+ route: "GET /v1/compliance/tasks/{taskId}",
11158
+ inputSchema: { task_id: zUuid() },
11159
+ annotations: READ
11160
+ },
11161
+ {
11162
+ name: "talonic_compliance_claim_task",
11163
+ title: "Claim a compliance task",
11164
+ description: describe({
11165
+ 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.",
11166
+ use: "starting work on one task from talonic_compliance_list_tasks.",
11167
+ args: "`task_id`.",
11168
+ returns: "{ task (with execution_epoch and the lease), instructions, input, output_schema, how_to_answer }. Keep execution_epoch for every later call.",
11169
+ errors: "409 when another agent holds the claim, the task is closed or not ready yet."
11170
+ }),
11171
+ route: "POST /v1/compliance/tasks/{taskId}/claim",
11172
+ inputSchema: { task_id: zUuid() },
11173
+ annotations: write9(false)
11174
+ },
11175
+ {
11176
+ name: "talonic_compliance_heartbeat_task",
11177
+ title: "Renew a compliance task claim",
11178
+ description: describe({
11179
+ what: "Renew the lease on a claimed task.",
11180
+ use: "work on a claimed task takes longer than its lease.",
11181
+ args: "`task_id`, `execution_epoch`.",
11182
+ returns: "The new lease expiry.",
11183
+ errors: "409 when the claim lapsed or was taken over (stop working on it)."
11184
+ }),
11185
+ route: "POST /v1/compliance/tasks/{taskId}/heartbeat",
11186
+ inputSchema: { task_id: zUuid(), execution_epoch: epoch },
11187
+ annotations: write9(true),
11188
+ body: ["execution_epoch"]
11189
+ },
11190
+ {
11191
+ name: "talonic_compliance_release_task",
11192
+ title: "Hand a compliance task back",
11193
+ description: describe({
11194
+ what: "Hand a claimed task back unanswered; it is open again for any agent.",
11195
+ use: "the agent cannot decide the task.",
11196
+ args: "`task_id`, `execution_epoch`.",
11197
+ returns: "The task, open again."
11198
+ }),
11199
+ route: "POST /v1/compliance/tasks/{taskId}/release",
11200
+ inputSchema: { task_id: zUuid(), execution_epoch: epoch },
11201
+ annotations: write9(true),
11202
+ body: ["execution_epoch"]
11203
+ },
11204
+ {
11205
+ name: "talonic_compliance_submit_task",
11206
+ title: "Answer a compliance task",
11207
+ description: describe({
11208
+ 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.",
11209
+ use: "the agent has decided a claimed task.",
11210
+ args: "`task_id`, `execution_epoch`, `answer` (an object matching output_schema).",
11211
+ returns: "{ task, result }.",
11212
+ 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)."
11213
+ }),
11214
+ route: "POST /v1/compliance/tasks/{taskId}/submit",
11215
+ inputSchema: {
11216
+ task_id: zUuid(),
11217
+ execution_epoch: epoch,
11218
+ answer: z.record(z.string(), z.unknown()).describe("The answer, matching the package's output_schema.")
11219
+ },
11220
+ annotations: write9(false),
11221
+ body: ["execution_epoch", "answer"]
11222
+ }
11223
+ ];
11224
+ var complianceGroup = {
11225
+ key: "compliance",
11226
+ label: "Compliance",
11227
+ docsSlug: "compliance-tools",
11228
+ probe: { path: "/v1/compliance/settings" },
11229
+ tools
11230
+ };
11231
+ var paging = {
11232
+ page: z.number().int().min(1).max(1e6).optional().describe("Page number, from 1."),
11233
+ limit: z.number().int().min(1).optional().describe("Rows per page (the desk caps it).")
11234
+ };
11235
+ var key = (what) => z.string().min(1).max(2e3).describe(`${what} as the desk lists it (no control characters).`);
11236
+ var team = z.string().max(2e3).optional().describe("One team's work only; all teams when left out.");
11237
+ var contractDeskGroup = {
11238
+ key: "contract_desk",
11239
+ label: "Contract Desk",
11240
+ docsSlug: "contract-desk-tools",
11241
+ probe: { path: "/v1/contract-desk/status" },
11242
+ tools: [
11243
+ {
11244
+ name: "talonic_contract_desk_status",
11245
+ title: "Contract Desk status",
11246
+ description: describe({
11247
+ 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.",
11248
+ use: "first call of a session, or after talonic_contract_desk_refresh to see it finish.",
11249
+ not: "the work itself (talonic_contract_desk_todo).",
11250
+ returns: "the desk's state: last refresh time and outcome, a running refresh, counts."
11251
+ }),
11252
+ route: "GET /v1/contract-desk/status",
11253
+ inputSchema: {},
11254
+ annotations: READ
11255
+ },
11256
+ {
11257
+ name: "talonic_contract_desk_refresh",
11258
+ title: "Refresh the Contract Desk",
11259
+ description: describe({
11260
+ 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.",
11261
+ use: "the source apps changed (new contracts, decisions made elsewhere) and the desk should show it before the next scheduled refresh.",
11262
+ not: "reading anything (every read tool shows the last refresh).",
11263
+ returns: "the refresh that was started (or the one already running)."
11264
+ }),
11265
+ route: "POST /v1/contract-desk/rebuild",
11266
+ inputSchema: {},
11267
+ annotations: write9(true)
11268
+ },
11269
+ {
11270
+ name: "talonic_contract_desk_sites",
11271
+ title: "Contract Desk sites",
11272
+ description: describe({
11273
+ what: "One page of sites with their contracts and open work, and the counts of the three filters.",
11274
+ use: "finding a site by number or name, or listing the sites with work due now or without documents.",
11275
+ not: "one site's contracts and items (talonic_contract_desk_get_site).",
11276
+ args: "`q` (words that must each occur in the site's number, name, contracts or partners), `filter` all|now|nodoc, `page`, `limit`.",
11277
+ returns: "{ data[] sites, total, page, limit, counts { all, now, nodoc } }."
11278
+ }),
11279
+ route: "GET /v1/contract-desk/sites",
11280
+ inputSchema: {
11281
+ q: z.string().max(500).optional().describe("Search words."),
11282
+ filter: z.enum(["all", "now", "nodoc"]).optional().describe("all, now (work due now) or nodoc (no documents)."),
11283
+ ...paging
11284
+ },
11285
+ annotations: READ,
11286
+ query: ["q", "filter", "page", "limit"]
11287
+ },
11288
+ {
11289
+ name: "talonic_contract_desk_get_site",
11290
+ title: "One Contract Desk site",
11291
+ description: describe({
11292
+ what: "One site with its contracts and its site-level items.",
11293
+ use: "the user names a site, or after talonic_contract_desk_sites.",
11294
+ not: "one contract's values (talonic_contract_desk_get_contract).",
11295
+ args: "`key` the site key from talonic_contract_desk_sites.",
11296
+ returns: "the site, its contracts and its open items. 404 when the desk holds no such site."
11297
+ }),
11298
+ route: "GET /v1/contract-desk/sites/{key}",
11299
+ inputSchema: { key: key("The site key") },
11300
+ annotations: READ
11301
+ },
11302
+ {
11303
+ name: "talonic_contract_desk_contracts",
11304
+ title: "Contract Desk contracts",
11305
+ description: describe({
11306
+ what: "One page of contracts, searchable, for one partner or one site.",
11307
+ use: "finding a contract by number, name, partner, site or type.",
11308
+ not: "one contract's items and values (talonic_contract_desk_get_contract).",
11309
+ 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`.",
11310
+ returns: "{ data[] contracts (crm_key, number, partner, site, type, open items), total, page, limit }."
11311
+ }),
11312
+ route: "GET /v1/contract-desk/contracts",
11313
+ inputSchema: {
11314
+ q: z.string().max(500).optional().describe("Search words."),
11315
+ partner: z.string().max(2e3).optional().describe("A partner_key, matched exactly."),
11316
+ site: z.string().max(2e3).optional().describe("A site key, matched exactly."),
11317
+ ...paging
11318
+ },
11319
+ annotations: READ,
11320
+ query: ["q", "partner", "site", "page", "limit"]
11321
+ },
11322
+ {
11323
+ name: "talonic_contract_desk_get_contract",
11324
+ title: "One Contract Desk contract",
11325
+ description: describe({
11326
+ what: "One contract with its items and values: where the documents and the CRM agree or differ, and what is open.",
11327
+ use: "the evidence for a contract, or before deciding several items on one contract.",
11328
+ not: "the decision screen of one item (talonic_contract_desk_get_decision).",
11329
+ args: "`id` the contract's crm_key.",
11330
+ returns: "the contract with its values, items and documents. 404 when the desk holds no such contract."
11331
+ }),
11332
+ route: "GET /v1/contract-desk/contracts/{id}",
11333
+ inputSchema: { id: key("The contract's crm_key") },
11334
+ annotations: READ
11335
+ },
11336
+ {
11337
+ name: "talonic_contract_desk_dashboard",
11338
+ title: "Contract Desk dashboard",
11339
+ description: describe({
11340
+ 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.",
11341
+ use: "the headline ('how much is open, what is due this week, which team is behind').",
11342
+ not: "the items themselves (talonic_contract_desk_todo).",
11343
+ args: "`team` (optional).",
11344
+ returns: "the dashboard figures for the team, or all teams."
11345
+ }),
11346
+ route: "GET /v1/contract-desk/dashboard",
11347
+ inputSchema: { team },
11348
+ annotations: READ,
11349
+ query: ["team"]
11350
+ },
11351
+ {
11352
+ name: "talonic_contract_desk_quality",
11353
+ title: "Contract Desk data quality",
11354
+ description: describe({
11355
+ 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.",
11356
+ use: "a data quality question across the contract portfolio.",
11357
+ not: "one contract's values (talonic_contract_desk_get_contract).",
11358
+ returns: "the quality figures."
11359
+ }),
11360
+ route: "GET /v1/contract-desk/quality",
11361
+ inputSchema: {},
11362
+ annotations: READ
11363
+ },
11364
+ {
11365
+ name: "talonic_contract_desk_todo",
11366
+ title: "Contract Desk to do list",
11367
+ description: describe({
11368
+ 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.",
11369
+ use: "starting work: pick a batch, then list its items with talonic_contract_desk_todo_items.",
11370
+ not: "one batch's items (talonic_contract_desk_todo_items).",
11371
+ args: "`team` (optional).",
11372
+ returns: "{ sections[] { section, count, batches[] { key, team, kind, count, \u2026 }, more }, decided_today, \u2026 }."
11373
+ }),
11374
+ route: "GET /v1/contract-desk/todo",
11375
+ inputSchema: { team },
11376
+ annotations: READ,
11377
+ query: ["team"]
11378
+ },
11379
+ {
11380
+ name: "talonic_contract_desk_todo_items",
11381
+ title: "Items of a Contract Desk batch",
11382
+ description: describe({
11383
+ what: "One page of the open items of a batch from the To do list.",
11384
+ use: "after talonic_contract_desk_todo, to get the item ids to open and decide.",
11385
+ not: "the evidence of one item (talonic_contract_desk_get_decision).",
11386
+ args: "`batch` (the batch key from talonic_contract_desk_todo, unchanged), `page`, `limit`.",
11387
+ 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."
11388
+ }),
11389
+ route: "GET /v1/contract-desk/todo/items",
11390
+ inputSchema: {
11391
+ batch: z.string().min(1).max(2e3).describe("The batch key from talonic_contract_desk_todo."),
11392
+ ...paging
11393
+ },
11394
+ annotations: READ,
11395
+ query: ["batch", "page", "limit"]
11396
+ },
11397
+ {
11398
+ name: "talonic_contract_desk_get_decision",
11399
+ title: "Evidence for one Contract Desk item",
11400
+ description: describe({
11401
+ 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.",
11402
+ use: "before talonic_contract_desk_decide, to show the user the evidence and the allowed actions.",
11403
+ not: "decided items (talonic_contract_desk_decisions).",
11404
+ args: "`id` the item id.",
11405
+ 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."
11406
+ }),
11407
+ route: "GET /v1/contract-desk/items/{id}/decision",
11408
+ inputSchema: { id: zUuid().describe("The item id.") },
11409
+ annotations: READ
11410
+ },
11411
+ {
11412
+ name: "talonic_contract_desk_decide",
11413
+ title: "Decide a Contract Desk item",
11414
+ description: describe({
11415
+ 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.",
11416
+ use: "the user chose what an item should be after seeing talonic_contract_desk_get_decision.",
11417
+ not: "accepting a colleague's suggestion (done by a person in the app); changing teams (talonic_contract_desk_save_settings).",
11418
+ 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`.",
11419
+ returns: "{ status decided|suggested, dry_run, decision_id (null on a dry run), undoable, crm_report update|missing|null, revision }.",
11420
+ 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."
11421
+ }),
11422
+ route: "POST /v1/contract-desk/items/{id}/decide",
11423
+ inputSchema: {
11424
+ id: zUuid().describe("The item id."),
11425
+ action: z.enum(["set", "crm_add", "handled", "notice_sent", "renewal_declined", "terminated"]).describe(
11426
+ "What to do; talonic_contract_desk_get_decision lists the ones this item offers."
11427
+ ),
11428
+ value: z.string().optional().describe("The value to record; only with action set."),
11429
+ note: z.string().optional().describe("Why, in a few words."),
11430
+ dry_run: z.boolean().optional().describe("Preview only; nothing is recorded.")
11431
+ },
11432
+ annotations: write9(false),
11433
+ body: ["action", "value", "note", "dry_run"]
11434
+ },
11435
+ {
11436
+ name: "talonic_contract_desk_decisions",
11437
+ title: "Contract Desk decisions",
11438
+ description: describe({
11439
+ 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.",
11440
+ use: "reviewing what was decided, finding a decision to undo, or one contract's history.",
11441
+ not: "open items (talonic_contract_desk_todo).",
11442
+ args: "`mine` (only this connection's person), `crm_key` (one contract), `page`, `limit`.",
11443
+ returns: "{ data[] { id, at, by_name, mine, kind, action, value, note, status, item, contract, undoable, undone_at }, total, page, limit, today }."
11444
+ }),
11445
+ route: "GET /v1/contract-desk/decisions",
11446
+ inputSchema: {
11447
+ mine: z.boolean().optional().describe("Only the decisions of this connection's person."),
11448
+ crm_key: z.string().max(2e3).optional().describe("One contract's decisions."),
11449
+ ...paging
11450
+ },
11451
+ annotations: READ,
11452
+ query: ["mine", "crm_key", "page", "limit"]
11453
+ },
11454
+ {
11455
+ name: "talonic_contract_desk_undo",
11456
+ title: "Undo a Contract Desk decision",
11457
+ description: describe({
11458
+ 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.",
11459
+ use: "a decision was wrong; the id comes from talonic_contract_desk_decide (decision_id) or talonic_contract_desk_decisions.",
11460
+ not: "deciding again (talonic_contract_desk_decide after the undo).",
11461
+ args: "`id` the decision id.",
11462
+ returns: "the decision with undone_at set. 409 not_undoable otherwise."
11463
+ }),
11464
+ route: "POST /v1/contract-desk/decisions/{id}/undo",
11465
+ inputSchema: { id: zUuid().describe("The decision id.") },
11466
+ annotations: write9(false)
11467
+ },
11468
+ {
11469
+ name: "talonic_contract_desk_settings",
11470
+ title: "Contract Desk team setup",
11471
+ description: describe({
11472
+ 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.",
11473
+ use: "before changing the setup, or to explain why an item went to a team.",
11474
+ not: "changing it (talonic_contract_desk_save_settings).",
11475
+ returns: "{ teams { kinds, fields }, defaults, choices { teams, kinds }, attributes[] }."
11476
+ }),
11477
+ route: "GET /v1/contract-desk/settings",
11478
+ inputSchema: {},
11479
+ annotations: READ
11480
+ },
11481
+ {
11482
+ name: "talonic_contract_desk_save_settings",
11483
+ title: "Change the Contract Desk team setup",
11484
+ description: describe({
11485
+ what: "Replace the whole team setup (the team per item kind and per attribute) and refresh the desk. Needs an Admin of the workspace.",
11486
+ use: "the user wants items routed to other teams. Read talonic_contract_desk_settings, change it, send it whole.",
11487
+ not: "partial edits: kinds and fields left out lose their team.",
11488
+ args: "`teams` { kinds { <kind>: <team> } for value, documents_missing, site_check, text_check, deadline; fields { <field_key>: <team> } }.",
11489
+ returns: "the saved setup. 400 for an unknown kind or team."
11490
+ }),
11491
+ route: "PUT /v1/contract-desk/settings",
11492
+ inputSchema: {
11493
+ teams: z.object({
11494
+ kinds: z.record(z.string(), z.string()).describe("<kind>: <team>."),
11495
+ fields: z.record(z.string(), z.string()).describe("<field_key>: <team>.")
11496
+ }).describe("The whole team setup.")
11497
+ },
11498
+ annotations: write9(true),
11499
+ body: ["teams"]
11500
+ }
11501
+ ]
11502
+ };
11503
+ var pipelineId2 = zUuid().optional().describe("The pipeline (talonic_customs_declaration_pipelines); default: the workspace's first.");
11504
+ var customsDeclarationGroup = {
11505
+ key: "customs_declaration",
11506
+ label: "Customs declaration",
11507
+ docsSlug: "customs-declaration-tools",
11508
+ probe: { path: "/v1/customs-declaration/pipelines" },
11509
+ tools: [
11510
+ {
11511
+ name: "talonic_customs_declaration_pipelines",
11512
+ title: "Customs declaration pipelines",
11513
+ description: describe({
11514
+ what: "The pipelines whose Spec compares transport documents with a filed customs declaration.",
11515
+ use: "finding the pipeline_id the other customs tools take, when the workspace has more than one.",
11516
+ returns: "{ data[] } pipelines with id and name."
11517
+ }),
11518
+ route: "GET /v1/customs-declaration/pipelines",
11519
+ inputSchema: {},
11520
+ annotations: READ
11521
+ },
11522
+ {
11523
+ name: "talonic_customs_declaration_issues",
11524
+ title: "Customs declaration worklist",
11525
+ description: describe({
11526
+ 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.",
11527
+ use: "'which declarations are not ready to file', the starting point before opening an order.",
11528
+ not: "every order including ready ones (talonic_customs_declaration_orders).",
11529
+ args: "`pipeline_id` (optional).",
11530
+ returns: "{ pipeline, read, available, truncated, data[] { lrn, record_document_id, sender, receiver, checks[] { id, message, fields }, differs[] } }. truncated = more orders exist than were read."
11531
+ }),
11532
+ route: "GET /v1/customs-declaration/issues",
11533
+ inputSchema: { pipeline_id: pipelineId2 },
11534
+ annotations: READ,
11535
+ query: ["pipeline_id"]
11536
+ },
11537
+ {
11538
+ name: "talonic_customs_declaration_orders",
11539
+ title: "Customs declaration orders",
11540
+ description: describe({
11541
+ 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.",
11542
+ use: "retrieving the evidence behind an issue (filter with `q` = its LRN), or listing orders ready to file.",
11543
+ args: "`pipeline_id`, `status` ready|review, `q` (LRN, sender, receiver or plates contains), `page` and `limit` (1-200; either asks for one page).",
11544
+ returns: "{ pipeline, read, available, items[] { lrn, ready, sender, receiver, plates, record_document_id, comparison[], checks[] }, page? { page, limit, total, filtered } }."
11545
+ }),
11546
+ route: "GET /v1/customs-declaration/declarations",
11547
+ inputSchema: {
11548
+ pipeline_id: pipelineId2,
11549
+ status: z.enum(["ready", "review"]).optional().describe("ready = every check passes; review = at least one fails."),
11550
+ q: z.string().max(200).optional().describe("LRN, sender, receiver or plates contains."),
11551
+ page: z.number().int().min(1).optional().describe("Page number (asks for one page)."),
11552
+ limit: z.number().int().min(1).max(200).optional().describe("Orders per page, at most 200 (default 50).")
11553
+ },
11554
+ annotations: READ,
11555
+ query: ["pipeline_id", "status", "q", "page", "limit"]
11556
+ }
11557
+ ]
11558
+ };
11559
+ var cursorArgs = {
11560
+ limit: z.number().int().min(1).max(100).optional().describe("Items per page (1-100, default 20)."),
11561
+ cursor: z.string().max(512).optional().describe("pagination.next_cursor of the previous page."),
11562
+ order: z.enum(["asc", "desc"]).optional().describe("By creation time; default desc (newest first)."),
11563
+ after: z.string().optional().describe("Only items created after this ISO-8601 timestamp."),
11564
+ before: z.string().optional().describe("Only items created before this ISO-8601 timestamp.")
11565
+ };
11566
+ var PAGE_QUERY = ["limit", "cursor", "order", "after", "before"];
11567
+ var PAGE_RETURNS = "pagination { total, limit, has_more, next_cursor }";
11568
+ var LIST_DOCUMENTS = describe({
11569
+ what: "List the workspace's documents, newest first, one page at a time, with filters. Only documents this connection may see are listed.",
11570
+ use: "browsing or counting documents by status, source, upload time or filename (e.g. 'which uploads failed today', 'the attachments of this email').",
11571
+ not: "finding documents by their content or a field value (talonic_search, talonic_filter); one document's details (talonic_get_document).",
11572
+ 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.",
11573
+ returns: `{ data[] { id, filename, pages, size_bytes, mime_type, type_detected, status, error?, source { id, type }, parent?, field_count, created_at, links }, ${PAGE_RETURNS} }.`
11574
+ });
11575
+ var REEXTRACT = describe({
11576
+ 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.",
11577
+ use: "the user asks to redo a document after its schema or setup changed, or a document came out wrong.",
11578
+ 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).",
11579
+ args: "`document_id` (UUID).",
11580
+ 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.",
11581
+ errors: "402 out of credits; 404 the document does not exist or this connection may not see it."
11582
+ });
11583
+ var DELETE_DOCUMENT = describe({
11584
+ what: "Delete one document from the workspace together with its captured values. Cannot be undone.",
11585
+ 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.",
11586
+ not: "hiding a document from a list or retagging it; deleting many documents at once without the user naming them.",
11587
+ args: "`document_id` (UUID).",
11588
+ returns: "{ deleted: true, id }.",
11589
+ 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)."
11590
+ });
11591
+ var LIST_EXTRACTIONS = describe({
11592
+ what: "List extractions (one per document that has captured values), newest first, one page at a time.",
11593
+ use: "finding the documents with completed or failed captures in a time range, or the extraction of one document.",
11594
+ not: "the values of one extraction (talonic_get_extraction_data); searching by value (talonic_filter).",
11595
+ args: "`document_id` (UUID), `status` complete|failed, `after` / `before` (ISO-8601), `limit` 1-100, `cursor`, `order`.",
11596
+ returns: `{ data[] { id, document_id, status, field_count, created_at, links }, ${PAGE_RETURNS} }. An extraction's id equals its document's id.`
11597
+ });
11598
+ var GET_EXTRACTION = describe({
11599
+ what: "One extraction in full: its fields with values, types and confidence, and the document it belongs to.",
11600
+ use: "inspecting how a document's values were captured before correcting them.",
11601
+ not: "just the field \u2192 value map (talonic_get_extraction_data).",
11602
+ args: "`extraction_id` (UUID; the document id).",
11603
+ returns: "The extraction with its fields, confidence and links."
11604
+ });
11605
+ var GET_EXTRACTION_DATA = describe({
11606
+ what: "One extraction's values as a flat field \u2192 value map (JSON), or as a one-row CSV.",
11607
+ use: "handing a document's captured values to another system or comparing them with a source.",
11608
+ not: "confidence and field metadata (talonic_get_extraction); values across many documents (talonic_field_values).",
11609
+ args: "`extraction_id` (UUID; the document id), `format` json|csv (default json).",
11610
+ returns: "JSON: { <field>: value }. CSV: { format: 'csv', csv } (header row plus one value row)."
11611
+ });
11612
+ var CORRECT_EXTRACTION = describe({
11613
+ 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.",
11614
+ use: "the user tells you a captured value is wrong and gives the right one.",
11615
+ not: "changing which fields a schema has (talonic_update_schema); re-reading the whole document (talonic_reextract_document).",
11616
+ args: "`extraction_id` (UUID; the document id), `values` { <field_name>: corrected value } (only the fields to change).",
11617
+ returns: "The extraction, plus cells_written[] and cells_skipped[] (the corrections that were withheld, with why).",
11618
+ errors: "400 `values` is not an object; 403 a workspace-wide (master view) credential; 404 unknown or not visible."
11619
+ });
11620
+ var LIST_JOBS = describe({
11621
+ what: "List jobs (a schema run over a set of documents), newest first, one page at a time.",
11622
+ use: "checking what jobs exist, which are still running, or finding a job id.",
11623
+ not: "Spec runs (talonic_get_run); one job (talonic_get_job).",
11624
+ args: "`status` (e.g. pending, processing, completed, failed), `after` / `before` (ISO-8601), `limit` 1-100, `cursor`, `order`.",
11625
+ returns: `{ data[] { id, name, status, schema, document_count, created_at, completed_at, links }, ${PAGE_RETURNS} }.`
11626
+ });
11627
+ var GET_JOB = describe({
11628
+ what: "One job: status, progress, schema, timestamps, error if it failed.",
11629
+ use: "polling a job created with talonic_create_job until it completes.",
11630
+ not: "the job's extracted rows (talonic_get_job_results).",
11631
+ args: "`job_id` (UUID).",
11632
+ returns: "{ id, name, status, schema, document_count, created_at, completed_at, error?, links }."
11633
+ });
11634
+ var GET_JOB_RESULTS = describe({
11635
+ 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.",
11636
+ use: "reading what a job extracted, e.g. to build a table or check a few values.",
11637
+ not: "one document's values (talonic_get_extraction_data).",
11638
+ args: "`job_id` (UUID).",
11639
+ returns: "{ job_id, job_status, schema { id, name }, total_rows, data[] { id, document_id, filename, status, values, confidence, validation_flags } }."
11640
+ });
11641
+ var CREATE_JOB = describe({
11642
+ 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.",
11643
+ use: "the user wants the same fields pulled from many existing documents into one table.",
11644
+ not: "one document (talonic_extract with document_id); running a configured Spec (talonic_run_spec).",
11645
+ 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).",
11646
+ 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.",
11647
+ errors: "400 no completed documents; 402 out of credits; 404 unknown schema."
11648
+ });
11649
+ var CANCEL_JOB = describe({
11650
+ what: "Cancel a pending or running job. Documents already processed keep their rows; the job ends as failed with the error 'Cancelled via API'.",
11651
+ use: "the user wants to stop a job (wrong schema, wrong documents, too expensive).",
11652
+ args: "`job_id` (UUID).",
11653
+ returns: "The job with status failed. Safe to retry: a job that already ended (completed, failed or cancelled) answers 409 and is left unchanged.",
11654
+ errors: "404 unknown job; 409 the job already ended."
11655
+ });
11656
+ var UPDATE_SCHEMA = describe({
11657
+ 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.",
11658
+ use: "the user wants to add, remove or retype fields of a saved schema, or rename it.",
11659
+ not: "creating a schema (talonic_save_schema); a schema managed by a Spec (refused with 409; change the Spec in the app instead).",
11660
+ 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? }.",
11661
+ returns: "The schema with its fields as a JSON Schema definition.",
11662
+ errors: "404 unknown schema; 409 the schema is managed by a Spec."
11663
+ });
11664
+ var DELETE_SCHEMA = describe({
11665
+ what: "Delete a saved schema. Cannot be undone. Documents already extracted with it keep their values.",
11666
+ use: "the user explicitly asks to remove a specific schema. Confirm the schema's name with the user before calling.",
11667
+ not: "a schema managed by a Spec (refused with 409).",
11668
+ args: "`schema_id` (UUID or SCH-\u2026 short id).",
11669
+ returns: "{ deleted: true, id }.",
11670
+ errors: "404 unknown schema; 409 the schema is managed by a Spec."
11671
+ });
11672
+ var documentId = { document_id: zUuid().describe("The document id.") };
11673
+ var extractionId = {
11674
+ extraction_id: zUuid().describe("The extraction id (the same as its document's id).")
11675
+ };
11676
+ var jobId = { job_id: zUuid().describe("The job id.") };
11677
+ var schemaId = {
11678
+ schema_id: z.string().min(1).max(64).describe("The schema's UUID or SCH-XXXXXXXX short id.")
11679
+ };
11680
+ var schemaFieldSchema = z.object({
11681
+ field_name: z.string().min(1).describe("Machine name of the field."),
11682
+ display_name: z.string().optional(),
11683
+ data_type: z.string().optional().describe("string (default), number, boolean, date, \u2026"),
11684
+ description: z.string().optional(),
11685
+ is_required: z.boolean().optional()
11686
+ });
11687
+ var getExtractionData = {
11688
+ name: "talonic_get_extraction_data",
11689
+ title: "One extraction's values",
11690
+ description: GET_EXTRACTION_DATA,
11691
+ route: "GET /v1/extractions/{extractionId}/data",
11692
+ inputSchema: {
11693
+ ...extractionId,
11694
+ format: z.enum(["json", "csv"]).optional().describe("json (default) or csv.")
11695
+ },
11696
+ annotations: READ,
11697
+ handler: async (ctx, args) => {
11698
+ const id = args["extraction_id"];
11699
+ if (args["format"] !== "csv") {
11700
+ return runGroupTool({ ...getExtractionData, handler: void 0 }, ctx, args);
11701
+ }
11702
+ return runTool(async () => {
11703
+ const url = buildUrl(ctx.baseUrl, `/v1/extractions/${encodeURIComponent(String(id))}/data`, {
11704
+ format: "csv"
11705
+ });
11706
+ const res = await resolveFetch(ctx.getToken)(url, {
11707
+ method: "GET",
11708
+ headers: { Authorization: `Bearer ${ctx.getToken()}`, Accept: "text/csv" }
11709
+ });
11710
+ if (!res.ok) throw await apiHttpError(res);
11711
+ return { format: "csv", csv: await res.text() };
11712
+ });
11713
+ }
11714
+ };
11715
+ var createJob = {
11716
+ name: "talonic_create_job",
11717
+ title: "Create a job over documents",
11718
+ description: CREATE_JOB,
11719
+ route: "POST /v1/jobs",
11720
+ inputSchema: {
11721
+ schema_id: zUuid().describe("UUID of the saved schema to run."),
11722
+ document_ids: z.array(zUuid()).min(1).max(1e4).optional().describe("The documents to process."),
11723
+ all_documents: z.boolean().optional().describe("true: every completed document of the workspace (instead of document_ids)."),
11724
+ name: z.string().max(200).optional().describe("A name for the job.")
11725
+ },
11726
+ annotations: write9(false),
11727
+ body: ["schema_id", "document_ids", "name"],
11728
+ handler: (ctx, args) => {
11729
+ const ids = args["document_ids"];
11730
+ const all = args["all_documents"] === true;
11731
+ if (ids?.length && all) {
11732
+ return Promise.resolve(
11733
+ validationError("pass `document_ids` or `all_documents: true`, not both.")
11734
+ );
11735
+ }
11736
+ if (!ids?.length && !all) {
11737
+ return Promise.resolve(
11738
+ validationError(
11739
+ "name the documents (`document_ids`) or pass `all_documents: true` to run over every completed document."
11740
+ )
11741
+ );
11742
+ }
11743
+ return runGroupTool({ ...createJob, handler: void 0 }, ctx, args);
11744
+ }
11745
+ };
11746
+ var dataManagementGroup = {
11747
+ key: "data_management",
11748
+ label: "Documents, extractions, jobs and schemas",
11749
+ docsSlug: "data-management-tools",
11750
+ probe: { path: "/v1/documents", params: { limit: 1 } },
11751
+ tools: [
11752
+ {
11753
+ name: "talonic_list_documents",
11754
+ title: "List documents",
11755
+ description: LIST_DOCUMENTS,
11756
+ route: "GET /v1/documents",
11757
+ inputSchema: {
11758
+ status: z.string().max(32).optional().describe("Only documents with this status."),
11759
+ source_id: zUuid().optional().describe("Only documents from this source."),
11760
+ source_type: z.string().max(64).optional().describe("Only documents from this kind of source."),
11761
+ search: z.string().max(200).optional().describe("Filename contains (case-insensitive)."),
11762
+ parent_id: zUuid().optional().describe("Only documents unpacked from this container document."),
11763
+ relation: z.string().max(32).optional().describe("Only nested documents of this kind, e.g. email_attachment."),
11764
+ top_level: z.boolean().optional().describe("true: hide documents nested in another."),
11765
+ text_degraded: z.boolean().optional().describe(
11766
+ "true: only documents whose text was not read verbatim; false: only those that were."
11767
+ ),
11768
+ ...cursorArgs
11769
+ },
11770
+ annotations: READ,
11771
+ query: [
11772
+ "status",
11773
+ "source_id",
11774
+ "source_type",
11775
+ "search",
11776
+ "parent_id",
11777
+ "relation",
11778
+ "top_level",
11779
+ "text_degraded",
11780
+ ...PAGE_QUERY
11781
+ ]
11782
+ },
11783
+ {
11784
+ name: "talonic_reextract_document",
11785
+ title: "Re-extract a document",
11786
+ description: REEXTRACT,
11787
+ route: "POST /v1/documents/{documentId}/re-extract",
11788
+ inputSchema: documentId,
11789
+ annotations: write9(false)
11790
+ },
11791
+ {
11792
+ name: "talonic_delete_document",
11793
+ title: "Delete a document",
11794
+ description: DELETE_DOCUMENT,
11795
+ route: "DELETE /v1/documents/{documentId}",
11796
+ inputSchema: documentId,
11797
+ annotations: write9(true, true)
11798
+ },
11799
+ {
11800
+ name: "talonic_list_extractions",
11801
+ title: "List extractions",
11802
+ description: LIST_EXTRACTIONS,
11803
+ route: "GET /v1/extractions",
11804
+ inputSchema: {
11805
+ document_id: zUuid().optional().describe("Only the extraction of this document."),
11806
+ status: z.enum(["complete", "failed"]).optional(),
11807
+ ...cursorArgs
11808
+ },
11809
+ annotations: READ,
11810
+ query: ["document_id", "status", ...PAGE_QUERY]
11811
+ },
11812
+ {
11813
+ name: "talonic_get_extraction",
11814
+ title: "One extraction",
11815
+ description: GET_EXTRACTION,
11816
+ route: "GET /v1/extractions/{extractionId}",
11817
+ inputSchema: extractionId,
11818
+ annotations: READ
11819
+ },
11820
+ getExtractionData,
11821
+ {
11822
+ name: "talonic_correct_extraction",
11823
+ title: "Correct extracted values",
11824
+ description: CORRECT_EXTRACTION,
11825
+ route: "PATCH /v1/extractions/{extractionId}/data",
11826
+ inputSchema: {
11827
+ ...extractionId,
11828
+ values: z.record(z.string(), z.unknown()).describe("{ <field_name>: corrected value } for the fields to change.")
11829
+ },
11830
+ annotations: write9(true),
11831
+ handler: (ctx, args) => {
11832
+ const values = args["values"];
11833
+ if (!values || typeof values !== "object" || Array.isArray(values)) {
11834
+ return Promise.resolve(validationError("`values` must be an object of field \u2192 value."));
11835
+ }
11836
+ if (Object.keys(values).length === 0) {
11837
+ return Promise.resolve(validationError("`values` names no field to correct."));
11838
+ }
11839
+ return runTool(
11840
+ () => apiJson(
11841
+ ctx.getToken,
11842
+ ctx.baseUrl,
11843
+ "PATCH",
11844
+ `/v1/extractions/${encodeURIComponent(String(args["extraction_id"]))}/data`,
11845
+ { body: values }
11846
+ )
11847
+ );
11848
+ }
11849
+ },
11850
+ {
11851
+ name: "talonic_list_jobs",
11852
+ title: "List jobs",
11853
+ description: LIST_JOBS,
11854
+ route: "GET /v1/jobs",
11855
+ inputSchema: {
11856
+ status: z.string().max(32).optional().describe("Only jobs with this status."),
11857
+ ...cursorArgs
11858
+ },
11859
+ annotations: READ,
11860
+ query: ["status", ...PAGE_QUERY]
11861
+ },
11862
+ {
11863
+ name: "talonic_get_job",
11864
+ title: "One job",
11865
+ description: GET_JOB,
11866
+ route: "GET /v1/jobs/{jobId}",
11867
+ inputSchema: jobId,
11868
+ annotations: READ
11869
+ },
11870
+ {
11871
+ name: "talonic_get_job_results",
11872
+ title: "A job's result rows",
11873
+ description: GET_JOB_RESULTS,
11874
+ route: "GET /v1/jobs/{jobId}/results",
11875
+ inputSchema: jobId,
11876
+ annotations: READ
11877
+ },
11878
+ createJob,
11879
+ {
11880
+ name: "talonic_cancel_job",
11881
+ title: "Cancel a job",
11882
+ description: CANCEL_JOB,
11883
+ route: "POST /v1/jobs/{jobId}/cancel",
11884
+ inputSchema: jobId,
11885
+ annotations: write9(true)
11886
+ },
11887
+ {
11888
+ name: "talonic_update_schema",
11889
+ title: "Change a saved schema",
11890
+ description: UPDATE_SCHEMA,
11891
+ route: "PUT /v1/schemas/{schemaId}",
11892
+ inputSchema: {
11893
+ ...schemaId,
11894
+ name: z.string().min(1).max(100).optional().describe("New name."),
11895
+ description: z.string().nullable().optional().describe("New description; null clears it."),
11896
+ definition: z.object({
11897
+ properties: z.record(z.string(), z.record(z.string(), z.unknown())),
11898
+ required: z.array(z.string()).optional()
11899
+ }).optional().describe("The complete new field list as a JSON Schema object. Replaces every field."),
11900
+ fields: z.array(schemaFieldSchema).min(1).optional().describe("The complete new field list as rows. Replaces every field.")
11901
+ },
11902
+ annotations: write9(true, true),
11903
+ body: ["name", "description", "definition", "fields"],
11904
+ handler: (ctx, args) => {
11905
+ if (args["definition"] !== void 0 && args["fields"] !== void 0) {
11906
+ return Promise.resolve(validationError("send `definition` or `fields`, not both."));
11907
+ }
11908
+ const changes = ["name", "description", "definition", "fields"].filter(
11909
+ (k) => args[k] !== void 0
11910
+ );
11911
+ if (changes.length === 0) {
11912
+ return Promise.resolve(
11913
+ validationError("nothing to change: pass name, description, definition or fields.")
11914
+ );
11915
+ }
11916
+ const req = buildRequest(
11917
+ {
11918
+ route: "PUT /v1/schemas/{schemaId}",
11919
+ body: ["name", "description", "definition", "fields"]
11920
+ },
11921
+ args
11922
+ );
11923
+ return runTool(
11924
+ () => apiJson(ctx.getToken, ctx.baseUrl, req.method, req.path, { body: req.body })
11925
+ );
11926
+ }
11927
+ },
11928
+ {
11929
+ name: "talonic_delete_schema",
11930
+ title: "Delete a saved schema",
11931
+ description: DELETE_SCHEMA,
11932
+ route: "DELETE /v1/schemas/{schemaId}",
11933
+ inputSchema: schemaId,
11934
+ annotations: write9(true, true)
11935
+ }
11936
+ ]
11937
+ };
11938
+ var LIST_EVENTS = describe({
11939
+ 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.",
11940
+ 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'.",
11941
+ not: "configuring webhooks (talonic_list_webhooks and its siblings, for workspace admins); workspace totals over a window (talonic_aggregate).",
11942
+ 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`).",
11943
+ 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."
11944
+ });
11945
+ var eventsGroup = {
11946
+ key: "events",
11947
+ label: "Events",
11948
+ docsSlug: "events-tools",
11949
+ probe: { path: "/v1/events", params: { limit: 1 } },
11950
+ tools: [
11951
+ {
11952
+ name: "talonic_list_events",
11953
+ title: "Workspace event feed",
11954
+ description: LIST_EVENTS,
11955
+ route: "GET /v1/events",
11956
+ inputSchema: {
11957
+ after: z.string().max(64).optional().describe(
11958
+ "Resume point: a saved next_cursor or an event id. Returns newer events, oldest first."
11959
+ ),
11960
+ since: z.string().optional().describe("Only events created at or after this ISO-8601 timestamp."),
11961
+ event_type: z.union([z.string(), z.array(z.string())]).optional().describe("One event type, or several (sent comma-separated)."),
11962
+ limit: z.number().int().min(1).max(200).optional().describe("Events per page (default 50)."),
11963
+ offset: z.number().int().min(0).optional().describe("Events to skip on the newest-first listing; ignored with `after`.")
11964
+ },
11965
+ annotations: READ,
11966
+ query: ["after", "since", "event_type", "limit", "offset"]
11967
+ }
11968
+ ]
11969
+ };
11970
+ var moneyFoundGroup = {
11971
+ key: "money_found",
11972
+ label: "Money Found",
11973
+ docsSlug: "money-found-tools",
11974
+ probe: { path: "/v1/money-found/reviews" },
11975
+ tools: [
11976
+ {
11977
+ name: "talonic_money_found_ledger",
11978
+ title: "Money Found ledger",
11979
+ description: describe({
11980
+ 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.",
11981
+ use: "'how much money is there to recover', or finding one row (lever id and row key) and the evidence behind it.",
11982
+ not: "what to ask the customer for (talonic_money_found_evidence_requests).",
11983
+ 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."
11984
+ }),
11985
+ route: "GET /v1/money-found/levers",
11986
+ inputSchema: {},
11987
+ annotations: READ
11988
+ },
11989
+ {
11990
+ name: "talonic_money_found_evidence_requests",
11991
+ title: "Money Found evidence requests",
11992
+ description: describe({
11993
+ 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.",
11994
+ use: "preparing the request for confirmations that turn potential rows into owed ones.",
11995
+ not: "the ledger itself (talonic_money_found_ledger).",
11996
+ returns: "{ currency, groups[] { cost_unit, framework_number, customer, contracts[], total, items[] { lever_id, row_key, invoice_type, period, ask, amount, contract } } }."
11997
+ }),
11998
+ route: "GET /v1/money-found/evidence-requests",
11999
+ inputSchema: {},
12000
+ annotations: READ
12001
+ },
12002
+ {
12003
+ name: "talonic_money_found_reviews",
12004
+ title: "Money Found re-reviews",
12005
+ description: describe({
12006
+ 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.",
12007
+ use: "after talonic_money_found_review_row or talonic_money_found_review_all, to read the outcome.",
12008
+ returns: "The re-reviews with their counts and suggested prices."
12009
+ }),
12010
+ route: "GET /v1/money-found/reviews",
12011
+ inputSchema: {},
12012
+ annotations: READ
12013
+ },
12014
+ {
12015
+ name: "talonic_money_found_review_row",
12016
+ title: "Re-review one Money Found row",
12017
+ description: describe({
12018
+ 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.",
12019
+ use: "the user doubts a row's amount or its price, or a contract was replaced.",
12020
+ args: "`lever_id`, `key` (the row key from talonic_money_found_ledger).",
12021
+ returns: "{ review } the queued review.",
12022
+ errors: "404 when the lever or row does not exist; 403 when the app is switched off."
12023
+ }),
12024
+ route: "POST /v1/money-found/rows/{leverId}/{key}/review",
12025
+ inputSchema: {
12026
+ lever_id: z.string().min(1).max(200).describe("The lever id of the row."),
12027
+ key: z.string().min(1).max(1e3).describe("The row key.")
12028
+ },
12029
+ annotations: write9(true)
12030
+ },
12031
+ {
12032
+ name: "talonic_money_found_review_all",
12033
+ title: "Re-review every pending Money Found row",
12034
+ description: describe({
12035
+ what: "Queue a re-review of every contract price row not reviewed since its check changed.",
12036
+ use: "bringing the whole ledger up to date after many documents arrived.",
12037
+ returns: "How many reviews were queued."
12038
+ }),
12039
+ route: "POST /v1/money-found/reviews/run",
12040
+ inputSchema: {},
12041
+ annotations: write9(true)
12042
+ }
12043
+ ]
12044
+ };
12045
+ var folderId = zUuid().describe("The folder id (talonic_transport_folders_list or _worklist).");
12046
+ var documentId2 = zUuid().describe("The document id, from the folder's documents.");
12047
+ var loadKey = z.string().min(1).max(200).describe("The load key, from the folder's loads.");
12048
+ 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 }.";
12049
+ var HANDOVER_MAX_BYTES = 8 * 1024 * 1024;
12050
+ var handoverTool = {
12051
+ name: "talonic_transport_folders_handover",
12052
+ title: "Customer document set of a load",
12053
+ description: describe({
12054
+ 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`).",
12055
+ use: "the user wants the papers to send with the invoice for a load, usually after talonic_transport_folders_confirm_load.",
12056
+ not: "the folder's matching (talonic_transport_folders_get).",
12057
+ args: "`folder_id`, `load_key`.",
12058
+ 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."
12059
+ }),
12060
+ route: "GET /v1/transport-folders/{folderId}/loads/{loadKey}/handover",
12061
+ inputSchema: { folder_id: folderId, load_key: loadKey },
12062
+ annotations: READ,
12063
+ handler: async (ctx, args) => {
12064
+ try {
12065
+ const req = buildRequest(handoverTool, args);
12066
+ const r = await apiJson(
12067
+ ctx.getToken,
12068
+ ctx.baseUrl,
12069
+ req.method,
12070
+ req.path
12071
+ );
12072
+ const meta = {
12073
+ filename: r.filename,
12074
+ size: Math.floor((r.pdf_base64?.length ?? 0) * 3 / 4),
12075
+ index: r.index
12076
+ };
12077
+ if (meta.size > HANDOVER_MAX_BYTES) {
12078
+ return toolError(
12079
+ new Error(
12080
+ `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.`
12081
+ )
12082
+ );
12083
+ }
12084
+ const result = {
12085
+ content: [
12086
+ { type: "text", text: JSON.stringify(meta) },
12087
+ {
12088
+ type: "resource",
12089
+ resource: {
12090
+ uri: buildUrl(ctx.baseUrl, req.path),
12091
+ mimeType: "application/pdf",
12092
+ blob: r.pdf_base64
12093
+ }
12094
+ }
12095
+ ],
12096
+ structuredContent: meta
12097
+ };
12098
+ return result;
12099
+ } catch (err) {
12100
+ return toolError(err);
12101
+ }
12102
+ }
12103
+ };
12104
+ var transportFoldersGroup = {
12105
+ key: "transport_folders",
12106
+ label: "Transport Folders",
12107
+ docsSlug: "transport-folders-tools",
12108
+ probe: { path: "/v1/transport-folders/settings" },
12109
+ tools: [
12110
+ {
12111
+ name: "talonic_transport_folders_list",
12112
+ title: "Transport folders",
12113
+ description: describe({
12114
+ 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.",
12115
+ use: "an overview of the folders, or finding one by transport number.",
12116
+ not: "only what needs a person (talonic_transport_folders_worklist); one folder's loads and documents (talonic_transport_folders_get).",
12117
+ returns: "{ configured, data[] { id, folder_key, status, loads, documents, \u2026 } }."
12118
+ }),
12119
+ route: "GET /v1/transport-folders",
12120
+ inputSchema: {},
12121
+ annotations: READ
12122
+ },
12123
+ {
12124
+ name: "talonic_transport_folders_worklist",
12125
+ title: "Transport Folders worklist",
12126
+ description: describe({
12127
+ what: "Everything that needs a person, across all folders: loads that are not complete and documents not assigned to a load.",
12128
+ use: "starting work; each entry names its folder for talonic_transport_folders_get.",
12129
+ not: "all folders (talonic_transport_folders_list).",
12130
+ returns: "{ loads[] { folder_id, load_key, verdict, flags, \u2026 }, documents[] { folder_id, document_id, type, suggested_load_key, \u2026 }, type_labels }."
12131
+ }),
12132
+ route: "GET /v1/transport-folders/worklist",
12133
+ inputSchema: {},
12134
+ annotations: READ
12135
+ },
12136
+ {
12137
+ name: "talonic_transport_folders_get",
12138
+ title: "One transport folder",
12139
+ description: describe({
12140
+ 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.",
12141
+ use: "the evidence before assigning a document or confirming a load.",
12142
+ not: "where a value sits on the page (talonic_transport_folders_boxes).",
12143
+ args: "`folder_id`.",
12144
+ returns: DETAIL_RETURNS
12145
+ }),
12146
+ route: "GET /v1/transport-folders/{folderId}",
12147
+ inputSchema: { folder_id: folderId },
12148
+ annotations: READ
12149
+ },
12150
+ {
12151
+ name: "talonic_transport_folders_boxes",
12152
+ title: "Where a document's values sit",
12153
+ description: describe({
12154
+ what: "Where each captured value of one document sits on its pages (boxes as page fractions), as far as already located.",
12155
+ use: "pointing the user to the value on the scan.",
12156
+ not: "locating values that have no box yet (talonic_transport_folders_locate_document).",
12157
+ args: "`folder_id`, `document_id`.",
12158
+ returns: "{ document_id, pages[], boxes[] { field, value, page, x, y, w, h } }."
12159
+ }),
12160
+ route: "GET /v1/transport-folders/{folderId}/documents/{documentId}/boxes",
12161
+ inputSchema: { folder_id: folderId, document_id: documentId2 },
12162
+ annotations: READ
12163
+ },
12164
+ {
12165
+ name: "talonic_transport_folders_locate_document",
12166
+ title: "Locate a document's values",
12167
+ description: describe({
12168
+ 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.",
12169
+ use: "talonic_transport_folders_boxes came back without boxes.",
12170
+ not: "a whole folder (talonic_transport_folders_locate_folder).",
12171
+ args: "`folder_id`, `document_id`.",
12172
+ returns: "the document's boxes, as talonic_transport_folders_boxes returns them."
12173
+ }),
12174
+ route: "POST /v1/transport-folders/{folderId}/documents/{documentId}/locate",
12175
+ inputSchema: { folder_id: folderId, document_id: documentId2 },
12176
+ annotations: write9(true)
12177
+ },
12178
+ {
12179
+ name: "talonic_transport_folders_locate_folder",
12180
+ title: "Locate a folder's values",
12181
+ description: describe({
12182
+ 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.",
12183
+ use: "before going through a folder's documents on screen.",
12184
+ not: "one document (talonic_transport_folders_locate_document).",
12185
+ args: "`folder_id`.",
12186
+ returns: "per document whether boxes are now stored."
12187
+ }),
12188
+ route: "POST /v1/transport-folders/{folderId}/locate",
12189
+ inputSchema: { folder_id: folderId },
12190
+ annotations: write9(true)
12191
+ },
12192
+ {
12193
+ name: "talonic_transport_folders_assign",
12194
+ title: "Assign a document to a load",
12195
+ description: describe({
12196
+ 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.",
12197
+ use: "a document waits for review, or was matched to the wrong load.",
12198
+ not: "confirming the load (talonic_transport_folders_confirm_load).",
12199
+ args: "`folder_id`, `document_id`, `load_key` (a load of this folder, or null for no load).",
12200
+ returns: DETAIL_RETURNS,
12201
+ errors: "400 load_key is not a load of this folder; 404 document not in this folder."
12202
+ }),
12203
+ route: "POST /v1/transport-folders/{folderId}/documents/{documentId}/assign",
12204
+ inputSchema: {
12205
+ folder_id: folderId,
12206
+ document_id: documentId2,
12207
+ load_key: z.string().max(200).nullable().describe("The load the document belongs to; null = it belongs to no load.")
12208
+ },
12209
+ annotations: write9(true),
12210
+ body: ["load_key"]
12211
+ },
12212
+ {
12213
+ name: "talonic_transport_folders_unassign",
12214
+ title: "Withdraw a document's assignment",
12215
+ description: describe({
12216
+ what: "Withdraw a person's assignment of a document, so the matching decides again.",
12217
+ use: "an assignment made with talonic_transport_folders_assign was wrong.",
12218
+ args: "`folder_id`, `document_id`.",
12219
+ returns: DETAIL_RETURNS
12220
+ }),
12221
+ route: "DELETE /v1/transport-folders/{folderId}/documents/{documentId}/assign",
12222
+ inputSchema: { folder_id: folderId, document_id: documentId2 },
12223
+ annotations: write9(true)
12224
+ },
12225
+ {
12226
+ name: "talonic_transport_folders_confirm_load",
12227
+ title: "Confirm a load",
12228
+ description: describe({
12229
+ 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.",
12230
+ use: "the load's verdict is complete, or the user checked it and accepts it.",
12231
+ not: "getting the PDF (talonic_transport_folders_handover).",
12232
+ args: "`folder_id`, `load_key`.",
12233
+ returns: DETAIL_RETURNS
12234
+ }),
12235
+ route: "POST /v1/transport-folders/{folderId}/loads/{loadKey}/confirm",
12236
+ inputSchema: { folder_id: folderId, load_key: loadKey },
12237
+ annotations: write9(true)
12238
+ },
12239
+ {
12240
+ name: "talonic_transport_folders_unconfirm_load",
12241
+ title: "Withdraw a load's confirmation",
12242
+ description: describe({
12243
+ what: "Withdraw the confirmation of a load.",
12244
+ use: "a load was confirmed by mistake.",
12245
+ args: "`folder_id`, `load_key`.",
12246
+ returns: DETAIL_RETURNS
12247
+ }),
12248
+ route: "DELETE /v1/transport-folders/{folderId}/loads/{loadKey}/confirm",
12249
+ inputSchema: { folder_id: folderId, load_key: loadKey },
12250
+ annotations: write9(true)
12251
+ },
12252
+ handoverTool,
12253
+ {
12254
+ name: "talonic_transport_folders_settings",
12255
+ title: "Transport Folders settings",
12256
+ description: describe({
12257
+ 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).",
12258
+ use: "setting up the app, or explaining why a folder has no loads.",
12259
+ not: "changing them (talonic_transport_folders_save_settings).",
12260
+ returns: "{ settings, pipelines[] { id, name, status }, reference_tables[] { id, name, row_count } }."
12261
+ }),
12262
+ route: "GET /v1/transport-folders/settings",
12263
+ inputSchema: {},
12264
+ annotations: READ
12265
+ },
12266
+ {
12267
+ name: "talonic_transport_folders_save_settings",
12268
+ title: "Change Transport Folders settings",
12269
+ description: describe({
12270
+ what: "Change the app's settings. Only the keys sent change; null clears one. Needs an Admin of the workspace.",
12271
+ use: "setting up the app or pointing it at another Spec or reference table.",
12272
+ 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).",
12273
+ returns: "the settings and choices, as talonic_transport_folders_settings returns them. 400 for an invalid pattern."
12274
+ }),
12275
+ route: "PUT /v1/transport-folders/settings",
12276
+ inputSchema: {
12277
+ pipeline_id: zUuid().nullable().optional().describe("The Spec run whose results describe the documents."),
12278
+ reference_data_id: zUuid().nullable().optional().describe("The reference table holding the loads."),
12279
+ folder_key_pattern: z.string().max(200).nullable().optional().describe("Regular expression; its first group is the transport number in a filename."),
12280
+ matcher: z.record(z.string(), z.unknown()).nullable().optional().describe("Overrides of the matching defaults.")
12281
+ },
12282
+ annotations: write9(true),
12283
+ body: ["pipeline_id", "reference_data_id", "folder_key_pattern", "matcher"]
12284
+ }
12285
+ ]
12286
+ };
12287
+
12288
+ // src/tools/tool-groups.ts
12289
+ var TOOL_GROUPS = [
12290
+ dataManagementGroup,
12291
+ eventsGroup,
12292
+ aggregateGroup,
12293
+ adminGroup,
12294
+ contractDeskGroup,
12295
+ transportFoldersGroup,
12296
+ complianceGroup,
12297
+ moneyFoundGroup,
12298
+ customsDeclarationGroup
12299
+ ];
12300
+ TOOL_GROUPS.map((g) => g.key);
12301
+ function registerToolGroups(server, keys, getToken, baseUrl) {
12302
+ const wanted = new Set(keys);
12303
+ for (const group of TOOL_GROUPS) {
12304
+ if (wanted.has(group.key)) registerGroup(server, group, getToken, baseUrl);
12305
+ }
12306
+ }
12307
+
12308
+ // package.json
12309
+ var package_default = {
12310
+ version: "0.1.105"};
12311
+
12312
+ // src/version.ts
12313
+ var VERSION = package_default.version;
12314
+ var SERVER_NAME = "talonic";
12315
+
12316
+ // src/server-factory.ts
12317
+ function makeTaggedFetch(getClientName, baseFetch = fetch) {
12318
+ return ((input, init) => {
12319
+ try {
12320
+ const headers = new Headers(init?.headers);
12321
+ const cn = getClientName();
12322
+ headers.set("user-agent", `talonic-mcp/${VERSION}${cn ? ` ${cn}` : ""}`);
12323
+ return baseFetch(input, { ...init, headers });
12324
+ } catch {
12325
+ return baseFetch(input, init);
12326
+ }
12327
+ });
12328
+ }
12329
+ function buildServerInstructions(opts) {
12330
+ return [
12331
+ "Talonic turns unstructured documents (PDFs, scans, images, DOCX, emails) into",
12332
+ "schema-validated JSON with per-field confidence scores and source provenance, and",
12333
+ "answers questions about the documents in the user's Talonic workspace.",
12334
+ "Which tool for which question:",
12335
+ "(0) any question about what the documents contain (counts, totals, duplicates,",
12336
+ "comparisons, anomalies) -> talonic_ask FIRST, in one call; do not explore fields,",
9209
12337
  "schemas, specs or SQL to answer it yourself;",
9210
12338
  "(1) a document by name or keyword -> talonic_search (literal keywords: one short term",
9211
12339
  "or an exact filename; on an empty result retry with a shorter keyword), then use the",
@@ -9242,6 +12370,16 @@ function buildServerInstructions(opts) {
9242
12370
  "apps:decide consent and a senior_member role or above; on HTTP 403 tell the user",
9243
12371
  "which consent or role is missing instead of retrying."
9244
12372
  ] : [],
12373
+ ...opts.includeAppsToolset ? [
12374
+ "To build an app: talonic_create_app -> talonic_save_app_draft ->",
12375
+ "talonic_interpret_app_rules -> talonic_publish_app -> talonic_run_app (dry_run first) ->",
12376
+ "talonic_get_app_run or talonic_get_run_verdicts -> talonic_check_app_acceptance.",
12377
+ "Human Reviews: talonic_list_app_reviews -> talonic_resolve_app_review."
12378
+ ] : [],
12379
+ ...opts.includeMiningDriverTools ? [
12380
+ "A rule-finding round waiting for an outside driver is claimed and closed with the",
12381
+ "decision-task tools; in between, call its tools with talonic_mining_call_round_tool."
12382
+ ] : [],
9245
12383
  "Tools that change workspace data (saving schemas, app updates, decisions) should only",
9246
12384
  "be called when the user asked for that change. Every error ends with a 'Next step'",
9247
12385
  "line: follow it.",
@@ -9305,7 +12443,9 @@ function createServer(options) {
9305
12443
  instructions: buildServerInstructions({
9306
12444
  includeGenericExecutor: options.includeGenericExecutor !== false,
9307
12445
  includeAgentTaskTools: options.includeAgentTaskTools !== false,
9308
- includeDecisionTaskTools: options.includeDecisionTaskTools !== false
12446
+ includeDecisionTaskTools: options.includeDecisionTaskTools !== false,
12447
+ includeAppsToolset: options.includeAppsToolset === true,
12448
+ includeMiningDriverTools: options.includeMiningDriverTools === true
9309
12449
  })
9310
12450
  }
9311
12451
  );
@@ -9347,6 +12487,14 @@ function createServer(options) {
9347
12487
  invocable: options.decisionTasksInvocable !== false
9348
12488
  });
9349
12489
  }
12490
+ if (options.includeAppsToolset) {
12491
+ registerAppsToolset(server, rawToken, baseUrl);
12492
+ }
12493
+ if (options.includeMiningDriverTools) {
12494
+ registerMiningDriverTools(server, rawToken, baseUrl, {
12495
+ invocable: options.decisionTasksInvocable !== false
12496
+ });
12497
+ }
9350
12498
  if (options.includeGrowthTools) {
9351
12499
  registerGrowthTools(server, rawToken, baseUrl);
9352
12500
  }
@@ -9380,6 +12528,9 @@ function createServer(options) {
9380
12528
  if (options.includePriceBaselineTools) {
9381
12529
  registerPriceBaselineTools(server, rawToken, baseUrl);
9382
12530
  }
12531
+ if (options.toolGroups?.length) {
12532
+ registerToolGroups(server, options.toolGroups, rawToken, baseUrl);
12533
+ }
9383
12534
  registerSchemasResource(server, getTalonic);
9384
12535
  registerWebhooksResource(server, rawToken, baseUrl);
9385
12536
  registerWidgets(server);
@@ -9446,6 +12597,15 @@ var growthAccessCached = makeAccessCache(pathProbe("/v1/growth/access"));
9446
12597
  var adminAgentTaskAccessCached = makeAccessCache(pathProbe("/v1/agent-tasks/admin/access"));
9447
12598
  var agentTasksAccessCached = makeAccessCache((t) => probeAgentTasksInUse(t, base()));
9448
12599
  var decisionTasksAccessCached = makeAccessCache((t) => probeExternalAppsInUse(t, base()));
12600
+ var appsToolsetAccessCached = makeAccessCache((t) => probeAppsToolsetAccess(t, base()));
12601
+ var miningAccessCached = makeAccessCache((t) => probeMiningInUse(t, base()));
12602
+ var toolGroupCaches = TOOL_GROUPS.map(
12603
+ (g) => [g.key, makeAccessCache((t) => probeGroup(g, t, base()))]
12604
+ );
12605
+ async function toolGroupsAccessCached(token) {
12606
+ const answers = await Promise.all(toolGroupCaches.map(([, cached]) => cached(token)));
12607
+ return toolGroupCaches.filter((_, i) => answers[i]).map(([key2]) => key2);
12608
+ }
9449
12609
  var MAX_BODY_BYTES = 64 * 1024 * 1024;
9450
12610
  var MAX_ANON_BODY_BYTES = 64 * 1024;
9451
12611
  async function probeTokenAccepted(token) {
@@ -9463,21 +12623,21 @@ async function probeTokenAccepted(token) {
9463
12623
  var TOKEN_CHECK_TTL_MS = 60 * 1e3;
9464
12624
  var tokenCheckCache = /* @__PURE__ */ new Map();
9465
12625
  async function tokenAcceptedCached(token, probe = probeTokenAccepted, now = Date.now) {
9466
- const key = createHash("sha256").update(token).digest("hex");
9467
- const hit = tokenCheckCache.get(key);
12626
+ const key2 = createHash("sha256").update(token).digest("hex");
12627
+ const hit = tokenCheckCache.get(key2);
9468
12628
  if (hit && hit.expiresAt > now()) return hit.ok;
9469
12629
  const ok = await probe(token);
9470
12630
  if (tokenCheckCache.size >= 1e3) tokenCheckCache.clear();
9471
- tokenCheckCache.set(key, { ok, expiresAt: now() + TOKEN_CHECK_TTL_MS });
12631
+ tokenCheckCache.set(key2, { ok, expiresAt: now() + TOKEN_CHECK_TTL_MS });
9472
12632
  return ok;
9473
12633
  }
9474
- function readBody(req, limit2) {
12634
+ function readBody(req, limit3) {
9475
12635
  return new Promise((resolve, reject) => {
9476
12636
  const chunks = [];
9477
12637
  let size = 0;
9478
12638
  req.on("data", (chunk) => {
9479
12639
  size += chunk.length;
9480
- if (size > limit2) {
12640
+ if (size > limit3) {
9481
12641
  req.removeAllListeners("data");
9482
12642
  req.resume();
9483
12643
  resolve(null);
@@ -9740,7 +12900,10 @@ function createRequestHandler(options = {}) {
9740
12900
  includePortfolioTools,
9741
12901
  includeProcessesTools,
9742
12902
  includeAgentTaskTools,
9743
- includeDecisionTaskTools
12903
+ externalAppsInUse,
12904
+ includeAppsToolset,
12905
+ includeMiningDriverTools,
12906
+ toolGroups
9744
12907
  ] = await Promise.all([
9745
12908
  (options.growthAccess ?? growthAccessCached)(token),
9746
12909
  (options.adminAgentTaskAccess ?? adminAgentTaskAccessCached)(token),
@@ -9754,8 +12917,12 @@ function createRequestHandler(options = {}) {
9754
12917
  (options.portfolioAccess ?? portfolioAccessCached)(token),
9755
12918
  (options.processesAccess ?? processesAccessCached)(token),
9756
12919
  (options.agentTasksAccess ?? agentTasksAccessCached)(token),
9757
- (options.decisionTasksAccess ?? decisionTasksAccessCached)(token)
12920
+ (options.decisionTasksAccess ?? decisionTasksAccessCached)(token),
12921
+ (options.appsToolsetAccess ?? appsToolsetAccessCached)(token),
12922
+ (options.miningAccess ?? miningAccessCached)(token),
12923
+ (options.toolGroupsAccess ?? toolGroupsAccessCached)(token)
9758
12924
  ]);
12925
+ const includeDecisionTaskTools = externalAppsInUse || includeMiningDriverTools;
9759
12926
  const mcpServer = createServer({
9760
12927
  tokenProvider: () => token,
9761
12928
  includeGrowthTools,
@@ -9771,6 +12938,9 @@ function createRequestHandler(options = {}) {
9771
12938
  includeProcessesTools,
9772
12939
  includeAgentTaskTools,
9773
12940
  includeDecisionTaskTools,
12941
+ includeAppsToolset,
12942
+ includeMiningDriverTools,
12943
+ toolGroups,
9774
12944
  ...process.env["TALONIC_BASE_URL"] ? { baseUrl: process.env["TALONIC_BASE_URL"] } : {},
9775
12945
  // Listing UX only: an OAuth token that visibly lacks apps:decide gets
9776
12946
  // the decision-task tools marked non-invocable. The platform decides.
@@ -9818,6 +12988,6 @@ if (isDirectInvocation()) {
9818
12988
  });
9819
12989
  }
9820
12990
 
9821
- export { adminAgentTaskAccessCached, agentTasksAccessCached, apAccessCached, contractsAccessCached, createRequestHandler, decisionTasksAccessCached, docGenAccessCached, growthAccessCached, isOpenAiClient, masterRecordsAccessCached, partiesAccessCached, portfolioAccessCached, priceBaselineAccessCached, processesAccessCached, submissionsAccessCached, tokenAcceptedCached };
12991
+ export { adminAgentTaskAccessCached, agentTasksAccessCached, apAccessCached, appsToolsetAccessCached, contractsAccessCached, createRequestHandler, decisionTasksAccessCached, docGenAccessCached, growthAccessCached, isOpenAiClient, masterRecordsAccessCached, miningAccessCached, partiesAccessCached, portfolioAccessCached, priceBaselineAccessCached, processesAccessCached, submissionsAccessCached, tokenAcceptedCached, toolGroupsAccessCached };
9822
12992
  //# sourceMappingURL=http-server.js.map
9823
12993
  //# sourceMappingURL=http-server.js.map