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,166 @@
|
|
|
1
|
+
/** Argument parsing and the target key of a write (issue #89). */
|
|
2
|
+
import { validateDispatchArgs } from 'node-autotask/operations';
|
|
3
|
+
import { stripUntrustedDeep } from 'node-autotask/untrusted';
|
|
4
|
+
import { hashOf } from '../../write/canonical.js';
|
|
5
|
+
import { reason } from './common.js';
|
|
6
|
+
import { caseDuplicate, sanitisedArtefact, cleanPayload, leftoverCombiningMark } from './payload.js';
|
|
7
|
+
// ---------------------------------------------------------------------------
|
|
8
|
+
// Arguments: the shape, the target ids, the data
|
|
9
|
+
// ---------------------------------------------------------------------------
|
|
10
|
+
export const SHAPE_ARGS = {
|
|
11
|
+
create: ['data'],
|
|
12
|
+
create_child: ['parentId', 'data'],
|
|
13
|
+
update: ['id', 'data'],
|
|
14
|
+
update_child: ['parentId', 'id', 'data'],
|
|
15
|
+
delete: ['id'],
|
|
16
|
+
delete_child: ['parentId', 'id'],
|
|
17
|
+
move: ['sourceId', 'toTicketId'],
|
|
18
|
+
// the generic shape takes the record's own declared arguments, in the registry's order (below)
|
|
19
|
+
call: [],
|
|
20
|
+
};
|
|
21
|
+
/** The argument names of the generic `call` shape that name the record's own id (the snapshot's target). */
|
|
22
|
+
export const CALL_ID_ARGS = new Set(['id', 'sourceId', 'sourceContactId']);
|
|
23
|
+
/** The argument names of the generic `call` shape that name a company the write touches (a scope fact). */
|
|
24
|
+
export const CALL_COMPANY_ARGS = new Set(['companyID', 'companyId', 'destinationCompanyId', 'destinationCompanyID']);
|
|
25
|
+
/**
|
|
26
|
+
* A non-negative integer id, or an integer string of digits (the registry accepts both forms for ids),
|
|
27
|
+
* so "0" reads as 0 exactly as "2001" reads as 2001. Anything else (negative, fractional, beyond
|
|
28
|
+
* 2^53, non-numeric) is undefined. Only a company reference may be 0 (the tenant's own company).
|
|
29
|
+
*/
|
|
30
|
+
export function asIdOrZero(value) {
|
|
31
|
+
const n = typeof value === 'string' && /^\d+$/.test(value) ? Number(value) : value;
|
|
32
|
+
return typeof n === 'number' && Number.isSafeInteger(n) && n >= 0 ? n : undefined;
|
|
33
|
+
}
|
|
34
|
+
/** A positive integer id, or an integer string of digits (the registry accepts both forms for ids). */
|
|
35
|
+
export function asId(value) {
|
|
36
|
+
const n = asIdOrZero(value);
|
|
37
|
+
return n === 0 ? undefined : n;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* The generic `call` shape (issue #191): the record's own declared arguments, in registry order, sent
|
|
41
|
+
* to the SDK op unchanged. There is no field-level snapshot to validate against, so the arguments are
|
|
42
|
+
* checked by the SDK's OWN pre-request validator (`validateDispatchArgs`: arity, required args, loose
|
|
43
|
+
* types, zero wire) and by the same payload hygiene the data object gets. Ids stay ids where the
|
|
44
|
+
* registry names one; an object argument is a payload and its references are scope facts.
|
|
45
|
+
*/
|
|
46
|
+
export function parseCallArgs(record, raw) {
|
|
47
|
+
const names = Object.keys(record.inputSchema);
|
|
48
|
+
const stripped = stripUntrustedDeep(raw);
|
|
49
|
+
if (stripped.length > names.length) {
|
|
50
|
+
return reason('INPUT_INVALID', `${record.id} takes at most ${names.length} arg(s): [${names.join(', ')}]`, 'args');
|
|
51
|
+
}
|
|
52
|
+
const required = names.filter((n) => record.inputSchema[n]?.required === true);
|
|
53
|
+
if (stripped.length < required.length) {
|
|
54
|
+
return reason('INPUT_INVALID', `${record.id} requires ${required.length} arg(s): [${required.join(', ')}] (declared: [${names.join(', ')}])`, 'args');
|
|
55
|
+
}
|
|
56
|
+
const out = [];
|
|
57
|
+
const targets = { resource: record.resource };
|
|
58
|
+
for (const [i, name] of names.entries()) {
|
|
59
|
+
const value = stripped[i];
|
|
60
|
+
if (value === undefined) {
|
|
61
|
+
out.push(undefined);
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
const where = `args.${i}`;
|
|
65
|
+
const payload = value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
66
|
+
if (payload) {
|
|
67
|
+
const dup = caseDuplicate(value, where);
|
|
68
|
+
if (dup !== undefined)
|
|
69
|
+
return reason('INPUT_INVALID', `${dup}: payload keys are plain ASCII field names (letters, digits, underscore), one key per field whatever its case`, dup);
|
|
70
|
+
const copied = sanitisedArtefact(value, where);
|
|
71
|
+
if (copied !== undefined)
|
|
72
|
+
return reason('INPUT_INVALID', `${copied} carries a copied-artefact class: a typed HTML entity sequence (< > &), a truncation marker (server or note_chars form), or a wrapper tag in this server's exact spelling. Leave it out or send a new value.`, copied);
|
|
73
|
+
}
|
|
74
|
+
const cleaned = cleanPayload(value);
|
|
75
|
+
if (payload) {
|
|
76
|
+
const leftover = leftoverCombiningMark(cleaned, where);
|
|
77
|
+
if (leftover !== undefined) {
|
|
78
|
+
return reason('INPUT_INVALID', `${leftover} carries a combining mark with no precomposed form (for example a lone U+0301); the vendor stores such a character as a different one, so the write would not round-trip. Send the precomposed character instead`, leftover);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
out.push(cleaned);
|
|
82
|
+
const id = asId(cleaned);
|
|
83
|
+
const parentId = asIdOrZero(cleaned); // a parent id may be 0 (company 0's children); the snapshot refuses 0 unless the parent is companies
|
|
84
|
+
if (id !== undefined && CALL_ID_ARGS.has(name))
|
|
85
|
+
targets.id = id;
|
|
86
|
+
else if (parentId !== undefined && name === 'parentId')
|
|
87
|
+
targets.parentId = parentId;
|
|
88
|
+
}
|
|
89
|
+
// a trailing absent option is simply absent (a stored `undefined` would read back as null)
|
|
90
|
+
let last = out.length - 1;
|
|
91
|
+
while (last >= 0 && out[last] === undefined)
|
|
92
|
+
last--;
|
|
93
|
+
const args = out.slice(0, last + 1);
|
|
94
|
+
try {
|
|
95
|
+
validateDispatchArgs(record, args);
|
|
96
|
+
}
|
|
97
|
+
catch (err) {
|
|
98
|
+
return reason('INPUT_INVALID', `${record.id}: ${err.message}`, 'args');
|
|
99
|
+
}
|
|
100
|
+
return { args, targets };
|
|
101
|
+
}
|
|
102
|
+
/** Validate the positional args against the shape; ids are positive integers, never names. */
|
|
103
|
+
export function parseArgs(shape, record, raw) {
|
|
104
|
+
if (shape === 'call')
|
|
105
|
+
return parseCallArgs(record, raw);
|
|
106
|
+
const names = SHAPE_ARGS[shape];
|
|
107
|
+
if (raw.length !== names.length)
|
|
108
|
+
return reason('INPUT_INVALID', `${record.id} takes ${names.length} arg(s): [${names.join(', ')}]`, 'args');
|
|
109
|
+
const stripped = stripUntrustedDeep(raw);
|
|
110
|
+
const out = [];
|
|
111
|
+
const targets = { resource: record.resource };
|
|
112
|
+
let data;
|
|
113
|
+
for (const [i, name] of names.entries()) {
|
|
114
|
+
const v = stripped[i];
|
|
115
|
+
if (name === 'data') {
|
|
116
|
+
if (v === null || typeof v !== 'object' || Array.isArray(v) || Object.keys(v).length === 0)
|
|
117
|
+
return reason('INPUT_INVALID', `args[${i}] (data) must be a non-empty object of vendor fields`, `args.${i}`);
|
|
118
|
+
const dup = caseDuplicate(v);
|
|
119
|
+
if (dup !== undefined)
|
|
120
|
+
return reason('INPUT_INVALID', `${dup}: payload keys are plain ASCII field names (letters, digits, underscore), one key per field whatever its case`, dup);
|
|
121
|
+
data = cleanPayload(v);
|
|
122
|
+
const leftover = leftoverCombiningMark(data, `args.${i}`);
|
|
123
|
+
if (leftover !== undefined) {
|
|
124
|
+
return reason('INPUT_INVALID', `${leftover} carries a combining mark with no precomposed form (for example a lone U+0301); the vendor stores such a character as a different one, so the write would not round-trip. Send the precomposed character (for example U+00E9) instead`, leftover);
|
|
125
|
+
}
|
|
126
|
+
const copied = sanitisedArtefact(data, `args.${i}`);
|
|
127
|
+
if (copied !== undefined) {
|
|
128
|
+
return reason('INPUT_INVALID', `${copied} carries a copied-artefact class: a typed HTML entity sequence (< > &), a truncation marker (server or note_chars form), or a wrapper tag in this server's exact spelling (raw or neutralised; other spellings cross as data). The gate is a copy-detect: it cannot tell a typed sequence from a stored one. Leave it out or send a new value; a vendor value that genuinely stores it cannot be written back.`, copied);
|
|
129
|
+
}
|
|
130
|
+
out.push(data);
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
// a parent id may be 0 (a contact on company 0); the snapshot refuses it before any read unless the parent is companies
|
|
134
|
+
if (typeof v !== 'number' || !Number.isSafeInteger(v) || v < 0 || (v === 0 && name !== 'parentId')) {
|
|
135
|
+
return reason('INPUT_INVALID', `args[${i}] (${name}) must be a numeric id; write targets are ids, never names (resolve a name with autotask_resolve first)`, `args.${i}`);
|
|
136
|
+
}
|
|
137
|
+
out.push(v);
|
|
138
|
+
// every id name is mapped explicitly: a move's last id is the TARGET ticket, never the record the snapshot reads
|
|
139
|
+
if (name === 'parentId')
|
|
140
|
+
targets.parentId = v;
|
|
141
|
+
else if (name === 'toTicketId')
|
|
142
|
+
targets.toId = v;
|
|
143
|
+
else if (name === 'id' || name === 'sourceId')
|
|
144
|
+
targets.id = v;
|
|
145
|
+
else
|
|
146
|
+
return reason('INPUT_INVALID', `${record.id}: unexpected argument ${name}`, `args.${i}`);
|
|
147
|
+
}
|
|
148
|
+
return data === undefined ? { args: out, targets } : { args: out, targets, data };
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* The ledger's key for a target: the record for an update or delete, the payload for a create, and for
|
|
152
|
+
* the generic `call` shape the record (or parent) it names — or, when it names none, the arguments.
|
|
153
|
+
*/
|
|
154
|
+
export function targetKeyOf(shape, targets, args) {
|
|
155
|
+
if (shape.startsWith('create'))
|
|
156
|
+
return `${targets.resource}:create:${hashOf(args).slice(7, 23)}`;
|
|
157
|
+
if (shape === 'call') {
|
|
158
|
+
if (targets.id !== undefined)
|
|
159
|
+
return `${targets.resource}:${targets.parentId === undefined ? '' : `${targets.parentId}/`}${targets.id}`;
|
|
160
|
+
if (targets.parentId !== undefined)
|
|
161
|
+
return `${targets.resource}:parent:${targets.parentId}`;
|
|
162
|
+
return `${targets.resource}:call:${hashOf(args).slice(7, 23)}`;
|
|
163
|
+
}
|
|
164
|
+
return `${targets.resource}:${targets.parentId === undefined ? '' : `${targets.parentId}/`}${targets.id}`;
|
|
165
|
+
}
|
|
166
|
+
//# sourceMappingURL=parse.js.map
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { WriteShape } from '../../write/hard-rules.js';
|
|
2
|
+
/**
|
|
3
|
+
* A field read case-insensitively (F2): the scope, policy and removal checks never depend on how a
|
|
4
|
+
* caller (or the vendor) cased a key. Payloads with keys that differ only by case are refused
|
|
5
|
+
* before this is ever consulted, so the match is unambiguous.
|
|
6
|
+
*/
|
|
7
|
+
export declare function ci(rec: Record<string, unknown>, field: string): unknown;
|
|
8
|
+
export declare const ASCII_KEY: RegExp;
|
|
9
|
+
/** The first key path that is not a plain ASCII identifier or repeats another key up to case. */
|
|
10
|
+
export declare function caseDuplicate(value: unknown, path?: string, depth?: number): string | undefined;
|
|
11
|
+
/**
|
|
12
|
+
* The first payload path whose string carries a copied-artefact class (sanitiser review S3): a
|
|
13
|
+
* typed HTML entity sequence (`<` `>` `&`), a truncation marker — the server's 500-char
|
|
14
|
+
* cap or the SDK's `note_chars` cap marker (`… [+N chars truncated]`, matched by shape: the SDK
|
|
15
|
+
* builds it per call and does not export it) — or a wrapper tag in either spelling, the raw one or
|
|
16
|
+
* the SDK's neutralised form (`wrapUntrusted` renders an interior wrapper tag as the literal escape
|
|
17
|
+
* text so the outer boundary stays exact; since 0.9.0 the read path serves that neutralised text,
|
|
18
|
+
* so a copied served value carries it).
|
|
19
|
+
* Since 0.9.0 the read path carries vendor text exactly as stored (issue #70), so a typed entity
|
|
20
|
+
* sequence in a payload may be a genuinely typed value, an echoed pre-0.9.0 escape, or text the
|
|
21
|
+
* vendor value really stores — the gate is a copy-detect that refuses the whole class and cannot
|
|
22
|
+
* tell them apart (the refusal tells the caller to leave the field out or send a new value); a
|
|
23
|
+
* marker or a wrapper tag, in either spelling, is a copied read artefact either way.
|
|
24
|
+
*/
|
|
25
|
+
export declare function sanitisedArtefact(value: unknown, path: string, depth?: number): string | undefined;
|
|
26
|
+
/**
|
|
27
|
+
* The SDK's dry-run `impact.reversible` speaks for the vendor, not this deployment (live-test
|
|
28
|
+
* finding): every delete in the registry needs approval (`requiresApproval` or `sensitive`, hard
|
|
29
|
+
* rules), so this server can never undo a create or a delete.
|
|
30
|
+
* An update keeps the SDK's answer (an update under the same rule reverses it).
|
|
31
|
+
*/
|
|
32
|
+
export declare function honestImpact(impact: unknown, shape: WriteShape): unknown;
|
|
33
|
+
/**
|
|
34
|
+
* Strip control and bidi characters and NFC-normalise every string in a write payload (never
|
|
35
|
+
* capped). NFC runs after the strip (issue 59): the vendor stores a decomposed accent (an `e` plus
|
|
36
|
+
* a combining acute, U+0301) as a different character (a spacing acute, U+00B4), so decomposed
|
|
37
|
+
* input would not round-trip; normalised, it is sent precomposed. The plan hash is taken over the
|
|
38
|
+
* normalised payload, and the preview diff shows exactly what is sent.
|
|
39
|
+
*/
|
|
40
|
+
export declare function cleanPayload(value: unknown, depth?: number): unknown;
|
|
41
|
+
/** A combining diacritical mark (U+0300–U+036F) that survived NFC has no precomposed form (for example a lone U+0301). */
|
|
42
|
+
export declare const LEFTOVER_COMBINING_MARK: RegExp;
|
|
43
|
+
/** The path of the first string under `path` that still carries such a mark, or undefined when none does. */
|
|
44
|
+
export declare function leftoverCombiningMark(value: unknown, path: string, depth?: number): string | undefined;
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/** Payload hygiene: case duplicates, sanitised artefacts, cleaning, leftover combining marks, the honest impact (issue #89). */
|
|
2
|
+
import { UNTRUSTED_CLOSE_NEUTRALISED, UNTRUSTED_OPEN_NEUTRALISED } from 'node-autotask/untrusted';
|
|
3
|
+
import { stripUnsafeChars } from '../results/untrusted.js';
|
|
4
|
+
import { TRUNCATION_MARKER } from '../results/envelope.js';
|
|
5
|
+
/**
|
|
6
|
+
* A field read case-insensitively (F2): the scope, policy and removal checks never depend on how a
|
|
7
|
+
* caller (or the vendor) cased a key. Payloads with keys that differ only by case are refused
|
|
8
|
+
* before this is ever consulted, so the match is unambiguous.
|
|
9
|
+
*/
|
|
10
|
+
export function ci(rec, field) {
|
|
11
|
+
if (field in rec)
|
|
12
|
+
return rec[field];
|
|
13
|
+
const lower = field.toLowerCase();
|
|
14
|
+
const key = Object.keys(rec).find((k) => k.toLowerCase() === lower);
|
|
15
|
+
return key === undefined ? undefined : rec[key];
|
|
16
|
+
}
|
|
17
|
+
export const ASCII_KEY = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
18
|
+
/** The first key path that is not a plain ASCII identifier or repeats another key up to case. */
|
|
19
|
+
export function caseDuplicate(value, path = 'data', depth = 0) {
|
|
20
|
+
if (depth > 12 || value === null || typeof value !== 'object')
|
|
21
|
+
return undefined;
|
|
22
|
+
if (Array.isArray(value)) {
|
|
23
|
+
for (const [i, v] of value.entries()) {
|
|
24
|
+
const hit = caseDuplicate(v, `${path}.${i}`, depth + 1);
|
|
25
|
+
if (hit !== undefined)
|
|
26
|
+
return hit;
|
|
27
|
+
}
|
|
28
|
+
return undefined;
|
|
29
|
+
}
|
|
30
|
+
const seen = new Set();
|
|
31
|
+
for (const [k, v] of Object.entries(value)) {
|
|
32
|
+
// Plain ASCII identifiers only (pre-release V3): a key such as `companyıD` (dotless i) or
|
|
33
|
+
// `taſkID` (long s) folds to an anchor name under other case rules while escaping ours.
|
|
34
|
+
if (!ASCII_KEY.test(k) || seen.has(k.toLowerCase()))
|
|
35
|
+
return `${path}.${k}`;
|
|
36
|
+
seen.add(k.toLowerCase());
|
|
37
|
+
const hit = caseDuplicate(v, `${path}.${k}`, depth + 1);
|
|
38
|
+
if (hit !== undefined)
|
|
39
|
+
return hit;
|
|
40
|
+
}
|
|
41
|
+
return undefined;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* The first payload path whose string carries a copied-artefact class (sanitiser review S3): a
|
|
45
|
+
* typed HTML entity sequence (`<` `>` `&`), a truncation marker — the server's 500-char
|
|
46
|
+
* cap or the SDK's `note_chars` cap marker (`… [+N chars truncated]`, matched by shape: the SDK
|
|
47
|
+
* builds it per call and does not export it) — or a wrapper tag in either spelling, the raw one or
|
|
48
|
+
* the SDK's neutralised form (`wrapUntrusted` renders an interior wrapper tag as the literal escape
|
|
49
|
+
* text so the outer boundary stays exact; since 0.9.0 the read path serves that neutralised text,
|
|
50
|
+
* so a copied served value carries it).
|
|
51
|
+
* Since 0.9.0 the read path carries vendor text exactly as stored (issue #70), so a typed entity
|
|
52
|
+
* sequence in a payload may be a genuinely typed value, an echoed pre-0.9.0 escape, or text the
|
|
53
|
+
* vendor value really stores — the gate is a copy-detect that refuses the whole class and cannot
|
|
54
|
+
* tell them apart (the refusal tells the caller to leave the field out or send a new value); a
|
|
55
|
+
* marker or a wrapper tag, in either spelling, is a copied read artefact either way.
|
|
56
|
+
*/
|
|
57
|
+
export function sanitisedArtefact(value, path, depth = 0) {
|
|
58
|
+
if (typeof value === 'string')
|
|
59
|
+
return /&(?:lt|gt|amp);|<\/?untrusted_content>|\u2026 \[\+\d+ chars truncated\]/.test(value) || value.includes(UNTRUSTED_OPEN_NEUTRALISED) || value.includes(UNTRUSTED_CLOSE_NEUTRALISED) || value.includes(TRUNCATION_MARKER) ? path : undefined;
|
|
60
|
+
if (depth > 12 || value === null || typeof value !== 'object')
|
|
61
|
+
return undefined;
|
|
62
|
+
for (const [k, v] of Object.entries(value)) {
|
|
63
|
+
const hit = sanitisedArtefact(v, `${path}.${k}`, depth + 1);
|
|
64
|
+
if (hit !== undefined)
|
|
65
|
+
return hit;
|
|
66
|
+
}
|
|
67
|
+
return undefined;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* The SDK's dry-run `impact.reversible` speaks for the vendor, not this deployment (live-test
|
|
71
|
+
* finding): every delete in the registry needs approval (`requiresApproval` or `sensitive`, hard
|
|
72
|
+
* rules), so this server can never undo a create or a delete.
|
|
73
|
+
* An update keeps the SDK's answer (an update under the same rule reverses it).
|
|
74
|
+
*/
|
|
75
|
+
export function honestImpact(impact, shape) {
|
|
76
|
+
if (impact === null || typeof impact !== 'object' || Array.isArray(impact) || shape.startsWith('update'))
|
|
77
|
+
return impact;
|
|
78
|
+
return { ...impact, reversible: false, reversibleNote: 'This server never runs deletes unattended: undoing it needs a person in Autotask.' };
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Strip control and bidi characters and NFC-normalise every string in a write payload (never
|
|
82
|
+
* capped). NFC runs after the strip (issue 59): the vendor stores a decomposed accent (an `e` plus
|
|
83
|
+
* a combining acute, U+0301) as a different character (a spacing acute, U+00B4), so decomposed
|
|
84
|
+
* input would not round-trip; normalised, it is sent precomposed. The plan hash is taken over the
|
|
85
|
+
* normalised payload, and the preview diff shows exactly what is sent.
|
|
86
|
+
*/
|
|
87
|
+
export function cleanPayload(value, depth = 0) {
|
|
88
|
+
if (typeof value === 'string')
|
|
89
|
+
return stripUnsafeChars(value).normalize('NFC');
|
|
90
|
+
if (depth > 12 || value === null || typeof value !== 'object')
|
|
91
|
+
return value;
|
|
92
|
+
if (Array.isArray(value))
|
|
93
|
+
return value.map((v) => cleanPayload(v, depth + 1));
|
|
94
|
+
return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, cleanPayload(v, depth + 1)]));
|
|
95
|
+
}
|
|
96
|
+
/** A combining diacritical mark (U+0300–U+036F) that survived NFC has no precomposed form (for example a lone U+0301). */
|
|
97
|
+
export const LEFTOVER_COMBINING_MARK = /[\u0300-\u036F]/u;
|
|
98
|
+
/** The path of the first string under `path` that still carries such a mark, or undefined when none does. */
|
|
99
|
+
export function leftoverCombiningMark(value, path, depth = 0) {
|
|
100
|
+
if (typeof value === 'string')
|
|
101
|
+
return LEFTOVER_COMBINING_MARK.test(value) ? path : undefined;
|
|
102
|
+
if (depth > 12 || value === null || typeof value !== 'object')
|
|
103
|
+
return undefined;
|
|
104
|
+
if (Array.isArray(value)) {
|
|
105
|
+
for (let i = 0; i < value.length; i++) {
|
|
106
|
+
const hit = leftoverCombiningMark(value[i], `${path}[${i}]`, depth + 1);
|
|
107
|
+
if (hit !== undefined)
|
|
108
|
+
return hit;
|
|
109
|
+
}
|
|
110
|
+
return undefined;
|
|
111
|
+
}
|
|
112
|
+
for (const [k, v] of Object.entries(value)) {
|
|
113
|
+
const hit = leftoverCombiningMark(v, `${path}.${k}`, depth + 1);
|
|
114
|
+
if (hit !== undefined)
|
|
115
|
+
return hit;
|
|
116
|
+
}
|
|
117
|
+
return undefined;
|
|
118
|
+
}
|
|
119
|
+
//# sourceMappingURL=payload.js.map
|
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
/** `autotask_write`: the preview tool (issue #89). */
|
|
2
|
+
import { MoveRefusedError } from 'node-autotask';
|
|
3
|
+
import { describeWrite } from 'node-autotask/operations';
|
|
4
|
+
import { abortedResult } from '../results/errors.js';
|
|
5
|
+
import { cleanUntrustedText, markResult } from '../results/untrusted.js';
|
|
6
|
+
import { assertOperationPermitted } from '../../policy.js';
|
|
7
|
+
import { WRITE_INPUT, closedInput } from '../schemas.js';
|
|
8
|
+
import { planHashOf } from '../../write/canonical.js';
|
|
9
|
+
import { dedupFor, evaluate, pinAudit } from '../../write/evaluate.js';
|
|
10
|
+
import { hardRuleFor, writeShape } from '../../write/hard-rules.js';
|
|
11
|
+
import { PLAN_TTL_MS } from '../../write/store.js';
|
|
12
|
+
import { Cancelled, writeDeps, tenantIdentity, answer, reason } from './common.js';
|
|
13
|
+
import { parseArgs } from './parse.js';
|
|
14
|
+
import { honestImpact } from './payload.js';
|
|
15
|
+
import { takeSnapshot, moveSummary, parentOf } from './snapshot.js';
|
|
16
|
+
import { catalogFindings, pairFindings } from './checks.js';
|
|
17
|
+
import { unresolvedReason, markedDiff, deriveFacts } from './facts.js';
|
|
18
|
+
import { UDF_CAPABLE } from '../catalog-data.js';
|
|
19
|
+
import { udfPreviewWarning } from '../write-guidance.js';
|
|
20
|
+
import { applyToolFor, approverFor } from './apply.js';
|
|
21
|
+
/**
|
|
22
|
+
* The generic `call` shape has no field-level snapshot (issue #191): no vendor reads establish what the
|
|
23
|
+
* op will change, so the preview states the arguments it will send — unchanged — and an impact that
|
|
24
|
+
* claims nothing it cannot know. It is one call, and this server cannot undo it.
|
|
25
|
+
*/
|
|
26
|
+
// A composite op decides its own steps, so the preview must not claim a record
|
|
27
|
+
// count or a single-record scope: `affected: null` + scope 'composite' is the
|
|
28
|
+
// honest answer (a `call` op decides how many rows it touches — a move or transfer
|
|
29
|
+
// can act on a whole book of work).
|
|
30
|
+
const CALL_IMPACT = { affected: null, scope: 'composite', reversible: false };
|
|
31
|
+
const CALL_WARNING = 'this operation has no field-level snapshot: the preview echoes the arguments as they will be sent and the scope reads behind them; autotask_apply sends exactly these arguments to the SDK operation. The blast radius is the op own: it can affect more than one record - check the operation arguments';
|
|
32
|
+
/**
|
|
33
|
+
* #163: who a time entry is for. A preview-only read (never in the plan hash): the resource's name and
|
|
34
|
+
* the entry's role echoed so the operator sees the human, not just an id. A miss is typed absent, never a failure.
|
|
35
|
+
*/
|
|
36
|
+
async function entryResource(r, a) {
|
|
37
|
+
if (r.op !== 'time_entries.create')
|
|
38
|
+
return undefined;
|
|
39
|
+
const data = a.parsed.data;
|
|
40
|
+
const id = data?.resourceID;
|
|
41
|
+
if (typeof id !== 'number' || !Number.isInteger(id) || id <= 0)
|
|
42
|
+
return undefined;
|
|
43
|
+
const roleID = typeof data?.roleID === 'number' ? data.roleID : null;
|
|
44
|
+
try {
|
|
45
|
+
const res = (await r.ctx.ops.invokeRead(r.ctx.client, 'resources.get', [id], { fresh: true }, r.signal));
|
|
46
|
+
if (res === undefined || res === null)
|
|
47
|
+
return { id, roleID, name: null };
|
|
48
|
+
const name = typeof res.name === 'string' ? res.name : [res.firstName, res.lastName].filter((x) => typeof x === 'string' && x !== '').join(' ');
|
|
49
|
+
return { id, roleID, name: cleanUntrustedText(name, false).slice(0, 100) || null };
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
return { id, roleID, name: null, absent: true };
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
/** A refusal from the field checks: INPUT_INVALID, audited as denied, before apply. */
|
|
56
|
+
function stop(f, r, parsed) {
|
|
57
|
+
if (f.refuse.length === 0)
|
|
58
|
+
return undefined;
|
|
59
|
+
const rs = f.refuse.map((d) => reason('INPUT_INVALID', d));
|
|
60
|
+
r.audit('denied', rs, undefined, parsed.targets);
|
|
61
|
+
return { stop: answer('error', 'supply_input', rs, { operation: r.op, targets: parsed.targets }) };
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* #183 S9: the coupled-pair rule (no wire), then the picklist and create-gate checks (one cached catalog read).
|
|
65
|
+
* Any refusal answers here as INPUT_INVALID, before apply; warnings join the preview.
|
|
66
|
+
*/
|
|
67
|
+
async function fieldChecks(r, a, current) {
|
|
68
|
+
const { shape, parsed, record } = a;
|
|
69
|
+
const op = shape === 'create' || shape === 'create_child' ? 'create' : shape === 'update' || shape === 'update_child' ? 'update' : undefined;
|
|
70
|
+
// The generic call shape has no data object; the one op whose argument is a picklist value of its own resource is covered.
|
|
71
|
+
// The other call ops (the moves, the stocked-items specials, `tickets.changeStatus`) take their own
|
|
72
|
+
// arguments, so a create-gate or pair refusal could be false: they stay with the SDK and the vendor.
|
|
73
|
+
const status = shape === 'call' && r.op === 'tickets.changeStatus' ? r.args.args[1] : undefined;
|
|
74
|
+
if (status !== undefined && status !== null) {
|
|
75
|
+
const found = await catalogFindings(r.ctx, { resource: 'tickets', op: 'update', data: { status }, current, parentField: undefined }, r.signal);
|
|
76
|
+
if (found.aborted === true)
|
|
77
|
+
return { stop: abortedResult() };
|
|
78
|
+
return stop(found, r, parsed) ?? { warn: found.warn, types: found.types };
|
|
79
|
+
}
|
|
80
|
+
if (op === undefined || parsed.data === undefined)
|
|
81
|
+
return { warn: [] };
|
|
82
|
+
const pair = pairFindings(record.resource, parsed.data, current);
|
|
83
|
+
const early = stop(pair, r, parsed);
|
|
84
|
+
if (early !== undefined)
|
|
85
|
+
return early;
|
|
86
|
+
const parentField = shape === 'create_child' ? (await parentOf(record.resource))?.field : undefined;
|
|
87
|
+
const found = await catalogFindings(r.ctx, { resource: record.resource, op, data: parsed.data, current, parentField }, r.signal);
|
|
88
|
+
if (found.aborted === true)
|
|
89
|
+
return { stop: abortedResult() };
|
|
90
|
+
return stop(found, r, parsed) ?? { warn: found.warn, types: found.types };
|
|
91
|
+
}
|
|
92
|
+
/** The response sanitiser's per-string cap (UNTRUSTED_TEXT_CAP): a longer warning would lose its tail. */
|
|
93
|
+
const LOCATION_WARNING_CAP = 500;
|
|
94
|
+
/**
|
|
95
|
+
* #183: a contact written with no `companyLocationID` while its company has active locations. One bounded
|
|
96
|
+
* read (limit 50), only when the field is unset; a failed or refused read adds nothing. The read goes through
|
|
97
|
+
* the same deployment gate as `autotask_read`. The sanitiser caps each warning at 500 characters, so the instruction
|
|
98
|
+
* comes first and only as many location ids as fit are listed. No vendor text enters the sentence: ids are numbers.
|
|
99
|
+
*/
|
|
100
|
+
async function locationWarning(r, a, current) {
|
|
101
|
+
if (r.op !== 'contacts.create' && r.op !== 'contacts.update')
|
|
102
|
+
return undefined;
|
|
103
|
+
const companyID = a.parsed.targets.parentId;
|
|
104
|
+
if (companyID === undefined || a.parsed.data === undefined || 'companyLocationID' in a.parsed.data)
|
|
105
|
+
return undefined;
|
|
106
|
+
if (current?.companyLocationID != null)
|
|
107
|
+
return undefined; // update on a contact that already has a location
|
|
108
|
+
try {
|
|
109
|
+
assertOperationPermitted('company_locations.query', r.ctx.record('company_locations.query'), r.ctx.config, r.ctx.log);
|
|
110
|
+
const rows = (await r.ctx.ops.invokeRead(r.ctx.client, 'company_locations.query', [{ filter: [{ field: 'companyID', op: 'eq', value: companyID }, { field: 'isActive', op: 'eq', value: true }], limit: 50 }], undefined, r.signal));
|
|
111
|
+
if (rows === undefined)
|
|
112
|
+
return null; // the SDK answers undefined for a cancelled call
|
|
113
|
+
const raw = (Array.isArray(rows) ? rows : rows?.items) ?? [];
|
|
114
|
+
const list = raw.filter((l) => Number.isSafeInteger(l.id) && l.id > 0); // ids are the only thing served: no row without one is listed or counted
|
|
115
|
+
if (list.length === 0)
|
|
116
|
+
return undefined;
|
|
117
|
+
const total = list.length >= 50 ? 'at least 50' : String(list.length);
|
|
118
|
+
const head = `companyLocationID is not set on this contact and the parent company ${companyID} has ${total} active location(s). Set companyLocationID before applying; if the contact's address is unknown${list.length > 1 ? ', ask the user which location applies' : ' and there is one location, set it'}. Location ids (names: company_locations.query): `;
|
|
119
|
+
// ids and the primary flag only: no vendor text in server prose; the model reads names through company_locations.query
|
|
120
|
+
const items = list.map((l) => `${l.id}${l.isPrimary === true ? ' (primary)' : ''}`);
|
|
121
|
+
let text = head;
|
|
122
|
+
let shown = 0;
|
|
123
|
+
for (const it of items) {
|
|
124
|
+
if (text.length + it.length + 2 > LOCATION_WARNING_CAP - 40)
|
|
125
|
+
break; // 40 = room for the ' (first N of at least M listed)' tail
|
|
126
|
+
text += (shown > 0 ? ', ' : '') + it;
|
|
127
|
+
shown++;
|
|
128
|
+
}
|
|
129
|
+
return shown < items.length ? `${text} (first ${shown} of ${total} listed)` : text;
|
|
130
|
+
}
|
|
131
|
+
catch {
|
|
132
|
+
return undefined;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* The SDK's approval rendering of this preview (#301, node-autotask #377): the one summary source. A
|
|
137
|
+
* composite op has no SDK dry run, so its arguments render as the data; any part a dry run lacks is
|
|
138
|
+
* filled from the plan (the SDK always returns them).
|
|
139
|
+
*/
|
|
140
|
+
function describe(record, shape, op, parsed, dry) {
|
|
141
|
+
const t = parsed.targets;
|
|
142
|
+
const ids = [t.parentId, t.id, t.toId].filter((v) => v !== undefined);
|
|
143
|
+
const data = shape === 'call' ? Object.fromEntries(Object.keys(record.inputSchema).map((k, i) => [k, parsed.args[i]])) : dry.data;
|
|
144
|
+
const impact = shape === 'call' ? CALL_IMPACT : (honestImpact(dry.impact, shape) ?? { scope: 'single', affected: 1, reversible: !shape.startsWith('delete') });
|
|
145
|
+
const full = { operation: op, target: { resource: t.resource, ids }, request: { method: '', path: '' }, checks: [], warnings: [], simulated: true, ...dry, wouldApply: dry.wouldApply ?? true, impact, data };
|
|
146
|
+
return describeWrite(full, record);
|
|
147
|
+
}
|
|
148
|
+
/** The policy decision over the derived facts, its audit row and the preview the answers carry. */
|
|
149
|
+
function evaluatePreview(r, a, snap, dry, resource, types) {
|
|
150
|
+
const { ctx, w, store, loaded, op, audit } = r;
|
|
151
|
+
const { record, shape, parsed } = a;
|
|
152
|
+
const now = w.runtime.now();
|
|
153
|
+
const tenantId = store.tenantId(tenantIdentity(ctx));
|
|
154
|
+
const facts = deriveFacts({ store, op, record, shape, parsed, snap });
|
|
155
|
+
const decision = evaluate(loaded, facts, w.runScope, store.counters(op, now));
|
|
156
|
+
const planHash = planHashOf({ op, args: parsed.args, targets: parsed.targets, snapshot: snap.inputs, policyHash: loaded.policyHash, facts, principal: w.principal, tenantId });
|
|
157
|
+
audit(decision.decision, decision.reasons, planHash, parsed.targets, facts);
|
|
158
|
+
const described = describe(record, shape, op, parsed, dry);
|
|
159
|
+
const preview = {
|
|
160
|
+
operation: op,
|
|
161
|
+
targets: parsed.targets,
|
|
162
|
+
decision: decision.decision,
|
|
163
|
+
hazards: decision.hazards,
|
|
164
|
+
diff: markedDiff(dry.diff, types),
|
|
165
|
+
warnings: (dry.warnings ?? []).slice(0, 20).map((x) => String(x)),
|
|
166
|
+
impact: shape === 'call' ? CALL_IMPACT : honestImpact(dry.impact, shape),
|
|
167
|
+
// #183 AC21: the body a create will send — the SDK-redacted dry-run `data` (never the raw
|
|
168
|
+
// parsed args: they still carry pre-redaction personal-data values), so a gated create on a
|
|
169
|
+
// DELETE-less resource confirms the exact body it approves.
|
|
170
|
+
...(shape === 'create' || shape === 'create_child' ? { payload: dry.data } : {}),
|
|
171
|
+
// #183 AC23: the record a delete will remove — the snapshot's target read (zero new wire: the
|
|
172
|
+
// read is already paid for the snapshot, the field checks and the policy facts), marked
|
|
173
|
+
// untrusted like every other served vendor record (S6).
|
|
174
|
+
...((shape === 'delete' || shape === 'delete_child') && snap.current !== undefined
|
|
175
|
+
? { record: markResult(snap.current, ctx.untrustedFields(op)) }
|
|
176
|
+
: {}),
|
|
177
|
+
...(shape === 'call' ? { dispatch: 'sdk-op', args: parsed.args } : {}),
|
|
178
|
+
...(resource !== undefined ? { resource } : {}),
|
|
179
|
+
...(shape === 'move' ? { move: moveSummary(record, parsed.targets, snap.current, dry.data, facts) } : {}),
|
|
180
|
+
};
|
|
181
|
+
return { now, tenantId, facts, decision, planHash, preview, described };
|
|
182
|
+
}
|
|
183
|
+
/** The answer for the decision: a denial, or a stored ready plan (`gate`: a person confirms it at apply). */
|
|
184
|
+
function persist(r, a, e) {
|
|
185
|
+
const { w, store, loaded, args, op } = r;
|
|
186
|
+
const { parsed, rule } = a;
|
|
187
|
+
const { now, tenantId, facts, decision, planHash, preview, described } = e;
|
|
188
|
+
if (decision.decision === 'deny')
|
|
189
|
+
return answer('denied', 'stop', decision.reasons, preview, { planHash });
|
|
190
|
+
const gate = decision.decision === 'gate';
|
|
191
|
+
const handle = store.newHandle();
|
|
192
|
+
const plan = {
|
|
193
|
+
handle,
|
|
194
|
+
planHash,
|
|
195
|
+
principal: w.principal,
|
|
196
|
+
tenantId,
|
|
197
|
+
op,
|
|
198
|
+
args: parsed.args,
|
|
199
|
+
targets: parsed.targets,
|
|
200
|
+
policyHash: loaded.policyHash,
|
|
201
|
+
decision: decision.decision,
|
|
202
|
+
facts,
|
|
203
|
+
...(args.reason !== undefined ? { reason: cleanUntrustedText(args.reason, false).slice(0, 200) } : {}),
|
|
204
|
+
summary: described.headline,
|
|
205
|
+
lines: described.lines,
|
|
206
|
+
reversible: described.reversible,
|
|
207
|
+
createdAt: now,
|
|
208
|
+
expiresAt: now + PLAN_TTL_MS,
|
|
209
|
+
};
|
|
210
|
+
store.savePlan(plan);
|
|
211
|
+
const minutes = Math.round(PLAN_TTL_MS / 60_000);
|
|
212
|
+
// #301: the echo the apply tool must send back verbatim, so the arguments a client shows are bound to this plan
|
|
213
|
+
const approval = { operation: op, targets: parsed.targets, summary: described.headline };
|
|
214
|
+
// #302: a hard-rule plan applies only through autotask_apply_destructive; on stdio the mode decides whether this server asks
|
|
215
|
+
const apply = applyToolFor(plan);
|
|
216
|
+
const asks = approverFor(loaded.transport, rule.mode, gate) === 'person';
|
|
217
|
+
return answer('ok', 'proceed', [], { ...preview, gate, plan: handle, expiresAt: new Date(plan.expiresAt).toISOString(), apply, approval }, {
|
|
218
|
+
plan: handle,
|
|
219
|
+
planHash,
|
|
220
|
+
summary: `Preview of ${op}: allowed${gate ? ' (a hard rule applies)' : ''}. Call ${apply} with plan ${handle} and approval's operation, targets and summary copied verbatim, within ${minutes} minutes.${asks ? ' This server asks the person to confirm it.' : ''}`,
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
/** Preview one operation: admit, read current state, ask the SDK, check fields and save the plan. */
|
|
224
|
+
async function execute(ctx, args, signal) {
|
|
225
|
+
const w = writeDeps(ctx);
|
|
226
|
+
const { store, loaded } = w.runtime;
|
|
227
|
+
const op = args.operation;
|
|
228
|
+
const audit = (decision, reasons, planHash, targets, facts) => store.audit({ event: 'preview', principal: w.principal, op,
|
|
229
|
+
...(targets !== undefined ? { targets } : {}), ...(planHash !== undefined ? { planHash } : {}),
|
|
230
|
+
decision, reasons: reasons.map((r) => r.code),
|
|
231
|
+
...(facts !== undefined ? pinAudit(facts, loaded, w.runScope) : {}),
|
|
232
|
+
...(args.reason !== undefined ? { reason: cleanUntrustedText(args.reason, false).slice(0, 200) } : {}),
|
|
233
|
+
}, w.runtime.now());
|
|
234
|
+
const r = { ctx, w, store, loaded, args, op, signal, audit };
|
|
235
|
+
const block = store.blocked();
|
|
236
|
+
if (block !== undefined) {
|
|
237
|
+
const rs = [reason(block.code, block.detail)];
|
|
238
|
+
audit('denied', rs);
|
|
239
|
+
return answer(block.next === 'retry' ? 'error' : 'denied', block.next, rs, { operation: op }, { retryable: block.next === 'retry' });
|
|
240
|
+
}
|
|
241
|
+
const found = ctx.record(op);
|
|
242
|
+
const hard = hardRuleFor(op, found);
|
|
243
|
+
const rule = loaded.table.get(op);
|
|
244
|
+
if (hard.never !== undefined || rule === undefined || rule.mode === 'deny') {
|
|
245
|
+
const why = hard.never !== undefined ? `${op}: ${hard.never}` : rule === undefined ? `${op} is not in AUTOTASK_WRITE (unlisted writes are read-only)` : `AUTOTASK_WRITE denies ${op}`;
|
|
246
|
+
const rs = [reason('OP_NOT_ALLOWED', why)];
|
|
247
|
+
audit('denied', rs);
|
|
248
|
+
return answer('denied', 'stop', rs, { operation: op });
|
|
249
|
+
}
|
|
250
|
+
const record = found;
|
|
251
|
+
const shape = writeShape(record);
|
|
252
|
+
const parsed = parseArgs(shape, record, args.args);
|
|
253
|
+
if ('code' in parsed)
|
|
254
|
+
return answer('error', 'supply_input', [parsed], { operation: op });
|
|
255
|
+
const a = { record, shape, parsed, rule };
|
|
256
|
+
let snap;
|
|
257
|
+
try {
|
|
258
|
+
snap = await takeSnapshot(ctx, record, parsed, dedupFor(loaded, op), signal);
|
|
259
|
+
}
|
|
260
|
+
catch (err) {
|
|
261
|
+
if (err instanceof Cancelled)
|
|
262
|
+
return abortedResult();
|
|
263
|
+
throw err;
|
|
264
|
+
}
|
|
265
|
+
if ('code' in snap)
|
|
266
|
+
return answer('needs_input', 'supply_input', [snap], { operation: op }, { missing: [`/${snap.field?.replace('.', '/') ?? 'args'}`] });
|
|
267
|
+
if (snap.unresolved.length > 0) {
|
|
268
|
+
const rs = [unresolvedReason(snap.unresolved)];
|
|
269
|
+
audit('deny', rs, undefined, parsed.targets);
|
|
270
|
+
return answer('denied', 'stop', rs, { operation: op, targets: parsed.targets });
|
|
271
|
+
}
|
|
272
|
+
// Scope must precede an SDK move refusal, whose message may name records outside this run.
|
|
273
|
+
if (shape === 'move') {
|
|
274
|
+
const facts = deriveFacts({ store, op, record, shape, parsed, snap });
|
|
275
|
+
const decision = evaluate(loaded, facts, w.runScope, store.counters(op, w.runtime.now()));
|
|
276
|
+
if (decision.decision === 'deny') {
|
|
277
|
+
audit('deny', decision.reasons, undefined, parsed.targets, facts);
|
|
278
|
+
return answer('denied', 'stop', decision.reasons, { operation: op, targets: parsed.targets });
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
let dry = { wouldApply: true, warnings: [CALL_WARNING] };
|
|
282
|
+
if (shape !== 'call') {
|
|
283
|
+
const confirm = record.effect === 'destructive' || record.flags.includes('requiresApproval') ? { confirm: op } : {};
|
|
284
|
+
const invoke = record.effect === 'destructive' ? ctx.ops.invokeDelete : ctx.ops.invokeWrite;
|
|
285
|
+
try {
|
|
286
|
+
dry = await invoke(ctx.client, op, parsed.args, confirm, signal);
|
|
287
|
+
}
|
|
288
|
+
catch (err) {
|
|
289
|
+
if (!(err instanceof MoveRefusedError))
|
|
290
|
+
throw err;
|
|
291
|
+
const rs = [reason('MOVE_REFUSED', `${err.code ?? 'MOVE_REFUSED'}: ${err.message}`)];
|
|
292
|
+
audit('denied', rs, undefined, parsed.targets);
|
|
293
|
+
return answer('denied', 'stop', rs, { operation: op, targets: parsed.targets });
|
|
294
|
+
}
|
|
295
|
+
if (dry === undefined)
|
|
296
|
+
return abortedResult();
|
|
297
|
+
if (dry.wouldApply === false) {
|
|
298
|
+
const failed = (dry.checks ?? []).filter((c) => !c.ok).map((c) => c.name);
|
|
299
|
+
const rs = [reason('INPUT_INVALID', `the SDK dry run would not apply: ${failed.join(', ') || 'check failed'}`)];
|
|
300
|
+
audit('denied', rs, undefined, parsed.targets);
|
|
301
|
+
return answer('error', 'supply_input', rs, { operation: op, checks: dry.checks });
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
const checked = await fieldChecks(r, a, snap.current);
|
|
305
|
+
if ('stop' in checked)
|
|
306
|
+
return checked.stop;
|
|
307
|
+
const loc = await locationWarning(r, a, snap.current);
|
|
308
|
+
if (loc === null)
|
|
309
|
+
return abortedResult();
|
|
310
|
+
const udf = shape === 'create' || shape === 'create_child' ? udfPreviewWarning(UDF_CAPABLE.has(record.resource), parsed.data, 'create') : shape === 'update' || shape === 'update_child' ? udfPreviewWarning(UDF_CAPABLE.has(record.resource), parsed.data, 'update') : undefined;
|
|
311
|
+
const dried = { ...dry, warnings: [...(udf === undefined ? [] : [udf]), ...checked.warn, ...(loc === undefined ? [] : [loc]), ...(dry.warnings ?? [])] };
|
|
312
|
+
return persist(r, a, evaluatePreview(r, a, snap, dried, await entryResource(r, a), checked.types));
|
|
313
|
+
}
|
|
314
|
+
export function buildWrite(ctx) {
|
|
315
|
+
return { title: 'Preview an Autotask write (changes nothing)', input: closedInput(WRITE_INPUT), run: (raw, signal) => execute(ctx, raw, signal) };
|
|
316
|
+
}
|
|
317
|
+
//# sourceMappingURL=preview.js.map
|