@sanity/workflow-mcp 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -15,7 +15,7 @@ Operate a running instance:
15
15
  | Tool | Read or write | What it's for |
16
16
  | ------------------------- | ------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
17
17
  | `list_workflow_instances` | read | Discover what's running. Filterable, capped. |
18
- | `get_workflow_state` | read | Project one instance into a flat shape: current stage, tasks, available actions, recent history. |
18
+ | `get_workflow_state` | read | Project one instance into a flat shape: current stage, activities, available actions, recent history. |
19
19
  | `diagnose_workflow` | read | Explain why an instance is or isn't progressing: a verdict, a one-line summary, and — when stuck — the cause plus suggested remediations. |
20
20
  | `fire_action` | write | Advance state. The only write. Mirrors the engine's universal "something happened" entry point. |
21
21
 
package/dist/index.cjs CHANGED
@@ -3,16 +3,15 @@ Object.defineProperty(exports, "__esModule", { value: !0 });
3
3
  var workflowEngine = require("@sanity/workflow-engine"), define = require("@sanity/workflow-engine/define");
4
4
  const minimalExample = {
5
5
  name: "quick-approval",
6
- version: 1,
7
6
  title: "Quick approval",
8
7
  description: "One review stage with a single approve action, then a terminal stage.",
9
8
  initialStage: "review",
10
- fields: [{ type: "doc.ref", name: "subject", title: "Document", source: { type: "init" } }],
9
+ fields: [{ type: "doc.ref", name: "subject", title: "Document", initialValue: { type: "input" } }],
11
10
  stages: [
12
11
  {
13
12
  name: "review",
14
13
  title: "Review",
15
- tasks: [
14
+ activities: [
16
15
  {
17
16
  name: "decide",
18
17
  title: "Decide",
@@ -26,16 +25,15 @@ const minimalExample = {
26
25
  ]
27
26
  }, reviewLoopExample = {
28
27
  name: "doc-review",
29
- version: 1,
30
28
  title: "Document review",
31
29
  description: "Draft, then editorial review that approves or rejects back to drafting.",
32
30
  initialStage: "drafting",
33
- fields: [{ type: "doc.ref", name: "subject", title: "Document", source: { type: "init" } }],
31
+ fields: [{ type: "doc.ref", name: "subject", title: "Document", initialValue: { type: "input" } }],
34
32
  stages: [
35
33
  {
36
34
  name: "drafting",
37
35
  title: "Drafting",
38
- tasks: [
36
+ activities: [
39
37
  {
40
38
  name: "write",
41
39
  title: "Write the draft",
@@ -48,7 +46,7 @@ const minimalExample = {
48
46
  {
49
47
  name: "review",
50
48
  title: "Editorial review",
51
- tasks: [
49
+ activities: [
52
50
  {
53
51
  name: "review",
54
52
  title: "Review the draft",
@@ -61,18 +59,18 @@ const minimalExample = {
61
59
  ],
62
60
  transitions: [
63
61
  { name: "to-approved", title: "Approve and finish", to: "approved" },
64
- // Reject flips the task to `failed`; this routes the instance back.
62
+ // Reject flips the activity to `failed`; this routes the instance back.
65
63
  {
66
64
  name: "to-drafting",
67
65
  title: "Send back to drafting",
68
66
  to: "drafting",
69
- filter: "$anyTaskFailed"
67
+ filter: "$anyActivityFailed"
70
68
  }
71
69
  ]
72
70
  },
73
71
  { name: "approved", title: "Approved", description: "Terminal \u2014 no transitions out." }
74
72
  ]
75
- }, ORIENTATION = "# Authoring a workflow definition\n\nA workflow definition is a plain JSON object. There is no code in it \u2014 every\ncondition (filters, predicates, guards) is a GROQ *string*. Generate the JSON,\nthen call `validate_workflow_definition` to check it; fix the reported errors\nand re-validate until it returns `valid: true`. The validator returns the\n*desugared* definition under `definition` \u2014 that is exactly what would deploy.\n\n## Shape\n\n- **Workflow**: `{ name, version (positive int), title, description?, initialStage, fields?, stages[], predicates? }`.\n `initialStage` must be the `name` of a declared stage.\n- **Stage**: `{ name, title?, description?, tasks?, transitions? }`. A stage with\n no transitions is terminal. Reaching a terminal stage ends the workflow.\n- **Task**: `{ name, title?, activation?, actions? }`. `activation` is `'auto'`\n (starts when the stage is entered) or `'manual'` (default \u2014 a human starts it).\n- **Action**: `{ name, title?, status?, params?, ops? }`.\n `status: 'done' | 'skipped' | 'failed'` is sugar that flips the *firing task* to\n that status when the action fires. `ops` are mutations applied when the action\n fires (e.g. `{type:'field.set', target:{field:'x'}, value:{type:'param', param:'p'}}`).\n `params` are values the action collects from the caller (referenced by\n `{type:'param', param:'<name>'}` sources).\n- **Transition**: `{ name, title?, to, filter? }`. `to` must name a declared\n stage. `filter` is a GROQ condition gating the exit; omit it and it defaults\n to `$allTasksDone`.\n- **Field** (workflow- or stage-scoped persistent state): `{ type, name, title?, source }`.\n Common `type`s: `doc.ref`, `doc.refs`, `value.string`, `value.url`,\n `value.number`, `value.boolean`. `source` is where the value comes from:\n `{type:'init'}` (supplied when the instance starts), `{type:'write'}` (a user\n edits it), `{type:'param', param:'<actionParamName>'}`, `{type:'now'}`, `{type:'actor'}`.\n By convention a workflow has an `init`-sourced `doc.ref` named `subject` \u2014 the\n headline document it is about.\n\n## GROQ in conditions\n\nBuilt-in variables available in filters/predicates: `$allTasksDone`,\n`$anyTaskFailed` (booleans over the current stage's tasks), `$tasks` (the task\nlist), `$fields` (field values), `$now`, and the caller-scoped vars `$actor`\n(the acting user), `$assigned` (whether the caller is the task's assignee \u2014 the\nidiomatic permission gate, used as `filter: '$assigned'`), and `$can`. Define\nreusable named conditions under top-level `predicates: { name: '<groq>' }` and\nreference them as `$name` (e.g.\n`predicates: { ready: \"count($tasks[status != 'done']) == 0\" }` \u2192 `$ready`).\n\nConditions evaluate against an in-memory snapshot (the instance + its subject +\nfield-declared docs) \u2014 **never** scan by `_type` (e.g. `*[_type==\"article\"]`);\nthat is a discovery query and the validator rejects it. To bring a document into\nscope, declare a `doc.ref` field for it.\n\n## Sugars worth knowing\n\n- Action `status: 'done' | 'skipped' | 'failed'` \u2014 flips the firing task (shown above).\n- Omitted transition `filter` \u2014 defaults to `$allTasksDone`.\n- Omitted task `activation` \u2014 defaults to `'manual'`.\n\n## Modeling defaults\n\nValid is not the same as good. Prefer these unless the request says otherwise:\n\n- **A decline/reject loops back.** Route a rejected / changes-requested\n transition to an *earlier* stage for revision (e.g. `review \u2192 drafting` gated\n on `$anyTaskFailed`), not to a terminal stage. Reserve terminal stages for\n completion and for explicit cancellation/abandonment \u2014 a workflow should not\n dead-end just because something was declined.\n- **Prefer draft \u2192 review.** Model an author working in a drafting stage who\n submits, then a review stage that gates. Don't add more review stages unless\n the request asks for multiple approvers or rounds.\n- **When the shape is ambiguous, pick the conventional one and confirm** with the\n user rather than inventing extra stages.\n\n## Rules the validator enforces\n\n- Stage names, task names (per stage) and transition names are unique.\n- Every transition `to` and `initialStage` names a declared stage.\n- Custom `predicates` must not shadow a built-in (e.g. `allTasksDone`).\n- Every GROQ string must parse and must not be a `_type` discovery scan.", AUTHORING_GUIDE = `${ORIENTATION}
73
+ }, ORIENTATION = "# Authoring a workflow definition\n\nA workflow definition is a plain JSON object. There is no code in it \u2014 every\ncondition (filters, predicates, guards) is a GROQ *string*. Generate the JSON,\nthen call `validate_workflow_definition` to check it; fix the reported errors\nand re-validate until it returns `valid: true`. The validator returns the\n*desugared* definition under `definition` \u2014 that is exactly what would deploy.\n\n## Shape\n\n- **Workflow**: `{ name, title, description?, initialStage, fields?, stages[], predicates? }`.\n `initialStage` must be the `name` of a declared stage. Do NOT include a\n `version` \u2014 definitions are immutable and content-addressed; deploy assigns\n the version from the content, the author never writes one.\n- **Stage**: `{ name, title?, description?, activities?, transitions? }`. A stage with\n no transitions is terminal. Reaching a terminal stage ends the workflow.\n- **Activity**: `{ name, title?, activation?, actions? }`. `activation` is `'auto'`\n (starts when the stage is entered) or `'manual'` (default \u2014 a human starts it).\n- **Action**: `{ name, title?, status?, params?, ops? }`.\n `status: 'done' | 'skipped' | 'failed'` is sugar that flips the *firing activity* to\n that status when the action fires. `ops` are mutations applied when the action\n fires (e.g. `{type:'field.set', target:{field:'x'}, value:{type:'param', param:'p'}}`).\n `params` are values the action collects from the caller (referenced by\n `{type:'param', param:'<name>'}` sources).\n- **Transition**: `{ name, title?, to, filter? }`. `to` must name a declared\n stage. `filter` is a GROQ condition gating the exit; omit it and it defaults\n to `$allActivitiesDone`.\n- **Field** (workflow- or stage-scoped persistent state): `{ type, name, title?, initialValue? }`.\n Scalar `type`s mirror Sanity: `string`, `text` (multiline), `number`,\n `boolean`, `date` (YYYY-MM-DD), `datetime` (ISO), `url`. Plus references\n (`doc.ref`, `doc.refs`, `release.ref`), identities (`actor` \u2014 one concrete\n principal; `assignee` / `assignees` \u2014 one or many user-or-role assignees), and\n the compositional kinds `object` (`{ type:'object', name, fields: [...] }`) and\n `array` (`{ type:'array', name, of: [...] }`) \u2014 `fields`/`of` are themselves\n field shapes, so any structure composes. `initialValue` seeds the slot once at\n materialisation and is **optional** \u2014 omit it for op-filled working memory\n (the common default). Arms: `{type:'input'}` (the caller supplies it when the\n instance starts), `{type:'query', query:'<groq>'}` (computed from the lake),\n `{type:'literal', value:<json>}`, or `{type:'fieldRead', field:'<name>'}`.\n By convention a workflow has an `input`-sourced `doc.ref` named `subject` \u2014 the\n headline document it is about.\n Two list sugars desugar to `array`: `{type:'todoList', name}` (ad-hoc\n status-tracked work \u2014 rows `{ label, status, assignee?, dueDate? }`) and\n `{type:'notes', name}` (an append-only audit/comment log \u2014 rows\n `{ body, actor, at }`; pairs with the `audit` op, which stamps `actor`/`at`).\n\n## GROQ in conditions\n\nBuilt-in variables available in filters/predicates: `$allActivitiesDone`,\n`$anyActivityFailed` (booleans over the current stage's activities), `$activities` (the activity\nlist), `$fields` (field values), `$now`, and the caller-scoped vars `$actor`\n(the acting user), `$assigned` (whether the caller is the activity's assignee \u2014 the\nidiomatic permission gate, used as `filter: '$assigned'`), and `$can`. Define\nreusable named conditions under top-level `predicates: { name: '<groq>' }` and\nreference them as `$name` (e.g.\n`predicates: { ready: \"count($activities[status != 'done']) == 0\" }` \u2192 `$ready`).\n\nConditions evaluate against an in-memory snapshot (the instance + its subject +\nfield-declared docs) \u2014 **never** scan by `_type` (e.g. `*[_type==\"article\"]`);\nthat is a discovery query and the validator rejects it. To bring a document into\nscope, declare a `doc.ref` field for it.\n\n## Sugars worth knowing\n\n- Action `status: 'done' | 'skipped' | 'failed'` \u2014 flips the firing activity (shown above).\n- Omitted transition `filter` \u2014 defaults to `$allActivitiesDone`.\n- Omitted activity `activation` \u2014 defaults to `'manual'`.\n\n## Modeling defaults\n\nValid is not the same as good. Prefer these unless the request says otherwise:\n\n- **A decline/reject loops back.** Route a rejected / changes-requested\n transition to an *earlier* stage for revision (e.g. `review \u2192 drafting` gated\n on `$anyActivityFailed`), not to a terminal stage. Reserve terminal stages for\n completion and for explicit cancellation/abandonment \u2014 a workflow should not\n dead-end just because something was declined.\n- **Prefer draft \u2192 review.** Model an author working in a drafting stage who\n submits, then a review stage that gates. Don't add more review stages unless\n the request asks for multiple approvers or rounds.\n- **When the shape is ambiguous, pick the conventional one and confirm** with the\n user rather than inventing extra stages.\n\n## Rules the validator enforces\n\n- Stage names, activity names (per stage) and transition names are unique.\n- Every transition `to` and `initialStage` names a declared stage.\n- Custom `predicates` must not shadow a built-in (e.g. `allActivitiesDone`).\n- Every GROQ string must parse and must not be a `_type` discovery scan.", AUTHORING_GUIDE = `${ORIENTATION}
76
74
 
77
75
  ## Examples
78
76
 
@@ -107,7 +105,7 @@ ${JSON.stringify(reviewLoopExample, null, 2)}
107
105
  },
108
106
  {
109
107
  name: "get_workflow_state",
110
- description: "Get the current state of a single workflow instance, projected for action. Returns the workflow's id and human-readable `workflowTitle`, the current stage, the subject document the workflow is about (when the workflow has a conventional subject \u2014 its ref and title), every task on the current stage with its available actions (and whether each action is currently allowed), and the most recent history entries. Use this whenever you need to understand what's possible on an instance before deciding to act. This is a pure read \u2014 it does not change anything. If you only need to discover what instances exist, use list_workflow_instances instead; this tool requires you to know the instance id. list_workflow_instances also returns the same `workflowTitle` and `subject` fields, so prefer it for fan-out discovery rather than polling get_workflow_state per instance.",
108
+ description: "Get the current state of a single workflow instance, projected for action. Returns the workflow's id and human-readable `workflowTitle`, the current stage, the subject document the workflow is about (when the workflow has a conventional subject \u2014 its ref and title), every activity on the current stage with its available actions (and whether each action is currently allowed), and the most recent history entries. Use this whenever you need to understand what's possible on an instance before deciding to act. This is a pure read \u2014 it does not change anything. If you only need to discover what instances exist, use list_workflow_instances instead; this tool requires you to know the instance id. list_workflow_instances also returns the same `workflowTitle` and `subject` fields, so prefer it for fan-out discovery rather than polling get_workflow_state per instance.",
111
109
  input_schema: {
112
110
  type: "object",
113
111
  properties: {
@@ -122,7 +120,7 @@ ${JSON.stringify(reviewLoopExample, null, 2)}
122
120
  },
123
121
  {
124
122
  name: "diagnose_workflow",
125
- description: "Explain why a single workflow instance is or isn't progressing. Returns a verdict (`state`: progressing, waiting, blocked, completed, aborted, or stuck), a one-line `summary`, and \u2014 when stuck \u2014 a structured `cause` plus the `remediations` that would unstick it. Use this when an instance seems stalled or the user asks \"why isn't this moving?\": it distinguishes a healthy instance (waiting on a human, or will advance on its own) from a genuinely stuck one (a failed effect or task, a dead-end transition). This is a pure read \u2014 it changes nothing, and the remediations it names are advisory: none can be executed through this server. To actually advance a healthy waiting instance use fire_action; for per-task action detail use get_workflow_state.",
123
+ description: "Explain why a single workflow instance is or isn't progressing. Returns a verdict (`state`: progressing, waiting, blocked, completed, aborted, or stuck), a one-line `summary`, and \u2014 when stuck \u2014 a structured `cause` plus the `remediations` that would unstick it. Use this when an instance seems stalled or the user asks \"why isn't this moving?\": it distinguishes a healthy instance (waiting on a human, or will advance on its own) from a genuinely stuck one (a failed effect or activity, a dead-end transition). This is a pure read \u2014 it changes nothing, and the remediations it names are advisory: none can be executed through this server. To actually advance a healthy waiting instance use fire_action; for per-activity action detail use get_workflow_state.",
126
124
  input_schema: {
127
125
  type: "object",
128
126
  properties: {
@@ -137,7 +135,7 @@ ${JSON.stringify(reviewLoopExample, null, 2)}
137
135
  },
138
136
  {
139
137
  name: "fire_action",
140
- description: "Advance a workflow instance by firing an action on one of its tasks. This is the only way to advance workflow state from the outside \u2014 there is no separate 'complete task' or 'transition stage' tool. To find the right (task, action) pair, call get_workflow_state first and pick from the allowed actions listed on the current stage's tasks. After firing, the engine cascades any auto-transitions that become eligible (so an 'approve' action on a review task may transition the workflow to a terminal stage in one shot). Returns the resulting state, same shape as get_workflow_state. If the action is not currently allowed (e.g. the task is already done, or a guard fails), this returns an error describing why.",
138
+ description: "Advance a workflow instance by firing an action on one of its activities. This is the only way to advance workflow state from the outside \u2014 there is no separate 'complete activity' or 'transition stage' tool. To find the right (activity, action) pair, call get_workflow_state first and pick from the allowed actions listed on the current stage's activities. After firing, the engine cascades any auto-transitions that become eligible (so an 'approve' action on a review activity may transition the workflow to a terminal stage in one shot). Returns the resulting state, same shape as get_workflow_state. If the action is not currently allowed (e.g. the activity is already done, or a guard fails), this returns an error describing why.",
141
139
  input_schema: {
142
140
  type: "object",
143
141
  properties: {
@@ -145,16 +143,16 @@ ${JSON.stringify(reviewLoopExample, null, 2)}
145
143
  type: "string",
146
144
  description: "The workflow instance id."
147
145
  },
148
- task: {
146
+ activity: {
149
147
  type: "string",
150
- description: "The id of the task on the current stage. Must be one of the tasks returned by get_workflow_state."
148
+ description: "The id of the activity on the current stage. Must be one of the activities returned by get_workflow_state."
151
149
  },
152
150
  action: {
153
151
  type: "string",
154
- description: "The id of the action on that task. Must be one of the actions listed as allowed=true on the task."
152
+ description: "The id of the action on that activity. Must be one of the actions listed as allowed=true on the activity."
155
153
  }
156
154
  },
157
- required: ["instance_id", "task", "action"],
155
+ required: ["instance_id", "activity", "action"],
158
156
  additionalProperties: !1
159
157
  }
160
158
  },
@@ -238,7 +236,7 @@ function projectSummary(doc, subjectTitles) {
238
236
  };
239
237
  }
240
238
  function projectState(instance, evaluation, subjectTitles) {
241
- const workflowTitle = JSON.parse(instance.definitionSnapshot).title, stageTitle = evaluation.currentStage.stage.title, tasks = evaluation.currentStage.tasks.map((te) => {
239
+ const workflowTitle = JSON.parse(instance.definitionSnapshot).title, stageTitle = evaluation.currentStage.stage.title, activities = evaluation.currentStage.activities.map((te) => {
242
240
  const actions = te.actions.map((ae) => {
243
241
  const verdict = workflowEngine.actionVerdict(te, ae);
244
242
  return {
@@ -249,9 +247,9 @@ function projectState(instance, evaluation, subjectTitles) {
249
247
  };
250
248
  });
251
249
  return {
252
- task: te.task.name,
253
- ...te.task.title !== void 0 ? { title: te.task.title } : {},
254
- ...te.task.description !== void 0 ? { description: te.task.description } : {},
250
+ activity: te.activity.name,
251
+ ...te.activity.title !== void 0 ? { title: te.activity.title } : {},
252
+ ...te.activity.description !== void 0 ? { description: te.activity.description } : {},
255
253
  status: te.status,
256
254
  actions
257
255
  };
@@ -268,7 +266,7 @@ function projectState(instance, evaluation, subjectTitles) {
268
266
  ...stageTitle !== void 0 ? { currentStageTitle: stageTitle } : {},
269
267
  done: isInstanceDone(instance),
270
268
  ...subject !== void 0 ? { subject } : {},
271
- tasks,
269
+ activities,
272
270
  recentHistory
273
271
  };
274
272
  }
@@ -283,10 +281,10 @@ function isInstanceDone(instance) {
283
281
  }
284
282
  const DISABLED_REASON_TEXT = {
285
283
  "filter-failed": "action's filter condition did not hold for this actor",
286
- "task-not-active": "task is not currently active",
284
+ "activity-not-active": "activity is not currently active",
287
285
  "stage-terminal": "stage is terminal \u2014 no further actions possible",
288
286
  "instance-completed": "instance has already completed",
289
- "requirements-unmet": "task's declared requirements are not yet satisfied"
287
+ "requirements-unmet": "activity's declared requirements are not yet satisfied"
290
288
  };
291
289
  function formatDisabledReason(reason) {
292
290
  return DISABLED_REASON_TEXT[reason.kind] ?? reason.kind.replace(/-/g, " ");
@@ -297,12 +295,12 @@ function summariseHistoryEntry(entry) {
297
295
  return `entered stage "${String(entry.stage)}"`;
298
296
  case "stageExited":
299
297
  return `exited stage "${String(entry.stage)}" \u2192 "${String(entry.toStage)}"`;
300
- case "taskActivated":
301
- return `task "${String(entry.task)}" activated`;
302
- case "taskStatusChanged":
303
- return `task "${String(entry.task)}" status: ${String(entry.from)} \u2192 ${String(entry.to)}`;
298
+ case "activityActivated":
299
+ return `activity "${String(entry.activity)}" activated`;
300
+ case "activityStatusChanged":
301
+ return `activity "${String(entry.activity)}" status: ${String(entry.from)} \u2192 ${String(entry.to)}`;
304
302
  case "actionFired":
305
- return `action "${String(entry.action)}" fired on task "${String(entry.task)}"`;
303
+ return `action "${String(entry.action)}" fired on activity "${String(entry.activity)}"`;
306
304
  case "transitionFired":
307
305
  return `transition fired: "${String(entry.fromStage)}" \u2192 "${String(entry.toStage)}"`;
308
306
  case "effectQueued":
@@ -310,7 +308,7 @@ function summariseHistoryEntry(entry) {
310
308
  case "effectCompleted":
311
309
  return `effect "${String(entry.effect)}" completed (${String(entry.status)})`;
312
310
  case "spawned":
313
- return `spawned child workflow from task "${String(entry.task)}"`;
311
+ return `spawned child workflow from activity "${String(entry.activity)}"`;
314
312
  default:
315
313
  return entry._type;
316
314
  }
@@ -320,9 +318,9 @@ function diagnosisSummary(diagnosis) {
320
318
  case "progressing":
321
319
  return "This instance will advance on its own.";
322
320
  case "waiting":
323
- return `Waiting for action on task "${diagnosis.task}": ${diagnosis.actions.join(" or ")}. This is the normal in-flight state \u2014 it advances when someone acts.`;
321
+ return `Waiting for action on activity "${diagnosis.activity}": ${diagnosis.actions.join(" or ")}. This is the normal in-flight state \u2014 it advances when someone acts.`;
324
322
  case "blocked":
325
- return `Task "${diagnosis.task}" is visible but not yet executable \u2014 unmet requirement(s): ${diagnosis.requirements.join(", ")}. It will not advance until those are satisfied.`;
323
+ return `Activity "${diagnosis.activity}" is visible but not yet executable \u2014 unmet requirement(s): ${diagnosis.requirements.join(", ")}. It will not advance until those are satisfied.`;
326
324
  case "completed":
327
325
  return `Completed at ${diagnosis.at}.`;
328
326
  case "aborted":
@@ -334,13 +332,13 @@ function diagnosisSummary(diagnosis) {
334
332
  function stuckSummary(cause) {
335
333
  switch (cause.kind) {
336
334
  case "failed-effect":
337
- return `Stuck: a failed effect "${cause.effect.name}" is blocking task "${cause.effect.origin.name}", which can't complete until the effect succeeds.`;
335
+ return `Stuck: a failed effect "${cause.effect.name}" is blocking activity "${cause.effect.origin.name}", which can't complete until the effect succeeds.`;
338
336
  case "hung-effect":
339
337
  return `Stuck: effect "${cause.effect.name}" was claimed but never completed \u2014 the drainer likely died mid-dispatch, so it won't drain on its own.`;
340
- case "failed-task":
341
- return `Stuck: task "${cause.task}" is in a terminal failed state, so any exit transition gated on it can never fire.`;
338
+ case "failed-activity":
339
+ return `Stuck: activity "${cause.activity}" is in a terminal failed state, so any exit transition gated on it can never fire.`;
342
340
  case "no-transition-fires":
343
- return "Stuck: every task is resolved but no exit transition's filter is satisfied \u2014 likely a routing state value a filter reads was never written.";
341
+ return "Stuck: every activity is resolved but no exit transition's filter is satisfied \u2014 likely a routing state value a filter reads was never written.";
344
342
  case "transition-unevaluable":
345
343
  return `Stuck (recoverable): exit transition(s) ${cause.transitions.join(", ")} read an operand that is missing or unreadable (GROQ null). It advances on its own once that data becomes readable \u2014 no manual fix needed.`;
346
344
  }
@@ -364,7 +362,7 @@ function buildTools(engine, options = {}) {
364
362
  const input = parseFireActionInput(rawInput);
365
363
  return await engine.fireAction({
366
364
  instanceId: input.instance_id,
367
- task: input.task,
365
+ activity: input.activity,
368
366
  action: input.action,
369
367
  ...accessOverride !== void 0 ? { access: accessOverride } : {}
370
368
  }), getInstanceState(engine, input.instance_id, accessOverride);
@@ -409,12 +407,12 @@ function parseFireActionInput(raw) {
409
407
  if (raw === null || typeof raw != "object")
410
408
  throw new Error("fire_action: input must be an object");
411
409
  const obj = raw;
412
- for (const key of ["instance_id", "task", "action"])
410
+ for (const key of ["instance_id", "activity", "action"])
413
411
  if (typeof obj[key] != "string" || obj[key] === "")
414
412
  throw new Error(`fire_action: ${key} is required`);
415
413
  return {
416
414
  instance_id: obj.instance_id,
417
- task: obj.task,
415
+ activity: obj.activity,
418
416
  action: obj.action
419
417
  };
420
418
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":["../src/authoring-guide.ts","../src/descriptors.ts","../src/projection.ts","../src/tools.ts"],"sourcesContent":["/**\n * Content for the `get_workflow_authoring_guide` tool.\n *\n * The agent calling the MCP server generates the workflow definition; this\n * guide is what teaches it the DSL well enough to do that on the first pass.\n * It is the orientation the examples can't convey on their own (the GROQ\n * built-ins, the sugars, the hard rules) plus two worked examples.\n *\n * The examples are kept inline (rather than imported from\n * `@sanity/workflow-examples`) on purpose: that package exports the *desugared*\n * `WorkflowDefinition` (the post-`defineWorkflow` shape), but an agent should emit\n * the *authoring* (sugar) shape — JSON, exactly what `validate_workflow_definition`\n * accepts — so importing the examples would show the wrong shape. Keeping them\n * inline also avoids promoting `@sanity/workflow-examples` to a runtime dependency\n * of a package headed for host embedding. The companion test runs every example\n * through the real validators, so a stale snippet fails CI rather than misleading\n * an agent.\n */\n\nimport type {AuthoringWorkflow} from '@sanity/workflow-engine'\n\nconst minimalExample = {\n name: 'quick-approval',\n version: 1,\n title: 'Quick approval',\n description: 'One review stage with a single approve action, then a terminal stage.',\n initialStage: 'review',\n fields: [{type: 'doc.ref', name: 'subject', title: 'Document', source: {type: 'init'}}],\n stages: [\n {\n name: 'review',\n title: 'Review',\n tasks: [\n {\n name: 'decide',\n title: 'Decide',\n activation: 'auto',\n actions: [{name: 'approve', title: 'Approve', status: 'done'}],\n },\n ],\n transitions: [{name: 'to-approved', title: 'Approve and finish', to: 'approved'}],\n },\n {name: 'approved', title: 'Approved', description: 'Terminal — no transitions out.'},\n ],\n} satisfies AuthoringWorkflow\n\nconst reviewLoopExample = {\n name: 'doc-review',\n version: 1,\n title: 'Document review',\n description: 'Draft, then editorial review that approves or rejects back to drafting.',\n initialStage: 'drafting',\n fields: [{type: 'doc.ref', name: 'subject', title: 'Document', source: {type: 'init'}}],\n stages: [\n {\n name: 'drafting',\n title: 'Drafting',\n tasks: [\n {\n name: 'write',\n title: 'Write the draft',\n activation: 'auto',\n actions: [{name: 'submit', title: 'Submit for review', status: 'done'}],\n },\n ],\n transitions: [{name: 'to-review', title: 'Send to review', to: 'review'}],\n },\n {\n name: 'review',\n title: 'Editorial review',\n tasks: [\n {\n name: 'review',\n title: 'Review the draft',\n activation: 'auto',\n actions: [\n {name: 'approve', title: 'Approve', status: 'done'},\n {name: 'reject', title: 'Reject', status: 'failed'},\n ],\n },\n ],\n transitions: [\n {name: 'to-approved', title: 'Approve and finish', to: 'approved'},\n // Reject flips the task to `failed`; this routes the instance back.\n {\n name: 'to-drafting',\n title: 'Send back to drafting',\n to: 'drafting',\n filter: '$anyTaskFailed',\n },\n ],\n },\n {name: 'approved', title: 'Approved', description: 'Terminal — no transitions out.'},\n ],\n} satisfies AuthoringWorkflow\n\n/**\n * Worked examples included verbatim in {@link AUTHORING_GUIDE}, and exercised by\n * the drift-guard test. Authoring (sugar) shape — what an agent passes to\n * `validate_workflow_definition`.\n */\nexport const GUIDE_EXAMPLES: AuthoringWorkflow[] = [minimalExample, reviewLoopExample]\n\nconst ORIENTATION = `# Authoring a workflow definition\n\nA workflow definition is a plain JSON object. There is no code in it — every\ncondition (filters, predicates, guards) is a GROQ *string*. Generate the JSON,\nthen call \\`validate_workflow_definition\\` to check it; fix the reported errors\nand re-validate until it returns \\`valid: true\\`. The validator returns the\n*desugared* definition under \\`definition\\` — that is exactly what would deploy.\n\n## Shape\n\n- **Workflow**: \\`{ name, version (positive int), title, description?, initialStage, fields?, stages[], predicates? }\\`.\n \\`initialStage\\` must be the \\`name\\` of a declared stage.\n- **Stage**: \\`{ name, title?, description?, tasks?, transitions? }\\`. A stage with\n no transitions is terminal. Reaching a terminal stage ends the workflow.\n- **Task**: \\`{ name, title?, activation?, actions? }\\`. \\`activation\\` is \\`'auto'\\`\n (starts when the stage is entered) or \\`'manual'\\` (default — a human starts it).\n- **Action**: \\`{ name, title?, status?, params?, ops? }\\`.\n \\`status: 'done' | 'skipped' | 'failed'\\` is sugar that flips the *firing task* to\n that status when the action fires. \\`ops\\` are mutations applied when the action\n fires (e.g. \\`{type:'field.set', target:{field:'x'}, value:{type:'param', param:'p'}}\\`).\n \\`params\\` are values the action collects from the caller (referenced by\n \\`{type:'param', param:'<name>'}\\` sources).\n- **Transition**: \\`{ name, title?, to, filter? }\\`. \\`to\\` must name a declared\n stage. \\`filter\\` is a GROQ condition gating the exit; omit it and it defaults\n to \\`$allTasksDone\\`.\n- **Field** (workflow- or stage-scoped persistent state): \\`{ type, name, title?, source }\\`.\n Common \\`type\\`s: \\`doc.ref\\`, \\`doc.refs\\`, \\`value.string\\`, \\`value.url\\`,\n \\`value.number\\`, \\`value.boolean\\`. \\`source\\` is where the value comes from:\n \\`{type:'init'}\\` (supplied when the instance starts), \\`{type:'write'}\\` (a user\n edits it), \\`{type:'param', param:'<actionParamName>'}\\`, \\`{type:'now'}\\`, \\`{type:'actor'}\\`.\n By convention a workflow has an \\`init\\`-sourced \\`doc.ref\\` named \\`subject\\` — the\n headline document it is about.\n\n## GROQ in conditions\n\nBuilt-in variables available in filters/predicates: \\`$allTasksDone\\`,\n\\`$anyTaskFailed\\` (booleans over the current stage's tasks), \\`$tasks\\` (the task\nlist), \\`$fields\\` (field values), \\`$now\\`, and the caller-scoped vars \\`$actor\\`\n(the acting user), \\`$assigned\\` (whether the caller is the task's assignee — the\nidiomatic permission gate, used as \\`filter: '$assigned'\\`), and \\`$can\\`. Define\nreusable named conditions under top-level \\`predicates: { name: '<groq>' }\\` and\nreference them as \\`$name\\` (e.g.\n\\`predicates: { ready: \"count($tasks[status != 'done']) == 0\" }\\` → \\`$ready\\`).\n\nConditions evaluate against an in-memory snapshot (the instance + its subject +\nfield-declared docs) — **never** scan by \\`_type\\` (e.g. \\`*[_type==\"article\"]\\`);\nthat is a discovery query and the validator rejects it. To bring a document into\nscope, declare a \\`doc.ref\\` field for it.\n\n## Sugars worth knowing\n\n- Action \\`status: 'done' | 'skipped' | 'failed'\\` — flips the firing task (shown above).\n- Omitted transition \\`filter\\` — defaults to \\`$allTasksDone\\`.\n- Omitted task \\`activation\\` — defaults to \\`'manual'\\`.\n\n## Modeling defaults\n\nValid is not the same as good. Prefer these unless the request says otherwise:\n\n- **A decline/reject loops back.** Route a rejected / changes-requested\n transition to an *earlier* stage for revision (e.g. \\`review → drafting\\` gated\n on \\`$anyTaskFailed\\`), not to a terminal stage. Reserve terminal stages for\n completion and for explicit cancellation/abandonment — a workflow should not\n dead-end just because something was declined.\n- **Prefer draft → review.** Model an author working in a drafting stage who\n submits, then a review stage that gates. Don't add more review stages unless\n the request asks for multiple approvers or rounds.\n- **When the shape is ambiguous, pick the conventional one and confirm** with the\n user rather than inventing extra stages.\n\n## Rules the validator enforces\n\n- Stage names, task names (per stage) and transition names are unique.\n- Every transition \\`to\\` and \\`initialStage\\` names a declared stage.\n- Custom \\`predicates\\` must not shadow a built-in (e.g. \\`allTasksDone\\`).\n- Every GROQ string must parse and must not be a \\`_type\\` discovery scan.`\n\n/**\n * The full text returned by `get_workflow_authoring_guide`: orientation plus the\n * two worked examples rendered as JSON.\n */\nexport const AUTHORING_GUIDE = `${ORIENTATION}\n\n## Examples\n\n### Example 1 — ${minimalExample.title} (minimal: one stage, one action)\n\\`\\`\\`json\n${JSON.stringify(minimalExample, null, 2)}\n\\`\\`\\`\n\n### Example 2 — ${reviewLoopExample.title} (review loop: reject routes back)\n\\`\\`\\`json\n${JSON.stringify(reviewLoopExample, null, 2)}\n\\`\\`\\`\n`\n","/**\n * The MCP tool surface for workflow operations — the static descriptors an\n * agent reads to decide what to call. The implementations live in `tools.ts`;\n * these are pure data (descriptions + JSON schemas) and safe to cache.\n *\n * Two jobs: operate running instances, and author new definitions.\n *\n * Operate an instance:\n *\n * - `list_workflow_instances` is the only way to *discover* what's\n * running without already knowing an id. Filterable, capped.\n * - `get_workflow_state` is the \"tell me everything actionable about\n * one instance\" call. It composes the engine's `evaluate` projection\n * into a flat shape an LLM can reason over without piecing together\n * raw `WorkflowInstance` documents.\n * - `diagnose_workflow` answers \"*why* isn't this moving?\" — it\n * classifies an instance as healthy (waiting/progressing) or genuinely\n * stuck (a failed effect/task, a dead-end transition) and names the\n * remediations that would unstick it. A pure read; the remediations are\n * advisory (none execute through this server).\n * - `fire_action` is the only write. Mirrors the engine's universal\n * \"something happened\" entry point — everything other than admin\n * override flows through it.\n *\n * Author a definition (both pure, engine-independent, neither deploys):\n *\n * - `get_workflow_authoring_guide` returns the DSL guide an agent reads\n * before writing a definition — shape, GROQ built-ins, sugars, examples.\n * - `validate_workflow_definition` runs the deploy-time checks (structure +\n * invariants + GROQ) and returns the desugared definition or a\n * path-prefixed error list. A human deploys it via the CLI.\n *\n * Surface choices that matter for an LLM consumer:\n *\n * - Descriptions are written for an agent, not a human reader.\n * Each one says (a) what the tool does, (b) when to use it,\n * (c) what *not* to use it for.\n * - Parameter names use snake_case, matching MCP convention.\n * - The write tool's description spells out that this is the way\n * to advance workflow state — not a side door. Without that line,\n * an LLM tends to look for a `complete_task` or `set_stage` tool.\n * - Read tools cap their output. A 50-page `recent_history` would\n * burn context and is rarely informative; 8 is enough to spot\n * loops or stuck-in-stage patterns.\n */\n\n/**\n * The descriptor shape the Anthropic Messages API + the MCP SDK both\n * accept. Kept here as a small, transport-neutral interface so we can\n * feed the same descriptors to either consumer.\n */\nexport interface ToolDescriptor {\n name: string\n description: string\n /** JSON Schema describing the tool's parameters. */\n input_schema: {\n type: 'object'\n properties: Record<string, unknown>\n required?: string[]\n additionalProperties?: boolean\n }\n}\n\n/** Maximum instances returned by list_workflow_instances. */\nexport const LIST_CAP = 25\n\n/**\n * The static tool descriptors. Independent of any engine — the bound\n * implementations that close over an engine live in {@link buildTools}.\n */\nexport const TOOL_DESCRIPTORS: ToolDescriptor[] = [\n {\n name: 'list_workflow_instances',\n description:\n 'List workflow instances in the configured workspace. Use this when you need ' +\n \"to find a workflow but don't already know its instance id, or to survey \" +\n \"what's in flight. Returns a compact summary — id, workflow type id and \" +\n 'human-readable `workflowTitle`, current stage, whether the instance is done, ' +\n 'and (when the workflow has a conventional subject document) a `subject` ' +\n \"field with the subject doc's ref and title. Use `workflowTitle` when the \" +\n 'user names the workflow by type (e.g. \"article reviews\") and `subject.title` ' +\n \"when they name a specific in-flight instance by what it's about (e.g. \" +\n '\"the article-review about pricing\"). ' +\n 'Capped at ' +\n String(LIST_CAP) +\n ' results. ' +\n 'Do NOT use this to inspect a single known instance — use get_workflow_state ' +\n 'for that, the response will be richer.',\n input_schema: {\n type: 'object',\n properties: {\n definition: {\n type: 'string',\n description:\n \"Optional. Restrict to instances of this workflow definition (e.g. 'article-review').\",\n },\n status: {\n type: 'string',\n enum: ['in_flight', 'done', 'any'],\n description:\n \"Optional. 'in_flight' returns instances not in a terminal stage; \" +\n \"'done' returns completed/aborted; 'any' returns both. Defaults to 'in_flight'.\",\n },\n },\n additionalProperties: false,\n },\n },\n {\n name: 'get_workflow_state',\n description:\n 'Get the current state of a single workflow instance, projected for action. ' +\n \"Returns the workflow's id and human-readable `workflowTitle`, the current \" +\n 'stage, the subject document the workflow is about (when the workflow has a ' +\n 'conventional subject — its ref and title), every task on the current stage ' +\n 'with its available actions (and whether each action is currently allowed), ' +\n 'and the most recent history entries. Use this whenever you need to understand ' +\n \"what's possible on an instance before deciding to act. \" +\n 'This is a pure read — it does not change anything. ' +\n 'If you only need to discover what instances exist, use list_workflow_instances ' +\n 'instead; this tool requires you to know the instance id. ' +\n 'list_workflow_instances also returns the same `workflowTitle` and `subject` ' +\n 'fields, so prefer it for fan-out discovery rather than polling ' +\n 'get_workflow_state per instance.',\n input_schema: {\n type: 'object',\n properties: {\n instance_id: {\n type: 'string',\n description: 'The workflow instance id.',\n },\n },\n required: ['instance_id'],\n additionalProperties: false,\n },\n },\n {\n name: 'diagnose_workflow',\n description:\n \"Explain why a single workflow instance is or isn't progressing. Returns a \" +\n 'verdict (`state`: progressing, waiting, blocked, completed, aborted, or ' +\n 'stuck), a one-line `summary`, and — when stuck — a structured `cause` plus ' +\n 'the `remediations` that would unstick it. Use this when an instance seems ' +\n 'stalled or the user asks \"why isn\\'t this moving?\": it distinguishes a healthy ' +\n 'instance (waiting on a human, or will advance on its own) from a genuinely ' +\n 'stuck one (a failed effect or task, a dead-end transition). ' +\n 'This is a pure read — it changes nothing, and the remediations it names are ' +\n 'advisory: none can be executed through this server. To actually advance a ' +\n 'healthy waiting instance use fire_action; for per-task action detail use ' +\n 'get_workflow_state.',\n input_schema: {\n type: 'object',\n properties: {\n instance_id: {\n type: 'string',\n description: 'The workflow instance id.',\n },\n },\n required: ['instance_id'],\n additionalProperties: false,\n },\n },\n {\n name: 'fire_action',\n description:\n 'Advance a workflow instance by firing an action on one of its tasks. ' +\n 'This is the only way to advance workflow state from the outside — there is no ' +\n \"separate 'complete task' or 'transition stage' tool. To find the right \" +\n '(task, action) pair, call get_workflow_state first and pick from the ' +\n \"allowed actions listed on the current stage's tasks. \" +\n 'After firing, the engine cascades any auto-transitions that become eligible ' +\n \"(so an 'approve' action on a review task may transition the workflow to a \" +\n 'terminal stage in one shot). Returns the resulting state, same shape as ' +\n 'get_workflow_state. ' +\n 'If the action is not currently allowed (e.g. the task is already done, or a ' +\n 'guard fails), this returns an error describing why.',\n input_schema: {\n type: 'object',\n properties: {\n instance_id: {\n type: 'string',\n description: 'The workflow instance id.',\n },\n task: {\n type: 'string',\n description:\n 'The id of the task on the current stage. Must be one of the tasks ' +\n 'returned by get_workflow_state.',\n },\n action: {\n type: 'string',\n description:\n 'The id of the action on that task. Must be one of the actions listed ' +\n 'as allowed=true on the task.',\n },\n },\n required: ['instance_id', 'task', 'action'],\n additionalProperties: false,\n },\n },\n {\n name: 'get_workflow_authoring_guide',\n description:\n 'Get the guide for authoring a workflow definition: the DSL shape, the ' +\n 'GROQ condition built-ins, the sugars, the rules the validator enforces, ' +\n 'and two worked JSON examples. Call this BEFORE writing a definition from ' +\n 'a description, then generate the JSON and check it with ' +\n 'validate_workflow_definition. Pure read; takes no arguments.',\n input_schema: {\n type: 'object',\n properties: {},\n additionalProperties: false,\n },\n },\n {\n name: 'validate_workflow_definition',\n description:\n 'Validate a workflow definition you have authored. Runs the same checks as ' +\n 'deploy — structural shape, cross-field invariants (e.g. every transition ' +\n 'target is a declared stage), and GROQ syntax — without writing anything. ' +\n 'Returns `{valid:true, definition}` where `definition` is the desugared form ' +\n 'that would deploy, or `{valid:false, error}` with every problem listed and ' +\n 'path-prefixed. This does NOT deploy — a human deploys the validated ' +\n 'definition via the CLI. Call get_workflow_authoring_guide first for the ' +\n 'shape; on `valid:false`, fix the reported problems and validate again.',\n input_schema: {\n type: 'object',\n properties: {\n definition: {\n type: 'object',\n description:\n 'The workflow definition to validate, as a JSON object in authoring ' +\n 'shape. See get_workflow_authoring_guide for the shape and examples.',\n },\n },\n required: ['definition'],\n additionalProperties: false,\n },\n },\n]\n","/**\n * Projection helpers — engine output shaped for an LLM consumer.\n *\n * Why a hand-written projection rather than returning the engine's\n * `WorkflowEvaluation` raw: the LLM only needs (a) which tasks exist,\n * (b) which actions are allowed on each, (c) why an action is denied\n * when it is. The evaluation includes per-stage field-entry resolution\n * and snapshot bookkeeping that bloats the payload without helping\n * the model pick the right next move.\n *\n * The engine reads that feed these live in `tools.ts`; this module is\n * pure shaping plus the one batched subject-title lookup they all share.\n */\n\nimport {\n actionVerdict,\n extractDocumentId,\n isTerminalStage,\n type Diagnosis,\n type Engine,\n type StuckCause,\n type WorkflowDefinition,\n type WorkflowEvaluation,\n type WorkflowInstance,\n} from '@sanity/workflow-engine'\n\nimport type {\n ProjectedActionVerdict,\n ProjectedHistoryEntry,\n ProjectedInstanceState,\n ProjectedInstanceSummary,\n ProjectedSubject,\n ProjectedTask,\n} from './types.ts'\n\n/**\n * The field-entry name we treat as the workflow's \"subject\" — the headline\n * doc the workflow is about. Convention-only (see ProjectedSubject docs);\n * a workflow without an entry with this name won't have `subject` populated\n * on the projection.\n */\nconst SUBJECT_ENTRY_NAME = 'subject'\n\n/** Maximum history entries returned in get_workflow_state. */\nconst HISTORY_CAP = 8\n\n// Subject doc resolution\n//\n// The conventional \"subject\" entry holds a doc.ref to the thing the\n// workflow is about. The entry value is a GDR URI (e.g.\n// `dataset:proj:ds:article-1`) — what `_id` in the store actually\n// uses is the bare `article-1` part. Extract, batch-fetch by id list,\n// build a Map keyed by GDR URI.\n//\n// Known gap: cross-resource subject docs. If the subject lives in a\n// different Sanity resource than the engine's own workflowResource,\n// this lookup misses — the engine's `query` runs against the workflow\n// resource's client. Production-shape fix is to thread the engine's\n// `resourceClients` resolver through here; out of scope for v0.1.\n\n/**\n * Look up the conventional subject entry on a workflow instance's\n * workflow-scope fields. Returns the GDR URI when present, undefined\n * when the workflow has no subject entry or the entry is null.\n */\nfunction getSubjectGdr(instance: WorkflowInstance): string | undefined {\n const entry = instance.fields.find((s) => s._type === 'doc.ref' && s.name === SUBJECT_ENTRY_NAME)\n if (entry === undefined || entry._type !== 'doc.ref') return undefined\n return entry.value?.id\n}\n\n/**\n * Batch-fetch the `title` field for every subject doc referenced by\n * the supplied instances. Returns a `Map<gdrUri, title>` — missing\n * keys mean the doc had no title (or didn't exist / was unreadable).\n * The caller projects `ref` from the GDR either way; this map only\n * controls whether `title` is populated.\n *\n * Single GROQ call regardless of how many instances are supplied. At\n * `LIST_CAP=25` this is cheap; per-instance lookups would be N+1.\n */\nexport async function fetchSubjectTitles(\n engine: Engine,\n instances: WorkflowInstance[],\n): Promise<Map<string, string>> {\n // Build docId → gdrUri so we can attribute results back. Skip any\n // malformed GDRs silently — the projection still surfaces `ref`,\n // the LLM falls back to that as an identifier.\n const docIdToGdr = new Map<string, string>()\n for (const inst of instances) {\n const gdr = getSubjectGdr(inst)\n if (gdr === undefined) continue\n try {\n docIdToGdr.set(extractDocumentId(gdr), gdr)\n } catch {\n // Malformed GDR — leave it out of the title lookup.\n }\n }\n if (docIdToGdr.size === 0) return new Map()\n\n // Subject docs are ordinary content, not workflow docs — they carry no\n // engine tag, so we read them straight off the engine's client rather\n // than through the tag-scoped `engine.query` (which mandates a\n // `$tag` filter). Access is the client credential's concern: a\n // doc the caller can't read simply comes back absent.\n let docs: {_id: string; title?: string}[]\n try {\n docs = await engine.client.fetch<{_id: string; title?: string}[]>(\n '*[_id in $docIds]{_id, title}',\n {docIds: Array.from(docIdToGdr.keys())},\n )\n } catch (err) {\n // Titles are optional enrichment — degrade to bare refs rather than\n // failing the whole tool call when the lookup can't be served.\n process.stderr.write(\n `workflow-mcp: subject-title lookup failed; returning refs without titles: ${\n err instanceof Error ? err.message : String(err)\n }\\n`,\n )\n return new Map()\n }\n\n const out = new Map<string, string>()\n for (const doc of docs) {\n const gdr = docIdToGdr.get(doc._id)\n if (gdr !== undefined && typeof doc.title === 'string' && doc.title !== '') {\n out.set(gdr, doc.title)\n }\n }\n return out\n}\n\n/**\n * Build a `ProjectedSubject` for one instance, given the title map\n * produced by `fetchSubjectTitles`. Returns undefined when the\n * workflow has no subject entry; returns `{ ref }` without `title`\n * when the entry is present but the doc has no title field.\n */\nfunction buildSubject(\n instance: WorkflowInstance,\n subjectTitles: Map<string, string>,\n): ProjectedSubject | undefined {\n const gdr = getSubjectGdr(instance)\n if (gdr === undefined) return undefined\n const title = subjectTitles.get(gdr)\n return title !== undefined ? {ref: gdr, title} : {ref: gdr}\n}\n\nexport function projectSummary(\n doc: WorkflowInstance,\n subjectTitles: Map<string, string>,\n): ProjectedInstanceSummary {\n const definition = JSON.parse(doc.definitionSnapshot) as WorkflowDefinition\n const stage = definition.stages.find((s) => s.name === doc.currentStage)\n const stageTitle = stage?.title\n const workflowTitle = definition.title\n const subject = buildSubject(doc, subjectTitles)\n return {\n instanceId: doc._id,\n definition: doc.definition,\n ...(workflowTitle !== undefined ? {workflowTitle} : {}),\n currentStage: doc.currentStage,\n ...(stageTitle !== undefined ? {currentStageTitle: stageTitle} : {}),\n lastChangedAt: doc.lastChangedAt,\n done: isInstanceDone(doc),\n ...(subject !== undefined ? {subject} : {}),\n }\n}\n\nexport function projectState(\n instance: WorkflowInstance,\n evaluation: WorkflowEvaluation,\n subjectTitles: Map<string, string>,\n): ProjectedInstanceState {\n // The evaluation already exposes the current stage's title from the\n // snapshot, but not the workflow's own title — parse the snapshot\n // once here to read it.\n const definition = JSON.parse(instance.definitionSnapshot) as WorkflowDefinition\n const workflowTitle = definition.title\n const stageTitle = evaluation.currentStage.stage.title\n\n const tasks: ProjectedTask[] = evaluation.currentStage.tasks.map((te) => {\n // Each action's verdict comes from the engine's shared `actionVerdict` —\n // the same \"is this firable, and why not\" the CLI reads — so the verdict\n // shape has one source; we keep the LLM-shaped per-task nesting.\n const actions: ProjectedActionVerdict[] = te.actions.map((ae) => {\n const verdict = actionVerdict(te, ae)\n return {\n action: verdict.action,\n ...(verdict.title !== undefined ? {title: verdict.title} : {}),\n allowed: verdict.allowed,\n ...(verdict.allowed === false && verdict.disabledReason !== undefined\n ? {disabledReason: formatDisabledReason(verdict.disabledReason)}\n : {}),\n }\n })\n\n return {\n task: te.task.name,\n ...(te.task.title !== undefined ? {title: te.task.title} : {}),\n ...(te.task.description !== undefined ? {description: te.task.description} : {}),\n status: te.status,\n actions,\n }\n })\n\n const recentHistory: ProjectedHistoryEntry[] = instance.history\n .slice(-HISTORY_CAP)\n .toReversed()\n .map((entry) => ({\n at: entry.at,\n type: entry._type,\n summary: summariseHistoryEntry(entry),\n }))\n\n const subject = buildSubject(instance, subjectTitles)\n return {\n instanceId: instance._id,\n definition: instance.definition,\n ...(workflowTitle !== undefined ? {workflowTitle} : {}),\n currentStage: instance.currentStage,\n ...(stageTitle !== undefined ? {currentStageTitle: stageTitle} : {}),\n done: isInstanceDone(instance),\n ...(subject !== undefined ? {subject} : {}),\n tasks,\n recentHistory,\n }\n}\n\nexport function isInstanceDone(instance: WorkflowInstance): boolean {\n // The engine sets `completedAt` when an instance enters a terminal\n // stage; falling back to the structural check covers any edge case\n // where the definition snapshot is the source of truth.\n if (instance.completedAt !== undefined) return true\n try {\n const definition = JSON.parse(instance.definitionSnapshot) as WorkflowDefinition\n const stage = definition.stages.find((s) => s.name === instance.currentStage)\n return stage !== undefined && isTerminalStage(stage)\n } catch {\n return false\n }\n}\n\n/**\n * Engine `disabledReason` is a structured tagged union (see\n * `DisabledReason` in @sanity/workflow-engine). For an LLM\n * we want a short English phrase rather than the tagged shape — the\n * tagged shape is still available on the raw evaluation if a richer\n * consumer wants it.\n */\nconst DISABLED_REASON_TEXT: Record<string, string> = {\n 'filter-failed': \"action's filter condition did not hold for this actor\",\n 'task-not-active': 'task is not currently active',\n 'stage-terminal': 'stage is terminal — no further actions possible',\n 'instance-completed': 'instance has already completed',\n 'requirements-unmet': \"task's declared requirements are not yet satisfied\",\n}\n\nfunction formatDisabledReason(reason: {kind: string}): string {\n // Fall back to a humanised form of the kind for reasons we don't have\n // bespoke copy for, so a new engine reason never renders as a raw enum.\n return DISABLED_REASON_TEXT[reason.kind] ?? reason.kind.replace(/-/g, ' ')\n}\n\nfunction summariseHistoryEntry(entry: {_type: string} & Record<string, unknown>): string {\n switch (entry._type) {\n case 'stageEntered':\n return `entered stage \"${String(entry.stage)}\"`\n case 'stageExited':\n return `exited stage \"${String(entry.stage)}\" → \"${String(entry.toStage)}\"`\n case 'taskActivated':\n return `task \"${String(entry.task)}\" activated`\n case 'taskStatusChanged':\n return `task \"${String(entry.task)}\" status: ${String(entry.from)} → ${String(entry.to)}`\n case 'actionFired':\n return `action \"${String(entry.action)}\" fired on task \"${String(entry.task)}\"`\n case 'transitionFired':\n return `transition fired: \"${String(entry.fromStage)}\" → \"${String(entry.toStage)}\"`\n case 'effectQueued':\n return `effect \"${String(entry.effect)}\" queued`\n case 'effectCompleted':\n return `effect \"${String(entry.effect)}\" completed (${String(entry.status)})`\n case 'spawned':\n return `spawned child workflow from task \"${String(entry.task)}\"`\n default:\n return entry._type\n }\n}\n\n// Diagnosis summary — a plain-English one-liner per verdict, the LLM-facing\n// counterpart to the CLI's terminal-decorated rendering. The engine's\n// `diagnostics` module deliberately does no rendering, so each consumer writes\n// its own; this one folds the key identifiers (the stuck effect/task, the\n// waiting actions) into one undecorated line.\n\n/** Exported for unit coverage of every verdict branch — see `tools.test.ts`.\n * Used internally by the diagnose_workflow read in `tools.ts`. */\nexport function diagnosisSummary(diagnosis: Diagnosis): string {\n switch (diagnosis.state) {\n case 'progressing':\n return 'This instance will advance on its own.'\n case 'waiting':\n return `Waiting for action on task \"${diagnosis.task}\": ${diagnosis.actions.join(' or ')}. This is the normal in-flight state — it advances when someone acts.`\n case 'blocked':\n return `Task \"${diagnosis.task}\" is visible but not yet executable — unmet requirement(s): ${diagnosis.requirements.join(', ')}. It will not advance until those are satisfied.`\n case 'completed':\n return `Completed at ${diagnosis.at}.`\n case 'aborted':\n return diagnosis.reason !== undefined\n ? `Aborted at ${diagnosis.at}: ${diagnosis.reason}.`\n : `Aborted at ${diagnosis.at}.`\n case 'stuck':\n return stuckSummary(diagnosis.cause)\n }\n}\n\nfunction stuckSummary(cause: StuckCause): string {\n switch (cause.kind) {\n case 'failed-effect':\n return `Stuck: a failed effect \"${cause.effect.name}\" is blocking task \"${cause.effect.origin.name}\", which can't complete until the effect succeeds.`\n case 'hung-effect':\n return `Stuck: effect \"${cause.effect.name}\" was claimed but never completed — the drainer likely died mid-dispatch, so it won't drain on its own.`\n case 'failed-task':\n return `Stuck: task \"${cause.task}\" is in a terminal failed state, so any exit transition gated on it can never fire.`\n case 'no-transition-fires':\n return `Stuck: every task is resolved but no exit transition's filter is satisfied — likely a routing state value a filter reads was never written.`\n case 'transition-unevaluable':\n return `Stuck (recoverable): exit transition(s) ${cause.transitions.join(', ')} read an operand that is missing or unreadable (GROQ null). It advances on its own once that data becomes readable — no manual fix needed.`\n }\n}\n","/**\n * Builds the MCP tool surface: binds the static descriptors (`descriptors.ts`)\n * to implementations that close over a single engine, parses tool input, and\n * runs the engine reads that the projection helpers (`projection.ts`) shape.\n */\n\nimport {\n validateDefinition,\n WORKFLOW_INSTANCE_TYPE,\n tagScopeFilter,\n type AuthoringWorkflow,\n type Engine,\n type WorkflowAccessOverride,\n type WorkflowInstance,\n} from '@sanity/workflow-engine'\nimport {defineWorkflow} from '@sanity/workflow-engine/define'\n\nimport {AUTHORING_GUIDE} from './authoring-guide.ts'\nimport {LIST_CAP, TOOL_DESCRIPTORS, type ToolDescriptor} from './descriptors.ts'\nimport {\n diagnosisSummary,\n fetchSubjectTitles,\n isInstanceDone,\n projectState,\n projectSummary,\n} from './projection.ts'\nimport type {\n ProjectedDiagnosis,\n ProjectedInstanceState,\n ProjectedInstanceSummary,\n ValidateDefinitionResult,\n} from './types.ts'\n\n/**\n * A tool implementation is a function from validated input → JSON-able\n * output. The runner is responsible for serialising the output and for\n * surfacing thrown errors as `is_error` tool results.\n */\nexport type ToolImpl = (input: unknown) => Promise<unknown>\n\nexport interface BuiltTools {\n descriptors: ToolDescriptor[]\n impls: Record<string, ToolImpl>\n}\n\n/**\n * Optional knobs for `buildTools`.\n *\n * `access` — override the engine's actor + grants resolution for every\n * call the tools make. In production, leave this unset: the engine\n * resolves the actor from the supplied client's token via `/users/me`.\n * In tests, pass `ALL_ACCESS` (from `@sanity/workflow-engine-test`)\n * because the TestClient has no token and would otherwise throw on\n * the resolution path.\n */\nexport interface BuildToolsOptions {\n access?: WorkflowAccessOverride\n}\n\n/**\n * Build the MCP tool descriptors and bound implementations against a\n * single engine. Pass the engine the tools should operate on; the\n * returned descriptors are static (safe to cache), the implementations\n * close over the engine.\n *\n * In production this is called once at server boot. In tests it's\n * called per-bench so each eval case has an isolated engine.\n */\nexport function buildTools(engine: Engine, options: BuildToolsOptions = {}): BuiltTools {\n const accessOverride = options.access\n\n const impls: Record<string, ToolImpl> = {\n list_workflow_instances: async (rawInput) => {\n const input = parseListInput(rawInput)\n return listInstances(engine, input)\n },\n get_workflow_state: async (rawInput) => {\n const input = parseInstanceIdInput(rawInput, 'get_workflow_state')\n return getInstanceState(engine, input.instance_id, accessOverride)\n },\n diagnose_workflow: async (rawInput) => {\n const input = parseInstanceIdInput(rawInput, 'diagnose_workflow')\n return getInstanceDiagnosis(engine, input.instance_id, accessOverride)\n },\n fire_action: async (rawInput) => {\n const input = parseFireActionInput(rawInput)\n await engine.fireAction({\n instanceId: input.instance_id,\n task: input.task,\n action: input.action,\n ...(accessOverride !== undefined ? {access: accessOverride} : {}),\n })\n // Re-use the same projection so the LLM sees consistent shapes\n // between get_workflow_state and fire_action responses.\n return getInstanceState(engine, input.instance_id, accessOverride)\n },\n // Authoring tools — engine-independent: they teach and check the DSL, they\n // don't touch the lake or an instance.\n get_workflow_authoring_guide: async () => AUTHORING_GUIDE,\n validate_workflow_definition: async (rawInput): Promise<ValidateDefinitionResult> => {\n const {definition} = parseValidateInput(rawInput)\n try {\n // `defineWorkflow` is the gate (valibot structural parse + desugar +\n // cross-field invariants); `validateDefinition` adds GROQ syntax checks.\n // The cast only satisfies the compiler — `defineWorkflow` validates the\n // value at runtime and throws an aggregated, path-prefixed error.\n const stored = defineWorkflow(definition as AuthoringWorkflow)\n validateDefinition(stored)\n return {valid: true, definition: stored}\n } catch (err) {\n return {valid: false, error: err instanceof Error ? err.message : String(err)}\n }\n },\n }\n\n return {descriptors: TOOL_DESCRIPTORS, impls}\n}\n\n// Input parsers — lightweight, no zod dependency\n//\n// Reasoning: pulling in zod would inflate the package for this handful of tools.\n// The MCP server and the eval harness already constrain the shape via\n// the JSON schema in the descriptor; these parsers exist for runtime\n// type-narrowing in TypeScript, not for deep validation.\n\ninterface ListInput {\n definition?: string\n status: 'in_flight' | 'done' | 'any'\n}\n\nfunction parseListInput(raw: unknown): ListInput {\n if (raw === null || typeof raw !== 'object') {\n return {status: 'in_flight'}\n }\n const obj = raw as Record<string, unknown>\n const status = obj.status === 'done' || obj.status === 'any' ? obj.status : ('in_flight' as const)\n const definition = typeof obj.definition === 'string' ? obj.definition : undefined\n return definition !== undefined ? {definition, status} : {status}\n}\n\n/** Narrow the validate input to `{definition: object}`. The deep validation\n * is `defineWorkflow`'s job — this only guards the envelope. */\nfunction parseValidateInput(raw: unknown): {definition: object} {\n if (raw === null || typeof raw !== 'object') {\n throw new Error('validate_workflow_definition: input must be an object')\n }\n const obj = raw as Record<string, unknown>\n if (obj.definition === null || typeof obj.definition !== 'object') {\n throw new Error('validate_workflow_definition: `definition` is required and must be an object')\n }\n return {definition: obj.definition}\n}\n\n/** Shared by every single-instance tool — `tool` names the caller so the\n * thrown error points at the right tool. */\nfunction parseInstanceIdInput(raw: unknown, tool: string): {instance_id: string} {\n if (raw === null || typeof raw !== 'object') {\n throw new Error(`${tool}: input must be an object`)\n }\n const obj = raw as Record<string, unknown>\n if (typeof obj.instance_id !== 'string' || obj.instance_id === '') {\n throw new Error(`${tool}: instance_id is required`)\n }\n return {instance_id: obj.instance_id}\n}\n\nfunction parseFireActionInput(raw: unknown): {\n instance_id: string\n task: string\n action: string\n} {\n if (raw === null || typeof raw !== 'object') {\n throw new Error('fire_action: input must be an object')\n }\n const obj = raw as Record<string, unknown>\n for (const key of ['instance_id', 'task', 'action'] as const) {\n if (typeof obj[key] !== 'string' || obj[key] === '') {\n throw new Error(`fire_action: ${key} is required`)\n }\n }\n return {\n instance_id: obj.instance_id as string,\n task: obj.task as string,\n action: obj.action as string,\n }\n}\n\n// Engine reads, projected for an LLM\n\nasync function listInstances(\n engine: Engine,\n input: ListInput,\n): Promise<{instances: ProjectedInstanceSummary[]}> {\n // Tag-scoped via the engine's own query helper — every instance\n // returned is one this engine is allowed to see.\n const groqParts = [`_type == \"${WORKFLOW_INSTANCE_TYPE}\"`]\n if (input.definition !== undefined) {\n groqParts.push('definition == $definition')\n }\n const groq =\n `*[${groqParts.join(' && ')} && ${tagScopeFilter()}] ` +\n `| order(lastChangedAt desc)[0...${LIST_CAP}]`\n\n const params: Record<string, unknown> = {}\n if (input.definition !== undefined) params.definition = input.definition\n\n const docs = await engine.query<WorkflowInstance[]>({groq, params})\n const filtered = docs.filter((doc) => {\n const done = isInstanceDone(doc)\n if (input.status === 'done') return done\n if (input.status === 'in_flight') return !done\n return true // \"any\"\n })\n const subjectTitles = await fetchSubjectTitles(engine, filtered)\n return {\n instances: filtered.map((doc) => projectSummary(doc, subjectTitles)),\n }\n}\n\nasync function getInstanceState(\n engine: Engine,\n instanceId: string,\n accessOverride: WorkflowAccessOverride | undefined,\n): Promise<ProjectedInstanceState> {\n const evaluation = await engine.evaluateInstance({\n instanceId,\n ...(accessOverride !== undefined ? {access: accessOverride} : {}),\n })\n const instance = await engine.getInstance({instanceId})\n const subjectTitles = await fetchSubjectTitles(engine, [instance])\n return projectState(instance, evaluation, subjectTitles)\n}\n\nasync function getInstanceDiagnosis(\n engine: Engine,\n instanceId: string,\n accessOverride: WorkflowAccessOverride | undefined,\n): Promise<ProjectedDiagnosis> {\n const {diagnosis, remediations} = await engine.diagnose({\n instanceId,\n ...(accessOverride !== undefined ? {access: accessOverride} : {}),\n })\n return {\n instanceId,\n state: diagnosis.state,\n summary: diagnosisSummary(diagnosis),\n ...(diagnosis.state === 'stuck' ? {cause: diagnosis.cause.kind} : {}),\n remediations,\n }\n}\n"],"names":["extractDocumentId","actionVerdict","isTerminalStage","defineWorkflow","validateDefinition","WORKFLOW_INSTANCE_TYPE","tagScopeFilter"],"mappings":";;;AAqBA,MAAM,iBAAiB;AAAA,EACrB,MAAM;AAAA,EACN,SAAS;AAAA,EACT,OAAO;AAAA,EACP,aAAa;AAAA,EACb,cAAc;AAAA,EACd,QAAQ,CAAC,EAAC,MAAM,WAAW,MAAM,WAAW,OAAO,YAAY,QAAQ,EAAC,MAAM,OAAA,GAAQ;AAAA,EACtF,QAAQ;AAAA,IACN;AAAA,MACE,MAAM;AAAA,MACN,OAAO;AAAA,MACP,OAAO;AAAA,QACL;AAAA,UACE,MAAM;AAAA,UACN,OAAO;AAAA,UACP,YAAY;AAAA,UACZ,SAAS,CAAC,EAAC,MAAM,WAAW,OAAO,WAAW,QAAQ,OAAA,CAAO;AAAA,QAAA;AAAA,MAC/D;AAAA,MAEF,aAAa,CAAC,EAAC,MAAM,eAAe,OAAO,sBAAsB,IAAI,WAAA,CAAW;AAAA,IAAA;AAAA,IAElF,EAAC,MAAM,YAAY,OAAO,YAAY,aAAa,sCAAA;AAAA,EAAgC;AAEvF,GAEM,oBAAoB;AAAA,EACxB,MAAM;AAAA,EACN,SAAS;AAAA,EACT,OAAO;AAAA,EACP,aAAa;AAAA,EACb,cAAc;AAAA,EACd,QAAQ,CAAC,EAAC,MAAM,WAAW,MAAM,WAAW,OAAO,YAAY,QAAQ,EAAC,MAAM,OAAA,GAAQ;AAAA,EACtF,QAAQ;AAAA,I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BAAiB;AAAA,IAC/C;AAAA,IACA,GAAI,mBAAmB,SAAY,EAAC,QAAQ,eAAA,IAAkB,CAAA;AAAA,EAAC,CAChE,GACK,WAAW,MAAM,OAAO,YAAY,EAAC,WAAA,CAAW,GAChD,gBAAgB,MAAM,mBAAmB,QAAQ,CAAC,QAAQ,CAAC;AACjE,SAAO,aAAa,UAAU,YAAY,aAAa;AACzD;AAEA,eAAe,qBACb,QACA,YACA,gBAC6B;AAC7B,QAAM,EAAC,WAAW,aAAA,IAAgB,MAAM,OAAO,SAAS;AAAA,IACtD;AAAA,IACA,GAAI,mBAAmB,SAAY,EAAC,QAAQ,eAAA,IAAkB,CAAA;AAAA,EAAC,CAChE;AACD,SAAO;AAAA,IACL;AAAA,IACA,OAAO,UAAU;AAAA,IACjB,SAAS,iBAAiB,SAAS;AAAA,IACnC,GAAI,UAAU,UAAU,UAAU,EAAC,OAAO,UAAU,MAAM,KAAA,IAAQ,CAAA;AAAA,IAClE;AAAA,EAAA;AAEJ;;"}
1
+ {"version":3,"file":"index.cjs","sources":["../src/authoring-guide.ts","../src/descriptors.ts","../src/projection.ts","../src/tools.ts"],"sourcesContent":["/**\n * Content for the `get_workflow_authoring_guide` tool.\n *\n * The agent calling the MCP server generates the workflow definition; this\n * guide is what teaches it the DSL well enough to do that on the first pass.\n * It is the orientation the examples can't convey on their own (the GROQ\n * built-ins, the sugars, the hard rules) plus two worked examples.\n *\n * The examples are kept inline (rather than imported from\n * `@sanity/workflow-examples`) on purpose: that package exports the *desugared*\n * `WorkflowDefinition` (the post-`defineWorkflow` shape), but an agent should emit\n * the *authoring* (sugar) shape — JSON, exactly what `validate_workflow_definition`\n * accepts — so importing the examples would show the wrong shape. Keeping them\n * inline also avoids promoting `@sanity/workflow-examples` to a runtime dependency\n * of a package headed for host embedding. The companion test runs every example\n * through the real validators, so a stale snippet fails CI rather than misleading\n * an agent.\n */\n\nimport type {AuthoringWorkflow} from '@sanity/workflow-engine'\n\nconst minimalExample = {\n name: 'quick-approval',\n title: 'Quick approval',\n description: 'One review stage with a single approve action, then a terminal stage.',\n initialStage: 'review',\n fields: [{type: 'doc.ref', name: 'subject', title: 'Document', initialValue: {type: 'input'}}],\n stages: [\n {\n name: 'review',\n title: 'Review',\n activities: [\n {\n name: 'decide',\n title: 'Decide',\n activation: 'auto',\n actions: [{name: 'approve', title: 'Approve', status: 'done'}],\n },\n ],\n transitions: [{name: 'to-approved', title: 'Approve and finish', to: 'approved'}],\n },\n {name: 'approved', title: 'Approved', description: 'Terminal — no transitions out.'},\n ],\n} satisfies AuthoringWorkflow\n\nconst reviewLoopExample = {\n name: 'doc-review',\n title: 'Document review',\n description: 'Draft, then editorial review that approves or rejects back to drafting.',\n initialStage: 'drafting',\n fields: [{type: 'doc.ref', name: 'subject', title: 'Document', initialValue: {type: 'input'}}],\n stages: [\n {\n name: 'drafting',\n title: 'Drafting',\n activities: [\n {\n name: 'write',\n title: 'Write the draft',\n activation: 'auto',\n actions: [{name: 'submit', title: 'Submit for review', status: 'done'}],\n },\n ],\n transitions: [{name: 'to-review', title: 'Send to review', to: 'review'}],\n },\n {\n name: 'review',\n title: 'Editorial review',\n activities: [\n {\n name: 'review',\n title: 'Review the draft',\n activation: 'auto',\n actions: [\n {name: 'approve', title: 'Approve', status: 'done'},\n {name: 'reject', title: 'Reject', status: 'failed'},\n ],\n },\n ],\n transitions: [\n {name: 'to-approved', title: 'Approve and finish', to: 'approved'},\n // Reject flips the activity to `failed`; this routes the instance back.\n {\n name: 'to-drafting',\n title: 'Send back to drafting',\n to: 'drafting',\n filter: '$anyActivityFailed',\n },\n ],\n },\n {name: 'approved', title: 'Approved', description: 'Terminal — no transitions out.'},\n ],\n} satisfies AuthoringWorkflow\n\n/**\n * Worked examples included verbatim in {@link AUTHORING_GUIDE}, and exercised by\n * the drift-guard test. Authoring (sugar) shape — what an agent passes to\n * `validate_workflow_definition`.\n */\nexport const GUIDE_EXAMPLES: AuthoringWorkflow[] = [minimalExample, reviewLoopExample]\n\nconst ORIENTATION = `# Authoring a workflow definition\n\nA workflow definition is a plain JSON object. There is no code in it — every\ncondition (filters, predicates, guards) is a GROQ *string*. Generate the JSON,\nthen call \\`validate_workflow_definition\\` to check it; fix the reported errors\nand re-validate until it returns \\`valid: true\\`. The validator returns the\n*desugared* definition under \\`definition\\` — that is exactly what would deploy.\n\n## Shape\n\n- **Workflow**: \\`{ name, title, description?, initialStage, fields?, stages[], predicates? }\\`.\n \\`initialStage\\` must be the \\`name\\` of a declared stage. Do NOT include a\n \\`version\\` — definitions are immutable and content-addressed; deploy assigns\n the version from the content, the author never writes one.\n- **Stage**: \\`{ name, title?, description?, activities?, transitions? }\\`. A stage with\n no transitions is terminal. Reaching a terminal stage ends the workflow.\n- **Activity**: \\`{ name, title?, activation?, actions? }\\`. \\`activation\\` is \\`'auto'\\`\n (starts when the stage is entered) or \\`'manual'\\` (default — a human starts it).\n- **Action**: \\`{ name, title?, status?, params?, ops? }\\`.\n \\`status: 'done' | 'skipped' | 'failed'\\` is sugar that flips the *firing activity* to\n that status when the action fires. \\`ops\\` are mutations applied when the action\n fires (e.g. \\`{type:'field.set', target:{field:'x'}, value:{type:'param', param:'p'}}\\`).\n \\`params\\` are values the action collects from the caller (referenced by\n \\`{type:'param', param:'<name>'}\\` sources).\n- **Transition**: \\`{ name, title?, to, filter? }\\`. \\`to\\` must name a declared\n stage. \\`filter\\` is a GROQ condition gating the exit; omit it and it defaults\n to \\`$allActivitiesDone\\`.\n- **Field** (workflow- or stage-scoped persistent state): \\`{ type, name, title?, initialValue? }\\`.\n Scalar \\`type\\`s mirror Sanity: \\`string\\`, \\`text\\` (multiline), \\`number\\`,\n \\`boolean\\`, \\`date\\` (YYYY-MM-DD), \\`datetime\\` (ISO), \\`url\\`. Plus references\n (\\`doc.ref\\`, \\`doc.refs\\`, \\`release.ref\\`), identities (\\`actor\\` — one concrete\n principal; \\`assignee\\` / \\`assignees\\` — one or many user-or-role assignees), and\n the compositional kinds \\`object\\` (\\`{ type:'object', name, fields: [...] }\\`) and\n \\`array\\` (\\`{ type:'array', name, of: [...] }\\`) — \\`fields\\`/\\`of\\` are themselves\n field shapes, so any structure composes. \\`initialValue\\` seeds the slot once at\n materialisation and is **optional** — omit it for op-filled working memory\n (the common default). Arms: \\`{type:'input'}\\` (the caller supplies it when the\n instance starts), \\`{type:'query', query:'<groq>'}\\` (computed from the lake),\n \\`{type:'literal', value:<json>}\\`, or \\`{type:'fieldRead', field:'<name>'}\\`.\n By convention a workflow has an \\`input\\`-sourced \\`doc.ref\\` named \\`subject\\` — the\n headline document it is about.\n Two list sugars desugar to \\`array\\`: \\`{type:'todoList', name}\\` (ad-hoc\n status-tracked work — rows \\`{ label, status, assignee?, dueDate? }\\`) and\n \\`{type:'notes', name}\\` (an append-only audit/comment log — rows\n \\`{ body, actor, at }\\`; pairs with the \\`audit\\` op, which stamps \\`actor\\`/\\`at\\`).\n\n## GROQ in conditions\n\nBuilt-in variables available in filters/predicates: \\`$allActivitiesDone\\`,\n\\`$anyActivityFailed\\` (booleans over the current stage's activities), \\`$activities\\` (the activity\nlist), \\`$fields\\` (field values), \\`$now\\`, and the caller-scoped vars \\`$actor\\`\n(the acting user), \\`$assigned\\` (whether the caller is the activity's assignee — the\nidiomatic permission gate, used as \\`filter: '$assigned'\\`), and \\`$can\\`. Define\nreusable named conditions under top-level \\`predicates: { name: '<groq>' }\\` and\nreference them as \\`$name\\` (e.g.\n\\`predicates: { ready: \"count($activities[status != 'done']) == 0\" }\\` → \\`$ready\\`).\n\nConditions evaluate against an in-memory snapshot (the instance + its subject +\nfield-declared docs) — **never** scan by \\`_type\\` (e.g. \\`*[_type==\"article\"]\\`);\nthat is a discovery query and the validator rejects it. To bring a document into\nscope, declare a \\`doc.ref\\` field for it.\n\n## Sugars worth knowing\n\n- Action \\`status: 'done' | 'skipped' | 'failed'\\` — flips the firing activity (shown above).\n- Omitted transition \\`filter\\` — defaults to \\`$allActivitiesDone\\`.\n- Omitted activity \\`activation\\` — defaults to \\`'manual'\\`.\n\n## Modeling defaults\n\nValid is not the same as good. Prefer these unless the request says otherwise:\n\n- **A decline/reject loops back.** Route a rejected / changes-requested\n transition to an *earlier* stage for revision (e.g. \\`review → drafting\\` gated\n on \\`$anyActivityFailed\\`), not to a terminal stage. Reserve terminal stages for\n completion and for explicit cancellation/abandonment — a workflow should not\n dead-end just because something was declined.\n- **Prefer draft → review.** Model an author working in a drafting stage who\n submits, then a review stage that gates. Don't add more review stages unless\n the request asks for multiple approvers or rounds.\n- **When the shape is ambiguous, pick the conventional one and confirm** with the\n user rather than inventing extra stages.\n\n## Rules the validator enforces\n\n- Stage names, activity names (per stage) and transition names are unique.\n- Every transition \\`to\\` and \\`initialStage\\` names a declared stage.\n- Custom \\`predicates\\` must not shadow a built-in (e.g. \\`allActivitiesDone\\`).\n- Every GROQ string must parse and must not be a \\`_type\\` discovery scan.`\n\n/**\n * The full text returned by `get_workflow_authoring_guide`: orientation plus the\n * two worked examples rendered as JSON.\n */\nexport const AUTHORING_GUIDE = `${ORIENTATION}\n\n## Examples\n\n### Example 1 — ${minimalExample.title} (minimal: one stage, one action)\n\\`\\`\\`json\n${JSON.stringify(minimalExample, null, 2)}\n\\`\\`\\`\n\n### Example 2 — ${reviewLoopExample.title} (review loop: reject routes back)\n\\`\\`\\`json\n${JSON.stringify(reviewLoopExample, null, 2)}\n\\`\\`\\`\n`\n","/**\n * The MCP tool surface for workflow operations — the static descriptors an\n * agent reads to decide what to call. The implementations live in `tools.ts`;\n * these are pure data (descriptions + JSON schemas) and safe to cache.\n *\n * Two jobs: operate running instances, and author new definitions.\n *\n * Operate an instance:\n *\n * - `list_workflow_instances` is the only way to *discover* what's\n * running without already knowing an id. Filterable, capped.\n * - `get_workflow_state` is the \"tell me everything actionable about\n * one instance\" call. It composes the engine's `evaluate` projection\n * into a flat shape an LLM can reason over without piecing together\n * raw `WorkflowInstance` documents.\n * - `diagnose_workflow` answers \"*why* isn't this moving?\" — it\n * classifies an instance as healthy (waiting/progressing) or genuinely\n * stuck (a failed effect/activity, a dead-end transition) and names the\n * remediations that would unstick it. A pure read; the remediations are\n * advisory (none execute through this server).\n * - `fire_action` is the only write. Mirrors the engine's universal\n * \"something happened\" entry point — everything other than admin\n * override flows through it.\n *\n * Author a definition (both pure, engine-independent, neither deploys):\n *\n * - `get_workflow_authoring_guide` returns the DSL guide an agent reads\n * before writing a definition — shape, GROQ built-ins, sugars, examples.\n * - `validate_workflow_definition` runs the deploy-time checks (structure +\n * invariants + GROQ) and returns the desugared definition or a\n * path-prefixed error list. A human deploys it via the CLI.\n *\n * Surface choices that matter for an LLM consumer:\n *\n * - Descriptions are written for an agent, not a human reader.\n * Each one says (a) what the tool does, (b) when to use it,\n * (c) what *not* to use it for.\n * - Parameter names use snake_case, matching MCP convention.\n * - The write tool's description spells out that this is the way\n * to advance workflow state — not a side door. Without that line,\n * an LLM tends to look for a `complete_activity` or `set_stage` tool.\n * - Read tools cap their output. A 50-page `recent_history` would\n * burn context and is rarely informative; 8 is enough to spot\n * loops or stuck-in-stage patterns.\n */\n\n/**\n * The descriptor shape the Anthropic Messages API + the MCP SDK both\n * accept. Kept here as a small, transport-neutral interface so we can\n * feed the same descriptors to either consumer.\n */\nexport interface ToolDescriptor {\n name: string\n description: string\n /** JSON Schema describing the tool's parameters. */\n input_schema: {\n type: 'object'\n properties: Record<string, unknown>\n required?: string[]\n additionalProperties?: boolean\n }\n}\n\n/** Maximum instances returned by list_workflow_instances. */\nexport const LIST_CAP = 25\n\n/**\n * The static tool descriptors. Independent of any engine — the bound\n * implementations that close over an engine live in {@link buildTools}.\n */\nexport const TOOL_DESCRIPTORS: ToolDescriptor[] = [\n {\n name: 'list_workflow_instances',\n description:\n 'List workflow instances in the configured workspace. Use this when you need ' +\n \"to find a workflow but don't already know its instance id, or to survey \" +\n \"what's in flight. Returns a compact summary — id, workflow type id and \" +\n 'human-readable `workflowTitle`, current stage, whether the instance is done, ' +\n 'and (when the workflow has a conventional subject document) a `subject` ' +\n \"field with the subject doc's ref and title. Use `workflowTitle` when the \" +\n 'user names the workflow by type (e.g. \"article reviews\") and `subject.title` ' +\n \"when they name a specific in-flight instance by what it's about (e.g. \" +\n '\"the article-review about pricing\"). ' +\n 'Capped at ' +\n String(LIST_CAP) +\n ' results. ' +\n 'Do NOT use this to inspect a single known instance — use get_workflow_state ' +\n 'for that, the response will be richer.',\n input_schema: {\n type: 'object',\n properties: {\n definition: {\n type: 'string',\n description:\n \"Optional. Restrict to instances of this workflow definition (e.g. 'article-review').\",\n },\n status: {\n type: 'string',\n enum: ['in_flight', 'done', 'any'],\n description:\n \"Optional. 'in_flight' returns instances not in a terminal stage; \" +\n \"'done' returns completed/aborted; 'any' returns both. Defaults to 'in_flight'.\",\n },\n },\n additionalProperties: false,\n },\n },\n {\n name: 'get_workflow_state',\n description:\n 'Get the current state of a single workflow instance, projected for action. ' +\n \"Returns the workflow's id and human-readable `workflowTitle`, the current \" +\n 'stage, the subject document the workflow is about (when the workflow has a ' +\n 'conventional subject — its ref and title), every activity on the current stage ' +\n 'with its available actions (and whether each action is currently allowed), ' +\n 'and the most recent history entries. Use this whenever you need to understand ' +\n \"what's possible on an instance before deciding to act. \" +\n 'This is a pure read — it does not change anything. ' +\n 'If you only need to discover what instances exist, use list_workflow_instances ' +\n 'instead; this tool requires you to know the instance id. ' +\n 'list_workflow_instances also returns the same `workflowTitle` and `subject` ' +\n 'fields, so prefer it for fan-out discovery rather than polling ' +\n 'get_workflow_state per instance.',\n input_schema: {\n type: 'object',\n properties: {\n instance_id: {\n type: 'string',\n description: 'The workflow instance id.',\n },\n },\n required: ['instance_id'],\n additionalProperties: false,\n },\n },\n {\n name: 'diagnose_workflow',\n description:\n \"Explain why a single workflow instance is or isn't progressing. Returns a \" +\n 'verdict (`state`: progressing, waiting, blocked, completed, aborted, or ' +\n 'stuck), a one-line `summary`, and — when stuck — a structured `cause` plus ' +\n 'the `remediations` that would unstick it. Use this when an instance seems ' +\n 'stalled or the user asks \"why isn\\'t this moving?\": it distinguishes a healthy ' +\n 'instance (waiting on a human, or will advance on its own) from a genuinely ' +\n 'stuck one (a failed effect or activity, a dead-end transition). ' +\n 'This is a pure read — it changes nothing, and the remediations it names are ' +\n 'advisory: none can be executed through this server. To actually advance a ' +\n 'healthy waiting instance use fire_action; for per-activity action detail use ' +\n 'get_workflow_state.',\n input_schema: {\n type: 'object',\n properties: {\n instance_id: {\n type: 'string',\n description: 'The workflow instance id.',\n },\n },\n required: ['instance_id'],\n additionalProperties: false,\n },\n },\n {\n name: 'fire_action',\n description:\n 'Advance a workflow instance by firing an action on one of its activities. ' +\n 'This is the only way to advance workflow state from the outside — there is no ' +\n \"separate 'complete activity' or 'transition stage' tool. To find the right \" +\n '(activity, action) pair, call get_workflow_state first and pick from the ' +\n \"allowed actions listed on the current stage's activities. \" +\n 'After firing, the engine cascades any auto-transitions that become eligible ' +\n \"(so an 'approve' action on a review activity may transition the workflow to a \" +\n 'terminal stage in one shot). Returns the resulting state, same shape as ' +\n 'get_workflow_state. ' +\n 'If the action is not currently allowed (e.g. the activity is already done, or a ' +\n 'guard fails), this returns an error describing why.',\n input_schema: {\n type: 'object',\n properties: {\n instance_id: {\n type: 'string',\n description: 'The workflow instance id.',\n },\n activity: {\n type: 'string',\n description:\n 'The id of the activity on the current stage. Must be one of the activities ' +\n 'returned by get_workflow_state.',\n },\n action: {\n type: 'string',\n description:\n 'The id of the action on that activity. Must be one of the actions listed ' +\n 'as allowed=true on the activity.',\n },\n },\n required: ['instance_id', 'activity', 'action'],\n additionalProperties: false,\n },\n },\n {\n name: 'get_workflow_authoring_guide',\n description:\n 'Get the guide for authoring a workflow definition: the DSL shape, the ' +\n 'GROQ condition built-ins, the sugars, the rules the validator enforces, ' +\n 'and two worked JSON examples. Call this BEFORE writing a definition from ' +\n 'a description, then generate the JSON and check it with ' +\n 'validate_workflow_definition. Pure read; takes no arguments.',\n input_schema: {\n type: 'object',\n properties: {},\n additionalProperties: false,\n },\n },\n {\n name: 'validate_workflow_definition',\n description:\n 'Validate a workflow definition you have authored. Runs the same checks as ' +\n 'deploy — structural shape, cross-field invariants (e.g. every transition ' +\n 'target is a declared stage), and GROQ syntax — without writing anything. ' +\n 'Returns `{valid:true, definition}` where `definition` is the desugared form ' +\n 'that would deploy, or `{valid:false, error}` with every problem listed and ' +\n 'path-prefixed. This does NOT deploy — a human deploys the validated ' +\n 'definition via the CLI. Call get_workflow_authoring_guide first for the ' +\n 'shape; on `valid:false`, fix the reported problems and validate again.',\n input_schema: {\n type: 'object',\n properties: {\n definition: {\n type: 'object',\n description:\n 'The workflow definition to validate, as a JSON object in authoring ' +\n 'shape. See get_workflow_authoring_guide for the shape and examples.',\n },\n },\n required: ['definition'],\n additionalProperties: false,\n },\n },\n]\n","/**\n * Projection helpers — engine output shaped for an LLM consumer.\n *\n * Why a hand-written projection rather than returning the engine's\n * `WorkflowEvaluation` raw: the LLM only needs (a) which activities exist,\n * (b) which actions are allowed on each, (c) why an action is denied\n * when it is. The evaluation includes per-stage field-entry resolution\n * and snapshot bookkeeping that bloats the payload without helping\n * the model pick the right next move.\n *\n * The engine reads that feed these live in `tools.ts`; this module is\n * pure shaping plus the one batched subject-title lookup they all share.\n */\n\nimport {\n actionVerdict,\n extractDocumentId,\n isTerminalStage,\n type Diagnosis,\n type Engine,\n type StuckCause,\n type WorkflowDefinition,\n type WorkflowEvaluation,\n type WorkflowInstance,\n} from '@sanity/workflow-engine'\n\nimport type {\n ProjectedActionVerdict,\n ProjectedHistoryEntry,\n ProjectedInstanceState,\n ProjectedInstanceSummary,\n ProjectedSubject,\n ProjectedActivity,\n} from './types.ts'\n\n/**\n * The field-entry name we treat as the workflow's \"subject\" — the headline\n * doc the workflow is about. Convention-only (see ProjectedSubject docs);\n * a workflow without an entry with this name won't have `subject` populated\n * on the projection.\n */\nconst SUBJECT_ENTRY_NAME = 'subject'\n\n/** Maximum history entries returned in get_workflow_state. */\nconst HISTORY_CAP = 8\n\n// Subject doc resolution\n//\n// The conventional \"subject\" entry holds a doc.ref to the thing the\n// workflow is about. The entry value is a GDR URI (e.g.\n// `dataset:proj:ds:article-1`) — what `_id` in the store actually\n// uses is the bare `article-1` part. Extract, batch-fetch by id list,\n// build a Map keyed by GDR URI.\n//\n// Known gap: cross-resource subject docs. If the subject lives in a\n// different Sanity resource than the engine's own workflowResource,\n// this lookup misses — the engine's `query` runs against the workflow\n// resource's client. Production-shape fix is to thread the engine's\n// `resourceClients` resolver through here; out of scope for v0.1.\n\n/**\n * Look up the conventional subject entry on a workflow instance's\n * workflow-scope fields. Returns the GDR URI when present, undefined\n * when the workflow has no subject entry or the entry is null.\n */\nfunction getSubjectGdr(instance: WorkflowInstance): string | undefined {\n const entry = instance.fields.find((s) => s._type === 'doc.ref' && s.name === SUBJECT_ENTRY_NAME)\n if (entry === undefined || entry._type !== 'doc.ref') return undefined\n return entry.value?.id\n}\n\n/**\n * Batch-fetch the `title` field for every subject doc referenced by\n * the supplied instances. Returns a `Map<gdrUri, title>` — missing\n * keys mean the doc had no title (or didn't exist / was unreadable).\n * The caller projects `ref` from the GDR either way; this map only\n * controls whether `title` is populated.\n *\n * Single GROQ call regardless of how many instances are supplied. At\n * `LIST_CAP=25` this is cheap; per-instance lookups would be N+1.\n */\nexport async function fetchSubjectTitles(\n engine: Engine,\n instances: WorkflowInstance[],\n): Promise<Map<string, string>> {\n // Build docId → gdrUri so we can attribute results back. Skip any\n // malformed GDRs silently — the projection still surfaces `ref`,\n // the LLM falls back to that as an identifier.\n const docIdToGdr = new Map<string, string>()\n for (const inst of instances) {\n const gdr = getSubjectGdr(inst)\n if (gdr === undefined) continue\n try {\n docIdToGdr.set(extractDocumentId(gdr), gdr)\n } catch {\n // Malformed GDR — leave it out of the title lookup.\n }\n }\n if (docIdToGdr.size === 0) return new Map()\n\n // Subject docs are ordinary content, not workflow docs — they carry no\n // engine tag, so we read them straight off the engine's client rather\n // than through the tag-scoped `engine.query` (which mandates a\n // `$tag` filter). Access is the client credential's concern: a\n // doc the caller can't read simply comes back absent.\n let docs: {_id: string; title?: string}[]\n try {\n docs = await engine.client.fetch<{_id: string; title?: string}[]>(\n '*[_id in $docIds]{_id, title}',\n {docIds: Array.from(docIdToGdr.keys())},\n )\n } catch (err) {\n // Titles are optional enrichment — degrade to bare refs rather than\n // failing the whole tool call when the lookup can't be served.\n process.stderr.write(\n `workflow-mcp: subject-title lookup failed; returning refs without titles: ${\n err instanceof Error ? err.message : String(err)\n }\\n`,\n )\n return new Map()\n }\n\n const out = new Map<string, string>()\n for (const doc of docs) {\n const gdr = docIdToGdr.get(doc._id)\n if (gdr !== undefined && typeof doc.title === 'string' && doc.title !== '') {\n out.set(gdr, doc.title)\n }\n }\n return out\n}\n\n/**\n * Build a `ProjectedSubject` for one instance, given the title map\n * produced by `fetchSubjectTitles`. Returns undefined when the\n * workflow has no subject entry; returns `{ ref }` without `title`\n * when the entry is present but the doc has no title field.\n */\nfunction buildSubject(\n instance: WorkflowInstance,\n subjectTitles: Map<string, string>,\n): ProjectedSubject | undefined {\n const gdr = getSubjectGdr(instance)\n if (gdr === undefined) return undefined\n const title = subjectTitles.get(gdr)\n return title !== undefined ? {ref: gdr, title} : {ref: gdr}\n}\n\nexport function projectSummary(\n doc: WorkflowInstance,\n subjectTitles: Map<string, string>,\n): ProjectedInstanceSummary {\n const definition = JSON.parse(doc.definitionSnapshot) as WorkflowDefinition\n const stage = definition.stages.find((s) => s.name === doc.currentStage)\n const stageTitle = stage?.title\n const workflowTitle = definition.title\n const subject = buildSubject(doc, subjectTitles)\n return {\n instanceId: doc._id,\n definition: doc.definition,\n ...(workflowTitle !== undefined ? {workflowTitle} : {}),\n currentStage: doc.currentStage,\n ...(stageTitle !== undefined ? {currentStageTitle: stageTitle} : {}),\n lastChangedAt: doc.lastChangedAt,\n done: isInstanceDone(doc),\n ...(subject !== undefined ? {subject} : {}),\n }\n}\n\nexport function projectState(\n instance: WorkflowInstance,\n evaluation: WorkflowEvaluation,\n subjectTitles: Map<string, string>,\n): ProjectedInstanceState {\n // The evaluation already exposes the current stage's title from the\n // snapshot, but not the workflow's own title — parse the snapshot\n // once here to read it.\n const definition = JSON.parse(instance.definitionSnapshot) as WorkflowDefinition\n const workflowTitle = definition.title\n const stageTitle = evaluation.currentStage.stage.title\n\n const activities: ProjectedActivity[] = evaluation.currentStage.activities.map((te) => {\n // Each action's verdict comes from the engine's shared `actionVerdict` —\n // the same \"is this firable, and why not\" the CLI reads — so the verdict\n // shape has one source; we keep the LLM-shaped per-activity nesting.\n const actions: ProjectedActionVerdict[] = te.actions.map((ae) => {\n const verdict = actionVerdict(te, ae)\n return {\n action: verdict.action,\n ...(verdict.title !== undefined ? {title: verdict.title} : {}),\n allowed: verdict.allowed,\n ...(verdict.allowed === false && verdict.disabledReason !== undefined\n ? {disabledReason: formatDisabledReason(verdict.disabledReason)}\n : {}),\n }\n })\n\n return {\n activity: te.activity.name,\n ...(te.activity.title !== undefined ? {title: te.activity.title} : {}),\n ...(te.activity.description !== undefined ? {description: te.activity.description} : {}),\n status: te.status,\n actions,\n }\n })\n\n const recentHistory: ProjectedHistoryEntry[] = instance.history\n .slice(-HISTORY_CAP)\n .toReversed()\n .map((entry) => ({\n at: entry.at,\n type: entry._type,\n summary: summariseHistoryEntry(entry),\n }))\n\n const subject = buildSubject(instance, subjectTitles)\n return {\n instanceId: instance._id,\n definition: instance.definition,\n ...(workflowTitle !== undefined ? {workflowTitle} : {}),\n currentStage: instance.currentStage,\n ...(stageTitle !== undefined ? {currentStageTitle: stageTitle} : {}),\n done: isInstanceDone(instance),\n ...(subject !== undefined ? {subject} : {}),\n activities,\n recentHistory,\n }\n}\n\nexport function isInstanceDone(instance: WorkflowInstance): boolean {\n // The engine sets `completedAt` when an instance enters a terminal\n // stage; falling back to the structural check covers any edge case\n // where the definition snapshot is the source of truth.\n if (instance.completedAt !== undefined) return true\n try {\n const definition = JSON.parse(instance.definitionSnapshot) as WorkflowDefinition\n const stage = definition.stages.find((s) => s.name === instance.currentStage)\n return stage !== undefined && isTerminalStage(stage)\n } catch {\n return false\n }\n}\n\n/**\n * Engine `disabledReason` is a structured tagged union (see\n * `DisabledReason` in @sanity/workflow-engine). For an LLM\n * we want a short English phrase rather than the tagged shape — the\n * tagged shape is still available on the raw evaluation if a richer\n * consumer wants it.\n */\nconst DISABLED_REASON_TEXT: Record<string, string> = {\n 'filter-failed': \"action's filter condition did not hold for this actor\",\n 'activity-not-active': 'activity is not currently active',\n 'stage-terminal': 'stage is terminal — no further actions possible',\n 'instance-completed': 'instance has already completed',\n 'requirements-unmet': \"activity's declared requirements are not yet satisfied\",\n}\n\nfunction formatDisabledReason(reason: {kind: string}): string {\n // Fall back to a humanised form of the kind for reasons we don't have\n // bespoke copy for, so a new engine reason never renders as a raw enum.\n return DISABLED_REASON_TEXT[reason.kind] ?? reason.kind.replace(/-/g, ' ')\n}\n\nfunction summariseHistoryEntry(entry: {_type: string} & Record<string, unknown>): string {\n switch (entry._type) {\n case 'stageEntered':\n return `entered stage \"${String(entry.stage)}\"`\n case 'stageExited':\n return `exited stage \"${String(entry.stage)}\" → \"${String(entry.toStage)}\"`\n case 'activityActivated':\n return `activity \"${String(entry.activity)}\" activated`\n case 'activityStatusChanged':\n return `activity \"${String(entry.activity)}\" status: ${String(entry.from)} → ${String(entry.to)}`\n case 'actionFired':\n return `action \"${String(entry.action)}\" fired on activity \"${String(entry.activity)}\"`\n case 'transitionFired':\n return `transition fired: \"${String(entry.fromStage)}\" → \"${String(entry.toStage)}\"`\n case 'effectQueued':\n return `effect \"${String(entry.effect)}\" queued`\n case 'effectCompleted':\n return `effect \"${String(entry.effect)}\" completed (${String(entry.status)})`\n case 'spawned':\n return `spawned child workflow from activity \"${String(entry.activity)}\"`\n default:\n return entry._type\n }\n}\n\n// Diagnosis summary — a plain-English one-liner per verdict, the LLM-facing\n// counterpart to the CLI's terminal-decorated rendering. The engine's\n// `diagnostics` module deliberately does no rendering, so each consumer writes\n// its own; this one folds the key identifiers (the stuck effect/activity, the\n// waiting actions) into one undecorated line.\n\n/** Exported for unit coverage of every verdict branch — see `tools.test.ts`.\n * Used internally by the diagnose_workflow read in `tools.ts`. */\nexport function diagnosisSummary(diagnosis: Diagnosis): string {\n switch (diagnosis.state) {\n case 'progressing':\n return 'This instance will advance on its own.'\n case 'waiting':\n return `Waiting for action on activity \"${diagnosis.activity}\": ${diagnosis.actions.join(' or ')}. This is the normal in-flight state — it advances when someone acts.`\n case 'blocked':\n return `Activity \"${diagnosis.activity}\" is visible but not yet executable — unmet requirement(s): ${diagnosis.requirements.join(', ')}. It will not advance until those are satisfied.`\n case 'completed':\n return `Completed at ${diagnosis.at}.`\n case 'aborted':\n return diagnosis.reason !== undefined\n ? `Aborted at ${diagnosis.at}: ${diagnosis.reason}.`\n : `Aborted at ${diagnosis.at}.`\n case 'stuck':\n return stuckSummary(diagnosis.cause)\n }\n}\n\nfunction stuckSummary(cause: StuckCause): string {\n switch (cause.kind) {\n case 'failed-effect':\n return `Stuck: a failed effect \"${cause.effect.name}\" is blocking activity \"${cause.effect.origin.name}\", which can't complete until the effect succeeds.`\n case 'hung-effect':\n return `Stuck: effect \"${cause.effect.name}\" was claimed but never completed — the drainer likely died mid-dispatch, so it won't drain on its own.`\n case 'failed-activity':\n return `Stuck: activity \"${cause.activity}\" is in a terminal failed state, so any exit transition gated on it can never fire.`\n case 'no-transition-fires':\n return `Stuck: every activity is resolved but no exit transition's filter is satisfied — likely a routing state value a filter reads was never written.`\n case 'transition-unevaluable':\n return `Stuck (recoverable): exit transition(s) ${cause.transitions.join(', ')} read an operand that is missing or unreadable (GROQ null). It advances on its own once that data becomes readable — no manual fix needed.`\n }\n}\n","/**\n * Builds the MCP tool surface: binds the static descriptors (`descriptors.ts`)\n * to implementations that close over a single engine, parses tool input, and\n * runs the engine reads that the projection helpers (`projection.ts`) shape.\n */\n\nimport {\n validateDefinition,\n WORKFLOW_INSTANCE_TYPE,\n tagScopeFilter,\n type AuthoringWorkflow,\n type Engine,\n type WorkflowAccessOverride,\n type WorkflowInstance,\n} from '@sanity/workflow-engine'\nimport {defineWorkflow} from '@sanity/workflow-engine/define'\n\nimport {AUTHORING_GUIDE} from './authoring-guide.ts'\nimport {LIST_CAP, TOOL_DESCRIPTORS, type ToolDescriptor} from './descriptors.ts'\nimport {\n diagnosisSummary,\n fetchSubjectTitles,\n isInstanceDone,\n projectState,\n projectSummary,\n} from './projection.ts'\nimport type {\n ProjectedDiagnosis,\n ProjectedInstanceState,\n ProjectedInstanceSummary,\n ValidateDefinitionResult,\n} from './types.ts'\n\n/**\n * A tool implementation is a function from validated input → JSON-able\n * output. The runner is responsible for serialising the output and for\n * surfacing thrown errors as `is_error` tool results.\n */\nexport type ToolImpl = (input: unknown) => Promise<unknown>\n\nexport interface BuiltTools {\n descriptors: ToolDescriptor[]\n impls: Record<string, ToolImpl>\n}\n\n/**\n * Optional knobs for `buildTools`.\n *\n * `access` — override the engine's actor + grants resolution for every\n * call the tools make. In production, leave this unset: the engine\n * resolves the actor from the supplied client's token via `/users/me`.\n * In tests, pass `ALL_ACCESS` (from `@sanity/workflow-engine-test`)\n * because the TestClient has no token and would otherwise throw on\n * the resolution path.\n */\nexport interface BuildToolsOptions {\n access?: WorkflowAccessOverride\n}\n\n/**\n * Build the MCP tool descriptors and bound implementations against a\n * single engine. Pass the engine the tools should operate on; the\n * returned descriptors are static (safe to cache), the implementations\n * close over the engine.\n *\n * In production this is called once at server boot. In tests it's\n * called per-bench so each eval case has an isolated engine.\n */\nexport function buildTools(engine: Engine, options: BuildToolsOptions = {}): BuiltTools {\n const accessOverride = options.access\n\n const impls: Record<string, ToolImpl> = {\n list_workflow_instances: async (rawInput) => {\n const input = parseListInput(rawInput)\n return listInstances(engine, input)\n },\n get_workflow_state: async (rawInput) => {\n const input = parseInstanceIdInput(rawInput, 'get_workflow_state')\n return getInstanceState(engine, input.instance_id, accessOverride)\n },\n diagnose_workflow: async (rawInput) => {\n const input = parseInstanceIdInput(rawInput, 'diagnose_workflow')\n return getInstanceDiagnosis(engine, input.instance_id, accessOverride)\n },\n fire_action: async (rawInput) => {\n const input = parseFireActionInput(rawInput)\n await engine.fireAction({\n instanceId: input.instance_id,\n activity: input.activity,\n action: input.action,\n ...(accessOverride !== undefined ? {access: accessOverride} : {}),\n })\n // Re-use the same projection so the LLM sees consistent shapes\n // between get_workflow_state and fire_action responses.\n return getInstanceState(engine, input.instance_id, accessOverride)\n },\n // Authoring tools — engine-independent: they teach and check the DSL, they\n // don't touch the lake or an instance.\n get_workflow_authoring_guide: async () => AUTHORING_GUIDE,\n validate_workflow_definition: async (rawInput): Promise<ValidateDefinitionResult> => {\n const {definition} = parseValidateInput(rawInput)\n try {\n // `defineWorkflow` is the gate (valibot structural parse + desugar +\n // cross-field invariants); `validateDefinition` adds GROQ syntax checks.\n // The cast only satisfies the compiler — `defineWorkflow` validates the\n // value at runtime and throws an aggregated, path-prefixed error.\n const stored = defineWorkflow(definition as AuthoringWorkflow)\n validateDefinition(stored)\n return {valid: true, definition: stored}\n } catch (err) {\n return {valid: false, error: err instanceof Error ? err.message : String(err)}\n }\n },\n }\n\n return {descriptors: TOOL_DESCRIPTORS, impls}\n}\n\n// Input parsers — lightweight, no zod dependency\n//\n// Reasoning: pulling in zod would inflate the package for this handful of tools.\n// The MCP server and the eval harness already constrain the shape via\n// the JSON schema in the descriptor; these parsers exist for runtime\n// type-narrowing in TypeScript, not for deep validation.\n\ninterface ListInput {\n definition?: string\n status: 'in_flight' | 'done' | 'any'\n}\n\nfunction parseListInput(raw: unknown): ListInput {\n if (raw === null || typeof raw !== 'object') {\n return {status: 'in_flight'}\n }\n const obj = raw as Record<string, unknown>\n const status = obj.status === 'done' || obj.status === 'any' ? obj.status : ('in_flight' as const)\n const definition = typeof obj.definition === 'string' ? obj.definition : undefined\n return definition !== undefined ? {definition, status} : {status}\n}\n\n/** Narrow the validate input to `{definition: object}`. The deep validation\n * is `defineWorkflow`'s job — this only guards the envelope. */\nfunction parseValidateInput(raw: unknown): {definition: object} {\n if (raw === null || typeof raw !== 'object') {\n throw new Error('validate_workflow_definition: input must be an object')\n }\n const obj = raw as Record<string, unknown>\n if (obj.definition === null || typeof obj.definition !== 'object') {\n throw new Error('validate_workflow_definition: `definition` is required and must be an object')\n }\n return {definition: obj.definition}\n}\n\n/** Shared by every single-instance tool — `tool` names the caller so the\n * thrown error points at the right tool. */\nfunction parseInstanceIdInput(raw: unknown, tool: string): {instance_id: string} {\n if (raw === null || typeof raw !== 'object') {\n throw new Error(`${tool}: input must be an object`)\n }\n const obj = raw as Record<string, unknown>\n if (typeof obj.instance_id !== 'string' || obj.instance_id === '') {\n throw new Error(`${tool}: instance_id is required`)\n }\n return {instance_id: obj.instance_id}\n}\n\nfunction parseFireActionInput(raw: unknown): {\n instance_id: string\n activity: string\n action: string\n} {\n if (raw === null || typeof raw !== 'object') {\n throw new Error('fire_action: input must be an object')\n }\n const obj = raw as Record<string, unknown>\n for (const key of ['instance_id', 'activity', 'action'] as const) {\n if (typeof obj[key] !== 'string' || obj[key] === '') {\n throw new Error(`fire_action: ${key} is required`)\n }\n }\n return {\n instance_id: obj.instance_id as string,\n activity: obj.activity as string,\n action: obj.action as string,\n }\n}\n\n// Engine reads, projected for an LLM\n\nasync function listInstances(\n engine: Engine,\n input: ListInput,\n): Promise<{instances: ProjectedInstanceSummary[]}> {\n // Tag-scoped via the engine's own query helper — every instance\n // returned is one this engine is allowed to see.\n const groqParts = [`_type == \"${WORKFLOW_INSTANCE_TYPE}\"`]\n if (input.definition !== undefined) {\n groqParts.push('definition == $definition')\n }\n const groq =\n `*[${groqParts.join(' && ')} && ${tagScopeFilter()}] ` +\n `| order(lastChangedAt desc)[0...${LIST_CAP}]`\n\n const params: Record<string, unknown> = {}\n if (input.definition !== undefined) params.definition = input.definition\n\n const docs = await engine.query<WorkflowInstance[]>({groq, params})\n const filtered = docs.filter((doc) => {\n const done = isInstanceDone(doc)\n if (input.status === 'done') return done\n if (input.status === 'in_flight') return !done\n return true // \"any\"\n })\n const subjectTitles = await fetchSubjectTitles(engine, filtered)\n return {\n instances: filtered.map((doc) => projectSummary(doc, subjectTitles)),\n }\n}\n\nasync function getInstanceState(\n engine: Engine,\n instanceId: string,\n accessOverride: WorkflowAccessOverride | undefined,\n): Promise<ProjectedInstanceState> {\n const evaluation = await engine.evaluateInstance({\n instanceId,\n ...(accessOverride !== undefined ? {access: accessOverride} : {}),\n })\n const instance = await engine.getInstance({instanceId})\n const subjectTitles = await fetchSubjectTitles(engine, [instance])\n return projectState(instance, evaluation, subjectTitles)\n}\n\nasync function getInstanceDiagnosis(\n engine: Engine,\n instanceId: string,\n accessOverride: WorkflowAccessOverride | undefined,\n): Promise<ProjectedDiagnosis> {\n const {diagnosis, remediations} = await engine.diagnose({\n instanceId,\n ...(accessOverride !== undefined ? {access: accessOverride} : {}),\n })\n return {\n instanceId,\n state: diagnosis.state,\n summary: diagnosisSummary(diagnosis),\n ...(diagnosis.state === 'stuck' ? {cause: diagnosis.cause.kind} : {}),\n remediations,\n }\n}\n"],"names":["extractDocumentId","actionVerdict","isTerminalStage","defineWorkflow","validateDefinition","WORKFLOW_INSTANCE_TYPE","tagScopeFilter"],"mappings":";;;AAqBA,MAAM,iBAAiB;AAAA,EACrB,MAAM;AAAA,EACN,OAAO;AAAA,EACP,aAAa;AAAA,EACb,cAAc;AAAA,EACd,QAAQ,CAAC,EAAC,MAAM,WAAW,MAAM,WAAW,OAAO,YAAY,cAAc,EAAC,MAAM,QAAA,GAAS;AAAA,EAC7F,QAAQ;AAAA,IACN;AAAA,MACE,MAAM;AAAA,MACN,OAAO;AAAA,MACP,YAAY;AAAA,QACV;AAAA,UACE,MAAM;AAAA,UACN,OAAO;AAAA,UACP,YAAY;AAAA,UACZ,SAAS,CAAC,EAAC,MAAM,WAAW,OAAO,WAAW,QAAQ,OAAA,CAAO;AAAA,QAAA;AAAA,MAC/D;AAAA,MAEF,aAAa,CAAC,EAAC,MAAM,eAAe,OAAO,sBAAsB,IAAI,WAAA,CAAW;AAAA,IAAA;AAAA,IAElF,EAAC,MAAM,YAAY,OAAO,YAAY,aAAa,sCAAA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