@talonic/mcp 0.1.104 → 0.1.106

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.
@@ -1,5 +1,5 @@
1
1
  import { createServer as createServer$1 } from 'http';
2
- import { createHash } from 'crypto';
2
+ import { webcrypto, 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';
@@ -2448,7 +2448,7 @@ var inputSchema = {
2448
2448
  instructions: z.string().optional().describe(
2449
2449
  "Natural-language guidance for the extractor, e.g. 'Focus on the billing section. Amounts are in EUR.'"
2450
2450
  ),
2451
- include_markdown: z.boolean().optional().describe("Include OCR-converted markdown in the response alongside structured data."),
2451
+ include_markdown: z.boolean().optional().describe("Also return the document's full text as markdown, alongside the fields."),
2452
2452
  include_provenance: z.boolean().optional().describe(
2453
2453
  "Include per-field provenance (source_text, section, page) showing where each value was found in the document."
2454
2454
  )
@@ -2497,7 +2497,7 @@ var outputSchema = {
2497
2497
  document: z.string().optional(),
2498
2498
  dashboard: z.string().optional()
2499
2499
  }).optional().describe("URLs for self, document, and human-readable dashboard view."),
2500
- markdown: z.string().optional().describe("OCR-converted markdown. Present only when `include_markdown: true`."),
2500
+ markdown: z.string().optional().describe("The document's full text as markdown. Present only when `include_markdown: true`."),
2501
2501
  cost: z.object({
2502
2502
  costCredits: z.number().describe("Credits consumed by this call."),
2503
2503
  costEur: z.number().describe("Approximate EUR cost of this call."),
@@ -2773,7 +2773,7 @@ function registerGetBalance(server, getTalonic) {
2773
2773
  var DESCRIPTION4 = [
2774
2774
  "Read Talonic's machine-readable credit pricing catalog: fixed per-unit rates so you can predict spend BEFORE running anything.",
2775
2775
  "",
2776
- "USE WHEN: estimating the cost of a planned extraction/structuring/matching job, or answering a pricing question. Public \u2014 works without spending credits.",
2776
+ "USE WHEN: estimating the cost of planned work (reading documents, extracting fields, matching records), or answering a pricing question. Public \u2014 works without spending credits.",
2777
2777
  "NOT FOR: the workspace's current balance (use talonic_get_balance) or what it has already spent (use talonic_get_usage).",
2778
2778
  "ARGS: none.",
2779
2779
  "RETURNS: currency, credits_per_eur, multipliers (e.g. batch 0.5x), and units[] \u2014 each { unit, label, credits, eur, free }."
@@ -2825,7 +2825,7 @@ function registerGetPricing(server, getTalonic) {
2825
2825
  var DESCRIPTION5 = [
2826
2826
  "Read the workspace's per-function credit consumption over a trailing window: where the credits actually went.",
2827
2827
  "",
2828
- "USE WHEN: the user asks what they have spent credits on, or you want to see which function (extraction, structuring, intelligence ops) dominates spend.",
2828
+ "USE WHEN: the user asks what they have spent credits on, or you want to see which kind of work (reading documents, structuring data, answering questions) takes most of the credits.",
2829
2829
  "NOT FOR: the remaining balance (use talonic_get_balance) or per-unit rates (use talonic_get_pricing).",
2830
2830
  "ARGS: days (optional, default 30, clamped 1-365).",
2831
2831
  "RETURNS: period_days, total_credits, and by_function[] \u2014 each { operation_type, operations, credits }, highest spend first."
@@ -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
  }
@@ -7832,7 +7832,7 @@ var outputValue = z.object({
7832
7832
  var outputs = z.record(z.string().min(1), outputValue).describe(
7833
7833
  "Output field key to { value, confidence?, reasoning?, escalate?, quote?, document_id? }. Use only declared fields."
7834
7834
  );
7835
- var pipelineId = zUuid().optional().describe("Optional pipeline (run) UUID: only that pipeline's tasks.");
7835
+ var pipelineId = zUuid().optional().describe("Optional run UUID: only that run's tasks.");
7836
7836
  var listInput = { status, limit, cursor, pipeline_id: pipelineId };
7837
7837
  var idInput = { task_id: taskId };
7838
7838
  var heartbeatInput = { task_id: taskId, execution_epoch: executionEpoch };
@@ -7984,39 +7984,39 @@ var MUTATING = {
7984
7984
  };
7985
7985
  var DESCRIPTIONS = {
7986
7986
  list: [
7987
- "List Agent-stage tasks visible to this Talonic workspace credential.",
7987
+ "List the agent tasks waiting in this workspace: checks a Spec hands to an outside agent (your agent) instead of a person, one per document.",
7988
7988
  "",
7989
- "USE WHEN: looking for external-agent work to process; begin with status 'available'. To take a batch of one pipeline (e.g. 'take 10 tasks of pipeline X'), list with pipeline_id and status 'available', then claim each with talonic_claim_agent_task; a task another agent took returns HTTP 409, so skip it and take the next.",
7989
+ "USE WHEN: looking for work for your agent to do; begin with status 'available'. To take a batch from one run (e.g. 'take 10 tasks of run X'), list with pipeline_id and status 'available', then claim each with talonic_claim_agent_task; a task another agent took returns HTTP 409, so skip it and take the next.",
7990
7990
  "NOT FOR: reading the immutable task payload (use talonic_get_agent_task) or taking a lease (use talonic_claim_agent_task).",
7991
7991
  "ARGS: optional status, pipeline_id, limit, and cursor. RETURNS: metadata only plus pagination.next_cursor."
7992
7992
  ].join("\n"),
7993
7993
  get: [
7994
- "Fetch one Agent-stage task's immutable input snapshot, instructions, and declared output contract. This disclosure is audited.",
7994
+ "Read one agent task: its fixed input, instructions, and the output fields it expects. Each read is recorded against the task.",
7995
7995
  "",
7996
7996
  "USE WHEN: inspecting a listed task before deciding whether to process it.",
7997
7997
  "NOT FOR: acquiring the task (use talonic_claim_agent_task) or returning results (use talonic_submit_agent_task).",
7998
7998
  "ARGS: task_id. RETURNS: metadata, input_snapshot, output_contract, instructions, and timeout_fallthrough."
7999
7999
  ].join("\n"),
8000
8000
  claim: [
8001
- "Claim an available Agent-stage task, or reclaim it after its lease expires.",
8001
+ "Claim an available agent task so no one else works on it, or reclaim it after its lease expires.",
8002
8002
  "",
8003
8003
  "USE WHEN: ready to process a task. Save the returned execution_epoch and lease_expires_at.",
8004
8004
  "NOT FOR: merely inspecting work (use talonic_get_agent_task) or extending an active lease (use talonic_heartbeat_agent_task).",
8005
8005
  "A conflicting live claim returns HTTP 409. A successful claim returns the task payload: input_snapshot, instructions, and output_contract, whose entries carry each field's Spec rules (description) and allowed codes (enumValues). Review the documents against those rules."
8006
8006
  ].join("\n"),
8007
8007
  heartbeat: [
8008
- "Extend the lease on a claimed Agent-stage task.",
8008
+ "Extend the lease on a claimed agent task so you keep it while you work.",
8009
8009
  "",
8010
8010
  "USE WHEN: processing may continue past lease_expires_at; heartbeat before expiry using the epoch from claim.",
8011
8011
  "NOT FOR: acquiring a task (use talonic_claim_agent_task) or submitting finished outputs (use talonic_submit_agent_task).",
8012
8012
  "ARGS: task_id and execution_epoch. Stale or foreign claims return HTTP 409."
8013
8013
  ].join("\n"),
8014
8014
  submit: [
8015
- "Submit declared output fields for a claimed Agent-stage task and resume the parked document.",
8015
+ "Submit the output fields for a claimed agent task; the document then continues through its Spec.",
8016
8016
  "",
8017
8017
  "USE WHEN: processing is complete and every required output in output_contract is ready.",
8018
8018
  "NOT FOR: undeclared fields or partial lease maintenance (use talonic_heartbeat_agent_task).",
8019
- "ARGS: task_id, execution_epoch, outputs keyed exactly by declared field key, and optional summary. The platform validates all fields and types transactionally before writing anything."
8019
+ "ARGS: task_id, execution_epoch, outputs keyed exactly by declared field key, and optional summary. Talonic checks every field and type before writing anything: all are saved or none."
8020
8020
  ].join("\n")
8021
8021
  };
8022
8022
  function registerAgentTaskTools(server, getToken, baseUrl) {
@@ -8208,6 +8208,517 @@ function probeAgentTasksInUse(token, baseUrl) {
8208
8208
  { limit: 1 }
8209
8209
  );
8210
8210
  }
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"];
8215
+ var appId = zUuid().describe(
8216
+ "App id: the UUID `id` from talonic_list_apps or talonic_create_app (not the app_\u2026 public id)."
8217
+ );
8218
+ var runId = zUuid().describe(
8219
+ "App run UUID (run_id from talonic_run_app or talonic_list_app_runs)."
8220
+ );
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 })
8257
+ );
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 })
8287
+ );
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 })
8294
+ );
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
+ })
8310
+ );
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 })
8320
+ );
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
+ }
8211
8722
  var DECIDE_SCOPE = "apps:decide";
8212
8723
  function tokenHasDecideScope(token) {
8213
8724
  if (token.startsWith("tlnc_")) return true;
@@ -8231,7 +8742,7 @@ var TASK_STATUSES2 = [
8231
8742
  "cancelled"
8232
8743
  ];
8233
8744
  var PACKAGE_PAGE_LIMIT_MAX = 2e3;
8234
- var appId = zUuid().describe(
8745
+ var appId2 = zUuid().describe(
8235
8746
  "Id of an External-mode app (from talonic_list_apps, where mode is 'external')."
8236
8747
  );
8237
8748
  var taskId2 = zUuid().describe("Decision task UUID.");
@@ -8259,7 +8770,7 @@ var serviceVersion = z.string().min(1).max(64).optional().describe("Optional bui
8259
8770
  var failReason = z.string().min(1).max(2e3).describe(
8260
8771
  "Why the task cannot be decided, up to 2,000 characters. Recorded on the Human Review the fail raises."
8261
8772
  );
8262
- var listInput2 = { app_id: appId, status: status2, limit: listLimit, cursor: cursor2 };
8773
+ var listInput2 = { app_id: appId2, status: status2, limit: listLimit, cursor: cursor2 };
8263
8774
  var idInput2 = { task_id: taskId2 };
8264
8775
  var packageInput = { task_id: taskId2, cursor: packageCursor, limit: packageLimit };
8265
8776
  var epochInput = { task_id: taskId2, execution_epoch: executionEpoch2 };
@@ -8334,12 +8845,12 @@ function handleFailDecisionTask(getToken, baseUrl, args) {
8334
8845
  })
8335
8846
  );
8336
8847
  }
8337
- var READ_ONLY3 = {
8848
+ var READ_ONLY4 = {
8338
8849
  readOnlyHint: true,
8339
8850
  destructiveHint: false,
8340
8851
  openWorldHint: false
8341
8852
  };
8342
- var MUTATING2 = {
8853
+ var MUTATING3 = {
8343
8854
  readOnlyHint: false,
8344
8855
  destructiveHint: false,
8345
8856
  openWorldHint: false
@@ -8352,10 +8863,10 @@ var DESTRUCTIVE = {
8352
8863
  var AUTH_NOTE = "AUTH: a tlnc_ key needs a per-app 'decide' grant; an OAuth connector session needs the apps:decide scope (consented at connect) and a live workspace role of senior_member or above. A 403 (decide_grant_required, insufficient_scope, insufficient_tier) names what is missing \u2014 tell the user, do not retry.";
8353
8864
  var DESCRIPTIONS2 = {
8354
8865
  list: [
8355
- "List one External-mode app's decision tasks (runs parked for an outside agent to decide), newest first.",
8866
+ "List one External-mode app's decision tasks (runs waiting for an outside agent to decide), newest first.",
8356
8867
  "",
8357
8868
  "USE WHEN: looking for decisions to make for an app; begin with status 'available'. This is the polling alternative to the app.decision_task.offered webhook.",
8358
- "NOT FOR: Agent-stage document tasks (use talonic_list_agent_tasks), reading a task's input package (claim it, then talonic_read_decision_package), or taking a lease (talonic_claim_decision_task).",
8869
+ "NOT FOR: agent tasks on documents in a Spec (use talonic_list_agent_tasks), reading a task's input package (claim it, then talonic_read_decision_package), or taking a lease (talonic_claim_decision_task).",
8359
8870
  "ARGS: app_id, optional status, limit, cursor. RETURNS: task metadata only (id, run_id, status, execution_epoch, lease and sla_deadline_at timing) plus pagination.next_cursor.",
8360
8871
  AUTH_NOTE
8361
8872
  ].join("\n"),
@@ -8367,7 +8878,7 @@ var DESCRIPTIONS2 = {
8367
8878
  AUTH_NOTE
8368
8879
  ].join("\n"),
8369
8880
  package: [
8370
- "Read one page of a claimed decision task's frozen input package: the records the decision must be made from, with their provenance locators. Only the current claimant may read it; each page read is journaled onto the run.",
8881
+ "Read one page of a claimed decision task's fixed input: the records the decision must be made from, each with the locator to cite as evidence. Only the current claimant may read it; each page read is recorded on the run.",
8371
8882
  "",
8372
8883
  "USE WHEN: after a successful claim, walking pages from package.first_cursor while pagination.has_more is true. The first page also carries the source documents list. A mining_round package is one record { system_prompt, first_turn, tools }.",
8373
8884
  "NOT FOR: unclaimed tasks (HTTP 409; claim first) or listing tasks (talonic_list_decision_tasks).",
@@ -8383,7 +8894,7 @@ var DESCRIPTIONS2 = {
8383
8894
  AUTH_NOTE
8384
8895
  ].join("\n"),
8385
8896
  submit: [
8386
- "Submit the decision for a claimed decision task; the platform verifies it transactionally and resumes the run.",
8897
+ "Submit the decision for a claimed decision task; Talonic checks it before saving anything, then the run continues.",
8387
8898
  "",
8388
8899
  "USE WHEN: the decision is final. outcome must satisfy output_contract from the claim (plain JSON Schema, or the verdict_matrix / record_set envelope), evidence lists the package locators relied on (verbatim; [] only if the app allows unevidenced decisions), rationale is a short summary. Rejections are HTTP 422 with the reason and change nothing; the task stays claimed under your epoch, so fix and resubmit before the lease ends.",
8389
8900
  "NOT FOR: giving the task back undecided (talonic_release_decision_task) or declaring it undecidable (talonic_fail_decision_task). Stale epoch is HTTP 409.",
@@ -8399,7 +8910,7 @@ var DESCRIPTIONS2 = {
8399
8910
  AUTH_NOTE
8400
8911
  ].join("\n"),
8401
8912
  fail: [
8402
- "Report that the claimed decision task cannot be decided: raises a Human Review with your reason AND applies the app's declared fallback policy (rules decide, hold for review, or fail the run).",
8913
+ "Report that the claimed decision task cannot be decided: sends it to a person for review with your reason AND applies the app's declared fallback policy (rules decide, hold for review, or fail the run).",
8403
8914
  "",
8404
8915
  "USE WHEN: the package is insufficient or contradictory and no claimant could decide it. This ends the task (status 'failed').",
8405
8916
  "NOT FOR: temporary give-backs (talonic_release_decision_task) or a decision you can make with low confidence (submit it with confidence set).",
@@ -8421,7 +8932,7 @@ function registerDecisionTaskTools(server, getToken, baseUrl, options = {}) {
8421
8932
  title: "List Decision Tasks",
8422
8933
  description: DESCRIPTIONS2.list,
8423
8934
  inputSchema: listInput2,
8424
- annotations: { title: "List Decision Tasks", ...READ_ONLY3 },
8935
+ annotations: { title: "List Decision Tasks", ...READ_ONLY4 },
8425
8936
  ...metaFor("listDecisionTasks")
8426
8937
  },
8427
8938
  async (args) => handleListDecisionTasks(getToken, baseUrl, args)
@@ -8432,7 +8943,7 @@ function registerDecisionTaskTools(server, getToken, baseUrl, options = {}) {
8432
8943
  title: "Claim Decision Task",
8433
8944
  description: DESCRIPTIONS2.claim,
8434
8945
  inputSchema: idInput2,
8435
- annotations: { title: "Claim Decision Task", ...MUTATING2 },
8946
+ annotations: { title: "Claim Decision Task", ...MUTATING3 },
8436
8947
  ...metaFor("claimDecisionTask")
8437
8948
  },
8438
8949
  async (args) => handleClaimDecisionTask(getToken, baseUrl, args)
@@ -8443,7 +8954,7 @@ function registerDecisionTaskTools(server, getToken, baseUrl, options = {}) {
8443
8954
  title: "Read Decision Package",
8444
8955
  description: DESCRIPTIONS2.package,
8445
8956
  inputSchema: packageInput,
8446
- annotations: { title: "Read Decision Package", ...READ_ONLY3 },
8957
+ annotations: { title: "Read Decision Package", ...READ_ONLY4 },
8447
8958
  ...metaFor("readDecisionPackage")
8448
8959
  },
8449
8960
  async (args) => handleReadDecisionPackage(getToken, baseUrl, args)
@@ -8454,7 +8965,7 @@ function registerDecisionTaskTools(server, getToken, baseUrl, options = {}) {
8454
8965
  title: "Heartbeat Decision Task",
8455
8966
  description: DESCRIPTIONS2.heartbeat,
8456
8967
  inputSchema: epochInput,
8457
- annotations: { title: "Heartbeat Decision Task", ...MUTATING2 },
8968
+ annotations: { title: "Heartbeat Decision Task", ...MUTATING3 },
8458
8969
  ...metaFor("heartbeatDecisionTask")
8459
8970
  },
8460
8971
  async (args) => handleHeartbeatDecisionTask(getToken, baseUrl, args)
@@ -8465,7 +8976,7 @@ function registerDecisionTaskTools(server, getToken, baseUrl, options = {}) {
8465
8976
  title: "Submit Decision Task",
8466
8977
  description: DESCRIPTIONS2.submit,
8467
8978
  inputSchema: submitInput2,
8468
- annotations: { title: "Submit Decision Task", ...MUTATING2 },
8979
+ annotations: { title: "Submit Decision Task", ...MUTATING3 },
8469
8980
  ...metaFor("submitDecisionTask")
8470
8981
  },
8471
8982
  async (args) => handleSubmitDecisionTask(getToken, baseUrl, args)
@@ -8476,7 +8987,7 @@ function registerDecisionTaskTools(server, getToken, baseUrl, options = {}) {
8476
8987
  title: "Release Decision Task",
8477
8988
  description: DESCRIPTIONS2.release,
8478
8989
  inputSchema: epochInput,
8479
- annotations: { title: "Release Decision Task", ...MUTATING2 },
8990
+ annotations: { title: "Release Decision Task", ...MUTATING3 },
8480
8991
  ...metaFor("releaseDecisionTask")
8481
8992
  },
8482
8993
  async (args) => handleReleaseDecisionTask(getToken, baseUrl, args)
@@ -8493,8 +9004,238 @@ function registerDecisionTaskTools(server, getToken, baseUrl, options = {}) {
8493
9004
  async (args) => handleFailDecisionTask(getToken, baseUrl, args)
8494
9005
  );
8495
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
+ }
8496
9237
  var DESCRIPTION11 = [
8497
- "Get the OCR-converted markdown text of a document.",
9238
+ "Get the full text of a document as markdown, including scanned pages.",
8498
9239
  "",
8499
9240
  "USE WHEN: the user wants the full text \u2014 'what does it say', summarise, or translate a document.",
8500
9241
  "NOT FOR: specific structured fields (use talonic_extract with a schema).",
@@ -8519,7 +9260,7 @@ var inputSchema10 = {
8519
9260
  };
8520
9261
  var outputSchema11 = {
8521
9262
  document_id: z.string().describe("ID of the document the markdown was extracted from."),
8522
- markdown: z.string().describe("OCR-converted markdown text content of the document."),
9263
+ markdown: z.string().describe("The document's full text as markdown."),
8523
9264
  cost: z.object({
8524
9265
  costCredits: z.number(),
8525
9266
  costEur: z.number(),
@@ -8600,11 +9341,11 @@ function registerToMarkdown(server, getTalonic, opts = {}) {
8600
9341
  }
8601
9342
  var MATURITIES = ["core", "proven", "candidate"];
8602
9343
  var maturityArg = z.enum(MATURITIES).optional().describe(
8603
- "Filter by maturity: `core` (universal, fully trusted \u2014 safe to build on), `proven` (recurring, stable id), `candidate` (newly discovered, may still be merged or renamed)."
9344
+ "Filter by maturity: `core` (established and trusted, safe to build on), `proven` (recurring, stable id), `candidate` (seen recently, may still be merged or renamed)."
8604
9345
  );
8605
9346
  var fieldIdArg = zUuid().optional().describe("Field UUID (from talonic_list_fields / talonic_search).");
8606
9347
  var fieldNameArg = z.string().min(1).optional().describe(
8607
- "Field NAME instead of an id \u2014 resolved through canonical name, synonyms, merge aliases and the registry's spelling fold, then followed to the live concept. Use the user's wording ('Invoice No', 'Vertragsnummer')."
9348
+ "Field NAME instead of an id \u2014 matched against the field's name, other spellings and synonyms, including fields that were merged into it. Use the user's wording ('Invoice No', 'Vertragsnummer')."
8608
9349
  );
8609
9350
  async function resolveFieldId(getToken, baseUrl, args) {
8610
9351
  if (args.field_id) return { id: args.field_id };
@@ -8617,18 +9358,20 @@ async function resolveFieldId(getToken, baseUrl, args) {
8617
9358
  };
8618
9359
  }
8619
9360
  var LIST_DESCRIPTION4 = [
8620
- "List the workspace's Field Registry \u2014 the canonical concepts Talonic has discovered across every ingested document, each with a stable id, maturity level, data type, synonyms and occurrence count.",
9361
+ "List the fields your workspace's documents carry (vendor name, invoice total, notice period \u2026), each with a stable id, how established it is (maturity), data type, synonyms and how often it occurs.",
8621
9362
  "",
8622
9363
  "USE WHEN: you need to know WHAT data exists before querying it, want to pick the right concept for a question, or need the exact field id for talonic_get_field / talonic_field_values.",
8623
- "NOT FOR: locating a specific document (talonic_search) or filtering documents by a value (talonic_filter). Not a warm-up before answering a question about the documents: call talonic_ask for that. The registry holds many one-off candidate fields; pass maturity core or proven unless the user asks for candidates.",
9364
+ "NOT FOR: locating a specific document (talonic_search) or filtering documents by a value (talonic_filter). Not a warm-up before answering a question about the documents: call talonic_ask for that. Many fields are one-off candidates; pass maturity core or proven unless the user asks for candidates.",
8624
9365
  "",
8625
- "ARGS: `search` (case-insensitive contains on name), `maturity` (core | proven | candidate \u2014 prefer `core`/`proven` for anything you will build on), `include_superseded` (default false: rows merged into another concept are hidden so you never see two ids for one concept), `limit`, `cursor`.",
9366
+ "ARGS: `search` (case-insensitive contains on name), `maturity` (core | proven | candidate \u2014 prefer `core`/`proven` for anything you will build on), `include_superseded` (default false: fields merged into another are hidden so you never see two ids for one field), `limit`, `cursor`.",
8626
9367
  "RETURNS: data[] of { id, canonical_name, display_name, data_type, maturity, tier, synonyms, description, occurrence_count, superseded_by, links } plus cursor pagination."
8627
9368
  ].join("\n");
8628
9369
  var listFieldsInputSchema = {
8629
9370
  search: z.string().optional().describe("Case-insensitive contains match on canonical_name / display_name."),
8630
9371
  maturity: maturityArg,
8631
- include_superseded: z.boolean().optional().describe("Include rows merged into a survivor (they carry `superseded_by`). Default false."),
9372
+ include_superseded: z.boolean().optional().describe(
9373
+ "Include fields merged into another one (they carry `superseded_by`). Default false."
9374
+ ),
8632
9375
  limit: z.number().int().min(1).max(100).optional().describe("Page size (default 20, max 100)."),
8633
9376
  cursor: z.string().optional().describe("Opaque cursor from pagination.next_cursor.")
8634
9377
  };
@@ -8646,20 +9389,18 @@ async function handleListFields(getToken, baseUrl, args) {
8646
9389
  );
8647
9390
  }
8648
9391
  var GET_DESCRIPTION3 = [
8649
- "Get the CONCEPT CARD for one Field Registry field: what it means (curated description + extraction instruction), its synonyms and aliases, maturity, where it occurs (document/occurrence counts, first/last seen, document-type spread), its value distribution (top values with counts, distinct count, examples), schema usage, and identity links (superseded_by, absorbed concepts).",
9392
+ "Describe one field: what it means, its synonyms and other names, maturity, where it occurs (document and occurrence counts, first and last seen, which document types), its values (top values with counts, distinct count, examples), which schemas use it, and the fields merged into it (superseded_by).",
8650
9393
  "",
8651
- "USE WHEN: you must decide whether a field is the right concept for a question, need example values or the value shape before writing a filter, or hold a field NAME from the user and need the live concept behind it.",
9394
+ "USE WHEN: you must decide whether a field is the right one for a question, need example values or the value shape before writing a filter, or hold a field NAME from the user and need the field behind it.",
8652
9395
  "NOT FOR: listing many fields (talonic_list_fields) or reading every value (talonic_field_values).",
8653
9396
  "",
8654
- "ARGS: exactly one of `field_id` or `name`. Names are resolved through canonical name \u2192 spelling fold \u2192 merge aliases \u2192 synonyms (then case-insensitive fallbacks) and followed to the live concept; the response says which arm matched. `include_history: true` appends the curation trail (merges, renames, maturity moves).",
9397
+ "ARGS: exactly one of `field_id` or `name`. A name is matched against field names, other spellings and synonyms and followed to the current field; `resolution` says how it matched. `include_history: true` adds the field's history (merges, renames, maturity changes).",
8655
9398
  "RETURNS: the card { id, canonical_name, maturity, data_type, definition, identity, occurrence, values, usage, links } plus `resolution` when a name was given and `history` when requested."
8656
9399
  ].join("\n");
8657
9400
  var getFieldInputSchema = {
8658
9401
  field_id: fieldIdArg,
8659
9402
  name: fieldNameArg,
8660
- include_history: z.boolean().optional().describe(
8661
- "Append the concept's curation history (tier changes, merges, renames), newest first."
8662
- )
9403
+ include_history: z.boolean().optional().describe("Add the field's history (maturity changes, merges, renames), newest first.")
8663
9404
  };
8664
9405
  async function handleGetField(getToken, baseUrl, args) {
8665
9406
  if (!args.field_id && !args.name) return validationError("Provide `field_id` or `name`.");
@@ -8687,9 +9428,9 @@ async function handleGetField(getToken, baseUrl, args) {
8687
9428
  });
8688
9429
  }
8689
9430
  var VALUES_DESCRIPTION = [
8690
- "Read a field's CURRENT VALUES across documents, with provenance \u2014 one row per bound occurrence: document id + filename + type, the value, confidence, the raw name it was captured under, the verbatim source text, and how confidently the raw name was matched to this concept (`resolved_by`).",
9431
+ "Read a field's CURRENT VALUES across documents, with evidence: one row per value, with the document id, filename and type, the value, its confidence, the label it appeared under in the document, the exact source text, and how the label was matched to this field (`resolved_by`).",
8691
9432
  "",
8692
- "USE WHEN: the user asks 'what are all the X across my documents', you need to tabulate or aggregate one concept across the corpus, or you want the evidence (source text + document) behind a value.",
9433
+ "USE WHEN: the user asks 'what are all the X across my documents', you need to tabulate or total one field across all documents, or you want the evidence (source text + document) behind a value.",
8693
9434
  "NOT FOR: multi-field row-shaped queries over documents (talonic_filter) or one document's full field set (talonic_get_document).",
8694
9435
  "",
8695
9436
  "ARGS: exactly one of `field_id` or `name`; optional `document_id` (one document), `value` (case-insensitive contains filter), `limit` (max 100), `cursor`.",
@@ -8795,13 +9536,13 @@ function unwrap(res) {
8795
9536
  }
8796
9537
  var documentIdsArg = z.array(zUuid()).max(1e3).optional().describe("Restrict to these document ids (hard filter, enforced server-side).");
8797
9538
  var FIND_DESCRIPTION = [
8798
- "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.",
9539
+ "Find where the data behind a concept lives before querying anything: turns a phrase ('payment volume per transaction', 'counterparty', 'Vertragslaufzeit') into the fields, values, documents and text passages that carry it, matching what it means as well as its words, even when the field has a different name.",
8799
9540
  "",
8800
- "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.",
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 sit in a document's text rather than in a field. Pass `account` whenever the question names one portfolio company (an account from talonic_list_accounts), so another company's figures cannot come back.",
8801
9542
  "NOT FOR: reading a known field's values (talonic_field_values) or filtering by a known field (talonic_filter).",
8802
9543
  "",
8803
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).",
8804
- "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."
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 ready to pass to the next call. Read-only."
8805
9546
  ].join("\n");
8806
9547
  var findDataInputSchema = {
8807
9548
  query: z.string().min(1).describe("The natural-language concept to locate."),
@@ -8836,14 +9577,14 @@ async function handleFindData(getToken, baseUrl, args) {
8836
9577
  }
8837
9578
  var DEDICATED = /* @__PURE__ */ new Set(["find_data"]);
8838
9579
  var LIST_TOOLS_DESCRIPTION = [
8839
- "List the platform's agent tool registry \u2014 every retrieval, provenance and analysis primitive the in-product Talonic agent runs on (find_data, describe_data, query_data for read-only SQL over the extracted data, get_document_markdown, workspace_overview, \u2026) with its input schema and whether THIS credential may invoke it.",
9580
+ "List Talonic's data tools: read-only look-ups and queries over the workspace (find_data, describe_data, query_data for a read-only SQL query over the extracted data, get_document_markdown, workspace_overview, \u2026), each with its input schema and whether THIS credential may call it.",
8840
9581
  "Target API: https://talonic.com/docs/api (GET /v1/agent/tools).",
8841
9582
  "",
8842
9583
  "USE WHEN: you want a capability talonic_* tools do not cover directly (e.g. SQL over the structured data, a workspace overview, cohort discovery) \u2014 list here, then call talonic_invoke_agent_tool with the tool name and its args.",
8843
- "NOT FOR: answering the user's question about their documents \u2014 call talonic_ask, which runs these same tools server-side in one call and returns a cited answer. Also not for discovering fields (talonic_find_data) or documents (talonic_search).",
9584
+ "NOT FOR: answering the user's question about their documents \u2014 call talonic_ask, which answers in one call with citations. Also not for discovering fields (talonic_find_data) or documents (talonic_search).",
8844
9585
  "",
8845
9586
  "ARGS: `only_invocable` (default true \u2014 hide tools this credential cannot run), `include_schemas` (default true \u2014 include each tool's JSON input schema).",
8846
- "RETURNS: { tools[] of { name, description, impact, capability, can_invoke, input_schema? }, invocable_count, totalCount }. Registry tools that already have their own talonic_* tool (find_data) are left out; call the dedicated tool."
9587
+ "RETURNS: { tools[] of { name, description, impact, capability, can_invoke, input_schema? }, invocable_count, totalCount }. Data tools that already have their own talonic_* tool (find_data) are left out; call the dedicated tool."
8847
9588
  ].join("\n");
8848
9589
  var listAgentToolsInputSchema = {
8849
9590
  only_invocable: z.boolean().optional().describe("Hide tools this credential cannot invoke. Default true."),
@@ -8874,12 +9615,12 @@ async function handleListAgentTools(getToken, baseUrl, args) {
8874
9615
  });
8875
9616
  }
8876
9617
  var INVOKE_DESCRIPTION = [
8877
- "Invoke ONE named tool from the platform's agent tool registry directly, with no model in the loop (e.g. `query_data` for a read-only SQL SELECT over the extracted data, `describe_data` for the queryable field list, `get_document_markdown` to read a document's text).",
8878
- "READ-ONLY FOR EVERY CREDENTIAL: the platform runs each caller of this route, API key or OAuth session alike, as its least-privilege viewer role, which grants only the registry's read-only tools (capability `data.read`). Write-capable registry tools are never invocable here, however you connected, so this tool reads and never changes workspace data.",
8879
- "Target API: Talonic agent tool registry \u2014 https://talonic.com/docs/api (POST /v1/agent/tools/{name}/invoke; input schemas from talonic_list_agent_tools).",
9618
+ "Run ONE named data tool directly and get its exact output (e.g. `query_data` for a read-only SQL SELECT over the extracted data, `describe_data` for the queryable field list, `get_document_markdown` to read a document's text).",
9619
+ "READ-ONLY FOR EVERY CREDENTIAL: the platform runs each caller of this route, API key or OAuth session alike, as its least-privilege viewer role, which grants only the read-only data tools (capability `data.read`). Tools that write are never invocable here, however you connected, so this tool reads and never changes workspace data.",
9620
+ "Target API: Talonic data tools \u2014 https://talonic.com/docs/api (POST /v1/agent/tools/{name}/invoke; input schemas from talonic_list_agent_tools).",
8880
9621
  "",
8881
9622
  "USE WHEN: talonic_list_agent_tools showed a tool with can_invoke: true that does what you need. Pass exactly the `args` its input_schema declares.",
8882
- "NOT FOR: answering a question about the documents (talonic_ask runs these tools server-side and returns one cited answer). Use this only for a query the user asked for, or when talonic_ask could not answer.",
9623
+ "NOT FOR: answering a question about the documents (talonic_ask returns one cited answer). Use this only for a query the user asked for, or when talonic_ask could not answer.",
8883
9624
  "",
8884
9625
  "ARGS: `name` (tool name), `args` (object matching the tool's input_schema), optional `document_ids` (hard scope for scope-aware tools).",
8885
9626
  "RETURNS: { tool, result (the tool's parsed output), citations?, artifacts?, cards? }. Denied capabilities come back as an error naming the capability required; the platform re-checks every call."
@@ -8987,15 +9728,15 @@ function registerAgentRegistryTools(server, getToken, baseUrl, opts = {}) {
8987
9728
  );
8988
9729
  }
8989
9730
  var LIST_DESCRIPTION5 = [
8990
- "List the workspace's Specs. A Spec is a saved extraction pipeline: an ordered list of processing steps plus the fields it produces; talonic_run_spec runs it over documents. Each row: id, name, description, schema_id (the schema the run's output rows follow \u2014 a DIFFERENT id from the Spec's), version / materialized_version (the published version runs use; null = never published), field_count, node_count, timestamps.",
9731
+ "List the workspace's Specs. A Spec is a saved way of reading one kind of document: the fields it produces and the steps (reading, checks, look-ups, reviews) that fill them; talonic_run_spec runs it over documents. Each row: id, name, description, schema_id (the schema the run's output rows follow \u2014 a DIFFERENT id from the Spec's), version / materialized_version (the published version runs use; null = never published), field_count, node_count, timestamps.",
8991
9732
  "",
8992
- "USE WHEN: the user wants to run 'their pipeline' / 'the invoice Spec', or you need a spec_id for talonic_run_spec / talonic_get_spec.",
9733
+ "USE WHEN: the user wants to run 'their invoice Spec' / 'our contract set-up', or you need a spec_id for talonic_run_spec / talonic_get_spec.",
8993
9734
  "NOT FOR: ad-hoc extraction schemas (talonic_list_schemas) or discovering fields (talonic_list_fields). Not a warm-up before answering a question about the documents: call talonic_ask for that.",
8994
9735
  "ARGS: optional `search` (name contains, case-insensitive), `limit` (1\u2013100, default 20), `cursor` (from pagination.next_cursor), `order` (asc|desc by updated_at).",
8995
9736
  "RETURNS: { data[] of { id, name, description, schema_id, version, materialized_version, materialized_at, field_count, node_count, created_at, updated_at, links }, pagination { total, limit, has_more, next_cursor } }."
8996
9737
  ].join("\n");
8997
9738
  var GET_DESCRIPTION4 = [
8998
- "Get one Spec's structure: identity and version state, the schema its output rows follow, `nodes[]` (the processing steps as the user configured them, in editing order), `phases[]` (the steps as they actually run, in run order; one configured validation step can run as several phases, so the two lists can differ), and `fields[]` (Spec field \u2194 schema field).",
9739
+ "Get one Spec's structure: identity and version state, the schema its output rows follow, `nodes[]` (the steps as the user set them up, in editing order), `phases[]` (the same steps in the order a run carries them out; one check can appear more than once, so the two lists can differ), and `fields[]` (Spec field \u2194 schema field).",
8999
9740
  "",
9000
9741
  "USE WHEN: you need to explain what a run will do, confirm a Spec is published (`version` non-null) before talonic_run_spec, or map field names to keys.",
9001
9742
  "NOT FOR: listing Specs (talonic_list_specs) or starting a run (talonic_run_spec).",
@@ -9035,7 +9776,7 @@ async function handleGetSpec(getToken, baseUrl, args) {
9035
9776
  return { ...spec, versions: versions.data ?? [] };
9036
9777
  });
9037
9778
  }
9038
- var READ_ONLY4 = {
9779
+ var READ_ONLY6 = {
9039
9780
  readOnlyHint: true,
9040
9781
  destructiveHint: false,
9041
9782
  idempotentHint: true,
@@ -9045,10 +9786,10 @@ function registerSpecTools(server, getToken, baseUrl) {
9045
9786
  server.registerTool(
9046
9787
  "talonic_list_specs",
9047
9788
  {
9048
- title: "List pipelines",
9789
+ title: "List Specs",
9049
9790
  description: LIST_DESCRIPTION5,
9050
9791
  inputSchema: listSpecsInputSchema,
9051
- annotations: { title: "List pipelines", ...READ_ONLY4 },
9792
+ annotations: { title: "List Specs", ...READ_ONLY6 },
9052
9793
  _meta: widgetToolMeta("listSpecs")
9053
9794
  },
9054
9795
  async (args) => handleListSpecs(getToken, baseUrl, args)
@@ -9056,10 +9797,10 @@ function registerSpecTools(server, getToken, baseUrl) {
9056
9797
  server.registerTool(
9057
9798
  "talonic_get_spec",
9058
9799
  {
9059
- title: "Look up a pipeline",
9800
+ title: "Look up a Spec",
9060
9801
  description: GET_DESCRIPTION4,
9061
9802
  inputSchema: getSpecInputSchema,
9062
- annotations: { title: "Look up a pipeline", ...READ_ONLY4 },
9803
+ annotations: { title: "Look up a Spec", ...READ_ONLY6 },
9063
9804
  _meta: widgetToolMeta("getSpec")
9064
9805
  },
9065
9806
  async (args) => handleGetSpec(getToken, baseUrl, args)
@@ -9072,15 +9813,15 @@ function mapRunStatus(raw) {
9072
9813
  return "processing";
9073
9814
  }
9074
9815
  var RUN_DESCRIPTION3 = [
9075
- "Run a Spec \u2014 the customer's configured pipeline \u2014 over documents, in one call. Two inputs: `document_ids` (documents already in the workspace; for a new file, first talonic_request_upload \u2192 poll talonic_get_document until completed) OR `file_urls` (public https files, max 20; Talonic ingests them first). Consumes credits.",
9816
+ "Run one of the workspace's Specs over documents, in one call, and get one structured row per document. Two inputs: `document_ids` (documents already in the workspace; for a new file, first talonic_request_upload \u2192 poll talonic_get_document until completed) OR `file_urls` (public https files, max 20; Talonic fetches and reads them first). Consumes credits.",
9076
9817
  "",
9077
- "USE WHEN: the user wants to 'run the invoice pipeline on these documents', process files through their Spec, or produce the Spec's structured rows.",
9818
+ "USE WHEN: the user wants to 'run the invoice Spec on these documents', process files through their Spec, or produce the Spec's structured rows.",
9078
9819
  "NOT FOR: one-off extraction with an ad-hoc schema (talonic_extract), or checking progress (talonic_get_run) / reading rows (talonic_get_run_results).",
9079
- "ARGS: `spec_id` (talonic_list_specs); exactly one of `document_ids[]` (1\u2013500) or `file_urls[]` (1\u201320, https); optional `name`, `pipeline_mode` (`new` default | `append` to the Spec's existing pipeline); `batch_id` and flat `metadata` only with file_urls.",
9820
+ "ARGS: `spec_id` (talonic_list_specs); exactly one of `document_ids[]` (1\u2013500) or `file_urls[]` (1\u201320, https); optional `name`, `pipeline_mode` (`new` default | `append` to the Spec's current run); `batch_id` and flat `metadata` only with file_urls.",
9080
9821
  "RETURNS: RunEnvelope { run_kind ('pipeline'|'run'), run_id, pipeline_id, spec_id, status ('processing'|'completed'|'failed'), raw_status, input_count, documents?, message?, links }. Then poll talonic_get_run with the `pipeline_id` when run_kind is 'pipeline', or with the `run_id` when it is 'run', every 5\u201310 s until status is completed/failed, then talonic_get_run_results."
9081
9822
  ].join("\n");
9082
9823
  var GET_RUN_DESCRIPTION = [
9083
- "Poll a Spec run started by talonic_run_spec: normalised status plus document-level progress and, for pipelines, per-phase progress.",
9824
+ "Poll a Spec run started by talonic_run_spec: normalised status plus progress per document and, for run_kind 'pipeline', per step.",
9084
9825
  "",
9085
9826
  "USE WHEN: waiting for a run to finish \u2014 poll every 5\u201310 s; stop on `completed` or `failed`.",
9086
9827
  "NOT FOR: reading the structured rows (talonic_get_run_results) or starting a run (talonic_run_spec).",
@@ -9088,7 +9829,7 @@ var GET_RUN_DESCRIPTION = [
9088
9829
  "RETURNS: { run_kind, run_id, pipeline_id, spec_id, status, raw_status, input_count?, progress { total_documents, completed_documents, error_documents, phases?[] }, documents?[], error_message?, created_at, updated_at }."
9089
9830
  ].join("\n");
9090
9831
  var RESULTS_DESCRIPTION = [
9091
- "Read a Spec run's structured rows \u2014 one row per document with the Spec's fields as clean values (held/pending-review cells serialize null), plus the column definitions.",
9832
+ "Read a Spec run's structured rows \u2014 one row per document with the Spec's fields as clean values (values held for review come back null), plus the column definitions.",
9092
9833
  "",
9093
9834
  "USE WHEN: talonic_get_run reports `completed` (partial rows are also readable while `processing`).",
9094
9835
  "NOT FOR: progress (talonic_get_run) or per-field provenance of a single value (include: ['provenance'] here, or talonic_field_values).",
@@ -9104,7 +9845,7 @@ var runSpecInputSchema = {
9104
9845
  document_ids: documentIdsArg2,
9105
9846
  file_urls: fileUrlsArg,
9106
9847
  name: z.string().min(1).max(200).optional().describe("Display name for the run."),
9107
- pipeline_mode: z.enum(["new", "append"]).optional().describe("`new` (default) or `append` to the Spec's existing pipeline."),
9848
+ pipeline_mode: z.enum(["new", "append"]).optional().describe("`new` (default) or `append` to the Spec's current run."),
9108
9849
  batch_id: z.string().min(1).max(200).optional().describe("Caller grouping key (file_urls path only)."),
9109
9850
  metadata: metadataArg
9110
9851
  };
@@ -9114,7 +9855,7 @@ var runRefInputSchema = {
9114
9855
  };
9115
9856
  var resultsInputSchema = {
9116
9857
  run_id: uuid.optional().describe(
9117
- "The RunEnvelope's run_id. Alone: a run_kind 'run' submission (/v1/run). With pipeline_id: scopes the pipeline's rows to that submission."
9858
+ "The RunEnvelope's run_id. Alone: a run_kind 'run' submission (/v1/run). With pipeline_id: only the rows of that submission."
9118
9859
  ),
9119
9860
  pipeline_id: uuid.optional().describe(
9120
9861
  "The RunEnvelope's pipeline_id (run_kind 'pipeline'); rows come from /v1/pipelines/{id}/results."
@@ -9275,7 +10016,7 @@ async function handleGetRunResults(getToken, baseUrl, args) {
9275
10016
  return { run_kind: kind, ...body };
9276
10017
  });
9277
10018
  }
9278
- var READ_ONLY5 = {
10019
+ var READ_ONLY7 = {
9279
10020
  readOnlyHint: true,
9280
10021
  destructiveHint: false,
9281
10022
  idempotentHint: true,
@@ -9285,11 +10026,11 @@ function registerRunTools(server, getToken, baseUrl) {
9285
10026
  server.registerTool(
9286
10027
  "talonic_run_spec",
9287
10028
  {
9288
- title: "Run a pipeline",
10029
+ title: "Run a Spec",
9289
10030
  description: RUN_DESCRIPTION3,
9290
10031
  inputSchema: runSpecInputSchema,
9291
10032
  annotations: {
9292
- title: "Run a pipeline",
10033
+ title: "Run a Spec",
9293
10034
  readOnlyHint: false,
9294
10035
  destructiveHint: false,
9295
10036
  openWorldHint: true
@@ -9304,7 +10045,7 @@ function registerRunTools(server, getToken, baseUrl) {
9304
10045
  title: "Check run progress",
9305
10046
  description: GET_RUN_DESCRIPTION,
9306
10047
  inputSchema: runRefInputSchema,
9307
- annotations: { title: "Check run progress", ...READ_ONLY5 },
10048
+ annotations: { title: "Check run progress", ...READ_ONLY7 },
9308
10049
  _meta: widgetToolMeta("getRun")
9309
10050
  },
9310
10051
  async (args) => handleGetRun(getToken, baseUrl, args)
@@ -9315,7 +10056,7 @@ function registerRunTools(server, getToken, baseUrl) {
9315
10056
  title: "Read run results",
9316
10057
  description: RESULTS_DESCRIPTION,
9317
10058
  inputSchema: resultsInputSchema,
9318
- annotations: { title: "Read run results", ...READ_ONLY5 },
10059
+ annotations: { title: "Read run results", ...READ_ONLY7 },
9319
10060
  _meta: widgetToolMeta("getRunResults")
9320
10061
  },
9321
10062
  async (args) => handleGetRunResults(getToken, baseUrl, args)
@@ -9326,9 +10067,9 @@ var ASK_DEFAULT_WAIT_S = 45;
9326
10067
  var ASK_MAX_WAIT_S = 55;
9327
10068
  var POLL_HINT = "still processing \u2014 call talonic_get_answer with this ask_id in a few seconds";
9328
10069
  var ASK_DESCRIPTION = [
9329
- "Ask a natural-language question over the workspace's documents and get a cited, verified answer (markdown). The Talonic agent plans over the workspace's extracted fields, runs read-only SQL over extracted cells, reads document text, and grounds every load-bearing claim in a source span. Consumes credits.",
10070
+ "Ask a natural-language question over the workspace's documents and get a cited, verified answer (markdown). Talonic looks across the extracted data and the documents' text, backs every claim that matters with a quote from a source document, and checks the answer before returning it. Consumes credits.",
9330
10071
  "",
9331
- "USE WHEN (the default for questions): the user asks anything about what their documents contain \u2014 counts, totals, duplicates, comparisons, anomalies ('which vendors invoiced us twice in May?'), or a summary across documents. One call replaces exploring fields, schemas, specs and SQL yourself; skip that exploration.",
10072
+ "USE WHEN (the default for questions): the user asks anything about what their documents contain \u2014 counts, totals, duplicates, comparisons, anomalies ('which vendors invoiced us twice in May?'), or a summary across documents. One call replaces exploring fields, schemas, Specs and queries yourself; skip that exploration.",
9332
10073
  "NOT FOR: reading a known field's values (talonic_field_values, free) or filtering documents by a known value (talonic_filter, free); locating which field holds a concept (talonic_find_data).",
9333
10074
  "ARGS: `question`; optional `scope` { document_ids[], schema_id, pipeline_id, data_product_id, document_type, source_id, tags[], ingested_after, ingested_before } (ANDed), `conversation_id` (continue a thread), `output_format` { instruction, template }, `wait_seconds` (0\u201355, default 45).",
9334
10075
  "RETURNS: { ask_id, status ('completed'|'processing'|'error'), conversation_id, answer (markdown), citations[] { quote, document_id, kind, filename, app_url }, verification { verdict, checks_total, checks_unsupported, correction }, usage { tokens, credits_charged }, tool_calls, artifacts[], waited_ms }. If status is still 'processing' after the wait, call talonic_get_answer with the ask_id."
@@ -9345,7 +10086,7 @@ var uuid2 = zUuid();
9345
10086
  var scopeSchema = z.object({
9346
10087
  document_ids: z.array(uuid2).max(500).optional().describe("Only these documents."),
9347
10088
  schema_id: uuid2.optional().describe("Only documents extracted with this schema."),
9348
- pipeline_id: uuid2.optional().describe("Only documents of this pipeline run."),
10089
+ pipeline_id: uuid2.optional().describe("Only documents of this Spec run."),
9349
10090
  data_product_id: uuid2.optional().describe(
9350
10091
  "Only documents of this data product (a curated document collection; rarely needed)."
9351
10092
  ),
@@ -9358,11 +10099,13 @@ var scopeSchema = z.object({
9358
10099
  var askInputSchema = {
9359
10100
  question: z.string().min(1).max(4e3).describe("The question, in the user's words."),
9360
10101
  scope: scopeSchema,
9361
- conversation_id: uuid2.optional().describe("Continue this conversation; the agent sees prior turns."),
10102
+ conversation_id: uuid2.optional().describe("Continue this conversation; earlier questions and answers are taken into account."),
9362
10103
  output_format: z.object({
9363
10104
  instruction: z.string().max(1e3).optional(),
9364
10105
  template: z.string().max(4e3).optional()
9365
- }).optional().describe("Shape the answer (form only, never grounding)."),
10106
+ }).optional().describe(
10107
+ "Shape the answer's layout (a table, a list, a template); never changes which sources it rests on."
10108
+ ),
9366
10109
  wait_seconds: z.number().int().min(0).max(ASK_MAX_WAIT_S).optional().describe(
9367
10110
  `Seconds to wait for the answer before returning 'processing' (default ${ASK_DEFAULT_WAIT_S}, max ${ASK_MAX_WAIT_S}).`
9368
10111
  )
@@ -11566,7 +12309,7 @@ function registerToolGroups(server, keys, getToken, baseUrl) {
11566
12309
 
11567
12310
  // package.json
11568
12311
  var package_default = {
11569
- version: "0.1.104"};
12312
+ version: "0.1.106"};
11570
12313
 
11571
12314
  // src/version.ts
11572
12315
  var VERSION = package_default.version;
@@ -11629,6 +12372,16 @@ function buildServerInstructions(opts) {
11629
12372
  "apps:decide consent and a senior_member role or above; on HTTP 403 tell the user",
11630
12373
  "which consent or role is missing instead of retrying."
11631
12374
  ] : [],
12375
+ ...opts.includeAppsToolset ? [
12376
+ "To build an app: talonic_create_app -> talonic_save_app_draft ->",
12377
+ "talonic_interpret_app_rules -> talonic_publish_app -> talonic_run_app (dry_run first) ->",
12378
+ "talonic_get_app_run or talonic_get_run_verdicts -> talonic_check_app_acceptance.",
12379
+ "Human Reviews: talonic_list_app_reviews -> talonic_resolve_app_review."
12380
+ ] : [],
12381
+ ...opts.includeMiningDriverTools ? [
12382
+ "A rule-finding round waiting for an outside driver is claimed and closed with the",
12383
+ "decision-task tools; in between, call its tools with talonic_mining_call_round_tool."
12384
+ ] : [],
11632
12385
  "Tools that change workspace data (saving schemas, app updates, decisions) should only",
11633
12386
  "be called when the user asked for that change. Every error ends with a 'Next step'",
11634
12387
  "line: follow it.",
@@ -11692,7 +12445,9 @@ function createServer(options) {
11692
12445
  instructions: buildServerInstructions({
11693
12446
  includeGenericExecutor: options.includeGenericExecutor !== false,
11694
12447
  includeAgentTaskTools: options.includeAgentTaskTools !== false,
11695
- includeDecisionTaskTools: options.includeDecisionTaskTools !== false
12448
+ includeDecisionTaskTools: options.includeDecisionTaskTools !== false,
12449
+ includeAppsToolset: options.includeAppsToolset === true,
12450
+ includeMiningDriverTools: options.includeMiningDriverTools === true
11696
12451
  })
11697
12452
  }
11698
12453
  );
@@ -11734,6 +12489,14 @@ function createServer(options) {
11734
12489
  invocable: options.decisionTasksInvocable !== false
11735
12490
  });
11736
12491
  }
12492
+ if (options.includeAppsToolset) {
12493
+ registerAppsToolset(server, rawToken, baseUrl);
12494
+ }
12495
+ if (options.includeMiningDriverTools) {
12496
+ registerMiningDriverTools(server, rawToken, baseUrl, {
12497
+ invocable: options.decisionTasksInvocable !== false
12498
+ });
12499
+ }
11737
12500
  if (options.includeGrowthTools) {
11738
12501
  registerGrowthTools(server, rawToken, baseUrl);
11739
12502
  }
@@ -11802,6 +12565,9 @@ var FAVICON_BASE64 = "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAAABGdBTUEAAL
11802
12565
  var FAVICON_BYTES = Buffer.from(FAVICON_BASE64, "base64");
11803
12566
 
11804
12567
  // src/http-server.ts
12568
+ if (!globalThis.crypto) {
12569
+ Object.defineProperty(globalThis, "crypto", { value: webcrypto, configurable: true });
12570
+ }
11805
12571
  var PORT = Number(process.env["PORT"] ?? 3e3);
11806
12572
  var PROBE_TTL_MS = 5 * 60 * 1e3;
11807
12573
  function makeAccessCache(defaultProbe) {
@@ -11836,6 +12602,8 @@ var growthAccessCached = makeAccessCache(pathProbe("/v1/growth/access"));
11836
12602
  var adminAgentTaskAccessCached = makeAccessCache(pathProbe("/v1/agent-tasks/admin/access"));
11837
12603
  var agentTasksAccessCached = makeAccessCache((t) => probeAgentTasksInUse(t, base()));
11838
12604
  var decisionTasksAccessCached = makeAccessCache((t) => probeExternalAppsInUse(t, base()));
12605
+ var appsToolsetAccessCached = makeAccessCache((t) => probeAppsToolsetAccess(t, base()));
12606
+ var miningAccessCached = makeAccessCache((t) => probeMiningInUse(t, base()));
11839
12607
  var toolGroupCaches = TOOL_GROUPS.map(
11840
12608
  (g) => [g.key, makeAccessCache((t) => probeGroup(g, t, base()))]
11841
12609
  );
@@ -11868,13 +12636,13 @@ async function tokenAcceptedCached(token, probe = probeTokenAccepted, now = Date
11868
12636
  tokenCheckCache.set(key2, { ok, expiresAt: now() + TOKEN_CHECK_TTL_MS });
11869
12637
  return ok;
11870
12638
  }
11871
- function readBody(req, limit2) {
12639
+ function readBody(req, limit3) {
11872
12640
  return new Promise((resolve, reject) => {
11873
12641
  const chunks = [];
11874
12642
  let size = 0;
11875
12643
  req.on("data", (chunk) => {
11876
12644
  size += chunk.length;
11877
- if (size > limit2) {
12645
+ if (size > limit3) {
11878
12646
  req.removeAllListeners("data");
11879
12647
  req.resume();
11880
12648
  resolve(null);
@@ -12137,7 +12905,9 @@ function createRequestHandler(options = {}) {
12137
12905
  includePortfolioTools,
12138
12906
  includeProcessesTools,
12139
12907
  includeAgentTaskTools,
12140
- includeDecisionTaskTools,
12908
+ externalAppsInUse,
12909
+ includeAppsToolset,
12910
+ includeMiningDriverTools,
12141
12911
  toolGroups
12142
12912
  ] = await Promise.all([
12143
12913
  (options.growthAccess ?? growthAccessCached)(token),
@@ -12153,8 +12923,11 @@ function createRequestHandler(options = {}) {
12153
12923
  (options.processesAccess ?? processesAccessCached)(token),
12154
12924
  (options.agentTasksAccess ?? agentTasksAccessCached)(token),
12155
12925
  (options.decisionTasksAccess ?? decisionTasksAccessCached)(token),
12926
+ (options.appsToolsetAccess ?? appsToolsetAccessCached)(token),
12927
+ (options.miningAccess ?? miningAccessCached)(token),
12156
12928
  (options.toolGroupsAccess ?? toolGroupsAccessCached)(token)
12157
12929
  ]);
12930
+ const includeDecisionTaskTools = externalAppsInUse || includeMiningDriverTools;
12158
12931
  const mcpServer = createServer({
12159
12932
  tokenProvider: () => token,
12160
12933
  includeGrowthTools,
@@ -12170,6 +12943,8 @@ function createRequestHandler(options = {}) {
12170
12943
  includeProcessesTools,
12171
12944
  includeAgentTaskTools,
12172
12945
  includeDecisionTaskTools,
12946
+ includeAppsToolset,
12947
+ includeMiningDriverTools,
12173
12948
  toolGroups,
12174
12949
  ...process.env["TALONIC_BASE_URL"] ? { baseUrl: process.env["TALONIC_BASE_URL"] } : {},
12175
12950
  // Listing UX only: an OAuth token that visibly lacks apps:decide gets
@@ -12218,6 +12993,6 @@ if (isDirectInvocation()) {
12218
12993
  });
12219
12994
  }
12220
12995
 
12221
- export { adminAgentTaskAccessCached, agentTasksAccessCached, apAccessCached, contractsAccessCached, createRequestHandler, decisionTasksAccessCached, docGenAccessCached, growthAccessCached, isOpenAiClient, masterRecordsAccessCached, partiesAccessCached, portfolioAccessCached, priceBaselineAccessCached, processesAccessCached, submissionsAccessCached, tokenAcceptedCached, toolGroupsAccessCached };
12996
+ export { adminAgentTaskAccessCached, agentTasksAccessCached, apAccessCached, appsToolsetAccessCached, contractsAccessCached, createRequestHandler, decisionTasksAccessCached, docGenAccessCached, growthAccessCached, isOpenAiClient, masterRecordsAccessCached, miningAccessCached, partiesAccessCached, portfolioAccessCached, priceBaselineAccessCached, processesAccessCached, submissionsAccessCached, tokenAcceptedCached, toolGroupsAccessCached };
12222
12997
  //# sourceMappingURL=http-server.js.map
12223
12998
  //# sourceMappingURL=http-server.js.map