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.
- package/.env.example +123 -0
- package/LICENSE +21 -0
- package/README.md +788 -0
- package/capabilities.json +487 -0
- package/dist/access/gate.d.ts +34 -0
- package/dist/access/gate.js +76 -0
- package/dist/access/grants.d.ts +20 -0
- package/dist/access/grants.js +35 -0
- package/dist/access/write-env.d.ts +41 -0
- package/dist/access/write-env.js +166 -0
- package/dist/auth.d.ts +74 -0
- package/dist/auth.js +129 -0
- package/dist/base-hosts.d.ts +38 -0
- package/dist/base-hosts.js +70 -0
- package/dist/config/load.d.ts +28 -0
- package/dist/config/load.js +105 -0
- package/dist/config/schema.d.ts +166 -0
- package/dist/config/schema.js +311 -0
- package/dist/credential.d.ts +28 -0
- package/dist/credential.js +32 -0
- package/dist/doctor.d.ts +112 -0
- package/dist/doctor.js +154 -0
- package/dist/http-guard.d.ts +57 -0
- package/dist/http-guard.js +134 -0
- package/dist/http.d.ts +50 -0
- package/dist/http.js +290 -0
- package/dist/lifecycle.d.ts +29 -0
- package/dist/lifecycle.js +52 -0
- package/dist/logger.d.ts +26 -0
- package/dist/logger.js +28 -0
- package/dist/main.d.ts +12 -0
- package/dist/main.js +283 -0
- package/dist/policy.d.ts +54 -0
- package/dist/policy.js +80 -0
- package/dist/tools/aggregate.d.ts +16 -0
- package/dist/tools/aggregate.js +64 -0
- package/dist/tools/capabilities-manifest.d.ts +4 -0
- package/dist/tools/capabilities-manifest.js +94 -0
- package/dist/tools/catalog-data.d.ts +116 -0
- package/dist/tools/catalog-data.js +207 -0
- package/dist/tools/clock.d.ts +17 -0
- package/dist/tools/clock.js +43 -0
- package/dist/tools/composites.d.ts +36 -0
- package/dist/tools/composites.js +305 -0
- package/dist/tools/context/client.d.ts +41 -0
- package/dist/tools/context/client.js +139 -0
- package/dist/tools/context/derive.d.ts +9 -0
- package/dist/tools/context/derive.js +32 -0
- package/dist/tools/context/scope.d.ts +24 -0
- package/dist/tools/context/scope.js +180 -0
- package/dist/tools/context/types.d.ts +141 -0
- package/dist/tools/context/types.js +2 -0
- package/dist/tools/dispatch.d.ts +78 -0
- package/dist/tools/dispatch.js +272 -0
- package/dist/tools/field-pointer.d.ts +25 -0
- package/dist/tools/field-pointer.js +45 -0
- package/dist/tools/guide.d.ts +30 -0
- package/dist/tools/guide.js +97 -0
- package/dist/tools/lists.d.ts +9 -0
- package/dist/tools/lists.js +205 -0
- package/dist/tools/meta.d.ts +22 -0
- package/dist/tools/meta.js +709 -0
- package/dist/tools/output-file.d.ts +26 -0
- package/dist/tools/output-file.js +140 -0
- package/dist/tools/rank.d.ts +21 -0
- package/dist/tools/rank.js +57 -0
- package/dist/tools/reasons.d.ts +33 -0
- package/dist/tools/reasons.js +121 -0
- package/dist/tools/register.d.ts +23 -0
- package/dist/tools/register.js +50 -0
- package/dist/tools/resolves.d.ts +28 -0
- package/dist/tools/resolves.js +399 -0
- package/dist/tools/results/envelope.d.ts +55 -0
- package/dist/tools/results/envelope.js +63 -0
- package/dist/tools/results/errors.d.ts +147 -0
- package/dist/tools/results/errors.js +384 -0
- package/dist/tools/results/untrusted.d.ts +129 -0
- package/dist/tools/results/untrusted.js +218 -0
- package/dist/tools/revenue-rollup.d.ts +8 -0
- package/dist/tools/revenue-rollup.js +112 -0
- package/dist/tools/schemas.d.ts +467 -0
- package/dist/tools/schemas.js +444 -0
- package/dist/tools/scope-guard.d.ts +2 -0
- package/dist/tools/scope-guard.js +11 -0
- package/dist/tools/server-version.d.ts +3 -0
- package/dist/tools/server-version.js +14 -0
- package/dist/tools/server.d.ts +92 -0
- package/dist/tools/server.js +170 -0
- package/dist/tools/surface.d.ts +37 -0
- package/dist/tools/surface.js +94 -0
- package/dist/tools/tsv.d.ts +52 -0
- package/dist/tools/tsv.js +95 -0
- package/dist/tools/write/apply.d.ts +40 -0
- package/dist/tools/write/apply.js +500 -0
- package/dist/tools/write/checks.d.ts +39 -0
- package/dist/tools/write/checks.js +137 -0
- package/dist/tools/write/common.d.ts +23 -0
- package/dist/tools/write/common.js +33 -0
- package/dist/tools/write/facts.d.ts +52 -0
- package/dist/tools/write/facts.js +151 -0
- package/dist/tools/write/outcome.d.ts +23 -0
- package/dist/tools/write/outcome.js +67 -0
- package/dist/tools/write/parse.d.ts +37 -0
- package/dist/tools/write/parse.js +166 -0
- package/dist/tools/write/payload.d.ts +44 -0
- package/dist/tools/write/payload.js +119 -0
- package/dist/tools/write/preview.d.ts +3 -0
- package/dist/tools/write/preview.js +317 -0
- package/dist/tools/write/snapshot.d.ts +68 -0
- package/dist/tools/write/snapshot.js +360 -0
- package/dist/tools/write-guidance.d.ts +174 -0
- package/dist/tools/write-guidance.js +317 -0
- package/dist/tools/write.d.ts +9 -0
- package/dist/tools/write.js +10 -0
- package/dist/write/canonical.d.ts +12 -0
- package/dist/write/canonical.js +31 -0
- package/dist/write/evaluate.d.ts +77 -0
- package/dist/write/evaluate.js +91 -0
- package/dist/write/hard-rules.d.ts +49 -0
- package/dist/write/hard-rules.js +48 -0
- package/dist/write/runtime.d.ts +37 -0
- package/dist/write/runtime.js +72 -0
- package/dist/write/store/audit-log.d.ts +13 -0
- package/dist/write/store/audit-log.js +25 -0
- package/dist/write/store/constants.d.ts +34 -0
- package/dist/write/store/constants.js +35 -0
- package/dist/write/store/files.d.ts +44 -0
- package/dist/write/store/files.js +157 -0
- package/dist/write/store/heartbeat.d.ts +9 -0
- package/dist/write/store/heartbeat.js +65 -0
- package/dist/write/store/ledger.d.ts +15 -0
- package/dist/write/store/ledger.js +86 -0
- package/dist/write/store/lifecycle.d.ts +35 -0
- package/dist/write/store/lifecycle.js +114 -0
- package/dist/write/store/lock.d.ts +97 -0
- package/dist/write/store/lock.js +464 -0
- package/dist/write/store/op-lock.d.ts +13 -0
- package/dist/write/store/op-lock.js +175 -0
- package/dist/write/store/plan-store.d.ts +7 -0
- package/dist/write/store/plan-store.js +48 -0
- package/dist/write/store/plans.d.ts +5 -0
- package/dist/write/store/plans.js +19 -0
- package/dist/write/store/types.d.ts +195 -0
- package/dist/write/store/types.js +2 -0
- package/dist/write/store.d.ts +6 -0
- package/dist/write/store.js +182 -0
- package/examples/agentgateway.write-gate.yaml +29 -0
- package/package.json +71 -0
- package/server.json +69 -0
- package/skills/ar-aging.md +65 -0
- package/skills/company-360.md +69 -0
- package/skills/contract-profitability.md +65 -0
- package/skills/crm-management.md +87 -0
- package/skills/filter-semantics.md +75 -0
- package/skills/invoice-export.md +61 -0
- package/skills/log-time-entry.md +77 -0
- package/skills/non-chargeable-work.md +67 -0
- package/skills/portfolio-margin.md +66 -0
- package/skills/recurring-revenue.md +65 -0
- package/skills/revenue-rollup.md +65 -0
- package/skills/slim-reads.md +67 -0
- package/skills/ticket-triage.md +64 -0
- package/skills/unbilled-work-review.md +66 -0
- package/skills/wip-hours.md +68 -0
|
@@ -0,0 +1,709 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* tools/meta.ts — the discovery and generic-read core:
|
|
3
|
+
*
|
|
4
|
+
* - `autotask_catalog` — ranked search over the registry rows, with THIS deployment's verdict per
|
|
5
|
+
* row (what the policy refuses is visible, not discovered by failing); zero wire;
|
|
6
|
+
* - `autotask_describe` — one operation's exact registry record + verdict + the guide playbooks
|
|
7
|
+
* that use it, or one resource's relationship map; zero wire;
|
|
8
|
+
* - `autotask_read` — any read operation by exact key, or up to 10 in one call (`items`: each item
|
|
9
|
+
* through the same gates, per-item results in input order, a refused or failed item in its own
|
|
10
|
+
* slot);
|
|
11
|
+
* - `autotask_tenant_status` — identity, API version and request thresholds (each part degrades
|
|
12
|
+
* on its own);
|
|
13
|
+
*
|
|
14
|
+
* Every handler runs inside the shared frame (`runTool`): closed args, input parse, the
|
|
15
|
+
* fail-closed refusal, then the work, with the SDK error contract mapped on failure.
|
|
16
|
+
*/
|
|
17
|
+
import { AutotaskConfigError } from 'node-autotask';
|
|
18
|
+
import { effectiveRequiredFields } from 'node-autotask/operations';
|
|
19
|
+
import { UDF_MERGE_NOTE, UDF_NONE, UDF_ROWS_NOTE, associationFields, associationRules, caveatNotes, fieldSemanticsNote, constraintNotes, coupledNotes, dateConventionNotes, statusScopeNote, udfDefinitionRows, udfMergeNote, udfMoreNote, udfUnavailable } from './write-guidance.js';
|
|
20
|
+
import { CATALOG, RECORDS, SDK_VERSION, UDF_CAPABLE, opsForTool, recordById, servedToolName, toolForOp, untrustedFieldsOf } from './catalog-data.js';
|
|
21
|
+
import { releaseClientOnError } from './context/derive.js';
|
|
22
|
+
import {} from './context/types.js';
|
|
23
|
+
import { abortedAnswer, FIELD_CATALOG_MAX_BYTES, InputInvalidError, readOneItem, requestSecrets } from './dispatch.js';
|
|
24
|
+
import { zoneClock } from './clock.js';
|
|
25
|
+
import { typedErrorPayload } from './results/errors.js';
|
|
26
|
+
import { markResult, sanitiseVendorOutput } from './results/untrusted.js';
|
|
27
|
+
import { ok } from './results/envelope.js';
|
|
28
|
+
import { bm25Rank } from './rank.js';
|
|
29
|
+
import { playbooksFor } from './guide.js';
|
|
30
|
+
import { FIELD_INFO_EXPENSIVE, fieldLookupCall, udfCatalogCall } from './field-pointer.js';
|
|
31
|
+
import { SERVER_NAME, SERVER_VERSION } from './server-version.js';
|
|
32
|
+
import { CATALOG_INPUT, DESCRIBE_INPUT, AR_AGING_INPUT, WIP_HOURS_INPUT, NON_CHARGEABLE_WORK_INPUT, COMPANY_FULL_PROFILE_INPUT, CONFIGURATION_ITEM_PROFILE_INPUT, CONTACT_FULL_PROFILE_INPUT, CONTRACT_FULL_PROFILE_INPUT, INVOICE_GET_INPUT, PORTFOLIO_MARGIN_INPUT, RECURRING_REVENUE_INPUT, REVENUE_ROLLUP_INPUT, PROJECT_GET_CONTEXT_INPUT, QUERY_INPUT, QUOTE_GET_INPUT, RESOLVE_INPUT, RESOURCE_WORKLOAD_INPUT, SERVICE_CALL_FULL_PROFILE_INPUT, TICKET_FULL_CONTEXT_INPUT, QUERY_LIMIT, READ_INPUT, TENANT_STATUS_INPUT, TENANT_STATUS_PARTS, readIgnoredKeys, closedInput, } from './schemas.js';
|
|
33
|
+
import { refusalReason } from '../policy.js';
|
|
34
|
+
/** Search text per catalog row (key words, the serving tool, purpose), built once. */
|
|
35
|
+
const ROW_TEXT = CATALOG.catalog.map((r) => `${r.operation} ${r.operation.replace(/[._]/g, ' ')} ${toolForOp(r.operation) ?? ''} ${r.purpose ?? ''}`);
|
|
36
|
+
/** `autotask_catalog`: the filtered, ranked, paged registry rows with this deployment's verdicts. */
|
|
37
|
+
export function buildCatalog(ctx) {
|
|
38
|
+
return {
|
|
39
|
+
title: 'Search the Autotask operation catalog',
|
|
40
|
+
input: closedInput(CATALOG_INPUT),
|
|
41
|
+
run: async (raw) => {
|
|
42
|
+
const args = raw;
|
|
43
|
+
// q ranks (BM25 over key, tool, purpose and preferredWhen, best first; #277: most words must
|
|
44
|
+
// match, rows a served tool answers rank up, deprecated rows down); the exact filters then narrow.
|
|
45
|
+
const key = args.q?.trim();
|
|
46
|
+
const boost = (i) => {
|
|
47
|
+
const r = CATALOG.catalog[i];
|
|
48
|
+
return (servedToolName(r, ctx.served) !== null && r.effect === 'read' ? 1.5 : 1) * (r.deprecated === true ? 0.5 : 1);
|
|
49
|
+
};
|
|
50
|
+
const order = args.q === undefined ? CATALOG.catalog.map((_, i) => i) : bm25Rank(ROW_TEXT, args.q, { boost, strict: true });
|
|
51
|
+
// #277: the date-window helpers are hidden unless include_hidden; an exact key always resolves.
|
|
52
|
+
const exact = CATALOG.catalog.findIndex((r) => r.operation === key);
|
|
53
|
+
const ranked = exact >= 0 ? [exact, ...order.filter((i) => i !== exact)] : order;
|
|
54
|
+
const shown = (r) => args.include_hidden === true || r.hidden !== true || r.operation === key;
|
|
55
|
+
const matched = ranked
|
|
56
|
+
.map((i) => CATALOG.catalog[i])
|
|
57
|
+
.filter((r) => {
|
|
58
|
+
if (args.tier !== undefined && r.tier !== args.tier)
|
|
59
|
+
return false;
|
|
60
|
+
if (args.effect !== undefined && r.effect !== args.effect)
|
|
61
|
+
return false;
|
|
62
|
+
if (args.resource !== undefined && r.operation.split('.')[0] !== args.resource)
|
|
63
|
+
return false;
|
|
64
|
+
return true;
|
|
65
|
+
});
|
|
66
|
+
// Only rows this deployment refuses for their EFFECT (writes) are hidden by default;
|
|
67
|
+
// read refusals (credential-minting) stay visible with their policyReason.
|
|
68
|
+
const verdicts = matched.map((r) => ({ r, reason: refusalReason(r.operation, ctx.record(r.operation), ctx.config, ctx.writable) }));
|
|
69
|
+
const isHidden = (v) => v.reason !== null && v.r.effect !== 'read';
|
|
70
|
+
const hiddenRefused = verdicts.filter(isHidden).length;
|
|
71
|
+
const hiddenRows = matched.filter((r) => !shown(r)).length;
|
|
72
|
+
const visible = (args.show_refused ? verdicts : verdicts.filter((v) => !isHidden(v))).filter((v) => shown(v.r));
|
|
73
|
+
const page = visible.slice(args.offset, args.offset + args.limit);
|
|
74
|
+
return ok(`${visible.length} catalog row(s) match${args.q !== undefined ? ', best first' : ''} (rows ${args.offset}-${args.offset + page.length}).${hiddenRefused > 0 && !args.show_refused ? ` ${hiddenRefused} refused write row(s) hidden.` : ''}${hiddenRows > 0 ? ` ${hiddenRows} date-window helper row(s) hidden (include_hidden).` : ''}`, {
|
|
75
|
+
total: matched.length,
|
|
76
|
+
offset: args.offset,
|
|
77
|
+
limit: args.limit,
|
|
78
|
+
hasMore: args.offset + args.limit < visible.length,
|
|
79
|
+
hidden_refused: hiddenRefused,
|
|
80
|
+
compact: args.compact === true,
|
|
81
|
+
rows: page.map(({ r, reason }) => {
|
|
82
|
+
const reachable = r.reachable && reason === null;
|
|
83
|
+
const tool = servedToolName(r, ctx.served);
|
|
84
|
+
if (args.compact === true)
|
|
85
|
+
return { operation: r.operation, tool, effect: r.effect, reachable };
|
|
86
|
+
return {
|
|
87
|
+
operation: r.operation,
|
|
88
|
+
tool,
|
|
89
|
+
purpose: r.operation.endsWith('.getFieldInfo') ? `${r.purpose ?? ''} ${FIELD_INFO_EXPENSIVE}`.trim() : r.purpose,
|
|
90
|
+
effect: r.effect,
|
|
91
|
+
requiredArgs: r.requiredArgs,
|
|
92
|
+
tier: r.tier,
|
|
93
|
+
reachable,
|
|
94
|
+
reachReason: r.reachReason,
|
|
95
|
+
policyReason: reason,
|
|
96
|
+
...(r.deprecated === true ? { deprecated: true } : {}),
|
|
97
|
+
};
|
|
98
|
+
}),
|
|
99
|
+
});
|
|
100
|
+
},
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
/** The zod input of each served tool that wraps registry operations (#76/#81: the per-tool crosswalk source). */
|
|
104
|
+
const TOOL_INPUT = {
|
|
105
|
+
autotask_resolve: RESOLVE_INPUT,
|
|
106
|
+
autotask_describe: DESCRIBE_INPUT,
|
|
107
|
+
autotask_tenant_status: TENANT_STATUS_INPUT,
|
|
108
|
+
autotask_ticket_full_context: TICKET_FULL_CONTEXT_INPUT,
|
|
109
|
+
autotask_company_full_profile: COMPANY_FULL_PROFILE_INPUT,
|
|
110
|
+
autotask_project_get_context: PROJECT_GET_CONTEXT_INPUT,
|
|
111
|
+
autotask_service_call_full_profile: SERVICE_CALL_FULL_PROFILE_INPUT,
|
|
112
|
+
autotask_resource_workload: RESOURCE_WORKLOAD_INPUT,
|
|
113
|
+
autotask_contact_full_profile: CONTACT_FULL_PROFILE_INPUT,
|
|
114
|
+
autotask_configuration_item_profile: CONFIGURATION_ITEM_PROFILE_INPUT,
|
|
115
|
+
autotask_contract_full_profile: CONTRACT_FULL_PROFILE_INPUT,
|
|
116
|
+
autotask_quote_get: QUOTE_GET_INPUT,
|
|
117
|
+
autotask_invoice_get: INVOICE_GET_INPUT,
|
|
118
|
+
autotask_revenue_rollup: REVENUE_ROLLUP_INPUT,
|
|
119
|
+
autotask_portfolio_margin: PORTFOLIO_MARGIN_INPUT,
|
|
120
|
+
autotask_recurring_revenue: RECURRING_REVENUE_INPUT,
|
|
121
|
+
autotask_ar_aging: AR_AGING_INPUT,
|
|
122
|
+
autotask_wip_hours: WIP_HOURS_INPUT,
|
|
123
|
+
autotask_non_chargeable_work: NON_CHARGEABLE_WORK_INPUT,
|
|
124
|
+
};
|
|
125
|
+
/** Tools whose argument SHAPE (not just casing) differs from the SDK call. */
|
|
126
|
+
const SHAPE_NOTES = {
|
|
127
|
+
autotask_resolve: 'flat args, not the SDK identifier + opts bag: identifier -> identifier (positional in every key); by picks the key (ticket_number -> tickets.findByTicketNumber, serial -> configuration_items.findBySerial, email -> contacts.findByEmail, id_or_name -> <resource>.resolve); no resource -> operations.resolveAny (match exact) or operations.searchAcrossResources (match contains), resource companies + match contains -> companies.search; resource tickets + match contains -> tickets.search (title contains; company_id -> companyID); the opts bag is built from expand, include_family (includeFamily), limit and resources',
|
|
128
|
+
autotask_tenant_status: 'parts [identity, version, thresholds, server, time] picks which of resources.whoAmI, version.get, threshold_information.get run, plus zero-wire server and time parts (default all); identity also returns impersonationResourceId; none takes args',
|
|
129
|
+
autotask_contact_full_profile: 'takes only id (+ ticket_limit), no parentId: the tool resolves the contact by id alone',
|
|
130
|
+
autotask_invoice_get: 'format selects the key: record -> invoices.get, html -> invoices.markupHtml, xml -> invoices.markupXml, pdf -> invoices.pdf; output_path is tool-only (writes the export to a file)',
|
|
131
|
+
autotask_revenue_rollup: 'flat args become the SDK opts bag; lastFullMonths is tool-only (1-36, default 12 full months in AUTOTASK_USER_TIMEZONE when both dates are omitted); pass both dates or neither; data.window echoes the dates and zone',
|
|
132
|
+
autotask_portfolio_margin: 'flat args become the SDK opts bag; lastFullMonths is tool-only (1-36, default 12 full months in AUTOTASK_USER_TIMEZONE when both dates are omitted); pass both dates or neither; data.window echoes the dates and zone',
|
|
133
|
+
autotask_recurring_revenue: 'flat args become the SDK opts bag; asOf defaults to today in AUTOTASK_USER_TIMEZONE (the SDK default is UTC); data.asOf echoes the date and zone',
|
|
134
|
+
autotask_ar_aging: 'flat args become the SDK opts bag; asOf defaults to today in AUTOTASK_USER_TIMEZONE (the SDK default is UTC); data.asOf echoes the date and zone',
|
|
135
|
+
autotask_wip_hours: 'flat args become the SDK opts bag; dateTo defaults to today in AUTOTASK_USER_TIMEZONE (the SDK default is UTC), dateFrom to 3 months before it; data.window echoes the dates and zone',
|
|
136
|
+
autotask_non_chargeable_work: 'flat args become the SDK opts bag; dateTo defaults to today in AUTOTASK_USER_TIMEZONE (the SDK default is UTC), dateFrom to 3 months before it; data.window echoes the dates and zone',
|
|
137
|
+
};
|
|
138
|
+
/** Non-casing renames: the SDK's name -> this tool's input key. */
|
|
139
|
+
const ARG_ALIASES = {
|
|
140
|
+
autotask_describe: { resourceKey: 'resource' },
|
|
141
|
+
};
|
|
142
|
+
/** The crosswalk for a non-query tool, derived from its zod input keys; undefined when it has nothing to say. */
|
|
143
|
+
function otherToolNames(tool) {
|
|
144
|
+
const input = tool === undefined ? undefined : TOOL_INPUT[tool];
|
|
145
|
+
if (tool === undefined || input === undefined)
|
|
146
|
+
return undefined;
|
|
147
|
+
const map = { ...ARG_ALIASES[tool] };
|
|
148
|
+
// Only names the backing record(s) document are SDK equivalents; the rest are server-composed, tool-only args.
|
|
149
|
+
const recText = opsForTool(tool).map((op) => JSON.stringify(recordById(op)?.inputSchema ?? {})).join(' ');
|
|
150
|
+
const toolOnly = [];
|
|
151
|
+
for (const snake of Object.keys(input.shape)) {
|
|
152
|
+
const camel = snake.replace(/_([a-z])/g, (_, c) => c.toUpperCase());
|
|
153
|
+
if (camel === snake)
|
|
154
|
+
continue;
|
|
155
|
+
if (recText.includes(camel))
|
|
156
|
+
map[camel] = snake;
|
|
157
|
+
else
|
|
158
|
+
toolOnly.push(snake);
|
|
159
|
+
}
|
|
160
|
+
const shape = SHAPE_NOTES[tool];
|
|
161
|
+
if (shape === undefined && Object.keys(map).length === 0 && toolOnly.length === 0)
|
|
162
|
+
return undefined;
|
|
163
|
+
const base = `${tool} args differ from the SDK call${shape !== undefined ? `: ${shape}` : ''}`;
|
|
164
|
+
const camelNote = Object.keys(map).length > 0 ? ' (SDK opts are camelCase; the camelCase -> snake_case pairs below are the ones the record documents)' : '';
|
|
165
|
+
return {
|
|
166
|
+
note: base + camelNote,
|
|
167
|
+
...map,
|
|
168
|
+
...(toolOnly.length > 0 ? { toolOnly: { args: toolOnly, note: 'server-composed tool-only args: the tool builds these itself, there is no SDK opt of this name' } } : {}),
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* The SDK camelCase param -> autotask_query snake_case arg crosswalk (#76), derived from QUERY_INPUT's own
|
|
173
|
+
* keys (lists.ts maps include_fields -> includeFields, note_chars -> noteChars ...) and kept only for the
|
|
174
|
+
* names the record documents. Undefined when the record is not served by autotask_query.
|
|
175
|
+
*/
|
|
176
|
+
export function paramNames(operation, rec) {
|
|
177
|
+
const tool = toolForOp(operation);
|
|
178
|
+
if (tool !== 'autotask_query')
|
|
179
|
+
return otherToolNames(tool);
|
|
180
|
+
// The record's documented param bag, from the structured inputSchema.*.properties[].name.
|
|
181
|
+
const props = Object.values(rec.inputSchema ?? {}).flatMap((v) => v.properties ?? []);
|
|
182
|
+
const bagKeys = [...new Set(props.map((p) => p.name))];
|
|
183
|
+
const map = {};
|
|
184
|
+
const toolArgs = new Set();
|
|
185
|
+
for (const snake of Object.keys(QUERY_INPUT.shape)) {
|
|
186
|
+
const camel = snake.replace(/_([a-z])/g, (_, c) => c.toUpperCase());
|
|
187
|
+
toolArgs.add(camel);
|
|
188
|
+
if (camel !== snake && bagKeys.includes(camel))
|
|
189
|
+
map[camel] = snake;
|
|
190
|
+
}
|
|
191
|
+
return {
|
|
192
|
+
note: 'the record documents the SDK param bag (camelCase); autotask_query takes these snake_case args',
|
|
193
|
+
...map,
|
|
194
|
+
unsupported: bagKeys.filter((k) => !toolArgs.has(k)),
|
|
195
|
+
toolDefaults: { limit: QUERY_LIMIT.parse(undefined) },
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
/** `autotask_describe`: one operation's record + verdict + playbooks, or one resource's relationship map. */
|
|
199
|
+
export function buildDescribe(ctx) {
|
|
200
|
+
return {
|
|
201
|
+
title: 'Describe one Autotask operation or resource',
|
|
202
|
+
input: closedInput(DESCRIBE_INPUT),
|
|
203
|
+
run: async (raw) => {
|
|
204
|
+
const args = raw;
|
|
205
|
+
if ((args.operation === undefined) === (args.resource === undefined)) {
|
|
206
|
+
throw new InputInvalidError('describe: pass exactly one of operation or resource', 'operation');
|
|
207
|
+
}
|
|
208
|
+
if (args.summary === true && args.operation === undefined) {
|
|
209
|
+
throw new InputInvalidError('describe: summary applies to an operation, not a resource map', 'summary');
|
|
210
|
+
}
|
|
211
|
+
if (args.full === true && (args.operation === undefined || args.summary === true)) {
|
|
212
|
+
throw new InputInvalidError('describe: full applies to an operation record and cannot be combined with summary', 'full');
|
|
213
|
+
}
|
|
214
|
+
const summary = args.summary === true;
|
|
215
|
+
const full = args.full === true;
|
|
216
|
+
if (args.resource !== undefined) {
|
|
217
|
+
const value = await ctx.ops.relationshipMap(ctx.client, args.resource);
|
|
218
|
+
if (value === undefined)
|
|
219
|
+
return abortedAnswer(ctx.correlationId);
|
|
220
|
+
return ok(`Relationship map for "${args.resource}".`, { resource: args.resource, map: projectMap(value), udf: udfBlock(args.resource) });
|
|
221
|
+
}
|
|
222
|
+
const operation = args.operation;
|
|
223
|
+
const rec = ctx.record(operation);
|
|
224
|
+
if (rec === undefined && operation.startsWith('autotask_')) {
|
|
225
|
+
const keys = opsForTool(operation).filter((k) => ctx.record(k) !== undefined);
|
|
226
|
+
if (keys.length === 0 && (operation === 'autotask_read' || operation === 'autotask_write')) {
|
|
227
|
+
throw new AutotaskConfigError(`describe: "${operation}" runs any ${operation === 'autotask_read' ? 'read' : 'write'} key — find one via autotask_catalog, then describe that key`, { operation });
|
|
228
|
+
}
|
|
229
|
+
if (keys.length === 0) {
|
|
230
|
+
throw new AutotaskConfigError(`describe: "${operation}" is not a tool that projects registry operations (find the exact key with autotask_catalog)`, { operation });
|
|
231
|
+
}
|
|
232
|
+
if (keys.length === 1)
|
|
233
|
+
return describeRecord(ctx, keys[0], operation, summary, full);
|
|
234
|
+
const byOp = new Map(CATALOG.catalog.map((r) => [r.operation, r]));
|
|
235
|
+
// One row per registry key (built from `keys`, so none can be dropped); the catalog row only enriches.
|
|
236
|
+
const rows = keys.map((k) => {
|
|
237
|
+
const r = byOp.get(k);
|
|
238
|
+
return {
|
|
239
|
+
operation: k,
|
|
240
|
+
purpose: r?.purpose ?? null,
|
|
241
|
+
effect: r?.effect ?? ctx.record(k).effect,
|
|
242
|
+
requiredArgs: r?.requiredArgs ?? [],
|
|
243
|
+
reachable: (r?.reachable ?? true) && refusalReason(k, ctx.record(k), ctx.config, ctx.writable) === null,
|
|
244
|
+
};
|
|
245
|
+
});
|
|
246
|
+
return ok(`"${operation}" serves ${keys.length} registry keys; pass one as operation for its full record.`, {
|
|
247
|
+
tool: operation,
|
|
248
|
+
...toolServed(ctx, operation),
|
|
249
|
+
operations: rows,
|
|
250
|
+
paramNames: paramNames(keys[0], ctx.record(keys[0])),
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
if (rec === undefined) {
|
|
254
|
+
throw new AutotaskConfigError(`describe: unknown operation "${operation}" — it is not in the capability registry (find the exact key with autotask_catalog)`, { operation });
|
|
255
|
+
}
|
|
256
|
+
return describeRecord(ctx, operation, undefined, summary, full);
|
|
257
|
+
},
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
/** Whether this deployment's tools/list carries the tool; when not, the keys still run through autotask_read. */
|
|
261
|
+
function toolServed(ctx, tool) {
|
|
262
|
+
const served = ctx.served.has(tool);
|
|
263
|
+
return served ? { tool_served: true } : { tool_served: false, tool_served_note: `"${tool}" is not in this deployment's tools/list; run the keys via autotask_read` };
|
|
264
|
+
}
|
|
265
|
+
/** Default notes the read path applies that the registry record does not advertise (the pinned SDK's own read-path defaults, and the `READ_INPUT` numeric `limit`/`latest` coercion). */
|
|
266
|
+
const SERVER_DEFAULTS = {
|
|
267
|
+
'operations.fieldCatalog': `via autotask_read: SDK compact default unless fields or labels:true is set; fields requests default labels true; maxBytes ${FIELD_CATALOG_MAX_BYTES} (truncated + truncation when cut); any value you pass wins`,
|
|
268
|
+
'contracts.profitability': 'via autotask_read: the SDK defaults the window to the last full calendar month (UTC) when both dates are omitted (the result\'s `period` carries `defaulted` + a note) and refuses a half window with the typed `CONFIG_ERROR` (zero wire); the server passes the SDK\'s error codes through unchanged',
|
|
269
|
+
};
|
|
270
|
+
/** AC27 (#183): a vendor entity with no create in the registry (live case: invoices) says so on its reads, mirroring
|
|
271
|
+
* the served no-DELETE `deleteBoundary` data; a "raise an invoice" question gets answered, not hunted. Zero wire.
|
|
272
|
+
* Entity test: the resource has `getEntityInfo` (the vendor entityInformation channel), which excludes
|
|
273
|
+
* `operations` and the helper endpoints (authenticate, version, zone_information, modules, ...). Evidence: the
|
|
274
|
+
* registry carries no create for these, and the vendor swagger the SDK plan is verified against documents no
|
|
275
|
+
* create verb for any of them (collection path, /Parent/{id}/Child paths and *_CreateEntity operationIds checked,
|
|
276
|
+
* node-autotask 0.34.0; method in docs/architecture.md). The note claims no more than that. */
|
|
277
|
+
const CREATE_RESOURCES = new Set(RECORDS.filter((r) => r.id.endsWith('.create')).map((r) => r.resource));
|
|
278
|
+
const ENTITY_RESOURCES = new Set(RECORDS.filter((r) => r.id.endsWith('.getEntityInfo')).map((r) => r.resource));
|
|
279
|
+
/** The single place to extend: entities the registry has no create for, yet the vendor documentation lists one, so the
|
|
280
|
+
* note would be false. `time_off_requests`: the swagger has a child create (POST /V1.0/Resources/{parentId}/TimeOffRequests,
|
|
281
|
+
* TimeOffRequestsChild_CreateEntity) and the SDK defines TimeOffRequestCreate; the SDK plan simply has no create row. */
|
|
282
|
+
export const NO_CREATE_EXCLUDED = new Set(['time_off_requests']);
|
|
283
|
+
/** The entities that carry the noCreate note (pinned by name in a test). */
|
|
284
|
+
export const NO_CREATE_ENTITIES = new Set([...ENTITY_RESOURCES].filter((r) => !CREATE_RESOURCES.has(r) && !NO_CREATE_EXCLUDED.has(r)));
|
|
285
|
+
const NO_CREATE_NOTE = 'do not look for a create operation: this server has none for this entity, and the vendor API documentation lists none.';
|
|
286
|
+
/**
|
|
287
|
+
* S8 (#183): the UDF block for `describe {resource}`: the mechanism facts (SDK row shape) + the definitions
|
|
288
|
+
* pointer. Zero wire: the capability fact is the registry itself (UDF_CAPABLE: the resources whose records
|
|
289
|
+
* carry the published udfCapable flag, SDK 0.37.0 #254; SDK 0.34.0 #219 N7), and the definitions are the live tenant
|
|
290
|
+
* read the pointer names (the scoped fieldCatalog read with the `udf` include).
|
|
291
|
+
*/
|
|
292
|
+
function udfBlock(resource) {
|
|
293
|
+
if (!UDF_CAPABLE.has(resource))
|
|
294
|
+
return 'not udf-capable';
|
|
295
|
+
return {
|
|
296
|
+
udfFilter: 'udf-marker',
|
|
297
|
+
udfFilterNote: 'a filter on a UDF name is accepted by the vendor only with a condition carrying udf:true (max 1 such condition per query); UDF names are tenant-specific and never in the field set',
|
|
298
|
+
udfWriteShape: 'merge',
|
|
299
|
+
mergeNote: UDF_MERGE_NOTE,
|
|
300
|
+
definitions: `${udfCatalogCall(resource)} serves the UDF definition rows (name, label, type, isRequired, isReadOnly, isPickList, referenceEntityType, picklistValues); live read — the SDK plan carries no UDF definition`,
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* AC12: the served `udfFields` of a udfCapable create/update: fixed-column rows as data, or a fixed sentence.
|
|
305
|
+
* autotask_describe is not a vendor-output tool (the register-time sanitiser skips it), so the vendor-authored
|
|
306
|
+
* strings (name, label, and the one picklist string per row) are cleaned, capped and wrapped here by the same
|
|
307
|
+
* choke point the read tools use: one wrapper per string, so no row can break out of its own. The fixed
|
|
308
|
+
* sentences are server prose and are never wrapped.
|
|
309
|
+
*/
|
|
310
|
+
function servedUdfFields(raw, readCall) {
|
|
311
|
+
if (raw.length === 0)
|
|
312
|
+
return UDF_NONE;
|
|
313
|
+
const { total, rows, moreValues } = udfDefinitionRows(raw);
|
|
314
|
+
return {
|
|
315
|
+
note: UDF_ROWS_NOTE,
|
|
316
|
+
...(total > rows.length ? { total, shown: rows.length } : {}),
|
|
317
|
+
...(moreValues ? { moreNote: udfMoreNote(readCall) } : {}),
|
|
318
|
+
fields: sanitiseVendorOutput(markResult(rows, ['name', 'label', 'picklist'])),
|
|
319
|
+
};
|
|
320
|
+
}
|
|
321
|
+
/**
|
|
322
|
+
* MCP-shaped guidance for one operation, placed BEFORE the SDK record (#109): the record's own
|
|
323
|
+
* `examples` are SDK JavaScript and its query grammar sits after long caveats. Queries get an `autotask_read` example; create/update get the required and read-only field names
|
|
324
|
+
* from `operations.fieldCatalog` (one governed read, served from the SDK field cache when warm;
|
|
325
|
+
* `unavailable` when the read fails or the operation is not reachable here, never an error) and an `autotask_write` example.
|
|
326
|
+
*/
|
|
327
|
+
async function guidanceFor(ctx, rec, reachable) {
|
|
328
|
+
const op = rec.id.slice(rec.resource.length + 1);
|
|
329
|
+
if (rec.effect === 'read' && op === 'query') {
|
|
330
|
+
return {
|
|
331
|
+
exampleArgs: [{ filter: [{ field: 'id', op: 'gt', value: 0 }], limit: 10 }],
|
|
332
|
+
example: `autotask_read {operation:"${rec.id}", args:[{filter:[{field:"id",op:"gt",value:0}],limit:10}]}`,
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
if (op === 'getFieldInfo' && rec.effect === 'read') {
|
|
336
|
+
return { expensive: FIELD_INFO_EXPENSIVE, instead: fieldLookupCall(rec.resource) };
|
|
337
|
+
}
|
|
338
|
+
if (rec.id === 'time_entries.dateWorkedWindow') {
|
|
339
|
+
// #173: the positional [from, to, opts] mixes types; the same window as one uniform-string filter
|
|
340
|
+
return {
|
|
341
|
+
exampleArgs: ['2026-10-20', '2026-10-22', { resourceID: 123 }],
|
|
342
|
+
sameWindowAsQuery: 'autotask_query {resource:"time_entries", filter:[{field:"resourceID",op:"eq",value:"123"},{field:"dateWorked",op:"gte",value:"2026-10-20"},{field:"dateWorked",op:"lte",value:"2026-10-22"}], limit:500}: the same rows up to limit (one window call returns at most 500 and a nextCursor to pass as cursor for the rest; dateWorked is a date, both days inclusive), without the posted counts, for a client that cannot send a mixed-type array.',
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
if (op === 'moveToTicket') {
|
|
346
|
+
// the move ops (#107): zero wire, a pointer to the governed path
|
|
347
|
+
return {
|
|
348
|
+
exampleArgs: [0, 0],
|
|
349
|
+
example: `autotask_write {operation:"${rec.id}", args:[<sourceId>, <toTicketId>]}, then autotask_apply_destructive (a company or contract change) or autotask_apply, as the preview names, with {plan, operation, targets, summary} copied from the preview approval`,
|
|
350
|
+
note: 'Args are [sourceId, toTicketId]; nothing else can be changed. The record is created on the target ticket and the original deleted (new id, new create date and creator; notifications may fire). AUTOTASK_WRITE must list this operation; a company or contract change needs a person to confirm it. Previews write nothing.',
|
|
351
|
+
};
|
|
352
|
+
}
|
|
353
|
+
if (rec.effect !== 'write' || (op !== 'create' && op !== 'update'))
|
|
354
|
+
return undefined;
|
|
355
|
+
let required;
|
|
356
|
+
let readOnly;
|
|
357
|
+
let requiredFrom;
|
|
358
|
+
let unproven = false;
|
|
359
|
+
let conditional;
|
|
360
|
+
let assoc = [];
|
|
361
|
+
let derived;
|
|
362
|
+
let facts;
|
|
363
|
+
let hasQuirks = false;
|
|
364
|
+
let statusScope;
|
|
365
|
+
let udfFields;
|
|
366
|
+
const udfCapable = UDF_CAPABLE.has(rec.resource);
|
|
367
|
+
try {
|
|
368
|
+
if (!reachable)
|
|
369
|
+
throw new Error('not reachable: no wire is spent describing an operation this deployment refuses');
|
|
370
|
+
const res = (await ctx.ops.invokeRead(ctx.client, 'operations.fieldCatalog', [{ resources: [rec.resource], ...(udfCapable ? { include: ['fields', 'udf'] } : {}), labels: true }]));
|
|
371
|
+
const row = res?.rows?.find((r) => r.resource === rec.resource);
|
|
372
|
+
const fields = row?.fields;
|
|
373
|
+
if (fields !== undefined) {
|
|
374
|
+
const spec = fields.filter((f) => f.isRequired === true && f.isReadOnly !== true).map((f) => f.name);
|
|
375
|
+
// The SDK's one precedence (live-proven > zone > spec) is a create fact; an update keeps the vendor's own set.
|
|
376
|
+
const zone = op === 'create' ? await zoneFactsOf(ctx, rec.resource) : undefined;
|
|
377
|
+
facts = zone?.createGuidance ?? undefined;
|
|
378
|
+
// quirk statements are SDK free text: none is served on a create, only a pointer, and only when a quirk
|
|
379
|
+
// names the create op (SDK 0.37.0 #253 structured quirks; #224)
|
|
380
|
+
hasQuirks = (zone?.quirks ?? []).some((q) => Array.isArray(q?.ops) && q.ops.includes('create'));
|
|
381
|
+
const eff = op === 'create' ? effectiveRequiredFields({ requiredFields: spec }, zone) : { fields: spec, from: 'spec', unproven: true };
|
|
382
|
+
// eff.fields is already the unconditional set (value-gated fields are in eff.conditional, SDK 0.34.0)
|
|
383
|
+
required = eff.fields;
|
|
384
|
+
conditional = 'conditional' in eff ? eff.conditional : undefined;
|
|
385
|
+
// an unproven plan prefix is not 'live-proven': say so rather than label it
|
|
386
|
+
unproven = op === 'create' && eff.unproven === true && eff.from === 'live-proven';
|
|
387
|
+
requiredFrom = unproven ? 'unproven-prefix' : eff.from;
|
|
388
|
+
// a vendor-read-only field that a create demands (contracts.contractType) is read-only for update only
|
|
389
|
+
readOnly = fields.filter((f) => f.isReadOnly === true && !(op === 'create' && required.includes(f.name))).map((f) => f.name);
|
|
390
|
+
assoc = associationFields(fields, required, { resource: rec.resource, op, parentCompany: facts?.parentCompany });
|
|
391
|
+
derived = row?.derivedFields;
|
|
392
|
+
statusScope = statusScopeNote(rec.resource, fields);
|
|
393
|
+
// AC12: the UDF definitions ride the same one read (no second call). The SDK field cache never stores an empty
|
|
394
|
+
// result, so an entity with no UDFs is one uncached GET per describe (two metadata calls with AUTOTASK_CACHE=off).
|
|
395
|
+
if (udfCapable)
|
|
396
|
+
udfFields = Array.isArray(row?.udf) ? servedUdfFields(row.udf, udfCatalogCall(rec.resource)) : udfUnavailable(udfCatalogCall(rec.resource));
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
catch {
|
|
400
|
+
// unavailable: reported below, the describe itself still answers
|
|
401
|
+
}
|
|
402
|
+
if (udfCapable && udfFields === undefined)
|
|
403
|
+
udfFields = udfUnavailable(udfCatalogCall(rec.resource));
|
|
404
|
+
const data = Object.fromEntries((required ?? []).map((f) => [f, '<value>']));
|
|
405
|
+
const exampleArgs = op === 'create' ? [data] : [0, { '<field>': '<value>' }];
|
|
406
|
+
const constraints = [...coupledNotes(rec.resource), ...constraintNotes(op, facts, derived, rec.resource), ...dateConventionNotes(rec.resource), ...udfMergeNote(op === 'update' && UDF_CAPABLE.has(rec.resource)), ...(statusScope !== undefined ? [statusScope] : [])];
|
|
407
|
+
const caveats = caveatNotes(rec.metadata?.caveats);
|
|
408
|
+
// a create the SDK marks unsatisfiable for any input gets no example to copy
|
|
409
|
+
const unsatisfiable = op === 'create' && facts?.blocker?.unsatisfiableViaApi === true;
|
|
410
|
+
return {
|
|
411
|
+
requiredFields: required ?? 'unavailable',
|
|
412
|
+
...(requiredFrom !== undefined ? { requiredFieldsFrom: requiredFrom } : {}),
|
|
413
|
+
...(unproven ? { requiredFieldsUnproven: true } : {}),
|
|
414
|
+
readOnlyFields: readOnly ?? 'unavailable',
|
|
415
|
+
...(required === undefined ? { fieldsNote: `field metadata could not be read; call autotask_read {operation:"operations.fieldCatalog", args:[{resources:["${rec.resource}"]}]}` } : {}),
|
|
416
|
+
...(conditional !== undefined ? { requiredFieldsConditional: conditional } : {}),
|
|
417
|
+
...(unsatisfiable ? { createUnsatisfiableViaApi: true } : { exampleArgs, example: `autotask_write {operation:"${rec.id}", args:${JSON.stringify(exampleArgs)}}` }),
|
|
418
|
+
note: `${op === 'create' ? 'Required fields can be wider than the vendor marks (see the playbooks).' : 'Update args are [id, {fields}]; send only the fields to change.'} Previews write nothing.`,
|
|
419
|
+
...(caveats.length > 0 ? { caveats } : {}),
|
|
420
|
+
...(constraints.length > 0 ? { constraints } : {}),
|
|
421
|
+
...(hasQuirks ? { quirksPointer: `known vendor quirks of this resource: autotask_describe {resource:"${rec.resource}"}.` } : {}),
|
|
422
|
+
...(assoc.length > 0
|
|
423
|
+
? {
|
|
424
|
+
associationFields: assoc,
|
|
425
|
+
associationRules: associationRules(assoc),
|
|
426
|
+
}
|
|
427
|
+
: {}),
|
|
428
|
+
...(udfFields !== undefined ? { udfFields } : {}),
|
|
429
|
+
};
|
|
430
|
+
}
|
|
431
|
+
/** The plan-pinned zone facts of one resource (zero wire), or undefined when none are pinned or the map is unreadable. */
|
|
432
|
+
async function zoneFactsOf(ctx, resource) {
|
|
433
|
+
try {
|
|
434
|
+
const map = (await ctx.ops.relationshipMap(ctx.client, resource));
|
|
435
|
+
return map?.zoneFacts ?? undefined;
|
|
436
|
+
}
|
|
437
|
+
catch {
|
|
438
|
+
return undefined;
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
/** The one read envelope of autotask_read (#97), served on the on-demand surface. */
|
|
442
|
+
const READ_ENVELOPE = 'data = { results: Slot[], ok: <count>, failed: <count>, budget?, budgetWarning? }, always an array in input order, one slot for a single read. Slot = { ok: true, operation, result, scopeNote? } or { ok: false, operation, error }. A single read that fails still answers the whole-call error envelope.';
|
|
443
|
+
/** Served relationship map without the SDK's free text: createGuidance loses `vendorEvidence` and
|
|
444
|
+
* `blocker.message`/`remedy`; each structured `zoneFacts.quirks` entry loses `evidence` (SDK 0.37.0 #253). The SDK
|
|
445
|
+
* ships no maintainer provenance since node-autotask 0.48.0 (#379), so nothing else is scrubbed (#255). */
|
|
446
|
+
function projectMap(map) {
|
|
447
|
+
const m = map;
|
|
448
|
+
const z = m?.zoneFacts;
|
|
449
|
+
if (z === undefined || z === null || typeof z !== 'object')
|
|
450
|
+
return map;
|
|
451
|
+
const zone = { ...z };
|
|
452
|
+
if (Array.isArray(z.quirks)) {
|
|
453
|
+
zone.quirks = z.quirks.map((q) => {
|
|
454
|
+
if (q === null || typeof q !== 'object')
|
|
455
|
+
return q;
|
|
456
|
+
const row = { ...q };
|
|
457
|
+
delete row.evidence;
|
|
458
|
+
return row;
|
|
459
|
+
});
|
|
460
|
+
}
|
|
461
|
+
const g = z.createGuidance;
|
|
462
|
+
if (g !== undefined && g !== null && typeof g === 'object') {
|
|
463
|
+
const slim = { ...g };
|
|
464
|
+
delete slim.vendorEvidence;
|
|
465
|
+
if (slim.blocker !== null && typeof slim.blocker === 'object') {
|
|
466
|
+
const b = { ...slim.blocker };
|
|
467
|
+
delete b.message;
|
|
468
|
+
delete b.remedy;
|
|
469
|
+
slim.blocker = b;
|
|
470
|
+
}
|
|
471
|
+
zone.createGuidance = slim;
|
|
472
|
+
}
|
|
473
|
+
return { ...m, zoneFacts: zone };
|
|
474
|
+
}
|
|
475
|
+
/** Served record: `metadata.caveats` rows keep kind/fields/remedyOp, not the SDK's free-text `note` (a known kind gets the server's sentence instead). */
|
|
476
|
+
function projectCaveats(rec) {
|
|
477
|
+
const md = rec.metadata;
|
|
478
|
+
if (md === undefined || md === null || !Array.isArray(md.caveats))
|
|
479
|
+
return rec;
|
|
480
|
+
const caveats = md.caveats.map((c) => {
|
|
481
|
+
if (c === null || typeof c !== 'object')
|
|
482
|
+
return c;
|
|
483
|
+
const row = { ...c };
|
|
484
|
+
delete row.note;
|
|
485
|
+
// #282: the hours caveat gets the server's own sentence (the SDK note is free text, never served)
|
|
486
|
+
const semantics = fieldSemanticsNote(row);
|
|
487
|
+
return semantics !== undefined ? { ...row, note: semantics } : row;
|
|
488
|
+
});
|
|
489
|
+
return { ...rec, metadata: { ...md, caveats } };
|
|
490
|
+
}
|
|
491
|
+
/** AC24 (#183): the SDK's create-usage sentence claims the full record is not returned, but the server's
|
|
492
|
+
* write envelope serves the created record back as `data.record` (the respond phase of
|
|
493
|
+
* src/tools/write/apply.ts), so no follow-up get is needed. The pinned SDK keeps its sentence, so
|
|
494
|
+
* the correction is server-composed at serve time — one template, both describe paths. */
|
|
495
|
+
const CREATE_USAGE_FALSE = 'the full record is not returned — follow up with get where needed.';
|
|
496
|
+
const CREATE_USAGE_TRUE = 'the record is read back as data.record (absent on a replay or when the vendor returns no id, null if the read-back fails).';
|
|
497
|
+
/** The served `metadata.usage`, with the create correction applied. */
|
|
498
|
+
function servedUsage(rec) {
|
|
499
|
+
const u = rec.metadata?.usage;
|
|
500
|
+
if (typeof u !== 'string')
|
|
501
|
+
return undefined;
|
|
502
|
+
// the read-back is one `<resource>.get`: a create with no get in the registry answers `data.record: null`
|
|
503
|
+
return u.includes(CREATE_USAGE_FALSE) && recordById(`${rec.resource}.get`) !== undefined ? u.replace(CREATE_USAGE_FALSE, CREATE_USAGE_TRUE) : u;
|
|
504
|
+
}
|
|
505
|
+
/** Served record: caveats projected, the create usage corrected (AC24) and the SDK's own test list dropped. */
|
|
506
|
+
function servedRecord(rec) {
|
|
507
|
+
const projected = { ...projectCaveats(rec) };
|
|
508
|
+
delete projected.tests;
|
|
509
|
+
const md = projected.metadata;
|
|
510
|
+
const usage = servedUsage(rec);
|
|
511
|
+
const out = typeof md?.usage !== 'string' || usage === undefined || md.usage === usage ? projected : { ...projected, metadata: { ...md, usage } };
|
|
512
|
+
return out;
|
|
513
|
+
}
|
|
514
|
+
/** The per-field caps of a describe summary (characters): purpose, args and usage only, about 2 KB in all (#197). */
|
|
515
|
+
const SUMMARY_CAPS = { purpose: 500, args: 600, usage: 400 };
|
|
516
|
+
/** `text` cut at a word boundary to at most `max` characters, with an ellipsis; `cut` records the field name when it was. */
|
|
517
|
+
function capText(text, max, name, cut) {
|
|
518
|
+
if (text.length <= max)
|
|
519
|
+
return text;
|
|
520
|
+
cut.push(name);
|
|
521
|
+
const head = text.slice(0, max - 1);
|
|
522
|
+
const space = head.lastIndexOf(' ');
|
|
523
|
+
return `${(space > max / 2 ? head.slice(0, space) : head).trimEnd()}\u2026`;
|
|
524
|
+
}
|
|
525
|
+
/** `autotask_describe {summary: true}`: the registry's purpose, args and usage text and the verdict; no examples, errors, tests or playbooks. */
|
|
526
|
+
function summariseRecord(ctx, operation, viaTool) {
|
|
527
|
+
const rec = ctx.record(operation);
|
|
528
|
+
const reason = refusalReason(operation, rec, ctx.config, ctx.writable);
|
|
529
|
+
const md = (rec.metadata ?? {});
|
|
530
|
+
const row = CATALOG.catalog.find((r) => r.operation === operation);
|
|
531
|
+
const text = (v) => (typeof v === 'string' ? v : '');
|
|
532
|
+
const cut = [];
|
|
533
|
+
const tool = viaTool ?? toolForOp(operation);
|
|
534
|
+
return ok(`Summary of "${rec.id}" (purpose, args, usage).`, {
|
|
535
|
+
operation: rec.id,
|
|
536
|
+
...(tool !== undefined ? { tool, ...toolServed(ctx, tool) } : {}),
|
|
537
|
+
purpose: capText(text(md.purpose) || text(row?.purpose), SUMMARY_CAPS.purpose, 'purpose', cut),
|
|
538
|
+
requiredArgs: row?.requiredArgs ?? [],
|
|
539
|
+
args: capText(text(md.args), SUMMARY_CAPS.args, 'args', cut),
|
|
540
|
+
usage: capText(text(servedUsage(rec)), SUMMARY_CAPS.usage, 'usage', cut),
|
|
541
|
+
reachable: reason === null,
|
|
542
|
+
why_not: reason,
|
|
543
|
+
summary: { cut, full: 'omit summary for the full record (examples, errors, playbooks).' },
|
|
544
|
+
});
|
|
545
|
+
}
|
|
546
|
+
/** #226: record keys a model does not need to call the operation (transport and retry detail); `full: true` serves them. `flags` stays (sensitive, requiresApproval). */
|
|
547
|
+
const SLIM_DROP = ['retry', 'staleCheck', 'inputSchemaStrict', 'pagination', 'resolution', 'envelope', 'compact', 'status', 'dryRun', 'permissions'];
|
|
548
|
+
/** #226: the slim record's caps: long prose fields (characters) and examples (count). */
|
|
549
|
+
const SLIM_CAPS = { usage: 1200, args: 1500, examples: 2 };
|
|
550
|
+
/** The default (slim) served record (#226): transport detail dropped, long usage/args prose cut at a word, the first examples; `cut` names what was cut. */
|
|
551
|
+
function slimServedRecord(rec, cut) {
|
|
552
|
+
const out = { ...servedRecord(rec) };
|
|
553
|
+
for (const k of SLIM_DROP)
|
|
554
|
+
delete out[k];
|
|
555
|
+
if (Array.isArray(out.examples) && out.examples.length > SLIM_CAPS.examples) {
|
|
556
|
+
out.examples = out.examples.slice(0, SLIM_CAPS.examples);
|
|
557
|
+
cut.push('examples');
|
|
558
|
+
}
|
|
559
|
+
const md = out.metadata;
|
|
560
|
+
if (md !== undefined) {
|
|
561
|
+
const next = { ...md };
|
|
562
|
+
for (const f of ['usage', 'args'])
|
|
563
|
+
if (typeof next[f] === 'string')
|
|
564
|
+
next[f] = capText(next[f], SLIM_CAPS[f], f, cut);
|
|
565
|
+
out.metadata = next;
|
|
566
|
+
}
|
|
567
|
+
return out;
|
|
568
|
+
}
|
|
569
|
+
/** One registry record + verdict + playbooks (+ the snake_case crosswalk when served by autotask_query). */
|
|
570
|
+
async function describeRecord(ctx, operation, viaTool, summary = false, full = false) {
|
|
571
|
+
if (summary)
|
|
572
|
+
return summariseRecord(ctx, operation, viaTool);
|
|
573
|
+
const rec = ctx.record(operation);
|
|
574
|
+
const reason = refusalReason(operation, rec, ctx.config, ctx.writable);
|
|
575
|
+
const guidance = await guidanceFor(ctx, rec, reason === null);
|
|
576
|
+
const names = paramNames(operation, rec);
|
|
577
|
+
const cut = [];
|
|
578
|
+
return ok(`Registry record for "${rec.id}".`, {
|
|
579
|
+
...(viaTool !== undefined ? { tool: viaTool, ...toolServed(ctx, viaTool) } : {}),
|
|
580
|
+
operation: rec.id,
|
|
581
|
+
...(guidance !== undefined ? { guidance } : {}),
|
|
582
|
+
...(rec.effect === 'read' && viaTool === undefined && !rec.id.endsWith('.query') ? { readEnvelope: READ_ENVELOPE } : {}),
|
|
583
|
+
record: { ...(full ? servedRecord(rec) : slimServedRecord(rec, cut)), untrustedFields: untrustedFieldsOf(rec) },
|
|
584
|
+
...(full ? {} : { detail: { cut, full: 'full: true serves the complete record (retry, paging and transport detail, every example, uncut text).' } }),
|
|
585
|
+
...(rec.effect === 'read' && NO_CREATE_ENTITIES.has(rec.resource) ? { noCreate: NO_CREATE_NOTE } : {}),
|
|
586
|
+
reachable: reason === null,
|
|
587
|
+
why_not: reason,
|
|
588
|
+
playbooks: playbooksFor(rec.id),
|
|
589
|
+
...(SERVER_DEFAULTS[rec.id] !== undefined ? { serverDefaults: SERVER_DEFAULTS[rec.id] } : {}),
|
|
590
|
+
...(names !== undefined ? { paramNames: names } : {}),
|
|
591
|
+
});
|
|
592
|
+
}
|
|
593
|
+
/** `autotask_read`: one read by exact key, or up to 10 (`items`) with per-item results. */
|
|
594
|
+
export function buildRead(ctx) {
|
|
595
|
+
return {
|
|
596
|
+
title: 'Run Autotask read operations by exact key',
|
|
597
|
+
input: closedInput(READ_INPUT, readIgnoredKeys),
|
|
598
|
+
run: async (raw, signal) => {
|
|
599
|
+
const args = raw;
|
|
600
|
+
if ((args.operation === undefined) === (args.items === undefined)) {
|
|
601
|
+
throw new InputInvalidError('read: pass exactly one of operation (with args) or items', 'operation');
|
|
602
|
+
}
|
|
603
|
+
if (args.operation !== undefined) {
|
|
604
|
+
const out = await readOneItem(ctx, args.operation, args.args, signal);
|
|
605
|
+
if (out.aborted)
|
|
606
|
+
return abortedAnswer(ctx.correlationId);
|
|
607
|
+
// ONE envelope for every read mode (#97): a single read is a one-slot `results`
|
|
608
|
+
const slot = { ok: true, operation: args.operation, result: out.result, ...(out.scopeNote !== undefined ? { scopeNote: out.scopeNote } : {}) };
|
|
609
|
+
return ok(`Executed "${args.operation}".`, { results: [slot], ok: 1, failed: 0 });
|
|
610
|
+
}
|
|
611
|
+
const items = args.items;
|
|
612
|
+
// The local per-credential window, zero wire. Over it: WARN only (the limiter waits within
|
|
613
|
+
// the call deadline; a hard refuse would break callers exactly when the window frees).
|
|
614
|
+
const budget = await ctx.ops.hourlyBudget(ctx.client);
|
|
615
|
+
const overWindow = budget !== undefined && items.length > budget.remaining;
|
|
616
|
+
let aborted = false;
|
|
617
|
+
const results = await Promise.all(items.map(async (item) => {
|
|
618
|
+
try {
|
|
619
|
+
const out = await readOneItem(ctx, item.operation, item.args, signal);
|
|
620
|
+
if (out.aborted)
|
|
621
|
+
aborted = true;
|
|
622
|
+
return { ok: true, operation: item.operation, result: out.result, ...(out.scopeNote !== undefined ? { scopeNote: out.scopeNote } : {}) };
|
|
623
|
+
}
|
|
624
|
+
catch (err) {
|
|
625
|
+
releaseClientOnError(ctx, err);
|
|
626
|
+
return { ok: false, operation: item.operation, error: typedErrorPayload(err, ctx.correlationId, requestSecrets(ctx)) };
|
|
627
|
+
}
|
|
628
|
+
}));
|
|
629
|
+
// A cancelled request answers the typed cancellation for the WHOLE call.
|
|
630
|
+
if (aborted)
|
|
631
|
+
return abortedAnswer(ctx.correlationId);
|
|
632
|
+
const succeeded = results.filter((r) => r.ok).length;
|
|
633
|
+
return ok(`${succeeded}/${results.length} item(s) succeeded.`, {
|
|
634
|
+
results,
|
|
635
|
+
ok: succeeded,
|
|
636
|
+
failed: results.length - succeeded,
|
|
637
|
+
...(overWindow
|
|
638
|
+
? {
|
|
639
|
+
budget,
|
|
640
|
+
budgetWarning: `${items.length} items exceed the ${budget.remaining} remaining local request(s) of this client's sliding hour — warn only: the call still runs (the limiter waits within the call deadline; a budget that cannot be met in time surfaces RATE_LIMITED with retryAfter).`,
|
|
641
|
+
}
|
|
642
|
+
: {}),
|
|
643
|
+
});
|
|
644
|
+
},
|
|
645
|
+
};
|
|
646
|
+
}
|
|
647
|
+
/** The tenant_status part -> backing operation. */
|
|
648
|
+
const STATUS_OPS = {
|
|
649
|
+
identity: 'resources.whoAmI',
|
|
650
|
+
version: 'version.get',
|
|
651
|
+
thresholds: 'threshold_information.get',
|
|
652
|
+
};
|
|
653
|
+
/** `autotask_tenant_status`: identity / version / thresholds / server / time; each part degrades to typed absent. */
|
|
654
|
+
export function buildTenantStatus(ctx) {
|
|
655
|
+
return {
|
|
656
|
+
title: 'Show the Autotask tenant identity, API version, thresholds and server version',
|
|
657
|
+
input: closedInput(TENANT_STATUS_INPUT),
|
|
658
|
+
run: async (raw, signal) => {
|
|
659
|
+
const args = raw;
|
|
660
|
+
const parts = [...new Set(args.parts)];
|
|
661
|
+
const data = {};
|
|
662
|
+
let firstError;
|
|
663
|
+
// whoAmI is the API user; the resource entries are logged as is the impersonation id (null: none). Zero wire, so present even when identity degrades.
|
|
664
|
+
if (parts.includes('identity'))
|
|
665
|
+
data.impersonationResourceId = ctx.poolConfig?.impersonationResourceId ?? null;
|
|
666
|
+
for (const part of parts) {
|
|
667
|
+
// Zero wire: this package's version (the same constant as serverInfo and /metadata), kept apart from the vendor `version` part.
|
|
668
|
+
if (part === 'server') {
|
|
669
|
+
data.server = { name: SERVER_NAME, version: SERVER_VERSION, sdkVersion: SDK_VERSION, profile: ctx.config.AUTOTASK_PROFILE };
|
|
670
|
+
continue;
|
|
671
|
+
}
|
|
672
|
+
// Zero wire: the users' zone (AUTOTASK_USER_TIMEZONE) and its clock (#171), so a client need not guess today's date or zone.
|
|
673
|
+
if (part === 'time') {
|
|
674
|
+
data.time = zoneClock(ctx.config.AUTOTASK_USER_TIMEZONE);
|
|
675
|
+
continue;
|
|
676
|
+
}
|
|
677
|
+
const op = STATUS_OPS[part];
|
|
678
|
+
try {
|
|
679
|
+
const value = await ctx.ops.invokeRead(ctx.client, op, [], undefined, signal);
|
|
680
|
+
if (value === undefined)
|
|
681
|
+
return abortedAnswer(ctx.correlationId);
|
|
682
|
+
const model = markResult(value, ctx.untrustedFields(op));
|
|
683
|
+
if (part !== 'thresholds') {
|
|
684
|
+
data[part] = model;
|
|
685
|
+
continue;
|
|
686
|
+
}
|
|
687
|
+
// The TENANT-wide vendor count (model) and the LOCAL per-credential window (budget,
|
|
688
|
+
// zero wire): two numbers in different scopes.
|
|
689
|
+
const budget = await ctx.ops.hourlyBudget(ctx.client);
|
|
690
|
+
data.thresholds = budget === undefined ? { model, budget: null, budgetNote: 'No local hourly budget on this client (its rate limiting is off).' } : { model, budget };
|
|
691
|
+
}
|
|
692
|
+
catch (err) {
|
|
693
|
+
// A credential refusal fails the call (every part would fail the same way).
|
|
694
|
+
const payload = typedErrorPayload(err, ctx.correlationId, requestSecrets(ctx));
|
|
695
|
+
if (payload.code === 'UNAUTHORIZED')
|
|
696
|
+
throw err;
|
|
697
|
+
firstError ??= err;
|
|
698
|
+
data[part] = { value: null, absent: String(payload.code) };
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
// Nothing answered: the call failed, with the first part's typed error (never an empty ok).
|
|
702
|
+
if (firstError !== undefined && parts.filter((p) => p !== 'server' && p !== 'time').every((p) => data[p]?.absent !== undefined))
|
|
703
|
+
throw firstError;
|
|
704
|
+
const identity = data.identity;
|
|
705
|
+
return ok(parts.includes('identity') && identity === null ? 'No Resource matched the configured user.' : `Tenant status returned (${parts.join(', ')}).`, data);
|
|
706
|
+
},
|
|
707
|
+
};
|
|
708
|
+
}
|
|
709
|
+
//# sourceMappingURL=meta.js.map
|