iit-mcp-autotask 0.63.16 → 0.63.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -799,8 +799,11 @@ guards (rate limiter, 429 cooldown) — a worse security posture, not a safer on
799
799
  quote live tenant metadata (field names, picklist labels), so it is served as untrusted content:
800
800
  embedded wrapper tags dropped, cleaned, secret-scrubbed, capped and wrapped in
801
801
  `<untrusted_content>`; `reasons[].detail` is its first 500 characters, unwrapped. Every other
802
- error message keeps the 200-character bound. An all-digit credential value (the impersonation id)
803
- is scrubbed only on digit boundaries, so it does not match inside a longer number.
802
+ error message keeps the 200-character bound. Every error path strips unsafe characters before it
803
+ scrubs, so a credential value split by an invisible character (U+200B) is still caught (#464). Any
804
+ all-digit credential value (usually the impersonation id) is scrubbed only on digit boundaries, so
805
+ it does not match inside a longer number; standing alone it still replaces the whole message, so a
806
+ short id equal to a listed picklist id (a selector refusal's `29 Label`) redacts that refusal.
804
807
  - **Host allow-list is fail-closed at boot** (see [Per-request credential model](#per-request-credential-model)).
805
808
  - **Sensitive-data-safe structured JSON logging:** NDJSON; stdio → stderr only (stdout is the
806
809
  protocol), http → stdout. Operation keys, status, latency and byte sizes are loggable; credential
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,393 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 1,401 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": 1393,
483
+ "backingRegistryOperations": 1401,
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": {}
package/dist/http.js CHANGED
@@ -24,7 +24,7 @@ import { runDoctor } from './doctor.js';
24
24
  import { SERVER_IDENTITY } from './tools/server.js';
25
25
  import { describeSurface } from './tools/surface.js';
26
26
  import { readRequestScope } from './auth.js';
27
- import { scrubSecrets } from './tools/results/errors.js';
27
+ import { stripThenScrub } from './tools/results/errors.js';
28
28
  import { createMcpGuard, MAX_BODY_BYTES } from './http-guard.js';
29
29
  import { AUTOTASK_BASE_URL_HEADER, AUTOTASK_IMPERSONATION_HEADER, AUTOTASK_INTEGRATION_CODE_HEADER, AUTOTASK_SECRET_HEADER, AUTOTASK_USERNAME_HEADER, } from './auth.js';
30
30
  /** The headers that carry per-request scope, and so must never be read from a duplicated pair. */
@@ -270,7 +270,7 @@ export function startHttpServer(config, mcp, log, tokens, exit = process.exit, e
270
270
  if (typeof v === 'string' && v.length > 0)
271
271
  secrets.push(v);
272
272
  }
273
- log.error('request failed', { err: scrubSecrets(err instanceof Error ? err.message : String(err), secrets) });
273
+ log.error('request failed', { err: stripThenScrub(err instanceof Error ? err.message : String(err), secrets) });
274
274
  if (!res.headersSent) {
275
275
  res.statusCode = 500;
276
276
  res.end('internal error');
@@ -108,7 +108,7 @@ export declare function sdkCacheOptions(cache: 'on' | 'off'): Pick<AutotaskConfi
108
108
  * fails the boot (or the CI test) instead of quietly shipping a tool surface that no longer
109
109
  * describes the SDK behind it.
110
110
  */
111
- export declare const BUILT_AGAINST_PLAN_HASH = "929593354ffa904a038cb7cbbf7b91ffbb05e9f06078181e9f225505f3463a88";
111
+ export declare const BUILT_AGAINST_PLAN_HASH = "911f1470a0ebbe66c39579e8d26d97253914f4fecfe3b8d69ee61bd1710be132";
112
112
  /**
113
113
  * Fail fast when the installed SDK's plan has moved out from under this surface.
114
114
  * Called at boot (main.ts) and safe to call repeatedly (pure comparison).
@@ -190,7 +190,7 @@ export function sdkCacheOptions(cache) {
190
190
  * fails the boot (or the CI test) instead of quietly shipping a tool surface that no longer
191
191
  * describes the SDK behind it.
192
192
  */
193
- export const BUILT_AGAINST_PLAN_HASH = '929593354ffa904a038cb7cbbf7b91ffbb05e9f06078181e9f225505f3463a88';
193
+ export const BUILT_AGAINST_PLAN_HASH = '911f1470a0ebbe66c39579e8d26d97253914f4fecfe3b8d69ee61bd1710be132';
194
194
  /**
195
195
  * Fail fast when the installed SDK's plan has moved out from under this surface.
196
196
  * Called at boot (main.ts) and safe to call repeatedly (pure comparison).
@@ -1,5 +1,5 @@
1
1
  /** SDK client construction (base options, placeholder, stdio client) and the default SDK ops bundle (issue #91). */
2
- import { knowledgeBaseStatusCode } from '../results/errors.js';
2
+ import { statusBasedVendorCode } from '../results/errors.js';
3
3
  import { AutotaskClient } from 'node-autotask';
4
4
  import { invokeDelete, invokeRead, invokeReadPages, invokeWrite, relationshipMap, resolveAny, searchAcrossResources } from 'node-autotask/operations';
5
5
  import { serverCredentialDefaults } from '../../config/load.js';
@@ -59,7 +59,7 @@ export function buildSdkBaseOptions(config, log) {
59
59
  const operation = typeof e.operation === 'string' ? e.operation : undefined;
60
60
  const status = typeof e.status === 'number' ? e.status : undefined;
61
61
  const errorCode = typeof e.errorCode === 'string' && e.errorCode !== 'MAINTENANCE'
62
- ? knowledgeBaseStatusCode(operation, status) ?? e.errorCode
62
+ ? statusBasedVendorCode(operation, status) ?? e.errorCode
63
63
  : e.errorCode === 'MAINTENANCE' ? 'MAINTENANCE' : undefined;
64
64
  log.info('autotask request', {
65
65
  ...(typeof e.correlationId === 'string' ? { correlationId: e.correlationId } : {}),
@@ -17,7 +17,7 @@ import { assertFilterShape, QUERY_LIMIT, QUERY_MAX_ROWS } from './schemas.js';
17
17
  import { RECORDS, toolForOp } from './catalog-data.js';
18
18
  import { AUTOTASK_BASE_PATH } from '../base-hosts.js';
19
19
  import { releaseClientOnError } from './context/derive.js';
20
- import { abortedResult, closedArgsError, errorContent, isKnowledgeBaseRootOperation, refusalContent } from './results/errors.js';
20
+ import { abortedResult, closedArgsError, errorContent, isShapeOnlyVendorOperation, refusalContent } from './results/errors.js';
21
21
  import { crossResourceUntrusted, isFileOperation, markFilePayload, markResult, markServerField } from './results/untrusted.js';
22
22
  import { mirrorEnvelope } from './results/envelope.js';
23
23
  import { assertOperationPermitted } from '../policy.js';
@@ -182,9 +182,10 @@ function annotateCatalogRows(result) {
182
182
  const operation = typeof resource === 'string' ? `${resource}.query` : undefined;
183
183
  const catalogRow = row;
184
184
  catalogRow.queryOperation = operation !== undefined && toolForOp(operation) === 'autotask_query' ? operation : null;
185
- if (isKnowledgeBaseRootOperation(operation) && catalogRow.error != null) {
185
+ if (isShapeOnlyVendorOperation(operation) && catalogRow.error != null) {
186
186
  // The SDK's row error carries vendor text and a code without trusted HTTP status.
187
- catalogRow.error = { code: 'UPSTREAM_ERROR', message: 'Autotask could not provide Knowledge Base metadata.' };
187
+ const message = resource === 'inventory_locations' ? 'Autotask could not provide inventory location metadata.' : 'Autotask could not provide Knowledge Base metadata.';
188
+ catalogRow.error = { code: 'UPSTREAM_ERROR', message };
188
189
  }
189
190
  }
190
191
  }
@@ -26,7 +26,7 @@ import { releaseClientOnError } from './context/derive.js';
26
26
  import {} from './context/types.js';
27
27
  import { abortedAnswer, FIELD_CATALOG_MAX_BYTES, InputInvalidError, readOneItem, requestSecrets } from './dispatch.js';
28
28
  import { zoneClock } from './clock.js';
29
- import { isKnowledgeBaseRootOperation, typedErrorPayload } from './results/errors.js';
29
+ import { isShapeOnlyVendorOperation, typedErrorPayload } from './results/errors.js';
30
30
  import { markResult, sanitiseVendorOutput, UNTRUSTED_TEXT_CAP } from './results/untrusted.js';
31
31
  import { errorEnvelope, ok, TRUNCATION_MARKER } from './results/envelope.js';
32
32
  import { compileBm25 } from './rank.js';
@@ -524,8 +524,8 @@ function staffAttachmentArgs(rec) {
524
524
  ? 'parentId and id each require a positive safe integer JSON number.'
525
525
  : 'parentId requires a positive safe integer JSON number. data is the attachment payload.';
526
526
  }
527
- function knowledgeBaseWriteArgs(rec) {
528
- if (!isKnowledgeBaseRootOperation(rec.id) || !isWriteEffect(rec))
527
+ function operatorWriteArgs(rec) {
528
+ if (!isShapeOnlyVendorOperation(rec.id) || !isWriteEffect(rec))
529
529
  return undefined;
530
530
  const ids = ['parentId', 'id'].filter(key => rec.inputSchema[key] !== undefined);
531
531
  if (ids.length === 0)
@@ -549,7 +549,7 @@ function servedRecord(rec) {
549
549
  if (usage !== undefined && usage !== md?.usage)
550
550
  projected.metadata = { ...md, usage };
551
551
  const staffArgs = staffAttachmentArgs(rec);
552
- const args = staffArgs ?? knowledgeBaseWriteArgs(rec);
552
+ const args = staffArgs ?? operatorWriteArgs(rec);
553
553
  if (args !== undefined) {
554
554
  const schema = { ...rec.inputSchema };
555
555
  for (const key of ['parentId', 'id']) {
@@ -620,7 +620,7 @@ function summariseRecord(ctx, operation, viaTool) {
620
620
  ...(tool !== undefined ? { tool, ...toolServed(ctx, tool) } : {}),
621
621
  purpose: capText(text(md.purpose) || text(row?.purpose), SUMMARY_CAPS.purpose, 'purpose', cut),
622
622
  requiredArgs: row?.requiredArgs ?? [],
623
- args: capText(staffAttachmentArgs(rec) ?? knowledgeBaseWriteArgs(rec) ?? text(md.args), SUMMARY_CAPS.args, 'args', cut),
623
+ args: capText(staffAttachmentArgs(rec) ?? operatorWriteArgs(rec) ?? text(md.args), SUMMARY_CAPS.args, 'args', cut),
624
624
  usage: capText(text(compactUsage(rec, true)), SUMMARY_CAPS.usage, 'usage', cut),
625
625
  reachable: reason === null,
626
626
  why_not: reason,
@@ -72,6 +72,12 @@ export declare function sdkValidationMessage(raw: string, secrets: readonly stri
72
72
  * (security R2).
73
73
  */
74
74
  export declare function scrubSecrets(value: string, secrets: readonly string[]): string;
75
+ /**
76
+ * {@link scrubSecrets} after the unsafe characters are stripped (#464): the choke point strips them later
77
+ * anyway, and a value split by an invisible format character (U+200B) would pass a scrub of the raw text
78
+ * and be rejoined by that strip. Every error path that scrubs vendor or SDK text uses this order.
79
+ */
80
+ export declare function stripThenScrub(value: string, secrets: readonly string[]): string;
75
81
  /**
76
82
  * Bound + scrub the vendor body the SDK carries under `vendorError` (V23/FT-5): the served
77
83
  * envelope is typed-only — never the raw body, never a request's own credential value.
@@ -122,10 +128,11 @@ export declare function vendorShapeDiagnostic(err: unknown, secrets: readonly st
122
128
  */
123
129
  export declare function isAuthFailure(err: unknown): boolean;
124
130
  export declare function isKnowledgeBaseRootOperation(operation: string | undefined): boolean;
131
+ export declare function isShapeOnlyVendorOperation(operation: string | undefined): boolean;
125
132
  /** A vendor failure's canonical status code, also used in transport audit logs. */
126
- export declare function knowledgeBaseStatusCode(operation: string | undefined, status: number | undefined): string | undefined;
133
+ export declare function statusBasedVendorCode(operation: string | undefined, status: number | undefined): string | undefined;
127
134
  /** Strip vendor-supplied codes while preserving trusted SDK envelope and maintenance classifications. */
128
- export declare function knowledgeBaseVendorCode(operation: string | undefined, httpStatus: number | undefined, error: unknown): string | undefined;
135
+ export declare function shapeOnlyVendorCode(operation: string | undefined, httpStatus: number | undefined, error: unknown): string | undefined;
129
136
  /**
130
137
  * Surface the SDK's error contract so the model can correct itself (architecture section 8:
131
138
  * wrap, never flatten). The SDK's fields cross this boundary: `code`, `category`, `retryable`,
@@ -5,7 +5,7 @@ import { unknownKeysRefusal } from 'node-autotask/operations';
5
5
  import { errorEnvelope, TRUNCATION_MARKER } from './envelope.js';
6
6
  import { classifyError } from '../reasons.js';
7
7
  import { UNTRUSTED_CLOSE, UNTRUSTED_OPEN } from 'node-autotask/untrusted';
8
- import { cleanUntrustedText, EVERY_ITEM, LONG_TEXT_CAP, note, wrapOrSelf } from './untrusted.js';
8
+ import { cleanUntrustedText, EVERY_ITEM, LONG_TEXT_CAP, note, stripUnsafeChars, wrapOrSelf } from './untrusted.js';
9
9
  /** Hard cap on the model-facing error text; see {@link boundErrorMessage}. */
10
10
  export const MAX_ERROR_MESSAGE_CHARS = 200;
11
11
  /**
@@ -116,10 +116,30 @@ export function sdkValidationMessage(raw, secrets) {
116
116
  */
117
117
  export function scrubSecrets(value, secrets) {
118
118
  for (const s of secrets)
119
- if (s.length > 0 && carriesSecret(value, s))
120
- return SECRET_MARKER;
119
+ for (const form of secretForms(s))
120
+ if (carriesSecret(value, form))
121
+ return SECRET_MARKER;
121
122
  return value;
122
123
  }
124
+ /**
125
+ * The forms of one credential value a scrub matches: the raw value and, when it differs, the value with
126
+ * the unsafe characters stripped. The credential shape check accepts values that carry such characters
127
+ * (U+00AD, U+200B, U+FE0F, ...), and every error path scrubs text after the strip (#464), so the stripped
128
+ * form is the one an echo takes there. An empty form never matches.
129
+ */
130
+ function secretForms(secret) {
131
+ const stripped = stripUnsafeChars(secret);
132
+ return [secret, ...(stripped !== secret ? [stripped] : [])].filter((f) => f.length > 0);
133
+ }
134
+ /**
135
+ * {@link scrubSecrets} after the unsafe characters are stripped (#464): the choke point strips them later
136
+ * anyway, and a value split by an invisible format character (U+200B) would pass a scrub of the raw text
137
+ * and be rejoined by that strip. Every error path that scrubs vendor or SDK text uses this order.
138
+ */
139
+ export function stripThenScrub(value, secrets) {
140
+ // scrubSecrets matches each secret raw and stripped, so a secret that itself carries an unsafe character is caught too.
141
+ return scrubSecrets(stripUnsafeChars(value), secrets);
142
+ }
123
143
  /**
124
144
  * Whether `value` carries the credential value `secret`. An all-digit value (the impersonation resource
125
145
  * id, often two or three digits) matches only on digit boundaries: inside a longer number (`29` in
@@ -156,11 +176,11 @@ export function boundVendorError(vendorError, secrets) {
156
176
  if (depth > 6)
157
177
  return '[DEPTH]';
158
178
  if (typeof v === 'string') {
159
- const scrubbed = scrubSecrets(v, secrets);
160
- if (scrubbed !== v)
161
- return SECRET_MARKER;
162
- // R5: vendor error text is cleaned like any other vendor text (strip; the per-string cap is the line below)
179
+ // R5: vendor error text is cleaned like any other vendor text (strip; the per-string cap is below),
180
+ // and scrubbed after the strip (#464), so a value split by an invisible character is caught whole.
163
181
  const clean = cleanUntrustedText(v, false);
182
+ if (scrubSecrets(clean, secrets) !== clean)
183
+ return SECRET_MARKER;
164
184
  return clean.length > VENDOR_FIELD_MAX ? `[TRUNCATED ${v.length}]` : clean;
165
185
  }
166
186
  // Each string here is already cleaned, so it is recorded `server`: the choke point keeps a
@@ -247,14 +267,14 @@ export function vendorShapeDiagnostic(err, secrets) {
247
267
  if (details !== null && typeof details === 'object') {
248
268
  const diagnostic = details.diagnostic;
249
269
  if (typeof diagnostic === 'string' && diagnostic.length > 0) {
250
- const scrubbed = scrubSecrets(diagnostic, secrets);
270
+ const scrubbed = stripThenScrub(diagnostic, secrets);
251
271
  // The scrub already replaced an echoed value: the statement is unreadable, so it is ABSENT.
252
- const clean = scrubbed !== diagnostic || isAnomalyFreeDiagnostic(scrubbed);
272
+ const clean = scrubbed === SECRET_MARKER || isAnomalyFreeDiagnostic(scrubbed);
253
273
  return clean ? undefined : scrubbed;
254
274
  }
255
275
  const problem = details.problem;
256
276
  if (typeof problem === 'string' && problem.length > 0) {
257
- return scrubSecrets(`sent value shows shell-quoting/line-break artifacts (${problem}) — check your env load`, secrets);
277
+ return stripThenScrub(`sent value shows shell-quoting/line-break artifacts (${problem}) — check your env load`, secrets);
258
278
  }
259
279
  }
260
280
  for (const value of secrets) {
@@ -285,19 +305,22 @@ export function isAuthFailure(err) {
285
305
  export function isKnowledgeBaseRootOperation(operation) {
286
306
  return operation !== undefined && /^knowledge_base_(articles|categories)\./.test(operation);
287
307
  }
308
+ export function isShapeOnlyVendorOperation(operation) {
309
+ return isKnowledgeBaseRootOperation(operation) || operation?.startsWith('inventory_locations.') === true;
310
+ }
288
311
  /** A vendor failure's canonical status code, also used in transport audit logs. */
289
- export function knowledgeBaseStatusCode(operation, status) {
290
- return isKnowledgeBaseRootOperation(operation) && status !== undefined && status >= 300
312
+ export function statusBasedVendorCode(operation, status) {
313
+ return isShapeOnlyVendorOperation(operation) && status !== undefined && status >= 300
291
314
  ? errorFromStatus(status, undefined).code : undefined;
292
315
  }
293
316
  /** Strip vendor-supplied codes while preserving trusted SDK envelope and maintenance classifications. */
294
- export function knowledgeBaseVendorCode(operation, httpStatus, error) {
317
+ export function shapeOnlyVendorCode(operation, httpStatus, error) {
295
318
  const vendorError = error?.vendorError;
296
- if (!isKnowledgeBaseRootOperation(operation) || (httpStatus === undefined && vendorError === undefined))
319
+ if (!isShapeOnlyVendorOperation(operation) || (httpStatus === undefined && vendorError === undefined))
297
320
  return undefined;
298
321
  if (error instanceof MaintenanceError)
299
322
  return 'MAINTENANCE';
300
- return knowledgeBaseStatusCode(operation, httpStatus)
323
+ return statusBasedVendorCode(operation, httpStatus)
301
324
  ?? (vendorError === undefined && isAutotaskError(error) ? error.code : 'AUTOTASK_ERROR');
302
325
  }
303
326
  /**
@@ -328,7 +351,7 @@ export function typedErrorPayload(err, correlationId, secrets = []) {
328
351
  const bool = (v) => (typeof v === 'boolean' ? v : undefined);
329
352
  const httpStatus = num(e.httpStatus);
330
353
  const operation = str(e.operation);
331
- const vendorCode = knowledgeBaseVendorCode(operation, httpStatus, err);
354
+ const vendorCode = shapeOnlyVendorCode(operation, httpStatus, err);
332
355
  const shapeOnlyVendorError = vendorCode !== undefined;
333
356
  const authFailure = shapeOnlyVendorError
334
357
  ? vendorCode === 'UNAUTHORIZED' || vendorCode === 'FORBIDDEN'
@@ -355,21 +378,23 @@ export function typedErrorPayload(err, correlationId, secrets = []) {
355
378
  // upstream body into err.message by design, and a SHORT body (a credential echo) would
356
379
  // otherwise cross under the 200-char bound. Other client-side errors (no httpStatus) keep the
357
380
  // SDK's own deterministic text (bounded as before).
358
- if (shapeOnlyVendorError && code === 'NOT_FOUND') {
381
+ if (shapeOnlyVendorError && code === 'NOT_FOUND' && (isKnowledgeBaseRootOperation(operation) || operation === 'inventory_locations.get')) {
359
382
  payload.message = operation === 'knowledge_base_articles.get'
360
383
  ? 'No published article was visible to this API user at the requested ID.'
361
- : 'No Knowledge Base record was visible to this API user at the requested ID.';
384
+ : isKnowledgeBaseRootOperation(operation)
385
+ ? 'No Knowledge Base record was visible to this API user at the requested ID.'
386
+ : 'No inventory location was visible to this API user at the requested ID.';
362
387
  }
363
388
  else if (httpStatus !== undefined) {
364
389
  payload.message = shapeMessage(httpStatus, url);
365
390
  }
366
391
  else if (shapeOnlyVendorError) {
367
- payload.message = 'Autotask refused the Knowledge Base operation.';
392
+ payload.message = isKnowledgeBaseRootOperation(operation) ? 'Autotask refused the Knowledge Base operation.' : 'Autotask refused the inventory location operation.';
368
393
  }
369
394
  else {
370
395
  payload.message = sdkValidation
371
396
  ? sdkValidationMessage(err.message, secrets)
372
- : scrubSecrets(rollupBudget ? err.message : boundErrorMessage(err instanceof Error ? err.message : String(err), url), secrets);
397
+ : boundedMessage(err instanceof Error ? err.message : String(err), rollupBudget, url, secrets);
373
398
  }
374
399
  // Untrusted content with the longer cap: recorded `long` so the choke point keeps up to 3,000
375
400
  // characters and the wrapper. `reasons[].detail` is built from this message (unwrapped) by
@@ -379,7 +404,7 @@ export function typedErrorPayload(err, correlationId, secrets = []) {
379
404
  note(payload, 'message', 'long');
380
405
  const suggestedAction = str(e.suggestedAction);
381
406
  if (!shapeOnlyVendorError && suggestedAction !== undefined)
382
- payload.suggestedAction = scrubSecrets(suggestedAction, secrets);
407
+ payload.suggestedAction = stripThenScrub(suggestedAction, secrets);
383
408
  // SDK-built budget guidance contains no vendor text; preserve its complete narrowing options.
384
409
  if (rollupBudget)
385
410
  for (const key of ['message', 'suggestedAction'])
@@ -411,6 +436,20 @@ export function typedErrorPayload(err, correlationId, secrets = []) {
411
436
  payload.correlationId = str(e.correlationId) ?? correlationId;
412
437
  return payload;
413
438
  }
439
+ /**
440
+ * The served message of a client-side error that is not SDK validation text (#464): unsafe characters
441
+ * stripped, then the request's credential values scrubbed on the whole text, then bounded at
442
+ * {@link MAX_ERROR_MESSAGE_CHARS} (last, so a cut can never leave half of a value the scrub would have
443
+ * matched whole). The rollup budget guidance keeps its complete text.
444
+ */
445
+ function boundedMessage(raw, keepWhole, url, secrets) {
446
+ const clean = stripUnsafeChars(raw);
447
+ // Over the cap with a dialed host, the message is the host shape: none of the raw text crosses.
448
+ if (!keepWhole && clean.length > MAX_ERROR_MESSAGE_CHARS && hostFromUrl(url) !== undefined)
449
+ return boundErrorMessage(clean, url);
450
+ const scrubbed = scrubSecrets(clean, secrets);
451
+ return keepWhole || scrubbed === SECRET_MARKER ? scrubbed : boundErrorMessage(scrubbed, url);
452
+ }
414
453
  /** The tool-level error envelope: the typed payload as the text block (the batch's per-item
415
454
  * slot — issue #15 — rides the SAME payload object, so a slot error is exactly what the single
416
455
  * read would have served). */
@@ -26,10 +26,9 @@ interface MissStore<E> {
26
26
  append(entry: E): void;
27
27
  }
28
28
  /**
29
- * Record a FIELD_NOT_PERSISTED miss as a later ledger line (the latest line wins, so a replay
30
- * answers the same reasons). The op lock may be held by a concurrent apply for a moment: wait a
31
- * few short beats for it. Returns false when the lock never freed — the caller says so in its
32
- * answer instead of letting a replay quietly answer plain ok.
29
+ * Record read-back verification as a later ledger line (the latest line wins on replay).
30
+ * Wait briefly for a concurrent apply to release the op lock. Return false if the result
31
+ * could not be recorded.
33
32
  */
34
33
  export declare function recordMiss<E>(store: MissStore<E>, entry: E, attempts?: number, waitMs?: number): Promise<boolean>;
35
34
  /** Build an apply tool (`destructive`: autotask_apply_destructive); human confirmation happens outside the apply lock. */
@@ -13,7 +13,7 @@ import { classifyWriteOutcome, MaintenanceError, MoveRefusedError } from 'node-a
13
13
  import { notPersistedFields } from 'node-autotask/operations';
14
14
  import { stripUntrustedDeep } from 'node-autotask/untrusted';
15
15
  import { InputInvalidError, requestSecrets, readOneItem } from '../dispatch.js';
16
- import { abortedResult, isKnowledgeBaseRootOperation, knowledgeBaseVendorCode, typedErrorPayload } from '../results/errors.js';
16
+ import { abortedResult, isShapeOnlyVendorOperation, shapeOnlyVendorCode, typedErrorPayload } from '../results/errors.js';
17
17
  import {} from '../results/envelope.js';
18
18
  import { ConfigError } from '../../config/schema.js';
19
19
  import { canonicalJson, planHashOf } from '../../write/canonical.js';
@@ -273,7 +273,12 @@ async function send(a, s) {
273
273
  ...base,
274
274
  state: 'succeeded',
275
275
  at: now(),
276
- outcome: createdId === undefined ? {} : { id: createdId },
276
+ outcome: createdId === undefined ? {} : {
277
+ id: createdId,
278
+ ...(['inventory_locations.create', 'inventory_locations.update'].includes(record.id)
279
+ ? { code: 'READBACK_UNVERIFIED' }
280
+ : {}),
281
+ },
277
282
  ...(shape.startsWith('create') && createdId !== undefined
278
283
  ? { created: { resource: record.resource, id: createdId, companyIds: plan.facts.companyIds, principal: plan.principal, tenantId: plan.tenantId } }
279
284
  : {}),
@@ -300,13 +305,15 @@ async function send(a, s) {
300
305
  const classified = classifyWriteOutcome(err);
301
306
  let c = classified;
302
307
  if (err instanceof MaintenanceError) {
303
- // The pinned SDK performs these reads before sending the Knowledge Base mutation.
308
+ // These SDK guard reads happen before the mutation is sent.
304
309
  const articleGuardRead = record.resource === 'knowledge_base_articles'
305
310
  && (err.operation === 'knowledge_base_categories.get' || err.operation === 'knowledge_base_articles.get'
306
311
  || err.operation === 'knowledge_base_articles.getFieldInfo');
307
312
  const categoryMergeRead = record.id === 'knowledge_base_categories.update'
308
313
  && err.operation === 'knowledge_base_categories.get';
309
- if (articleGuardRead || categoryMergeRead) {
314
+ const inventoryLocationGuardRead = record.id === 'inventory_locations.update'
315
+ && err.operation === 'inventory_locations.get';
316
+ if (articleGuardRead || categoryMergeRead || inventoryLocationGuardRead) {
310
317
  c = { ...classified, state: 'failed', retryable: true };
311
318
  }
312
319
  else if (err.notSent !== true && err.httpStatus !== undefined && (err.httpStatus < 200 || err.httpStatus >= 300)) {
@@ -314,9 +321,9 @@ async function send(a, s) {
314
321
  }
315
322
  }
316
323
  // a definite refusal keeps the vendor's first message (capped, sanitised) so a replay or a later investigation can say why
317
- const said = c.state === 'failed' && !c.retryable && !isKnowledgeBaseRootOperation(plan.op)
324
+ const said = c.state === 'failed' && !c.retryable && !isShapeOnlyVendorOperation(plan.op)
318
325
  ? vendorRefusal(err, requestSecrets(ctx)) : undefined;
319
- const code = knowledgeBaseVendorCode(plan.op, c.httpStatus, err) ?? c.code;
326
+ const code = shapeOnlyVendorCode(plan.op, c.httpStatus, err) ?? c.code;
320
327
  entry = { ...base, state: c.state, at: now(), outcome: { code, retryable: c.retryable, ...(c.httpStatus !== undefined ? { httpStatus: c.httpStatus } : {}), ...(said !== undefined ? { vendorMessage: said } : {}) } };
321
328
  }
322
329
  }
@@ -364,10 +371,9 @@ function recordResult(a, entry, confirmation) {
364
371
  /** Waits before each re-read of an update whose first read-back looks stale (#184); tests set it to zeros. */
365
372
  export const READBACK_RECHECK = { delaysMs: [750, 1500] };
366
373
  /**
367
- * Record a FIELD_NOT_PERSISTED miss as a later ledger line (the latest line wins, so a replay
368
- * answers the same reasons). The op lock may be held by a concurrent apply for a moment: wait a
369
- * few short beats for it. Returns false when the lock never freed — the caller says so in its
370
- * answer instead of letting a replay quietly answer plain ok.
374
+ * Record read-back verification as a later ledger line (the latest line wins on replay).
375
+ * Wait briefly for a concurrent apply to release the op lock. Return false if the result
376
+ * could not be recorded.
371
377
  */
372
378
  export async function recordMiss(store, entry, attempts = 10, waitMs = 100) {
373
379
  for (let i = 0; i < attempts; i += 1) {
@@ -385,12 +391,50 @@ export async function recordMiss(store, entry, attempts = 10, waitMs = 100) {
385
391
  }
386
392
  return false;
387
393
  }
394
+ function inventoryLocationMisses(sent, stored, id) {
395
+ if (stored === null || typeof stored !== 'object' || !Object.hasOwn(stored, 'id') || stored.id !== id) {
396
+ throw new Error('Inventory location read-back did not match the expected ID');
397
+ }
398
+ if (sent === null || typeof sent !== 'object')
399
+ return [];
400
+ const submitted = sent;
401
+ const persisted = stored;
402
+ return Object.keys(submitted).filter(field => !Object.hasOwn(persisted, field) || submitted[field] !== persisted[field]);
403
+ }
404
+ async function recordReadBack(a, entry) {
405
+ try {
406
+ if (await recordMiss(a.store, entry))
407
+ return true;
408
+ }
409
+ catch {
410
+ // The read-back is already known even if the ledger write fails.
411
+ }
412
+ a.ctx.log.warn('Write read-back verification could not be recorded in the ledger', { op: a.plan.op });
413
+ return false;
414
+ }
415
+ async function reportPersistedMiss(a, entry, fields, record) {
416
+ const missedEntry = { ...entry, outcome: { ...entry.outcome, code: 'FIELD_NOT_PERSISTED', fields } };
417
+ const recorded = await recordReadBack(a, missedEntry);
418
+ return notPersistedAnswer(a.plan, missedEntry, fields, { replayed: false, record, unrecorded: !recorded });
419
+ }
420
+ async function reportVerifiedReadBack(a, entry, record) {
421
+ const extra = { replayed: false, data: { record: record ?? null } };
422
+ if (entry.outcome?.code !== 'READBACK_UNVERIFIED')
423
+ return outcomeAnswer(a.plan, entry, extra);
424
+ const verified = { ...entry, outcome: { id: entry.outcome.id } };
425
+ const recorded = await recordReadBack(a, verified);
426
+ return outcomeAnswer(a.plan, verified, {
427
+ ...extra,
428
+ ...(recorded ? {} : { summary: 'The write was verified, but verification could not be recorded in the ledger. A replay may still report an unverified result. Do not resend the write.' }),
429
+ });
430
+ }
388
431
  /** Answer from the recorded entry: failures, moves, and the read-backs of creates and updates. */
389
432
  async function respond(a, r) {
390
- const { ctx, store, plan } = a;
433
+ const { ctx, plan } = a;
391
434
  const { record, shape, entry, error, moveResult, callResult } = r;
392
435
  if (entry.state !== 'succeeded') {
393
- const data = error === undefined ? {} : { error: honestError(typedErrorPayload(error, ctx.correlationId, requestSecrets(ctx)), entry) };
436
+ const secrets = requestSecrets(ctx);
437
+ const data = error === undefined ? {} : { error: honestError(typedErrorPayload(error, ctx.correlationId, secrets), entry, secrets) };
394
438
  return outcomeAnswer(plan, entry, { replayed: false, data });
395
439
  }
396
440
  if (shape === 'move')
@@ -409,9 +453,16 @@ async function respond(a, r) {
409
453
  projectRaw = (result) => projectTimeEntryVerification(result, id);
410
454
  }
411
455
  const back = await readOneItem(ctx, `${record.resource}.get`, getIds(ctx, record.resource, plan.targets.parentId, id), undefined, { fresh: true }, projectRaw);
412
- return outcomeAnswer(plan, entry, { replayed: false, data: { record: back.result ?? null } });
456
+ if (entry.outcome.code === 'READBACK_UNVERIFIED') {
457
+ const missed = inventoryLocationMisses(plan.args.at(-1), back.result, id);
458
+ if (missed.length > 0)
459
+ return await reportPersistedMiss(a, entry, missed, back.result);
460
+ }
461
+ return await reportVerifiedReadBack(a, entry, back.result);
413
462
  }
414
463
  catch (err) {
464
+ if (entry.outcome.code === 'READBACK_UNVERIFIED')
465
+ return outcomeAnswer(plan, entry, { replayed: false });
415
466
  const code = String(typedErrorPayload(err, ctx.correlationId).code);
416
467
  return outcomeAnswer(plan, entry, {
417
468
  replayed: false,
@@ -435,8 +486,13 @@ async function respond(a, r) {
435
486
  let back = await readBack();
436
487
  let missed = [];
437
488
  for (let i = 0;; i++) {
438
- const stored = back.result !== null && typeof back.result === 'object' ? stripUntrustedDeep(back.result) : undefined;
439
- missed = stored === undefined || sent === null || typeof sent !== 'object' ? [] : notPersistedFields(sent, stored);
489
+ if (record.id === 'inventory_locations.update') {
490
+ missed = inventoryLocationMisses(sent, back.result, id);
491
+ }
492
+ else {
493
+ const stored = back.result !== null && typeof back.result === 'object' ? stripUntrustedDeep(back.result) : undefined;
494
+ missed = stored === undefined || sent === null || typeof sent !== 'object' ? [] : notPersistedFields(sent, stored);
495
+ }
440
496
  const delay = READBACK_RECHECK.delaysMs[i];
441
497
  if (missed.length === 0 || delay === undefined)
442
498
  break;
@@ -444,15 +500,13 @@ async function respond(a, r) {
444
500
  back = await readBack();
445
501
  }
446
502
  if (missed.length === 0)
447
- return outcomeAnswer(plan, entry, { replayed: false, data: { record: back.result ?? null } });
503
+ return await reportVerifiedReadBack(a, entry, back.result);
448
504
  // record the miss: the latest ledger line wins, so a replay answers the same reasons.
449
- const missedEntry = { ...entry, outcome: { ...entry.outcome, code: 'FIELD_NOT_PERSISTED', fields: missed } };
450
- const recorded = await recordMiss(store, missedEntry);
451
- if (!recorded)
452
- ctx.log.warn('FIELD_NOT_PERSISTED could not be recorded in the ledger (op lock busy)', { op: plan.op });
453
- return notPersistedAnswer(plan, missedEntry, missed, { replayed: false, record: back.result ?? null, unrecorded: !recorded });
505
+ return await reportPersistedMiss(a, entry, missed, back.result ?? null);
454
506
  }
455
507
  catch (err) {
508
+ if (entry.outcome?.code === 'READBACK_UNVERIFIED')
509
+ return outcomeAnswer(plan, entry, { replayed: false });
456
510
  const code = String(typedErrorPayload(err, ctx.correlationId).code);
457
511
  return outcomeAnswer(plan, entry, {
458
512
  replayed: false,
@@ -6,14 +6,19 @@ import { type LedgerEntry, type PlanRecord } from '../../write/store.js';
6
6
  * transient (`retryable: true`, "Retry with backoff"), but a 500 with an errors[] body is a
7
7
  * deterministic business-rule rejection, and an unknown outcome must never be re-sent. Only a
8
8
  * genuinely retryable failure keeps the SDK's hint.
9
+ *
10
+ * `secrets` (#413): the request's own credential values. The typed payload has already bounded and
11
+ * scrubbed these vendor messages; each is stripped and scrubbed again here (strip first, #464), so the
12
+ * advice never depends on how the payload was built.
9
13
  */
10
- export declare function honestError(payload: Record<string, unknown>, entry: LedgerEntry): Record<string, unknown>;
14
+ export declare function honestError(payload: Record<string, unknown>, entry: LedgerEntry, secrets: readonly string[]): Record<string, unknown>;
11
15
  /** The cap on the vendor refusal text a failed ledger line keeps. */
12
16
  export declare const VENDOR_MESSAGE_CAP = 300;
13
17
  /**
14
18
  * The vendor's first errors[] message, as a failed ledger line keeps it so a later investigation
15
- * or replay can say why the write was refused. Untrusted vendor text: request secrets scrubbed,
16
- * unsafe characters stripped, whitespace collapsed to one line, capped at {@link VENDOR_MESSAGE_CAP}.
19
+ * or replay can say why the write was refused. Untrusted vendor text: unsafe characters stripped, then
20
+ * request secrets scrubbed (#464: a value split by an invisible character is caught whole), whitespace
21
+ * collapsed to one line, capped at {@link VENDOR_MESSAGE_CAP}.
17
22
  */
18
23
  export declare function vendorRefusal(err: unknown, secrets: readonly string[]): string | undefined;
19
24
  /** The envelope of an update whose HTTP write succeeded but whose stored record lacks some sent fields (issue #103). */
@@ -1,7 +1,7 @@
1
1
  import { COOLDOWN_MINUTES } from '../../write/store.js';
2
2
  import { answer, applyToolFor, reason } from './common.js';
3
- import { isKnowledgeBaseRootOperation, scrubSecrets } from '../results/errors.js';
4
- import { cleanUntrustedText, stripUnsafeChars } from '../results/untrusted.js';
3
+ import { isShapeOnlyVendorOperation, stripThenScrub } from '../results/errors.js';
4
+ import { cleanUntrustedText } from '../results/untrusted.js';
5
5
  // ---------------------------------------------------------------------------
6
6
  // autotask_apply: the execution
7
7
  // ---------------------------------------------------------------------------
@@ -10,15 +10,18 @@ import { cleanUntrustedText, stripUnsafeChars } from '../results/untrusted.js';
10
10
  * transient (`retryable: true`, "Retry with backoff"), but a 500 with an errors[] body is a
11
11
  * deterministic business-rule rejection, and an unknown outcome must never be re-sent. Only a
12
12
  * genuinely retryable failure keeps the SDK's hint.
13
+ *
14
+ * `secrets` (#413): the request's own credential values. The typed payload has already bounded and
15
+ * scrubbed these vendor messages; each is stripped and scrubbed again here (strip first, #464), so the
16
+ * advice never depends on how the payload was built.
13
17
  */
14
- export function honestError(payload, entry) {
18
+ export function honestError(payload, entry, secrets) {
15
19
  if (entry.outcome?.retryable === true)
16
20
  return { ...payload, nextAction: 'retry' };
17
21
  if (entry.state === 'unknown')
18
22
  return { ...payload, retryable: false, nextAction: 'stop', suggestedAction: 'The write may have landed: read the record to verify; do not re-send.' };
19
- // The typed payload has already bounded and scrubbed these vendor messages.
20
23
  const errors = payload.vendorError?.errors;
21
- const said = Array.isArray(errors) ? errors.filter((e) => typeof e === 'string').slice(0, 3).map((e) => e.slice(0, 200)) : [];
24
+ const said = Array.isArray(errors) ? errors.filter((e) => typeof e === 'string').slice(0, 3).map((e) => stripThenScrub(e, secrets).slice(0, 200)) : [];
22
25
  return { ...payload, retryable: false, nextAction: 'stop', suggestedAction: refusedAction(said.join('; ')) };
23
26
  }
24
27
  /** The nested error's advice for a definite refusal, naming the vendor's text when there is any. */
@@ -30,28 +33,35 @@ function refusedAction(said) {
30
33
  export const VENDOR_MESSAGE_CAP = 300;
31
34
  /**
32
35
  * The vendor's first errors[] message, as a failed ledger line keeps it so a later investigation
33
- * or replay can say why the write was refused. Untrusted vendor text: request secrets scrubbed,
34
- * unsafe characters stripped, whitespace collapsed to one line, capped at {@link VENDOR_MESSAGE_CAP}.
36
+ * or replay can say why the write was refused. Untrusted vendor text: unsafe characters stripped, then
37
+ * request secrets scrubbed (#464: a value split by an invisible character is caught whole), whitespace
38
+ * collapsed to one line, capped at {@link VENDOR_MESSAGE_CAP}.
35
39
  */
36
40
  export function vendorRefusal(err, secrets) {
37
41
  const errors = err?.vendorError?.errors;
38
42
  const first = Array.isArray(errors) ? errors.find((e) => typeof e === 'string' && e.trim() !== '') : undefined;
39
43
  if (first === undefined)
40
44
  return undefined;
41
- const text = stripUnsafeChars(scrubSecrets(first, secrets)).replace(/\s+/g, ' ').trim();
45
+ const text = stripThenScrub(first, secrets).replace(/\s+/g, ' ').trim();
42
46
  return text === '' ? undefined : cleanUntrustedText(text, true, VENDOR_MESSAGE_CAP);
43
47
  }
44
48
  /** The envelope of an update whose HTTP write succeeded but whose stored record lacks some sent fields (issue #103). */
45
49
  export function notPersistedAnswer(plan, entry, fields, extra) {
46
50
  const resource = plan.targets.resource;
47
- return answer('error', 'stop', [reason('FIELD_NOT_PERSISTED', `the vendor accepted the update but did not apply: ${fields.join(', ')}. ${extra.record === undefined ? 'Re-read the record to see what is stored' : 'The stored record is in data.record'}; the field was still unchanged after repeated re-reads, so the vendor appears not to support changing it on ${resource}. Re-read the record once more later before repeating the update.`, fields[0])], {
51
+ const created = plan.facts.shape.startsWith('create');
52
+ const names = fields.join(', ');
53
+ const evidence = extra.record === undefined ? 'Re-read the record to see what is stored' : 'The stored record is in data.record';
54
+ const detail = created
55
+ ? `Autotask created the record, and the read-back differed from the approved values for ${names}. ${evidence}. Review the stored record before making another change.`
56
+ : `the vendor accepted the update but did not apply: ${names}. ${evidence}; the field was still unchanged after repeated re-reads, so the vendor appears not to support changing it on ${resource}. Re-read the record once more later before repeating the update.`;
57
+ return answer('error', 'stop', [reason('FIELD_NOT_PERSISTED', detail, fields[0])], {
48
58
  operation: plan.op,
49
59
  targets: plan.targets,
50
60
  outcome: 'succeeded',
51
61
  result: entry.outcome?.id === undefined ? {} : { id: entry.outcome.id },
52
62
  ...(extra.record === undefined ? {} : { record: extra.record }),
53
63
  notPersisted: fields,
54
- }, { plan: plan.handle, planHash: plan.planHash, ...(extra.replayed ? { replayed: true } : {}), summary: `${plan.op} reached the vendor (HTTP success) but ${fields.join(', ')} did not change.${extra.unrecorded === true ? ' This miss could not be recorded (the state lock was busy): a replay of this plan will answer plain ok, so re-read the record before relying on it.' : ''}` });
64
+ }, { plan: plan.handle, planHash: plan.planHash, ...(extra.replayed ? { replayed: true } : {}), summary: `${plan.op} ${created ? `created the record, and its read-back differed for ${names}.` : `reached the vendor (HTTP success) but ${names} did not change.`}${extra.unrecorded === true ? ' The verification result could not be recorded. Re-read the record before relying on a replay.' : ''}` });
55
65
  }
56
66
  /** The envelope for a recorded (or just recorded) outcome. `result` overrides the ledger id a success reports. */
57
67
  export function outcomeAnswer(plan, entry, extra) {
@@ -60,6 +70,9 @@ export function outcomeAnswer(plan, entry, extra) {
60
70
  if (entry.state === 'succeeded' && entry.outcome?.code === 'FIELD_NOT_PERSISTED' && entry.outcome.fields !== undefined) {
61
71
  return notPersistedAnswer(plan, entry, entry.outcome.fields, { replayed: extra.replayed });
62
72
  }
73
+ if (entry.state === 'succeeded' && entry.outcome?.code === 'READBACK_UNVERIFIED') {
74
+ return answer('error', 'stop', [reason('WRITE_OUTCOME_UNKNOWN', 'Autotask returned a write receipt. Read-back verification is pending or unavailable. Read the record at data.result.id before making another change. Do not resend the write.')], { ...base, result: { id: entry.outcome.id } }, meta);
75
+ }
63
76
  if (entry.state === 'succeeded' && entry.outcome?.sourceId !== undefined) {
64
77
  // a move: old id -> new id (the SDK result is the verification: no extra read-back)
65
78
  const manual = entry.outcome.code === 'MOVE_MANUAL_DELETE';
@@ -95,7 +108,7 @@ export function outcomeAnswer(plan, entry, extra) {
95
108
  },
96
109
  };
97
110
  }
98
- else if (extra.replayed && !retryable && (said !== undefined || isKnowledgeBaseRootOperation(plan.op)) && !('error' in base)) {
111
+ else if (extra.replayed && !retryable && (said !== undefined || isShapeOnlyVendorOperation(plan.op)) && !('error' in base)) {
99
112
  data = { ...base, error: { error: true, code: entry.outcome?.code ?? 'WRITE_FAILED', ...(entry.outcome?.httpStatus !== undefined ? { httpStatus: entry.outcome.httpStatus } : {}), retryable: false, nextAction: 'stop', suggestedAction: refusedAction(said ?? '') } };
100
113
  }
101
114
  const failureCode = forbidden ? 'FORBIDDEN' : entry.outcome?.code ?? 'error';
@@ -29,7 +29,7 @@ export declare function sanitisedArtefact(value: unknown, path: string, depth?:
29
29
  * rules), so this server can never undo a create or a delete.
30
30
  * An update keeps the SDK's answer, including irreversible cancellation.
31
31
  */
32
- export declare function honestImpact(impact: unknown, shape: WriteShape): unknown;
32
+ export declare function honestImpact(impact: unknown, shape: WriteShape, deleteBoundary?: unknown): unknown;
33
33
  /**
34
34
  * Strip control and bidi characters and NFC-normalise every string in a write payload (never
35
35
  * capped). NFC runs after the strip (issue 59): the vendor stores a decomposed accent (an `e` plus
@@ -72,10 +72,13 @@ export function sanitisedArtefact(value, path, depth = 0) {
72
72
  * rules), so this server can never undo a create or a delete.
73
73
  * An update keeps the SDK's answer, including irreversible cancellation.
74
74
  */
75
- export function honestImpact(impact, shape) {
75
+ export function honestImpact(impact, shape, deleteBoundary) {
76
76
  if (impact === null || typeof impact !== 'object' || Array.isArray(impact) || shape.startsWith('update'))
77
77
  return impact;
78
- return { ...impact, reversible: false, reversibleNote: 'This server never runs deletes unattended: undoing it needs a person in Autotask.' };
78
+ const note = deleteBoundary?.note;
79
+ const reversibleNote = shape.startsWith('create') && typeof note === 'string' ? note
80
+ : 'This server never runs deletes unattended: undoing it needs a person in Autotask.';
81
+ return { ...impact, reversible: false, reversibleNote };
79
82
  }
80
83
  /**
81
84
  * Strip control and bidi characters and NFC-normalise every string in a write payload (never
@@ -143,7 +143,7 @@ function describe(record, shape, op, parsed, dry) {
143
143
  const t = parsed.targets;
144
144
  const ids = [t.parentId, t.id, t.toId].filter((v) => v !== undefined);
145
145
  const data = shape === 'call' ? Object.fromEntries(Object.keys(record.inputSchema).map((k, i) => [k, parsed.args[i]])) : dry.data;
146
- const impact = shape === 'call' ? CALL_IMPACT : (honestImpact(dry.impact, shape) ?? { scope: 'single', affected: 1, reversible: !shape.startsWith('delete') });
146
+ const impact = shape === 'call' ? CALL_IMPACT : (honestImpact(dry.impact, shape, record.metadata.deleteBoundary) ?? { scope: 'single', affected: 1, reversible: !shape.startsWith('delete') });
147
147
  const full = { operation: op, target: { resource: t.resource, ids }, request: { method: '', path: '' }, checks: [], warnings: [], simulated: true, ...dry, wouldApply: dry.wouldApply ?? true, impact, data };
148
148
  return describeWrite(full, record);
149
149
  }
@@ -181,7 +181,7 @@ function evaluatePreview(r, a, snap, dry, resource, types) {
181
181
  hazards: decision.hazards,
182
182
  diff: markedDiff(dry.diff, types),
183
183
  warnings: (dry.warnings ?? []).slice(0, 20).map((x) => String(x)),
184
- impact: shape === 'call' ? CALL_IMPACT : honestImpact(dry.impact, shape),
184
+ impact: shape === 'call' ? CALL_IMPACT : honestImpact(dry.impact, shape, record.metadata.deleteBoundary),
185
185
  // #183 AC21: the body a create will send — the SDK-redacted dry-run `data` (never the raw
186
186
  // parsed args: they still carry pre-redaction personal-data values), so a gated create on a
187
187
  // DELETE-less resource confirms the exact body it approves.
@@ -111,7 +111,9 @@ function createReader(ctx, targetKey, signal, operation) {
111
111
  const articleCategory = articleWrite && resource === 'knowledge_base_categories';
112
112
  const knowledgeBaseRecord = (articleWrite && resource === 'knowledge_base_articles')
113
113
  || (resource === 'knowledge_base_categories' && (categoryWrite || articleCategory));
114
- if (knowledgeBaseRecord && (model === null || typeof model !== 'object' || Array.isArray(model)
114
+ const inventoryLocation = operation === 'inventory_locations.update' && resource === 'inventory_locations';
115
+ if ((knowledgeBaseRecord || inventoryLocation) && (model === null || typeof model !== 'object' || Array.isArray(model)
116
+ || (inventoryLocation && !Object.hasOwn(model, 'id'))
115
117
  || asIdOrZero(ci(model, 'id')) !== ids.at(-1))) {
116
118
  throw new SnapshotScopeUnresolved(`${resource}: the fresh record did not establish the requested identity`);
117
119
  }
@@ -20,16 +20,15 @@ export declare function readJsonl<T>(path: string): {
20
20
  /** Rewrite a JSONL file atomically (0600, fsync, rename). */
21
21
  export declare function rewriteJsonl(path: string, rows: unknown[]): void;
22
22
  /**
23
- * One O_APPEND line: open, write, fsync, close (issue #68). The write is a single write(2) of the
24
- * whole line, so a peer's fresh read sees the line whole or not at all; the per-append close is
25
- * what makes the boot-rewrite rename safe for every process (no persistent fd to orphan).
23
+ * Append one checked O_APPEND write under the caller's op lock. Preserve a complete legacy
24
+ * tail even if its newline was lost. The per-append close lets the boot rewrite safely rename.
26
25
  */
27
26
  export declare function appendJsonl(path: string, row: unknown): void;
28
27
  /**
29
28
  * A fresh scan of a JSONL file (issue #68: the file is the single source of truth). Tolerates a
30
- * torn FINAL line (a peer crashed mid-append, or this read raced one): if only the final line
31
- * fails to parse, the file is re-read once, and if it still fails the final line is dropped
32
- * WITHOUT counting it as a bad line (the boot rewrite is the authority that counts bad lines).
29
+ * torn final line (a peer crashed mid-append, or this read raced one). Re-read an invalid final
30
+ * line once and skip it if still bad. Complete JSON without a final newline remains visible
31
+ * because older writers could have acted on the row. The boot rewrite counts bad lines.
33
32
  * A bad line anywhere else is skipped here and counted at the next boot.
34
33
  */
35
34
  export declare function scanJsonl<T>(path: string): T[];
@@ -1,6 +1,6 @@
1
1
  /** Small file helpers: JSONL read/scan/append/rewrite, the state key, the kill file, handles (issue #88). */
2
2
  import { randomBytes } from 'node:crypto';
3
- import { closeSync, existsSync, fsyncSync, openSync, readFileSync, renameSync, statSync, writeSync } from 'node:fs';
3
+ import { closeSync, existsSync, fstatSync, fsyncSync, ftruncateSync, openSync, readFileSync, readSync, renameSync, statSync, writeSync } from 'node:fs';
4
4
  import { ConfigError } from '../../config/schema.js';
5
5
  import { OP_LOCK_POLL_MS } from './constants.js';
6
6
  export const LOOSE_MODE = 0o077;
@@ -69,24 +69,58 @@ export function readJsonl(path) {
69
69
  }
70
70
  return { rows, bad };
71
71
  }
72
+ function writeComplete(fd, text) {
73
+ const bytes = Buffer.from(text);
74
+ if (writeSync(fd, bytes) !== bytes.length)
75
+ throw new Error('Incomplete JSONL write');
76
+ }
72
77
  /** Rewrite a JSONL file atomically (0600, fsync, rename). */
73
78
  export function rewriteJsonl(path, rows) {
74
79
  const tmp = `${path}.tmp`;
75
80
  const fd = openSync(tmp, 'w', 0o600);
76
- writeSync(fd, rows.map((r) => `${JSON.stringify(r)}\n`).join(''));
77
- fsyncSync(fd);
78
- closeSync(fd);
81
+ try {
82
+ writeComplete(fd, rows.map((r) => `${JSON.stringify(r)}\n`).join(''));
83
+ fsyncSync(fd);
84
+ }
85
+ finally {
86
+ closeSync(fd);
87
+ }
79
88
  renameSync(tmp, path);
80
89
  }
81
90
  /**
82
- * One O_APPEND line: open, write, fsync, close (issue #68). The write is a single write(2) of the
83
- * whole line, so a peer's fresh read sees the line whole or not at all; the per-append close is
84
- * what makes the boot-rewrite rename safe for every process (no persistent fd to orphan).
91
+ * Append one checked O_APPEND write under the caller's op lock. Preserve a complete legacy
92
+ * tail even if its newline was lost. The per-append close lets the boot rewrite safely rename.
85
93
  */
86
94
  export function appendJsonl(path, row) {
87
- const fd = openSync(path, 'a', 0o600);
95
+ const line = `${JSON.stringify(row)}\n`;
96
+ const fd = openSync(path, 'a+', 0o600);
88
97
  try {
89
- writeSync(fd, `${JSON.stringify(row)}\n`);
98
+ let { size } = fstatSync(fd);
99
+ let prefix = '';
100
+ if (size > 0) {
101
+ const tail = Buffer.alloc(1);
102
+ if (readSync(fd, tail, 0, 1, size - 1) !== 1)
103
+ throw new Error('Could not read the JSONL tail');
104
+ if (tail[0] !== 0x0a) {
105
+ const contents = readFileSync(path);
106
+ const boundary = contents.lastIndexOf(0x0a) + 1;
107
+ try {
108
+ JSON.parse(contents.subarray(boundary).toString('utf8'));
109
+ prefix = '\n'; // A previous release may have accepted and acted on this complete row.
110
+ }
111
+ catch {
112
+ ftruncateSync(fd, boundary);
113
+ size = boundary;
114
+ }
115
+ }
116
+ }
117
+ try {
118
+ writeComplete(fd, prefix + line);
119
+ }
120
+ catch (err) {
121
+ ftruncateSync(fd, size);
122
+ throw err;
123
+ }
90
124
  fsyncSync(fd);
91
125
  }
92
126
  finally {
@@ -95,9 +129,9 @@ export function appendJsonl(path, row) {
95
129
  }
96
130
  /**
97
131
  * A fresh scan of a JSONL file (issue #68: the file is the single source of truth). Tolerates a
98
- * torn FINAL line (a peer crashed mid-append, or this read raced one): if only the final line
99
- * fails to parse, the file is re-read once, and if it still fails the final line is dropped
100
- * WITHOUT counting it as a bad line (the boot rewrite is the authority that counts bad lines).
132
+ * torn final line (a peer crashed mid-append, or this read raced one). Re-read an invalid final
133
+ * line once and skip it if still bad. Complete JSON without a final newline remains visible
134
+ * because older writers could have acted on the row. The boot rewrite counts bad lines.
101
135
  * A bad line anywhere else is skipped here and counted at the next boot.
102
136
  */
103
137
  export function scanJsonl(path) {
@@ -72,7 +72,7 @@ export function createLedger({ ledgerPath }) {
72
72
  // have changed the file, so a caught error must never expose an older view.
73
73
  rows = undefined;
74
74
  // The stamp is what the boot rewrite reads back: which `sending` lines belong to live
75
- // holders (issue #68). One O_APPEND line: open, write, fsync, close.
75
+ // holders (issue #68). One checked O_APPEND line: open, write, fsync, close.
76
76
  appendJsonl(ledgerPath, { ...entry, boot: BOOT_ID, pid: process.pid });
77
77
  },
78
78
  counters(op, at) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "iit-mcp-autotask",
3
- "version": "0.63.16",
3
+ "version": "0.63.18",
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.86.0",
57
+ "node-autotask": "0.88.1",
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.63.16",
3
+ "version": "0.63.18",
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.86.0"
65
+ "versionRange": "0.88.1"
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"
@@ -28,7 +28,7 @@ Configuration items (CIs) are the assets. Count and group before listing. Values
28
28
  3. Group the same filter: `group_by: ["productID"]` first (or `configurationItemType`, `companyID`), `top: 50`. `groupsTruncated` or `hasMore`: partial, say so. Keys come named (`productIDName`); a `null` name: `products` (`companies`: `companyName`) by `id in`. Type names: `autotask_query {resource: "configuration_item_types", filter: [{field: "id", op: "exist", value: ""}], include_fields: ["id", "name"], limit: 100}`.
29
29
  4. List the same filter: `autotask_query {resource: "configuration_items", filter: <step 2>, include_fields: ["id", "referenceTitle", "serialNumber", "productID", "installDate", "warrantyExpirationDate", "sourceChargeID", "sourceChargeType"], limit: 100}`, plus `companyID` unless it is the scope. Every row: `output_path` (stdio only), not a larger limit.
30
30
  5. Licence terms: `autotask_query {resource: "subscriptions", filter: [{field: "configurationItemID", op: "in", value: "<CI ids>"}], include_fields: ["id", "configurationItemID", "subscriptionName", "effectiveDate", "expirationDate", "purchaseOrderNumber", "status"], limit: 100}`; expiring soon: add `expirationDate` `gte` today and `lte` a date. None there is not "no terms": check the CI's `warrantyExpirationDate`, `domainExpirationDateTime`, `sslValidUntilDateTime`, `userDefinedFields` and `contractServiceID`. Billing products: `configuration_item_billing_product_associations` by `configurationItemID in`.
31
- 6. Purchase date (CIs have none), in order: (a) the subscription `effectiveDate` and `purchaseOrderNumber`; (b) the CI's charge, only when the `sourceChargeType` label names its resource (the SDK has no type map; never guess): `autotask_query {resource: "<contract|project|ticket>_charges", filter: [{field: "id", op: "eq", value: "<sourceChargeID>"}], include_fields: ["datePurchased", "productID", "purchaseOrderNumber"], limit: 1}`; (c) `purchase_order_items` by `productID in` (`orderID`, `productID`, `quantity`), then `purchase_order_item_receiving` by `purchaseOrderItemID in` (`receiveDate`, `serialNumber`): product-level only, unless a receiving `serialNumber` equals the CI serial; (d) else `installDate`, labelled a proxy, never the purchase date.
31
+ 6. Purchase date (CIs have none), in order: (a) the subscription `effectiveDate` and `purchaseOrderNumber`; (b) the CI's charge, only when the `sourceChargeType` label names its resource (the SDK has no type map; never guess): `autotask_query {resource: "<contract|project|ticket>_charges", filter: [{field: "id", op: "eq", value: "<sourceChargeID>"}], include_fields: ["datePurchased", "productID", "purchaseOrderNumber"], limit: 1}`; (c) `purchase_order_items` by `productID in` (`orderID`, `productID`, `quantity`), then `purchase_order_item_receiving` by `purchaseOrderItemID in` (`purchaseOrderItemID`, `receiveDate`, `serialNumber`): product-level only, unless a receiving `serialNumber` equals the CI serial; (d) else `installDate`, labelled a proxy, never the purchase date.
32
32
  7. One item in depth, when served (`records` toolset): `autotask_configuration_item_profile {id: <CI id>}` (a part `unavailable` is a permission gap, not absence).
33
33
 
34
34
  ## Guardrails