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,305 @@
1
+ /**
2
+ * tools/composites.ts — the Layer-C composites: one call, the whole object the workflow needs.
3
+ *
4
+ * All nine composites (`tickets.fullContext`, `companies.fullProfile`,
5
+ * `configuration_items.profile`, `projects.getContext`, `quotes.withItems`,
6
+ * `contacts.fullProfile`, `service_calls.fullProfile`, `contracts.fullProfile`,
7
+ * `resources.workload`) are SDK-backed: the SDK runs its own bounded fan-out with per-part
8
+ * `absent` degradation — the server passes the declared limits through and serves the result.
9
+ * `projects.getContext` adds two server-side parts after the root (#287): the project's phases and
10
+ * tasks, each one capped query plus one exact count, degrading the same way.
11
+ * The ROOT read is not caught (a missing root fails the call with the typed vendor error);
12
+ * every PART degrades independently to `{ value: null, absent: <code> }` (a part that cannot
13
+ * resolve — no foreign key, no rows, a NOT_FOUND — is reported, never a tool failure).
14
+ *
15
+ * A composite folds records of several resources (company, contact, notes, time entries, ...):
16
+ * the cross-resource field union (`crossResourceUntrusted`) marks all of them (final review R3),
17
+ * not the root's stamp alone.
18
+ */
19
+ import { AutotaskConfigError } from 'node-autotask';
20
+ import { TICKET_FULL_CONTEXT_INPUT, COMPANY_FULL_PROFILE_INPUT, COMPANY_PROFILE_PART_LIMIT_DEFAULT, CONFIGURATION_ITEM_PROFILE_INPUT, PROJECT_GET_CONTEXT_INPUT, QUOTE_GET_INPUT, INVOICE_GET_INPUT, CONTACT_FULL_PROFILE_INPUT, SERVICE_CALL_FULL_PROFILE_INPUT, CONTRACT_FULL_PROFILE_INPUT, RESOURCE_WORKLOAD_INPUT, closedInput, } from './schemas.js';
21
+ import { abortedAnswer } from './dispatch.js';
22
+ import { crossResourceUntrusted, documentCore, markFilePayload, markResult } from './results/untrusted.js';
23
+ import { ok } from './results/envelope.js';
24
+ import { resolveOutputTarget } from './output-file.js';
25
+ import { assertOperationPermitted } from '../policy.js';
26
+ /** A filter bag with only the keys the caller set. */
27
+ function bagOf(entries) {
28
+ const bag = {};
29
+ for (const [k, v] of entries)
30
+ if (v !== undefined)
31
+ bag[k] = v;
32
+ return bag;
33
+ }
34
+ // ---------------------------------------------------------------------------
35
+ // The nine SDK-backed composites (the SDK runs the bounded fan-out inside)
36
+ // ---------------------------------------------------------------------------
37
+ function sdkComposite(ctx, spec) {
38
+ const rec = ctx.record(spec.operation);
39
+ if (rec === undefined)
40
+ throw new Error(`composites: no registry record for ${spec.operation}`);
41
+ // The composite folds records of several resources (company, contact, notes, time entries, ...):
42
+ // the cross-resource field union marks them all (final review R3), not the root's stamp alone.
43
+ const fields = crossResourceUntrusted();
44
+ return {
45
+ title: spec.title,
46
+ input: spec.input,
47
+ run: async (args, signal) => {
48
+ assertOperationPermitted(spec.operation, rec, ctx.config, ctx.log);
49
+ const opts = spec.opts(args);
50
+ // A missing root fails the call (the typed vendor error); per-part misses degrade inside the
51
+ // SDK. The positional list is built CONDITIONALLY: the declared arity is id + an OPTIONAL
52
+ // opts bag, and a trailing undefined slot is refused pre-dispatch as a second arg.
53
+ const pos = [args.id];
54
+ if (Object.keys(opts).length > 0)
55
+ pos.push(opts);
56
+ const result = await ctx.ops.invokeRead(ctx.client, spec.operation, pos, undefined, signal);
57
+ if (result === undefined)
58
+ return abortedAnswer(ctx.correlationId);
59
+ if (spec.extraParts === undefined)
60
+ return ok(`${spec.title} returned.`, { result: markResult(result, fields) });
61
+ const extra = await spec.extraParts(args, signal);
62
+ if (extra === undefined)
63
+ return abortedAnswer(ctx.correlationId);
64
+ return ok(`${spec.title} returned.`, { result: markResult({ ...result, ...extra }, fields) });
65
+ },
66
+ };
67
+ }
68
+ // ---- the nine SDK-backed composites ----
69
+ export function buildTicketFullContext(ctx) {
70
+ return sdkComposite(ctx, {
71
+ operation: 'tickets.fullContext',
72
+ title: 'Get a ticket with its full bounded context',
73
+ input: closedInput(TICKET_FULL_CONTEXT_INPUT),
74
+ opts: (a) => bagOf([
75
+ ['noteLimit', a.note_limit],
76
+ ['timeEntryLimit', a.time_entry_limit],
77
+ ['includeAttachments', a.include_attachments],
78
+ ['includeHistories', a.include_histories],
79
+ ['textLimit', a.text_limit],
80
+ ['names', a.names],
81
+ ['maxNameReads', a.max_name_reads],
82
+ ]),
83
+ });
84
+ }
85
+ export function buildCompanyFullProfile(ctx) {
86
+ return sdkComposite(ctx, {
87
+ operation: 'companies.fullProfile',
88
+ title: 'Get a company with its full bounded profile',
89
+ input: closedInput(COMPANY_FULL_PROFILE_INPUT),
90
+ opts: (a) => bagOf([
91
+ ['fields', a.fields],
92
+ ['locationLimit', a.location_limit],
93
+ ['contactLimit', a.contact_limit ?? COMPANY_PROFILE_PART_LIMIT_DEFAULT],
94
+ ['noteLimit', a.note_limit ?? COMPANY_PROFILE_PART_LIMIT_DEFAULT],
95
+ ['ticketLimit', a.ticket_limit ?? COMPANY_PROFILE_PART_LIMIT_DEFAULT],
96
+ ['projectLimit', a.project_limit ?? COMPANY_PROFILE_PART_LIMIT_DEFAULT],
97
+ ['names', a.names],
98
+ ['maxNameReads', a.max_name_reads],
99
+ ]),
100
+ });
101
+ }
102
+ export function buildConfigurationItemProfile(ctx) {
103
+ return sdkComposite(ctx, {
104
+ operation: 'configuration_items.profile',
105
+ title: 'Get a configuration item with its bounded profile',
106
+ input: closedInput(CONFIGURATION_ITEM_PROFILE_INPUT),
107
+ opts: (a) => bagOf([['noteLimit', a.note_limit], ['relatedLimit', a.related_limit], ['names', a.names], ['maxNameReads', a.max_name_reads]]),
108
+ });
109
+ }
110
+ /** #287: row caps of the phases and tasks parts (exact totals come from the count reads). */
111
+ export const PROJECT_PHASE_CAP = 100;
112
+ export const PROJECT_TASK_CAP = 200;
113
+ const PHASE_FIELDS = ['id', 'parentPhaseID', 'phaseNumber', 'title', 'description', 'startDate', 'dueDate', 'estimatedHours'];
114
+ const TASK_FIELDS = ['id', 'taskNumber', 'title', 'status', 'phaseID', 'assignedResourceID', 'estimatedHours', 'remainingHours'];
115
+ /**
116
+ * Phases nested by parentPhaseID; a phase whose parent is not in the served set, or whose parent
117
+ * chain loops back to itself (untrusted vendor data), stays top-level: every served phase appears once.
118
+ */
119
+ export function phaseTree(rows) {
120
+ const byId = new Map(rows.map((r) => [r.id, { ...r, children: [] }]));
121
+ const inCycle = (p) => {
122
+ const seen = new Set([p.id]);
123
+ for (let cur = byId.get(p.parentPhaseID); cur !== undefined; cur = byId.get(cur.parentPhaseID)) {
124
+ if (seen.has(cur.id))
125
+ return true;
126
+ seen.add(cur.id);
127
+ }
128
+ return false;
129
+ };
130
+ const roots = [];
131
+ for (const p of byId.values()) {
132
+ const parent = p.parentPhaseID == null ? undefined : byId.get(p.parentPhaseID);
133
+ if (parent !== undefined && !inCycle(p))
134
+ parent.children.push(p);
135
+ else
136
+ roots.push(p);
137
+ }
138
+ return roots;
139
+ }
140
+ /** A cancelled request: the SDK throws ABORTED; the mock seam answers undefined. */
141
+ const isAbort = (err, signal) => signal?.aborted === true || err?.code === 'ABORTED';
142
+ /**
143
+ * The project's phases or tasks (#287): one capped query plus one exact count, degrading to
144
+ * `{ value: null, absent: <code> }` like the SDK's own composite parts. `truncated` is true when
145
+ * more rows exist than were served (never a silent cut); `count` is null when the count read failed.
146
+ */
147
+ async function projectRowsPart(ctx, resource, projectId, opts, signal) {
148
+ const filter = [{ field: 'projectID', op: 'eq', value: projectId }];
149
+ try {
150
+ for (const op of [`${resource}.query`, `${resource}.count`])
151
+ assertOperationPermitted(op, ctx.record(op), ctx.config, ctx.log);
152
+ const bag = bagOf([['filter', filter], ['limit', opts.limit], ['includeFields', opts.includeFields], ['names', opts.names]]);
153
+ const [page, total] = await Promise.all([
154
+ ctx.ops.invokeRead(ctx.client, `${resource}.query`, [bag], undefined, signal),
155
+ ctx.ops.invokeRead(ctx.client, `${resource}.count`, [{ filter }], undefined, signal).catch((err) => (isAbort(err, signal) ? undefined : null)),
156
+ ]);
157
+ if (page === undefined || total === undefined)
158
+ return undefined;
159
+ const v = page;
160
+ const items = Array.isArray(v.items) ? v.items : [];
161
+ const t = total;
162
+ const count = typeof t === 'number' ? t : typeof t?.count === 'number' ? t.count : null;
163
+ const truncated = v.hasMore === true || (count !== null && count > items.length);
164
+ return { value: { items: resource === 'phases' ? phaseTree(items) : items, served: items.length, count, truncated } };
165
+ }
166
+ catch (err) {
167
+ if (isAbort(err, signal))
168
+ return undefined;
169
+ const e = err;
170
+ return { value: null, absent: typeof e.code === 'string' && e.code !== '' ? e.code : typeof e.name === 'string' && e.name !== '' ? e.name : 'ERROR' };
171
+ }
172
+ }
173
+ export function buildProjectGetContext(ctx) {
174
+ return sdkComposite(ctx, {
175
+ operation: 'projects.getContext',
176
+ title: 'Get a project with its bounded context',
177
+ input: closedInput(PROJECT_GET_CONTEXT_INPUT),
178
+ opts: (a) => bagOf([['names', a.names], ['maxNameReads', a.max_name_reads]]),
179
+ extraParts: async (a, signal) => {
180
+ const [phases, tasks] = await Promise.all([
181
+ projectRowsPart(ctx, 'phases', a.id, { limit: PROJECT_PHASE_CAP, includeFields: PHASE_FIELDS }, signal),
182
+ projectRowsPart(ctx, 'tasks', a.id, { limit: PROJECT_TASK_CAP, includeFields: TASK_FIELDS, names: a.names }, signal),
183
+ ]);
184
+ return phases === undefined || tasks === undefined ? undefined : { phases, tasks };
185
+ },
186
+ });
187
+ }
188
+ // ---- autotask_quote_get: the quote + its line items (the items part is the SDK fan-out) ----
189
+ export function buildQuoteGet(ctx) {
190
+ return sdkComposite(ctx, {
191
+ operation: 'quotes.withItems',
192
+ title: 'Get a quote with its line items',
193
+ input: closedInput(QUOTE_GET_INPUT),
194
+ opts: (a) => bagOf([['itemLimit', a.item_limit]]),
195
+ });
196
+ }
197
+ // ---- autotask_invoice_get: the invoice record (A1: there is no invoice_items resource) ----
198
+ /**
199
+ * The invoice export (issue #54): the raw vendor document, never escaped vendor text.
200
+ *
201
+ * - FILE form (an `output_path` is passed; stdio only — the module refuses anything else before
202
+ * any vendor wire): the RAW document goes to the file (UTF-8 text for html/xml, the decoded
203
+ * bytes for pdf — never cleaned, wrapped or escaped: it is a disk artifact, not model context),
204
+ * and the result carries only the path and the size.
205
+ * - IN-BAND form (no `output_path`, any transport): the document crosses as the SDK's file-payload
206
+ * shape `{ encoding: 'base64', byteLength, truncated, data }`, recorded `binary` by provenance —
207
+ * pure base64 crosses the choke point uncapped and unescaped (the alphabet has no bracket), and
208
+ * decoding `data` yields the exact vendor document.
209
+ * - a `pdf` past the SDK's 1 MiB inline limit crosses without its body (`truncated: true`, no
210
+ * `data`): no file can be written, and that in-band envelope is answered instead.
211
+ */
212
+ export function buildInvoiceGet(ctx) {
213
+ const OPS = { record: 'invoices.get', html: 'invoices.markupHtml', xml: 'invoices.markupXml', pdf: 'invoices.pdf' };
214
+ return {
215
+ title: 'Get an invoice record or export',
216
+ input: closedInput(INVOICE_GET_INPUT),
217
+ run: async (raw, signal) => {
218
+ const args = raw;
219
+ const op = OPS[args.format];
220
+ assertOperationPermitted(op, ctx.record(op), ctx.config, ctx.log);
221
+ if (args.format === 'record' && args.output_path !== undefined) {
222
+ throw new AutotaskConfigError('output_path applies to the export formats (html, xml, pdf): the record is a small JSON payload, always served in-band (nothing was dialled, nothing was written)', { operation: op });
223
+ }
224
+ // The file form validates the target BEFORE any vendor wire (a bad path never reaches the
225
+ // vendor; the module enforces the stdio-only and containment rules).
226
+ const target = args.output_path !== undefined
227
+ ? await resolveOutputTarget({
228
+ root: ctx.config.AUTOTASK_OUTPUT_DIR,
229
+ stateDir: ctx.config.AUTOTASK_STATE_DIR,
230
+ transport: ctx.config.MCP_TRANSPORT,
231
+ relativePath: args.output_path,
232
+ })
233
+ : undefined;
234
+ const result = await ctx.ops.invokeRead(ctx.client, op, [args.id], undefined, signal);
235
+ if (result === undefined)
236
+ return abortedAnswer(ctx.correlationId);
237
+ if (args.format === 'record') {
238
+ return ok('Invoice returned.', { format: args.format, result: markResult(result, ctx.untrustedFields(op)) });
239
+ }
240
+ if (typeof result === 'string') {
241
+ // html / xml: the vendor markup (one outer wrapper pair dropped, the house rule: a value
242
+ // that arrives pre-wrapped is a vendor forgery — the pinned SDK's read path returns raw).
243
+ const doc = documentCore(result);
244
+ if (target !== undefined) {
245
+ const bytes = await target.write(doc);
246
+ return ok(`Invoice ${args.format} export written to the configured output directory (${bytes} bytes); the file holds the raw document, the result carries only the path and size.`, { format: args.format, result: { outputPath: target.path, bytes, encoding: 'utf-8' } });
247
+ }
248
+ const buf = Buffer.from(doc, 'utf8');
249
+ const payload = { encoding: 'base64', byteLength: buf.byteLength, truncated: false, data: buf.toString('base64') };
250
+ markFilePayload(payload);
251
+ return ok(`Invoice ${args.format} export returned as a base64 document; decode result.data for the raw markup.`, { format: args.format, result: payload });
252
+ }
253
+ // pdf: the SDK's file payload { encoding, byteLength, truncated, data? }.
254
+ const payload = markResult(result, ctx.untrustedFields(op));
255
+ if (target !== undefined && payload.truncated !== true && typeof payload.data === 'string') {
256
+ const bytes = await target.write(Buffer.from(payload.data, 'base64'));
257
+ return ok(`Invoice ${args.format} export written to the configured output directory (${bytes} bytes); the file holds the raw document, the result carries only the path and size.`, { format: args.format, result: { outputPath: target.path, bytes, encoding: 'binary' } });
258
+ }
259
+ markFilePayload(payload);
260
+ if (target !== undefined) {
261
+ // The SDK's 1 MiB inline limit kept the body from crossing: no file can be written.
262
+ return ok(`Invoice ${args.format} export exceeded the vendor 1 MiB inline limit; no file was written, the result carries the truncation note.`, { format: args.format, result: payload });
263
+ }
264
+ return ok(`Invoice ${args.format} export returned as a base64 file payload; decode result.data for the raw document.`, { format: args.format, result: payload });
265
+ },
266
+ };
267
+ }
268
+ // ---- autotask_contact_full_profile: the contact, its company, its open tickets ----
269
+ export function buildContactFullProfile(ctx) {
270
+ return sdkComposite(ctx, {
271
+ operation: 'contacts.fullProfile',
272
+ title: 'Get a contact with its company and open tickets',
273
+ input: closedInput(CONTACT_FULL_PROFILE_INPUT),
274
+ opts: (a) => bagOf([['ticketLimit', a.ticket_limit]]),
275
+ });
276
+ }
277
+ // ---- autotask_service_call_full_profile: the call, its tickets, its tasks, its resource assignments ----
278
+ export function buildServiceCallFullProfile(ctx) {
279
+ return sdkComposite(ctx, {
280
+ operation: 'service_calls.fullProfile',
281
+ title: 'Get a service call with its tickets, tasks and resource assignments',
282
+ input: closedInput(SERVICE_CALL_FULL_PROFILE_INPUT),
283
+ opts: (a) => bagOf([['ticketLimit', a.ticket_limit], ['taskLimit', a.task_limit]]),
284
+ });
285
+ }
286
+ // ---- autotask_contract_full_profile: the contract, its services, its billing rules,
287
+ // ---- its recent charges (issue #49) and its service units (issue #49) ----
288
+ export function buildContractFullProfile(ctx) {
289
+ return sdkComposite(ctx, {
290
+ operation: 'contracts.fullProfile',
291
+ title: 'Get a contract with its services, billing rules, recent charges and service units',
292
+ input: closedInput(CONTRACT_FULL_PROFILE_INPUT),
293
+ opts: (a) => bagOf([['serviceLimit', a.service_limit], ['billingRuleLimit', a.billing_rule_limit]]),
294
+ });
295
+ }
296
+ // ---- autotask_resource_workload: the resource, its open work, its balances ----
297
+ export function buildResourceWorkload(ctx) {
298
+ return sdkComposite(ctx, {
299
+ operation: 'resources.workload',
300
+ title: 'Get a resource\'s workload: open tickets, assignments, balances, time off',
301
+ input: closedInput(RESOURCE_WORKLOAD_INPUT),
302
+ opts: (a) => bagOf([['ticketLimit', a.ticket_limit], ['taskLimit', a.task_limit], ['timeOffLimit', a.time_off_limit]]),
303
+ });
304
+ }
305
+ //# sourceMappingURL=composites.js.map
@@ -0,0 +1,41 @@
1
+ import type { AutotaskConfig } from 'node-autotask';
2
+ import type { Config } from '../../config/schema.js';
3
+ import type { Logger } from '../../logger.js';
4
+ import type { ToolClient, ToolOps } from './types.js';
5
+ /** The reserved placeholder origin (RFC 6761: nothing in the real world resolves it). */
6
+ export declare const PLACEHOLDER_ORIGIN = "https://no-autotask-origin.invalid";
7
+ export declare const PLACEHOLDER_BASE_URL = "https://no-autotask-origin.invalid/atservicesrest";
8
+ /** Sentinel credential values a placeholder client is constructed with (never real, never dialled). */
9
+ export declare const SENTINEL_CREDENTIAL = "unresolved-request-scope";
10
+ /**
11
+ * The deployment-wide SDK options every client this factory builds gets (the agent profile +
12
+ * the env overrides + the cache off switch + the zero maintenance wait + the literal-IP host
13
+ * floor + the audit sink).
14
+ * Precedence: explicit env > `agent` profile > SDK default (the profile fills only what is
15
+ * left unset).
16
+ */
17
+ export declare function buildSdkBaseOptions(config: Config, log: Logger): Omit<AutotaskConfig, 'apiIntegrationCode' | 'userName' | 'secret'>;
18
+ /** A fail-closed placeholder client: constructed but never dialled (context refuses pre-request). */
19
+ export declare function buildPlaceholderClient(baseOptions: ReturnType<typeof buildSdkBaseOptions>): ToolClient;
20
+ /** The one process-lifetime client of the stdio transport (the environment IS the identity). */
21
+ export declare function buildStdioClient(config: Config, log: Logger): {
22
+ client: ToolClient;
23
+ origin: string;
24
+ };
25
+ /**
26
+ * The SDK operations bundle (the production default; tests substitute a fixture-backed bundle).
27
+ *
28
+ * (Historical, FT-4: before node-autotask 0.9.0 the invoke router resolved `client['authenticate']` to the
29
+ * convenience METHOD, so `authenticate.get` answered CONFIG_ERROR and this bundle special-cased it to
30
+ * `authenticateResource.get()`. 0.9.0 routes it to the resource holder (#88), so every read now goes through
31
+ * `invokeRead` and its governor; `authenticate.*` is refused by the deployment policy before it.)
32
+ */
33
+ export declare const defaultToolOps: ToolOps;
34
+ /**
35
+ * Propagate the MCP request's cancellation into the SDK's in-flight request (architecture 7.6:
36
+ * an abandoned request stops consuming vendor budget). The SDK's `withSignal` returns
37
+ * `undefined` when the signal has already aborted or no transport is attached — the SDK's own
38
+ * handler then answers the typed cancellation; the handler's generic catch would otherwise
39
+ * re-report it as a tool error, so this wrapper throws the SDK's typed `AbortError` instead.
40
+ */
41
+ export declare function withSignal(client: ToolClient, signal: AbortSignal | undefined, fn: () => Promise<unknown>): Promise<unknown>;
@@ -0,0 +1,139 @@
1
+ /** SDK client construction (base options, placeholder, stdio client) and the default SDK ops bundle (issue #91). */
2
+ import { AutotaskClient } from 'node-autotask';
3
+ import { invokeDelete, invokeRead, invokeWrite, relationshipMap, resolveAny, searchAcrossResources } from 'node-autotask/operations';
4
+ import { serverCredentialDefaults } from '../../config/load.js';
5
+ import { normalizeBaseUrl } from '../../base-hosts.js';
6
+ import { sdkCacheOptions } from '../catalog-data.js';
7
+ // ---------------------------------------------------------------------------
8
+ // SDK client construction
9
+ // ---------------------------------------------------------------------------
10
+ /** The reserved placeholder origin (RFC 6761: nothing in the real world resolves it). */
11
+ export const PLACEHOLDER_ORIGIN = 'https://no-autotask-origin.invalid';
12
+ export const PLACEHOLDER_BASE_URL = `${PLACEHOLDER_ORIGIN}/atservicesrest`;
13
+ /** Sentinel credential values a placeholder client is constructed with (never real, never dialled). */
14
+ export const SENTINEL_CREDENTIAL = 'unresolved-request-scope';
15
+ /**
16
+ * The deployment-wide SDK options every client this factory builds gets (the agent profile +
17
+ * the env overrides + the cache off switch + the zero maintenance wait + the literal-IP host
18
+ * floor + the audit sink).
19
+ * Precedence: explicit env > `agent` profile > SDK default (the profile fills only what is
20
+ * left unset).
21
+ */
22
+ export function buildSdkBaseOptions(config, log) {
23
+ const defaultBase = config.AUTOTASK_BASE_URL;
24
+ const defaultBaseUrl = defaultBase === undefined ? undefined : normalizeBaseUrl(defaultBase)?.baseUrl;
25
+ return {
26
+ // The vendor budget guard: never the `library` defaults, never an operator-tuned value
27
+ // above the vendor cap (config validation enforces the cap).
28
+ profile: 'agent',
29
+ // Keep LLM-facing name/label siblings enabled (SDK labels are opt-in).
30
+ labels: true,
31
+ // Tool calls must never hang inside a vendor maintenance window (issue #252): the wait is
32
+ // 0, so the SDK's shared per-zone maintenance gate opens and surfaces the typed
33
+ // MaintenanceError at once (node-autotask 0.40.0 #285) instead of a call riding out the
34
+ // vendor page. The SDK's poll interval keeps its default. No timeout-based logic lives in
35
+ // the server.
36
+ maintenanceMaxWaitMs: 0,
37
+ ...(config.AUTOTASK_RATE_LIMIT_PER_HOUR !== undefined ? { rateLimit: { perHour: config.AUTOTASK_RATE_LIMIT_PER_HOUR } } : {}),
38
+ ...(config.AUTOTASK_MAX_CONCURRENT !== undefined ? { maxConcurrent: config.AUTOTASK_MAX_CONCURRENT } : {}),
39
+ ...(config.AUTOTASK_TIMEOUT_MS !== undefined ? { timeoutMs: config.AUTOTASK_TIMEOUT_MS } : {}),
40
+ ...(config.AUTOTASK_MAX_RETRIES !== undefined ? { maxRetries: config.AUTOTASK_MAX_RETRIES } : {}),
41
+ // The literal-IP SSRF floor: a LITERAL private/loopback origin is refused at construction
42
+ // even if the deployment allow-list named it (the private bound wins — security S2/C2.4).
43
+ hostPolicy: {
44
+ blockPrivateHosts: true,
45
+ ...(defaultBaseUrl !== undefined ? { allowedOrigins: [defaultBaseUrl] } : {}),
46
+ },
47
+ // The approved cache deviation, docs/architecture.md 8.1 (user-approved; issue #252):
48
+ // AUTOTASK_CACHE is the single off switch — `off` sends `cache: false` (every read re-dials
49
+ // the vendor); `on` sends nothing (the SDK default-on caches). No TTL overrides (SDK 0.40.0
50
+ // merged the caches into one block).
51
+ ...sdkCacheOptions(config.AUTOTASK_CACHE),
52
+ // One bounded line per settled request (the SDK stamps the correlation id and redacts the
53
+ // body at the wire; the `path` carries no query values by construction). Only the event's
54
+ // own shape metadata is forwarded — never bodies or payload values (security S9).
55
+ onAudit: (event) => {
56
+ const e = event;
57
+ log.info('autotask request', {
58
+ ...(typeof e.correlationId === 'string' ? { correlationId: e.correlationId } : {}),
59
+ ...(typeof e.operation === 'string' ? { operation: e.operation } : {}),
60
+ ...(typeof e.method === 'string' ? { method: e.method } : {}),
61
+ ...(typeof e.path === 'string' ? { path: e.path } : {}),
62
+ ...(typeof e.status === 'number' ? { status: e.status } : {}),
63
+ ...(typeof e.durationMs === 'number' ? { durationMs: e.durationMs } : {}),
64
+ ...(typeof e.errorCode === 'string' ? { errorCode: e.errorCode } : {}),
65
+ ...(e.notSent === true ? { notSent: true } : {}),
66
+ });
67
+ },
68
+ };
69
+ }
70
+ /** A fail-closed placeholder client: constructed but never dialled (context refuses pre-request). */
71
+ export function buildPlaceholderClient(baseOptions) {
72
+ // The placeholders keep the literal-IP floor only: their reserved origin must survive
73
+ // construction so the sentinel is what a dialled placeholder would present, unmistakably.
74
+ const client = new AutotaskClient({
75
+ ...baseOptions,
76
+ apiIntegrationCode: SENTINEL_CREDENTIAL,
77
+ userName: SENTINEL_CREDENTIAL,
78
+ secret: SENTINEL_CREDENTIAL,
79
+ baseUrl: PLACEHOLDER_BASE_URL,
80
+ hostPolicy: { blockPrivateHosts: true },
81
+ });
82
+ return client;
83
+ }
84
+ /** The one process-lifetime client of the stdio transport (the environment IS the identity). */
85
+ export function buildStdioClient(config, log) {
86
+ const baseOptions = buildSdkBaseOptions(config, log);
87
+ const defaults = serverCredentialDefaults(config);
88
+ if (defaults === undefined || config.AUTOTASK_BASE_URL === undefined) {
89
+ // Unreachable: loadConfig requires all four under stdio. The line after it is unreachable;
90
+ // it exists so the narrowing is a type fact rather than a comment.
91
+ throw new Error('stdio client built without a complete credential tuple — loadConfig guarantees this cannot happen');
92
+ }
93
+ const normalized = normalizeBaseUrl(config.AUTOTASK_BASE_URL);
94
+ if (normalized === undefined)
95
+ throw new Error('AUTOTASK_BASE_URL failed normalization after boot validation — this cannot happen');
96
+ const client = new AutotaskClient({
97
+ ...baseOptions,
98
+ apiIntegrationCode: defaults.apiIntegrationCode,
99
+ userName: defaults.userName,
100
+ secret: defaults.secret,
101
+ ...(defaults.impersonationResourceId !== undefined ? { impersonationResourceId: defaults.impersonationResourceId } : {}),
102
+ baseUrl: normalized.baseUrl,
103
+ });
104
+ return { client, origin: normalized.origin };
105
+ }
106
+ // ---------------------------------------------------------------------------
107
+ // The SDK operations bundle (the mock seam is `ToolOps`; tests inject theirs through the factory option `ops`)
108
+ // ---------------------------------------------------------------------------
109
+ /**
110
+ * The SDK operations bundle (the production default; tests substitute a fixture-backed bundle).
111
+ *
112
+ * (Historical, FT-4: before node-autotask 0.9.0 the invoke router resolved `client['authenticate']` to the
113
+ * convenience METHOD, so `authenticate.get` answered CONFIG_ERROR and this bundle special-cased it to
114
+ * `authenticateResource.get()`. 0.9.0 routes it to the resource holder (#88), so every read now goes through
115
+ * `invokeRead` and its governor; `authenticate.*` is refused by the deployment policy before it.)
116
+ */
117
+ export const defaultToolOps = {
118
+ invokeRead: (client, operation, args, opts, signal) => withSignal(client, signal, () => invokeRead(client, operation, args, opts ?? {})),
119
+ invokeWrite: (client, operation, args, opts, signal) => withSignal(client, signal, () => invokeWrite(client, operation, args, opts ?? {})),
120
+ invokeDelete: (client, operation, args, opts, signal) => withSignal(client, signal, () => invokeDelete(client, operation, args, opts ?? {})),
121
+ resolveAny: (client, identifier, opts, signal) => withSignal(client, signal, () => resolveAny(client, identifier, opts ?? {})),
122
+ searchAcrossResources: (client, query, opts, signal) => withSignal(client, signal, () => searchAcrossResources(client, query, opts ?? {})),
123
+ relationshipMap: (client, resourceKey) => relationshipMap(client, resourceKey),
124
+ hourlyBudget: (client) => Promise.resolve(client.hourlyBudget()),
125
+ };
126
+ /**
127
+ * Propagate the MCP request's cancellation into the SDK's in-flight request (architecture 7.6:
128
+ * an abandoned request stops consuming vendor budget). The SDK's `withSignal` returns
129
+ * `undefined` when the signal has already aborted or no transport is attached — the SDK's own
130
+ * handler then answers the typed cancellation; the handler's generic catch would otherwise
131
+ * re-report it as a tool error, so this wrapper throws the SDK's typed `AbortError` instead.
132
+ */
133
+ export function withSignal(client, signal, fn) {
134
+ const c = client;
135
+ if (signal === undefined || typeof c.withSignal !== 'function')
136
+ return fn();
137
+ return c.withSignal(signal, fn);
138
+ }
139
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1,9 @@
1
+ import type { ToolDeps, ToolContext } from './types.js';
2
+ /** Derive the context the registrations share. */
3
+ export declare function deriveToolContext(deps: ToolDeps, served?: ReadonlySet<string>): ToolContext;
4
+ /**
5
+ * A vendor 401 (or impersonation-scope 401/403) deletes the pooled entry so a stale identity is
6
+ * not negative-cached and replayed (security S1/C1.8, S3/C3.5): the next request with the same
7
+ * tuple recreates the client and starts fresh. Safe to call with a non-pooled client (no-op).
8
+ */
9
+ export declare function releaseClientOnError(deps: ToolDeps, err: unknown): void;
@@ -0,0 +1,32 @@
1
+ /** Deriving a tool context from the deps, and releasing a client on error (issue #91). */
2
+ import { isAutotaskError } from 'node-autotask';
3
+ import { isAuthFailure } from '../results/errors.js';
4
+ import { recordById, toolDescription, untrustedFieldsOf } from '../catalog-data.js';
5
+ /** Derive the context the registrations share. */
6
+ export function deriveToolContext(deps, served = new Set()) {
7
+ return {
8
+ ...deps,
9
+ served,
10
+ writable: new Set(deps.write === undefined ? [] : [...deps.write.runtime.loaded.table].filter(([, row]) => row.mode !== 'deny').map(([op]) => op)),
11
+ record: recordById,
12
+ untrustedFields: (operation) => {
13
+ const rec = recordById(operation);
14
+ return rec === undefined ? [] : untrustedFieldsOf(rec);
15
+ },
16
+ description: toolDescription,
17
+ };
18
+ }
19
+ /**
20
+ * A vendor 401 (or impersonation-scope 401/403) deletes the pooled entry so a stale identity is
21
+ * not negative-cached and replayed (security S1/C1.8, S3/C3.5): the next request with the same
22
+ * tuple recreates the client and starts fresh. Safe to call with a non-pooled client (no-op).
23
+ */
24
+ export function releaseClientOnError(deps, err) {
25
+ if (deps.pool === undefined || deps.poolConfig === undefined)
26
+ return;
27
+ if (isAutotaskError(err) && isAuthFailure(err)) {
28
+ const removed = deps.pool.delete(deps.poolConfig);
29
+ deps.log.info('deleted pooled client after credential refusal', { removed, poolSize: deps.pool.size });
30
+ }
31
+ }
32
+ //# sourceMappingURL=derive.js.map
@@ -0,0 +1,24 @@
1
+ /** HTTP per-request credential and scope resolution (issue #91). */
2
+ import type { ClientPool } from 'node-autotask/pool';
3
+ import type { Config } from '../../config/schema.js';
4
+ import type { Logger } from '../../logger.js';
5
+ import type { HttpScopeResolver } from './types.js';
6
+ import { buildSdkBaseOptions } from './client.js';
7
+ /**
8
+ * Build the per-request scope resolver for the http transport.
9
+ *
10
+ * The effective policy (mirrors the security S2/C2.2 layering):
11
+ * - a caller-named origin is refused unless `AUTOTASK_ALLOWED_BASE_HOSTS` permits it;
12
+ * - allow-list unset + default origin set -> the default origin only is accepted;
13
+ * - neither set -> boot is refused unless the explicit lab-only `AUTOTASK_ALLOW_ANY_BASE_HOST`
14
+ * (config validation makes that mode reachable by typing it out, never by forgetting);
15
+ * - the default origin is operator truth: never checked against the allow-list, but it must
16
+ * itself pass the https + private-IP bounds (enforced at boot / at construction).
17
+ *
18
+ * Credentials are all-or-nothing: a request presenting 1 or 2 of the three identity headers is
19
+ * malformed and resolves to the `partial_credential` refusal (there is no per-field default
20
+ * fill); a request presenting none uses the server-held default tuple ONLY when it is set AND
21
+ * the request did not name a different origin (the default identity is only ever presented to
22
+ * the default origin — a caller cannot aim it at a host it controls).
23
+ */
24
+ export declare function createHttpScopeResolver(config: Config, log: Logger, pool: ClientPool, baseOptions: ReturnType<typeof buildSdkBaseOptions>): HttpScopeResolver;