@artemiskit/core 0.5.3 → 0.6.0

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 (74) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/dist/adapters/factory.d.ts +1 -1
  3. package/dist/adapters/index.d.ts +3 -3
  4. package/dist/adapters/registry.d.ts +1 -1
  5. package/dist/agent-evaluation/index.d.ts +2 -2
  6. package/dist/agent-evaluation/scorer.d.ts +1 -1
  7. package/dist/agent-workflow/catalog.d.ts +27 -0
  8. package/dist/agent-workflow/catalog.d.ts.map +1 -0
  9. package/dist/agent-workflow/index.d.ts +7 -0
  10. package/dist/agent-workflow/index.d.ts.map +1 -0
  11. package/dist/agent-workflow/parser.d.ts +7 -0
  12. package/dist/agent-workflow/parser.d.ts.map +1 -0
  13. package/dist/agent-workflow/schema.d.ts +664 -0
  14. package/dist/agent-workflow/schema.d.ts.map +1 -0
  15. package/dist/agent-workflow/simulated-tools.d.ts +35 -0
  16. package/dist/agent-workflow/simulated-tools.d.ts.map +1 -0
  17. package/dist/agent-workflow/target.d.ts +230 -0
  18. package/dist/agent-workflow/target.d.ts.map +1 -0
  19. package/dist/artifacts/index.d.ts +2 -2
  20. package/dist/artifacts/manifest.d.ts +1 -1
  21. package/dist/artifacts/types.d.ts +2 -2
  22. package/dist/comparison/eligibility.d.ts +1 -1
  23. package/dist/comparison/index.d.ts +1 -1
  24. package/dist/evaluators/combined.d.ts +2 -2
  25. package/dist/evaluators/contains.d.ts +2 -2
  26. package/dist/evaluators/exact.d.ts +2 -2
  27. package/dist/evaluators/fuzzy.d.ts +2 -2
  28. package/dist/evaluators/index.d.ts +13 -13
  29. package/dist/evaluators/inline.d.ts +2 -2
  30. package/dist/evaluators/json-schema.d.ts +2 -2
  31. package/dist/evaluators/llm-grader.d.ts +2 -2
  32. package/dist/evaluators/not-contains.d.ts +2 -2
  33. package/dist/evaluators/regex.d.ts +2 -2
  34. package/dist/evaluators/similarity.d.ts +2 -2
  35. package/dist/evaluators/tool-trace.d.ts +2 -2
  36. package/dist/evaluators/types.d.ts +3 -3
  37. package/dist/index.d.ts +15 -14
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/index.js +16291 -14983
  40. package/dist/provenance/execution-provenance.d.ts +1 -1
  41. package/dist/provenance/git.d.ts +1 -1
  42. package/dist/provenance/index.d.ts +4 -4
  43. package/dist/provenance/workload-identity.d.ts +2 -2
  44. package/dist/redaction/index.d.ts +2 -2
  45. package/dist/redaction/redactor.d.ts +1 -1
  46. package/dist/runner/executor.d.ts +3 -3
  47. package/dist/runner/index.d.ts +3 -3
  48. package/dist/runner/runner.d.ts +1 -1
  49. package/dist/runner/types.d.ts +5 -5
  50. package/dist/scenario/index.d.ts +4 -4
  51. package/dist/scenario/parser.d.ts +1 -1
  52. package/dist/scenario/variables.d.ts +1 -1
  53. package/dist/storage/factory.d.ts +1 -1
  54. package/dist/storage/index.d.ts +4 -4
  55. package/dist/storage/local.d.ts +2 -2
  56. package/dist/storage/supabase.d.ts +2 -2
  57. package/dist/storage/types.d.ts +2 -2
  58. package/dist/tools/fixture-executor.d.ts +2 -2
  59. package/dist/tools/index.d.ts +3 -3
  60. package/dist/tools/types.d.ts +1 -1
  61. package/dist/utils/index.d.ts +2 -2
  62. package/dist/validator/index.d.ts +2 -2
  63. package/dist/validator/validator.d.ts +1 -1
  64. package/package.json +4 -4
  65. package/src/agent-workflow/catalog.ts +219 -0
  66. package/src/agent-workflow/index.ts +6 -0
  67. package/src/agent-workflow/parser.ts +43 -0
  68. package/src/agent-workflow/schema.test.ts +218 -0
  69. package/src/agent-workflow/schema.ts +254 -0
  70. package/src/agent-workflow/simulated-tools.test.ts +177 -0
  71. package/src/agent-workflow/simulated-tools.ts +230 -0
  72. package/src/agent-workflow/target.test.ts +276 -0
  73. package/src/agent-workflow/target.ts +292 -0
  74. package/src/index.ts +3 -0
@@ -0,0 +1,292 @@
1
+ import Ajv from 'ajv';
2
+ import { z } from 'zod';
3
+ import type { GenerateOptions, ModelClient, TokenUsage, ToolCall } from '../adapters/types';
4
+
5
+ const identifier = z.string().min(1).max(256);
6
+ const toolName = z.string().regex(/^[a-zA-Z_][a-zA-Z0-9_-]{0,63}$/);
7
+ const text = z.string().max(1_000_000);
8
+ const toolCallSchema = z
9
+ .object({
10
+ id: identifier,
11
+ type: z.literal('function'),
12
+ function: z.object({ name: toolName, arguments: text }).strict(),
13
+ })
14
+ .strict();
15
+ const messageSchema = z
16
+ .object({
17
+ role: z.enum(['system', 'user', 'assistant', 'tool']),
18
+ content: text,
19
+ toolCallId: identifier.optional(),
20
+ tool_calls: z.array(toolCallSchema).min(1).max(100).optional(),
21
+ })
22
+ .strict();
23
+ const timeoutSchema = z.number().int().min(1).max(2_147_483_647);
24
+ const requestSchema = z
25
+ .object({
26
+ messages: z.array(messageSchema).min(1).max(1000),
27
+ tools: z
28
+ .array(
29
+ z
30
+ .object({
31
+ type: z.literal('function'),
32
+ function: z
33
+ .object({
34
+ name: toolName,
35
+ description: z.string().max(10_000).optional(),
36
+ parameters: z.record(z.unknown()),
37
+ })
38
+ .strict(),
39
+ })
40
+ .strict()
41
+ )
42
+ .max(100),
43
+ model: identifier.optional(),
44
+ generation: z
45
+ .object({
46
+ maxTokens: z.number().int().positive().max(1_000_000),
47
+ temperature: z.number().finite().min(0).max(2).optional(),
48
+ topP: z.number().finite().min(0).max(1).optional(),
49
+ seed: z.number().int().safe().optional(),
50
+ stop: z.array(z.string().min(1).max(1000)).max(16).optional(),
51
+ })
52
+ .strict(),
53
+ budgets: z
54
+ .object({
55
+ timeoutMs: timeoutSchema,
56
+ maxToolCalls: z.number().int().min(0).max(100),
57
+ })
58
+ .strict(),
59
+ })
60
+ .strict();
61
+ const resultSchema = z.object({
62
+ id: identifier,
63
+ model: identifier,
64
+ text,
65
+ tokens: z.object({
66
+ prompt: z.number().int().nonnegative().safe(),
67
+ completion: z.number().int().nonnegative().safe(),
68
+ total: z.number().int().nonnegative().safe(),
69
+ }),
70
+ latencyMs: z.number().finite().nonnegative(),
71
+ finishReason: z
72
+ .enum(['stop', 'length', 'function_call', 'tool_calls', 'content_filter'])
73
+ .optional(),
74
+ toolCalls: z.array(toolCallSchema).max(100).optional(),
75
+ functionCall: z.unknown().optional(),
76
+ });
77
+
78
+ export type AgentTurnRequest = z.infer<typeof requestSchema>;
79
+ export type AgentTargetFailure = {
80
+ status: 'unsupported' | 'invalid' | 'error';
81
+ code:
82
+ | 'invalid_request'
83
+ | 'tool_use_unsupported'
84
+ | 'invalid_response'
85
+ | 'target_error'
86
+ | 'timeout'
87
+ | 'aborted';
88
+ };
89
+ export type AgentTargetCapabilities = {
90
+ status: 'available';
91
+ toolUse: boolean;
92
+ /** ModelClient has no AbortSignal contract. Timeouts bound waiting, not transport work. */
93
+ transportCancellation: false;
94
+ };
95
+ export type AgentTurnResult =
96
+ | AgentTargetFailure
97
+ | {
98
+ status: 'completed';
99
+ id: string;
100
+ model: string;
101
+ message: { role: 'assistant'; content: string; tool_calls?: ToolCall[] };
102
+ /** Adapter-reported counts only; zero can mean unavailable in existing adapters. */
103
+ tokens: TokenUsage;
104
+ latencyMs: number;
105
+ finishReason?: 'stop' | 'length' | 'tool_calls' | 'content_filter';
106
+ };
107
+
108
+ /** One bounded model turn. Tool execution, policy enforcement, and scoring belong to the harness. */
109
+ export interface AgentTarget {
110
+ readonly provider: string;
111
+ capabilities(
112
+ options: { timeoutMs: number },
113
+ signal?: AbortSignal
114
+ ): Promise<AgentTargetCapabilities | AgentTargetFailure>;
115
+ turn(request: AgentTurnRequest, signal?: AbortSignal): Promise<AgentTurnResult>;
116
+ }
117
+
118
+ const failure = (
119
+ status: AgentTargetFailure['status'],
120
+ code: AgentTargetFailure['code']
121
+ ): AgentTargetFailure => ({ status, code });
122
+
123
+ /** Do not expose provider exception text, which can contain credentials or customer content. */
124
+ function bounded<T>(
125
+ run: () => Promise<T>,
126
+ timeoutMs: number,
127
+ signal?: AbortSignal
128
+ ): Promise<T | AgentTargetFailure> {
129
+ if (signal?.aborted) return Promise.resolve(failure('error', 'aborted'));
130
+ return new Promise((resolve) => {
131
+ let finished = false;
132
+ const finish = (value: T | AgentTargetFailure) => {
133
+ if (finished) return;
134
+ finished = true;
135
+ clearTimeout(timer);
136
+ signal?.removeEventListener('abort', abort);
137
+ resolve(value);
138
+ };
139
+ const abort = () => finish(failure('error', 'aborted'));
140
+ const timer = setTimeout(() => finish(failure('error', 'timeout')), timeoutMs);
141
+ signal?.addEventListener('abort', abort, { once: true });
142
+ Promise.resolve()
143
+ .then<T | AgentTargetFailure>(() => (signal?.aborted ? failure('error', 'aborted') : run()))
144
+ .then(finish, () => finish(failure('error', 'target_error')));
145
+ });
146
+ }
147
+
148
+ function validTranscript(messages: AgentTurnRequest['messages']): boolean {
149
+ const seen = new Set<string>();
150
+ const pending = new Set<string>();
151
+ for (const message of messages) {
152
+ if (message.role === 'tool') {
153
+ if (!message.toolCallId || message.tool_calls || !pending.delete(message.toolCallId))
154
+ return false;
155
+ continue;
156
+ }
157
+ if (message.toolCallId || pending.size || (message.tool_calls && message.role !== 'assistant'))
158
+ return false;
159
+ for (const call of message.tool_calls ?? []) {
160
+ if (seen.has(call.id)) return false;
161
+ try {
162
+ const args: unknown = JSON.parse(call.function.arguments);
163
+ if (!args || typeof args !== 'object' || Array.isArray(args)) return false;
164
+ } catch {
165
+ return false;
166
+ }
167
+ seen.add(call.id);
168
+ pending.add(call.id);
169
+ }
170
+ }
171
+ return pending.size === 0;
172
+ }
173
+
174
+ /**
175
+ * Bridge existing adapters without provider-specific dispatch. Callers must configure adapter
176
+ * transport timeouts/retries separately: cancellation here cannot stop an in-flight provider call.
177
+ * Returned text/tool arguments are working conversation data, not sanitized retained evidence.
178
+ */
179
+ export function createModelClientTarget(client: ModelClient): AgentTarget {
180
+ if (
181
+ !client ||
182
+ !identifier.safeParse(client.provider).success ||
183
+ typeof client.generate !== 'function' ||
184
+ typeof client.capabilities !== 'function'
185
+ ) {
186
+ throw new TypeError('Invalid ModelClient');
187
+ }
188
+ const readCapabilities = async (): Promise<AgentTargetCapabilities | AgentTargetFailure> => {
189
+ const value = await client.capabilities();
190
+ if (!value || typeof value.toolUse !== 'boolean') return failure('invalid', 'invalid_response');
191
+ return { status: 'available', toolUse: value.toolUse, transportCancellation: false };
192
+ };
193
+ return {
194
+ provider: client.provider,
195
+ async capabilities(options, signal) {
196
+ if (!timeoutSchema.safeParse(options?.timeoutMs).success)
197
+ return failure('invalid', 'invalid_request');
198
+ return bounded(readCapabilities, options.timeoutMs, signal);
199
+ },
200
+ async turn(request, signal) {
201
+ let parsed: ReturnType<typeof requestSchema.safeParse>;
202
+ try {
203
+ parsed = requestSchema.safeParse(request);
204
+ } catch {
205
+ return failure('invalid', 'invalid_request');
206
+ }
207
+ if (!parsed.success || !validTranscript(parsed.data.messages))
208
+ return failure('invalid', 'invalid_request');
209
+ const input = parsed.data;
210
+ const validators = new Map<string, ReturnType<Ajv['compile']>>();
211
+ try {
212
+ const ajv = new Ajv({ strict: false, allErrors: false, validateFormats: false });
213
+ for (const tool of input.tools) {
214
+ if (validators.has(tool.function.name)) return failure('invalid', 'invalid_request');
215
+ // Compile a detached JSON schema without remote loading or async validation.
216
+ const schema = JSON.parse(JSON.stringify(tool.function.parameters));
217
+ if (schema.$async) return failure('invalid', 'invalid_request');
218
+ const validate = ajv.compile(schema);
219
+ if ('$async' in validate && validate.$async) return failure('invalid', 'invalid_request');
220
+ validators.set(tool.function.name, validate);
221
+ }
222
+ } catch {
223
+ return failure('invalid', 'invalid_request');
224
+ }
225
+ const started = Date.now();
226
+ return bounded(
227
+ async (): Promise<AgentTurnResult> => {
228
+ const capabilities = await readCapabilities();
229
+ if (capabilities.status !== 'available') return capabilities;
230
+ if (input.tools.length && !capabilities.toolUse)
231
+ return failure('unsupported', 'tool_use_unsupported');
232
+ if (signal?.aborted) return failure('error', 'aborted');
233
+ if (Date.now() - started >= input.budgets.timeoutMs) return failure('error', 'timeout');
234
+ const options: GenerateOptions = {
235
+ prompt: input.messages,
236
+ tools: input.tools,
237
+ model: input.model,
238
+ ...input.generation,
239
+ };
240
+ const generated = resultSchema.safeParse(await client.generate(options));
241
+ if (!generated.success) return failure('invalid', 'invalid_response');
242
+ const result = generated.data;
243
+ const calls = result.toolCalls ?? [];
244
+ if (
245
+ result.functionCall !== undefined ||
246
+ result.finishReason === 'function_call' ||
247
+ (result.finishReason === 'tool_calls' && calls.length === 0) ||
248
+ calls.length > input.budgets.maxToolCalls ||
249
+ result.tokens.total !== result.tokens.prompt + result.tokens.completion
250
+ )
251
+ return failure('invalid', 'invalid_response');
252
+ const ids = new Set(
253
+ input.messages.flatMap((message) => message.tool_calls?.map((call) => call.id) ?? [])
254
+ );
255
+ for (const call of calls) {
256
+ if (ids.has(call.id)) return failure('invalid', 'invalid_response');
257
+ ids.add(call.id);
258
+ const validate = validators.get(call.function.name);
259
+ try {
260
+ const args: unknown = JSON.parse(call.function.arguments);
261
+ if (
262
+ !args ||
263
+ typeof args !== 'object' ||
264
+ Array.isArray(args) ||
265
+ !validate ||
266
+ validate(args) !== true
267
+ )
268
+ return failure('invalid', 'invalid_response');
269
+ } catch {
270
+ return failure('invalid', 'invalid_response');
271
+ }
272
+ }
273
+ return {
274
+ status: 'completed',
275
+ id: result.id,
276
+ model: result.model,
277
+ message: {
278
+ role: 'assistant',
279
+ content: result.text,
280
+ ...(calls.length ? { tool_calls: calls } : {}),
281
+ },
282
+ tokens: result.tokens,
283
+ latencyMs: result.latencyMs,
284
+ finishReason: result.finishReason,
285
+ };
286
+ },
287
+ input.budgets.timeoutMs,
288
+ signal
289
+ );
290
+ },
291
+ };
292
+ }
package/src/index.ts CHANGED
@@ -42,5 +42,8 @@ export * from './tools';
42
42
  // Real-agent evaluation contracts
43
43
  export * from './agent-evaluation';
44
44
 
45
+ // Versioned workflow contracts and single-step primitives
46
+ export * from './agent-workflow';
47
+
45
48
  // Validator
46
49
  export * from './validator';