iit-mcp-autotask 0.54.2

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.
Files changed (164) hide show
  1. package/.env.example +123 -0
  2. package/LICENSE +21 -0
  3. package/README.md +788 -0
  4. package/capabilities.json +487 -0
  5. package/dist/access/gate.d.ts +34 -0
  6. package/dist/access/gate.js +76 -0
  7. package/dist/access/grants.d.ts +20 -0
  8. package/dist/access/grants.js +35 -0
  9. package/dist/access/write-env.d.ts +41 -0
  10. package/dist/access/write-env.js +166 -0
  11. package/dist/auth.d.ts +74 -0
  12. package/dist/auth.js +129 -0
  13. package/dist/base-hosts.d.ts +38 -0
  14. package/dist/base-hosts.js +70 -0
  15. package/dist/config/load.d.ts +28 -0
  16. package/dist/config/load.js +105 -0
  17. package/dist/config/schema.d.ts +166 -0
  18. package/dist/config/schema.js +311 -0
  19. package/dist/credential.d.ts +28 -0
  20. package/dist/credential.js +32 -0
  21. package/dist/doctor.d.ts +112 -0
  22. package/dist/doctor.js +154 -0
  23. package/dist/http-guard.d.ts +57 -0
  24. package/dist/http-guard.js +134 -0
  25. package/dist/http.d.ts +50 -0
  26. package/dist/http.js +290 -0
  27. package/dist/lifecycle.d.ts +29 -0
  28. package/dist/lifecycle.js +52 -0
  29. package/dist/logger.d.ts +26 -0
  30. package/dist/logger.js +28 -0
  31. package/dist/main.d.ts +12 -0
  32. package/dist/main.js +283 -0
  33. package/dist/policy.d.ts +54 -0
  34. package/dist/policy.js +80 -0
  35. package/dist/tools/aggregate.d.ts +16 -0
  36. package/dist/tools/aggregate.js +64 -0
  37. package/dist/tools/capabilities-manifest.d.ts +4 -0
  38. package/dist/tools/capabilities-manifest.js +94 -0
  39. package/dist/tools/catalog-data.d.ts +116 -0
  40. package/dist/tools/catalog-data.js +207 -0
  41. package/dist/tools/clock.d.ts +17 -0
  42. package/dist/tools/clock.js +43 -0
  43. package/dist/tools/composites.d.ts +36 -0
  44. package/dist/tools/composites.js +305 -0
  45. package/dist/tools/context/client.d.ts +41 -0
  46. package/dist/tools/context/client.js +139 -0
  47. package/dist/tools/context/derive.d.ts +9 -0
  48. package/dist/tools/context/derive.js +32 -0
  49. package/dist/tools/context/scope.d.ts +24 -0
  50. package/dist/tools/context/scope.js +180 -0
  51. package/dist/tools/context/types.d.ts +141 -0
  52. package/dist/tools/context/types.js +2 -0
  53. package/dist/tools/dispatch.d.ts +78 -0
  54. package/dist/tools/dispatch.js +272 -0
  55. package/dist/tools/field-pointer.d.ts +25 -0
  56. package/dist/tools/field-pointer.js +45 -0
  57. package/dist/tools/guide.d.ts +30 -0
  58. package/dist/tools/guide.js +97 -0
  59. package/dist/tools/lists.d.ts +9 -0
  60. package/dist/tools/lists.js +205 -0
  61. package/dist/tools/meta.d.ts +22 -0
  62. package/dist/tools/meta.js +709 -0
  63. package/dist/tools/output-file.d.ts +26 -0
  64. package/dist/tools/output-file.js +140 -0
  65. package/dist/tools/rank.d.ts +21 -0
  66. package/dist/tools/rank.js +57 -0
  67. package/dist/tools/reasons.d.ts +33 -0
  68. package/dist/tools/reasons.js +121 -0
  69. package/dist/tools/register.d.ts +23 -0
  70. package/dist/tools/register.js +50 -0
  71. package/dist/tools/resolves.d.ts +28 -0
  72. package/dist/tools/resolves.js +399 -0
  73. package/dist/tools/results/envelope.d.ts +55 -0
  74. package/dist/tools/results/envelope.js +63 -0
  75. package/dist/tools/results/errors.d.ts +147 -0
  76. package/dist/tools/results/errors.js +384 -0
  77. package/dist/tools/results/untrusted.d.ts +129 -0
  78. package/dist/tools/results/untrusted.js +218 -0
  79. package/dist/tools/revenue-rollup.d.ts +8 -0
  80. package/dist/tools/revenue-rollup.js +112 -0
  81. package/dist/tools/schemas.d.ts +467 -0
  82. package/dist/tools/schemas.js +444 -0
  83. package/dist/tools/scope-guard.d.ts +2 -0
  84. package/dist/tools/scope-guard.js +11 -0
  85. package/dist/tools/server-version.d.ts +3 -0
  86. package/dist/tools/server-version.js +14 -0
  87. package/dist/tools/server.d.ts +92 -0
  88. package/dist/tools/server.js +170 -0
  89. package/dist/tools/surface.d.ts +37 -0
  90. package/dist/tools/surface.js +94 -0
  91. package/dist/tools/tsv.d.ts +52 -0
  92. package/dist/tools/tsv.js +95 -0
  93. package/dist/tools/write/apply.d.ts +40 -0
  94. package/dist/tools/write/apply.js +500 -0
  95. package/dist/tools/write/checks.d.ts +39 -0
  96. package/dist/tools/write/checks.js +137 -0
  97. package/dist/tools/write/common.d.ts +23 -0
  98. package/dist/tools/write/common.js +33 -0
  99. package/dist/tools/write/facts.d.ts +52 -0
  100. package/dist/tools/write/facts.js +151 -0
  101. package/dist/tools/write/outcome.d.ts +23 -0
  102. package/dist/tools/write/outcome.js +67 -0
  103. package/dist/tools/write/parse.d.ts +37 -0
  104. package/dist/tools/write/parse.js +166 -0
  105. package/dist/tools/write/payload.d.ts +44 -0
  106. package/dist/tools/write/payload.js +119 -0
  107. package/dist/tools/write/preview.d.ts +3 -0
  108. package/dist/tools/write/preview.js +317 -0
  109. package/dist/tools/write/snapshot.d.ts +68 -0
  110. package/dist/tools/write/snapshot.js +360 -0
  111. package/dist/tools/write-guidance.d.ts +174 -0
  112. package/dist/tools/write-guidance.js +317 -0
  113. package/dist/tools/write.d.ts +9 -0
  114. package/dist/tools/write.js +10 -0
  115. package/dist/write/canonical.d.ts +12 -0
  116. package/dist/write/canonical.js +31 -0
  117. package/dist/write/evaluate.d.ts +77 -0
  118. package/dist/write/evaluate.js +91 -0
  119. package/dist/write/hard-rules.d.ts +49 -0
  120. package/dist/write/hard-rules.js +48 -0
  121. package/dist/write/runtime.d.ts +37 -0
  122. package/dist/write/runtime.js +72 -0
  123. package/dist/write/store/audit-log.d.ts +13 -0
  124. package/dist/write/store/audit-log.js +25 -0
  125. package/dist/write/store/constants.d.ts +34 -0
  126. package/dist/write/store/constants.js +35 -0
  127. package/dist/write/store/files.d.ts +44 -0
  128. package/dist/write/store/files.js +157 -0
  129. package/dist/write/store/heartbeat.d.ts +9 -0
  130. package/dist/write/store/heartbeat.js +65 -0
  131. package/dist/write/store/ledger.d.ts +15 -0
  132. package/dist/write/store/ledger.js +86 -0
  133. package/dist/write/store/lifecycle.d.ts +35 -0
  134. package/dist/write/store/lifecycle.js +114 -0
  135. package/dist/write/store/lock.d.ts +97 -0
  136. package/dist/write/store/lock.js +464 -0
  137. package/dist/write/store/op-lock.d.ts +13 -0
  138. package/dist/write/store/op-lock.js +175 -0
  139. package/dist/write/store/plan-store.d.ts +7 -0
  140. package/dist/write/store/plan-store.js +48 -0
  141. package/dist/write/store/plans.d.ts +5 -0
  142. package/dist/write/store/plans.js +19 -0
  143. package/dist/write/store/types.d.ts +195 -0
  144. package/dist/write/store/types.js +2 -0
  145. package/dist/write/store.d.ts +6 -0
  146. package/dist/write/store.js +182 -0
  147. package/examples/agentgateway.write-gate.yaml +29 -0
  148. package/package.json +71 -0
  149. package/server.json +69 -0
  150. package/skills/ar-aging.md +65 -0
  151. package/skills/company-360.md +69 -0
  152. package/skills/contract-profitability.md +65 -0
  153. package/skills/crm-management.md +87 -0
  154. package/skills/filter-semantics.md +75 -0
  155. package/skills/invoice-export.md +61 -0
  156. package/skills/log-time-entry.md +77 -0
  157. package/skills/non-chargeable-work.md +67 -0
  158. package/skills/portfolio-margin.md +66 -0
  159. package/skills/recurring-revenue.md +65 -0
  160. package/skills/revenue-rollup.md +65 -0
  161. package/skills/slim-reads.md +67 -0
  162. package/skills/ticket-triage.md +64 -0
  163. package/skills/unbilled-work-review.md +66 -0
  164. package/skills/wip-hours.md +68 -0
@@ -0,0 +1,272 @@
1
+ /**
2
+ * tools/dispatch.ts — the shared tool-call frame and the registry read path.
3
+ *
4
+ * The shared frame ({@link runTool}) is the seam the tests lean on: handlers carry no mock
5
+ * branches; the client + the `ToolOps` bundle come from the context, and a fixture-backed bundle
6
+ * answers every tool identically to production. It also owns the envelope: every result leaves
7
+ * it with this serving unit's correlation id stamped, and every input is parsed here (M1), so the
8
+ * SDK never answers a call with its own plain-text error.
9
+ *
10
+ * `readOneItem` is the single registry-read implementation: `autotask_read` (one operation or up
11
+ * to 10 `items`) and the read-backed tools all drive it, so every read passes the same gates in
12
+ * the same order.
13
+ */
14
+ import { AutotaskConfigError } from 'node-autotask';
15
+ import { stripUntrustedDeep } from 'node-autotask/untrusted';
16
+ import { assertFilterShape, QUERY_LIMIT, QUERY_MAX_ROWS } from './schemas.js';
17
+ import { RECORDS, toolForOp } from './catalog-data.js';
18
+ import { AUTOTASK_BASE_PATH } from '../base-hosts.js';
19
+ import { releaseClientOnError } from './context/derive.js';
20
+ import { abortedResult, closedArgsError, errorContent, refusalContent } from './results/errors.js';
21
+ import { crossResourceUntrusted, isFileOperation, markFilePayload, markResult, markServerField } from './results/untrusted.js';
22
+ import {} from './results/envelope.js';
23
+ import { assertOperationPermitted } from '../policy.js';
24
+ import { scopeRequiredInput } from './scope-guard.js';
25
+ import { fieldNameInput } from './field-pointer.js';
26
+ /** The MCP request's AbortSignal, when the transport provides one (architecture 7.6). */
27
+ function mcpSignal(extra) {
28
+ const e = extra;
29
+ return e?.mcpReq?.signal;
30
+ }
31
+ /** A typed input refusal raised inside a handler (an invalid argument combination). */
32
+ export class InputInvalidError extends AutotaskConfigError {
33
+ field;
34
+ constructor(message, field, operation) {
35
+ super(message, operation === undefined ? {} : { operation });
36
+ if (field !== undefined)
37
+ this.field = field;
38
+ }
39
+ }
40
+ /**
41
+ * The shared call frame, run by EVERY registered handler:
42
+ * 1. the closed top-level argument set (issue #3: an unknown key is refused with the typed
43
+ * contract, its value never echoed — BEFORE anything else);
44
+ * 2. the zod parse of the input (M1: a schema-invalid input answers the `INPUT_INVALID` envelope);
45
+ * 3. the fail-closed refusal (a placeholder client answers its typed envelope, zero vendor
46
+ * wire, before any request is built);
47
+ * 4. the work, with the SDK error contract mapped on failure (wrap, never flatten) and the
48
+ * pooled client released on a credential refusal (no negative caching);
49
+ * 5. the correlation id stamped on the envelope (and the mirrored text block).
50
+ */
51
+ export async function runTool(ctx, input, rawArgs, extra, work) {
52
+ return stamp(ctx.correlationId, await frame(ctx, input, rawArgs, extra, work));
53
+ }
54
+ /** `raw` without the keys `ignored` names (a copy; `raw` itself unchanged), or `raw` as is when there are none. */
55
+ function dropKeys(raw, ignored) {
56
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
57
+ return raw;
58
+ const keys = ignored(raw);
59
+ return keys.length === 0 ? raw : Object.fromEntries(Object.entries(raw).filter(([k]) => !keys.includes(k)));
60
+ }
61
+ async function frame(ctx, input, rawArgs, extra, work) {
62
+ const raw = dropKeys(rawArgs ?? {}, input.ignored);
63
+ const closed = closedArgsError(raw, input.validKeys, ctx.correlationId);
64
+ if (closed !== null)
65
+ return closed;
66
+ const parsed = input.schema.safeParse(raw);
67
+ if (!parsed.success) {
68
+ const issue = parsed.error.issues[0];
69
+ const field = issue === undefined ? undefined : issue.path.map(String).join('.');
70
+ return errorContent(new InputInvalidError(`invalid input: ${input.hint?.(raw) ?? ''}${parsed.error.issues.map((i) => `${i.path.map(String).join('.') || '(input)'}: ${i.message}`).join('; ')}`, field === '' ? undefined : field), ctx.correlationId);
71
+ }
72
+ if (ctx.refusal !== undefined)
73
+ return refusalContent(ctx.refusal.kind, ctx.correlationId, ctx.refusal.anomalies ?? []);
74
+ try {
75
+ return await work(parsed.data, mcpSignal(extra), extra);
76
+ }
77
+ catch (err) {
78
+ releaseClientOnError(ctx, err);
79
+ // V23/FT-5: the request's own credential values ride into the error wrap so a vendor body
80
+ // that echoes them is value-scrubbed before it crosses.
81
+ return errorContent(err, ctx.correlationId, requestSecrets(ctx));
82
+ }
83
+ }
84
+ /**
85
+ * Stamp the serving unit's correlation id on a finished result (and its mirrored text block).
86
+ * An `input_required` result is not a tool result: it carries no envelope and is returned untouched.
87
+ */
88
+ function stamp(correlationId, result) {
89
+ if (!('structuredContent' in result) || result.structuredContent === undefined)
90
+ return result;
91
+ const finished = result;
92
+ if (finished.structuredContent.correlationId !== '')
93
+ return finished;
94
+ finished.structuredContent.correlationId = correlationId;
95
+ const first = finished.content[0];
96
+ if (first !== undefined)
97
+ first.text = JSON.stringify(finished.structuredContent);
98
+ return finished;
99
+ }
100
+ /** The typed answer when the MCP request was cancelled before the upstream call settled. */
101
+ export function abortedAnswer(corr) {
102
+ return abortedResult(corr);
103
+ }
104
+ /**
105
+ * The request's own credential values (V23/FT-5 scrub scope): the 3-tuple + the impersonation
106
+ * id that THIS serving unit dialed (or dials) the vendor with. The vendor may echo any of them
107
+ * in a 4xx body; the error wrap value-scrubs them before the envelope crosses.
108
+ */
109
+ export function requestSecrets(ctx) {
110
+ const pc = ctx.poolConfig;
111
+ if (pc === undefined)
112
+ return [];
113
+ const out = [];
114
+ for (const v of [pc.apiIntegrationCode, pc.userName, pc.secret, pc.impersonationResourceId]) {
115
+ if (typeof v === 'string' && v.length > 0)
116
+ out.push(v);
117
+ }
118
+ return out;
119
+ }
120
+ /**
121
+ * The default `maxBytes` of a served fieldCatalog result (node-autotask 0.39.0 #282). The cap bounds the
122
+ * SDK result; the MCP message is about 3x it: the field names are wrapped as untrusted content (measured
123
+ * 1.4x on a five-resource compact catalog), and the envelope crosses twice (structuredContent plus its
124
+ * escaped JSON copy in the text block, 2.1x). 30,000 keeps the message near 90 KB, under ~96 KB; 65,536
125
+ * would serve about 190 KB. A caller that needs more passes its own maxBytes.
126
+ */
127
+ export const FIELD_CATALOG_MAX_BYTES = 30_000;
128
+ /** The reads whose `nextCursor` is a pass-back pagination cursor: the SDK's `metadata.passBackCursor` marker (#254, node-autotask 0.48.0 #378). */
129
+ export const CURSOR_OPS = new Set(RECORDS.filter((r) => r.metadata?.passBackCursor === 'nextCursor').map((r) => r.id));
130
+ /** The continuation path a TimeEntries cursor names, under the fixed base path (compared case-insensitively). */
131
+ const ENTRY_CURSOR_PATH = `${AUTOTASK_BASE_PATH}/V1.0/TimeEntries/query/next`.toLowerCase();
132
+ /** The query a vendor continuation URL carries: `paging` and `search`, URL-encoded values only. */
133
+ const ENTRY_CURSOR_PARAM = /^(?:paging|search)=[A-Za-z0-9%._~+-]+$/;
134
+ /**
135
+ * A vendor TimeEntries continuation URL (#224; mirrors the SDK's cursorToPath + entryCursorPath, tighter):
136
+ * printable ASCII with no whitespace, absolute and already in canonical form, on this request's own Autotask origin, no userinfo, no
137
+ * fragment, exactly the continuation path, and only `paging` / `search` query parameters with encoded
138
+ * values. Anything else is not granted the cursor exemption (it is served as wrapped, capped vendor text).
139
+ */
140
+ export function isEntryCursor(value, origin) {
141
+ if (origin === undefined || !/^[\x21-\x7e]+$/.test(value) || !value.startsWith(`${origin}/`))
142
+ return false;
143
+ let u;
144
+ try {
145
+ u = new URL(value);
146
+ }
147
+ catch {
148
+ return false;
149
+ }
150
+ if (u.href !== value || u.origin !== origin || u.username !== '' || u.password !== '' || u.hash !== '' || value.includes('#'))
151
+ return false;
152
+ if (u.pathname.toLowerCase() !== ENTRY_CURSOR_PATH)
153
+ return false;
154
+ const query = u.search.replace(/^\?/, '');
155
+ return query === '' || query.split('&').every((p) => ENTRY_CURSOR_PARAM.test(p));
156
+ }
157
+ /**
158
+ * The helper reads whose result is marked by their own SDK untrusted stamp (#254) instead of the
159
+ * cross-resource union, which names fields their folds use for closed enums. Since node-autotask 0.48.0
160
+ * (#378) the `contracts.profitability` stamp names its folded `label` and `note`; #196 keeps the rollup's
161
+ * picklist labels plain, and portfolioMargin (SDK 0.49.0) and recurringRevenue (SDK 0.52.0) and arAging (SDK 0.54.0) and wipHours (SDK 0.55.0) and nonChargeableWork (SDK 0.56.0) stamp only their vendor `name`. All strings still pass the shared sanitizer.
162
+ */
163
+ const OWN_STAMP_OPS = new Set(['contracts.profitability', 'operations.revenueRollup', 'operations.portfolioMargin', 'operations.recurringRevenue', 'operations.arAging', 'operations.wipHours', 'operations.nonChargeableWork']);
164
+ /**
165
+ * Server-built annotations added to a served result AFTER the untrusted marking (issue #102). Each
166
+ * `operations.fieldCatalog` resource row says which `autotask_query` operation serves it (or null:
167
+ * `autotask_read` only). The name is NOT `queryable`: the SDK row already carries `queryable: string[]`.
168
+ */
169
+ function annotateCatalogRows(result) {
170
+ // 0.39.0 (#282): the truncation note is SDK-built (an enum reason, byte counts, resource keys), never vendor
171
+ // text; `reason` and `note` share names with vendor free-text fields, so they are recorded server-built.
172
+ const truncation = result?.truncation;
173
+ if (truncation !== null && typeof truncation === 'object')
174
+ for (const key of ['reason', 'note'])
175
+ markServerField(truncation, key, 'server');
176
+ const rows = result?.rows;
177
+ if (!Array.isArray(rows))
178
+ return;
179
+ for (const row of rows) {
180
+ if (row === null || typeof row !== 'object')
181
+ continue;
182
+ const resource = row.resource;
183
+ // #228: autotask_query serves every <resource>.query read
184
+ row.queryOperation = typeof resource === 'string' && toolForOp(`${resource}.query`) === 'autotask_query' ? `${resource}.query` : null;
185
+ }
186
+ }
187
+ /**
188
+ * One registry read, through every gate in order: the unknown-operation refusal, the deployment
189
+ * policy (reads only; credential-minting never), the ONE-level `<untrusted_content>` strip of the
190
+ * inputs, the query/count filter-shape gate, the governed invoke (the SDK's single read governor)
191
+ * and the untrusted projection of the result. Errors are THROWN — the frame wraps them once, the
192
+ * `items` form maps them per slot.
193
+ */
194
+ export async function readOneItem(ctx, operation, args, signal, opts) {
195
+ const rec = ctx.record(operation);
196
+ if (rec === undefined) {
197
+ throw new AutotaskConfigError(`invoke: unknown operation "${operation}" — it is not in the capability registry (find the exact key with autotask_catalog)`, { operation });
198
+ }
199
+ assertOperationPermitted(operation, rec, ctx.config, ctx.log);
200
+ // Issue #1: strip ONE exact outer <untrusted_content> wrapper from the string inputs.
201
+ const cleanArgs = stripUntrustedDeep(args);
202
+ // #294: the SDK signature requires the options bag; an omitted one is empty (the SDK owns the window default and validation).
203
+ if (operation === 'contracts.profitability' && cleanArgs[1] === undefined)
204
+ cleanArgs[1] = {};
205
+ let walkMaxRows;
206
+ // #18: the *.query / *.count ops take a params bag whose `filter` top-level shape is refused
207
+ // pre-request (zero wire on a refused shape).
208
+ if (operation.endsWith('.query') || operation.endsWith('.count')) {
209
+ // No params bag at all (args omitted / []): the same bounded default (#83); the SDK's own bag-less form is unbounded.
210
+ // #243: a missing or [] filter stays accepted here (limit 50; the walk guard above 500 rows): autotask_read is the generic
211
+ // path and this bounded default is its contract; autotask_query refuses the missing filter because it is the guided surface.
212
+ if (operation.endsWith('.query') && cleanArgs[0] === undefined)
213
+ cleanArgs[0] = { limit: QUERY_LIMIT.parse(undefined) };
214
+ // #173: a digit-string limit/latest arrives as a number (READ_INPUT coerces the query bag).
215
+ const bagArg = cleanArgs[0];
216
+ if (bagArg !== null && typeof bagArg === 'object' && !Array.isArray(bagArg)) {
217
+ assertFilterShape(bagArg.filter, operation);
218
+ const bag = { ...bagArg };
219
+ const walk = bag.walk;
220
+ walkMaxRows = walk !== null && typeof walk === 'object' ? walk.maxRows : undefined;
221
+ if (operation.endsWith('.query') && typeof walkMaxRows === 'number' && walkMaxRows > QUERY_MAX_ROWS) {
222
+ throw new InputInvalidError(`query: walk.maxRows cannot exceed ${QUERY_MAX_ROWS} for inline reads; use autotask_query with output_path for larger exports`, 'args[0].walk.maxRows', operation);
223
+ }
224
+ // Slim-read default: a bare *.query read is bounded like autotask_query (explicit limit honoured).
225
+ if (operation.endsWith('.query') && !('limit' in bag)) {
226
+ const latest = bag.latest;
227
+ bag.limit = Math.max(QUERY_LIMIT.parse(undefined), typeof latest === 'number' ? latest : 0);
228
+ }
229
+ cleanArgs[0] = bag;
230
+ }
231
+ }
232
+ let scopeNote;
233
+ if (operation.endsWith('.query') && cleanArgs[0] !== null && typeof cleanArgs[0] === 'object' && !Array.isArray(cleanArgs[0])) {
234
+ const bag = cleanArgs[0];
235
+ // A no-filter read is a bounded sample of the tenant table (#245).
236
+ const f = bag.filter;
237
+ if ((f === undefined || (Array.isArray(f) && f.length === 0)) && bag.latest === undefined && typeof bag.limit === 'number') {
238
+ scopeNote = `no filter: the first ${typeof walkMaxRows === 'number' ? walkMaxRows : bag.limit} rows in id order, not a scoped or complete answer.`;
239
+ }
240
+ }
241
+ // The SDK owns compact rows; this serving surface keeps projected labels and its message-size cap.
242
+ if (operation === 'operations.fieldCatalog' && (cleanArgs[0] === undefined || (cleanArgs[0] !== null && typeof cleanArgs[0] === 'object' && !Array.isArray(cleanArgs[0])))) {
243
+ const bag = (cleanArgs[0] ?? {});
244
+ cleanArgs[0] = { ...(Array.isArray(bag.fields) && bag.fields.length > 0 ? { labels: true } : {}), maxBytes: FIELD_CATALOG_MAX_BYTES, ...bag };
245
+ }
246
+ const result = await ctx.ops.invokeRead(ctx.client, operation, cleanArgs, opts, signal).catch((err) => {
247
+ // #224: a refused cursor the caller passed is the caller's input; a refused vendor continuation is not
248
+ if (CURSOR_OPS.has(operation) && err?.code === 'RESPONSE_REJECTED' && cleanArgs.some((a) => a !== null && typeof a === 'object' && typeof a.cursor === 'string')) {
249
+ Object.assign(err, { callerInput: true });
250
+ }
251
+ throw fieldNameInput(scopeRequiredInput(err, operation === 'operations.aggregate' ? 'args[1]' : 'args[0].filter'));
252
+ });
253
+ if (result === undefined)
254
+ return { aborted: true, result: undefined };
255
+ if (OWN_STAMP_OPS.has(operation))
256
+ return { result: markResult(result, ctx.untrustedFields(operation)), ...(scopeNote !== undefined ? { scopeNote } : {}) };
257
+ // Issue #1: wrap the SDK result's externally-sourced free text — envelope-shaped results are
258
+ // walked deeply (items[] arrays included).
259
+ // Arrays too (final review R2: the *.search and find helpers answer arrays).
260
+ const projected = result !== null && typeof result === 'object' ? markResult(result, crossResourceUntrusted()) : result;
261
+ if (isFileOperation(operation))
262
+ markFilePayload(projected);
263
+ // #224: the posted-state reads' nextCursor goes back verbatim as opts.cursor; the 500 cap would cut it
264
+ const cursor = CURSOR_OPS.has(operation) && projected !== null && typeof projected === 'object' ? projected.nextCursor : undefined;
265
+ // only a TimeEntries continuation URL is a cursor; anything else is vendor text (500 cap, wrapped)
266
+ if (typeof cursor === 'string')
267
+ markServerField(projected, 'nextCursor', isEntryCursor(cursor, ctx.origin) ? 'cursor' : 'wrap');
268
+ if (operation === 'operations.fieldCatalog')
269
+ annotateCatalogRows(projected);
270
+ return { result: projected, ...(scopeNote !== undefined ? { scopeNote } : {}) };
271
+ }
272
+ //# sourceMappingURL=dispatch.js.map
@@ -0,0 +1,25 @@
1
+ /**
2
+ * tools/field-pointer.ts — the one place the "how do I list this resource's field names" call is
3
+ * written (issues #102, #98). The bare `operations.fieldCatalog` serves the five workflow resources
4
+ * (~85 KB) and misses four of the five queryable resources; a SCOPED call serves one resource's row.
5
+ * The query refusal, the playbooks and the instruction text all quote this, so they cannot drift.
6
+ */
7
+ /** The scoped catalog call for one resource (`resources: [key]` — a scoped call also returns picklist labels by default on this server). */
8
+ export declare function scopedCatalogCall(resource: string): string;
9
+ /** The same call with a placeholder, as the playbooks print it. */
10
+ export declare const SCOPED_CATALOG_TEMPLATE: string;
11
+ /**
12
+ * The field-name lookup for one resource (#197, F3): a projected, labelled `operations.fieldCatalog` call.
13
+ * `fields` names the columns wanted; a scoped call without `fields` serves the whole resource row.
14
+ */
15
+ export declare function fieldLookupCall(resource: string): string;
16
+ /**
17
+ * S8 (#183): the scoped read that serves one resource's UDF definition rows (SDK 0.34.0 #219 N7:
18
+ * the `udf` include; labels and picklist values ride `labels: true`). UDF definitions are
19
+ * tenant-specific and never in the plan artifact, so this live read is their only source.
20
+ */
21
+ export declare function udfCatalogCall(resource: string): string;
22
+ /** Why a bare `<resource>.getFieldInfo` is the wrong way to find one field (a whole table per call). */
23
+ export declare const FIELD_INFO_EXPENSIVE = "Expensive: it returns the whole field table (about 190 KB for companies) on every call. To find a field name use operations.fieldCatalog with resources, fields and labels:true.";
24
+ /** Map SDK field-name syntax to the calling tool, keeping the SDK's remedy. */
25
+ export declare function fieldNameInput(err: unknown, query?: boolean): unknown;
@@ -0,0 +1,45 @@
1
+ /**
2
+ * tools/field-pointer.ts — the one place the "how do I list this resource's field names" call is
3
+ * written (issues #102, #98). The bare `operations.fieldCatalog` serves the five workflow resources
4
+ * (~85 KB) and misses four of the five queryable resources; a SCOPED call serves one resource's row.
5
+ * The query refusal, the playbooks and the instruction text all quote this, so they cannot drift.
6
+ */
7
+ import { AutotaskConfigError } from 'node-autotask';
8
+ /** The scoped catalog call for one resource (`resources: [key]` — a scoped call also returns picklist labels by default on this server). */
9
+ export function scopedCatalogCall(resource) {
10
+ return `autotask_read {operation:"operations.fieldCatalog", args:[{resources:["${resource}"]}]}`;
11
+ }
12
+ /** The same call with a placeholder, as the playbooks print it. */
13
+ export const SCOPED_CATALOG_TEMPLATE = scopedCatalogCall('<resource>');
14
+ /**
15
+ * The field-name lookup for one resource (#197, F3): a projected, labelled `operations.fieldCatalog` call.
16
+ * `fields` names the columns wanted; a scoped call without `fields` serves the whole resource row.
17
+ */
18
+ export function fieldLookupCall(resource) {
19
+ return `autotask_read {operation:"operations.fieldCatalog", args:[{resources:["${resource}"], fields:["<name>"], labels:true}]}`;
20
+ }
21
+ /**
22
+ * S8 (#183): the scoped read that serves one resource's UDF definition rows (SDK 0.34.0 #219 N7:
23
+ * the `udf` include; labels and picklist values ride `labels: true`). UDF definitions are
24
+ * tenant-specific and never in the plan artifact, so this live read is their only source.
25
+ */
26
+ export function udfCatalogCall(resource) {
27
+ return `autotask_read {operation:"operations.fieldCatalog", args:[{resources:["${resource}"], include:["udf"], labels:true}]}`;
28
+ }
29
+ /** Why a bare `<resource>.getFieldInfo` is the wrong way to find one field (a whole table per call). */
30
+ export const FIELD_INFO_EXPENSIVE = 'Expensive: it returns the whole field table (about 190 KB for companies) on every call. To find a field name use operations.fieldCatalog with resources, fields and labels:true.';
31
+ /** Map SDK field-name syntax to the calling tool, keeping the SDK's remedy. */
32
+ export function fieldNameInput(err, query = false) {
33
+ if (!(err instanceof AutotaskConfigError) || !err.message.includes('unknown field name'))
34
+ return err;
35
+ const syntax = (text) => {
36
+ const clean = text.replace(/\s*\(src\/field-sets\.ts\)/g, '');
37
+ return query ? clean.replaceAll('includeFields', 'include_fields').replace(/\bfieldCheck:\s*false\b/g, 'autotask_read args[0].fieldCheck:false') : clean;
38
+ };
39
+ err.message = syntax(err.message);
40
+ const e = err;
41
+ if (typeof e.suggestedAction === 'string')
42
+ e.suggestedAction = syntax(e.suggestedAction);
43
+ return err;
44
+ }
45
+ //# sourceMappingURL=field-pointer.js.map
@@ -0,0 +1,30 @@
1
+ import type { ToolContext } from './context/types.js';
2
+ import type { BuiltTool } from './surface.js';
3
+ /** The packaged skills directory (two levels up from both `src/tools/` and `dist/tools/`). */
4
+ export declare const SKILLS_DIR: import("url").URL;
5
+ export interface Skill {
6
+ name: string;
7
+ description: string;
8
+ kind: string;
9
+ profile: string;
10
+ /** `<tool>:<operation>` or bare `<tool>` entries, as written in the frontmatter. */
11
+ ops: string[];
12
+ related: string[];
13
+ /** The whole file (frontmatter included). */
14
+ text: string;
15
+ /** The body sections by `## ` heading. */
16
+ sections: Record<string, string>;
17
+ frontmatter: Record<string, unknown>;
18
+ }
19
+ /**
20
+ * Parse the frontmatter: one `key: value` per line, where a value opening with `[` or `{` is JSON
21
+ * (a YAML flow collection) and anything else is a plain string.
22
+ */
23
+ export declare function parseSkill(text: string): Skill;
24
+ /** Every packaged skill, read once at boot, by name. */
25
+ export declare const SKILLS: ReadonlyMap<string, Skill>;
26
+ /** The skills whose steps use `operation` (the `playbooks[]` reverse index). */
27
+ export declare function playbooksFor(operation: string): string[];
28
+ /** The skills a profile can run (operator skills are listed only where the write path is served). */
29
+ export declare function skillsFor(profile: string): Skill[];
30
+ export declare function buildGuide(ctx: ToolContext): BuiltTool;
@@ -0,0 +1,97 @@
1
+ /**
2
+ * tools/guide.ts — `autotask_guide`: the packaged outcome playbooks (`skills/*.md`).
3
+ *
4
+ * No args returns the index (one line per skill); `{skill}` returns one skill file and
5
+ * `{skill, section}` one of its sections. The files are static and packaged with the server: the
6
+ * guide never interpolates API data and never calls the vendor. Each skill's frontmatter `ops`
7
+ * list (`<tool>:<operation>` entries) also feeds the reverse index `autotask_describe` serves as
8
+ * `playbooks[]`, so a model that lands on an operation is pointed at the recipe that uses it.
9
+ */
10
+ import { readdirSync, readFileSync } from 'node:fs';
11
+ import { NotFoundError } from 'node-autotask';
12
+ import { GUIDE_INPUT, closedInput } from './schemas.js';
13
+ import { ok } from './results/envelope.js';
14
+ /** The packaged skills directory (two levels up from both `src/tools/` and `dist/tools/`). */
15
+ export const SKILLS_DIR = new URL('../../skills/', import.meta.url);
16
+ /**
17
+ * Parse the frontmatter: one `key: value` per line, where a value opening with `[` or `{` is JSON
18
+ * (a YAML flow collection) and anything else is a plain string.
19
+ */
20
+ export function parseSkill(text) {
21
+ const m = /^---\n([\s\S]*?)\n---\n/.exec(text);
22
+ if (m === null)
23
+ throw new Error('skill file has no frontmatter');
24
+ const fm = {};
25
+ for (const line of (m[1] ?? '').split('\n')) {
26
+ const i = line.indexOf(':');
27
+ if (i <= 0)
28
+ continue;
29
+ const key = line.slice(0, i).trim();
30
+ const raw = line.slice(i + 1).trim();
31
+ fm[key] = raw.startsWith('[') || raw.startsWith('{') ? JSON.parse(raw) : raw;
32
+ }
33
+ const sections = {};
34
+ const body = text.slice(m[0].length).replace(/^<!-- generated:(start|end) -->$/gm, '');
35
+ for (const part of body.split(/^## /m).slice(1)) {
36
+ const nl = part.indexOf('\n');
37
+ sections[part.slice(0, nl).trim()] = part.slice(nl + 1).trim();
38
+ }
39
+ const list = (v) => (Array.isArray(v) ? v.map(String) : []);
40
+ return {
41
+ name: String(fm.name ?? ''),
42
+ description: String(fm.description ?? ''),
43
+ kind: String(fm.kind ?? ''),
44
+ profile: String(fm.profile ?? ''),
45
+ ops: list(fm.ops),
46
+ related: list(fm.related),
47
+ text,
48
+ sections,
49
+ frontmatter: fm,
50
+ };
51
+ }
52
+ /** Every packaged skill, read once at boot, by name. */
53
+ export const SKILLS = (() => {
54
+ const out = new Map();
55
+ for (const file of readdirSync(SKILLS_DIR).filter((f) => f.endsWith('.md')).sort()) {
56
+ const skill = parseSkill(readFileSync(new URL(file, SKILLS_DIR), 'utf8'));
57
+ out.set(skill.name, skill);
58
+ }
59
+ return out;
60
+ })();
61
+ /** The skills whose steps use `operation` (the `playbooks[]` reverse index). */
62
+ export function playbooksFor(operation) {
63
+ return [...SKILLS.values()].filter((s) => s.ops.some((o) => o.split(':')[1] === operation)).map((s) => s.name);
64
+ }
65
+ /** The skills a profile can run (operator skills are listed only where the write path is served). */
66
+ export function skillsFor(profile) {
67
+ return [...SKILLS.values()].filter((s) => s.profile === 'readonly' || s.profile === profile);
68
+ }
69
+ export function buildGuide(ctx) {
70
+ return {
71
+ title: 'Autotask playbooks (guide)',
72
+ input: closedInput(GUIDE_INPUT),
73
+ run: async (raw) => {
74
+ const args = raw;
75
+ const available = skillsFor(ctx.config.AUTOTASK_PROFILE);
76
+ if (args.skill === undefined) {
77
+ return ok(`${available.length} playbook(s). Call autotask_guide {skill} for one.`, {
78
+ skills: available.map((s) => ({ name: s.name, kind: s.kind, description: s.description })),
79
+ });
80
+ }
81
+ const skill = available.find((s) => s.name === args.skill);
82
+ if (skill === undefined) {
83
+ throw new NotFoundError(`guide: no playbook named "${args.skill}"`, { suggestedAction: 'Call autotask_guide with no arguments for the index.' });
84
+ }
85
+ if (args.section === undefined)
86
+ return ok(`Playbook ${skill.name}.`, { skill: skill.name, text: skill.text });
87
+ const section = Object.keys(skill.sections).find((h) => h.toLowerCase() === args.section?.toLowerCase());
88
+ if (section === undefined) {
89
+ throw new NotFoundError(`guide: playbook "${skill.name}" has no section "${args.section}"`, {
90
+ suggestedAction: `Sections: ${Object.keys(skill.sections).join(', ')}.`,
91
+ });
92
+ }
93
+ return ok(`Playbook ${skill.name}, section ${section}.`, { skill: skill.name, section, text: skill.sections[section] });
94
+ },
95
+ };
96
+ }
97
+ //# sourceMappingURL=guide.js.map
@@ -0,0 +1,9 @@
1
+ import type { ToolContext } from './context/types.js';
2
+ import type { BuiltTool } from './surface.js';
3
+ /**
4
+ * #235: the columns a tickets / time_entries row carries when include_fields is absent. A full row is
5
+ * about 4 KB (107 keys with labels) / 2 KB, so 12 tickets cost 50 KB; these cost about a quarter.
6
+ * output_path (a file, not context) and autotask_read of <resource>.query keep the full row.
7
+ */
8
+ export declare const DEFAULT_COLUMNS: Readonly<Record<string, readonly string[]>>;
9
+ export declare function buildQuery(ctx: ToolContext): BuiltTool;