@argentic-ai/client 0.2.1 → 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
 
@@ -68,34 +68,19 @@ const out = await client.wake('support-bot', { message: 'Book Tuesday.', model:
68
68
 
69
69
  `run` answers the tools an agent asked for with a text message the model reads, and now also sends the same results as the `results` field of the wake: `[{ seq, result }]`, where `seq` is the action's `seq` and `result` is exactly what the tool returned (or the `{ error }` object when it threw). The API journals each as the real result of that call. The first wake of a run has none, and a result the ledger already held is sent again like the others. Pass `structuredResults: false` to send the text only. If the API you talk to does not know the field yet, it answers 400 and names `results`; the client sends that wake again once without it, under the same key, and leaves it out from then on. Calling `client.wake()` yourself, add `results` to the body next to the `message`, never with `fire_due`, at most 100 entries.
70
70
 
71
- ## Waking on a schedule (handleDue)
71
+ ## Waking the agent later
72
72
 
73
- Create a recurring schedule or a one-shot timer, and read what is 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 client = new Argentic()
77
- await client.putSchedule('support-bot', 'morning-check', { cron: '0 9 * * *', message: 'Review overnight tickets.' }) // five UTC fields
78
- await client.putSchedule('support-bot', 'follow-up', { at: '2026-11-20T09:00:00Z', message: 'Chase the open refund.' }) // one-shot
79
- await client.schedules('support-bot') // name, cron or at, next_at, last_fired_at, fires
80
- await client.due() // what is due now; wake each agent with fire_due, or let the notice below do it
81
- await client.deleteSchedule('support-bot', 'follow-up')
82
- ```
83
-
84
-
85
- Beta, off by default on the hosted API, and open to single beta users only for now. When an agent falls due (a plan's `wake_at`, a schedule, a timer or a hook event), Argentic POSTs a signed notice to the `wake_url` you registered. The notice names the agent and why it is due and carries no agent content and no model key. `handleDue` checks the signature and the time, then wakes the agent with `fire_due` on your own model key.
86
-
87
- Register the address and read the secret with the client: `await client.setWakeUrl('https://app.example.com/argentic/due')`, then `(await client.notices()).signing_secret` (`whsec_...`). Store it like a password, for example as `ARGENTIC_WEBHOOK_SECRET`. The model key stays on your server: set `MODEL_KEY` there, as for any other wake.
88
-
89
- ```ts
90
- import { Hono } from 'hono'
91
- import { handleDueResponse } from '@argentic-ai/client'
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()) })
92
78
 
93
- const app = new Hono()
94
- // Reads ARGENTIC_API_KEY, MODEL_KEY and ARGENTIC_WEBHOOK_SECRET from the environment.
95
- app.post('/argentic/due', (c) => handleDueResponse(c.req.raw))
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 })
96
81
  ```
97
82
 
98
- `handleDueResponse` answers 200 when the agent was woken, 401 if the signature or time is wrong, 400 if the body is not an `agent.due` notice, 500 if the secret is missing or malformed, and 502 if the wake itself failed (the notice is then sent again). It takes a Fetch `Request` or `{ body, headers }` with the raw body text, and works the same in a Next.js route handler. `handleDue(request, { secret, client, model, toleranceSeconds })` returns `{ notice, wake }` and throws `WebhookVerificationError` (with a `code`) before any call is made. `verifyDue(request)` only verifies and parses, so you can queue the notice and wake later. The wake uses the notice's `webhook-id` as its idempotency key, so a notice delivered twice replays the first wake instead of waking twice. Timestamps more than 300 seconds off are refused.
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.
99
84
 
100
85
  ## What to know
101
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. */
@@ -45,10 +47,12 @@ export declare function withOncePer<T extends ToolDecl>(tools: T[], oncePer?: Re
45
47
  export interface WakeBody {
46
48
  /** Required unless `fire_due` is set; the API refuses both together. */
47
49
  message?: string;
48
- /** Wake for the plans, schedules and timers that have fallen due instead of with a message. */
50
+ /** Wake for the plans that have fallen due instead of with a message: send it at the `wake_at` an earlier answer gave. */
49
51
  fire_due?: boolean;
50
52
  /** Which memory of the agent to wake. Left out, the agent's default. */
51
53
  memory?: string;
54
+ /** True when your app wakes the agent at the `wake_at` each answer gives: the agent may then put a time on a plan. Send it on every wake of that agent. */
55
+ schedule?: boolean;
52
56
  model: ModelSpec;
53
57
  system?: string;
54
58
  /** Facts for this call only (opening hours, the signed-in user's plan), up to 16,000 characters. Not written to the journal or memory; send it again on the next call if the agent still needs it. */
@@ -81,7 +85,7 @@ export interface Action {
81
85
  args: Record<string, unknown>;
82
86
  seq: number;
83
87
  }
84
- 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';
85
89
  export interface WakeResult {
86
90
  status: WakeStatus;
87
91
  reply: string;
@@ -91,6 +95,8 @@ export interface WakeResult {
91
95
  actions?: Action[];
92
96
  resumed?: boolean;
93
97
  error?: string;
98
+ /** When the agent next wants waking (its earliest plan time, already past when one is due), or null. Argentic keeps no clock: wake the agent then with `fire_due: true`. */
99
+ wake_at?: string | null;
94
100
  /** True when this key was already answered and the stored answer came back. */
95
101
  idempotentReplay: boolean;
96
102
  }
@@ -114,48 +120,13 @@ export declare class ArgenticError extends Error {
114
120
  }
115
121
  /** A next step for an error a first run tends to hit, or undefined. Examples print it instead of a stack trace. */
116
122
  export declare function hintFor(e: unknown): string | undefined;
117
- /** The body of a schedule write: exactly one of `cron` or `at`. */
118
- export interface ScheduleBody {
119
- /** Five numeric UTC fields (numbers, `*`, ranges, lists, steps). Occurrences closer than the host's grid (60 minutes in the beta) are refused. */
120
- cron?: string;
121
- /** A one-shot timer: ISO 8601 with an offset, in the future by at least the grid, at most 366 days ahead. */
122
- at?: string;
123
- /** What the agent is told when it fires, up to 4,000 characters. */
124
- message: string;
125
- enabled?: boolean;
126
- }
127
- export interface Schedule {
128
- name: string;
129
- /** Present on a recurring schedule. */
130
- cron?: string;
131
- /** Present on a one-shot timer, with `timer: true`. */
132
- at?: string;
133
- timer?: true;
134
- message: string;
135
- enabled: boolean;
136
- next_at: string;
137
- last_fired_at: string | null;
138
- fires: number;
139
- }
140
- /** One entry of due(): a plan (`plan_id`, `wake_at`), a schedule or timer (`schedule`, `scheduled_at`) or an agent waiting on an event (`reasons`, `since`). */
123
+ /** One entry of due(): a plan whose `wake_at` has passed. */
141
124
  export interface DueItem {
142
125
  agent: string;
143
126
  memory?: string;
144
- plan_id?: number;
145
- text?: string;
146
- wake_at?: string;
147
- schedule?: string;
148
- scheduled_at?: string;
149
- timer?: true;
150
- reasons?: string[];
151
- since?: string;
152
- /** The notice to your wake_url ran out of attempts. */
153
- notice_failing?: true;
154
- }
155
- export interface NoticeSettings {
156
- wake_url: string | null;
157
- /** Give this to handleDue / verifyDue as `secret`. */
158
- signing_secret: string;
127
+ plan_id: number;
128
+ text: string;
129
+ wake_at: string;
159
130
  }
160
131
  export interface ClientOptions {
161
132
  /** Defaults to the ARGENTIC_API_KEY environment variable. */
@@ -194,22 +165,10 @@ export declare class Argentic {
194
165
  wake(agent: string, body: WakeBody, idempotencyKey: string): Promise<WakeResult>;
195
166
  /** Re-render a wake's prompts from the journal and compare them to what the model was shown. Spends nothing. */
196
167
  replay(agent: string, wakeId: string): Promise<ReplayResult>;
197
- /** What is due now: plans past their wake_at, schedules and timers whose time has come, and agents waiting on an answered approval or a hook. Read only; costs nothing. */
168
+ /** Plans of your agents whose wake_at has passed. Every wake answer already gives `wake_at`; this is for a scheduler that lost track. Read only; costs nothing. */
198
169
  due(opts?: {
199
170
  limit?: number;
200
171
  }): Promise<DueItem[]>;
201
- /** Create or replace a recurring schedule (`cron`, five UTC fields) or a one-shot timer (`at`, ISO 8601 with an offset) on an agent. Needs the hosted API to have schedules switched on. */
202
- putSchedule(agent: string, name: string, body: ScheduleBody, opts?: {
203
- memory?: string;
204
- }): Promise<Schedule>;
205
- /** The schedules and timers of one agent. */
206
- schedules(agent: string, opts?: {
207
- memory?: string;
208
- }): Promise<Schedule[]>;
209
- /** Delete a schedule or timer. Throws a 404 ArgenticError if it does not exist. */
210
- deleteSchedule(agent: string, name: string, opts?: {
211
- memory?: string;
212
- }): Promise<void>;
213
172
  /**
214
173
  * Declare an agent's tools once (at most 32). A wake that sends no `tools` uses them; a wake that does send `tools` uses
215
174
  * those instead. Replaces what was stored; an empty list clears it. Returns the stored tools.
@@ -217,68 +176,9 @@ export declare class Argentic {
217
176
  putTools(agent: string, tools: ToolDecl[]): Promise<ToolDecl[]>;
218
177
  /** The tools stored for an agent with putTools(), or an empty list. */
219
178
  tools(agent: string): Promise<ToolDecl[]>;
220
- /** Where Argentic posts a signed `agent.due` notice (https, port 443, a public host), or null to stop the notices and keep polling due(). Returns the stored address. */
221
- setWakeUrl(url: string | null): Promise<string | null>;
222
- /** The wake URL and the signing secret (`whsec_...`) to give handleDue as `secret`. */
223
- notices(): Promise<NoticeSettings>;
224
179
  private plainHeaders;
225
- private schedulePath;
226
180
  private send;
227
181
  }
228
- /** What the notice says. It names the agent and why it is due, never its content. */
229
- export interface DueNotice {
230
- type: 'agent.due';
231
- agent: string;
232
- memory: string | null;
233
- reasons: string[];
234
- /** ISO time the agent became due. */
235
- since: string;
236
- }
237
- export type WebhookErrorCode = 'bad_secret' | 'missing_header' | 'bad_timestamp' | 'stale' | 'bad_signature' | 'bad_body';
238
- /** The notice cannot be trusted or read. Nothing was woken. `code` says why. */
239
- export declare class WebhookVerificationError extends Error {
240
- readonly code: WebhookErrorCode;
241
- constructor(message: string, code: WebhookErrorCode);
242
- }
243
- /** A Fetch API Request, or the raw body text with its headers. */
244
- export type DueRequest = Request | {
245
- body: string;
246
- headers: Record<string, string> | Headers;
247
- };
248
- export interface VerifyOptions {
249
- /** The `whsec_...` secret shown when the wake_url was registered. Defaults to the ARGENTIC_WEBHOOK_SECRET environment variable. */
250
- secret?: string;
251
- /** How far the notice's timestamp may be from now, either way, in seconds. Default 300. */
252
- toleranceSeconds?: number;
253
- /** The current time in milliseconds. For tests. */
254
- now?: () => number;
255
- }
256
- export interface DueOptions extends VerifyOptions {
257
- /** The client that wakes the agent. Defaults to a new Argentic(), which reads ARGENTIC_API_KEY and MODEL_KEY. */
258
- client?: Argentic;
259
- model?: ModelSpec;
260
- }
261
- /** `v1,<base64 HMAC-SHA256>` over "id.timestamp.body", keyed by the base64-decoded part of the secret after `whsec_`. Standard Webhooks. */
262
- export declare function signNotice(secret: string, id: string, timestamp: number | string, body: string): string;
263
- /**
264
- * Check the signature and the time, then parse the notice. No network. The signature is checked against the body exactly as it arrived,
265
- * so pass the raw text, not re-serialized JSON. Use it to queue the notice and wake later; the returned `id` is the key to wake with.
266
- */
267
- export declare function verifyDue(req: DueRequest, opts?: VerifyOptions): Promise<{
268
- notice: DueNotice;
269
- id: string;
270
- }>;
271
- /**
272
- * Verify a due notice, then wake the agent for what fell due, on your own model key (the notice carries none).
273
- * The wake's idempotency key comes from the notice's webhook-id, so a notice delivered again replays the first wake's answer.
274
- * Throws WebhookVerificationError before any call is made if the notice is not valid.
275
- */
276
- export declare function handleDue(req: DueRequest, opts?: DueOptions): Promise<{
277
- notice: DueNotice;
278
- wake: WakeResult;
279
- }>;
280
- /** handleDue as a route handler's answer: 200 woken, 401 not verified, 400 unreadable body, 500 secret not set up, 502 the wake failed (so the notice is sent again). */
281
- export declare function handleDueResponse(req: DueRequest, opts?: DueOptions): Promise<Response>;
282
182
  export interface LedgerEntry {
283
183
  tool: string;
284
184
  args: Record<string, unknown>;
@@ -288,14 +188,15 @@ export interface LedgerEntry {
288
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. */
289
189
  export type StoppedWake = Omit<WakeResult, 'idempotentReplay'>;
290
190
  export declare class Ledger {
291
- readonly path: string;
191
+ readonly path?: string | undefined;
292
192
  private entries;
293
193
  private wakes;
294
194
  /**
295
- * A missing file starts an empty ledger. A file that cannot be read or parsed is set aside as `<path>.corrupt` and `onCorrupt`
296
- * 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.
297
198
  */
298
- constructor(path: string, onCorrupt?: (message: string) => void);
199
+ constructor(path?: string | undefined, onCorrupt?: (message: string) => void);
299
200
  get(key: string): LedgerEntry | undefined;
300
201
  set(key: string, entry: LedgerEntry): void;
301
202
  /** The stopped wake answered for this idempotency key, if one was kept. */
@@ -333,11 +234,21 @@ export interface RunOptions {
333
234
  client: Argentic;
334
235
  agent: string;
335
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. */
336
238
  runId: string;
337
- 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;
338
245
  system?: string;
339
246
  tools: Tool[];
340
- 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;
341
252
  model?: ModelSpec;
342
253
  maxSteps?: number;
343
254
  limits?: WakeBody['limits'];
@@ -374,6 +285,8 @@ export interface RunResult {
374
285
  steps: number;
375
286
  status: WakeStatus | 'max_steps';
376
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;
377
290
  }
378
291
  export declare function run(opts: RunOptions): Promise<RunResult>;
379
292
  /** @deprecated Renamed to `run` in 0.2.0. Same function; this name stays so existing code keeps working. */
package/dist/argentic.js CHANGED
@@ -1,6 +1,5 @@
1
1
  // Argentic core: a small client and a tool loop. No dependencies, Node 22+.
2
2
  // Argentic runs the agent loop; your code carries out the tool calls it asks for.
3
- import { createHmac, timingSafeEqual } from 'node:crypto';
4
3
  import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
5
4
  import { dirname } from 'node:path';
6
5
  export const defaultBaseUrl = 'https://api.getargentic.com';
@@ -202,26 +201,12 @@ export class Argentic {
202
201
  unverifiable: json.unverifiable ?? count((t) => t.match === null),
203
202
  };
204
203
  }
205
- /** What is due now: plans past their wake_at, schedules and timers whose time has come, and agents waiting on an answered approval or a hook. Read only; costs nothing. */
204
+ /** Plans of your agents whose wake_at has passed. Every wake answer already gives `wake_at`; this is for a scheduler that lost track. Read only; costs nothing. */
206
205
  async due(opts = {}) {
207
206
  const q = opts.limit === undefined ? '' : `?limit=${encodeURIComponent(String(opts.limit))}`;
208
207
  const res = await this.send(`/v1/due${q}`, undefined, this.plainHeaders(), 'GET');
209
208
  return (await res.json()).due ?? [];
210
209
  }
211
- /** Create or replace a recurring schedule (`cron`, five UTC fields) or a one-shot timer (`at`, ISO 8601 with an offset) on an agent. Needs the hosted API to have schedules switched on. */
212
- async putSchedule(agent, name, body, opts = {}) {
213
- const res = await this.send(this.schedulePath(agent, name, opts.memory), JSON.stringify(body), { ...this.plainHeaders(), 'Content-Type': 'application/json' }, 'PUT');
214
- return (await res.json()).schedule;
215
- }
216
- /** The schedules and timers of one agent. */
217
- async schedules(agent, opts = {}) {
218
- const res = await this.send(this.schedulePath(agent, undefined, opts.memory), undefined, this.plainHeaders(), 'GET');
219
- return (await res.json()).schedules ?? [];
220
- }
221
- /** Delete a schedule or timer. Throws a 404 ArgenticError if it does not exist. */
222
- async deleteSchedule(agent, name, opts = {}) {
223
- await this.send(this.schedulePath(agent, name, opts.memory), undefined, this.plainHeaders(), 'DELETE');
224
- }
225
210
  /**
226
211
  * Declare an agent's tools once (at most 32). A wake that sends no `tools` uses them; a wake that does send `tools` uses
227
212
  * those instead. Replaces what was stored; an empty list clears it. Returns the stored tools.
@@ -235,23 +220,9 @@ export class Argentic {
235
220
  const res = await this.send(`/v1/agents/${encodeURIComponent(agent)}/tools`, undefined, this.plainHeaders(), 'GET');
236
221
  return (await res.json()).tools ?? [];
237
222
  }
238
- /** Where Argentic posts a signed `agent.due` notice (https, port 443, a public host), or null to stop the notices and keep polling due(). Returns the stored address. */
239
- async setWakeUrl(url) {
240
- const res = await this.send('/v1/settings/wake_url', JSON.stringify({ url }), { ...this.plainHeaders(), 'Content-Type': 'application/json' }, 'PUT');
241
- return (await res.json()).wake_url;
242
- }
243
- /** The wake URL and the signing secret (`whsec_...`) to give handleDue as `secret`. */
244
- async notices() {
245
- const res = await this.send('/v1/settings/notices', undefined, this.plainHeaders(), 'GET');
246
- return (await res.json());
247
- }
248
223
  plainHeaders() {
249
224
  return { Authorization: `Bearer ${this.apiKey}` };
250
225
  }
251
- schedulePath(agent, name, memory) {
252
- const base = `/v1/agents/${encodeURIComponent(agent)}/schedules${name === undefined ? '' : `/${encodeURIComponent(name)}`}`;
253
- return memory === undefined ? base : `${base}?memory=${encodeURIComponent(memory)}`;
254
- }
255
226
  async send(path, body, headers, method = 'POST') {
256
227
  let failures = 0;
257
228
  let queued = 0;
@@ -271,7 +242,7 @@ export class Argentic {
271
242
  }
272
243
  if (res && res.ok)
273
244
  return res;
274
- // 409 on a wake means queued behind another call; on a schedule write it means a limit, which is the caller's to read.
245
+ // 409 on a wake means queued behind another call.
275
246
  if (res && res.status === 409 && method === 'POST') {
276
247
  const info = (await res.json().catch(() => ({})));
277
248
  if (++queued > this.maxQueuedWaits)
@@ -294,112 +265,19 @@ export class Argentic {
294
265
  }
295
266
  }
296
267
  }
297
- /** The notice cannot be trusted or read. Nothing was woken. `code` says why. */
298
- export class WebhookVerificationError extends Error {
299
- code;
300
- constructor(message, code) {
301
- super(message);
302
- this.code = code;
303
- this.name = 'WebhookVerificationError';
304
- }
305
- }
306
- /** `v1,<base64 HMAC-SHA256>` over "id.timestamp.body", keyed by the base64-decoded part of the secret after `whsec_`. Standard Webhooks. */
307
- export function signNotice(secret, id, timestamp, body) {
308
- return `v1,${createHmac('sha256', secretKey(secret)).update(`${id}.${timestamp}.${body}`).digest('base64')}`;
309
- }
310
- function secretKey(secret) {
311
- const b64 = (secret ?? '').replace(/^whsec_/, '');
312
- const key = /^[A-Za-z0-9+/]+={0,2}$/.test(b64) && b64.length % 4 === 0 ? Buffer.from(b64, 'base64') : undefined;
313
- if (!key?.length)
314
- throw new WebhookVerificationError('the webhook secret is missing or not a whsec_ base64 string (set ARGENTIC_WEBHOOK_SECRET)', 'bad_secret');
315
- return key;
316
- }
317
- async function readDue(req) {
318
- if (typeof Request !== 'undefined' && req instanceof Request)
319
- return { body: await req.text(), get: (n) => req.headers.get(n) ?? undefined };
320
- const { body, headers } = req;
321
- if (headers instanceof Headers)
322
- return { body, get: (n) => headers.get(n) ?? undefined };
323
- const lower = new Map(Object.entries(headers).map(([k, v]) => [k.toLowerCase(), v]));
324
- return { body, get: (n) => lower.get(n) };
325
- }
326
- /**
327
- * Check the signature and the time, then parse the notice. No network. The signature is checked against the body exactly as it arrived,
328
- * so pass the raw text, not re-serialized JSON. Use it to queue the notice and wake later; the returned `id` is the key to wake with.
329
- */
330
- export async function verifyDue(req, opts = {}) {
331
- const key = secretKey(opts.secret ?? process.env.ARGENTIC_WEBHOOK_SECRET);
332
- const { body, get } = await readDue(req);
333
- const id = get('webhook-id');
334
- const stamp = get('webhook-timestamp');
335
- const sigs = get('webhook-signature');
336
- if (!id || !stamp || !sigs)
337
- throw new WebhookVerificationError('missing webhook-id, webhook-timestamp or webhook-signature header', 'missing_header');
338
- if (!/^\d{1,12}$/.test(stamp))
339
- throw new WebhookVerificationError('webhook-timestamp is not a number of seconds', 'bad_timestamp');
340
- const nowS = (opts.now ?? Date.now)() / 1000;
341
- if (Math.abs(nowS - Number(stamp)) > (opts.toleranceSeconds ?? 300))
342
- throw new WebhookVerificationError('webhook-timestamp is outside the allowed window', 'stale');
343
- const expected = createHmac('sha256', key).update(`${id}.${stamp}.${body}`).digest();
344
- let ok = false;
345
- for (const entry of sigs.split(/\s+/)) {
346
- const [version, sig] = entry.split(',');
347
- if (version !== 'v1' || !sig)
348
- continue;
349
- const given = Buffer.from(sig, 'base64');
350
- if (given.length === expected.length && timingSafeEqual(given, expected))
351
- ok = true;
352
- }
353
- if (!ok)
354
- throw new WebhookVerificationError('no webhook-signature matches', 'bad_signature');
355
- let notice;
356
- try {
357
- notice = JSON.parse(body);
358
- }
359
- catch {
360
- throw new WebhookVerificationError('the notice body is not JSON', 'bad_body');
361
- }
362
- if (notice?.type !== 'agent.due' || typeof notice.agent !== 'string' || !notice.agent)
363
- throw new WebhookVerificationError('not an agent.due notice', 'bad_body');
364
- return { notice, id };
365
- }
366
- /**
367
- * Verify a due notice, then wake the agent for what fell due, on your own model key (the notice carries none).
368
- * The wake's idempotency key comes from the notice's webhook-id, so a notice delivered again replays the first wake's answer.
369
- * Throws WebhookVerificationError before any call is made if the notice is not valid.
370
- */
371
- export async function handleDue(req, opts = {}) {
372
- const { notice, id } = await verifyDue(req, opts);
373
- const body = { fire_due: true, model: opts.model ?? freeModel };
374
- if (notice.memory != null)
375
- body.memory = notice.memory;
376
- const wake = await (opts.client ?? new Argentic()).wake(notice.agent, body, safeKey(id));
377
- return { notice, wake };
378
- }
379
- /** handleDue as a route handler's answer: 200 woken, 401 not verified, 400 unreadable body, 500 secret not set up, 502 the wake failed (so the notice is sent again). */
380
- export async function handleDueResponse(req, opts = {}) {
381
- try {
382
- const { notice, wake } = await handleDue(req, opts);
383
- return Response.json({ agent: notice.agent, wake_id: wake.wake_id, status: wake.status });
384
- }
385
- catch (e) {
386
- if (e instanceof WebhookVerificationError) {
387
- const status = e.code === 'bad_body' ? 400 : e.code === 'bad_secret' ? 500 : 401;
388
- return Response.json({ error: e.code }, { status });
389
- }
390
- return Response.json({ error: 'wake_failed' }, { status: 502 });
391
- }
392
- }
393
268
  export class Ledger {
394
269
  path;
395
270
  entries = {};
396
271
  wakes = {};
397
272
  /**
398
- * A missing file starts an empty ledger. A file that cannot be read or parsed is set aside as `<path>.corrupt` and `onCorrupt`
399
- * 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.
400
276
  */
401
277
  constructor(path, onCorrupt = (m) => console.warn(m)) {
402
278
  this.path = path;
279
+ if (path === undefined)
280
+ return;
403
281
  let text;
404
282
  try {
405
283
  text = readFileSync(path, 'utf8');
@@ -446,6 +324,8 @@ export class Ledger {
446
324
  }
447
325
  /** Write temp file, then rename, so a crash never leaves half a ledger. */
448
326
  save() {
327
+ if (this.path === undefined)
328
+ return;
449
329
  mkdirSync(dirname(this.path) || '.', { recursive: true });
450
330
  const tmp = `${this.path}.${process.pid}.tmp`;
451
331
  writeFileSync(tmp, JSON.stringify(Object.keys(this.wakes).length ? { entries: this.entries, wakes: this.wakes } : { entries: this.entries }, null, 2));
@@ -475,6 +355,8 @@ const safeKey = (s) => s.replace(/[^A-Za-z0-9\-_.:]/g, '-').slice(0, 128);
475
355
  const carriesOn = (s) => s === 'turn_cap' || s === 'time_cap';
476
356
  export async function run(opts) {
477
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');
478
360
  const log = opts.log ?? ((line) => console.log(line));
479
361
  const maxSteps = opts.maxSteps ?? 8;
480
362
  const model = opts.model ?? freeModel;
@@ -489,6 +371,7 @@ export async function run(opts) {
489
371
  const wakes = [];
490
372
  let message = opts.task;
491
373
  let reply = '';
374
+ let wakeAt = null;
492
375
  let spentUsd = 0;
493
376
  let status = 'max_steps';
494
377
  let steps = 0;
@@ -497,7 +380,9 @@ export async function run(opts) {
497
380
  let pending = [];
498
381
  for (let step = 0; step < maxSteps; step++) {
499
382
  const key = safeKey(`${opts.runId}.${step}`);
500
- 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;
501
386
  if (structured && step > 0 && pending.length)
502
387
  body.results = pending;
503
388
  opts.onWakeStart?.({ step });
@@ -513,11 +398,13 @@ export async function run(opts) {
513
398
  ledger.setWake(key, answer);
514
399
  }
515
400
  steps = step + 1;
516
- wakes.push(res.wake_id);
401
+ if (res.wake_id)
402
+ wakes.push(res.wake_id); // a `fireDue` wake with nothing due has none
517
403
  reply = res.reply ?? '';
518
404
  spentUsd += res.spent_usd ?? 0;
519
405
  status = res.status;
520
- 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)' : ''}`);
521
408
  opts.onWake?.({ step, wakeId: res.wake_id, status: res.status, replayed: !!res.idempotentReplay });
522
409
  const actions = res.actions ?? [];
523
410
  const results = [];
@@ -560,7 +447,7 @@ export async function run(opts) {
560
447
  message = 'Results of the tools you asked for:\n' + JSON.stringify(results);
561
448
  pending = results.map(({ seq, result }) => ({ seq, result }));
562
449
  }
563
- return { reply, wakes, steps, status, spentUsd };
450
+ return { reply, wakes, steps, status, spentUsd, wakeAt };
564
451
  }
565
452
  /** @deprecated Renamed to `run` in 0.2.0. Same function; this name stays so existing code keeps working. */
566
453
  export const runDurable = run;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@argentic-ai/client",
3
- "version": "0.2.1",
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",