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,218 @@
1
+ /** Untrusted-text handling: unsafe-character stripping, provenance marking and vendor-output sanitising (issue #90). */
2
+ import { deepMarkUntrusted, UNTRUSTED_CLOSE, UNTRUSTED_OPEN, wrapUntrusted } from 'node-autotask/untrusted';
3
+ import { RECORDS, untrustedFieldsOf } from '../catalog-data.js';
4
+ import { TRUNCATION_MARKER } from './envelope.js';
5
+ /**
6
+ * Characters stripped from every untrusted free-text value (M8, review F3, pre-release V9 and the
7
+ * follow-up review): every control character except `\n` and `\t` (`\p{Cc}`), every format
8
+ * character (`\p{Cf}`: bidi controls, zero-width characters, the soft hyphen, the tag block U+E0000-
9
+ * E007F, ...), every default-ignorable code point (variation selectors, fillers, the grapheme
10
+ * joiner, Mongolian free variation selectors, ...), and the line and paragraph separators
11
+ * U+2028/9. They hide or reorder text a model then reads as instructions, or split a token so one
12
+ * check misses what a later reader sees.
13
+ *
14
+ * Tradeoff, decided conservatively: the zero-width joiner and the emoji variation selector are in
15
+ * this set, so an emoji ZWJ sequence crosses as its separate emoji (a family emoji as three
16
+ * people) and a text-or-emoji presentation choice is lost. Letters, accents and plain emoji are kept.
17
+ */
18
+ export const UNSAFE_CHARS = /(?![\n\t])[\p{Cc}\p{Cf}\p{Cs}\p{Default_Ignorable_Code_Point}\u2028\u2029]/gu;
19
+ /** The per-value cap on untrusted free text (M8). */
20
+ export const UNTRUSTED_TEXT_CAP = 500;
21
+ /** Strip the unsafe characters only (write payloads: D-21; nothing else is changed). */
22
+ export function stripUnsafeChars(text) {
23
+ return text.replace(UNSAFE_CHARS, '');
24
+ }
25
+ /**
26
+ * The angle-bracket escape of untrusted vendor text (the pre-release follow-up reviews) was
27
+ * REMOVED in 0.9.0 (issue #70): it was pure cost for LLM consumers and broke read-modify-write
28
+ * round-trips of values carrying &, < or >. The injection controls are the strip pass above and
29
+ * the <untrusted_content> wrapper the choke point applies to stamped fields (the wrapper marks
30
+ * the whole field untrusted; the server instructions carry the data-never-instructions rule).
31
+ */
32
+ /**
33
+ * Clean one untrusted value: strip the unsafe characters, then (when `cap`) cut at
34
+ * {@link UNTRUSTED_TEXT_CAP}; a cut value carries {@link TRUNCATION_MARKER}.
35
+ */
36
+ export function cleanUntrustedText(text, cap = true, max = UNTRUSTED_TEXT_CAP) {
37
+ const clean = stripUnsafeChars(text);
38
+ if (!cap || clean.length <= max)
39
+ return clean;
40
+ let cut = clean.slice(0, max);
41
+ // never end on half a surrogate pair (final review R8)
42
+ if (/[\uD800-\uDBFF]$/.test(cut))
43
+ cut = cut.slice(0, -1);
44
+ return `${cut}${TRUNCATION_MARKER}`;
45
+ }
46
+ /** One character outside the base64 alphabet (a linear test: no backtracking, any length). */
47
+ export const NOT_BASE64 = /[^A-Za-z0-9+/=\r\n]/;
48
+ /** Nesting past this depth is dropped rather than walked (final review R7). */
49
+ export const MAX_OUTPUT_DEPTH = 64;
50
+ /** The per-array provenance key: applies to every string item of an array. */
51
+ export const EVERY_ITEM = '*';
52
+ /** The cap on a `cursor` value: the SDK's own cursor cap (a longer cursor is refused before any request). */
53
+ export const CURSOR_CAP = 2048;
54
+ export const PROVENANCE = new WeakMap();
55
+ export function note(target, key, kind) {
56
+ let fields = PROVENANCE.get(target);
57
+ if (fields === undefined) {
58
+ fields = new Map();
59
+ PROVENANCE.set(target, fields);
60
+ }
61
+ fields.set(key, kind);
62
+ }
63
+ /** Record that `target[key]` is a server-built document or table (see {@link Provenance}). */
64
+ export function markServerField(target, key, kind) {
65
+ note(target, key, kind);
66
+ }
67
+ /** The operations whose result carries a file payload in `data` (FileQueryResultModel). */
68
+ export function isFileOperation(operation) {
69
+ return operation.endsWith('.download') || operation === 'invoices.pdf';
70
+ }
71
+ /** Record a file result's `data` as `binary` (provenance: only for {@link isFileOperation} results). */
72
+ export function markFilePayload(value) {
73
+ if (value !== null && typeof value === 'object' && !Array.isArray(value) && typeof value.data === 'string') {
74
+ note(value, 'data', 'binary');
75
+ }
76
+ }
77
+ export function wrapOrSelf(clean) {
78
+ return wrapUntrusted(clean) ?? clean;
79
+ }
80
+ /**
81
+ * Drop ONE outer wrapper pair, unconditionally, from a value that starts with the open tag and ends
82
+ * with the close tag. The pinned SDK's read path returns raw values (node-autotask#103: wrapping is
83
+ * projection-layer only), except the `contracts.profitability` renewal labels it wraps at the producer
84
+ * (SDK 0.47.2, node-autotask#375); otherwise the live input class is a vendor forgery. Both get exactly
85
+ * the same treatment: nothing about the value is trusted, the inner text is then cleaned like any
86
+ * vendor text and wrapped once by this server.
87
+ */
88
+ export function outerUnwrap(value) {
89
+ return value.length >= UNTRUSTED_OPEN.length + UNTRUSTED_CLOSE.length && value.startsWith(UNTRUSTED_OPEN) && value.endsWith(UNTRUSTED_CLOSE)
90
+ ? value.slice(UNTRUSTED_OPEN.length, value.length - UNTRUSTED_CLOSE.length)
91
+ : undefined;
92
+ }
93
+ /**
94
+ * The vendor document core of a value that may arrive pre-wrapped (issue #54): drop exactly ONE outer
95
+ * wrapper pair — the live class is a vendor forgery (the pinned SDK's read path returns raw values,
96
+ * node-autotask#103), otherwise the value unchanged. The invoice export channels encode and write the
97
+ * document core, so the artifact is the vendor document, never a wrapped one.
98
+ */
99
+ export function documentCore(value) {
100
+ return outerUnwrap(value) ?? value;
101
+ }
102
+ /**
103
+ * The deny-by-default choke point for vendor output (final review R1-R3, R5, R7, and the two
104
+ * follow-up findings): every string in a vendor-calling tool's result, at any depth, and every
105
+ * object key, is vendor text: cleaned ({@link cleanUntrustedText}: unsafe characters stripped,
106
+ * capped at 500). Nothing is ever skipped because of what a string looks
107
+ * like. A value that arrives pre-wrapped (a vendor forgery, or an SDK producer-wrapped profitability
108
+ * renewal label: see {@link outerUnwrap}) loses its one outer pair ({@link outerUnwrap}); its inner
109
+ * text is cleaned and capped like any vendor text and wrapped once, since it came marked
110
+ * untrusted. An unmarked string is
111
+ * cleaned, not wrapped. Otherwise the wrapper is applied here and only here, to the fields the
112
+ * server recorded by provenance ({@link markResult}, {@link markServerField}).
113
+ */
114
+ export function sanitiseVendorOutput(value, opts = {}, kind, depth = 0) {
115
+ const cap = opts.cap !== false;
116
+ if (typeof value === 'string') {
117
+ if (kind === 'server')
118
+ return value;
119
+ if (kind === 'binary' && !NOT_BASE64.test(value))
120
+ return value;
121
+ const inner = outerUnwrap(value);
122
+ const text = inner ?? value;
123
+ if (kind === 'document')
124
+ return wrapOrSelf(cleanUntrustedText(text, false));
125
+ if (kind === 'cursor' && inner === undefined)
126
+ return cleanUntrustedText(text, cap, CURSOR_CAP);
127
+ const clean = cleanUntrustedText(text, cap);
128
+ return kind === 'wrap' || inner !== undefined ? wrapOrSelf(clean) : clean;
129
+ }
130
+ if (value === null || typeof value !== 'object')
131
+ return value;
132
+ if (depth >= MAX_OUTPUT_DEPTH)
133
+ return '[DEPTH]';
134
+ const fields = PROVENANCE.get(value);
135
+ if (Array.isArray(value)) {
136
+ const items = fields?.get(EVERY_ITEM) ?? (kind === 'wrap' ? 'wrap' : undefined);
137
+ return value.map((v) => sanitiseVendorOutput(v, opts, items, depth + 1));
138
+ }
139
+ // Keys (sanitiser review S6): every key is cleaned; a key that is already clean is placed first
140
+ // and keeps its provenance, so a look-alike key (`ti` + U+200B + `tle`) can never take a stamped
141
+ // field's place or strip its wrapper; a collision gets a numbered suffix, never an overwrite; and
142
+ // keys are defined, not assigned, so `__proto__` is an ordinary key.
143
+ const out = {};
144
+ const put = (key, v) => Object.defineProperty(out, key, { value: v, enumerable: true, writable: true, configurable: true });
145
+ const entries = Object.entries(value).map(([k, v]) => ({ k, v, clean: cleanUntrustedText(k) }));
146
+ for (const { k, v, clean } of [...entries.filter((e) => e.k === e.clean), ...entries.filter((e) => e.k !== e.clean)]) {
147
+ let key = clean;
148
+ for (let n = 1; Object.prototype.hasOwnProperty.call(out, key); n++)
149
+ key = `${clean}~${n}`;
150
+ put(key, sanitiseVendorOutput(v, opts, k === clean ? fields?.get(k) : undefined, depth + 1));
151
+ }
152
+ return out;
153
+ }
154
+ export const CORRELATION_ID = /^[0-9a-f-]{36}$/;
155
+ /**
156
+ * Server prose (summary, reason detail and field) can embed vendor values that arrive pre-wrapped
157
+ * (a vendor forgery — the pinned SDK's read path returns raw values).
158
+ * Prose is cleaned, never wrapped, so the embedded wrapper tags are dropped (the split/join below)
159
+ * before cleaning: the dropped tags are the injection control here — no wrapper tag survives into
160
+ * prose, and the brackets left over stay raw (0.9.0 removed the escape, issue #70).
161
+ */
162
+ export function cleanProse(text, cap = true) {
163
+ return cleanUntrustedText(text.split(UNTRUSTED_OPEN).join('').split(UNTRUSTED_CLOSE).join(''), cap);
164
+ }
165
+ /**
166
+ * Apply {@link sanitiseVendorOutput} to a finished vendor-tool result and re-mirror its text block.
167
+ * `serverCorrelationId` replaces a top-level correlation id that is not this server's own shape
168
+ * (sanitiser review S5). Every envelope string that is not a fixed enum passes the choke point:
169
+ * data, summary, candidates, and each reason's detail and field (S4).
170
+ */
171
+ export function sanitiseToolReturn(result, serverCorrelationId = '') {
172
+ const env = result.structuredContent;
173
+ env.data = sanitiseVendorOutput(env.data);
174
+ if (typeof env.summary === 'string')
175
+ env.summary = cleanProse(env.summary);
176
+ if (env.candidates !== undefined)
177
+ env.candidates = sanitiseVendorOutput(env.candidates);
178
+ if (env.reasons !== undefined)
179
+ env.reasons = env.reasons.map((r) => ({ ...r, detail: cleanProse(r.detail), ...(r.field !== undefined ? { field: cleanProse(r.field, false).slice(0, 200) } : {}) }));
180
+ if (env.status !== 'ok' && !CORRELATION_ID.test(env.correlationId ?? ''))
181
+ env.correlationId = serverCorrelationId;
182
+ if (env.textCapped === undefined && JSON.stringify(env.data ?? null).includes(TRUNCATION_MARKER))
183
+ env.textCapped = true;
184
+ const first = result.content[0];
185
+ if (first !== undefined)
186
+ first.text = JSON.stringify(env);
187
+ return result;
188
+ }
189
+ /**
190
+ * Record the untrusted-content projection on a result: a copy in which the plan-derived field list
191
+ * (the registry stamp) and every user-defined field value (`userDefinedFields[].value`, review F3)
192
+ * are marked `wrap` by provenance through the SDK's field/UDF projection. Nothing is cleaned or wrapped here: the choke point
193
+ * ({@link sanitiseVendorOutput}, run on every vendor tool's result and on TSV cells and
194
+ * output_path files) cleans every string and wraps exactly the marked ones.
195
+ */
196
+ export function markResult(value, fields) {
197
+ return deepMarkUntrusted(value, fields, (text, target, key) => {
198
+ note(target, Array.isArray(target) ? EVERY_ITEM : String(key), 'wrap');
199
+ return text; // The host must unwrap, clean and cap raw text before wrapping it.
200
+ });
201
+ }
202
+ /**
203
+ * The cross-resource untrusted field union (resolveAny / searchAcrossResources /
204
+ * the mode tools serve records from several resources — the superset is safe: the wrapper only
205
+ * affects fields that are present).
206
+ */
207
+ export const CROSS_RESOURCE_UNTRUSTED = (() => {
208
+ const set = new Set();
209
+ for (const r of RECORDS)
210
+ for (const f of untrustedFieldsOf(r))
211
+ set.add(f);
212
+ return [...set].sort();
213
+ })();
214
+ /** The cross-resource untrusted field union (see {@link CROSS_RESOURCE_UNTRUSTED}). */
215
+ export function crossResourceUntrusted() {
216
+ return CROSS_RESOURCE_UNTRUSTED;
217
+ }
218
+ //# sourceMappingURL=untrusted.js.map
@@ -0,0 +1,8 @@
1
+ import type { ToolContext } from './context/types.js';
2
+ import type { BuiltTool } from './surface.js';
3
+ export declare function buildRevenueRollup(ctx: ToolContext): BuiltTool;
4
+ export declare function buildPortfolioMargin(ctx: ToolContext): BuiltTool;
5
+ export declare function buildRecurringRevenue(ctx: ToolContext): BuiltTool;
6
+ export declare function buildArAging(ctx: ToolContext): BuiltTool;
7
+ export declare function buildWipHours(ctx: ToolContext): BuiltTool;
8
+ export declare function buildNonChargeableWork(ctx: ToolContext): BuiltTool;
@@ -0,0 +1,112 @@
1
+ /** The finance tools resolve a relative window; the SDK owns the reports and their budgets. */
2
+ import { zoneClock } from './clock.js';
3
+ import { abortedAnswer, InputInvalidError, readOneItem } from './dispatch.js';
4
+ import { ok } from './results/envelope.js';
5
+ import { AR_AGING_INPUT, closedInput, PORTFOLIO_MARGIN_INPUT, NON_CHARGEABLE_WORK_INPUT, RECURRING_REVENUE_INPUT, REVENUE_ROLLUP_INPUT, WIP_HOURS_INPUT } from './schemas.js';
6
+ /** Exactly one scope and a full-month window (both dates, or lastFullMonths in the user zone), then the SDK op. */
7
+ async function runFinanceReport(ctx, label, operation, scopeKeys, args, signal) {
8
+ const { lastFullMonths, ...opts } = args;
9
+ if (scopeKeys.filter((k) => opts[k] !== undefined).length !== 1) {
10
+ throw new InputInvalidError(`${label}: choose exactly one scope: ${scopeKeys.slice(0, -1).join(', ')} or tenantWide: true (autotask_resolve finds company ids).`, 'scope');
11
+ }
12
+ const hasFrom = opts.dateFrom !== undefined;
13
+ const hasTo = opts.dateTo !== undefined;
14
+ if (hasFrom !== hasTo)
15
+ throw new InputInvalidError(`${label}: pass both dateFrom and dateTo, or neither.`, hasFrom ? 'dateTo' : 'dateFrom');
16
+ if (hasFrom && lastFullMonths !== undefined)
17
+ throw new InputInvalidError(`${label}: lastFullMonths applies only when both dates are omitted.`, 'lastFullMonths');
18
+ const zone = ctx.config.AUTOTASK_USER_TIMEZONE;
19
+ if (!hasFrom) {
20
+ const [year, month] = zoneClock(zone).nowLocal.slice(0, 7).split('-').map(Number);
21
+ opts.dateFrom = new Date(Date.UTC(year, month - 1 - (lastFullMonths ?? 12), 1)).toISOString().slice(0, 10);
22
+ opts.dateTo = new Date(Date.UTC(year, month - 1, 0)).toISOString().slice(0, 10);
23
+ }
24
+ const out = await readOneItem(ctx, operation, [opts], signal);
25
+ return { out, window: { dateFrom: opts.dateFrom, dateTo: opts.dateTo, zone } };
26
+ }
27
+ export function buildRevenueRollup(ctx) {
28
+ return {
29
+ title: 'Revenue by vertical, contract type and other dimensions',
30
+ input: closedInput(REVENUE_ROLLUP_INPUT),
31
+ run: async (args, signal) => {
32
+ const { out, window } = await runFinanceReport(ctx, 'revenue rollup', 'operations.revenueRollup', ['companyIDs', 'ownerResourceID', 'contractIDs', 'tenantWide'], args, signal);
33
+ if (out.aborted)
34
+ return abortedAnswer(ctx.correlationId);
35
+ return ok('Revenue rollup returned; report excluded revenue from coverage alongside the in-scope total.', { window, result: out.result });
36
+ },
37
+ };
38
+ }
39
+ export function buildPortfolioMargin(ctx) {
40
+ return {
41
+ title: 'Contract profit and margin by contract type and other dimensions',
42
+ input: closedInput(PORTFOLIO_MARGIN_INPUT),
43
+ run: async (args, signal) => {
44
+ const { out, window } = await runFinanceReport(ctx, 'portfolio margin', 'operations.portfolioMargin', ['contractIDs', 'companyIDs', 'tenantWide'], args, signal);
45
+ if (out.aborted)
46
+ return abortedAnswer(ctx.correlationId);
47
+ return ok('Portfolio margin returned; report complete and coverage.contractsWithGaps with the totals (complete false: the figures are floors); margins are per-contract item-date P&L, not comparable to the revenue rollup.', { window, result: out.result });
48
+ },
49
+ };
50
+ }
51
+ /** One scope (companyIDs or tenantWide) and a dateKey date (asOf or dateTo) defaulting to today in the user zone, then the SDK op. */
52
+ async function runZoneDatedReport(ctx, label, operation, dateKey, args, signal) {
53
+ const opts = { ...args };
54
+ if (['companyIDs', 'tenantWide'].filter((k) => opts[k] !== undefined).length !== 1) {
55
+ throw new InputInvalidError(`${label}: choose exactly one scope: companyIDs or tenantWide: true (autotask_resolve finds company ids).`, 'scope');
56
+ }
57
+ const zone = ctx.config.AUTOTASK_USER_TIMEZONE;
58
+ opts[dateKey] ??= zoneClock(zone).nowLocal.slice(0, 10);
59
+ const out = await readOneItem(ctx, operation, [opts], signal);
60
+ return { out, date: opts[dateKey], zone };
61
+ }
62
+ export function buildRecurringRevenue(ctx) {
63
+ return {
64
+ title: 'Monthly recurring revenue per company, with contracts ending soon',
65
+ input: closedInput(RECURRING_REVENUE_INPUT),
66
+ run: async (args, signal) => {
67
+ const { out, date, zone } = await runZoneDatedReport(ctx, 'recurring revenue', 'operations.recurringRevenue', 'asOf', args, signal);
68
+ if (out.aborted)
69
+ return abortedAnswer(ctx.correlationId);
70
+ return ok('Recurring revenue returned; report services, subscriptions and charges MRR per source (never summed: a subscription may be billed through a service) and the expiring contracts; a mid-month asOf counts only the charges dated so far.', { asOf: { date, zone }, result: out.result });
71
+ },
72
+ };
73
+ }
74
+ export function buildArAging(ctx) {
75
+ return {
76
+ title: 'Unpaid invoice aging per company',
77
+ input: closedInput(AR_AGING_INPUT),
78
+ run: async (args, signal) => {
79
+ const { out, date, zone } = await runZoneDatedReport(ctx, 'AR aging', 'operations.arAging', 'asOf', args, signal);
80
+ if (out.aborted)
81
+ return abortedAnswer(ctx.correlationId);
82
+ return ok('AR aging returned; unpaid means paidDate absent and partial payments are not reflected (coverage says so); report totals per currency, never summed across currencies.', { asOf: { date, zone }, result: out.result });
83
+ },
84
+ };
85
+ }
86
+ export function buildWipHours(ctx) {
87
+ return {
88
+ title: 'Unposted billable hours (work in progress)',
89
+ input: closedInput(WIP_HOURS_INPUT),
90
+ run: async (args, signal) => {
91
+ const { out, date, zone } = await runZoneDatedReport(ctx, 'WIP hours', 'operations.wipHours', 'dateTo', args, signal);
92
+ if (out.aborted)
93
+ return abortedAnswer(ctx.correlationId);
94
+ const window = out.result?.window;
95
+ return ok('WIP hours returned; hours only, no dollar value; approvedHours/unapprovedHours are null when coverage.approvalData is false (approval not recorded); postedUninvoiced is a sanity metric, not WIP.', { window: { dateFrom: window?.dateFrom, dateTo: date, zone }, result: out.result });
96
+ },
97
+ };
98
+ }
99
+ export function buildNonChargeableWork(ctx) {
100
+ return {
101
+ title: 'Non-chargeable work (non-billable and contract-covered)',
102
+ input: closedInput(NON_CHARGEABLE_WORK_INPUT),
103
+ run: async (args, signal) => {
104
+ const { out, date, zone } = await runZoneDatedReport(ctx, 'non-chargeable work', 'operations.nonChargeableWork', 'dateTo', args, signal);
105
+ if (out.aborted)
106
+ return abortedAnswer(ctx.correlationId);
107
+ const window = out.result?.window;
108
+ return ok('Non-chargeable work returned; no revenue is reported; rows + rowsTruncated + coverage.unresolved = totals; report coverage.unresolved and chargeableLines beside the totals.', { window: { dateFrom: window?.dateFrom, dateTo: date, zone }, result: out.result });
109
+ },
110
+ };
111
+ }
112
+ //# sourceMappingURL=revenue-rollup.js.map