iit-mcp-autotask 0.65.1 → 0.66.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/.env.example CHANGED
@@ -57,6 +57,7 @@ AUTOTASK_PROFILE=readonly
57
57
  # unattended or deny (this server asks the person). HTTP: allow or deny only (the MCP client gates).
58
58
  # Grammar, hard rules and dedup: docs/write-gate.md.
59
59
  # AUTOTASK_WRITE=*:deny,tickets.*:allow,time_entries.create:allow,companies.update:deny
60
+ # Any guarded SDK family is served by listing it (for example company_to_dos.*:allow); the account-wide roots also need an all-company run scope.
60
61
  # AUTOTASK_DEDUP=companies.create:companyName
61
62
  # operator: the state dir (mode 0700; plans, ledger, audit, locks; same-version processes on one host may share it).
62
63
  # AUTOTASK_STATE_DIR=/var/lib/autotask-mcp
package/README.md CHANGED
@@ -315,10 +315,31 @@ signal. Keep the rest of the state dir; `audit.jsonl` is the write history.
315
315
 
316
316
  ### Query results: TSV, `output_path` and the saved-file shape
317
317
 
318
- Name and label siblings are enabled by default on SDK-backed reads and the four SDK composites.
319
- A supported per-call `names: false` disables them; composite `max_name_reads` still lowers the SDK name-read budget.
320
-
321
- `autotask_query` always wraps untrusted text and uses the SDK's default transport and labels; `via`, `names`, and `untrusted_wrapper` are refused as unknown inputs.
318
+ Name and label siblings (`<field>Label`, `<id>Name`) are on by default on every read whose SDK operation supports them
319
+ (node-autotask `docs/LABEL-COVERAGE.md` is the coverage inventory). `names: false` is the per-call opt-out and returns raw
320
+ values with no label-only reads; it is a top-level input of:
321
+
322
+ - `autotask_query`: rows, `tsv`, `group_by` keys and `output_path` (a `names` key inside a `*.query` or
323
+ `operations.aggregate` bag sent through `autotask_read` wins over the call's option);
324
+ - `autotask_read`: every read of the call, a single operation or a batch of `items` (`*.get`, `*.resolve`, searches, finders,
325
+ `operations.fetchByIds`, `operations.resolveAny`, `operations.searchAcrossResources`, queries, aggregates);
326
+ - `autotask_resolve`: every branch (exact, contains, fuzzy where it applies, sweep, staff, natural key);
327
+ - the composites `autotask_ticket_full_context`, `autotask_company_full_profile`, `autotask_contact_full_profile`,
328
+ `autotask_contract_full_profile`, `autotask_service_call_full_profile`, `autotask_project_get_context`,
329
+ `autotask_configuration_item_profile`, `autotask_quote_get`, `autotask_resource_workload` and `autotask_invoice_get`
330
+ (record format). `max_name_reads` lowers the name-read budget of the composites whose SDK option bag takes it
331
+ (ticket, company, project, configuration item).
332
+
333
+ `names: true` on an operation that has no label path (counts, metadata, downloads, the invoice exports) is refused by the SDK
334
+ before any request; `names: false` is always a no-op there. Genuinely unsupported (SDK basis, `docs/LABEL-COVERAGE.md`):
335
+ counts and metadata reads, file and export payloads, integration-endpoint results, `companies.searchFuzzy` (a fixed
336
+ four-field projection), and the purpose-built roll-ups (revenue, AR aging, WIP, margin, recurring revenue, non-chargeable
337
+ work), which carry their own pinned label fields. A picklist `*Label` sibling is absent when the tenant's API user cannot read
338
+ the field metadata (the raw value stays); an id with no readable name gets a `null` `*Name`. Both are visibility limits, never
339
+ proof of absence. The server's own snapshot, guard and verification reads (write previews, apply read-backs, the verification
340
+ projections) always send `names: false`, so approved plans and strict outputs stay raw.
341
+
342
+ `autotask_query` always wraps untrusted text and uses the SDK's default transport; `via` and `untrusted_wrapper` are refused as unknown inputs.
322
343
 
323
344
  `autotask_query` answers `data.result` with the SDK's bounded-query envelope:
324
345
 
package/capabilities.json CHANGED
@@ -74,7 +74,7 @@
74
74
  },
75
75
  {
76
76
  "id": "autotask.platform.catalog",
77
- "description": "Find the exact operation key for anything without a dedicated tool: ranked search (q) over the 1,455 registry operations, with effect and whether this deployment serves it. No vendor call.",
77
+ "description": "Find the exact operation key for anything without a dedicated tool: ranked search (q) over the 2,082 registry operations, with effect and whether this deployment serves it. No vendor call.",
78
78
  "mcpPrimitive": "tool",
79
79
  "toolName": "autotask_catalog",
80
80
  "type": "read",
@@ -480,7 +480,7 @@
480
480
  "autotask_describe",
481
481
  "autotask_read"
482
482
  ],
483
- "backingRegistryOperations": 1455,
483
+ "backingRegistryOperations": 2082,
484
484
  "note": "autotask_catalog finds the exact operation key (ranked search), autotask_describe serves its contract, autotask_read runs any effect=read key. Writes go through the operator profile (autotask_write then autotask_apply); authenticate.* is never served."
485
485
  },
486
486
  "schemas": {}
@@ -153,7 +153,7 @@ export async function readBillingReview(ctx, input, signal) {
153
153
  else
154
154
  invalid();
155
155
  // SDK queries are uncached; its fresh option is valid only for primitive get reads.
156
- const result = await readOneItem(ctx, input.operation, args, signal, input.operation === 'time_entries.get' ? { fresh: true } : undefined, project);
156
+ const result = await readOneItem(ctx, input.operation, args, signal, input.operation === 'time_entries.get' ? { fresh: true, names: false } : { names: false }, project); // SDK queries are uncached, so no fresh; labels are never wanted in a verification snapshot
157
157
  if (result.aborted)
158
158
  return abortedAnswer(ctx.correlationId);
159
159
  if (result.scopeNote !== undefined)
@@ -122,7 +122,7 @@ export declare function sdkCacheOptions(cache: 'on' | 'off'): Pick<AutotaskConfi
122
122
  * fails the boot (or the CI test) instead of quietly shipping a tool surface that no longer
123
123
  * describes the SDK behind it.
124
124
  */
125
- export declare const BUILT_AGAINST_PLAN_HASH = "851551c93be98a8eb27a8acf3d7c0e895e3024097150a86f5f9eed6229b1bd32";
125
+ export declare const BUILT_AGAINST_PLAN_HASH = "87f8f8c5b88bdca0067c5a6fc7bcbb854f16a3f0b5bdd23aff0c27d033b37809";
126
126
  /**
127
127
  * Fail fast when the installed SDK's plan has moved out from under this surface.
128
128
  * Called at boot (main.ts) and safe to call repeatedly (pure comparison).
@@ -227,7 +227,7 @@ export function sdkCacheOptions(cache) {
227
227
  * fails the boot (or the CI test) instead of quietly shipping a tool surface that no longer
228
228
  * describes the SDK behind it.
229
229
  */
230
- export const BUILT_AGAINST_PLAN_HASH = '851551c93be98a8eb27a8acf3d7c0e895e3024097150a86f5f9eed6229b1bd32';
230
+ export const BUILT_AGAINST_PLAN_HASH = '87f8f8c5b88bdca0067c5a6fc7bcbb854f16a3f0b5bdd23aff0c27d033b37809';
231
231
  /**
232
232
  * Fail fast when the installed SDK's plan has moved out from under this surface.
233
233
  * Called at boot (main.ts) and safe to call repeatedly (pure comparison).
@@ -18,7 +18,7 @@
18
18
  */
19
19
  import { AutotaskConfigError } from 'node-autotask';
20
20
  import { TICKET_FULL_CONTEXT_INPUT, COMPANY_FULL_PROFILE_INPUT, COMPANY_PROFILE_PART_LIMIT_DEFAULT, CONFIGURATION_ITEM_PROFILE_INPUT, PROJECT_GET_CONTEXT_INPUT, QUOTE_GET_INPUT, INVOICE_GET_INPUT, CONTACT_FULL_PROFILE_INPUT, SERVICE_CALL_FULL_PROFILE_INPUT, CONTRACT_FULL_PROFILE_INPUT, RESOURCE_WORKLOAD_INPUT, closedInput, } from './schemas.js';
21
- import { abortedAnswer } from './dispatch.js';
21
+ import { abortedAnswer, InputInvalidError } from './dispatch.js';
22
22
  import { crossResourceUntrusted, documentCore, markFilePayload, markResult } from './results/untrusted.js';
23
23
  import { ok } from './results/envelope.js';
24
24
  import { resolveOutputTarget } from './output-file.js';
@@ -184,7 +184,7 @@ export function buildProjectGetContext(ctx) {
184
184
  opts: (a) => bagOf([['names', a.names], ['maxNameReads', a.max_name_reads]]),
185
185
  extraParts: async (a, signal) => {
186
186
  const [phases, tasks] = await Promise.all([
187
- projectRowsPart(ctx, 'phases', a.id, { limit: PROJECT_PHASE_CAP, includeFields: PHASE_FIELDS }, signal),
187
+ projectRowsPart(ctx, 'phases', a.id, { limit: PROJECT_PHASE_CAP, includeFields: PHASE_FIELDS, names: a.names }, signal),
188
188
  projectRowsPart(ctx, 'tasks', a.id, { limit: PROJECT_TASK_CAP, includeFields: TASK_FIELDS, names: a.names }, signal),
189
189
  ]);
190
190
  return phases === undefined || tasks === undefined ? undefined : { phases, tasks };
@@ -197,7 +197,7 @@ export function buildQuoteGet(ctx) {
197
197
  operation: 'quotes.withItems',
198
198
  title: 'Get a quote with its line items',
199
199
  input: closedInput(QUOTE_GET_INPUT),
200
- opts: (a) => bagOf([['itemLimit', a.item_limit]]),
200
+ opts: (a) => bagOf([['itemLimit', a.item_limit], ['names', a.names]]),
201
201
  });
202
202
  }
203
203
  // ---- autotask_invoice_get: the invoice record (A1: there is no invoice_items resource) ----
@@ -223,6 +223,8 @@ export function buildInvoiceGet(ctx) {
223
223
  run: async (raw, signal) => {
224
224
  const args = raw;
225
225
  const op = OPS[args.format];
226
+ if (args.names === true && args.format !== 'record')
227
+ throw new InputInvalidError('invoice: names applies to the record format only (the exports carry no labels)', 'names');
226
228
  assertOperationPermitted(op, ctx.record(op), ctx.config, ctx.log);
227
229
  if (args.format === 'record' && args.output_path !== undefined) {
228
230
  throw new AutotaskConfigError('output_path applies to the export formats (html, xml, pdf): the record is a small JSON payload, always served in-band (nothing was dialled, nothing was written)', { operation: op });
@@ -237,7 +239,8 @@ export function buildInvoiceGet(ctx) {
237
239
  relativePath: args.output_path,
238
240
  })
239
241
  : undefined;
240
- const result = await ctx.ops.invokeRead(ctx.client, op, [args.id], undefined, signal);
242
+ // #502: names rides the record read only; the export formats carry no labels (names:true there is refused by the SDK)
243
+ const result = await ctx.ops.invokeRead(ctx.client, op, [args.id], args.names === undefined ? undefined : { names: args.names }, signal);
241
244
  if (result === undefined)
242
245
  return abortedAnswer(ctx.correlationId);
243
246
  if (args.format === 'record') {
@@ -277,7 +280,7 @@ export function buildContactFullProfile(ctx) {
277
280
  operation: 'contacts.fullProfile',
278
281
  title: 'Get a contact with its company and open tickets',
279
282
  input: closedInput(CONTACT_FULL_PROFILE_INPUT),
280
- opts: (a) => bagOf([['ticketLimit', a.ticket_limit]]),
283
+ opts: (a) => bagOf([['ticketLimit', a.ticket_limit], ['names', a.names]]),
281
284
  });
282
285
  }
283
286
  // ---- autotask_service_call_full_profile: the call, its tickets, its tasks, its resource assignments ----
@@ -286,7 +289,7 @@ export function buildServiceCallFullProfile(ctx) {
286
289
  operation: 'service_calls.fullProfile',
287
290
  title: 'Get a service call with its tickets, tasks and resource assignments',
288
291
  input: closedInput(SERVICE_CALL_FULL_PROFILE_INPUT),
289
- opts: (a) => bagOf([['ticketLimit', a.ticket_limit], ['taskLimit', a.task_limit]]),
292
+ opts: (a) => bagOf([['ticketLimit', a.ticket_limit], ['taskLimit', a.task_limit], ['names', a.names]]),
290
293
  });
291
294
  }
292
295
  // ---- autotask_contract_full_profile: the contract, its services, its billing rules,
@@ -296,7 +299,7 @@ export function buildContractFullProfile(ctx) {
296
299
  operation: 'contracts.fullProfile',
297
300
  title: 'Get a contract with its services, billing rules, recent charges and service units',
298
301
  input: closedInput(CONTRACT_FULL_PROFILE_INPUT),
299
- opts: (a) => bagOf([['serviceLimit', a.service_limit], ['billingRuleLimit', a.billing_rule_limit]]),
302
+ opts: (a) => bagOf([['serviceLimit', a.service_limit], ['billingRuleLimit', a.billing_rule_limit], ['names', a.names]]),
300
303
  });
301
304
  }
302
305
  // ---- autotask_resource_workload: the resource, its open work, its balances ----
@@ -305,7 +308,7 @@ export function buildResourceWorkload(ctx) {
305
308
  operation: 'resources.workload',
306
309
  title: 'Get a resource\'s workload: open tickets, assignments, balances, time off',
307
310
  input: closedInput(RESOURCE_WORKLOAD_INPUT),
308
- opts: (a) => bagOf([['ticketLimit', a.ticket_limit], ['taskLimit', a.task_limit], ['timeOffLimit', a.time_off_limit]]),
311
+ opts: (a) => bagOf([['ticketLimit', a.ticket_limit], ['taskLimit', a.task_limit], ['timeOffLimit', a.time_off_limit], ['names', a.names]]),
309
312
  });
310
313
  }
311
314
  //# sourceMappingURL=composites.js.map
@@ -63,10 +63,12 @@ export interface ToolOps {
63
63
  resources?: readonly string[];
64
64
  match?: 'exact' | 'auto';
65
65
  limit?: number;
66
+ names?: boolean;
66
67
  }, signal?: AbortSignal): Promise<unknown>;
67
68
  searchAcrossResources(client: ToolClient, query: string, opts?: {
68
69
  resources?: readonly string[];
69
70
  limit?: number;
71
+ names?: boolean;
70
72
  }, signal?: AbortSignal): Promise<unknown>;
71
73
  /** Zero wire by construction — no signal needed. */
72
74
  relationshipMap(client: ToolClient, resourceKey: string): Promise<unknown>;
@@ -78,7 +78,7 @@ export function buildQuery(ctx) {
78
78
  const clash = ['latest', 'include_fields', 'note_chars', 'format', 'output_path', 'acknowledge_unscoped'].find((k) => args[k] !== undefined);
79
79
  if (clash !== undefined)
80
80
  throw new InputInvalidError(`query: ${clash} lists rows; group_by, sum and count return totals only (pass filter, top and limit)`, clash);
81
- return runAggregate(ctx, operation, args.filter, { groupBy: args.group_by, sum: args.sum, top: args.top, limit: args.limit }, signal, { resource: args.resource });
81
+ return runAggregate(ctx, operation, args.filter, { groupBy: args.group_by, sum: args.sum, top: args.top, limit: args.limit, names: args.names }, signal, { resource: args.resource });
82
82
  }
83
83
  if (args.top !== undefined)
84
84
  throw new InputInvalidError('query: top caps the groups of group_by / sum', 'top');
@@ -104,6 +104,8 @@ export function buildQuery(ctx) {
104
104
  bag.noteChars = args.note_chars;
105
105
  if (args.acknowledge_unscoped !== undefined)
106
106
  bag.acknowledgeUnscoped = args.acknowledge_unscoped;
107
+ if (args.names !== undefined)
108
+ bag.names = args.names;
107
109
  const companies = args.resource === 'documents' ? documentCompanyScope(ctx) : undefined;
108
110
  const rawResult = await ctx.ops.invokeRead(ctx.client, operation, [scopedDocumentQuery(operation, bag, companies)], undefined, signal)
109
111
  .catch((err) => { throw fieldNameInput(scopeRequiredInput(err, 'filter', true), true); });
@@ -232,6 +234,7 @@ async function outputPathAnswer(ctx, resource, operation, noun, fields, args, si
232
234
  walk: { maxRows: OUTPUT_MAX_ROWS },
233
235
  ...(args.include_fields === undefined ? {} : { includeFields: args.include_fields }),
234
236
  ...(args.acknowledge_unscoped === undefined ? {} : { acknowledgeUnscoped: args.acknowledge_unscoped }),
237
+ ...(args.names === undefined ? {} : { names: args.names }),
235
238
  }, companies)], companies === undefined ? consume : page => {
236
239
  verifyDocumentRows(operation, page.items, companies);
237
240
  return consume({ ...page, items: projectDocumentRows(page.items, args.include_fields) });
@@ -785,13 +785,15 @@ export function buildRead(ctx) {
785
785
  }
786
786
  if (args.projection === 'billing_review_entry_v1')
787
787
  return readBillingReview(ctx, args, signal);
788
+ // #502: the per-call label option, forwarded as the invoke-level `names` to every read of this call
789
+ const nameOpts = args.names === undefined ? undefined : { names: args.names };
788
790
  if (args.projection === TICKET_NOTE_VERIFICATION_PROJECTION) {
789
791
  if (args.operation !== 'ticket_notes.get' || args.items !== undefined || args.args.length !== 2 ||
790
792
  args.args.some(id => !Number.isSafeInteger(id) || id <= 0)) {
791
793
  throw new InputInvalidError('ticket note verification requires one ticket_notes.get and positive ticket/note ids', 'projection');
792
794
  }
793
795
  const [ticketId, noteId] = args.args;
794
- const out = await readOneItem(ctx, args.operation, args.args, signal, { fresh: true }, raw => projectTicketNoteVerification(raw, ticketId, noteId));
796
+ const out = await readOneItem(ctx, args.operation, args.args, signal, { fresh: true, names: false }, raw => projectTicketNoteVerification(raw, ticketId, noteId));
795
797
  if (out.aborted)
796
798
  return abortedAnswer(ctx.correlationId);
797
799
  return ok('Fresh TicketNote verification; note text withheld.', out.result);
@@ -800,13 +802,13 @@ export function buildRead(ctx) {
800
802
  if (args.operation !== 'time_entries.get' || args.items !== undefined || args.args.length !== 1 || !Number.isSafeInteger(args.args[0]) || args.args[0] <= 0) {
801
803
  throw new InputInvalidError('verification projection requires one time_entries.get and one positive numeric id', 'projection');
802
804
  }
803
- const out = await readOneItem(ctx, args.operation, args.args, signal, { fresh: true });
805
+ const out = await readOneItem(ctx, args.operation, args.args, signal, { fresh: true, names: false });
804
806
  if (out.aborted)
805
807
  return abortedAnswer(ctx.correlationId);
806
808
  return ok('Fresh time-entry verification snapshot; note bodies withheld.', projectTimeEntryVerification(out.result, args.args[0]));
807
809
  }
808
810
  if (args.operation !== undefined) {
809
- const out = await readOneItem(ctx, args.operation, args.args, signal);
811
+ const out = await readOneItem(ctx, args.operation, args.args, signal, nameOpts);
810
812
  if (out.aborted)
811
813
  return abortedAnswer(ctx.correlationId);
812
814
  // ONE envelope for every read mode (#97): a single read is a one-slot `results`
@@ -821,7 +823,7 @@ export function buildRead(ctx) {
821
823
  let aborted = false;
822
824
  const results = await Promise.all(items.map(async (item) => {
823
825
  try {
824
- const out = await readOneItem(ctx, item.operation, item.args, signal);
826
+ const out = await readOneItem(ctx, item.operation, item.args, signal, nameOpts);
825
827
  if (out.aborted)
826
828
  aborted = true;
827
829
  return { ok: true, operation: item.operation, result: out.result, ...(out.scopeNote !== undefined ? { scopeNote: out.scopeNote } : {}) };
@@ -14,7 +14,11 @@ export declare function safeRef(text: string): string | undefined;
14
14
  /** The human reference of a record of `resource` ({@link safeRef} text), or null when the record carries none. */
15
15
  export declare function refOf(resource: string, record: unknown): string | null;
16
16
  type Expand = boolean | 'full';
17
- /** #225: a record without its `[REDACTED]`, null and empty fields; `expand: "full"` keeps the record as the SDK returned it. */
17
+ /**
18
+ * #225: a record without its `[REDACTED]`, null and empty fields; `expand: "full"` keeps the record as the SDK returned it.
19
+ * #502: a null label sibling (`companyTypeLabel: null`: known value, no name) stays whenever its source value is kept,
20
+ * so "known but unmapped" is told apart from "no label metadata" (sibling absent).
21
+ */
18
22
  export declare function slimRecord(record: unknown, expand: Expand): unknown;
19
23
  /**
20
24
  * A resource outside the six this tool resolves, but with a `<resource>.resolve` read in the registry (company_locations,
@@ -111,11 +111,32 @@ function isEmptyValue(v) {
111
111
  return v.length === 0;
112
112
  return typeof v === 'object' && Object.keys(v).length === 0;
113
113
  }
114
- /** #225: a record without its `[REDACTED]`, null and empty fields; `expand: "full"` keeps the record as the SDK returned it. */
114
+ /**
115
+ * The source key a label sibling belongs to: `<field>Label` (picklist) or `<id>Name` (`companyIDName`), else undefined.
116
+ * Only the SDK's two sibling shapes qualify, so a vendor field such as `companyName` is never read as one.
117
+ */
118
+ function siblingSource(key) {
119
+ if (key.endsWith('Label') && key.length > 5)
120
+ return key.slice(0, -5);
121
+ if (key.endsWith('IDName'))
122
+ return key.slice(0, -4);
123
+ return undefined;
124
+ }
125
+ /**
126
+ * #225: a record without its `[REDACTED]`, null and empty fields; `expand: "full"` keeps the record as the SDK returned it.
127
+ * #502: a null label sibling (`companyTypeLabel: null`: known value, no name) stays whenever its source value is kept,
128
+ * so "known but unmapped" is told apart from "no label metadata" (sibling absent).
129
+ */
115
130
  export function slimRecord(record, expand) {
116
131
  if (expand === 'full' || typeof record !== 'object' || record === null || Array.isArray(record))
117
132
  return record;
118
- return Object.fromEntries(Object.entries(record).filter(([, v]) => !isEmptyValue(v)));
133
+ const rec = record;
134
+ return Object.fromEntries(Object.entries(rec).filter(([k, v]) => {
135
+ if (!isEmptyValue(v))
136
+ return true;
137
+ const source = siblingSource(k);
138
+ return v === null && source !== undefined && !isEmptyValue(rec[source]);
139
+ }));
119
140
  }
120
141
  /** One sweep match: compact by default, the (slim) record under `record` when `expand`. */
121
142
  function matchRow(resource, record, expand) {
@@ -124,9 +145,15 @@ function matchRow(resource, record, expand) {
124
145
  return { resource, ref, record: slimRecord(record, expand) };
125
146
  const rec = asRecord(record);
126
147
  const row = { resource, ref, id: rec.id ?? null };
127
- for (const f of COMPACT_FIELDS[resource] ?? [])
128
- if (rec[f] !== undefined)
129
- row[f] = rec[f];
148
+ for (const f of COMPACT_FIELDS[resource] ?? []) {
149
+ if (rec[f] === undefined)
150
+ continue;
151
+ row[f] = rec[f];
152
+ // #502: the label siblings of a kept field ride along, null included
153
+ for (const sibling of [`${f}Label`, `${f}Name`])
154
+ if (Object.hasOwn(rec, sibling))
155
+ row[sibling] = rec[sibling];
156
+ }
130
157
  return row;
131
158
  }
132
159
  /**
@@ -206,30 +233,34 @@ const how = (match, matched) => (match === 'auto' ? { match: 'auto', matched } :
206
233
  export function buildResolve(ctx) {
207
234
  const input = closedInput(RESOLVE_INPUT, undefined, resolveRefusalHint);
208
235
  const gate = (operation) => assertOperationPermitted(operation, ctx.record(operation), ctx.config, ctx.log);
209
- const ticketRow = (t) => ({ ...matchRow('tickets', t, false), ...(asRecord(t).companyID !== undefined ? { companyID: asRecord(t).companyID } : {}) });
236
+ const ticketRow = (t) => ({ ...matchRow('tickets', t, false), ...(asRecord(t).companyID !== undefined ? { companyID: asRecord(t).companyID, ...(Object.hasOwn(asRecord(t), 'companyIDName') ? { companyIDName: asRecord(t).companyIDName } : {}) } : {}) });
210
237
  return {
211
238
  title: 'Resolve an identifier to an Autotask record',
212
239
  input,
213
240
  run: async (raw, signal) => {
214
241
  const a = raw;
215
242
  validateCombination(a);
243
+ // #502: the per-call label option rides every SDK read as the invoke-level `names` (absent: the client default, labels on)
244
+ const nm = a.names === undefined ? undefined : { names: a.names };
245
+ // companies.searchFuzzy has no label path (SDK coverage inventory): the SDK refuses names:true there, so only the opt-out is sent
246
+ const nmFuzzy = a.names === false ? nm : undefined;
216
247
  /** The contains search of companies (`companies.search`, capped at 10) or tickets (`tickets.search` on title); undefined when aborted. */
217
248
  const searchContains = async (resource) => {
218
249
  if (resource === 'companies') {
219
250
  gate('companies.search');
220
- const found = await ctx.ops.invokeRead(ctx.client, 'companies.search', [String(a.identifier), { limit: Math.min(a.limit, COMPANY_CONTAINS_MAX_LIMIT), includeFamily: a.include_family }], undefined, signal);
251
+ const found = await ctx.ops.invokeRead(ctx.client, 'companies.search', [String(a.identifier), { limit: Math.min(a.limit, COMPANY_CONTAINS_MAX_LIMIT), includeFamily: a.include_family }], nm, signal);
221
252
  return found === undefined ? undefined : Array.isArray(found) ? found : [];
222
253
  }
223
254
  gate('tickets.search');
224
255
  const opts = { limit: a.limit, ...(a.company_id !== undefined ? { companyID: a.company_id } : {}), ...(a.expand ? {} : { includeFields: ['ticketNumber', 'title', 'status', 'assignedResourceID', 'companyID'] }) };
225
- const found = await ctx.ops.invokeRead(ctx.client, 'tickets.search', [String(a.identifier), opts], undefined, signal);
256
+ const found = await ctx.ops.invokeRead(ctx.client, 'tickets.search', [String(a.identifier), opts], nm, signal);
226
257
  return found === undefined ? undefined : Array.isArray(found) ? found : [];
227
258
  };
228
259
  /** Fuzzy rows are suggestions, including a single distance-zero hit; the caller always chooses. */
229
260
  const searchFuzzy = async () => {
230
261
  gate('companies.searchFuzzy');
231
262
  const opts = { limit: Math.min(a.limit, COMPANY_CONTAINS_MAX_LIMIT), includeFamily: a.include_family, includeInactive: a.include_inactive };
232
- const value = await ctx.ops.invokeRead(ctx.client, 'companies.searchFuzzy', [String(a.identifier), opts], undefined, signal);
263
+ const value = await ctx.ops.invokeRead(ctx.client, 'companies.searchFuzzy', [String(a.identifier), opts], nmFuzzy, signal);
233
264
  if (value === undefined)
234
265
  return abortedAnswer(ctx.correlationId);
235
266
  const found = value;
@@ -274,11 +305,11 @@ export function buildResolve(ctx) {
274
305
  };
275
306
  if (a.match === 'contains') {
276
307
  gate('operations.searchAcrossResources');
277
- const value = await ctx.ops.searchAcrossResources(ctx.client, String(a.identifier), { resources, limit: a.limit }, signal);
308
+ const value = await ctx.ops.searchAcrossResources(ctx.client, String(a.identifier), { resources, limit: a.limit, ...nm }, signal);
278
309
  return value === undefined ? abortedAnswer(ctx.correlationId) : renderContains(value);
279
310
  }
280
311
  gate('operations.resolveAny');
281
- const value = await ctx.ops.resolveAny(ctx.client, a.identifier, { resources, match: a.match, limit: a.limit }, signal);
312
+ const value = await ctx.ops.resolveAny(ctx.client, a.identifier, { resources, match: a.match, limit: a.limit, ...nm }, signal);
282
313
  if (value === undefined)
283
314
  return abortedAnswer(ctx.correlationId);
284
315
  const v = value;
@@ -304,7 +335,7 @@ export function buildResolve(ctx) {
304
335
  // ---- staff (#172): one email can match an owner and every API user they own ----
305
336
  if (resource === 'resources') {
306
337
  gate('operations.resolveStaff');
307
- const value = await ctx.ops.invokeRead(ctx.client, 'operations.resolveStaff', [a.identifier, { emailOnly: a.by === 'email', includeApiUsers: a.include_api_users, limit: Math.min(a.limit, 10) }], undefined, signal);
338
+ const value = await ctx.ops.invokeRead(ctx.client, 'operations.resolveStaff', [a.identifier, { emailOnly: a.by === 'email', includeApiUsers: a.include_api_users, limit: Math.min(a.limit, 10), ...nm }], undefined, signal);
308
339
  if (value === undefined)
309
340
  return abortedAnswer(ctx.correlationId);
310
341
  const found = value;
@@ -341,7 +372,7 @@ export function buildResolve(ctx) {
341
372
  const { operation } = BY_KEY[a.by];
342
373
  gate(operation);
343
374
  // A miss is a typed NOT_FOUND from the SDK — runTool maps it to TARGET_NOT_FOUND.
344
- const record = await ctx.ops.invokeRead(ctx.client, operation, [a.identifier], undefined, signal);
375
+ const record = await ctx.ops.invokeRead(ctx.client, operation, [a.identifier], nm, signal);
345
376
  if (record === undefined)
346
377
  return abortedAnswer(ctx.correlationId);
347
378
  if (record === null)
@@ -388,7 +419,7 @@ export function buildResolve(ctx) {
388
419
  gate(operation);
389
420
  try {
390
421
  if (!containsOnly)
391
- record = await ctx.ops.invokeRead(ctx.client, operation, a.expand ? [a.identifier, { expand: true }] : [a.identifier], undefined, signal);
422
+ record = await ctx.ops.invokeRead(ctx.client, operation, a.expand ? [a.identifier, { expand: true }] : [a.identifier], nm, signal);
392
423
  }
393
424
  catch (err) {
394
425
  const e = err;
@@ -316,7 +316,13 @@ export function markReadResult(operation, result) {
316
316
  if (operation.startsWith('inventory_items.') || (operation === 'operations.aggregate' && value.resource === 'inventory_items')) {
317
317
  return markResult(result, INVENTORY_FIELDS);
318
318
  }
319
- const projected = markResult(result, CROSS_RESOURCE_UNTRUSTED);
319
+ // node-autotask 0.102.0 stamps `value` untrusted on the inventory field reads; in the field catalog a picklist
320
+ // `value` is the id a write sends back, so it stays plain there and on every other field-metadata read (its `label`
321
+ // is still wrapped). Only the two inventory resources the SDK stamped keep `value` wrapped.
322
+ const metadataRead = operation === 'operations.fieldCatalog' || /\.(getFieldInfo|getUdfInfo)(ByParent)?$/.test(operation);
323
+ const stampedValue = /^inventory_(item_serial_numbers|stocked_items)\./.test(operation);
324
+ const fields = metadataRead && !stampedValue ? CROSS_RESOURCE_UNTRUSTED.filter((f) => f !== 'value') : CROSS_RESOURCE_UNTRUSTED;
325
+ const projected = markResult(result, fields);
320
326
  if (operation === 'operations.fetchByIds' || operation === 'operations.resolveAny' || operation === 'operations.searchAcrossResources') {
321
327
  const field = operation === 'operations.searchAcrossResources' ? 'matches' : 'value';
322
328
  const results = markInventoryRows(projected.results, field);
@@ -210,6 +210,7 @@ export declare const READ_INPUT: z.ZodPipe<z.ZodObject<{
210
210
  billing_review_entry_v1: "billing_review_entry_v1";
211
211
  ticket_note_verification_v1: "ticket_note_verification_v1";
212
212
  }>>, unknown>;
213
+ names: z.ZodOptional<z.ZodBoolean>;
213
214
  expectedReadRuntime: z.ZodOptional<z.ZodString>;
214
215
  }, z.core.$strip>, z.ZodTransform<{
215
216
  args: unknown[];
@@ -219,6 +220,7 @@ export declare const READ_INPUT: z.ZodPipe<z.ZodObject<{
219
220
  args: unknown[];
220
221
  }[] | undefined;
221
222
  projection?: "default" | "time_entry_verification_v1" | "billing_review_entry_v1" | "ticket_note_verification_v1" | undefined;
223
+ names?: boolean | undefined;
222
224
  expectedReadRuntime?: string | undefined;
223
225
  }, {
224
226
  args: unknown[];
@@ -228,6 +230,7 @@ export declare const READ_INPUT: z.ZodPipe<z.ZodObject<{
228
230
  args: unknown[];
229
231
  }[] | undefined;
230
232
  projection?: "default" | "time_entry_verification_v1" | "billing_review_entry_v1" | "ticket_note_verification_v1" | undefined;
233
+ names?: boolean | undefined;
231
234
  expectedReadRuntime?: string | undefined;
232
235
  }>>;
233
236
  export declare const RESOLVE_INPUT: z.ZodObject<{
@@ -265,6 +268,7 @@ export declare const RESOLVE_INPUT: z.ZodObject<{
265
268
  include_inactive: z.ZodDefault<z.ZodBoolean>;
266
269
  include_api_users: z.ZodDefault<z.ZodBoolean>;
267
270
  limit: z.ZodDefault<z.ZodNumber>;
271
+ names: z.ZodOptional<z.ZodBoolean>;
268
272
  }, z.core.$strip>;
269
273
  export declare const QUERY_INPUT: z.ZodObject<{
270
274
  resource: z.ZodString;
@@ -283,6 +287,7 @@ export declare const QUERY_INPUT: z.ZodObject<{
283
287
  }>>;
284
288
  acknowledge_unscoped: z.ZodOptional<z.ZodBoolean>;
285
289
  output_path: z.ZodOptional<z.ZodString>;
290
+ names: z.ZodOptional<z.ZodBoolean>;
286
291
  }, z.core.$strip>;
287
292
  export declare const TENANT_STATUS_PARTS: readonly ["identity", "version", "thresholds", "server", "time"];
288
293
  export declare const TENANT_STATUS_INPUT: z.ZodObject<{
@@ -419,16 +424,19 @@ export declare const SERVICE_CALL_FULL_PROFILE_INPUT: z.ZodObject<{
419
424
  id: z.ZodNumber;
420
425
  ticket_limit: z.ZodDefault<z.ZodNumber>;
421
426
  task_limit: z.ZodDefault<z.ZodNumber>;
427
+ names: z.ZodDefault<z.ZodBoolean>;
422
428
  }, z.core.$strip>;
423
429
  export declare const RESOURCE_WORKLOAD_INPUT: z.ZodObject<{
424
430
  id: z.ZodNumber;
425
431
  ticket_limit: z.ZodDefault<z.ZodNumber>;
426
432
  task_limit: z.ZodDefault<z.ZodNumber>;
427
433
  time_off_limit: z.ZodDefault<z.ZodNumber>;
434
+ names: z.ZodOptional<z.ZodBoolean>;
428
435
  }, z.core.$strip>;
429
436
  export declare const CONTACT_FULL_PROFILE_INPUT: z.ZodObject<{
430
437
  id: z.ZodNumber;
431
438
  ticket_limit: z.ZodDefault<z.ZodNumber>;
439
+ names: z.ZodDefault<z.ZodBoolean>;
432
440
  }, z.core.$strip>;
433
441
  export declare const CONFIGURATION_ITEM_PROFILE_INPUT: z.ZodObject<{
434
442
  names: z.ZodDefault<z.ZodBoolean>;
@@ -442,10 +450,12 @@ export declare const CONTRACT_FULL_PROFILE_INPUT: z.ZodObject<{
442
450
  id: z.ZodNumber;
443
451
  service_limit: z.ZodDefault<z.ZodNumber>;
444
452
  billing_rule_limit: z.ZodDefault<z.ZodNumber>;
453
+ names: z.ZodDefault<z.ZodBoolean>;
445
454
  }, z.core.$strip>;
446
455
  export declare const QUOTE_GET_INPUT: z.ZodObject<{
447
456
  id: z.ZodNumber;
448
457
  item_limit: z.ZodDefault<z.ZodNumber>;
458
+ names: z.ZodOptional<z.ZodBoolean>;
449
459
  }, z.core.$strip>;
450
460
  export declare const INVOICE_GET_INPUT: z.ZodObject<{
451
461
  id: z.ZodNumber;
@@ -455,6 +465,7 @@ export declare const INVOICE_GET_INPUT: z.ZodObject<{
455
465
  xml: "xml";
456
466
  pdf: "pdf";
457
467
  }>>;
468
+ names: z.ZodOptional<z.ZodBoolean>;
458
469
  output_path: z.ZodOptional<z.ZodString>;
459
470
  }, z.core.$strip>;
460
471
  export declare const WRITE_INPUT: z.ZodObject<{
@@ -239,6 +239,7 @@ export const READ_INPUT = z.object({
239
239
  args: unset(ARGS),
240
240
  items: unset(z.array(READ_ITEM).min(1).max(READ_MAX_ITEMS).optional()).describe('Batch reads in one call, each { operation, args }; use instead of operation.'),
241
241
  projection: unset(z.enum(['default', 'time_entry_verification_v1', 'billing_review_entry_v1', 'ticket_note_verification_v1']).optional()).describe('default: normal read. time_entry_verification_v1: fresh metadata-only get. ticket_note_verification_v1: fresh parent-scoped ticket_notes.get [ticketId,noteId], hashes/counts only. billing_review_entry_v1: fresh ticket-entry get or bounded query (limit<=25, no includeFields); full bounded display notes and raw hashes.'),
242
+ names: z.boolean().optional().describe('false: no labels (default on).'),
242
243
  expectedReadRuntime: z.string().regex(/^[a-f0-9]{64}$/).optional().describe('Require server.readRuntime.sha256 from autotask_tenant_status; changed or unavailable runtime refuses before any vendor dispatch.'),
243
244
  }).transform(v => v.projection === 'billing_review_entry_v1' ? v : numericQueryBag(v));
244
245
  export const RESOLVE_INPUT = z.object({
@@ -253,6 +254,7 @@ export const RESOLVE_INPUT = z.object({
253
254
  include_inactive: z.boolean().default(false).describe('Companies fuzzy/auto: inactive fuzzy candidates too (default false). Exact/contains unchanged.'),
254
255
  include_api_users: z.boolean().default(false).describe('resources only: include API users (default excluded).'),
255
256
  limit: z.number().int().min(1).max(50).default(10).describe('Matches; companies/staff cap 10.'),
257
+ names: z.boolean().optional().describe('false: no labels (default on).'),
256
258
  });
257
259
  export const QUERY_INPUT = z.object({
258
260
  resource: z
@@ -271,6 +273,7 @@ export const QUERY_INPUT = z.object({
271
273
  format: z.enum(['json', 'tsv']).optional().describe('tsv: the table as data.tsv, items omitted.'),
272
274
  acknowledge_unscoped: z.boolean().optional().describe('true walks a large unscoped filter that is otherwise refused.'),
273
275
  output_path: z.string().min(1).optional().describe('stdio only: write all matches to a file (JSON; TSV with format tsv) under AUTOTASK_OUTPUT_DIR, default output/ in AUTOTASK_STATE_DIR. Not with latest or note_chars.'),
276
+ names: z.boolean().optional().describe('Label siblings (<field>Label, <id>Name) are on by default; false returns raw values only.'),
274
277
  });
275
278
  export const TENANT_STATUS_PARTS = ['identity', 'version', 'thresholds', 'server', 'time'];
276
279
  export const TENANT_STATUS_INPUT = z.object({
@@ -280,7 +283,7 @@ export const TENANT_STATUS_INPUT = z.object({
280
283
  * The per-call name options on the four SDK-backed composites; labels default on.
281
284
  */
282
285
  const COMPOSITE_NAME_KEYS = {
283
- names: z.boolean().default(true).describe('Add name labels (default true).'),
286
+ names: z.boolean().default(true).describe('Label siblings (<field>Label, <id>Name) are on by default; false returns raw values only.'),
284
287
  max_name_reads: z.number().int().min(1).optional().describe('Lower the name-read budget.'),
285
288
  };
286
289
  export const TICKET_FULL_CONTEXT_INPUT = z.object({
@@ -388,16 +391,19 @@ export const SERVICE_CALL_FULL_PROFILE_INPUT = z.object({
388
391
  id: ID.describe('Numeric service call id.'),
389
392
  ticket_limit: QUERY_LIMIT,
390
393
  task_limit: QUERY_LIMIT,
394
+ names: COMPOSITE_NAME_KEYS.names, // the SDK composite takes no maxNameReads: one shared name-read budget
391
395
  });
392
396
  export const RESOURCE_WORKLOAD_INPUT = z.object({
393
397
  id: ID.describe('Numeric resource id.'),
394
398
  ticket_limit: QUERY_LIMIT,
395
399
  task_limit: QUERY_LIMIT,
396
400
  time_off_limit: QUERY_LIMIT,
401
+ names: z.boolean().optional().describe('false: no labels.'),
397
402
  });
398
403
  export const CONTACT_FULL_PROFILE_INPUT = z.object({
399
404
  id: ID.describe('Numeric contact id.'),
400
405
  ticket_limit: QUERY_LIMIT,
406
+ names: COMPOSITE_NAME_KEYS.names, // the SDK composite takes no maxNameReads: one shared name-read budget
401
407
  });
402
408
  export const CONFIGURATION_ITEM_PROFILE_INPUT = z.object({
403
409
  id: ID.describe('Numeric configuration item id.'),
@@ -410,14 +416,17 @@ export const CONTRACT_FULL_PROFILE_INPUT = z.object({
410
416
  id: ID.describe('Numeric contract id.'),
411
417
  service_limit: QUERY_LIMIT,
412
418
  billing_rule_limit: QUERY_LIMIT,
419
+ names: COMPOSITE_NAME_KEYS.names, // the SDK composite takes no maxNameReads: one shared name-read budget
413
420
  });
414
421
  export const QUOTE_GET_INPUT = z.object({
415
422
  id: ID.describe('Numeric quote id.'),
416
423
  item_limit: QUERY_LIMIT,
424
+ names: z.boolean().optional().describe('false: no labels.'),
417
425
  });
418
426
  export const INVOICE_GET_INPUT = z.object({
419
427
  id: ID.describe('Numeric invoice id.'),
420
428
  format: z.enum(['record', 'html', 'xml', 'pdf']).default('record').describe('record (default), html, xml or pdf.'),
429
+ names: z.boolean().optional().describe('record only; false: no labels.'),
421
430
  output_path: z
422
431
  .string()
423
432
  .min(1)
@@ -80,6 +80,7 @@ Routing:
80
80
  Filters: [{field, op, value}]; op is ${FILTER_OPS.slice(0, -1).join(', ')} or ${FILTER_OPS.at(-1)}; group with {op: "and"|"or", items: [...]}. Field names are vendor-cased: operations.fieldCatalog args [{resources:[key], fields:[names], labels:true}], not getFieldInfo. A bare object is refused. in/notIn take an array or "1,2,3".
81
81
  Dates: UTC ISO-8601; dateWorked is a YYYY-MM-DD date, never converted.
82
82
  Scope queries by supported IDs. Time entries use ticket.companyID. Unscoped is a tenant-wide walk, refused above ${UNSCOPED_WALK_THRESHOLD} rows unless acknowledge_unscoped (query) or acknowledgeUnscoped (read). Totals: autotask_query group_by/sum (same scope); time: both hoursWorked and hoursToBill.
83
+ Labels (<field>Label, <id>Name) ride supported reads by default; names: false returns raw values.
83
84
  A list miss is not proof of absence: verify by id.${zone}`;
84
85
  }
85
86
  /** The full identity stamp (the `/metadata` build block — the era pair, FR-2). */
@@ -8,6 +8,7 @@ import { documentId, isDocumentOwner } from '../documents.js';
8
8
  import { APPLY_INPUT, APPLY_PARSE, closedInput } from '../schemas.js';
9
9
  import { projectTimeEntryVerification } from '../time-entry-verification.js';
10
10
  import { writeDeps } from './common.js';
11
+ import { storedApproval, withFamilyDispatchCheck } from './sdk-approval.js';
11
12
  import { impersonatedContext, validateImpersonation } from './impersonation.js';
12
13
  import { isImpersonationValidationDenial, releaseClientOnError } from '../context/derive.js';
13
14
  import { gateApply } from '../../access/gate.js';
@@ -368,7 +369,7 @@ async function send(a, s) {
368
369
  // The SDK compares the approved snapshot stamp on its final guarded read.
369
370
  const stamp = snap.lastModifiedDate ?? (shape === 'move' ? ci(snap.current ?? {}, 'lastModifiedDateTime') : undefined);
370
371
  const staleOpts = typeof stamp === 'string' ? { lastModifiedDate: stamp } : {};
371
- const write = () => invoke(ctx.client, plan.op, plan.args, { dryRun: false, ...confirm, ...approvedWriteOptions(snap), ...staleOpts, maxRetries: 0 });
372
+ const write = () => invoke(ctx.client, plan.op, plan.args, { dryRun: false, ...confirm, ...approvedWriteOptions(snap), ...storedApproval(plan.sdkApproval), ...staleOpts, maxRetries: 0 });
372
373
  const check = () => {
373
374
  dispatchBlock = store.blocked();
374
375
  if (documentWrite)
@@ -377,7 +378,8 @@ async function send(a, s) {
377
378
  };
378
379
  const client = ctx.client;
379
380
  const pending = documentWrite ? client.withDocumentMutationDispatchCheck(check, write)
380
- : categoryWrite ? client.withDocumentCategoryMutationDispatchCheck(check, write) : write();
381
+ : categoryWrite ? client.withDocumentCategoryMutationDispatchCheck(check, write)
382
+ : withFamilyDispatchCheck(client, record.resource, check, write) ?? write();
381
383
  const result = await Promise.race([pending, capped]);
382
384
  if (result === 'cap') {
383
385
  entry = { ...base, state: 'unknown', at: now(), outcome: { code: 'APPLY_TIMEOUT' } };
@@ -601,7 +603,7 @@ async function readStrictApply(a, resource, id, sent = a.plan.args.at(-1), owner
601
603
  const ids = resource === 'documents' ? [a.plan.targets.parentId, id] : getIds(a.ctx, resource, a.plan.targets.parentId, id);
602
604
  const exactDecimal = resource !== 'inventory_locations';
603
605
  let missed = [];
604
- const back = await readOneItem(a.ctx, operation, ids, undefined, resource === 'documents' ? undefined : { fresh: true }, exactDecimal
606
+ const back = await readOneItem(a.ctx, operation, ids, undefined, resource === 'documents' ? { names: false } : { fresh: true, names: false }, exactDecimal
605
607
  ? (raw) => {
606
608
  if (resource === 'documents') {
607
609
  const row = raw;
@@ -692,7 +694,7 @@ async function respond(a, r) {
692
694
  throw new InputInvalidError('time entry verification requires a positive numeric created id', 'readBack');
693
695
  projectRaw = (result) => projectTimeEntryVerification(result, id);
694
696
  }
695
- const back = await readOneItem(ctx, `${record.resource}.get`, getIds(ctx, record.resource, plan.targets.parentId, id), undefined, { fresh: true }, projectRaw);
697
+ const back = await readOneItem(ctx, `${record.resource}.get`, getIds(ctx, record.resource, plan.targets.parentId, id), undefined, { fresh: true, names: false }, projectRaw);
696
698
  return await reportVerifiedReadBack(a, entry, back.result);
697
699
  }
698
700
  catch (err) {
@@ -721,7 +723,7 @@ async function respond(a, r) {
721
723
  const readBack = async () => {
722
724
  if (strict)
723
725
  return readStrictApply(a, record.resource, id, r.approvedReplacement, r.documentOwners);
724
- const { result } = await readOneItem(ctx, `${record.resource}.get`, getIds(ctx, record.resource, plan.targets.parentId, id), undefined, { fresh: true });
726
+ const { result } = await readOneItem(ctx, `${record.resource}.get`, getIds(ctx, record.resource, plan.targets.parentId, id), undefined, { fresh: true, names: false });
725
727
  const stored = result !== null && typeof result === 'object' ? stripUntrustedDeep(result) : undefined;
726
728
  const missed = stored === undefined || sent === null || typeof sent !== 'object' ? [] : notPersistedFields(sent, stored);
727
729
  return { result, missed };
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Approval facts for the SDK write families whose previews return none (node-autotask 0.96.0 and later: taxes, tax
3
+ * categories, payment terms, action types, work type modifiers, product notes and tiers, daily availability, role
4
+ * departments, service desk roles, article notes). Their `expected*` options are optional, but without them the SDK
5
+ * only checks the target as it is at send time. Built here from the snapshot's current record (and the few
6
+ * reference reads the SDK's own guard repeats), they bind the apply to the state the preview showed: the SDK refuses
7
+ * STALE_OBJECT, unsent, when any of it changed.
8
+ *
9
+ * A fact that cannot be established exactly (a missing field, a redacted value, an unreadable reference, an
10
+ * ambiguous picklist choice) leaves that write unbound rather than guessing; the SDK's own guard still runs.
11
+ */
12
+ import type { CapabilityRecord } from 'node-autotask/capabilities';
13
+ import type { ToolContext } from '../context/types.js';
14
+ import type { ParsedArgs } from './parse.js';
15
+ type Row = Record<string, unknown>;
16
+ type Built = Record<string, unknown> | undefined;
17
+ /** The `expected*` options binding this write to the state the preview read; undefined for any other op or when a fact cannot be established. */
18
+ export declare function deriveGuardFacts(ctx: ToolContext, record: CapabilityRecord, parsed: ParsedArgs, current: Row | undefined, lastModifiedDate: string | undefined, signal: AbortSignal | undefined): Promise<Built>;
19
+ export {};
@@ -0,0 +1,168 @@
1
+ import { REDACTED_MARKER } from 'node-autotask/untrusted';
2
+ import { assertOperationPermitted } from '../../policy.js';
3
+ import { Cancelled } from './common.js';
4
+ import { readWasAborted } from './concurrent.js';
5
+ const own = (row, key) => (Object.hasOwn(row, key) ? row[key] : undefined);
6
+ const pick = (row, keys) => Object.fromEntries(keys.filter((k) => Object.hasOwn(row, k)).map((k) => [k, row[k]]));
7
+ const isRow = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
8
+ const redacted = (row, keys) => keys.some((k) => row[k] === REDACTED_MARKER);
9
+ /** `{ id, <the family's writable fields present in the record> }`, the shape the SDK's guarded roots capture. */
10
+ const ROOT_FIELDS = {
11
+ 'payment_terms.update': { option: 'expectedPaymentTermFacts', fields: ['name', 'description', 'isActive', 'paymentDueInDays'] },
12
+ 'tax_categories.update': { option: 'expectedTaxCategoryFacts', fields: ['name', 'description', 'isActive'] },
13
+ 'taxes.update': { option: 'expectedTaxFacts', fields: ['taxName', 'taxRate', 'isCompounded', 'taxCategoryID', 'taxRegionID'] },
14
+ };
15
+ const DAILY_FIELDS = ['sundayAvailableHours', 'mondayAvailableHours', 'tuesdayAvailableHours', 'wednesdayAvailableHours', 'thursdayAvailableHours', 'fridayAvailableHours',
16
+ 'saturdayAvailableHours', 'weeklyBillableHoursGoal', 'travelAvailability'];
17
+ const ROLE_DEPARTMENT_FIELDS = ['resourceID', 'roleID', 'departmentID', 'isActive', 'isDefault', 'isDepartmentLead'];
18
+ const SERVICE_DESK_FIELDS = ['resourceID', 'roleID', 'isActive', 'isDefault'];
19
+ const ACTION_TYPE_FIELDS = ['id', 'name', 'view', 'isActive', 'isSystemActionType'];
20
+ /** One reference read behind the deployment's read policy; a failure other than cancellation leaves the fact unestablished. */
21
+ async function readRow(i, operation, args) {
22
+ try {
23
+ assertOperationPermitted(operation, i.ctx.record(operation), i.ctx.config, i.ctx.log);
24
+ const row = await i.ctx.ops.invokeRead(i.ctx.client, operation, args, { fresh: true, names: false }, i.signal);
25
+ if (row === undefined)
26
+ throw new Cancelled();
27
+ return isRow(row) ? row : undefined;
28
+ }
29
+ catch (err) {
30
+ if (err instanceof Cancelled || readWasAborted(err, i.signal))
31
+ throw new Cancelled();
32
+ return undefined;
33
+ }
34
+ }
35
+ /** The one picklist choice of `resource.field` whose value satisfies `match`, from the field catalog; undefined unless exactly one. */
36
+ async function choice(i, resource, field, match) {
37
+ try {
38
+ assertOperationPermitted('operations.fieldCatalog', i.ctx.record('operations.fieldCatalog'), i.ctx.config, i.ctx.log);
39
+ const res = await i.ctx.ops.invokeRead(i.ctx.client, 'operations.fieldCatalog', [{ resources: [resource], fields: [field], labels: true }], undefined, i.signal);
40
+ if (res === undefined)
41
+ throw new Cancelled();
42
+ const fields = res.rows?.find((r) => r.resource === resource)?.fields?.filter((f) => f.name === field);
43
+ const found = fields?.length === 1 ? fields[0].picklistValues?.filter((c) => typeof c.value === 'string' && match(c.value)) : undefined;
44
+ const one = found?.length === 1 ? found[0] : undefined;
45
+ return typeof one?.value === 'string' && typeof one.label === 'string' ? { value: one.value, label: one.label } : undefined;
46
+ }
47
+ catch (err) {
48
+ if (err instanceof Cancelled || readWasAborted(err, i.signal))
49
+ throw new Cancelled();
50
+ return undefined;
51
+ }
52
+ }
53
+ const rootFacts = ({ op, current }) => {
54
+ const spec = ROOT_FIELDS[op];
55
+ if (spec === undefined || current === undefined || !Object.hasOwn(current, spec.fields[0]) || redacted(current, spec.fields))
56
+ return undefined;
57
+ return { [spec.option]: { id: current.id, ...pick(current, spec.fields) } };
58
+ };
59
+ const workTypeModifier = ({ current }) => current === undefined ? undefined : { expectedWorkTypeModifierFacts: { id: current.id, ...pick(current, ['modifierType', 'modifierValue']) } };
60
+ async function actionType(i) {
61
+ const { parsed, current } = i;
62
+ const create = i.op === 'action_types.create';
63
+ const view = parsed.data?.view;
64
+ if (!create && current === undefined)
65
+ return undefined;
66
+ const picked = typeof view === 'number' ? await choice(i, 'action_types', 'view', (v) => Number(v) === view) : undefined;
67
+ if (typeof view === 'number' && picked === undefined)
68
+ return undefined;
69
+ const target = create ? {} : { current: pick(current, ACTION_TYPE_FIELDS) };
70
+ return { expectedActionTypeFacts: { ...target, ...(picked === undefined ? {} : { view: picked }) } };
71
+ }
72
+ const dailyAvailability = ({ current }) => current !== undefined && ['id', 'resourceID', ...DAILY_FIELDS].every((k) => Object.hasOwn(current, k))
73
+ ? { expectedDailyAvailabilityFacts: { current: pick(current, ['id', 'resourceID', ...DAILY_FIELDS]) } } : undefined;
74
+ async function roleDepartment(i) {
75
+ const { parsed, current } = i;
76
+ const parentId = parsed.targets.parentId;
77
+ const data = (parsed.data ?? {});
78
+ const staff = parentId === undefined ? undefined : await readRow(i, 'resources.get', [parentId]);
79
+ if (parentId === undefined || typeof staff?.isActive !== 'boolean')
80
+ return undefined;
81
+ const roleID = data.roleID;
82
+ const role = typeof roleID === 'number' ? await readRow(i, 'roles.get', [roleID]) : undefined;
83
+ if (typeof roleID === 'number' && typeof role?.isActive !== 'boolean')
84
+ return undefined;
85
+ return { expectedRoleDepartmentFacts: {
86
+ resource: { id: parentId, isActive: staff.isActive },
87
+ ...(current === undefined ? {} : { current: pick(current, ['id', ...ROLE_DEPARTMENT_FIELDS]) }),
88
+ ...(typeof roleID === 'number' ? { role: { id: roleID, isActive: role.isActive } } : {}),
89
+ ...(data.departmentID === undefined ? {} : { departmentId: data.departmentID }),
90
+ } };
91
+ }
92
+ async function serviceDeskRole(i) {
93
+ const { parsed, current } = i;
94
+ const parentId = parsed.targets.parentId;
95
+ const roleID = parsed.data?.roleID ?? current?.roleID;
96
+ const staff = parentId === undefined ? undefined : await readRow(i, 'resources.get', [parentId]);
97
+ const role = typeof roleID === 'number' ? await readRow(i, 'roles.get', [roleID]) : undefined;
98
+ if (parentId === undefined || typeof roleID !== 'number' || typeof staff?.isActive !== 'boolean' || typeof role?.isActive !== 'boolean')
99
+ return undefined;
100
+ return { expectedServiceDeskRoleFacts: {
101
+ resource: { id: parentId, isActive: staff.isActive, defaultServiceDeskRoleID: staff.defaultServiceDeskRoleID },
102
+ role: { id: roleID, isActive: role.isActive },
103
+ ...(current === undefined ? {} : { current: pick(current, ['id', ...SERVICE_DESK_FIELDS]) }),
104
+ } };
105
+ }
106
+ async function productNote(i) {
107
+ const { parsed, current } = i;
108
+ const parentId = parsed.targets.parentId;
109
+ if (parentId === undefined)
110
+ return undefined;
111
+ if (i.op === 'product_notes.create') {
112
+ const product = await readRow(i, 'products.get', [parentId]);
113
+ return typeof product?.name === 'string' && product.name !== REDACTED_MARKER ? { expectedProductNoteFacts: { product: { id: parentId, name: product.name } } } : undefined;
114
+ }
115
+ if (current === undefined || redacted(current, ['title', 'description']))
116
+ return undefined;
117
+ return { expectedProductNoteFacts: { note: { id: current.id, productID: parentId, ...pick(current, ['title', 'description']) } } };
118
+ }
119
+ async function productTier(i) {
120
+ const { parsed, current } = i;
121
+ const parentId = parsed.targets.parentId;
122
+ if (parentId === undefined)
123
+ return undefined;
124
+ const product = await readRow(i, 'products.get', [parentId]);
125
+ const method = product?.priceCostMethod;
126
+ if (typeof method !== 'number')
127
+ return undefined;
128
+ const picked = await choice(i, 'products', 'priceCostMethod', (v) => Number(v) === method);
129
+ if (picked === undefined)
130
+ return undefined;
131
+ const create = i.op === 'product_tiers.create';
132
+ if (!create && current === undefined)
133
+ return undefined;
134
+ return { expectedProductTierFacts: {
135
+ productId: parentId, priceCostMethod: method, methodLabel: picked.label,
136
+ ...(create ? {} : { current: pick(current, ['id', 'upToUnitCount', 'unitPrice', 'unitCost']) }),
137
+ } };
138
+ }
139
+ const articleNote = ({ op, current, lastModifiedDate }) => {
140
+ const modifier = current === undefined ? undefined : own(current, 'lastModifiedByResourceID');
141
+ return op !== 'article_notes.create' && typeof modifier === 'number' && lastModifiedDate !== undefined ? { expectedArticleNoteModifierID: modifier } : undefined;
142
+ };
143
+ const BUILDERS = {
144
+ 'payment_terms.update': rootFacts,
145
+ 'tax_categories.update': rootFacts,
146
+ 'taxes.update': rootFacts,
147
+ 'work_type_modifiers.update': workTypeModifier,
148
+ 'action_types.create': actionType,
149
+ 'action_types.update': actionType,
150
+ 'action_types.delete': actionType,
151
+ 'resource_daily_availabilities.update': dailyAvailability,
152
+ 'resource_role_departments.create': roleDepartment,
153
+ 'resource_role_departments.update': roleDepartment,
154
+ 'resource_service_desk_roles.create': serviceDeskRole,
155
+ 'resource_service_desk_roles.update': serviceDeskRole,
156
+ 'product_notes.create': productNote,
157
+ 'product_notes.update': productNote,
158
+ 'product_tiers.create': productTier,
159
+ 'product_tiers.update': productTier,
160
+ 'product_tiers.delete': productTier,
161
+ 'article_notes.update': articleNote,
162
+ 'article_notes.delete': articleNote,
163
+ };
164
+ /** The `expected*` options binding this write to the state the preview read; undefined for any other op or when a fact cannot be established. */
165
+ export async function deriveGuardFacts(ctx, record, parsed, current, lastModifiedDate, signal) {
166
+ return BUILDERS[record.id]?.({ ctx, op: record.id, parsed, current, lastModifiedDate, signal });
167
+ }
168
+ //# sourceMappingURL=guard-facts.js.map
@@ -22,7 +22,7 @@ export async function validateImpersonation(ctx, id, signal) {
22
22
  if (id === undefined)
23
23
  return undefined;
24
24
  assertOperationPermitted('resources.get', ctx.record('resources.get'), ctx.config, ctx.log);
25
- const target = await withImpersonationValidation(ctx, () => ctx.ops.invokeRead(ctx.client, 'resources.get', [id], { fresh: true }, signal));
25
+ const target = await withImpersonationValidation(ctx, () => ctx.ops.invokeRead(ctx.client, 'resources.get', [id], { fresh: true, names: false }, signal));
26
26
  if (cancelled())
27
27
  return abortedResult();
28
28
  if (target !== null && target !== undefined && target.id === id)
@@ -21,6 +21,8 @@ import { unresolvedReason, markedDiff, deriveFacts } from './facts.js';
21
21
  import { UDF_CAPABLE } from '../catalog-data.js';
22
22
  import { udfPreviewWarning } from '../write-guidance.js';
23
23
  import { approverFor } from './apply.js';
24
+ import { approvalFromPreview } from './sdk-approval.js';
25
+ import { deriveGuardFacts } from './guard-facts.js';
24
26
  import { creatorIdentity, impersonatedContext, validateImpersonation } from './impersonation.js';
25
27
  /**
26
28
  * The generic `call` shape has no field-level snapshot (issue #191): no vendor reads establish what the
@@ -46,7 +48,7 @@ async function entryResource(r, a) {
46
48
  return undefined;
47
49
  const roleID = typeof data?.roleID === 'number' ? data.roleID : null;
48
50
  try {
49
- const res = (await r.ctx.ops.invokeRead(r.ctx.client, 'resources.get', [id], { fresh: true }, r.signal));
51
+ const res = (await r.ctx.ops.invokeRead(r.ctx.client, 'resources.get', [id], { fresh: true, names: false }, r.signal));
50
52
  if (res === undefined || res === null)
51
53
  return { id, roleID, name: null };
52
54
  const name = typeof res.name === 'string' ? res.name : [res.firstName, res.lastName].filter((x) => typeof x === 'string' && x !== '').join(' ');
@@ -107,7 +109,7 @@ async function locationWarning(r, a, current) {
107
109
  return undefined; // update on a contact that already has a location
108
110
  try {
109
111
  assertOperationPermitted('company_locations.query', r.ctx.record('company_locations.query'), r.ctx.config, r.ctx.log);
110
- const rows = (await r.ctx.ops.invokeRead(r.ctx.client, 'company_locations.query', [{ filter: [{ field: 'companyID', op: 'eq', value: companyID }, { field: 'isActive', op: 'eq', value: true }], limit: 50 }], undefined, r.signal));
112
+ const rows = (await r.ctx.ops.invokeRead(r.ctx.client, 'company_locations.query', [{ filter: [{ field: 'companyID', op: 'eq', value: companyID }, { field: 'isActive', op: 'eq', value: true }], limit: 50, names: false }], undefined, r.signal));
111
113
  if (rows === undefined)
112
114
  return null; // the SDK answers undefined for a cancelled call
113
115
  const raw = (Array.isArray(rows) ? rows : rows?.items) ?? [];
@@ -148,7 +150,7 @@ function describe(record, shape, op, parsed, dry) {
148
150
  return describeWrite(full, record);
149
151
  }
150
152
  /** The policy decision over the derived facts, its audit row and the preview the answers carry. */
151
- function evaluatePreview(r, a, snap, dry, resource, types) {
153
+ function evaluatePreview(r, a, snap, dry, sdkApproval, resource, types) {
152
154
  const { ctx, w, store, loaded, op, audit } = r;
153
155
  const { record, shape, parsed } = a;
154
156
  const now = w.runtime.now();
@@ -197,13 +199,13 @@ function evaluatePreview(r, a, snap, dry, resource, types) {
197
199
  ...(resource !== undefined ? { resource } : {}),
198
200
  ...(shape === 'move' ? { move: moveSummary(record, parsed.targets, snap.current, dry.data, facts) } : {}),
199
201
  };
200
- return { now, tenantId, facts, decision, planHash, preview, described };
202
+ return { now, tenantId, facts, decision, planHash, preview, described, sdkApproval };
201
203
  }
202
204
  /** The answer for the decision: a denial, or a stored ready plan (`gate`: a person confirms it at apply). */
203
205
  function persist(r, a, e) {
204
206
  const { w, store, loaded, args, op } = r;
205
207
  const { parsed, rule } = a;
206
- const { now, tenantId, facts, decision, planHash, preview, described } = e;
208
+ const { now, tenantId, facts, decision, planHash, preview, described, sdkApproval } = e;
207
209
  if (decision.decision === 'deny')
208
210
  return answer('denied', 'stop', decision.reasons, preview, { planHash });
209
211
  const gate = decision.decision === 'gate';
@@ -220,6 +222,7 @@ function persist(r, a, e) {
220
222
  policyHash: loaded.policyHash,
221
223
  decision: decision.decision,
222
224
  facts,
225
+ ...(sdkApproval !== undefined ? { sdkApproval } : {}),
223
226
  ...(args.reason !== undefined ? { reason: cleanUntrustedText(args.reason, false).slice(0, 200) } : {}),
224
227
  summary: described.headline,
225
228
  lines: described.lines,
@@ -314,11 +317,21 @@ async function execute(ctx, args, signal, ownerTenantId) {
314
317
  }
315
318
  }
316
319
  let dry = { wouldApply: true, warnings: [CALL_WARNING] };
320
+ // The optional SDK binds whose previews return no facts: built from the snapshot, passed to the dry run and stored with the plan.
321
+ let guard;
322
+ try {
323
+ guard = shape === 'call' ? undefined : await deriveGuardFacts(ctx, record, parsed, snap.current, snap.lastModifiedDate, signal);
324
+ }
325
+ catch (err) {
326
+ if (err instanceof Cancelled)
327
+ return abortedResult();
328
+ throw err;
329
+ }
317
330
  if (shape !== 'call') {
318
331
  const confirm = record.effect === 'destructive' || record.flags.includes('requiresApproval') ? { confirm: op } : {};
319
332
  const invoke = record.effect === 'destructive' ? ctx.ops.invokeDelete : ctx.ops.invokeWrite;
320
333
  try {
321
- dry = await invoke(ctx.client, op, parsed.args, { ...confirm, ...approvedWriteOptions(snap) }, signal);
334
+ dry = await invoke(ctx.client, op, parsed.args, { ...confirm, ...approvedWriteOptions(snap), ...guard }, signal);
322
335
  }
323
336
  catch (err) {
324
337
  if (err instanceof StaleObjectError && err.notSent === true
@@ -363,7 +376,7 @@ async function execute(ctx, args, signal, ownerTenantId) {
363
376
  return abortedResult();
364
377
  const udf = shape === 'create' || shape === 'create_child' ? udfPreviewWarning(UDF_CAPABLE.has(record.resource), parsed.data, 'create') : shape === 'update' || shape === 'update_child' ? udfPreviewWarning(UDF_CAPABLE.has(record.resource), parsed.data, 'update') : undefined;
365
378
  const dried = { ...dry, warnings: [...(udf === undefined ? [] : [udf]), ...checked.warn, ...(loc === undefined ? [] : [loc]), ...(dry.warnings ?? [])] };
366
- return persist(r, a, evaluatePreview(r, a, snap, dried, resource, checked.types));
379
+ return persist(r, a, evaluatePreview(r, a, snap, dried, guard === undefined && approvalFromPreview(dry) === undefined ? undefined : { ...guard, ...approvalFromPreview(dry) }, resource, checked.types));
367
380
  }
368
381
  export function buildWrite(ctx) {
369
382
  return { title: 'Preview an Autotask write (changes nothing)', input: closedInput(WRITE_INPUT), run: async (raw, signal) => {
@@ -0,0 +1,25 @@
1
+ /**
2
+ * The SDK's guarded write families (node-autotask 0.96.0 to 0.116.0): a preview (dry run) returns the facts the
3
+ * approval binds, and apply must hand them back unchanged through one `expected*` option, or the SDK refuses before
4
+ * any send. This module carries them from the preview into the stored plan and back, and applies the family's
5
+ * final-send dispatch check. Facts are read only from the SDK's own dry-run result, never from caller input, and
6
+ * never echoed to the client.
7
+ */
8
+ import type { AutotaskClient } from 'node-autotask';
9
+ /** Every option name this module may pass to the SDK (the allow-list a stored plan is filtered by at apply). */
10
+ /** The options `deriveGuardFacts` (guard-facts.ts) builds from the snapshot: the SDK's optional binds whose previews return no facts. */
11
+ export declare const GUARD_FACT_OPTIONS: readonly ["expectedPaymentTermFacts", "expectedTaxCategoryFacts", "expectedTaxFacts", "expectedWorkTypeModifierFacts", "expectedActionTypeFacts", "expectedDailyAvailabilityFacts", "expectedRoleDepartmentFacts", "expectedServiceDeskRoleFacts", "expectedProductNoteFacts", "expectedProductTierFacts", "expectedArticleNoteModifierID"];
12
+ export declare const SDK_APPROVAL_OPTIONS: ReadonlySet<string>;
13
+ /** The approval options a dry-run result carries, by SDK option name; undefined when it carries none. */
14
+ export declare function approvalFromPreview(dry: unknown): Record<string, unknown> | undefined;
15
+ /** The stored approval, restricted to known option names. */
16
+ export declare function storedApproval(stored: unknown): Record<string, unknown>;
17
+ /** Every resource whose writes run inside a family dispatch check: the SDK's guarded write families (0.96.0 and later). */
18
+ export declare const GUARDED_RESOURCES: readonly string[];
19
+ /** The SDK methods this table names (the unit test asserts the table covers every `with*MutationDispatchCheck` on the client). */
20
+ export declare const DISPATCH_SCOPE_METHODS: readonly string[];
21
+ /**
22
+ * Run `write` inside the family's final-send dispatch check, or return undefined when the resource has no such scope
23
+ * (the caller then runs `write` itself). `check` returns false to refuse the send.
24
+ */
25
+ export declare function withFamilyDispatchCheck(client: AutotaskClient, resource: string, check: () => boolean, write: () => Promise<unknown>): Promise<unknown> | undefined;
@@ -0,0 +1,97 @@
1
+ /**
2
+ * The SDK options (INVOKE_OPTION_KEYS) a preview result can feed, keyed by the preview result key that carries the facts.
3
+ * The inventory, document-category and document-owner options are excluded: the snapshot builds those itself.
4
+ */
5
+ const PREVIEW_KEY_TO_OPTION = {
6
+ articleContentRevision: 'expectedArticleContentRevision',
7
+ ticketScope: 'expectedTicketScope',
8
+ ...Object.fromEntries([
9
+ 'articleAssetCategory', 'articleAssociation', 'articleDocumentAssociation', 'articleTag', 'businessHours', 'changeOrderCharge',
10
+ 'clientPortalLocale', 'comanagedAssociation', 'companyCategory', 'companyTeam', 'companyToDo', 'contactBilling', 'documentChild',
11
+ 'ticketRma', 'ticketTag', 'webhookChild', 'webhookErrorLog', 'serviceBundle', 'pricing',
12
+ ].map((family) => [`${family}Facts`, `expected${family[0].toUpperCase()}${family.slice(1)}Facts`])),
13
+ };
14
+ /** Every option name this module may pass to the SDK (the allow-list a stored plan is filtered by at apply). */
15
+ /** The options `deriveGuardFacts` (guard-facts.ts) builds from the snapshot: the SDK's optional binds whose previews return no facts. */
16
+ export const GUARD_FACT_OPTIONS = ['expectedPaymentTermFacts', 'expectedTaxCategoryFacts', 'expectedTaxFacts', 'expectedWorkTypeModifierFacts', 'expectedActionTypeFacts',
17
+ 'expectedDailyAvailabilityFacts', 'expectedRoleDepartmentFacts', 'expectedServiceDeskRoleFacts', 'expectedProductNoteFacts', 'expectedProductTierFacts', 'expectedArticleNoteModifierID'];
18
+ export const SDK_APPROVAL_OPTIONS = new Set([...Object.values(PREVIEW_KEY_TO_OPTION), ...GUARD_FACT_OPTIONS]);
19
+ /** The approval options a dry-run result carries, by SDK option name; undefined when it carries none. */
20
+ export function approvalFromPreview(dry) {
21
+ if (dry === null || typeof dry !== 'object')
22
+ return undefined;
23
+ const found = Object.entries(PREVIEW_KEY_TO_OPTION).filter(([key]) => Object.hasOwn(dry, key) && dry[key] !== undefined);
24
+ return found.length === 0 ? undefined : Object.fromEntries(found.map(([key, option]) => [option, dry[key]]));
25
+ }
26
+ /** The stored approval, restricted to known option names. */
27
+ export function storedApproval(stored) {
28
+ if (stored === null || typeof stored !== 'object')
29
+ return {};
30
+ return Object.fromEntries(Object.entries(stored).filter(([option]) => SDK_APPROVAL_OPTIONS.has(option)));
31
+ }
32
+ /** resource -> client method (`with<Name>MutationDispatchCheck`) for the families whose check takes (check, fn). */
33
+ const SCOPES = {
34
+ action_types: 'ActionType',
35
+ article_attachments: 'ArticleAttachment',
36
+ article_configuration_item_category_associations: 'ArticleConfigurationItemCategoryAssociation',
37
+ article_notes: 'ArticleNote',
38
+ article_plain_text_content: 'ArticlePlainTextContent',
39
+ article_tag_associations: 'ArticleTagAssociation',
40
+ article_ticket_associations: 'ArticleTicketAssociation',
41
+ article_to_article_associations: 'ArticleToArticleAssociation',
42
+ article_to_document_associations: 'ArticleToDocumentAssociation',
43
+ change_order_charges: 'ChangeOrderCharge',
44
+ client_portal_users: 'ClientPortalUser',
45
+ comanaged_associations: 'ComanagedAssociation',
46
+ company_categories: 'CompanyCategory',
47
+ company_teams: 'CompanyTeam',
48
+ company_to_dos: 'CompanyToDo',
49
+ contact_billing_product_associations: 'ContactBillingProductAssociation',
50
+ internal_location_with_business_hours: 'InternalLocationWithBusinessHours',
51
+ payment_terms: 'PaymentTerm',
52
+ product_notes: 'ProductNote',
53
+ product_tiers: 'ProductTier',
54
+ resource_daily_availabilities: 'ResourceDailyAvailability',
55
+ resource_role_departments: 'ResourceRoleDepartment',
56
+ resource_service_desk_roles: 'ResourceServiceDeskRole',
57
+ tax_categories: 'TaxCategory',
58
+ taxes: 'Tax',
59
+ ticket_rma_credits: 'TicketRmaCredit',
60
+ ticket_tag_associations: 'TicketTagAssociation',
61
+ webhook_event_error_logs: 'WebhookEventErrorLog',
62
+ work_type_modifiers: 'WorkTypeModifier',
63
+ // node-autotask 0.115.0 (the lookups below are optional-chained, so an older SDK simply has no check to run)
64
+ service_bundles: 'ServiceBundle',
65
+ service_bundle_services: 'ServiceBundleService',
66
+ price_list_product_tiers: 'PriceListProductTier',
67
+ price_list_service_bundles: 'PriceListServiceBundle',
68
+ // node-autotask 0.116.0
69
+ price_list_products: 'PriceListProduct',
70
+ price_list_material_codes: 'PriceListMaterialCode',
71
+ price_list_roles: 'PriceListRole',
72
+ price_list_services: 'PriceListService',
73
+ price_list_work_type_modifiers: 'PriceListWorkTypeModifier',
74
+ };
75
+ const DOCUMENT_CHILDREN = new Set(['document_notes', 'document_attachments', 'document_checklist_items', 'document_configuration_item_associations',
76
+ 'document_configuration_item_category_associations', 'document_ticket_associations', 'document_to_document_associations', 'document_tag_associations', 'document_to_article_associations']);
77
+ const WEBHOOK_CHILDREN = new Set(['company', 'contact', 'configuration_item', 'ticket'].flatMap((p) => ['fields', 'udf_fields', 'excluded_resources'].map((c) => `${p}_webhook_${c}`))
78
+ .concat(['ticket_note_webhook_fields', 'ticket_note_webhook_excluded_resources']));
79
+ const isWebhookChild = (resource) => WEBHOOK_CHILDREN.has(resource);
80
+ /** Every resource whose writes run inside a family dispatch check: the SDK's guarded write families (0.96.0 and later). */
81
+ export const GUARDED_RESOURCES = [...Object.keys(SCOPES), ...DOCUMENT_CHILDREN, ...WEBHOOK_CHILDREN];
82
+ /** The SDK methods this table names (the unit test asserts the table covers every `with*MutationDispatchCheck` on the client). */
83
+ export const DISPATCH_SCOPE_METHODS = [...Object.values(SCOPES).map((n) => `with${n}MutationDispatchCheck`), 'withDocumentChildMutationDispatchCheck', 'withWebhookChildMutationDispatchCheck'];
84
+ /**
85
+ * Run `write` inside the family's final-send dispatch check, or return undefined when the resource has no such scope
86
+ * (the caller then runs `write` itself). `check` returns false to refuse the send.
87
+ */
88
+ export function withFamilyDispatchCheck(client, resource, check, write) {
89
+ const c = client;
90
+ if (DOCUMENT_CHILDREN.has(resource))
91
+ return c.withDocumentChildMutationDispatchCheck?.(resource, check, write);
92
+ if (isWebhookChild(resource))
93
+ return c.withWebhookChildMutationDispatchCheck?.(resource, check, write);
94
+ const name = SCOPES[resource];
95
+ return name === undefined ? undefined : c[`with${name}MutationDispatchCheck`]?.(check, write);
96
+ }
97
+ //# sourceMappingURL=sdk-approval.js.map
@@ -108,7 +108,7 @@ async function takeDocumentSnapshot(ctx, record, parsed, duplicateFields, signal
108
108
  if (parent === undefined || parentId === undefined)
109
109
  return reason('TARGET_NOT_IN_SCOPE', 'Could not establish the DocumentCategories route.');
110
110
  const read = async (operation, args) => {
111
- const row = await ctx.ops.invokeRead(ctx.client, operation, args, operation.endsWith('.get') ? { fresh: true } : undefined, signal);
111
+ const row = await ctx.ops.invokeRead(ctx.client, operation, args, operation.endsWith('.get') ? { fresh: true, names: false } : { names: false }, signal);
112
112
  if (row === undefined)
113
113
  throw new Cancelled();
114
114
  return row;
@@ -289,7 +289,7 @@ function createReader(ctx, targetKey, signal, operation) {
289
289
  let request = pending.get(key);
290
290
  if (request === undefined) {
291
291
  request = (async () => {
292
- const v = await ctx.ops.invokeRead(ctx.client, `${resource}.get`, ids, { fresh: true }, signal);
292
+ const v = await ctx.ops.invokeRead(ctx.client, `${resource}.get`, ids, { fresh: true, names: false }, signal);
293
293
  if (v === undefined)
294
294
  throw new Cancelled();
295
295
  const model = v;
@@ -534,7 +534,7 @@ export async function takeCallSnapshot(ctx, record, parsed, signal) {
534
534
  if (!simple && ctx.record(`${record.resource}.query`) !== undefined) {
535
535
  // a parent-scoped get needs a parent the arguments do not name (a contact's companyID): read the
536
536
  // row by id, as the move path does, and let the row's own references anchor it
537
- const found = await ctx.ops.invokeRead(ctx.client, `${record.resource}.query`, [{ filter: [{ field: 'id', op: 'eq', value: selfId }], limit: 1 }], undefined, signal);
537
+ const found = await ctx.ops.invokeRead(ctx.client, `${record.resource}.query`, [{ filter: [{ field: 'id', op: 'eq', value: selfId }], limit: 1 }], { names: false }, signal);
538
538
  if (found === undefined)
539
539
  throw new Cancelled();
540
540
  const row = (found.items ?? [])[0];
@@ -667,7 +667,7 @@ export async function takeSnapshot(ctx, record, parsed, duplicateFields, signal,
667
667
  if (targets.toId !== undefined && !hasSimpleGet(record.resource, ctx)) {
668
668
  // a move's source whose get is parent-scoped (a ticket charge): read it by id, as the SDK does; its ticketID anchors it
669
669
  const key = `${record.resource}:${targets.id}`;
670
- const found = await ctx.ops.invokeRead(ctx.client, `${record.resource}.query`, [{ filter: [{ field: 'id', op: 'eq', value: targets.id }], limit: 1 }], undefined, signal);
670
+ const found = await ctx.ops.invokeRead(ctx.client, `${record.resource}.query`, [{ filter: [{ field: 'id', op: 'eq', value: targets.id }], limit: 1 }], { names: false }, signal);
671
671
  if (found === undefined)
672
672
  throw new Cancelled();
673
673
  const row = (found.items ?? [])[0];
@@ -706,6 +706,12 @@ export async function takeSnapshot(ctx, record, parsed, duplicateFields, signal,
706
706
  }
707
707
  lastModifiedDate = stamp;
708
708
  }
709
+ // The SDK compares an article note's supplied revision (and, below, its approved modifier) before an update or delete.
710
+ if (record.resource === 'article_notes' && record.id !== 'article_notes.create') {
711
+ const stamp = ci(current, 'lastModifiedDateTime');
712
+ if (typeof stamp === 'string' && stamp.length > 0)
713
+ lastModifiedDate = stamp;
714
+ }
709
715
  // The note's independent locator lookup below supplies its authoritative asset.
710
716
  await anchor(record.resource, current, 0, false, !independentNoteAttachment);
711
717
  }
@@ -851,7 +857,7 @@ export async function takeSnapshot(ctx, record, parsed, duplicateFields, signal,
851
857
  filter.push({ field: parent.field, op: 'eq', value: targets.parentId });
852
858
  const categoryCreate = record.id === 'document_categories.create';
853
859
  // A single match is conclusive. A later page failure cannot erase it.
854
- const found = await ctx.ops.invokeRead(ctx.client, `${record.resource}.query`, [{ filter, limit: categoryCreate ? 1 : 5 }], undefined, signal);
860
+ const found = await ctx.ops.invokeRead(ctx.client, `${record.resource}.query`, [{ filter, limit: categoryCreate ? 1 : 5 }], { names: false }, signal);
855
861
  if (found === undefined)
856
862
  throw new Cancelled();
857
863
  const page = found;
@@ -24,6 +24,8 @@ export interface PlanRecord {
24
24
  /** `allow`: executable now. `gate`: executes only once a person confirms it at apply. */
25
25
  decision: 'allow' | 'gate';
26
26
  facts: WriteFacts;
27
+ /** The SDK approval options a guarded family's preview returned (node-autotask 0.96+), handed back unchanged at apply. Never served to a client. */
28
+ sdkApproval?: Record<string, unknown>;
27
29
  reason?: string;
28
30
  /** #301: the SDK's `describeWrite` rendering at preview: `summary` (its headline) is the echo apply checks. */
29
31
  summary: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "iit-mcp-autotask",
3
- "version": "0.65.1",
3
+ "version": "0.66.0",
4
4
  "description": "MCP server for the Autotask (Datto) PSA domain, built on the node-autotask SDK",
5
5
  "license": "MIT",
6
6
  "author": "Max Soukhomlinov",
@@ -54,7 +54,7 @@
54
54
  },
55
55
  "dependencies": {
56
56
  "@modelcontextprotocol/server": "^2.2.0",
57
- "node-autotask": "0.95.0",
57
+ "node-autotask": "0.116.0",
58
58
  "zod": "^4.6.7"
59
59
  },
60
60
  "devDependencies": {
package/server.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "iit-mcp-autotask",
3
- "version": "0.65.1",
3
+ "version": "0.66.0",
4
4
  "description": "MCP server for the Autotask (Datto) PSA API, powered by the node-autotask SDK",
5
5
  "mcpProtocolBaseline": "2026-07-28",
6
6
  "legacyProtocolFallback": "2025-11-25",
@@ -62,7 +62,7 @@
62
62
  "capabilitiesManifest": "capabilities.json",
63
63
  "sdk": {
64
64
  "package": "node-autotask",
65
- "versionRange": "0.95.0"
65
+ "versionRange": "0.116.0"
66
66
  },
67
67
  "vendorExtensions": false,
68
68
  "credentialModelNote": "per-request; server-held under stdio or, on HTTP, only behind AUTOTASK_HTTP_AUTH=tokens; operator plans and the ledger are keyed by principal and tenant id, never by credential, and an apply authenticates the request credential and restores the plan's per-write impersonation"
@@ -26,7 +26,7 @@ No inputs: this is a reference page about autotask_query read cost, not a proced
26
26
  1. Name the columns you need on autotask_query: include_fields: ["id", "dateWorked", "hoursWorked", "hoursToBill", "summaryNotes"] (exact vendor casing; id is always included). Summarising time, report both hours: hoursWorked is the time worked, hoursToBill the billable quantity (it can differ).
27
27
  2. Cap free text: note_chars: 200 truncates each free-text field (internalNotes, summaryNotes, description) with a marker.
28
28
  3. Need status or priority names? autotask_read operations.fieldCatalog with resources: [key] and fields: [names] returns picklist labels by default on this server (labels: false opts out); without fields the rows are compact and carry no picklist values: resolve codes once, no second call.
29
- 4. Need names for company, resource or ticket ids, or status labels? They come on autotask_query rows by default (companyIDName, statusLabel) and cannot be switched off there (autotask_query has no names input). The names: false opt-out belongs to the args[0] bag of a *.query run through autotask_read and to the composites' names input.
29
+ 4. Need names for company, resource or ticket ids, or status labels? They come on every label-capable read by default (companyIDName, statusLabel, companyTypeLabel). Pass names: false to autotask_query, autotask_read, autotask_resolve or a composite for raw values only (no label reads); a names key in the args[0] bag of a *.query or operations.aggregate read wins.
30
30
  5. A *.query run through autotask_read defaults limit to 50 when absent (an explicit limit is honoured); add include_fields (as includeFields) and noteChars in its args[0] bag to slim it. Breaking since the unified read envelope (#97): the answer is `data.results[0].result`, no longer `data.result`.
31
31
 
32
32
  ## Guardrails