iit-mcp-autotask 0.54.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (164) hide show
  1. package/.env.example +123 -0
  2. package/LICENSE +21 -0
  3. package/README.md +788 -0
  4. package/capabilities.json +487 -0
  5. package/dist/access/gate.d.ts +34 -0
  6. package/dist/access/gate.js +76 -0
  7. package/dist/access/grants.d.ts +20 -0
  8. package/dist/access/grants.js +35 -0
  9. package/dist/access/write-env.d.ts +41 -0
  10. package/dist/access/write-env.js +166 -0
  11. package/dist/auth.d.ts +74 -0
  12. package/dist/auth.js +129 -0
  13. package/dist/base-hosts.d.ts +38 -0
  14. package/dist/base-hosts.js +70 -0
  15. package/dist/config/load.d.ts +28 -0
  16. package/dist/config/load.js +105 -0
  17. package/dist/config/schema.d.ts +166 -0
  18. package/dist/config/schema.js +311 -0
  19. package/dist/credential.d.ts +28 -0
  20. package/dist/credential.js +32 -0
  21. package/dist/doctor.d.ts +112 -0
  22. package/dist/doctor.js +154 -0
  23. package/dist/http-guard.d.ts +57 -0
  24. package/dist/http-guard.js +134 -0
  25. package/dist/http.d.ts +50 -0
  26. package/dist/http.js +290 -0
  27. package/dist/lifecycle.d.ts +29 -0
  28. package/dist/lifecycle.js +52 -0
  29. package/dist/logger.d.ts +26 -0
  30. package/dist/logger.js +28 -0
  31. package/dist/main.d.ts +12 -0
  32. package/dist/main.js +283 -0
  33. package/dist/policy.d.ts +54 -0
  34. package/dist/policy.js +80 -0
  35. package/dist/tools/aggregate.d.ts +16 -0
  36. package/dist/tools/aggregate.js +64 -0
  37. package/dist/tools/capabilities-manifest.d.ts +4 -0
  38. package/dist/tools/capabilities-manifest.js +94 -0
  39. package/dist/tools/catalog-data.d.ts +116 -0
  40. package/dist/tools/catalog-data.js +207 -0
  41. package/dist/tools/clock.d.ts +17 -0
  42. package/dist/tools/clock.js +43 -0
  43. package/dist/tools/composites.d.ts +36 -0
  44. package/dist/tools/composites.js +305 -0
  45. package/dist/tools/context/client.d.ts +41 -0
  46. package/dist/tools/context/client.js +139 -0
  47. package/dist/tools/context/derive.d.ts +9 -0
  48. package/dist/tools/context/derive.js +32 -0
  49. package/dist/tools/context/scope.d.ts +24 -0
  50. package/dist/tools/context/scope.js +180 -0
  51. package/dist/tools/context/types.d.ts +141 -0
  52. package/dist/tools/context/types.js +2 -0
  53. package/dist/tools/dispatch.d.ts +78 -0
  54. package/dist/tools/dispatch.js +272 -0
  55. package/dist/tools/field-pointer.d.ts +25 -0
  56. package/dist/tools/field-pointer.js +45 -0
  57. package/dist/tools/guide.d.ts +30 -0
  58. package/dist/tools/guide.js +97 -0
  59. package/dist/tools/lists.d.ts +9 -0
  60. package/dist/tools/lists.js +205 -0
  61. package/dist/tools/meta.d.ts +22 -0
  62. package/dist/tools/meta.js +709 -0
  63. package/dist/tools/output-file.d.ts +26 -0
  64. package/dist/tools/output-file.js +140 -0
  65. package/dist/tools/rank.d.ts +21 -0
  66. package/dist/tools/rank.js +57 -0
  67. package/dist/tools/reasons.d.ts +33 -0
  68. package/dist/tools/reasons.js +121 -0
  69. package/dist/tools/register.d.ts +23 -0
  70. package/dist/tools/register.js +50 -0
  71. package/dist/tools/resolves.d.ts +28 -0
  72. package/dist/tools/resolves.js +399 -0
  73. package/dist/tools/results/envelope.d.ts +55 -0
  74. package/dist/tools/results/envelope.js +63 -0
  75. package/dist/tools/results/errors.d.ts +147 -0
  76. package/dist/tools/results/errors.js +384 -0
  77. package/dist/tools/results/untrusted.d.ts +129 -0
  78. package/dist/tools/results/untrusted.js +218 -0
  79. package/dist/tools/revenue-rollup.d.ts +8 -0
  80. package/dist/tools/revenue-rollup.js +112 -0
  81. package/dist/tools/schemas.d.ts +467 -0
  82. package/dist/tools/schemas.js +444 -0
  83. package/dist/tools/scope-guard.d.ts +2 -0
  84. package/dist/tools/scope-guard.js +11 -0
  85. package/dist/tools/server-version.d.ts +3 -0
  86. package/dist/tools/server-version.js +14 -0
  87. package/dist/tools/server.d.ts +92 -0
  88. package/dist/tools/server.js +170 -0
  89. package/dist/tools/surface.d.ts +37 -0
  90. package/dist/tools/surface.js +94 -0
  91. package/dist/tools/tsv.d.ts +52 -0
  92. package/dist/tools/tsv.js +95 -0
  93. package/dist/tools/write/apply.d.ts +40 -0
  94. package/dist/tools/write/apply.js +500 -0
  95. package/dist/tools/write/checks.d.ts +39 -0
  96. package/dist/tools/write/checks.js +137 -0
  97. package/dist/tools/write/common.d.ts +23 -0
  98. package/dist/tools/write/common.js +33 -0
  99. package/dist/tools/write/facts.d.ts +52 -0
  100. package/dist/tools/write/facts.js +151 -0
  101. package/dist/tools/write/outcome.d.ts +23 -0
  102. package/dist/tools/write/outcome.js +67 -0
  103. package/dist/tools/write/parse.d.ts +37 -0
  104. package/dist/tools/write/parse.js +166 -0
  105. package/dist/tools/write/payload.d.ts +44 -0
  106. package/dist/tools/write/payload.js +119 -0
  107. package/dist/tools/write/preview.d.ts +3 -0
  108. package/dist/tools/write/preview.js +317 -0
  109. package/dist/tools/write/snapshot.d.ts +68 -0
  110. package/dist/tools/write/snapshot.js +360 -0
  111. package/dist/tools/write-guidance.d.ts +174 -0
  112. package/dist/tools/write-guidance.js +317 -0
  113. package/dist/tools/write.d.ts +9 -0
  114. package/dist/tools/write.js +10 -0
  115. package/dist/write/canonical.d.ts +12 -0
  116. package/dist/write/canonical.js +31 -0
  117. package/dist/write/evaluate.d.ts +77 -0
  118. package/dist/write/evaluate.js +91 -0
  119. package/dist/write/hard-rules.d.ts +49 -0
  120. package/dist/write/hard-rules.js +48 -0
  121. package/dist/write/runtime.d.ts +37 -0
  122. package/dist/write/runtime.js +72 -0
  123. package/dist/write/store/audit-log.d.ts +13 -0
  124. package/dist/write/store/audit-log.js +25 -0
  125. package/dist/write/store/constants.d.ts +34 -0
  126. package/dist/write/store/constants.js +35 -0
  127. package/dist/write/store/files.d.ts +44 -0
  128. package/dist/write/store/files.js +157 -0
  129. package/dist/write/store/heartbeat.d.ts +9 -0
  130. package/dist/write/store/heartbeat.js +65 -0
  131. package/dist/write/store/ledger.d.ts +15 -0
  132. package/dist/write/store/ledger.js +86 -0
  133. package/dist/write/store/lifecycle.d.ts +35 -0
  134. package/dist/write/store/lifecycle.js +114 -0
  135. package/dist/write/store/lock.d.ts +97 -0
  136. package/dist/write/store/lock.js +464 -0
  137. package/dist/write/store/op-lock.d.ts +13 -0
  138. package/dist/write/store/op-lock.js +175 -0
  139. package/dist/write/store/plan-store.d.ts +7 -0
  140. package/dist/write/store/plan-store.js +48 -0
  141. package/dist/write/store/plans.d.ts +5 -0
  142. package/dist/write/store/plans.js +19 -0
  143. package/dist/write/store/types.d.ts +195 -0
  144. package/dist/write/store/types.js +2 -0
  145. package/dist/write/store.d.ts +6 -0
  146. package/dist/write/store.js +182 -0
  147. package/examples/agentgateway.write-gate.yaml +29 -0
  148. package/package.json +71 -0
  149. package/server.json +69 -0
  150. package/skills/ar-aging.md +65 -0
  151. package/skills/company-360.md +69 -0
  152. package/skills/contract-profitability.md +65 -0
  153. package/skills/crm-management.md +87 -0
  154. package/skills/filter-semantics.md +75 -0
  155. package/skills/invoice-export.md +61 -0
  156. package/skills/log-time-entry.md +77 -0
  157. package/skills/non-chargeable-work.md +67 -0
  158. package/skills/portfolio-margin.md +66 -0
  159. package/skills/recurring-revenue.md +65 -0
  160. package/skills/revenue-rollup.md +65 -0
  161. package/skills/slim-reads.md +67 -0
  162. package/skills/ticket-triage.md +64 -0
  163. package/skills/unbilled-work-review.md +66 -0
  164. package/skills/wip-hours.md +68 -0
@@ -0,0 +1,500 @@
1
+ /**
2
+ * Apply one stored plan, preserving admission, human confirmation, fresh reads, claim and one send.
3
+ * Two tools, by risk (#302): `autotask_apply` takes plans that hit no hard rule, `autotask_apply_destructive`
4
+ * the ones that do; the transport decides who approves (stdio: this server, HTTP: the client or gateway).
5
+ */
6
+ import { APPLY_INPUT, APPLY_PARSE, closedInput } from '../schemas.js';
7
+ import { writeDeps } from './common.js';
8
+ import { gateApply } from '../../access/gate.js';
9
+ import { classifyWriteOutcome, MoveRefusedError } from 'node-autotask';
10
+ import { notPersistedFields } from 'node-autotask/operations';
11
+ import { stripUntrustedDeep } from 'node-autotask/untrusted';
12
+ import { requestSecrets, readOneItem } from '../dispatch.js';
13
+ import { abortedResult, typedErrorPayload } from '../results/errors.js';
14
+ import {} from '../results/envelope.js';
15
+ import { ConfigError } from '../../config/schema.js';
16
+ import { canonicalJson, planHashOf } from '../../write/canonical.js';
17
+ import { dedupFor, evaluate, pinAudit, PIN_RULE } from '../../write/evaluate.js';
18
+ import { writeShape } from '../../write/hard-rules.js';
19
+ import { COOLDOWN_MINUTES } from '../../write/store.js';
20
+ import { Cancelled, tenantIdentity, answer, reason } from './common.js';
21
+ import { SHAPE_ARGS, parseArgs } from './parse.js';
22
+ import { ci } from './payload.js';
23
+ import { getIds, takeSnapshot } from './snapshot.js';
24
+ import { unresolvedReason, deriveFacts } from './facts.js';
25
+ import { honestError, notPersistedAnswer, outcomeAnswer } from './outcome.js';
26
+ /**
27
+ * Who must approve one apply: `person` (stdio form or grant), `policy:unattended`, `client` (HTTP), or
28
+ * undefined (stdio `allow` and no hard rule: no approval is recorded). `hard`: the plan hits a hard rule.
29
+ */
30
+ export function approverFor(transport, mode, hard) {
31
+ if (mode === undefined || mode === 'deny')
32
+ return undefined; // evaluate() refuses it
33
+ if (transport === 'http')
34
+ return 'client';
35
+ if (mode === 'unattended')
36
+ return 'policy:unattended';
37
+ return mode === 'confirm' || hard ? 'person' : undefined;
38
+ }
39
+ /** The `refused` helper: audits `apply_refused`, then answers. */
40
+ function makeRefused(w, store, now, handle) {
41
+ return (status, next, r, plan, extra = {}) => {
42
+ store.audit({ event: 'apply_refused', principal: w.principal, op: plan?.op ?? '-', ...(plan !== undefined ? { targets: plan.targets, planHash: plan.planHash } : {}), decision: status, reasons: [r.code], ...(plan !== undefined ? pinAudit(plan.facts, w.runtime.loaded, w.runScope) : {}) }, now());
43
+ return answer(status, next, [r], plan === undefined ? { plan: handle } : { operation: plan.op, targets: plan.targets }, {
44
+ ...(plan !== undefined ? { plan: plan.handle, planHash: plan.planHash } : {}),
45
+ ...extra,
46
+ });
47
+ };
48
+ }
49
+ /** The first lookup, the blocked check, the plan itself and who may apply it: everything before the apply lock. */
50
+ function admit(a) {
51
+ const { ctx, w, store, handle, refused } = a;
52
+ const block = store.blocked();
53
+ if (block !== undefined) {
54
+ return refused(block.next === 'retry' ? 'error' : 'denied', block.next, reason(block.code, block.detail), undefined, { retryable: block.next === 'retry' });
55
+ }
56
+ const plan = store.loadPlan(handle);
57
+ if (plan === undefined)
58
+ return refused('error', 'repreview', reason('PLAN_NOT_FOUND', 'no plan with this handle (unknown, expired and pruned, or not authentic); preview again'));
59
+ // Old plan identities cannot replay the new ledger contract; encrypted records remain authenticated by AES-GCM.
60
+ if ('snapshotHash' in plan || !/^sha256:[a-f0-9]{64}$/.test(plan.planHash) || typeof plan.summary !== 'string')
61
+ return refused('error', 'repreview', reason('PLAN_NOT_FOUND', 'this plan uses an older format; preview again'));
62
+ // A handle is never authentication: the caller must be the principal and the tenant that previewed.
63
+ if (plan.principal !== w.principal || plan.tenantId !== store.tenantId(tenantIdentity(ctx))) {
64
+ return refused('denied', 'stop', reason('PRINCIPAL_MISMATCH', 'this plan belongs to another principal or another Autotask tenant credential'), plan);
65
+ }
66
+ return plan;
67
+ }
68
+ /** #301: the caller's echo of the preview's `approval` must equal the stored plan exactly; checked before anything else runs. */
69
+ function echoAnswer(a, echo) {
70
+ const { plan, refused } = a;
71
+ const wrong = [
72
+ echo.operation !== plan.op && 'operation',
73
+ canonicalJson(echo.targets ?? null) !== canonicalJson(plan.targets) && 'targets',
74
+ echo.summary !== plan.summary && 'summary',
75
+ ].filter((f) => f !== false);
76
+ if (wrong.length === 0)
77
+ return undefined;
78
+ return refused('denied', 'repreview', reason('PLAN_MISMATCH', `${wrong.join(', ')} must be copied verbatim from the preview's approval (missing or different); nothing was sent`), plan);
79
+ }
80
+ /** Whether a ledger hit ends the apply (a conflict or a replay); only a retryable failure that wrote nothing runs again. */
81
+ const hitEnds = (plan, hit) => hit.planHash !== plan.planHash || !(hit.state === 'failed' && hit.outcome?.retryable === true);
82
+ /** An expired plan, or one previewed under another policy: refused before anything else (the gate included). */
83
+ function staleAnswer(a) {
84
+ const { loaded, now, plan, refused } = a;
85
+ if (now() > plan.expiresAt)
86
+ return refused('error', 'repreview', reason('PLAN_EXPIRED', 'the plan has expired; preview again'), plan);
87
+ if (plan.policyHash !== loaded.policyHash)
88
+ return refused('error', 'repreview', reason('STATE_DRIFT', 'the policy changed since the preview; preview again'), plan);
89
+ return undefined;
90
+ }
91
+ // The hit answer — shared by the FIRST lookup (its old position) and the claim's rescan:
92
+ // the same plan hash answers with the recorded outcome (`replayed: true`), except a
93
+ // retryable failure that wrote nothing (a 429) which may run again under the same key;
94
+ // `undefined` means a retryable no-send failure may run again.
95
+ function hitAnswer(a, hit) {
96
+ const { plan } = a;
97
+ // F1: a retryable failure (a 429, or refused before it was sent) wrote nothing, so the
98
+ // same plan may run again under the same key; the SDK's own cooldown still gates the
99
+ // send. Everything else replays: succeeded, a deterministic failure, and above all
100
+ // `unknown` and a lingering `sending` (a peer's in-flight write, issue #68), which are
101
+ // never re-sent (a changed plan needs a fresh preview, whose duplicate
102
+ // query finds a write that did land).
103
+ if (hitEnds(plan, hit))
104
+ return outcomeAnswer(plan, hit, { replayed: true });
105
+ return undefined;
106
+ }
107
+ /** Run one admitted plan: replay, re-read and evaluate, atomically claim, then send once. */
108
+ async function execute(a, confirmation) {
109
+ const { ctx, w, store, loaded, now, signal, plan, refused } = a;
110
+ // GATES in the old relative order (issue #68): the first lookup is a FRESH from-disk
111
+ // scan, no op lock — a same-key replay NEVER dials the vendor, so an apply after a
112
+ // landed write answers from the ledger; a snapshot re-read before this gate would read
113
+ // the CHANGED vendor state, drift, and refuse before reaching the replay path (the
114
+ // ordering flaw that broke acceptance criterion 3).
115
+ const hit = store.lookup(plan.planHash);
116
+ if (hit !== undefined) {
117
+ const early = hitAnswer(a, hit);
118
+ if (early !== undefined)
119
+ return early;
120
+ }
121
+ const stale = staleAnswer(a);
122
+ if (stale !== undefined)
123
+ return stale;
124
+ const decision = evaluate(loaded, plan.facts, w.runScope, store.counters(plan.op, now()));
125
+ if (decision.decision === 'deny')
126
+ return refused('denied', 'stop', decision.reasons[0], plan);
127
+ // Defence in depth: a plan that needs an approver never runs without one (fail closed, zero vendor calls).
128
+ if (approverFor(loaded.transport, loaded.table.get(plan.op)?.mode, plan.decision === 'gate' || decision.decision === 'gate') !== undefined && confirmation === undefined) {
129
+ return refused('denied', 'stop', reason('GATE_UNSUPPORTED', `${plan.op} needs a person to confirm it, and none was given; nothing was sent`), plan);
130
+ }
131
+ if (store.coolingDown(plan.facts.targetKey, now())) {
132
+ // The cooldown length comes from the server's own constant (issue #252): no hard-typed minute count.
133
+ return refused('denied', 'verify_then_repreview', reason('COOLDOWN_ACTIVE', `an earlier write to this target has an unknown outcome; re-read it, then preview again after the ${COOLDOWN_MINUTES}-minute cooldown`), plan);
134
+ }
135
+ // The snapshot re-read (the only vendor call before the send) stays OUTSIDE the op lock
136
+ // — the claim's critical section must never span a vendor round-trip (issue #68) — in
137
+ // its old position: after the gates above, before the claim.
138
+ const record = ctx.record(plan.op);
139
+ const shape = writeShape(record);
140
+ if (shape === 'move') {
141
+ // a move has no data: the targets the snapshot reads must be the ones the args name (never trusted from the stored plan)
142
+ const again = parseArgs(shape, record, plan.args);
143
+ if ('code' in again || canonicalJson(again.targets) !== canonicalJson(plan.targets))
144
+ return refused('error', 'repreview', reason('PLAN_NOT_FOUND', 'the stored plan targets do not match its arguments (not authentic); preview again'), plan);
145
+ }
146
+ const parsed = { args: plan.args, targets: plan.targets, ...(SHAPE_ARGS[shape].includes('data') ? { data: plan.args.at(-1) } : {}) };
147
+ let snap;
148
+ try {
149
+ snap = await takeSnapshot(ctx, record, parsed, dedupFor(loaded, plan.op), signal);
150
+ }
151
+ catch (err) {
152
+ if (err instanceof Cancelled)
153
+ return abortedResult();
154
+ throw err;
155
+ }
156
+ if (!('code' in snap) && snap.unresolved.length > 0)
157
+ return refused('denied', 'stop', unresolvedReason(snap.unresolved), plan);
158
+ if ('code' in snap) {
159
+ return refused('error', 'repreview', reason('STATE_DRIFT', 'the target changed since the preview; preview again'), plan);
160
+ }
161
+ // Issue #106: evaluate FRESH facts (rebuilt from the re-read, never the stored ones) after the re-read.
162
+ const fresh = deriveFacts({ store, op: plan.op, record, shape, parsed, snap });
163
+ const freshDecision = evaluate(loaded, fresh, w.runScope, store.counters(plan.op, now()));
164
+ // The pin has explicit duplicate/cap refusals; other changed facts retain the drift contract.
165
+ if (freshDecision.decision === 'deny' && freshDecision.rule === PIN_RULE)
166
+ return refused('denied', 'stop', freshDecision.reasons[0], plan);
167
+ // the human confirmed these facts; different fresh facts are drift, and the old confirmation is unusable
168
+ if (planHashOf({ ...plan, snapshot: snap.inputs, facts: fresh, policyHash: loaded.policyHash }) !== plan.planHash || (confirmation !== undefined && confirmation.planHash !== plan.planHash)) {
169
+ return refused('error', 'repreview', reason('STATE_DRIFT', 'the facts behind this plan changed since the confirmation; preview again'), plan);
170
+ }
171
+ if (freshDecision.decision === 'deny')
172
+ return refused('denied', 'stop', freshDecision.reasons[0], plan);
173
+ // an allow plan whose fresh facts now need a person was not what the preview promised
174
+ if (plan.decision === 'allow' && freshDecision.decision === 'gate') {
175
+ return refused('error', 'repreview', reason('STATE_DRIFT', 'the write now needs a person to confirm it (the facts changed since the preview); preview again'), plan);
176
+ }
177
+ // Last point a cancellation stops the write before anything is claimed: nothing has been sent.
178
+ if (signal?.aborted === true)
179
+ return abortedResult();
180
+ let base = { idemKey: plan.planHash, planHash: plan.planHash, targetKey: plan.facts.targetKey, op: plan.op };
181
+ const opBlocked = store.acquireOpLock();
182
+ if (opBlocked !== undefined) {
183
+ return refused('error', 'retry', reason(opBlocked.code, opBlocked.detail), plan, { retryable: true });
184
+ }
185
+ try {
186
+ if (confirmation !== undefined)
187
+ base = { ...base, approverId: confirmation.via };
188
+ const late = store.blocked();
189
+ if (late !== undefined)
190
+ return refused(late.next === 'retry' ? 'error' : 'denied', late.next, reason(late.code, late.detail), plan, { retryable: late.next === 'retry' });
191
+ const rescan = store.lookup(plan.planHash);
192
+ if (rescan !== undefined) {
193
+ const lateHit = hitAnswer(a, rescan);
194
+ if (lateHit !== undefined)
195
+ return lateHit;
196
+ }
197
+ if (store.coolingDown(plan.facts.targetKey, now()))
198
+ return refused('denied', 'verify_then_repreview', reason('COOLDOWN_ACTIVE', 'another write to this target is in flight or has an unknown outcome; verify it before previewing again'), plan);
199
+ const checked = evaluate(a.loaded, plan.facts, a.w.runScope, store.counters(plan.op, now()));
200
+ if (checked.decision === 'deny')
201
+ return refused('denied', 'stop', checked.reasons[0], plan);
202
+ store.append({ ...base, state: 'sending', at: now() });
203
+ }
204
+ finally {
205
+ store.releaseOpLock();
206
+ }
207
+ const sent = await send(a, { confirmation, record, shape, snap, base });
208
+ recordResult(a, sent.entry, confirmation);
209
+ return respond(a, { record, shape, entry: sent.entry, error: sent.error, moveResult: sent.moveResult, callResult: sent.callResult });
210
+ }
211
+ /** `apply_start`, then the one SDK write under the cap. Never returns a ToolReturn: the outcome is always a ledger entry. */
212
+ async function send(a, s) {
213
+ const { ctx, w, store, now, plan } = a;
214
+ const { confirmation, record, shape, snap, base } = s;
215
+ store.audit({ event: 'apply_start', principal: w.principal, op: plan.op, targets: plan.targets, planHash: plan.planHash, decision: 'sending', reasons: [], ...pinAudit(plan.facts, w.runtime.loaded, w.runScope), ...(confirmation !== undefined ? { approverId: confirmation.via } : {}) }, now());
216
+ // The SDK write: no MCP signal (M7, never aborted once sending), capped at the apply wait.
217
+ // Retries are off via the PER-CALL maxRetries: 0 on the tenant client (node-autotask#105:
218
+ // exactly one send) — a write is never auto-retried, whatever the client's configured
219
+ // budget; no dedicated client.
220
+ const confirm = record.effect === 'destructive' || record.flags.includes('requiresApproval') ? { confirm: plan.op } : {};
221
+ const invoke = record.effect === 'destructive' ? ctx.ops.invokeDelete : ctx.ops.invokeWrite;
222
+ let timer;
223
+ const capped = new Promise((resolve) => {
224
+ timer = setTimeout(() => resolve('cap'), w.runtime.applyCapMs);
225
+ timer.unref?.();
226
+ });
227
+ let entry;
228
+ let error;
229
+ let moveResult;
230
+ let callResult;
231
+ try {
232
+ // ponytail: past the cap the write keeps running and its late answer is not recorded; the
233
+ // outcome stays unknown (cooldown, re-read) rather than racing a second ledger update.
234
+ // a move also passes the source's lastModified stamp (the SDK's stale-object guard, a second guard behind the server's snapshot re-read)
235
+ const stamp = shape === 'move' ? ci(snap.current ?? {}, 'lastModifiedDateTime') : undefined;
236
+ const moveOpts = typeof stamp === 'string' ? { lastModifiedDate: stamp } : {};
237
+ const result = await Promise.race([invoke(ctx.client, plan.op, plan.args, { dryRun: false, ...confirm, ...moveOpts, maxRetries: 0 }), capped]);
238
+ if (result === 'cap') {
239
+ entry = { ...base, state: 'unknown', at: now(), outcome: { code: 'APPLY_TIMEOUT' } };
240
+ }
241
+ else if (shape === 'move') {
242
+ // the SDK's MoveResult: ids and a status only (its `snapshot` carries note text and never reaches the ledger, audit or envelope)
243
+ const m = result;
244
+ const newId = typeof m?.newId === 'number' ? m.newId : undefined;
245
+ const clean = newId !== undefined && (m?.status === 'moved' || m?.status === 'moved_source_absent' || m?.status === 'moved_manual_delete');
246
+ // the contract is a MoveResult or a thrown refusal: anything else is NOT recorded as a success (fail closed, never re-sent)
247
+ entry = !clean
248
+ ? { ...base, state: 'unknown', at: now(), outcome: { code: 'MOVE_UNKNOWN', retryable: false, ...(plan.targets.id !== undefined ? { sourceId: plan.targets.id } : {}), ...(newId !== undefined ? { newId } : {}) } }
249
+ : {
250
+ ...base,
251
+ state: 'succeeded',
252
+ at: now(),
253
+ outcome: {
254
+ ...(newId !== undefined ? { id: newId, newId } : {}),
255
+ ...(plan.targets.id !== undefined ? { sourceId: plan.targets.id } : {}),
256
+ ...(m?.status === 'moved_manual_delete' ? { code: 'MOVE_MANUAL_DELETE' } : m?.status === 'moved_source_absent' ? { code: 'MOVE_SOURCE_ABSENT' } : {}),
257
+ },
258
+ };
259
+ moveResult = m === null ? undefined : { status: String(m.status), correlationId: typeof m.correlationId === 'string' ? m.correlationId : undefined, ...(m.manualAction !== undefined ? { manualAction: { action: m.manualAction.action, uiLink: m.manualAction.uiLink, reason: m.manualAction.reason } } : {}) };
260
+ }
261
+ else {
262
+ if (shape === 'call')
263
+ callResult = result;
264
+ const id = result?.id;
265
+ const createdId = typeof id === 'number' || typeof id === 'string' ? id : undefined;
266
+ entry = {
267
+ ...base,
268
+ state: 'succeeded',
269
+ at: now(),
270
+ outcome: createdId === undefined ? {} : { id: createdId },
271
+ ...(shape.startsWith('create') && createdId !== undefined
272
+ ? { created: { resource: record.resource, id: createdId, companyIds: plan.facts.companyIds, principal: plan.principal, tenantId: plan.tenantId } }
273
+ : {}),
274
+ };
275
+ }
276
+ }
277
+ catch (err) {
278
+ error = err;
279
+ const refusal = err instanceof MoveRefusedError ? err.details : undefined;
280
+ if (err instanceof MoveRefusedError && (refusal?.status === 'partial' || refusal?.status === 'unknown')) {
281
+ // the engine's partial/unknown (both records may exist): never a plain failure, never re-sent
282
+ entry = {
283
+ ...base,
284
+ state: 'unknown',
285
+ at: now(),
286
+ outcome: { code: refusal.status === 'partial' ? 'MOVE_PARTIAL' : 'MOVE_UNKNOWN', retryable: false, ...(plan.targets.id !== undefined ? { sourceId: plan.targets.id } : {}), ...(typeof refusal.newId === 'number' ? { newId: refusal.newId } : {}) },
287
+ };
288
+ }
289
+ else if (err instanceof MoveRefusedError) {
290
+ // a hard refusal or a rolled-back attempt: nothing is left behind, and a re-send would be refused again
291
+ entry = { ...base, state: 'failed', at: now(), outcome: { code: err.code ?? 'MOVE_REFUSED', retryable: false } };
292
+ }
293
+ else {
294
+ const c = classifyWriteOutcome(err); // the SDK's write-outcome classifier (node-autotask#104): unknown is never a blind resend
295
+ entry = { ...base, state: c.state, at: now(), outcome: { code: c.code, retryable: c.retryable, ...(c.httpStatus !== undefined ? { httpStatus: c.httpStatus } : {}) } };
296
+ }
297
+ }
298
+ finally {
299
+ clearTimeout(timer);
300
+ }
301
+ return { entry, error, moveResult, ...(shape === 'call' ? { callResult: callResult ?? null } : {}) };
302
+ }
303
+ /** Record the outcome (under the op lock) and run the post-write standing check. Throws a ConfigError by design; never caught here. */
304
+ function recordResult(a, entry, confirmation) {
305
+ const { ctx, w, store, now, plan } = a;
306
+ // The result append takes the op lock (issue #68 review): one O_APPEND line is not
307
+ // enough — a peer that boots between our open('a') and writeSync renames the ledger out
308
+ // from under the write, and the `succeeded` line (with its `created` block) is orphaned
309
+ // on the old inode. Under the op lock the append serialises with the boot rewrite and
310
+ // with the peer's claim, and the apply_result audit rides the SAME acquisition (audit is
311
+ // re-entrant-aware: it appends directly while the lock is ours).
312
+ const blockedAfter = store.acquireOpLock();
313
+ if (blockedAfter !== undefined) {
314
+ throw new ConfigError(`AUTOTASK_STATE_DIR: the write may have landed on the vendor side, but its result could not be recorded (${blockedAfter.detail}); re-read the target before any retry`);
315
+ }
316
+ try {
317
+ store.append(entry);
318
+ store.audit({ event: 'apply_result', principal: w.principal, op: plan.op, targets: plan.targets, planHash: plan.planHash, decision: entry.state, reasons: entry.outcome?.code === undefined ? [] : [entry.outcome.code], ...pinAudit(plan.facts, w.runtime.loaded, w.runScope), ...(confirmation !== undefined ? { approverId: confirmation.via } : {}) }, now());
319
+ ctx.log.info('write applied', { op: plan.op, outcome: entry.state });
320
+ }
321
+ finally {
322
+ store.releaseOpLock();
323
+ }
324
+ // The last blocked() gate was before the vendor send: this process's holder registration
325
+ // may have been removed while the write was in flight. A GENUINE stop (STATE_UNAVAILABLE
326
+ // with next === 'stop': the registration was deleted) throws — answering success for a
327
+ // write that an external actor has already stopped is worse than a loud failure (the
328
+ // ledger and audit lines WERE written; the failure is about this process's standing).
329
+ // A kill switch that comes up during the send does NOT throw: the registration is still
330
+ // present, the audit line appends, and the kill switch stops the NEXT write (the
331
+ // main-branch behaviour, kept deliberately). A transient unreadable registration
332
+ // (STATE_UNAVAILABLE with next === 'retry') proceeds to the audit as normal: the write
333
+ // completed.
334
+ const after = store.blocked();
335
+ if (after !== undefined && after.code === 'STATE_UNAVAILABLE' && after.next === 'stop') {
336
+ throw new ConfigError(`AUTOTASK_STATE_DIR: this process's holder registration was removed while the write was in flight; the write completed on the vendor side and its ledger and audit lines were recorded, but this process is stopped (${after.detail})`);
337
+ }
338
+ }
339
+ /** Waits before each re-read of an update whose first read-back looks stale (#184); tests set it to zeros. */
340
+ export const READBACK_RECHECK = { delaysMs: [750, 1500] };
341
+ /**
342
+ * Record a FIELD_NOT_PERSISTED miss as a later ledger line (the latest line wins, so a replay
343
+ * answers the same reasons). The op lock may be held by a concurrent apply for a moment: wait a
344
+ * few short beats for it. Returns false when the lock never freed — the caller says so in its
345
+ * answer instead of letting a replay quietly answer plain ok.
346
+ */
347
+ export async function recordMiss(store, entry, attempts = 10, waitMs = 100) {
348
+ for (let i = 0; i < attempts; i += 1) {
349
+ if (store.acquireOpLock() === undefined) {
350
+ try {
351
+ store.append(entry);
352
+ }
353
+ finally {
354
+ store.releaseOpLock();
355
+ }
356
+ return true;
357
+ }
358
+ if (i < attempts - 1)
359
+ await new Promise((resolve) => setTimeout(resolve, waitMs));
360
+ }
361
+ return false;
362
+ }
363
+ /** Answer from the recorded entry: failures, moves, and the read-backs of creates and updates. */
364
+ async function respond(a, r) {
365
+ const { ctx, store, plan } = a;
366
+ const { record, shape, entry, error, moveResult, callResult } = r;
367
+ if (entry.state !== 'succeeded') {
368
+ const data = error === undefined ? {} : { error: honestError(typedErrorPayload(error, ctx.correlationId, requestSecrets(ctx)), error, entry) };
369
+ return outcomeAnswer(plan, entry, { replayed: false, data });
370
+ }
371
+ if (shape === 'move')
372
+ return outcomeAnswer(plan, entry, { replayed: false, ...(moveResult !== undefined ? { data: { move: moveResult } } : {}) });
373
+ // The generic shape answers the operation's own result (the ledger records ids and the outcome, never a payload)
374
+ if (shape === 'call')
375
+ return outcomeAnswer(plan, entry, { replayed: false, result: callResult ?? null });
376
+ // A create reads its stored record back (one governed get); a failed read-back never fails the write.
377
+ if (shape.startsWith('create') && entry.outcome?.id !== undefined) {
378
+ try {
379
+ const back = await readOneItem(ctx, `${record.resource}.get`, getIds(ctx, record.resource, plan.targets.parentId, entry.outcome.id), undefined);
380
+ return outcomeAnswer(plan, entry, { replayed: false, data: { record: back.result ?? null } });
381
+ }
382
+ catch (err) {
383
+ const code = String(typedErrorPayload(err, ctx.correlationId).code);
384
+ return outcomeAnswer(plan, entry, {
385
+ replayed: false,
386
+ data: { record: null },
387
+ summary: `${plan.op} succeeded, but the stored record read-back failed (${code}): the entry was created; its id rides the result envelope.`,
388
+ });
389
+ }
390
+ }
391
+ // An update reads its stored record back too (issue #103): the vendor accepts some updates and
392
+ // silently keeps the old value. The HTTP write succeeded and the ledger says so; the envelope
393
+ // is not plain ok when a field the caller sent is not what is stored. A failed read-back never
394
+ // fails the write.
395
+ if ((shape === 'update' || shape === 'update_child') && plan.targets.id !== undefined) {
396
+ try {
397
+ // Issue #184: the vendor's read path can lag its write (~0.6 s seen on ww29), so one zero-delay
398
+ // read that still shows the old value is not proof the field was dropped. Re-read a bounded
399
+ // number of times before the hard "do not repeat" verdict.
400
+ const sent = plan.args.at(-1);
401
+ const id = plan.targets.id;
402
+ const readBack = () => readOneItem(ctx, `${record.resource}.get`, getIds(ctx, record.resource, plan.targets.parentId, id), undefined, { fresh: true }); // every read-back (and re-read) hits the wire
403
+ let back = await readBack();
404
+ let missed = [];
405
+ for (let i = 0;; i++) {
406
+ const stored = back.result !== null && typeof back.result === 'object' ? stripUntrustedDeep(back.result) : undefined;
407
+ missed = stored === undefined || sent === null || typeof sent !== 'object' ? [] : notPersistedFields(sent, stored);
408
+ const delay = READBACK_RECHECK.delaysMs[i];
409
+ if (missed.length === 0 || delay === undefined)
410
+ break;
411
+ await new Promise((resolve) => setTimeout(resolve, delay));
412
+ back = await readBack();
413
+ }
414
+ if (missed.length === 0)
415
+ return outcomeAnswer(plan, entry, { replayed: false, data: { record: back.result ?? null } });
416
+ // record the miss: the latest ledger line wins, so a replay answers the same reasons.
417
+ const missedEntry = { ...entry, outcome: { ...entry.outcome, code: 'FIELD_NOT_PERSISTED', fields: missed } };
418
+ const recorded = await recordMiss(store, missedEntry);
419
+ if (!recorded)
420
+ ctx.log.warn('FIELD_NOT_PERSISTED could not be recorded in the ledger (op lock busy)', { op: plan.op });
421
+ return notPersistedAnswer(plan, missedEntry, missed, { replayed: false, record: back.result ?? null, unrecorded: !recorded });
422
+ }
423
+ catch (err) {
424
+ const code = String(typedErrorPayload(err, ctx.correlationId).code);
425
+ return outcomeAnswer(plan, entry, {
426
+ replayed: false,
427
+ data: { record: null },
428
+ summary: `${plan.op} succeeded, but the stored record read-back failed (${code}); whether every field was applied is unverified — re-read the record.`,
429
+ });
430
+ }
431
+ }
432
+ return outcomeAnswer(plan, entry, { replayed: false });
433
+ }
434
+ /** The apply tool for a plan: a plan that hits a hard rule applies only through the destructive one (#302). */
435
+ export const applyToolFor = (plan) => plan.decision === 'gate' ? 'autotask_apply_destructive' : 'autotask_apply';
436
+ /** Build an apply tool (`destructive`: autotask_apply_destructive); human confirmation happens outside the apply lock. */
437
+ export function buildApply(ctx, destructive = false) {
438
+ const tool = destructive ? 'autotask_apply_destructive' : 'autotask_apply';
439
+ return {
440
+ title: destructive ? 'Apply one previewed Autotask write plan that names this tool (deletes, webhooks, sensitive or approval-required operations, moves that change company or contract)' : 'Apply one previewed Autotask write plan',
441
+ input: { ...closedInput(APPLY_INPUT), schema: APPLY_PARSE },
442
+ run: async (raw, signal, extra) => {
443
+ const w = writeDeps(ctx);
444
+ const { store, loaded, grants } = w.runtime;
445
+ const now = w.runtime.now;
446
+ const handle = raw.plan;
447
+ const refused = makeRefused(w, store, now, handle);
448
+ const first = { ctx, w, store, loaded, now, signal, handle, refused };
449
+ const admitted = admit(first);
450
+ if ('content' in admitted)
451
+ return admitted;
452
+ const a = { ...first, plan: admitted };
453
+ const plan = a.plan;
454
+ const mismatch = echoAnswer(a, raw);
455
+ if (mismatch !== undefined)
456
+ return mismatch;
457
+ // the tool a client gates by name must be the plan's own, on every transport
458
+ if (applyToolFor(plan) !== tool) {
459
+ return refused('denied', 'supply_input', reason('PLAN_MISMATCH', `this plan ${plan.decision === 'gate' ? 'hits a hard rule' : 'hits no hard rule'}: apply it with ${applyToolFor(plan)}; nothing was sent`), plan);
460
+ }
461
+ // Who approves (#302). HTTP: the client or gateway did, so the server never asks. stdio: the
462
+ // mode decides; a person's answer runs over the LOADED plan and OUTSIDE the apply lock (it must
463
+ // never hold it). A ledger hit that ends the apply (a replay) answers in execute() without asking;
464
+ // a retryable failure that wrote nothing runs again, so it asks again. An expired or drifted plan
465
+ // is refused before asking.
466
+ const needs = approverFor(loaded.transport, loaded.table.get(plan.op)?.mode, plan.decision === 'gate');
467
+ let confirmation;
468
+ if (needs === 'client' || needs === 'policy:unattended')
469
+ confirmation = { via: needs, planHash: plan.planHash };
470
+ const hit = store.lookup(plan.planHash);
471
+ if (needs === 'person' && (hit === undefined || !hitEnds(plan, hit))) {
472
+ const stale = staleAnswer(a);
473
+ if (stale !== undefined)
474
+ return stale;
475
+ const key = { principal: plan.principal, tenantId: plan.tenantId, policyHash: plan.policyHash, op: plan.op };
476
+ const grantId = grants.match(key, now());
477
+ if (grantId !== undefined) {
478
+ confirmation = { via: `session:${grantId}`, planHash: plan.planHash };
479
+ }
480
+ else {
481
+ const gate = gateApply({ plan, caller: { transport: 'stdio' }, extra, legacyCaps: ctx.clientCapabilities?.() });
482
+ if ('result' in gate) {
483
+ const out = gate.result;
484
+ // a typed deny (not the confirm form) is audited before it answers
485
+ if ('structuredContent' in out) {
486
+ const code = out.structuredContent.reasons[0].code;
487
+ store.audit({ event: 'gate_refused', principal: w.principal, op: plan.op, targets: plan.targets, planHash: plan.planHash, decision: 'denied', reasons: [code] }, now());
488
+ }
489
+ return out;
490
+ }
491
+ confirmation = gate.ok;
492
+ const granted = grants.add(key, gate.remember, now());
493
+ store.audit({ event: 'gate_confirmed', principal: w.principal, op: plan.op, targets: plan.targets, planHash: plan.planHash, decision: 'confirmed', reasons: granted === undefined ? [] : [`remember:${gate.remember}`], approverId: confirmation.via }, now());
494
+ }
495
+ }
496
+ return store.withApplyLock(() => execute(a, confirmation));
497
+ },
498
+ };
499
+ }
500
+ //# sourceMappingURL=apply.js.map
@@ -0,0 +1,39 @@
1
+ import type { ToolContext } from '../context/types.js';
2
+ import { type CreateFacts } from '../write-guidance.js';
3
+ export interface PicklistRow {
4
+ name: string;
5
+ isRequired?: boolean;
6
+ isReadOnly?: boolean;
7
+ type?: unknown;
8
+ picklistValues?: Array<{
9
+ value?: unknown;
10
+ isActive?: unknown;
11
+ parentValue?: unknown;
12
+ }>;
13
+ }
14
+ export interface Findings {
15
+ refuse: string[];
16
+ warn: string[];
17
+ }
18
+ export declare function listOf(xs: readonly string[]): string;
19
+ /** A write that sets one field of a coupled pair without the other (counting the stored record on update). No wire. */
20
+ export declare function pairFindings(resource: string, data: Record<string, unknown>, current?: Record<string, unknown>): Findings;
21
+ /** A changed picklist value the catalog marks isActive false: refuse where proven, warn elsewhere. */
22
+ export declare function picklistFindings(resource: string, data: Record<string, unknown>, fields: readonly PicklistRow[], current?: Record<string, unknown>): Findings;
23
+ /** A create's value gates and effective required set (SDK createGuidance) checked against the payload. */
24
+ export declare function gateFindings(data: Record<string, unknown>, facts: CreateFacts | undefined, required: {
25
+ fields: readonly string[];
26
+ from: string;
27
+ proven: boolean;
28
+ }, skip?: string): Findings;
29
+ /** One field-catalog read (labels; the SDK serves it from its field cache when warm) and the static zone facts. A failed read adds nothing. */
30
+ export declare function catalogFindings(ctx: ToolContext, p: {
31
+ resource: string;
32
+ op: 'create' | 'update';
33
+ data: Record<string, unknown>;
34
+ current?: Record<string, unknown>;
35
+ parentField?: string;
36
+ }, signal: AbortSignal | undefined): Promise<Findings & {
37
+ aborted?: boolean;
38
+ types?: Map<string, string>;
39
+ }>;