@superdoc-dev/sdk 1.0.0-alpha.3 → 1.0.0-alpha.4

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 (53) hide show
  1. package/dist/generated/client.d.ts +1790 -0
  2. package/dist/generated/client.d.ts.map +1 -0
  3. package/dist/generated/client.js +66 -0
  4. package/dist/generated/contract.d.ts +13676 -0
  5. package/dist/generated/contract.d.ts.map +1 -0
  6. package/dist/generated/contract.js +17809 -0
  7. package/dist/index.d.ts +23 -0
  8. package/dist/index.d.ts.map +1 -0
  9. package/dist/index.js +29 -0
  10. package/dist/runtime/embedded-cli.d.ts +5 -0
  11. package/dist/runtime/embedded-cli.d.ts.map +1 -0
  12. package/dist/runtime/embedded-cli.js +94 -0
  13. package/dist/runtime/errors.d.ts +17 -0
  14. package/dist/runtime/errors.d.ts.map +1 -0
  15. package/dist/runtime/errors.js +18 -0
  16. package/dist/runtime/host.d.ts +36 -0
  17. package/dist/runtime/host.d.ts.map +1 -0
  18. package/dist/runtime/host.js +345 -0
  19. package/dist/runtime/process.d.ts +16 -0
  20. package/dist/runtime/process.d.ts.map +1 -0
  21. package/dist/runtime/process.js +27 -0
  22. package/dist/runtime/transport-common.d.ts +44 -0
  23. package/dist/runtime/transport-common.d.ts.map +1 -0
  24. package/dist/runtime/transport-common.js +65 -0
  25. package/dist/skills.d.ts +25 -0
  26. package/dist/skills.d.ts.map +1 -0
  27. package/dist/skills.js +140 -0
  28. package/dist/tools.d.ts +113 -0
  29. package/dist/tools.d.ts.map +1 -0
  30. package/dist/tools.js +360 -0
  31. package/package.json +19 -10
  32. package/tools/catalog.json +17128 -0
  33. package/tools/tool-name-map.json +96 -0
  34. package/tools/tools-policy.json +100 -0
  35. package/tools/tools.anthropic.json +3275 -0
  36. package/tools/tools.generic.json +16573 -0
  37. package/tools/tools.openai.json +3557 -0
  38. package/tools/tools.vercel.json +3557 -0
  39. package/skills/editing-docx.md +0 -157
  40. package/src/__tests__/skills.test.ts +0 -166
  41. package/src/__tests__/tools.test.ts +0 -96
  42. package/src/generated/client.ts +0 -3643
  43. package/src/generated/contract.ts +0 -15952
  44. package/src/index.ts +0 -87
  45. package/src/runtime/__tests__/process.test.ts +0 -38
  46. package/src/runtime/__tests__/transport-common.test.ts +0 -174
  47. package/src/runtime/embedded-cli.ts +0 -109
  48. package/src/runtime/errors.ts +0 -30
  49. package/src/runtime/host.ts +0 -481
  50. package/src/runtime/process.ts +0 -45
  51. package/src/runtime/transport-common.ts +0 -169
  52. package/src/skills.ts +0 -195
  53. package/src/tools.ts +0 -701
package/dist/tools.js ADDED
@@ -0,0 +1,360 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { readFileSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { CONTRACT } from './generated/contract.js';
6
+ import { SuperDocCliError } from './runtime/errors.js';
7
+ // Resolve tools directory relative to package root (works from both src/ and dist/)
8
+ const toolsDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'tools');
9
+ const providerFileByName = {
10
+ openai: 'tools.openai.json',
11
+ anthropic: 'tools.anthropic.json',
12
+ vercel: 'tools.vercel.json',
13
+ generic: 'tools.generic.json',
14
+ };
15
+ let _policyCache = null;
16
+ function loadPolicy() {
17
+ if (_policyCache)
18
+ return _policyCache;
19
+ const raw = readFileSync(path.join(toolsDir, 'tools-policy.json'), 'utf8');
20
+ _policyCache = JSON.parse(raw);
21
+ return _policyCache;
22
+ }
23
+ function isRecord(value) {
24
+ return typeof value === 'object' && value != null && !Array.isArray(value);
25
+ }
26
+ function isPresent(value) {
27
+ if (value == null)
28
+ return false;
29
+ if (Array.isArray(value))
30
+ return value.length > 0;
31
+ return true;
32
+ }
33
+ function extractProviderToolName(tool) {
34
+ // Anthropic / Generic: top-level name
35
+ if (typeof tool.name === 'string')
36
+ return tool.name;
37
+ // OpenAI / Vercel: nested under function.name
38
+ if (isRecord(tool.function) && typeof tool.function.name === 'string') {
39
+ return tool.function.name;
40
+ }
41
+ return null;
42
+ }
43
+ function invalidArgument(message, details) {
44
+ throw new SuperDocCliError(message, { code: 'INVALID_ARGUMENT', details });
45
+ }
46
+ async function readJson(fileName) {
47
+ const filePath = path.join(toolsDir, fileName);
48
+ let raw = '';
49
+ try {
50
+ raw = await readFile(filePath, 'utf8');
51
+ }
52
+ catch (error) {
53
+ throw new SuperDocCliError('Unable to load packaged tool artifact.', {
54
+ code: 'TOOLS_ASSET_NOT_FOUND',
55
+ details: {
56
+ filePath,
57
+ message: error instanceof Error ? error.message : String(error),
58
+ },
59
+ });
60
+ }
61
+ try {
62
+ return JSON.parse(raw);
63
+ }
64
+ catch (error) {
65
+ throw new SuperDocCliError('Packaged tool artifact is invalid JSON.', {
66
+ code: 'TOOLS_ASSET_INVALID',
67
+ details: {
68
+ filePath,
69
+ message: error instanceof Error ? error.message : String(error),
70
+ },
71
+ });
72
+ }
73
+ }
74
+ async function loadProviderBundle(provider) {
75
+ return readJson(providerFileByName[provider]);
76
+ }
77
+ async function loadToolNameMap() {
78
+ return readJson('tool-name-map.json');
79
+ }
80
+ async function loadCatalog() {
81
+ return readJson('catalog.json');
82
+ }
83
+ function normalizeFeatures(features) {
84
+ return {
85
+ hasTables: Boolean(features?.hasTables),
86
+ hasLists: Boolean(features?.hasLists),
87
+ hasComments: Boolean(features?.hasComments),
88
+ hasTrackedChanges: Boolean(features?.hasTrackedChanges),
89
+ isEmptyDocument: Boolean(features?.isEmptyDocument),
90
+ };
91
+ }
92
+ function stableSortByPhasePriority(entries, priorityOrder) {
93
+ const priority = new Map(priorityOrder.map((category, index) => [category, index]));
94
+ return [...entries].sort((a, b) => {
95
+ const aPriority = priority.get(a.category) ?? Number.MAX_SAFE_INTEGER;
96
+ const bPriority = priority.get(b.category) ?? Number.MAX_SAFE_INTEGER;
97
+ if (aPriority !== bPriority)
98
+ return aPriority - bPriority;
99
+ return a.toolName.localeCompare(b.toolName);
100
+ });
101
+ }
102
+ const OPERATION_INDEX = Object.fromEntries(Object.entries(CONTRACT.operations).map(([id, op]) => [id, op]));
103
+ function validateDispatchArgs(operationId, args) {
104
+ const operation = OPERATION_INDEX[operationId];
105
+ if (!operation) {
106
+ invalidArgument(`Unknown operation id ${operationId}.`);
107
+ }
108
+ // Unknown-param rejection
109
+ const allowedParams = new Set(operation.params.map((param) => String(param.name)));
110
+ for (const key of Object.keys(args)) {
111
+ if (!allowedParams.has(key)) {
112
+ invalidArgument(`Unexpected parameter ${key} for ${operationId}.`);
113
+ }
114
+ }
115
+ // Required-param enforcement
116
+ for (const param of operation.params) {
117
+ if ('required' in param && Boolean(param.required) && args[param.name] == null) {
118
+ invalidArgument(`Missing required parameter ${param.name} for ${operationId}.`);
119
+ }
120
+ }
121
+ // Constraint validation (CLI handles schema-level type validation authoritatively)
122
+ const constraints = 'constraints' in operation ? operation.constraints : undefined;
123
+ if (!constraints || !isRecord(constraints))
124
+ return;
125
+ const mutuallyExclusive = Array.isArray(constraints.mutuallyExclusive) ? constraints.mutuallyExclusive : [];
126
+ const requiresOneOf = Array.isArray(constraints.requiresOneOf) ? constraints.requiresOneOf : [];
127
+ const requiredWhen = Array.isArray(constraints.requiredWhen) ? constraints.requiredWhen : [];
128
+ for (const group of mutuallyExclusive) {
129
+ if (!Array.isArray(group))
130
+ continue;
131
+ const present = group.filter((name) => isPresent(args[name]));
132
+ if (present.length > 1) {
133
+ invalidArgument(`Arguments are mutually exclusive for ${operationId}: ${group.join(', ')}`, {
134
+ operationId,
135
+ group,
136
+ });
137
+ }
138
+ }
139
+ for (const group of requiresOneOf) {
140
+ if (!Array.isArray(group))
141
+ continue;
142
+ const hasAny = group.some((name) => isPresent(args[name]));
143
+ if (!hasAny) {
144
+ invalidArgument(`One of the following arguments is required for ${operationId}: ${group.join(', ')}`, {
145
+ operationId,
146
+ group,
147
+ });
148
+ }
149
+ }
150
+ for (const rule of requiredWhen) {
151
+ if (!isRecord(rule))
152
+ continue;
153
+ const whenValue = args[rule.whenParam];
154
+ let shouldRequire = false;
155
+ if (Object.prototype.hasOwnProperty.call(rule, 'equals')) {
156
+ shouldRequire = whenValue === rule.equals;
157
+ }
158
+ else if (Object.prototype.hasOwnProperty.call(rule, 'present')) {
159
+ const present = rule.present === true;
160
+ shouldRequire = present ? isPresent(whenValue) : !isPresent(whenValue);
161
+ }
162
+ else {
163
+ shouldRequire = isPresent(whenValue);
164
+ }
165
+ if (shouldRequire && !isPresent(args[rule.param])) {
166
+ invalidArgument(`Argument ${rule.param} is required by constraints for ${operationId}.`, {
167
+ operationId,
168
+ rule,
169
+ });
170
+ }
171
+ }
172
+ }
173
+ function resolveDocApiMethod(client, operationId) {
174
+ const tokens = operationId.split('.').slice(1);
175
+ let cursor = client.doc;
176
+ for (const token of tokens) {
177
+ if (!isRecord(cursor) || !(token in cursor)) {
178
+ throw new SuperDocCliError(`No SDK doc method found for operation ${operationId}.`, {
179
+ code: 'TOOL_DISPATCH_NOT_FOUND',
180
+ details: { operationId, token },
181
+ });
182
+ }
183
+ cursor = cursor[token];
184
+ }
185
+ if (typeof cursor !== 'function') {
186
+ throw new SuperDocCliError(`Resolved member for ${operationId} is not callable.`, {
187
+ code: 'TOOL_DISPATCH_NOT_FOUND',
188
+ details: { operationId },
189
+ });
190
+ }
191
+ return cursor;
192
+ }
193
+ export async function getToolCatalog(options = {}) {
194
+ const catalog = await loadCatalog();
195
+ if (!options.profile)
196
+ return catalog;
197
+ return {
198
+ ...catalog,
199
+ profiles: {
200
+ intent: options.profile === 'intent' ? catalog.profiles.intent : { name: 'intent', tools: [] },
201
+ operation: options.profile === 'operation' ? catalog.profiles.operation : { name: 'operation', tools: [] },
202
+ },
203
+ };
204
+ }
205
+ export async function listTools(provider, options = {}) {
206
+ const profile = options.profile ?? 'intent';
207
+ const bundle = await loadProviderBundle(provider);
208
+ const tools = bundle.profiles[profile];
209
+ if (!Array.isArray(tools)) {
210
+ throw new SuperDocCliError('Tool provider bundle is missing profile tools.', {
211
+ code: 'TOOLS_ASSET_INVALID',
212
+ details: { provider, profile },
213
+ });
214
+ }
215
+ return tools;
216
+ }
217
+ export async function resolveToolOperation(toolName) {
218
+ const map = await loadToolNameMap();
219
+ return typeof map[toolName] === 'string' ? map[toolName] : null;
220
+ }
221
+ export function inferDocumentFeatures(infoResult) {
222
+ if (!isRecord(infoResult)) {
223
+ return {
224
+ hasTables: false,
225
+ hasLists: false,
226
+ hasComments: false,
227
+ hasTrackedChanges: false,
228
+ isEmptyDocument: false,
229
+ };
230
+ }
231
+ const counts = isRecord(infoResult.counts) ? infoResult.counts : {};
232
+ const words = typeof counts.words === 'number' ? counts.words : 0;
233
+ const paragraphs = typeof counts.paragraphs === 'number' ? counts.paragraphs : 0;
234
+ const tables = typeof counts.tables === 'number' ? counts.tables : 0;
235
+ const comments = typeof counts.comments === 'number' ? counts.comments : 0;
236
+ const lists = typeof counts.lists === 'number' ? counts.lists : typeof counts.listItems === 'number' ? counts.listItems : 0;
237
+ const trackedChanges = typeof counts.trackedChanges === 'number'
238
+ ? counts.trackedChanges
239
+ : typeof counts.tracked_changes === 'number'
240
+ ? counts.tracked_changes
241
+ : 0;
242
+ return {
243
+ hasTables: tables > 0,
244
+ hasLists: lists > 0,
245
+ hasComments: comments > 0,
246
+ hasTrackedChanges: trackedChanges > 0,
247
+ isEmptyDocument: words === 0 && paragraphs <= 1,
248
+ };
249
+ }
250
+ export async function chooseTools(input) {
251
+ const catalog = await loadCatalog();
252
+ const policy = loadPolicy();
253
+ const profile = input.profile ?? 'intent';
254
+ const phase = input.taskContext?.phase ?? 'read';
255
+ const phasePolicy = policy.phases[phase];
256
+ const featureMap = normalizeFeatures(input.documentFeatures);
257
+ const maxTools = Math.max(1, input.budget?.maxTools ?? policy.defaults.maxToolsByProfile[profile]);
258
+ const minReadTools = Math.max(0, input.budget?.minReadTools ?? policy.defaults.minReadTools);
259
+ const includeCategories = new Set(input.policy?.includeCategories ?? phasePolicy.include);
260
+ const excludeCategories = new Set([...(input.policy?.excludeCategories ?? []), ...phasePolicy.exclude]);
261
+ const allowMutatingTools = input.policy?.allowMutatingTools ?? phase === 'mutate';
262
+ const excluded = [];
263
+ const profileTools = catalog.profiles[profile].tools;
264
+ const indexByToolName = new Map(profileTools.map((tool) => [tool.toolName, tool]));
265
+ let candidates = profileTools.filter((tool) => {
266
+ if (tool.requiredCapabilities.some((capability) => !featureMap[capability])) {
267
+ excluded.push({ toolName: tool.toolName, reason: 'missing-required-capability' });
268
+ return false;
269
+ }
270
+ if (!allowMutatingTools && tool.mutates) {
271
+ excluded.push({ toolName: tool.toolName, reason: 'mutations-disabled' });
272
+ return false;
273
+ }
274
+ if (includeCategories.size > 0 && !includeCategories.has(tool.category)) {
275
+ excluded.push({ toolName: tool.toolName, reason: 'category-not-included' });
276
+ return false;
277
+ }
278
+ if (excludeCategories.has(tool.category)) {
279
+ excluded.push({ toolName: tool.toolName, reason: 'phase-category-excluded' });
280
+ return false;
281
+ }
282
+ return true;
283
+ });
284
+ const forceExclude = new Set(input.policy?.forceExclude ?? []);
285
+ candidates = candidates.filter((tool) => {
286
+ if (!forceExclude.has(tool.toolName))
287
+ return true;
288
+ excluded.push({ toolName: tool.toolName, reason: 'force-excluded' });
289
+ return false;
290
+ });
291
+ for (const forcedToolName of input.policy?.forceInclude ?? []) {
292
+ const forced = indexByToolName.get(forcedToolName);
293
+ if (!forced) {
294
+ excluded.push({ toolName: forcedToolName, reason: 'not-in-profile' });
295
+ continue;
296
+ }
297
+ candidates.push(forced);
298
+ }
299
+ candidates = [...new Map(candidates.map((tool) => [tool.toolName, tool])).values()];
300
+ const selected = [];
301
+ const foundationalIds = new Set(policy.defaults.foundationalOperationIds);
302
+ const foundational = candidates.filter((tool) => foundationalIds.has(tool.operationId));
303
+ for (const tool of foundational) {
304
+ if (selected.length >= minReadTools || selected.length >= maxTools)
305
+ break;
306
+ selected.push(tool);
307
+ }
308
+ const remaining = stableSortByPhasePriority(candidates.filter((tool) => !selected.some((entry) => entry.toolName === tool.toolName)), phasePolicy.priority);
309
+ for (const tool of remaining) {
310
+ if (selected.length >= maxTools) {
311
+ excluded.push({ toolName: tool.toolName, reason: 'budget-trim' });
312
+ continue;
313
+ }
314
+ selected.push(tool);
315
+ }
316
+ const bundle = await loadProviderBundle(input.provider);
317
+ const providerTools = Array.isArray(bundle.profiles[profile]) ? bundle.profiles[profile] : [];
318
+ const providerIndex = new Map(providerTools
319
+ .filter((tool) => isRecord(tool))
320
+ .map((tool) => [extractProviderToolName(tool), tool])
321
+ .filter((entry) => entry[0] !== null));
322
+ const selectedProviderTools = selected
323
+ .map((tool) => providerIndex.get(tool.toolName))
324
+ .filter((tool) => Boolean(tool));
325
+ return {
326
+ tools: selectedProviderTools,
327
+ selected: selected.map((tool) => ({
328
+ operationId: tool.operationId,
329
+ toolName: tool.toolName,
330
+ category: tool.category,
331
+ mutates: tool.mutates,
332
+ profile: tool.profile,
333
+ })),
334
+ excluded,
335
+ selectionMeta: {
336
+ profile,
337
+ phase,
338
+ maxTools,
339
+ minReadTools,
340
+ selectedCount: selected.length,
341
+ decisionVersion: policy.defaults.chooserDecisionVersion,
342
+ provider: input.provider,
343
+ },
344
+ };
345
+ }
346
+ export async function dispatchSuperDocTool(client, toolName, args = {}, invokeOptions) {
347
+ const operationId = await resolveToolOperation(toolName);
348
+ if (!operationId) {
349
+ throw new SuperDocCliError(`Unknown SuperDoc tool: ${toolName}`, {
350
+ code: 'TOOL_NOT_FOUND',
351
+ details: { toolName },
352
+ });
353
+ }
354
+ if (!isRecord(args)) {
355
+ invalidArgument(`Tool arguments for ${toolName} must be an object.`);
356
+ }
357
+ validateDispatchArgs(operationId, args);
358
+ const method = resolveDocApiMethod(client, operationId);
359
+ return method(args, invokeOptions);
360
+ }
package/package.json CHANGED
@@ -1,21 +1,29 @@
1
1
  {
2
2
  "name": "@superdoc-dev/sdk",
3
- "version": "1.0.0-alpha.3",
3
+ "version": "1.0.0-alpha.4",
4
4
  "private": false,
5
5
  "type": "module",
6
- "main": "./src/index.ts",
7
- "module": "./src/index.ts",
6
+ "main": "./dist/index.js",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "import": {
12
+ "types": "./dist/index.d.ts",
13
+ "default": "./dist/index.js"
14
+ }
15
+ }
16
+ },
8
17
  "files": [
9
- "src",
10
- "skills",
18
+ "dist",
11
19
  "tools"
12
20
  ],
13
21
  "optionalDependencies": {
14
- "@superdoc-dev/sdk-darwin-arm64": "1.0.0-alpha.3",
15
- "@superdoc-dev/sdk-darwin-x64": "1.0.0-alpha.3",
16
- "@superdoc-dev/sdk-linux-arm64": "1.0.0-alpha.3",
17
- "@superdoc-dev/sdk-linux-x64": "1.0.0-alpha.3",
18
- "@superdoc-dev/sdk-windows-x64": "1.0.0-alpha.3"
22
+ "@superdoc-dev/sdk-darwin-arm64": "1.0.0-alpha.4",
23
+ "@superdoc-dev/sdk-darwin-x64": "1.0.0-alpha.4",
24
+ "@superdoc-dev/sdk-linux-arm64": "1.0.0-alpha.4",
25
+ "@superdoc-dev/sdk-linux-x64": "1.0.0-alpha.4",
26
+ "@superdoc-dev/sdk-windows-x64": "1.0.0-alpha.4"
19
27
  },
20
28
  "devDependencies": {
21
29
  "@types/bun": "^1.3.8",
@@ -26,6 +34,7 @@
26
34
  "access": "public"
27
35
  },
28
36
  "scripts": {
37
+ "build": "tsc",
29
38
  "typecheck": "tsc --noEmit"
30
39
  }
31
40
  }