@argentic-ai/client 0.3.0 → 0.4.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
@@ -49,7 +49,7 @@ const out = await run({
49
49
  console.log(out.reply)
50
50
  ```
51
51
 
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.
52
+ `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
53
 
54
54
  ## Once per operation (`once_per`, 0.1.7)
55
55
 
@@ -70,17 +70,17 @@ const out = await client.wake('support-bot', { message: 'Book Tuesday.', model:
70
70
 
71
71
  ## Waking the agent later
72
72
 
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`:
73
+ 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
74
 
75
75
  ```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() })
76
+ const out = await run({ client, agent: 'support-bot', runId: event.id, task: event.text, tools, schedule: true })
77
+ if (out.wakeAt) await queue.add('wake-support-bot', {}, { delay: Math.max(1000, Date.parse(out.wakeAt) - Date.now()) })
78
78
 
79
- // later, in that job:
80
- const next = await client.wake('support-bot', { fire_due: true, model: freeModel, schedule: true })
79
+ // later, in that job: the agent's tools run as before, and the result has the next wakeAt
80
+ const next = await run({ client, agent: 'support-bot', runId: `due-${Date.now()}`, fireDue: true, tools, schedule: true })
81
81
  ```
82
82
 
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.
83
+ 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
84
 
85
85
  ## What to know
86
86
 
@@ -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;
@@ -186,14 +188,15 @@ export interface LedgerEntry {
186
188
  /** 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
189
  export type StoppedWake = Omit<WakeResult, 'idempotentReplay'>;
188
190
  export declare class Ledger {
189
- readonly path: string;
191
+ readonly path?: string | undefined;
190
192
  private entries;
191
193
  private wakes;
192
194
  /**
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.
195
+ * With no `path` the ledger lives in memory only and nothing is written to disk. With one, a missing file starts an empty
196
+ * ledger, and a file that cannot be read or parsed is set aside as `<path>.corrupt` and `onCorrupt` is told, because an
197
+ * empty ledger means finished actions may run again. `onCorrupt` defaults to console.warn.
195
198
  */
196
- constructor(path: string, onCorrupt?: (message: string) => void);
199
+ constructor(path?: string | undefined, onCorrupt?: (message: string) => void);
197
200
  get(key: string): LedgerEntry | undefined;
198
201
  set(key: string, entry: LedgerEntry): void;
199
202
  /** The stopped wake answered for this idempotency key, if one was kept. */
@@ -231,11 +234,21 @@ export interface RunOptions {
231
234
  client: Argentic;
232
235
  agent: string;
233
236
  /** Chosen by you and kept the same across restarts. */
237
+ /** 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
238
  runId: string;
235
- task: string;
239
+ /** The new event: what happened since the agent last ran. Send only that, never the earlier messages. Leave it out when `fireDue` is set. */
240
+ task?: string;
241
+ /** Wake the agent for the plans whose `wake_at` has come, instead of with a task. Costs nothing when none is due. */
242
+ fireDue?: boolean;
243
+ /** 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. */
244
+ schedule?: boolean;
236
245
  system?: string;
237
246
  tools: Tool[];
238
- ledgerPath: string;
247
+ /**
248
+ * Where finished actions are kept, so a process that was killed and started again does not run them twice. Leave it out and
249
+ * they are kept in memory for this call only (no file is written); then make your tools safe to repeat, with `ctx.idempotencyKey`.
250
+ */
251
+ ledgerPath?: string;
239
252
  model?: ModelSpec;
240
253
  maxSteps?: number;
241
254
  limits?: WakeBody['limits'];
@@ -272,6 +285,8 @@ export interface RunResult {
272
285
  steps: number;
273
286
  status: WakeStatus | 'max_steps';
274
287
  spentUsd: number;
288
+ /** 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`. */
289
+ wakeAt: string | null;
275
290
  }
276
291
  export declare function run(opts: RunOptions): Promise<RunResult>;
277
292
  /** @deprecated Renamed to `run` in 0.2.0. Same function; this name stays so existing code keeps working. */
package/dist/argentic.js CHANGED
@@ -270,11 +270,14 @@ export class Ledger {
270
270
  entries = {};
271
271
  wakes = {};
272
272
  /**
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.
273
+ * With no `path` the ledger lives in memory only and nothing is written to disk. With one, a missing file starts an empty
274
+ * ledger, and a file that cannot be read or parsed is set aside as `<path>.corrupt` and `onCorrupt` is told, because an
275
+ * empty ledger means finished actions may run again. `onCorrupt` defaults to console.warn.
275
276
  */
276
277
  constructor(path, onCorrupt = (m) => console.warn(m)) {
277
278
  this.path = path;
279
+ if (path === undefined)
280
+ return;
278
281
  let text;
279
282
  try {
280
283
  text = readFileSync(path, 'utf8');
@@ -321,6 +324,8 @@ export class Ledger {
321
324
  }
322
325
  /** Write temp file, then rename, so a crash never leaves half a ledger. */
323
326
  save() {
327
+ if (this.path === undefined)
328
+ return;
324
329
  mkdirSync(dirname(this.path) || '.', { recursive: true });
325
330
  const tmp = `${this.path}.${process.pid}.tmp`;
326
331
  writeFileSync(tmp, JSON.stringify(Object.keys(this.wakes).length ? { entries: this.entries, wakes: this.wakes } : { entries: this.entries }, null, 2));
@@ -350,6 +355,8 @@ const safeKey = (s) => s.replace(/[^A-Za-z0-9\-_.:]/g, '-').slice(0, 128);
350
355
  const carriesOn = (s) => s === 'turn_cap' || s === 'time_cap';
351
356
  export async function run(opts) {
352
357
  const { client, agent, tools } = opts;
358
+ if (opts.fireDue ? opts.task !== undefined : opts.task === undefined)
359
+ throw new Error('run: pass `task` (the new event) or `fireDue: true`, not both and not neither');
353
360
  const log = opts.log ?? ((line) => console.log(line));
354
361
  const maxSteps = opts.maxSteps ?? 8;
355
362
  const model = opts.model ?? freeModel;
@@ -364,6 +371,7 @@ export async function run(opts) {
364
371
  const wakes = [];
365
372
  let message = opts.task;
366
373
  let reply = '';
374
+ let wakeAt = null;
367
375
  let spentUsd = 0;
368
376
  let status = 'max_steps';
369
377
  let steps = 0;
@@ -372,7 +380,9 @@ export async function run(opts) {
372
380
  let pending = [];
373
381
  for (let step = 0; step < maxSteps; step++) {
374
382
  const key = safeKey(`${opts.runId}.${step}`);
375
- const body = { message, model, tools: decls };
383
+ const body = step === 0 && opts.fireDue ? { fire_due: true, model, tools: decls } : { message, model, tools: decls };
384
+ if (opts.schedule)
385
+ body.schedule = true;
376
386
  if (structured && step > 0 && pending.length)
377
387
  body.results = pending;
378
388
  opts.onWakeStart?.({ step });
@@ -388,11 +398,13 @@ export async function run(opts) {
388
398
  ledger.setWake(key, answer);
389
399
  }
390
400
  steps = step + 1;
391
- wakes.push(res.wake_id);
401
+ if (res.wake_id)
402
+ wakes.push(res.wake_id); // a `fireDue` wake with nothing due has none
392
403
  reply = res.reply ?? '';
393
404
  spentUsd += res.spent_usd ?? 0;
394
405
  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)' : ''}`);
406
+ wakeAt = res.wake_at ?? null;
407
+ log(`step ${step}: wake ${res.wake_id ?? '(nothing due)'} ${res.status}${kept ? ' (stopped answer kept in the ledger)' : res.idempotentReplay ? ' (stored answer replayed)' : ''}`);
396
408
  opts.onWake?.({ step, wakeId: res.wake_id, status: res.status, replayed: !!res.idempotentReplay });
397
409
  const actions = res.actions ?? [];
398
410
  const results = [];
@@ -435,7 +447,7 @@ export async function run(opts) {
435
447
  message = 'Results of the tools you asked for:\n' + JSON.stringify(results);
436
448
  pending = results.map(({ seq, result }) => ({ seq, result }));
437
449
  }
438
- return { reply, wakes, steps, status, spentUsd };
450
+ return { reply, wakes, steps, status, spentUsd, wakeAt };
439
451
  }
440
452
  /** @deprecated Renamed to `run` in 0.2.0. Same function; this name stays so existing code keeps working. */
441
453
  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.4.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",