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,26 @@
1
+ /** The `output_path` walk cap: rows written at most, with an explicit truncation note. */
2
+ export declare const OUTPUT_MAX_ROWS = 10000;
3
+ /** The default output root's directory name under `AUTOTASK_STATE_DIR` (issue #101). */
4
+ export declare const DEFAULT_OUTPUT_SUBDIR = "output";
5
+ export interface OutputTargetRequest {
6
+ /** `AUTOTASK_OUTPUT_DIR` (undefined/blank = the default under the state dir). */
7
+ root: string | undefined;
8
+ /** `AUTOTASK_STATE_DIR`: the default root's parent. */
9
+ stateDir?: string | undefined;
10
+ /** The transport of this serving unit (`stdio` only). */
11
+ transport: string;
12
+ /** The caller's path, RELATIVE to the root. */
13
+ relativePath: string;
14
+ }
15
+ /** A validated target: the canonical path (as served in `outputPath`) and its one-shot writer. */
16
+ export interface OutputTarget {
17
+ path: string;
18
+ /** Create the file (never overwrite) and write `data` (UTF-8 string, or raw bytes); returns the byte size. */
19
+ write(data: string | Buffer): Promise<number>;
20
+ }
21
+ /**
22
+ * Validate an `output_path` before any vendor wire and return its writer. Creates the target's missing
23
+ * parent directories only after their deepest existing ancestor is verified inside the root.
24
+ * @throws {AutotaskConfigError} on every refusal above; nothing outside the root is ever created.
25
+ */
26
+ export declare function resolveOutputTarget(req: OutputTargetRequest): Promise<OutputTarget>;
@@ -0,0 +1,140 @@
1
+ /**
2
+ * tools/output-file.ts — `output_path` (issue #11, ruling N6): the ONE place this server writes a
3
+ * file, and every refusal that keeps it inside the operator's root.
4
+ *
5
+ * - **stdio only**: under `http` the caller is a request, not the process owner; refused before any path work.
6
+ * - **an env root** (`AUTOTASK_OUTPUT_DIR`, absolute, never `/`). Unset -> `output/` under
7
+ * `AUTOTASK_STATE_DIR` (issue #101, created one level deep); with neither set the feature refuses.
8
+ * An explicit root must already exist (the server never creates it).
9
+ * - **nothing outside the root is ever created.** The caller's path is relative and names a file. The
10
+ * deepest EXISTING ancestor is `realpath`-resolved and verified inside the root BEFORE any `mkdir`;
11
+ * the created parent is re-verified. The root itself may be a symlink (containment is against its target).
12
+ * - **never overwrites**: an existing target (file, symlink, dangling link, directory) is refused,
13
+ * checked before any vendor wire and again, atomically, by the `O_EXCL | O_NOFOLLOW` open, which can
14
+ * neither follow nor reuse anything swapped in after validation. The write re-resolves the parent.
15
+ * - every filesystem failure crosses as a typed refusal naming only the error CODE, never an OS message.
16
+ *
17
+ * Honest model note: under `stdio` the caller and this process are the SAME user. The protection is
18
+ * containment, not a defence against a same-user race on an INTERMEDIATE directory between the
19
+ * write-time parent check and the open (no portable `openat` in Node).
20
+ */
21
+ import { constants } from 'node:fs';
22
+ import { lstat, mkdir, open, realpath, stat, unlink } from 'node:fs/promises';
23
+ import { basename, dirname, isAbsolute, join, parse, relative, resolve, sep } from 'node:path';
24
+ import { AutotaskConfigError } from 'node-autotask';
25
+ /** The `output_path` walk cap: rows written at most, with an explicit truncation note. */
26
+ export const OUTPUT_MAX_ROWS = 10_000;
27
+ /** The default output root's directory name under `AUTOTASK_STATE_DIR` (issue #101). */
28
+ export const DEFAULT_OUTPUT_SUBDIR = 'output';
29
+ const NOTHING = ' — nothing was written';
30
+ const refuse = (message) => {
31
+ throw new AutotaskConfigError(`output_path: ${message}${NOTHING}`, { operation: 'output_path' });
32
+ };
33
+ const exists = (path) => refuse(`${path} already exists; the server never overwrites a file, pass a new path`);
34
+ /** True when `p` is outside `root` (or, unless `allowRoot`, is the root itself). */
35
+ const outside = (root, p, allowRoot = true) => {
36
+ const rel = relative(root, p);
37
+ return (rel === '' && !allowRoot) || rel.startsWith('..') || isAbsolute(rel);
38
+ };
39
+ /** One filesystem step; a failure crosses as the typed refusal naming its CODE (EEXIST via `onExist`). */
40
+ async function fsStep(what, fn, onExist) {
41
+ try {
42
+ return await fn();
43
+ }
44
+ catch (err) {
45
+ if (err instanceof AutotaskConfigError)
46
+ throw err;
47
+ const code = err.code;
48
+ if (code === 'EEXIST' && onExist !== undefined)
49
+ return onExist();
50
+ return refuse(`could not ${what} (${typeof code === 'string' ? code : 'UNKNOWN'})`);
51
+ }
52
+ }
53
+ /** `lstat` (or `stat`: the root may be a symlink); ENOENT -> undefined. */
54
+ const inspect = (p, follow = false) => fsStep('inspect the output path', () => (follow ? stat(p) : lstat(p)).catch((e) => (e.code === 'ENOENT' ? undefined : Promise.reject(e))));
55
+ /**
56
+ * Validate an `output_path` before any vendor wire and return its writer. Creates the target's missing
57
+ * parent directories only after their deepest existing ancestor is verified inside the root.
58
+ * @throws {AutotaskConfigError} on every refusal above; nothing outside the root is ever created.
59
+ */
60
+ export async function resolveOutputTarget(req) {
61
+ if (req.transport !== 'stdio')
62
+ refuse(`available on the stdio transport only (this serving unit is "${req.transport}")`);
63
+ let root = req.root;
64
+ if (root === undefined || root.trim() === '') {
65
+ const state = req.stateDir;
66
+ if (state === undefined || state.trim() === '')
67
+ refuse('requires the AUTOTASK_OUTPUT_DIR environment root, or an AUTOTASK_STATE_DIR to default it under (set one in the launching environment)');
68
+ if (state.includes('\u0000') || !isAbsolute(state))
69
+ refuse('AUTOTASK_STATE_DIR must be an absolute path without NUL bytes to default the output root under it');
70
+ if (!(await inspect(resolve(state), true))?.isDirectory())
71
+ refuse('AUTOTASK_STATE_DIR does not exist or is not a directory, so the default output root cannot be created');
72
+ root = join(resolve(state), DEFAULT_OUTPUT_SUBDIR);
73
+ await fsStep('create the default output root', () => mkdir(root), () => undefined);
74
+ }
75
+ if (root.includes('\u0000') || !isAbsolute(root))
76
+ refuse('AUTOTASK_OUTPUT_DIR must be an absolute path without NUL bytes');
77
+ const rootPath = resolve(root);
78
+ if (rootPath === parse(rootPath).root)
79
+ refuse('AUTOTASK_OUTPUT_DIR must not be the filesystem root (a root that contains everything cannot contain anything)');
80
+ const rel = req.relativePath;
81
+ if (rel.trim() === '')
82
+ refuse('the path must be a non-empty path relative to AUTOTASK_OUTPUT_DIR');
83
+ if (rel.includes('\u0000'))
84
+ refuse('the path contains a NUL byte, which is not a usable path');
85
+ if (isAbsolute(rel))
86
+ refuse('the path must be RELATIVE to AUTOTASK_OUTPUT_DIR, never absolute');
87
+ if (rel.endsWith('/') || rel.endsWith(sep) || rel.endsWith('\\'))
88
+ refuse('the path must name a FILE: a trailing separator names a directory');
89
+ const lexical = resolve(rootPath, rel);
90
+ if (outside(rootPath, lexical, false))
91
+ refuse('the path escapes AUTOTASK_OUTPUT_DIR (traversal)');
92
+ const rootStat = await inspect(rootPath, true);
93
+ if (rootStat === undefined)
94
+ refuse('AUTOTASK_OUTPUT_DIR does not exist — create it first (the server never creates the root)');
95
+ if (!rootStat.isDirectory())
96
+ refuse('AUTOTASK_OUTPUT_DIR is not a directory');
97
+ const rootReal = await fsStep('resolve the output root', () => realpath(rootPath));
98
+ // The deepest EXISTING ancestor, verified before anything is created (a symlink out is caught with zero effect).
99
+ let existing = dirname(lexical);
100
+ while ((await inspect(existing)) === undefined)
101
+ existing = dirname(existing);
102
+ const escapes = async (dir) => outside(rootReal, await fsStep('resolve the target directory', () => realpath(dir)));
103
+ if (await escapes(existing))
104
+ refuse('the resolved directory escapes AUTOTASK_OUTPUT_DIR (traversal or a symlink)');
105
+ await fsStep('create the target directory', () => mkdir(dirname(lexical), { recursive: true }));
106
+ const parentReal = await fsStep('resolve the target directory', () => realpath(dirname(lexical)));
107
+ if (outside(rootReal, parentReal))
108
+ refuse('the resolved directory escapes AUTOTASK_OUTPUT_DIR (traversal or a symlink)');
109
+ const path = join(parentReal, basename(lexical));
110
+ const found = await inspect(path);
111
+ if (found?.isSymbolicLink())
112
+ refuse('the target is a SYMLINK — the write never follows one');
113
+ if (found?.isDirectory())
114
+ refuse('the path names an existing DIRECTORY — pass a file path');
115
+ if (found !== undefined && !found.isFile())
116
+ refuse('the target is not a regular file');
117
+ if (found !== undefined)
118
+ exists(path);
119
+ return {
120
+ path,
121
+ async write(data) {
122
+ if (await escapes(dirname(path)))
123
+ refuse('the resolved directory escapes AUTOTASK_OUTPUT_DIR (the filesystem changed after validation)');
124
+ const flags = constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW;
125
+ const handle = await fsStep('open the result file', () => open(path, flags, 0o666), () => exists(path));
126
+ try {
127
+ await fsStep('write the result file', () => handle.writeFile(data));
128
+ }
129
+ catch (err) {
130
+ await unlink(path).catch(() => undefined); // this handle created the file exclusively: a partial file must not block the retry
131
+ throw err;
132
+ }
133
+ finally {
134
+ await handle.close().catch(() => undefined);
135
+ }
136
+ return Buffer.byteLength(data);
137
+ },
138
+ };
139
+ }
140
+ //# sourceMappingURL=output-file.js.map
@@ -0,0 +1,21 @@
1
+ /**
2
+ * tools/rank.ts — a deterministic lexical ranker (BM25) over short documents.
3
+ *
4
+ * `autotask_catalog` ranks the registry rows for a `q` with it (key + purpose), and the selection
5
+ * tests rank the served tools for an intent with the same function (name + description), so the
6
+ * golden tests measure exactly what a lexical client-side tool search would see.
7
+ */
8
+ /** Lower-case word tokens; `camelCase` and `snake_case` keys split into their words. */
9
+ export declare function tokenize(text: string): string[];
10
+ /**
11
+ * Score every document against the query (BM25, k1 1.2, b 0.75, times the share of query words
12
+ * the document matches) and return the indexes of the documents with a positive score, best
13
+ * first; ties keep document order.
14
+ */
15
+ export interface RankOptions {
16
+ /** A per-document score multiplier (the catalog: tool-served rows up, deprecated rows down; #277). */
17
+ boost?: (i: number) => number;
18
+ /** Multi-term questions (#277): coverage counts squared and a document matching under half the words is dropped. */
19
+ strict?: boolean;
20
+ }
21
+ export declare function bm25Rank(docs: readonly string[], query: string, opts?: RankOptions): number[];
@@ -0,0 +1,57 @@
1
+ /**
2
+ * tools/rank.ts — a deterministic lexical ranker (BM25) over short documents.
3
+ *
4
+ * `autotask_catalog` ranks the registry rows for a `q` with it (key + purpose), and the selection
5
+ * tests rank the served tools for an intent with the same function (name + description), so the
6
+ * golden tests measure exactly what a lexical client-side tool search would see.
7
+ */
8
+ /** Lower-case word tokens; `camelCase` and `snake_case` keys split into their words. */
9
+ export function tokenize(text) {
10
+ return text
11
+ .replace(/([a-z])([A-Z])/g, '$1 $2')
12
+ .toLowerCase()
13
+ .split(/[^a-z0-9]+/)
14
+ .filter((t) => t.length > 1)
15
+ .map(stem);
16
+ }
17
+ /** A crude plural fold so "tickets" matches "ticket" (enough for this vocabulary). */
18
+ function stem(token) {
19
+ if (token.length > 4 && token.endsWith('ies'))
20
+ return `${token.slice(0, -3)}y`;
21
+ if (token.length > 3 && token.endsWith('s') && !token.endsWith('ss'))
22
+ return token.slice(0, -1);
23
+ return token;
24
+ }
25
+ export function bm25Rank(docs, query, opts = {}) {
26
+ const terms = [...new Set(tokenize(query))];
27
+ const toks = docs.map(tokenize);
28
+ const avg = toks.reduce((n, t) => n + t.length, 0) / Math.max(toks.length, 1);
29
+ const df = new Map();
30
+ for (const t of toks)
31
+ for (const term of new Set(t))
32
+ df.set(term, (df.get(term) ?? 0) + 1);
33
+ const scored = toks.map((t, i) => {
34
+ let score = 0;
35
+ let matched = 0;
36
+ for (const term of terms) {
37
+ const tf = t.filter((x) => x === term).length;
38
+ if (tf === 0)
39
+ continue;
40
+ matched++;
41
+ const n = df.get(term) ?? 0;
42
+ const idf = Math.log(1 + (toks.length - n + 0.5) / (n + 0.5));
43
+ score += idf * ((tf * 2.2) / (tf + 1.2 * (0.25 + (0.75 * t.length) / avg)));
44
+ }
45
+ // Coordination: a document matching more of the query's words outranks one that repeats a
46
+ // single common word (`month` in every `lastFullMonth` key, for instance).
47
+ const coverage = matched / Math.max(terms.length, 1);
48
+ if (opts.strict === true && matched * 2 < terms.length)
49
+ return { i, score: 0 };
50
+ return { i, score: score * coverage * (opts.strict === true ? coverage : 1) * (opts.boost?.(i) ?? 1) };
51
+ });
52
+ return scored
53
+ .filter((s) => s.score > 0)
54
+ .sort((a, b) => b.score - a.score || a.i - b.i)
55
+ .map((s) => s.i);
56
+ }
57
+ //# sourceMappingURL=rank.js.map
@@ -0,0 +1,33 @@
1
+ export declare const STATUSES: readonly ["ok", "needs_input", "ambiguous", "denied", "error"];
2
+ export type Status = (typeof STATUSES)[number];
3
+ export declare const NEXT_ACTIONS: readonly ["proceed", "supply_input", "choose_candidate", "repreview", "manual_action", "poll_task", "verify_then_repreview", "retry", "stop"];
4
+ export type NextAction = (typeof NEXT_ACTIONS)[number];
5
+ export declare const REASON_CODES: readonly ["INPUT_INVALID", "TARGET_NOT_FOUND", "AMBIGUOUS_MATCH", "RESULT_TRUNCATED", "POLICY_DENIED", "HOST_POLICY_DENIED", "CREDENTIAL_MISSING", "CREDENTIAL_MALFORMED", "UNAUTHORIZED", "RATE_LIMITED", "MAINTENANCE_ACTIVE", "ABORTED", "UPSTREAM_ERROR", "INTERNAL_ERROR", "BUDGET_EXCEEDED", "INPUT_MISSING", "SCOPE_REQUIRED", "OP_NOT_ALLOWED", "TARGET_NOT_IN_SCOPE", "MOVE_REFUSED", "LIMIT_RATE", "DUPLICATE_EXISTS", "COOLDOWN_ACTIVE", "KILL_SWITCH", "STATE_UNAVAILABLE", "GATE_UNSUPPORTED", "GATE_DECLINED", "PLAN_NOT_FOUND", "PLAN_EXPIRED", "PLAN_MISMATCH", "PRINCIPAL_MISMATCH", "STATE_DRIFT", "WRITE_FAILED", "FIELD_NOT_PERSISTED", "WRITE_OUTCOME_UNKNOWN"];
6
+ export type ReasonCode = (typeof REASON_CODES)[number];
7
+ export interface Reason {
8
+ code: ReasonCode;
9
+ field?: string;
10
+ detail: string;
11
+ }
12
+ /** The longest `reasons[].detail` served (the typed payload in `data` keeps the full bounded message). */
13
+ export declare const MAX_REASON_DETAIL = 500;
14
+ /**
15
+ * How one typed error payload (the `typedErrorPayload` shape) maps onto the envelope. `next` is the SDK's
16
+ * `nextAction` (node-autotask #296, issue #254), computed with the SDK's own `nextActionFor` for a payload
17
+ * that does not carry one; the server overrides it only for its own inputs: a credential refusal stops (the
18
+ * caller cannot fix the deployment's credential), and a refused cursor the caller passed (dispatch marks
19
+ * `callerInput`) is caller input. The reason code is this server's closed vocabulary.
20
+ */
21
+ export declare function classifyError(payload: {
22
+ code?: unknown;
23
+ category?: unknown;
24
+ retryable?: unknown;
25
+ httpStatus?: unknown;
26
+ callerInput?: unknown;
27
+ nextAction?: unknown;
28
+ }): {
29
+ status: Status;
30
+ next: NextAction;
31
+ code: ReasonCode;
32
+ retryable: boolean;
33
+ };
@@ -0,0 +1,121 @@
1
+ /**
2
+ * tools/reasons.ts — the closed vocabulary of the result envelope (0.6.0).
3
+ *
4
+ * Every tool answers the same envelope: `status` says what happened, `next` says what the caller
5
+ * does about it, and `reasons[]` names why with a code from {@link REASON_CODES}. The SDK's own
6
+ * error code stays in `data.code` (the typed payload, unchanged); the reason code is this server's
7
+ * fixed mapping of it, so a caller can branch on a short, closed list instead of the SDK's open one.
8
+ * The lists are pinned by a test: adding a value is a contract change.
9
+ */
10
+ import { nextActionFor } from 'node-autotask';
11
+ export const STATUSES = ['ok', 'needs_input', 'ambiguous', 'denied', 'error'];
12
+ export const NEXT_ACTIONS = [
13
+ 'proceed',
14
+ 'supply_input',
15
+ 'choose_candidate',
16
+ 'repreview',
17
+ 'manual_action',
18
+ 'poll_task',
19
+ 'verify_then_repreview',
20
+ 'retry',
21
+ 'stop',
22
+ ];
23
+ export const REASON_CODES = [
24
+ 'INPUT_INVALID',
25
+ 'TARGET_NOT_FOUND',
26
+ 'AMBIGUOUS_MATCH',
27
+ 'RESULT_TRUNCATED',
28
+ 'POLICY_DENIED',
29
+ 'HOST_POLICY_DENIED',
30
+ 'CREDENTIAL_MISSING',
31
+ 'CREDENTIAL_MALFORMED',
32
+ 'UNAUTHORIZED',
33
+ 'RATE_LIMITED',
34
+ 'MAINTENANCE_ACTIVE',
35
+ 'ABORTED',
36
+ 'UPSTREAM_ERROR',
37
+ 'INTERNAL_ERROR',
38
+ 'BUDGET_EXCEEDED',
39
+ // the operator write path (autotask_write / autotask_apply / autotask_apply_destructive)
40
+ 'INPUT_MISSING',
41
+ 'SCOPE_REQUIRED',
42
+ 'OP_NOT_ALLOWED',
43
+ 'TARGET_NOT_IN_SCOPE',
44
+ 'MOVE_REFUSED',
45
+ 'LIMIT_RATE',
46
+ 'DUPLICATE_EXISTS',
47
+ 'COOLDOWN_ACTIVE',
48
+ 'KILL_SWITCH',
49
+ 'STATE_UNAVAILABLE',
50
+ 'GATE_UNSUPPORTED',
51
+ 'GATE_DECLINED',
52
+ 'PLAN_NOT_FOUND',
53
+ 'PLAN_EXPIRED',
54
+ 'PLAN_MISMATCH',
55
+ 'PRINCIPAL_MISMATCH',
56
+ 'STATE_DRIFT',
57
+ 'WRITE_FAILED',
58
+ 'FIELD_NOT_PERSISTED',
59
+ 'WRITE_OUTCOME_UNKNOWN',
60
+ ];
61
+ /** The longest `reasons[].detail` served (the typed payload in `data` keeps the full bounded message). */
62
+ export const MAX_REASON_DETAIL = 500;
63
+ const SDK_NEXT = new Set(['supply_input', 'retry', 'stop', 'choose_candidate']);
64
+ /** The reason code per error code where the code alone decides it (the rest go by category). */
65
+ const REASON_BY_CODE = {
66
+ POLICY_DENIED: 'POLICY_DENIED',
67
+ HOST_POLICY_DENIED: 'HOST_POLICY_DENIED',
68
+ CREDENTIAL_MISSING: 'CREDENTIAL_MISSING',
69
+ CREDENTIAL_MALFORMED: 'CREDENTIAL_MALFORMED',
70
+ UNAUTHORIZED: 'UNAUTHORIZED',
71
+ FORBIDDEN: 'UNAUTHORIZED',
72
+ RESOLUTION_AMBIGUOUS: 'AMBIGUOUS_MATCH',
73
+ RESOLUTION_TRUNCATED: 'RESULT_TRUNCATED',
74
+ NOT_FOUND: 'TARGET_NOT_FOUND',
75
+ COMPANY_NOT_FOUND: 'TARGET_NOT_FOUND',
76
+ RESOURCE_UNKNOWN: 'TARGET_NOT_FOUND',
77
+ // #243: the unscoped-walk refusal: add the scope (or acknowledge) and call again
78
+ SCOPE_REQUIRED: 'SCOPE_REQUIRED',
79
+ // SDK 0.37.0: a budgeted helper refused; a narrower window or scope, or a raised maxVendorCalls, may pass
80
+ BUDGET_EXCEEDED: 'BUDGET_EXCEEDED',
81
+ CONFIG_ERROR: 'INPUT_INVALID',
82
+ VALIDATION_FAILED: 'INPUT_INVALID',
83
+ BAD_REQUEST: 'INPUT_INVALID',
84
+ QUERY_TOO_LONG: 'INPUT_INVALID',
85
+ LATEST_WINDOW_INCOMPLETE: 'INPUT_INVALID',
86
+ LATEST_THRESHOLD_UNRESOLVED: 'INPUT_INVALID',
87
+ MARKER_UNSAFE_ID: 'INPUT_INVALID',
88
+ PAGINATION_LIMIT: 'INPUT_INVALID',
89
+ // node-autotask 0.40.0 (#285): ONE code for the whole vendor maintenance window (the SDK's own code stays in data.code)
90
+ MAINTENANCE: 'MAINTENANCE_ACTIVE',
91
+ RATE_LIMITED: 'RATE_LIMITED',
92
+ RATE_LIMITED_COOLDOWN: 'RATE_LIMITED',
93
+ ABORTED: 'ABORTED',
94
+ };
95
+ /**
96
+ * How one typed error payload (the `typedErrorPayload` shape) maps onto the envelope. `next` is the SDK's
97
+ * `nextAction` (node-autotask #296, issue #254), computed with the SDK's own `nextActionFor` for a payload
98
+ * that does not carry one; the server overrides it only for its own inputs: a credential refusal stops (the
99
+ * caller cannot fix the deployment's credential), and a refused cursor the caller passed (dispatch marks
100
+ * `callerInput`) is caller input. The reason code is this server's closed vocabulary.
101
+ */
102
+ export function classifyError(payload) {
103
+ const code = typeof payload.code === 'string' ? payload.code : 'INTERNAL_ERROR';
104
+ const category = typeof payload.category === 'string' ? payload.category : undefined;
105
+ const callerCursor = code === 'RESPONSE_REJECTED' && payload.callerInput === true;
106
+ const upstream = typeof payload.httpStatus === 'number' || category === 'network' || category === 'server';
107
+ const reason = REASON_BY_CODE[code] ??
108
+ (category === 'not_found' ? 'TARGET_NOT_FOUND' : category === 'validation' || callerCursor ? 'INPUT_INVALID' : upstream || code !== 'INTERNAL_ERROR' ? 'UPSTREAM_ERROR' : 'INTERNAL_ERROR');
109
+ // a payload without a category (not an SDK error) whose code names caller input is computed as validation
110
+ const fallbackCategory = category ?? (reason === 'INPUT_INVALID' || reason === 'TARGET_NOT_FOUND' ? 'validation' : undefined);
111
+ const next = code.startsWith('CREDENTIAL_')
112
+ ? 'stop'
113
+ : callerCursor
114
+ ? 'supply_input'
115
+ : typeof payload.nextAction === 'string' && SDK_NEXT.has(payload.nextAction)
116
+ ? payload.nextAction
117
+ : nextActionFor(code, { category: fallbackCategory, retryable: payload.retryable === true });
118
+ const status = reason === 'POLICY_DENIED' || reason === 'HOST_POLICY_DENIED' ? 'denied' : next === 'choose_candidate' ? 'ambiguous' : 'error';
119
+ return { status, next, code: reason, retryable: next === 'retry' };
120
+ }
121
+ //# sourceMappingURL=reasons.js.map
@@ -0,0 +1,23 @@
1
+ /**
2
+ * tools/register.ts — `registerTools`: derives the per-server context from the deps bundle once,
3
+ * then registers the deployment's slice of {@link SURFACE} in surface order (the registration
4
+ * order is the `tools/list` order the model sees).
5
+ *
6
+ * Every tool shares one shape: the closed input, the result envelope, and
7
+ * annotations derived from its surface row (`openWorldHint` is true exactly when the tool calls the
8
+ * vendor; every tool is read-only except `autotask_apply` and `autotask_apply_destructive`, which change vendor state —
9
+ * `autotask_write` only previews). The guide alone carries `_meta`
10
+ * (`anthropic/alwaysLoad`), so hosts that defer tool loading still see it.
11
+ */
12
+ import type { McpServer } from '@modelcontextprotocol/server';
13
+ import { type ToolDeps } from './context/types.js';
14
+ import { type SurfaceEntry } from './surface.js';
15
+ /** The MCP annotations for one surface row. */
16
+ export declare function annotationsOf(entry: SurfaceEntry): {
17
+ readOnlyHint: boolean;
18
+ destructiveHint: boolean;
19
+ idempotentHint: true;
20
+ openWorldHint: boolean;
21
+ };
22
+ /** Register the deployment's tool surface on one serving unit's server. */
23
+ export declare function registerTools(server: McpServer, deps: ToolDeps): void;
@@ -0,0 +1,50 @@
1
+ import { anyGate } from '../access/write-env.js';
2
+ import { deriveToolContext } from './context/derive.js';
3
+ import {} from './context/types.js';
4
+ import { runTool } from './dispatch.js';
5
+ import { selectSurface } from './surface.js';
6
+ import { errorEnvelope } from './results/envelope.js';
7
+ import { sanitiseToolReturn } from './results/untrusted.js';
8
+ /** The MCP annotations for one surface row. */
9
+ export function annotationsOf(entry) {
10
+ // apply: destructive (it can run a delete), idempotent (a recorded outcome replays).
11
+ if (entry.mutates === true)
12
+ return { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: entry.vendor };
13
+ return { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: entry.vendor };
14
+ }
15
+ /** Register the deployment's tool surface on one serving unit's server. */
16
+ export function registerTools(server, deps) {
17
+ const entries = selectSurface(deps.config);
18
+ // a 2025-era stdio connection's initialize capabilities (the human gate's legacy elicitation check)
19
+ const ctx = deriveToolContext({ ...deps, clientCapabilities: () => server.server.getClientCapabilities() }, new Set(entries.map((e) => e.name)));
20
+ for (const entry of entries) {
21
+ const tool = entry.build(ctx);
22
+ server.registerTool(entry.name, {
23
+ title: tool.title,
24
+ description: ctx.description(entry.name),
25
+ inputSchema: tool.input.input,
26
+ annotations: annotationsOf(entry),
27
+ ...(entry.name === 'autotask_guide' ? { _meta: { 'anthropic/alwaysLoad': true } } : {}),
28
+ ...(entry.mutates === true && deps.write !== undefined && anyGate(deps.write.runtime.loaded, entry.name === 'autotask_apply_destructive') ? { _meta: { 'anthropic/requiresUserInteraction': true } } : {}),
29
+ }, async (raw, extra) => {
30
+ const result = await runTool(ctx, tool.input, raw, extra, async (args, signal, x) => (await tool.run(args, signal, x)));
31
+ // An `input_required` result is the human gate's request: it is not a tool result, carries no
32
+ // vendor text, and is returned exactly as the SDK built it.
33
+ if (!entry.vendor || !('structuredContent' in result))
34
+ return result;
35
+ const finished = result;
36
+ // The single choke point for vendor text (final review R1-R3, R5): every string in a
37
+ // vendor-calling tool's result is cleaned; the wrapper goes on the fields recorded by
38
+ // provenance. Any failure inside it answers a fixed error envelope (sanitiser review S1):
39
+ // never a bare exception, a stack, or the vendor text that caused it.
40
+ try {
41
+ return sanitiseToolReturn(finished, ctx.correlationId);
42
+ }
43
+ catch {
44
+ ctx.log.error('the vendor-text sanitiser failed; the result was withheld', { tool: entry.name });
45
+ return errorEnvelope({ error: true, code: 'INTERNAL_ERROR', category: 'internal', retryable: false, message: 'The result could not be made safe to return and was withheld.', correlationId: ctx.correlationId }, ctx.correlationId);
46
+ }
47
+ });
48
+ }
49
+ }
50
+ //# sourceMappingURL=register.js.map
@@ -0,0 +1,28 @@
1
+ import type { ToolContext } from './context/types.js';
2
+ import type { BuiltTool } from './surface.js';
3
+ /** The issue #9 contains cap for companies: at most 10 candidates (may be lowered, never raised). */
4
+ export declare const COMPANY_CONTAINS_MAX_LIMIT = 10;
5
+ /** The cap on a `ref` (#230), in code points; a longer name is cut and ends with `…`. */
6
+ export declare const REF_MAX = 80;
7
+ /**
8
+ * #230: the one contract for vendor names this tool prints unwrapped (`ref` and summary lines), so a
9
+ * citation stays the plain name: unsafe characters stripped, whitespace (newlines included)
10
+ * collapsed to one space, markup characters ``< > { } [ ] ` " | \`` dropped (no tag, fake wrapper
11
+ * close or fence survives), capped at {@link REF_MAX}. Still vendor-authored: data, never instructions.
12
+ */
13
+ export declare function safeRef(text: string): string | undefined;
14
+ /** The human reference of a record of `resource` ({@link safeRef} text), or null when the record carries none. */
15
+ export declare function refOf(resource: string, record: unknown): string | null;
16
+ type Expand = boolean | 'full';
17
+ /** #225: a record without its `[REDACTED]`, null and empty fields; `expand: "full"` keeps the record as the SDK returned it. */
18
+ export declare function slimRecord(record: unknown, expand: Expand): unknown;
19
+ /**
20
+ * A resource outside the six this tool resolves, but with a `<resource>.resolve` read in the registry (company_locations,
21
+ * roles, billing_codes, products, ...): the refusal names that one-call, zero-surface route. The pointer leads the
22
+ * message (the reason detail is cut at 200 characters, and the longest of the 116 names still fits whole); the list of
23
+ * valid resources follows and may be cut. The key is shape-checked and registry-checked (the regex is defence in depth),
24
+ * so no caller text reaches the sentence.
25
+ */
26
+ export declare function resolveRefusalHint(raw: Record<string, unknown>): string | undefined;
27
+ export declare function buildResolve(ctx: ToolContext): BuiltTool;
28
+ export {};