@argentic-ai/client 0.3.0 → 0.5.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.
package/README.md CHANGED
@@ -39,7 +39,8 @@ const tools = { refund_order: tool({
39
39
  execute: async (args, { toolCallId }) => refund(args, toolCallId),
40
40
  }) }
41
41
 
42
- // apiKey defaults to ARGENTIC_API_KEY and modelKey to MODEL_KEY
42
+ // apiKey defaults to ARGENTIC_API_KEY, modelKey to MODEL_KEY, and embedKey to EMBED_KEY
43
+ // (optional: with it, the agent's recall also finds what was said in other words)
43
44
  const client = new Argentic()
44
45
  const out = await run({
45
46
  client, agent: 'my-agent', runId: 'order-1182', ledgerPath: '.argentic-ledger.json',
@@ -49,7 +50,7 @@ const out = await run({
49
50
  console.log(out.reply)
50
51
  ```
51
52
 
52
- Keep `agent` and `runId` the same across restarts. A request that takes longer than `timeoutMs` (default 300000, 0 for no limit) counts as a network failure and is retried with the same key. If the ledger file is not valid JSON, `run` warns on stderr, sets the file aside as `<path>.corrupt` and starts empty, so finished actions may run again. `client.replay(agent, wakeId)` re-renders a wake's prompts from the journal and compares them to what the model saw; it calls no model and spends nothing.
53
+ `task` is the new event: what happened since the agent last ran, never the earlier messages. Keep `agent` and `runId` the same when a run is retried (the id of the event that woke the agent is a good `runId`). `ledgerPath` is optional: with it, finished actions are written to that file so a killed process does not run them twice; without it they are kept in memory for the call, so make your tools safe to repeat with the `ctx.idempotencyKey` your `execute` receives. A request that takes longer than `timeoutMs` (default 300000, 0 for no limit) counts as a network failure and is retried with the same key. If the ledger file is not valid JSON, `run` warns on stderr, sets the file aside as `<path>.corrupt` and starts empty, so finished actions may run again. `client.replay(agent, wakeId)` re-renders a wake's prompts from the journal and compares them to what the model saw; it calls no model and spends nothing.
53
54
 
54
55
  ## Once per operation (`once_per`, 0.1.7)
55
56
 
@@ -70,17 +71,17 @@ const out = await client.wake('support-bot', { message: 'Book Tuesday.', model:
70
71
 
71
72
  ## Waking the agent later
72
73
 
73
- Argentic has no clock of its own: your app decides when an agent runs. Send `schedule: true` on the agent's wakes so it can put a time on a plan. Every answer then has `wake_at`, the time the agent next wants waking, or `null`. Keep the latest one per agent in your own scheduler (a cron job, a delayed queue job) and at that time wake the agent with `fire_due`:
74
+ Argentic has no clock of its own: your app decides when an agent runs. Pass `schedule: true` to `run` so the agent can put a time on a plan. The result's `wakeAt` is the time it next wants waking (an ISO time, already past if a plan is due), or `null`. Keep it in your own scheduler (a cron job, a delayed queue job) and wake the agent then with `fireDue: true`, which takes the place of `task`:
74
75
 
75
76
  ```ts
76
- const out = await client.wake('support-bot', { message: 'Chase the refund on Friday.', model: freeModel, schedule: true }, 'chase-1')
77
- if (out.wake_at) await queue.add('wake-support-bot', {}, { delay: Date.parse(out.wake_at) - Date.now() })
77
+ const out = await run({ client, agent: 'support-bot', runId: event.id, task: event.text, tools, schedule: true })
78
+ if (out.wakeAt) await queue.add('wake-support-bot', {}, { delay: Math.max(1000, Date.parse(out.wakeAt) - Date.now()) })
78
79
 
79
- // later, in that job:
80
- const next = await client.wake('support-bot', { fire_due: true, model: freeModel, schedule: true })
80
+ // later, in that job: the agent's tools run as before, and the result has the next wakeAt
81
+ const next = await run({ client, agent: 'support-bot', runId: `due-${Date.now()}`, fireDue: true, tools, schedule: true })
81
82
  ```
82
83
 
83
- A `fire_due` wake with nothing due makes no model call and costs nothing. `client.due()` lists every plan whose time has passed, if your scheduler loses track.
84
+ A `fireDue` wake with nothing due makes no model call and costs nothing. With `client.wake()` the same fields are `schedule: true`, `fire_due: true` and the answer's `wake_at`. `client.due()` lists every plan whose time has passed, if your scheduler loses track.
84
85
 
85
86
  ## What to know
86
87
 
@@ -4,9 +4,11 @@ export declare const defaultTimeoutMs = 300000;
4
4
  export interface ModelSpec {
5
5
  provider: string;
6
6
  id: string;
7
+ /** Dollars per million tokens. `cache_hit` is what a cached input token costs, if your provider has a cache price. */
7
8
  prices: {
8
9
  in: number;
9
10
  out: number;
11
+ cache_hit?: number;
10
12
  };
11
13
  }
12
14
  /** The free default model. */
@@ -83,7 +85,7 @@ export interface Action {
83
85
  args: Record<string, unknown>;
84
86
  seq: number;
85
87
  }
86
- export type WakeStatus = 'done' | 'spend_cap' | 'budget_cap' | 'turn_cap' | 'time_cap' | 'error' | 'approval_required';
88
+ export type WakeStatus = 'done' | 'spend_cap' | 'budget_cap' | 'turn_cap' | 'time_cap' | 'error';
87
89
  export interface WakeResult {
88
90
  status: WakeStatus;
89
91
  reply: string;
@@ -131,6 +133,15 @@ export interface ClientOptions {
131
133
  apiKey?: string;
132
134
  /** Sent as X-Model-Key on wake. Defaults to the MODEL_KEY environment variable. */
133
135
  modelKey?: string;
136
+ /**
137
+ * Your embedding provider key, sent as X-Embed-Key on wake, so the agent's recall also finds what was said in other words. Defaults to the
138
+ * EMBED_KEY environment variable; without one, recall works by words. Never stored by Argentic; your provider bills you for it.
139
+ */
140
+ embedKey?: string;
141
+ /** Sent as X-Embed-Provider: `cohere` (the default) or `bedrock`. Defaults to the EMBED_PROVIDER environment variable. */
142
+ embedProvider?: string;
143
+ /** Sent as X-Embed-Region, for `bedrock` (default `us-east-1`). Defaults to the EMBED_REGION environment variable. */
144
+ embedRegion?: string;
134
145
  baseUrl?: string;
135
146
  /** How long one request may take before that try counts as a network failure, in milliseconds. Default 300000; 0 means no limit. */
136
147
  timeoutMs?: number;
@@ -144,6 +155,7 @@ export interface ClientOptions {
144
155
  export declare class Argentic {
145
156
  private readonly apiKey;
146
157
  private readonly modelKey?;
158
+ private readonly embed;
147
159
  private readonly baseUrl;
148
160
  private readonly timeoutMs;
149
161
  private readonly doFetch;
@@ -186,14 +198,15 @@ export interface LedgerEntry {
186
198
  /** A wake that stopped at its turn or time limit with actions to run, kept so a restart sends their results instead of asking the wake again. */
187
199
  export type StoppedWake = Omit<WakeResult, 'idempotentReplay'>;
188
200
  export declare class Ledger {
189
- readonly path: string;
201
+ readonly path?: string | undefined;
190
202
  private entries;
191
203
  private wakes;
192
204
  /**
193
- * A missing file starts an empty ledger. A file that cannot be read or parsed is set aside as `<path>.corrupt` and `onCorrupt`
194
- * is told, because an empty ledger means finished actions may run again. `onCorrupt` defaults to console.warn.
205
+ * With no `path` the ledger lives in memory only and nothing is written to disk. With one, a missing file starts an empty
206
+ * ledger, and a file that cannot be read or parsed is set aside as `<path>.corrupt` and `onCorrupt` is told, because an
207
+ * empty ledger means finished actions may run again. `onCorrupt` defaults to console.warn.
195
208
  */
196
- constructor(path: string, onCorrupt?: (message: string) => void);
209
+ constructor(path?: string | undefined, onCorrupt?: (message: string) => void);
197
210
  get(key: string): LedgerEntry | undefined;
198
211
  set(key: string, entry: LedgerEntry): void;
199
212
  /** The stopped wake answered for this idempotency key, if one was kept. */
@@ -231,11 +244,21 @@ export interface RunOptions {
231
244
  client: Argentic;
232
245
  agent: string;
233
246
  /** Chosen by you and kept the same across restarts. */
247
+ /** Chosen by you and kept the same when a run is retried. The id of the event that woke the agent is a good one. */
234
248
  runId: string;
235
- task: string;
249
+ /** The new event: what happened since the agent last ran. Send only that, never the earlier messages. Leave it out when `fireDue` is set. */
250
+ task?: string;
251
+ /** Wake the agent for the plans whose `wake_at` has come, instead of with a task. Costs nothing when none is due. */
252
+ fireDue?: boolean;
253
+ /** True when your app will wake the agent at the `wake_at` this run returns, so the agent may put a time on a plan. Send it on every run of that agent. */
254
+ schedule?: boolean;
236
255
  system?: string;
237
256
  tools: Tool[];
238
- ledgerPath: string;
257
+ /**
258
+ * Where finished actions are kept, so a process that was killed and started again does not run them twice. Leave it out and
259
+ * they are kept in memory for this call only (no file is written); then make your tools safe to repeat, with `ctx.idempotencyKey`.
260
+ */
261
+ ledgerPath?: string;
239
262
  model?: ModelSpec;
240
263
  maxSteps?: number;
241
264
  limits?: WakeBody['limits'];
@@ -272,6 +295,8 @@ export interface RunResult {
272
295
  steps: number;
273
296
  status: WakeStatus | 'max_steps';
274
297
  spentUsd: number;
298
+ /** When the agent next wants waking (an ISO time, already past if a plan is due), or null. Argentic keeps no clock: your scheduler wakes it then, with `run({ fireDue: true })`. Needs `schedule: true`. */
299
+ wakeAt: string | null;
275
300
  }
276
301
  export declare function run(opts: RunOptions): Promise<RunResult>;
277
302
  /** @deprecated Renamed to `run` in 0.2.0. Same function; this name stays so existing code keeps working. */
package/dist/argentic.js CHANGED
@@ -119,6 +119,8 @@ export function hintFor(e) {
119
119
  return 'Check ARGENTIC_API_KEY. A key only works on the API it was made for, so if you set ARGENTIC_BASE_URL, make the key in that dashboard.';
120
120
  if (code === 'model_key_rejected')
121
121
  return 'Your model provider refused MODEL_KEY. Check it is a key for the provider in the error (a free NVIDIA key starts with nvapi-).';
122
+ if (code === 'bad_embed_key')
123
+ return 'The API cannot use EMBED_KEY as sent: EMBED_PROVIDER is cohere (the default) or bedrock, EMBED_REGION goes with bedrock only, and the key has no spaces. Unset EMBED_KEY to recall by words alone.';
122
124
  if (code === 'bad_model')
123
125
  return 'Your provider does not know this model id. Set ARGENTIC_MODEL_ID to one it serves, or unset it for the free default.';
124
126
  if (e.status === 402)
@@ -133,6 +135,7 @@ const wait = (ms) => new Promise((r) => setTimeout(r, ms));
133
135
  export class Argentic {
134
136
  apiKey;
135
137
  modelKey;
138
+ embed;
136
139
  baseUrl;
137
140
  timeoutMs;
138
141
  doFetch;
@@ -144,6 +147,12 @@ export class Argentic {
144
147
  constructor(opts = {}) {
145
148
  this.apiKey = opts.apiKey ?? process.env.ARGENTIC_API_KEY ?? '';
146
149
  this.modelKey = opts.modelKey || process.env.MODEL_KEY || undefined;
150
+ const embedKey = opts.embedKey || process.env.EMBED_KEY || undefined;
151
+ const embedProvider = opts.embedProvider || process.env.EMBED_PROVIDER || undefined;
152
+ const embedRegion = opts.embedRegion || process.env.EMBED_REGION || undefined;
153
+ this.embed = embedKey
154
+ ? { 'X-Embed-Key': embedKey, ...(embedProvider ? { 'X-Embed-Provider': embedProvider } : {}), ...(embedRegion ? { 'X-Embed-Region': embedRegion } : {}) }
155
+ : {};
147
156
  this.timeoutMs = opts.timeoutMs ?? defaultTimeoutMs;
148
157
  this.baseUrl = (opts.baseUrl ?? process.env.ARGENTIC_BASE_URL ?? defaultBaseUrl).replace(/\/+$/, '');
149
158
  this.doFetch = opts.fetch ?? fetch;
@@ -166,6 +175,7 @@ export class Argentic {
166
175
  };
167
176
  if (this.modelKey)
168
177
  headers['X-Model-Key'] = this.modelKey;
178
+ Object.assign(headers, this.embed);
169
179
  const path = `/v1/agents/${encodeURIComponent(agent)}/wake`;
170
180
  const { results, ...plain } = body;
171
181
  let res;
@@ -270,11 +280,14 @@ export class Ledger {
270
280
  entries = {};
271
281
  wakes = {};
272
282
  /**
273
- * A missing file starts an empty ledger. A file that cannot be read or parsed is set aside as `<path>.corrupt` and `onCorrupt`
274
- * is told, because an empty ledger means finished actions may run again. `onCorrupt` defaults to console.warn.
283
+ * With no `path` the ledger lives in memory only and nothing is written to disk. With one, a missing file starts an empty
284
+ * ledger, and a file that cannot be read or parsed is set aside as `<path>.corrupt` and `onCorrupt` is told, because an
285
+ * empty ledger means finished actions may run again. `onCorrupt` defaults to console.warn.
275
286
  */
276
287
  constructor(path, onCorrupt = (m) => console.warn(m)) {
277
288
  this.path = path;
289
+ if (path === undefined)
290
+ return;
278
291
  let text;
279
292
  try {
280
293
  text = readFileSync(path, 'utf8');
@@ -321,6 +334,8 @@ export class Ledger {
321
334
  }
322
335
  /** Write temp file, then rename, so a crash never leaves half a ledger. */
323
336
  save() {
337
+ if (this.path === undefined)
338
+ return;
324
339
  mkdirSync(dirname(this.path) || '.', { recursive: true });
325
340
  const tmp = `${this.path}.${process.pid}.tmp`;
326
341
  writeFileSync(tmp, JSON.stringify(Object.keys(this.wakes).length ? { entries: this.entries, wakes: this.wakes } : { entries: this.entries }, null, 2));
@@ -350,6 +365,8 @@ const safeKey = (s) => s.replace(/[^A-Za-z0-9\-_.:]/g, '-').slice(0, 128);
350
365
  const carriesOn = (s) => s === 'turn_cap' || s === 'time_cap';
351
366
  export async function run(opts) {
352
367
  const { client, agent, tools } = opts;
368
+ if (opts.fireDue ? opts.task !== undefined : opts.task === undefined)
369
+ throw new Error('run: pass `task` (the new event) or `fireDue: true`, not both and not neither');
353
370
  const log = opts.log ?? ((line) => console.log(line));
354
371
  const maxSteps = opts.maxSteps ?? 8;
355
372
  const model = opts.model ?? freeModel;
@@ -364,6 +381,7 @@ export async function run(opts) {
364
381
  const wakes = [];
365
382
  let message = opts.task;
366
383
  let reply = '';
384
+ let wakeAt = null;
367
385
  let spentUsd = 0;
368
386
  let status = 'max_steps';
369
387
  let steps = 0;
@@ -372,7 +390,9 @@ export async function run(opts) {
372
390
  let pending = [];
373
391
  for (let step = 0; step < maxSteps; step++) {
374
392
  const key = safeKey(`${opts.runId}.${step}`);
375
- const body = { message, model, tools: decls };
393
+ const body = step === 0 && opts.fireDue ? { fire_due: true, model, tools: decls } : { message, model, tools: decls };
394
+ if (opts.schedule)
395
+ body.schedule = true;
376
396
  if (structured && step > 0 && pending.length)
377
397
  body.results = pending;
378
398
  opts.onWakeStart?.({ step });
@@ -388,11 +408,13 @@ export async function run(opts) {
388
408
  ledger.setWake(key, answer);
389
409
  }
390
410
  steps = step + 1;
391
- wakes.push(res.wake_id);
411
+ if (res.wake_id)
412
+ wakes.push(res.wake_id); // a `fireDue` wake with nothing due has none
392
413
  reply = res.reply ?? '';
393
414
  spentUsd += res.spent_usd ?? 0;
394
415
  status = res.status;
395
- log(`step ${step}: wake ${res.wake_id} ${res.status}${kept ? ' (stopped answer kept in the ledger)' : res.idempotentReplay ? ' (stored answer replayed)' : ''}`);
416
+ wakeAt = res.wake_at ?? null;
417
+ log(`step ${step}: wake ${res.wake_id ?? '(nothing due)'} ${res.status}${kept ? ' (stopped answer kept in the ledger)' : res.idempotentReplay ? ' (stored answer replayed)' : ''}`);
396
418
  opts.onWake?.({ step, wakeId: res.wake_id, status: res.status, replayed: !!res.idempotentReplay });
397
419
  const actions = res.actions ?? [];
398
420
  const results = [];
@@ -435,7 +457,7 @@ export async function run(opts) {
435
457
  message = 'Results of the tools you asked for:\n' + JSON.stringify(results);
436
458
  pending = results.map(({ seq, result }) => ({ seq, result }));
437
459
  }
438
- return { reply, wakes, steps, status, spentUsd };
460
+ return { reply, wakes, steps, status, spentUsd, wakeAt };
439
461
  }
440
462
  /** @deprecated Renamed to `run` in 0.2.0. Same function; this name stays so existing code keeps working. */
441
463
  export const runDurable = run;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@argentic-ai/client",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "description": "Argentic client for TypeScript. Argentic is an engine that keeps AI agents right for hours while prompt size is bounded. Adapters for the Vercel AI SDK and Mastra.",
5
5
  "license": "MIT",
6
6
  "type": "module",