iit-mcp-autotask 0.54.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (164) hide show
  1. package/.env.example +123 -0
  2. package/LICENSE +21 -0
  3. package/README.md +788 -0
  4. package/capabilities.json +487 -0
  5. package/dist/access/gate.d.ts +34 -0
  6. package/dist/access/gate.js +76 -0
  7. package/dist/access/grants.d.ts +20 -0
  8. package/dist/access/grants.js +35 -0
  9. package/dist/access/write-env.d.ts +41 -0
  10. package/dist/access/write-env.js +166 -0
  11. package/dist/auth.d.ts +74 -0
  12. package/dist/auth.js +129 -0
  13. package/dist/base-hosts.d.ts +38 -0
  14. package/dist/base-hosts.js +70 -0
  15. package/dist/config/load.d.ts +28 -0
  16. package/dist/config/load.js +105 -0
  17. package/dist/config/schema.d.ts +166 -0
  18. package/dist/config/schema.js +311 -0
  19. package/dist/credential.d.ts +28 -0
  20. package/dist/credential.js +32 -0
  21. package/dist/doctor.d.ts +112 -0
  22. package/dist/doctor.js +154 -0
  23. package/dist/http-guard.d.ts +57 -0
  24. package/dist/http-guard.js +134 -0
  25. package/dist/http.d.ts +50 -0
  26. package/dist/http.js +290 -0
  27. package/dist/lifecycle.d.ts +29 -0
  28. package/dist/lifecycle.js +52 -0
  29. package/dist/logger.d.ts +26 -0
  30. package/dist/logger.js +28 -0
  31. package/dist/main.d.ts +12 -0
  32. package/dist/main.js +283 -0
  33. package/dist/policy.d.ts +54 -0
  34. package/dist/policy.js +80 -0
  35. package/dist/tools/aggregate.d.ts +16 -0
  36. package/dist/tools/aggregate.js +64 -0
  37. package/dist/tools/capabilities-manifest.d.ts +4 -0
  38. package/dist/tools/capabilities-manifest.js +94 -0
  39. package/dist/tools/catalog-data.d.ts +116 -0
  40. package/dist/tools/catalog-data.js +207 -0
  41. package/dist/tools/clock.d.ts +17 -0
  42. package/dist/tools/clock.js +43 -0
  43. package/dist/tools/composites.d.ts +36 -0
  44. package/dist/tools/composites.js +305 -0
  45. package/dist/tools/context/client.d.ts +41 -0
  46. package/dist/tools/context/client.js +139 -0
  47. package/dist/tools/context/derive.d.ts +9 -0
  48. package/dist/tools/context/derive.js +32 -0
  49. package/dist/tools/context/scope.d.ts +24 -0
  50. package/dist/tools/context/scope.js +180 -0
  51. package/dist/tools/context/types.d.ts +141 -0
  52. package/dist/tools/context/types.js +2 -0
  53. package/dist/tools/dispatch.d.ts +78 -0
  54. package/dist/tools/dispatch.js +272 -0
  55. package/dist/tools/field-pointer.d.ts +25 -0
  56. package/dist/tools/field-pointer.js +45 -0
  57. package/dist/tools/guide.d.ts +30 -0
  58. package/dist/tools/guide.js +97 -0
  59. package/dist/tools/lists.d.ts +9 -0
  60. package/dist/tools/lists.js +205 -0
  61. package/dist/tools/meta.d.ts +22 -0
  62. package/dist/tools/meta.js +709 -0
  63. package/dist/tools/output-file.d.ts +26 -0
  64. package/dist/tools/output-file.js +140 -0
  65. package/dist/tools/rank.d.ts +21 -0
  66. package/dist/tools/rank.js +57 -0
  67. package/dist/tools/reasons.d.ts +33 -0
  68. package/dist/tools/reasons.js +121 -0
  69. package/dist/tools/register.d.ts +23 -0
  70. package/dist/tools/register.js +50 -0
  71. package/dist/tools/resolves.d.ts +28 -0
  72. package/dist/tools/resolves.js +399 -0
  73. package/dist/tools/results/envelope.d.ts +55 -0
  74. package/dist/tools/results/envelope.js +63 -0
  75. package/dist/tools/results/errors.d.ts +147 -0
  76. package/dist/tools/results/errors.js +384 -0
  77. package/dist/tools/results/untrusted.d.ts +129 -0
  78. package/dist/tools/results/untrusted.js +218 -0
  79. package/dist/tools/revenue-rollup.d.ts +8 -0
  80. package/dist/tools/revenue-rollup.js +112 -0
  81. package/dist/tools/schemas.d.ts +467 -0
  82. package/dist/tools/schemas.js +444 -0
  83. package/dist/tools/scope-guard.d.ts +2 -0
  84. package/dist/tools/scope-guard.js +11 -0
  85. package/dist/tools/server-version.d.ts +3 -0
  86. package/dist/tools/server-version.js +14 -0
  87. package/dist/tools/server.d.ts +92 -0
  88. package/dist/tools/server.js +170 -0
  89. package/dist/tools/surface.d.ts +37 -0
  90. package/dist/tools/surface.js +94 -0
  91. package/dist/tools/tsv.d.ts +52 -0
  92. package/dist/tools/tsv.js +95 -0
  93. package/dist/tools/write/apply.d.ts +40 -0
  94. package/dist/tools/write/apply.js +500 -0
  95. package/dist/tools/write/checks.d.ts +39 -0
  96. package/dist/tools/write/checks.js +137 -0
  97. package/dist/tools/write/common.d.ts +23 -0
  98. package/dist/tools/write/common.js +33 -0
  99. package/dist/tools/write/facts.d.ts +52 -0
  100. package/dist/tools/write/facts.js +151 -0
  101. package/dist/tools/write/outcome.d.ts +23 -0
  102. package/dist/tools/write/outcome.js +67 -0
  103. package/dist/tools/write/parse.d.ts +37 -0
  104. package/dist/tools/write/parse.js +166 -0
  105. package/dist/tools/write/payload.d.ts +44 -0
  106. package/dist/tools/write/payload.js +119 -0
  107. package/dist/tools/write/preview.d.ts +3 -0
  108. package/dist/tools/write/preview.js +317 -0
  109. package/dist/tools/write/snapshot.d.ts +68 -0
  110. package/dist/tools/write/snapshot.js +360 -0
  111. package/dist/tools/write-guidance.d.ts +174 -0
  112. package/dist/tools/write-guidance.js +317 -0
  113. package/dist/tools/write.d.ts +9 -0
  114. package/dist/tools/write.js +10 -0
  115. package/dist/write/canonical.d.ts +12 -0
  116. package/dist/write/canonical.js +31 -0
  117. package/dist/write/evaluate.d.ts +77 -0
  118. package/dist/write/evaluate.js +91 -0
  119. package/dist/write/hard-rules.d.ts +49 -0
  120. package/dist/write/hard-rules.js +48 -0
  121. package/dist/write/runtime.d.ts +37 -0
  122. package/dist/write/runtime.js +72 -0
  123. package/dist/write/store/audit-log.d.ts +13 -0
  124. package/dist/write/store/audit-log.js +25 -0
  125. package/dist/write/store/constants.d.ts +34 -0
  126. package/dist/write/store/constants.js +35 -0
  127. package/dist/write/store/files.d.ts +44 -0
  128. package/dist/write/store/files.js +157 -0
  129. package/dist/write/store/heartbeat.d.ts +9 -0
  130. package/dist/write/store/heartbeat.js +65 -0
  131. package/dist/write/store/ledger.d.ts +15 -0
  132. package/dist/write/store/ledger.js +86 -0
  133. package/dist/write/store/lifecycle.d.ts +35 -0
  134. package/dist/write/store/lifecycle.js +114 -0
  135. package/dist/write/store/lock.d.ts +97 -0
  136. package/dist/write/store/lock.js +464 -0
  137. package/dist/write/store/op-lock.d.ts +13 -0
  138. package/dist/write/store/op-lock.js +175 -0
  139. package/dist/write/store/plan-store.d.ts +7 -0
  140. package/dist/write/store/plan-store.js +48 -0
  141. package/dist/write/store/plans.d.ts +5 -0
  142. package/dist/write/store/plans.js +19 -0
  143. package/dist/write/store/types.d.ts +195 -0
  144. package/dist/write/store/types.js +2 -0
  145. package/dist/write/store.d.ts +6 -0
  146. package/dist/write/store.js +182 -0
  147. package/examples/agentgateway.write-gate.yaml +29 -0
  148. package/package.json +71 -0
  149. package/server.json +69 -0
  150. package/skills/ar-aging.md +65 -0
  151. package/skills/company-360.md +69 -0
  152. package/skills/contract-profitability.md +65 -0
  153. package/skills/crm-management.md +87 -0
  154. package/skills/filter-semantics.md +75 -0
  155. package/skills/invoice-export.md +61 -0
  156. package/skills/log-time-entry.md +77 -0
  157. package/skills/non-chargeable-work.md +67 -0
  158. package/skills/portfolio-margin.md +66 -0
  159. package/skills/recurring-revenue.md +65 -0
  160. package/skills/revenue-rollup.md +65 -0
  161. package/skills/slim-reads.md +67 -0
  162. package/skills/ticket-triage.md +64 -0
  163. package/skills/unbilled-work-review.md +66 -0
  164. package/skills/wip-hours.md +68 -0
@@ -0,0 +1,137 @@
1
+ /**
2
+ * #183 S9: the preview's field checks, built only from facts the SDK already serves (the field catalog's
3
+ * picklist rows, zoneFacts.createGuidance, the effective required set). Each fact kind has one fixed
4
+ * template: instruction first, field names and ids only, no vendor text, short enough for the 500-character cap.
5
+ * A refusal answers before apply; a warning rides the preview.
6
+ */
7
+ import { effectiveRequiredFields } from 'node-autotask/operations';
8
+ import { assertOperationPermitted } from '../../policy.js';
9
+ import { writeQuirks } from '../write-guidance.js';
10
+ const SAFE = /^[A-Za-z][A-Za-z0-9]{0,63}$/;
11
+ const SAFE_VALUE = /^[A-Za-z0-9_-]{1,32}$/;
12
+ const get = (o, name) => {
13
+ if (o === undefined)
14
+ return undefined;
15
+ const k = Object.keys(o).find((x) => x.toLowerCase() === name.toLowerCase());
16
+ return k === undefined ? undefined : o[k];
17
+ };
18
+ const present = (o, name) => get(o, name) != null;
19
+ const has = (o, name) => o !== undefined && Object.keys(o).some((x) => x.toLowerCase() === name.toLowerCase());
20
+ /** The value after the write: a key sent in the payload (even null) decides; only an absent key falls back to the stored record. */
21
+ const after = (data, current, name) => (has(data, name) ? get(data, name) : get(current, name)) != null;
22
+ /** Room for a joined list in one sentence: names are added while the list stays short, the rest is counted. */
23
+ const LIST_BUDGET = 200;
24
+ export function listOf(xs) {
25
+ let out = '';
26
+ let n = 0;
27
+ for (const x of xs) {
28
+ if (n > 0 && out.length + x.length + 2 > LIST_BUDGET)
29
+ break;
30
+ out += (n > 0 ? ', ' : '') + x;
31
+ n++;
32
+ }
33
+ return n < xs.length ? `${out} and ${xs.length - n} more` : out;
34
+ }
35
+ /** A write that sets one field of a coupled pair without the other (counting the stored record on update). No wire. */
36
+ export function pairFindings(resource, data, current) {
37
+ const out = { refuse: [], warn: [] };
38
+ for (const { fields, source } of writeQuirks(resource).coupledFields ?? []) {
39
+ for (const [x, y] of [fields, [fields[1], fields[0]]]) {
40
+ if (present(data, x) && !after(data, current, y)) {
41
+ out.refuse.push(`Set ${y} together with ${x}: the vendor refuses ${x} without ${y}. Take ${y} from ${source}.`);
42
+ }
43
+ }
44
+ }
45
+ return out;
46
+ }
47
+ /** A changed picklist value the catalog marks isActive false: refuse where proven, warn elsewhere. */
48
+ export function picklistFindings(resource, data, fields, current) {
49
+ const out = { refuse: [], warn: [] };
50
+ for (const f of fields) {
51
+ if (!SAFE.test(f.name) || !Array.isArray(f.picklistValues) || !present(data, f.name))
52
+ continue;
53
+ const sent = String(get(data, f.name));
54
+ if (current !== undefined && String(get(current, f.name)) === sent)
55
+ continue; // unchanged: the record already carries it
56
+ if (!f.picklistValues.some((p) => String(p.value) === sent && p.isActive === false))
57
+ continue;
58
+ const shown = SAFE_VALUE.test(sent) ? ` = ${sent}` : '';
59
+ if (writeQuirks(resource).inactiveRefused?.includes(f.name) === true) {
60
+ out.refuse.push(`Choose an active ${f.name} value: ${f.name}${shown} is inactive (isActive false in operations.fieldCatalog, resources ["${resource}"], labels true) and the vendor refuses it.`);
61
+ }
62
+ else {
63
+ out.warn.push(`${f.name}${shown} is marked isActive false in operations.fieldCatalog (resources ["${resource}"], labels true). This write is not blocked because the vendor's answer for an inactive ${f.name} value is unverified; confirm the value with the user unless it was copied from an existing record.`);
64
+ }
65
+ }
66
+ return out;
67
+ }
68
+ /** A create's value gates and effective required set (SDK createGuidance) checked against the payload. */
69
+ export function gateFindings(data, facts, required, skip) {
70
+ const out = { refuse: [], warn: [] };
71
+ const safe = (xs) => xs.filter((x) => SAFE.test(x));
72
+ const val = (v) => (SAFE_VALUE.test(String(v)) ? String(v) : '(this value)');
73
+ for (const r of facts?.rejectedValues ?? []) {
74
+ if (SAFE.test(r.field) && present(data, r.field) && String(get(data, r.field)) === String(r.value)) {
75
+ out.refuse.push(`Choose another ${r.field}: the vendor rejects ${r.field} = ${val(r.value)} on create.`);
76
+ }
77
+ }
78
+ for (const g of facts?.requiresByValue ?? []) {
79
+ if (!SAFE.test(g.field) || !present(data, g.field) || String(get(data, g.field)) !== String(g.value))
80
+ continue;
81
+ const fixed = g.values ?? {};
82
+ const missing = safe(g.requires.allOf ?? []).filter((n) => !present(data, n) && !(n in fixed));
83
+ const anyOf = safe(g.requires.anyOf ?? []);
84
+ const needAny = anyOf.length > 0 && !anyOf.some((n) => present(data, n));
85
+ const wrong = Object.entries(fixed).filter(([k, v]) => SAFE.test(k) && String(get(data, k)) !== String(v)).map(([k, v]) => `${k} = ${val(v)}`);
86
+ if (missing.length === 0 && !needAny && wrong.length === 0)
87
+ continue;
88
+ const parts = [missing.length > 0 ? `supply ${listOf(missing)}` : '', needAny ? `supply at least one of ${listOf(anyOf)}` : '', wrong.length > 0 ? `set ${listOf(wrong)}` : ''].filter((s) => s !== '');
89
+ const text = `${parts.join('; ')}: the vendor requires this when ${g.field} = ${val(g.value)} and refuses the create without it.`;
90
+ out.refuse.push(text[0].toUpperCase() + text.slice(1));
91
+ }
92
+ const gap = safe(required.fields).filter((n) => n.toLowerCase() !== skip?.toLowerCase() && !present(data, n));
93
+ if (gap.length > 0) {
94
+ const basis = required.proven ? 'the vendor demanded' : required.from === 'zone' ? 'the SDK zone facts list' : required.from === 'spec' ? 'the field metadata marks' : 'the SDK create ladder (not fully proven) lists';
95
+ const text = `${required.proven ? 'Supply' : 'Check and supply'} ${listOf(gap)}: ${basis} ${gap.length > 1 ? 'these' : 'this'} as required on create.`;
96
+ (required.proven ? out.refuse : out.warn).push(text);
97
+ }
98
+ return out;
99
+ }
100
+ /** One field-catalog read (labels; the SDK serves it from its field cache when warm) and the static zone facts. A failed read adds nothing. */
101
+ export async function catalogFindings(ctx, p, signal) {
102
+ const out = { refuse: [], warn: [] };
103
+ try {
104
+ assertOperationPermitted('operations.fieldCatalog', ctx.record('operations.fieldCatalog'), ctx.config, ctx.log);
105
+ const res = (await ctx.ops.invokeRead(ctx.client, 'operations.fieldCatalog', [{ resources: [p.resource], labels: true }], undefined, signal));
106
+ if (res === undefined)
107
+ return { ...out, aborted: true }; // the SDK answers undefined for a cancelled call
108
+ const fields = res.rows?.find((r) => r.resource === p.resource)?.fields;
109
+ if (fields === undefined)
110
+ return out;
111
+ out.types = new Map(fields.flatMap((f) => (typeof f.name === 'string' && typeof f.type === 'string' ? [[f.name.toLowerCase(), f.type]] : [])));
112
+ const parts = [picklistFindings(p.resource, p.data, fields, p.current)];
113
+ if (p.op === 'create') {
114
+ try {
115
+ const map = (await ctx.ops.relationshipMap(ctx.client, p.resource));
116
+ const zone = map?.zoneFacts ?? undefined;
117
+ const spec = fields.filter((f) => f.isRequired === true && f.isReadOnly !== true).map((f) => f.name);
118
+ const eff = effectiveRequiredFields({ requiredFields: spec }, zone);
119
+ parts.push(gateFindings(p.data, zone?.createGuidance, { fields: eff.fields, from: eff.from, proven: eff.from === 'live-proven' && eff.unproven !== true }, p.parentField));
120
+ }
121
+ catch {
122
+ // no zone facts: the picklist findings stand alone
123
+ }
124
+ }
125
+ for (const x of parts) {
126
+ out.refuse.push(...x.refuse);
127
+ out.warn.push(...x.warn);
128
+ }
129
+ }
130
+ catch {
131
+ if (signal?.aborted === true)
132
+ return { ...out, aborted: true };
133
+ // unavailable: the dry run and the vendor remain the check
134
+ }
135
+ return out;
136
+ }
137
+ //# sourceMappingURL=checks.js.map
@@ -0,0 +1,23 @@
1
+ /** Shared by the preview and apply tools: the write deps, the tenant identity, the answer and reason builders (issue #89). */
2
+ import type { ToolContext, WriteDeps } from '../context/types.js';
3
+ import { type ToolReturn } from '../results/envelope.js';
4
+ import type { NextAction, Reason, ReasonCode, Status } from '../reasons.js';
5
+ import type { TenantIdentity } from '../../write/store.js';
6
+ /** Thrown inside a snapshot when the MCP request was cancelled before a read settled. */
7
+ export declare class Cancelled extends Error {
8
+ }
9
+ /** The write deps, which the operator rows are only ever built with. */
10
+ export declare function writeDeps(ctx: ToolContext): WriteDeps;
11
+ /** The tenant identity of this serving unit's credential (its identity fields, never the secret). */
12
+ export declare function tenantIdentity(ctx: ToolContext): TenantIdentity;
13
+ /** One envelope of the write path (`plan`/`planHash`/`replayed` ride at the top level). */
14
+ export declare function answer(status: Status, next: NextAction, reasons: Reason[], data: unknown, extra?: {
15
+ summary?: string;
16
+ plan?: string;
17
+ planHash?: string;
18
+ replayed?: boolean;
19
+ missing?: string[];
20
+ retryable?: boolean;
21
+ }): ToolReturn;
22
+ export declare const reason: (code: ReasonCode, detail: string, field?: string) => Reason;
23
+ export declare function isNotFound(err: unknown): boolean;
@@ -0,0 +1,33 @@
1
+ import { envelopeResult } from '../results/envelope.js';
2
+ /** Thrown inside a snapshot when the MCP request was cancelled before a read settled. */
3
+ export class Cancelled extends Error {
4
+ }
5
+ /** The write deps, which the operator rows are only ever built with. */
6
+ export function writeDeps(ctx) {
7
+ if (ctx.write === undefined)
8
+ throw new Error('the operator write tools were built without the write runtime');
9
+ return ctx.write;
10
+ }
11
+ /** The tenant identity of this serving unit's credential (its identity fields, never the secret). */
12
+ export function tenantIdentity(ctx) {
13
+ const pc = ctx.poolConfig;
14
+ if (pc === undefined || ctx.origin === undefined)
15
+ throw new Error('the write path needs a resolved credential and origin');
16
+ return {
17
+ integrationCode: pc.apiIntegrationCode,
18
+ username: pc.userName,
19
+ origin: ctx.origin,
20
+ ...(pc.impersonationResourceId !== undefined ? { impersonationId: String(pc.impersonationResourceId) } : {}),
21
+ };
22
+ }
23
+ /** One envelope of the write path (`plan`/`planHash`/`replayed` ride at the top level). */
24
+ export function answer(status, next, reasons, data, extra = {}) {
25
+ const { retryable, ...rest } = extra;
26
+ return envelopeResult({ status, data, next, reasons: reasons.map((r) => ({ ...r, detail: r.detail.slice(0, 500) })), retryable: retryable === true, correlationId: '', ...rest });
27
+ }
28
+ export const reason = (code, detail, field) => (field === undefined ? { code, detail } : { code, field, detail });
29
+ export function isNotFound(err) {
30
+ const e = err;
31
+ return e?.code === 'NOT_FOUND' || e?.category === 'not_found';
32
+ }
33
+ //# sourceMappingURL=common.js.map
@@ -0,0 +1,52 @@
1
+ /** Policy facts derived from a snapshot, including the move facts (issue #89). */
2
+ import type { CapabilityRecord } from 'node-autotask/capabilities';
3
+ import type { Reason } from '../reasons.js';
4
+ import { type WriteFacts } from '../../write/evaluate.js';
5
+ import type { WriteShape } from '../../write/hard-rules.js';
6
+ import type { StateStore } from '../../write/store.js';
7
+ import { type ParsedArgs } from './parse.js';
8
+ import type { Snapshot } from './snapshot.js';
9
+ /** The refusal for a write whose company cannot be established from live records. */
10
+ export declare function unresolvedReason(refs: string[]): Reason;
11
+ /** Field name (lower case) -> catalog type, as the preview's one cached field-catalog read reports it. */
12
+ export type FieldTypes = ReadonlyMap<string, string>;
13
+ /**
14
+ * #183 AC20: the vendor compares datetimes as strings, so re-sending the instant a record already
15
+ * holds (`2026-10-28T00:00:00.000Z` against `2026-10-28T00:00:00Z`) shows as a change that is not
16
+ * one. Compare as instants instead: entries whose `from` and `to` are equal instants in different
17
+ * representations are dropped (no diff), and the entries that remain show both sides in the
18
+ * canonical UTC spelling (`...000Z`). Only entries with an explicit zone designator (or an epoch number
19
+ * against one) on both sides are compared; a date-only or zoneless side is shown as sent. Only a field the field
20
+ * catalog types as date/datetime is touched: a text field holding date-shaped text is a plain value, and
21
+ * a field whose type is unknown (catalog unreadable, field absent) shows its entry as is, never dropped.
22
+ */
23
+ export declare function normaliseDiff(diff: unknown, types?: FieldTypes): unknown[];
24
+ /**
25
+ * A diff entry with both values marked: `from` is the vendor's current value (untrusted vendor
26
+ * text: cleaned, capped, wrapped); `to` is a document (cleaned and wrapped, never capped). The
27
+ * served `to` is the value the apply sends — the payload is cleaned before the plan, so the sent
28
+ * value is exactly what goes out the wire — except that entries of catalog-typed datetime fields are display-normalised
29
+ * to the canonical `.000Z` spelling of the same instant (#183 AC20): the apply still sends the
30
+ * caller's raw value. The cap counts the entries the normalised diff actually reports.
31
+ */
32
+ export declare function markedDiff(diff: unknown, types?: FieldTypes): unknown[];
33
+ export declare function deriveFacts(a: {
34
+ store: StateStore;
35
+ op: string;
36
+ record: CapabilityRecord;
37
+ shape: WriteShape;
38
+ parsed: ParsedArgs;
39
+ snap: Snapshot;
40
+ }): WriteFacts;
41
+ /**
42
+ * The move facts (issue #107), rebuilt from the snapshot at preview and again at apply: what a move
43
+ * would break (company or contract change: a soft break that gates the move for a person), and whether
44
+ * an earlier move of this source is unresolved. The ticket comparison reads the stable facts the
45
+ * snapshot hashed, so nothing here trusts the plan.
46
+ */
47
+ export declare function moveFacts(a: {
48
+ store: StateStore;
49
+ record: CapabilityRecord;
50
+ parsed: ParsedArgs;
51
+ snap: Snapshot;
52
+ }): Pick<WriteFacts, 'escalate'>;
@@ -0,0 +1,151 @@
1
+ import { markServerField } from '../results/untrusted.js';
2
+ import { PIN_FIELDS, PIN_OP } from '../../write/evaluate.js';
3
+ import { reason } from './common.js';
4
+ import { targetKeyOf } from './parse.js';
5
+ import { ci } from './payload.js';
6
+ import { INSTANT } from './snapshot.js';
7
+ /** The refusal for a write whose company cannot be established from live records. */
8
+ export function unresolvedReason(refs) {
9
+ return reason('TARGET_NOT_IN_SCOPE', `the company behind ${refs.join(', ')} could not be established from a live record; a write whose company cannot be established is refused`);
10
+ }
11
+ // ---------------------------------------------------------------------------
12
+ // autotask_write: the preview
13
+ // ---------------------------------------------------------------------------
14
+ /**
15
+ * A value the preview diff can compare as an instant: an instant with an explicit zone designator (Z or an
16
+ * offset), or a plausible epoch-milliseconds number. A date-only value and a zoneless time have no zone of
17
+ * their own (the vendor decides it), so they are never an instant and are shown as sent; small numbers
18
+ * (ids, counts, flags) are not datetimes.
19
+ */
20
+ function instantMs(value) {
21
+ if (typeof value === 'number') {
22
+ if (!Number.isFinite(value) || Math.abs(value) < 1e11 || Math.abs(value) > 4e12)
23
+ return null;
24
+ return value;
25
+ }
26
+ if (typeof value !== 'string' || !INSTANT.test(value))
27
+ return null;
28
+ const ms = Date.parse(value);
29
+ if (!Number.isFinite(ms))
30
+ return null;
31
+ // V8 rolls an impossible day over (2026-02-30 -> 2026-03-02): the written date must round-trip, or it is not an instant
32
+ const [y, m, d] = value.slice(0, 10).split('-').map(Number);
33
+ const day = new Date(Date.UTC(y, m - 1, d));
34
+ return day.getUTCFullYear() === y && day.getUTCMonth() === m - 1 && day.getUTCDate() === d ? ms : null;
35
+ }
36
+ /** Catalog `type` values that name a date or datetime (the vendor's dataType is `datetime` for both). */
37
+ const DATE_TYPES = new Set(['datetime', 'date']);
38
+ /**
39
+ * #183 AC20: the vendor compares datetimes as strings, so re-sending the instant a record already
40
+ * holds (`2026-10-28T00:00:00.000Z` against `2026-10-28T00:00:00Z`) shows as a change that is not
41
+ * one. Compare as instants instead: entries whose `from` and `to` are equal instants in different
42
+ * representations are dropped (no diff), and the entries that remain show both sides in the
43
+ * canonical UTC spelling (`...000Z`). Only entries with an explicit zone designator (or an epoch number
44
+ * against one) on both sides are compared; a date-only or zoneless side is shown as sent. Only a field the field
45
+ * catalog types as date/datetime is touched: a text field holding date-shaped text is a plain value, and
46
+ * a field whose type is unknown (catalog unreadable, field absent) shows its entry as is, never dropped.
47
+ */
48
+ export function normaliseDiff(diff, types) {
49
+ if (!Array.isArray(diff))
50
+ return [];
51
+ const out = [];
52
+ for (const d of diff) {
53
+ if (d === null || typeof d !== 'object' || Array.isArray(d)) {
54
+ out.push(d);
55
+ continue;
56
+ }
57
+ const entry = { ...d };
58
+ const type = typeof entry.field === 'string' ? types?.get(entry.field.toLowerCase()) : undefined;
59
+ if (type === undefined || !DATE_TYPES.has(type.toLowerCase())) {
60
+ out.push(entry);
61
+ continue;
62
+ }
63
+ let fromMs = instantMs(entry.from);
64
+ let toMs = instantMs(entry.to);
65
+ // a bare number is an epoch only against a datetime string: two numbers (or a number against anything else) is a plain value, left as is
66
+ if (typeof entry.from === 'number' && !(typeof entry.to === 'string' && toMs !== null))
67
+ fromMs = null;
68
+ if (typeof entry.to === 'number' && !(typeof entry.from === 'string' && fromMs !== null))
69
+ toMs = null;
70
+ // both sides must be instants: an entry with a date-only, zoneless or other side is shown as sent
71
+ if (fromMs === null || toMs === null) {
72
+ out.push(entry);
73
+ continue;
74
+ }
75
+ if (fromMs === toMs)
76
+ continue;
77
+ entry.from = new Date(fromMs).toISOString();
78
+ entry.to = new Date(toMs).toISOString();
79
+ out.push(entry);
80
+ }
81
+ return out;
82
+ }
83
+ /**
84
+ * A diff entry with both values marked: `from` is the vendor's current value (untrusted vendor
85
+ * text: cleaned, capped, wrapped); `to` is a document (cleaned and wrapped, never capped). The
86
+ * served `to` is the value the apply sends — the payload is cleaned before the plan, so the sent
87
+ * value is exactly what goes out the wire — except that entries of catalog-typed datetime fields are display-normalised
88
+ * to the canonical `.000Z` spelling of the same instant (#183 AC20): the apply still sends the
89
+ * caller's raw value. The cap counts the entries the normalised diff actually reports.
90
+ */
91
+ export function markedDiff(diff, types) {
92
+ return normaliseDiff(diff, types).slice(0, 100).map((d) => {
93
+ if (d === null || typeof d !== 'object' || Array.isArray(d))
94
+ return d;
95
+ const entry = d;
96
+ if (typeof entry.from === 'string')
97
+ markServerField(entry, 'from', 'wrap');
98
+ if (typeof entry.to === 'string')
99
+ markServerField(entry, 'to', 'document');
100
+ return entry;
101
+ });
102
+ }
103
+ /**
104
+ * The facts the policy is evaluated on, derived from a snapshot (the preview's, and at apply the FRESH
105
+ * re-read: apply never trusts facts stored with the plan, issue #106).
106
+ */
107
+ /** What a submitter-pinned create is judged on: every payload key outside the allow-list (any case; a repeated submitterID key counts) and the submitterID as sent. */
108
+ function pinFacts(data) {
109
+ const keys = Object.keys(data ?? {});
110
+ const lower = keys.map((k) => k.toLowerCase());
111
+ const extraFields = keys.filter((_k, i) => !PIN_FIELDS.includes(lower[i]) || lower.indexOf(lower[i]) !== i);
112
+ const submitter = data === undefined ? undefined : ci(data, 'submitterID');
113
+ const weekEnding = data === undefined ? undefined : ci(data, 'weekEnding');
114
+ return { extraFields, ...(submitter !== undefined ? { submitter } : {}), ...(weekEnding !== undefined ? { weekEnding } : {}) };
115
+ }
116
+ export function deriveFacts(a) {
117
+ const { shape, parsed, snap } = a;
118
+ return {
119
+ op: a.op,
120
+ shape,
121
+ companyIds: snap.companyIds,
122
+ duplicates: snap.duplicates,
123
+ targetKey: targetKeyOf(shape, parsed.targets, parsed.args),
124
+ ...(a.op === PIN_OP ? { pin: pinFacts(parsed.data) } : {}),
125
+ ...(shape === 'move' ? moveFacts({ store: a.store, record: a.record, parsed, snap }) : {}),
126
+ };
127
+ }
128
+ /**
129
+ * The move facts (issue #107), rebuilt from the snapshot at preview and again at apply: what a move
130
+ * would break (company or contract change: a soft break that gates the move for a person), and whether
131
+ * an earlier move of this source is unresolved. The ticket comparison reads the stable facts the
132
+ * snapshot hashed, so nothing here trusts the plan.
133
+ */
134
+ export function moveFacts(a) {
135
+ const { snap, parsed } = a;
136
+ const reads = snap.inputs.reads;
137
+ const fromId = ci(snap.current ?? {}, 'ticketID');
138
+ const from = typeof fromId === 'number' ? reads[`tickets:${fromId}`] : undefined;
139
+ const to = reads[`tickets:${parsed.targets.toId}`];
140
+ const escalate = [];
141
+ if (from === undefined || to === undefined)
142
+ escalate.push('the source and target tickets could not be compared');
143
+ else {
144
+ if (ci(from, 'companyID') !== ci(to, 'companyID'))
145
+ escalate.push('the target ticket belongs to a different company');
146
+ if ((ci(from, 'contractID') ?? null) !== (ci(to, 'contractID') ?? null))
147
+ escalate.push('the target ticket is on a different contract');
148
+ }
149
+ return { escalate };
150
+ }
151
+ //# sourceMappingURL=facts.js.map
@@ -0,0 +1,23 @@
1
+ /** How a recorded ledger outcome is answered: honest errors, a move's manual delete, not-persisted and replayed outcomes (issue #89). */
2
+ import type { ToolReturn } from '../results/envelope.js';
3
+ import { type LedgerEntry, type PlanRecord } from '../../write/store.js';
4
+ /**
5
+ * The nested error must agree with the envelope (live-test finding): the SDK calls a vendor 500
6
+ * transient (`retryable: true`, "Retry with backoff"), but a 500 with an errors[] body is a
7
+ * deterministic business-rule rejection, and an unknown outcome must never be re-sent. Only a
8
+ * genuinely retryable failure keeps the SDK's hint.
9
+ */
10
+ export declare function honestError(payload: Record<string, unknown>, err: unknown, entry: LedgerEntry): Record<string, unknown>;
11
+ /** The envelope of an update whose HTTP write succeeded but whose stored record lacks some sent fields (issue #103). */
12
+ export declare function notPersistedAnswer(plan: PlanRecord, entry: LedgerEntry, fields: string[], extra: {
13
+ replayed: boolean;
14
+ record?: unknown;
15
+ unrecorded?: boolean;
16
+ }): ToolReturn;
17
+ /** The envelope for a recorded (or just recorded) outcome. `result` overrides the ledger id a success reports. */
18
+ export declare function outcomeAnswer(plan: PlanRecord, entry: LedgerEntry, extra: {
19
+ replayed: boolean;
20
+ data?: Record<string, unknown>;
21
+ summary?: string;
22
+ result?: unknown;
23
+ }): ToolReturn;
@@ -0,0 +1,67 @@
1
+ import { COOLDOWN_MINUTES } from '../../write/store.js';
2
+ import { answer, reason } from './common.js';
3
+ // ---------------------------------------------------------------------------
4
+ // autotask_apply: the execution
5
+ // ---------------------------------------------------------------------------
6
+ /**
7
+ * The nested error must agree with the envelope (live-test finding): the SDK calls a vendor 500
8
+ * transient (`retryable: true`, "Retry with backoff"), but a 500 with an errors[] body is a
9
+ * deterministic business-rule rejection, and an unknown outcome must never be re-sent. Only a
10
+ * genuinely retryable failure keeps the SDK's hint.
11
+ */
12
+ export function honestError(payload, err, entry) {
13
+ if (entry.outcome?.retryable === true)
14
+ return { ...payload, nextAction: 'retry' };
15
+ if (entry.state === 'unknown')
16
+ return { ...payload, retryable: false, nextAction: 'stop', suggestedAction: 'The write may have landed: read the record to verify; do not re-send.' };
17
+ const errors = err?.vendorError?.errors;
18
+ const said = Array.isArray(errors) ? errors.filter((e) => typeof e === 'string').slice(0, 3).map((e) => e.slice(0, 200)) : [];
19
+ const text = said.join('; ').trim();
20
+ return { ...payload, retryable: false, nextAction: 'stop', suggestedAction: text !== '' ? `The vendor refused: ${text}${/[.!?]$/.test(text) ? '' : '.'} Fix the input; do not retry.` : 'Fix the input; do not retry.' };
21
+ }
22
+ /** The envelope of an update whose HTTP write succeeded but whose stored record lacks some sent fields (issue #103). */
23
+ export function notPersistedAnswer(plan, entry, fields, extra) {
24
+ const resource = plan.targets.resource;
25
+ 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])], {
26
+ operation: plan.op,
27
+ targets: plan.targets,
28
+ outcome: 'succeeded',
29
+ result: entry.outcome?.id === undefined ? {} : { id: entry.outcome.id },
30
+ ...(extra.record === undefined ? {} : { record: extra.record }),
31
+ notPersisted: fields,
32
+ }, { 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.' : ''}` });
33
+ }
34
+ /** The envelope for a recorded (or just recorded) outcome. `result` overrides the ledger id a success reports. */
35
+ export function outcomeAnswer(plan, entry, extra) {
36
+ const meta = { plan: plan.handle, planHash: plan.planHash, ...(extra.replayed ? { replayed: true } : {}) };
37
+ const base = { operation: plan.op, targets: plan.targets, outcome: entry.state === 'sending' ? 'unknown' : entry.state, ...extra.data };
38
+ if (entry.state === 'succeeded' && entry.outcome?.code === 'FIELD_NOT_PERSISTED' && entry.outcome.fields !== undefined) {
39
+ return notPersistedAnswer(plan, entry, entry.outcome.fields, { replayed: extra.replayed });
40
+ }
41
+ if (entry.state === 'succeeded' && entry.outcome?.sourceId !== undefined) {
42
+ // a move: old id -> new id (the SDK result is the verification: no extra read-back)
43
+ const manual = entry.outcome.code === 'MOVE_MANUAL_DELETE';
44
+ return answer('ok', manual ? 'manual_action' : 'proceed', [], { ...base, result: { sourceId: entry.outcome.sourceId, newId: entry.outcome.newId } }, {
45
+ ...meta,
46
+ summary: manual
47
+ ? `${plan.op}: the verified copy ${String(entry.outcome.newId)} exists on the target ticket, but the vendor refused to delete the source ${String(entry.outcome.sourceId)}: a person must delete the source in Autotask (data.move.manualAction.uiLink when present). Do not move it again.`
48
+ : `${plan.op} moved ${String(entry.outcome.sourceId)} to new id ${String(entry.outcome.newId)}${extra.replayed ? ' (recorded outcome replayed; nothing was sent again)' : ''}.`,
49
+ });
50
+ }
51
+ if (entry.state === 'succeeded') {
52
+ // a generic `call` op reports its own SDK result; a shaped one reports the ledger id
53
+ const result = 'result' in extra ? extra.result : entry.outcome?.id === undefined ? {} : { id: entry.outcome.id };
54
+ return answer('ok', 'proceed', [], { ...base, result }, { ...meta, summary: extra.summary ?? `${plan.op} succeeded${extra.replayed ? ' (recorded outcome replayed; nothing was sent again)' : ''}.` });
55
+ }
56
+ if (entry.state === 'failed') {
57
+ const retryable = entry.outcome?.retryable === true;
58
+ const code = retryable && entry.outcome?.code?.startsWith('RATE_LIMITED') === true ? 'RATE_LIMITED' : 'WRITE_FAILED';
59
+ return answer('error', retryable ? 'retry' : 'stop', [reason(code, `${plan.op} failed (${entry.outcome?.code ?? 'error'}${entry.outcome?.httpStatus !== undefined ? `, HTTP ${entry.outcome.httpStatus}` : ''}); nothing was written${retryable ? `; after the wait call autotask_apply with this same plan handle (${plan.handle}); do not preview again` : ''}`)], base, { ...meta, retryable });
60
+ }
61
+ if (entry.outcome?.code === 'MOVE_PARTIAL' || entry.outcome?.code === 'MOVE_UNKNOWN') {
62
+ const ids = `source ${String(entry.outcome.sourceId)}${entry.outcome.newId !== undefined ? `, new ${String(entry.outcome.newId)}` : ''}`;
63
+ return answer('error', 'stop', [reason('WRITE_OUTCOME_UNKNOWN', `${plan.op} did not finish cleanly (${entry.outcome.code}; ${ids}): both records may exist. Do not move or re-send; re-read both and resolve in Autotask`)], base, meta);
64
+ }
65
+ return answer('error', 'verify_then_repreview', [reason('WRITE_OUTCOME_UNKNOWN', `${plan.op} may or may not have landed (${entry.outcome?.code ?? 'no answer'}); this plan is never sent again. Re-read the target. If absent, a new attempt requires corrected input or changed stable vendor facts and the ${COOLDOWN_MINUTES}-minute cooldown; identical input and facts replay this unknown outcome`)], base, meta);
66
+ }
67
+ //# sourceMappingURL=outcome.js.map
@@ -0,0 +1,37 @@
1
+ import type { CapabilityRecord } from 'node-autotask/capabilities';
2
+ import type { Reason } from '../reasons.js';
3
+ import type { WriteShape } from '../../write/hard-rules.js';
4
+ import type { PlanTargets } from '../../write/store.js';
5
+ export declare const SHAPE_ARGS: Record<WriteShape, string[]>;
6
+ /** The argument names of the generic `call` shape that name the record's own id (the snapshot's target). */
7
+ export declare const CALL_ID_ARGS: ReadonlySet<string>;
8
+ /** The argument names of the generic `call` shape that name a company the write touches (a scope fact). */
9
+ export declare const CALL_COMPANY_ARGS: ReadonlySet<string>;
10
+ /**
11
+ * A non-negative integer id, or an integer string of digits (the registry accepts both forms for ids),
12
+ * so "0" reads as 0 exactly as "2001" reads as 2001. Anything else (negative, fractional, beyond
13
+ * 2^53, non-numeric) is undefined. Only a company reference may be 0 (the tenant's own company).
14
+ */
15
+ export declare function asIdOrZero(value: unknown): number | undefined;
16
+ /** A positive integer id, or an integer string of digits (the registry accepts both forms for ids). */
17
+ export declare function asId(value: unknown): number | undefined;
18
+ export interface ParsedArgs {
19
+ args: unknown[];
20
+ targets: PlanTargets;
21
+ data?: Record<string, unknown>;
22
+ }
23
+ /**
24
+ * The generic `call` shape (issue #191): the record's own declared arguments, in registry order, sent
25
+ * to the SDK op unchanged. There is no field-level snapshot to validate against, so the arguments are
26
+ * checked by the SDK's OWN pre-request validator (`validateDispatchArgs`: arity, required args, loose
27
+ * types, zero wire) and by the same payload hygiene the data object gets. Ids stay ids where the
28
+ * registry names one; an object argument is a payload and its references are scope facts.
29
+ */
30
+ export declare function parseCallArgs(record: CapabilityRecord, raw: unknown[]): ParsedArgs | Reason;
31
+ /** Validate the positional args against the shape; ids are positive integers, never names. */
32
+ export declare function parseArgs(shape: WriteShape, record: CapabilityRecord, raw: unknown[]): ParsedArgs | Reason;
33
+ /**
34
+ * The ledger's key for a target: the record for an update or delete, the payload for a create, and for
35
+ * the generic `call` shape the record (or parent) it names — or, when it names none, the arguments.
36
+ */
37
+ export declare function targetKeyOf(shape: WriteShape, targets: PlanTargets, args: unknown[]): string;