@jush-agent/sdk 0.0.1 → 0.2.6250

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
@@ -1,3 +1,505 @@
1
1
  # @jush-agent/sdk
2
2
 
3
- A placeholder, published once so that the package exists and its trusted publisher can be configured. Install a later version.
3
+ Jush's agents in your program. The SDK starts `jush-core`, the process your
4
+ program's cores run in, and gives your program the cores, their
5
+ conversations, providers and devices, and plugins of your own whose commands
6
+ the agents run as `jush <group> <command>`.
7
+
8
+ A core is one Jush: its conversations, provider entries, devices and
9
+ settings, kept in a directory you choose. A team bot, for example, opens one
10
+ core for each team it serves.
11
+
12
+ ## Install
13
+
14
+ ```sh
15
+ npm install @jush-agent/sdk zod
16
+ ```
17
+
18
+ The package installs the executables of your machine's platform, macOS,
19
+ Linux or Windows on x86-64 or ARM64, from its optional platform packages,
20
+ such as `@jush-agent/sdk-linux-x64`. It runs on Node.js 22 or later, Bun and
21
+ Deno. `zod` defines your plugins' command arguments.
22
+
23
+ ## Quick start
24
+
25
+ The following program opens a core, gives it an Anthropic API key and a
26
+ device on your machine, and runs one turn:
27
+
28
+ ```ts
29
+ import { Jush } from '@jush-agent/sdk'
30
+
31
+ const jush = await Jush.start()
32
+ const core = await jush.open('./data/team-a')
33
+
34
+ const provider = await core.providers.create({
35
+ source: 'vendor',
36
+ vendorId: 'anthropic',
37
+ apiKey: process.env.ANTHROPIC_API_KEY,
38
+ })
39
+ const device = await core.devices.create()
40
+ await device.spawn()
41
+
42
+ const conversation = await core.conversations.create({
43
+ title: 'Release notes',
44
+ model: { providerId: provider.id, modelId: 'claude-sonnet-4-5' },
45
+ target: { kind: 'device', deviceId: device.id, path: '/srv/work' },
46
+ })
47
+ const turn = await conversation.run('Draft the notes for this week from the git log')
48
+ console.log(turn.outcome, turn.text)
49
+
50
+ await jush.close()
51
+ ```
52
+
53
+ `turn.outcome` is `finished`, `failed` or `stopped`; `turn.text` is the text
54
+ the agent wrote after your message, and `turn.blocks` everything it did.
55
+ Blocks read back as a page, as after a dropped connection, come in the light
56
+ form the app's list holds: a tool call without its output's text, and with
57
+ only the description of a long input, and thinking without its text. The
58
+ answer's text is whole.
59
+
60
+ ## Cores
61
+
62
+ `Jush.start()` starts one `jush-core` process for your program, and
63
+ `jush.open(dir)` opens a core in it, creating the core when `dir` is absent
64
+ or empty. A process holds any number of cores. Open the same directory again
65
+ later, and the core has everything it had: conversations, provider entries,
66
+ devices and settings.
67
+
68
+ A core is open in one process at a time; opening it in a second fails with a
69
+ `JushError` whose `code` is `core_open`.
70
+
71
+ `core.close()` closes one core, and `jush.close()` closes every core and ends
72
+ the process. A turn still running when its core closes stops there, and Jush
73
+ takes it up again when the core opens again.
74
+
75
+ `jush-core` and the runners the SDK starts write their logs to your
76
+ program's standard error.
77
+
78
+ ## A process of its own
79
+
80
+ `Jush.start()` ties the process to your program: when your program stops,
81
+ for example to deploy a new version, every core closes, and a running turn
82
+ stops until the core opens again. To keep the cores running while your
83
+ program restarts, or to share them between several services, run
84
+ `jush-core` on its own, as a server:
85
+
86
+ ```sh
87
+ export JUSH_CORE_TOKEN=7f3c9e2a51d84b06
88
+ export JUSH_RELEASE=node_modules/@jush-agent/sdk/release:node_modules/@jush-agent/sdk-linux-x64/release
89
+ node_modules/@jush-agent/sdk-linux-x64/bin/jush-core serve --listen 127.0.0.1:4100
90
+ ```
91
+
92
+ `jush-core` is in your platform's package. `JUSH_RELEASE` lists the
93
+ `release` directories of the SDK and of each platform package, as `PATH`
94
+ does, so the cores' devices run Jush's commands. Each of your services
95
+ connects with the same token:
96
+
97
+ ```ts
98
+ const jush = await Jush.connect({ url: 'http://127.0.0.1:4100', token, plugins: [chat] })
99
+ const core = await jush.open('/srv/bot/data/team-a')
100
+ ```
101
+
102
+ - Opening a directory the process holds already answers the same core, with
103
+ its conversations and turns as they went on while your program was away.
104
+ - `jush.close()` disconnects and closes nothing; `core.close()` closes the
105
+ core for every service.
106
+ - Each connection declares its plugins again, and the last declaration of a
107
+ plugin's id stands: a new version of your program changes the commands
108
+ of every conversation at once.
109
+ - `SIGTERM` or Ctrl-C stops the process, which closes every core. Your
110
+ program connects again by itself once the process is back, declares its
111
+ plugins and opens its cores again, and goes on.
112
+
113
+ Set `JUSH_PUBLIC_URL` to where the process is reached from outside, such as
114
+ `https://bot.example.com/jush`, for schedules' URLs and plugins' sign-ins,
115
+ which the process then answers itself.
116
+
117
+ A runner reaches a process of its own as it reaches a Jush server: start it
118
+ anywhere with `jush-runner run --backend http://bot.example.com:4100`. It
119
+ prints a pairing code and waits; pair it to a core with
120
+ `core.devices.claim(code)`. The runner keeps its token, and connects again
121
+ by itself after it or the process restarts.
122
+
123
+ ## Providers
124
+
125
+ A provider entry is what a core's agents call models with. Create one with
126
+ an API key of a vendor, such as `anthropic`, `openai` or `google`:
127
+
128
+ ```ts
129
+ const openai = await core.providers.create({ source: 'vendor', vendorId: 'openai', apiKey: process.env.OPENAI_API_KEY })
130
+ ```
131
+
132
+ Or with an endpoint that speaks a vendor's protocol, such as a gateway or a
133
+ model server of your own; `providerType` is the protocol, `anthropic` when
134
+ absent:
135
+
136
+ ```ts
137
+ const gateway = await core.providers.create({
138
+ source: 'compatible',
139
+ providerType: 'openai',
140
+ label: 'Team Gateway',
141
+ baseUrl: 'https://gateway.example.com/v1',
142
+ apiKey: process.env.GATEWAY_KEY,
143
+ })
144
+ ```
145
+
146
+ The models each entry offers are in the core's state, as
147
+ `core.state.models.providers`, each with its `providerId` and `models`.
148
+ `core.providers` also lists, updates and removes entries.
149
+
150
+ ### Subscriptions
151
+
152
+ A subscription entry signs in with an account instead of a key: `codex` for
153
+ ChatGPT, `claude-code` for Claude, or `grok-build` for Grok. The user
154
+ confirms the sign-in in a browser. Its stages are in `core.state.logins`:
155
+
156
+ ```ts
157
+ const signIn = await core.providers.signIn({ providerType: 'codex' })
158
+ const stop = core.on('state', (state) => {
159
+ const login = state.logins.find((each) => each.id === signIn.id)?.login
160
+ if (login?.status === 'pending' && login.verificationUrl !== null) {
161
+ showToUser(`Open ${login.verificationUrl} and enter ${login.userCode}`)
162
+ } else if (login !== undefined && login.status !== 'pending') {
163
+ stop()
164
+ }
165
+ })
166
+ ```
167
+
168
+ When a login's `needsCode` is true, the user signs in at the address
169
+ instead, and you hand the code the page shows to `signIn.submitCode(code)`.
170
+ `signIn.cancel()` stops it.
171
+
172
+ An entry can hold several accounts: `core.providers.accounts(id)` signs in
173
+ another one, and lists, activates, orders and removes them. Once an entry
174
+ holds two or more, its `rotation` says which account each agent uses:
175
+ `manual` the active one, `in_order` the first in their order that is not used
176
+ up, and `smart` first the one whose quota resets soonest, since what is left
177
+ at a reset is lost:
178
+
179
+ ```ts
180
+ await core.providers.update(entry.id, { rotation: 'smart' })
181
+ ```
182
+
183
+ ## Devices
184
+
185
+ A device is a machine the agents run commands on, served by a
186
+ `jush-runner`. `device.spawn()` starts the package's own runner on your
187
+ program's machine. Give it a command to start a runner elsewhere, such as in
188
+ a container; each device's runner keeps its state in a directory of its own,
189
+ `--home`:
190
+
191
+ ```ts
192
+ const box = await core.devices.create()
193
+ await box.spawn(['docker', 'exec', '-i', 'box-7', 'jush-runner', 'run', '--stdio', '--home', `/var/lib/jush/${box.id}`])
194
+ ```
195
+
196
+ `spawn()` resolves once the core counts the device online, so a conversation
197
+ can be created on it, and answers the runner's child process. It fails when
198
+ the command exits before, or when no runner comes on its channel within 30
199
+ seconds, and then ends the command. The core counts a device online for a
200
+ short while after its runner drops, and after the core opens, if its runner
201
+ was connected when the core closed, waiting for the runner to come back;
202
+ `spawn()` of such a device resolves at once, so watch the child process for a
203
+ runner that exits.
204
+
205
+ A runner that reaches the core some other way, such as over SSH or a socket,
206
+ connects with `device.connect({ readable, writable })`, the standard output
207
+ and input of a runner already started. It resolves as `spawn()` does, with
208
+ `ended`, which resolves once either end closed.
209
+
210
+ A core keeps its devices, but not their runners: when your program starts
211
+ again, start a runner for each device the core lists:
212
+
213
+ ```ts
214
+ for (const listed of core.state.devices) {
215
+ await core.devices.of(listed).spawn()
216
+ }
217
+ ```
218
+
219
+ `device.revoke()` revokes a device, as the app's Revoke does: its token opens
220
+ nothing from then on, the commands running on it are lost, and the commands of
221
+ a conversation whose target it is fail until `update({ target })` names
222
+ another. A runner connected to it exits and removes its `--home`, or only its
223
+ own files there when `--home` is the home directory, holds it, or is a
224
+ filesystem's root, such as a volume's mount point.
225
+
226
+ ### Sandboxes that expire
227
+
228
+ A sandbox that lives for a while and then goes, such as a container your
229
+ platform keeps for 24 hours, is one device for each sandbox. Make a device
230
+ when the sandbox starts, and revoke it when the sandbox ends; a device is
231
+ never reused for the next sandbox, since its runner's state went with the
232
+ sandbox. One sandbox can serve one conversation, or every conversation of its
233
+ day.
234
+
235
+ When a sandbox ends before a conversation does, start a new sandbox, move the
236
+ conversation onto its device, and revoke the old device:
237
+
238
+ ```ts
239
+ const next = await core.devices.create()
240
+ await next.spawn(['sandbox', 'exec', 'sbx-0412', 'jush-runner', 'run', '--stdio', '--home', `/var/lib/jush/${next.id}`])
241
+ for (const conversation of onOldSandbox) {
242
+ await conversation.update({ target: { kind: 'device', deviceId: next.id, path: '/workspace' } })
243
+ }
244
+ await old.revoke()
245
+ ```
246
+
247
+ The conversation keeps its transcript, and its agent is told on its next turn
248
+ that no file moved: what the old sandbox held, its files and the browser
249
+ profiles on it among them, went with it. What has to outlive a sandbox lives
250
+ on a volume your platform keeps across sandboxes.
251
+
252
+ ## Conversations
253
+
254
+ `core.conversations.create()` takes the conversation's `title`, `model` and
255
+ `target`, the device and directory its commands run in. A conversation
256
+ without a target runs on the Cloud, which only Jush's server runs, so in a
257
+ program it is refused with `cloud_unavailable`, as one on a device that does
258
+ not exist is with `device_not_found`. `core.conversations.open(id)` takes a
259
+ conversation created earlier, and `conversation.update(patch)` changes the
260
+ same fields later.
261
+
262
+ Each conversation's browser has a profile of its own, so a sign-in made in
263
+ one conversation is not seen in another. Conversations that name the same
264
+ `browserProfile` on one device share its browser instead: a site one of them
265
+ signs in to is signed in for the others, and each keeps its own tabs. The
266
+ profile is the directory `~/.jush/browser-profiles/<name>` on the device,
267
+ made at its first use; list, copy or remove it as any directory.
268
+
269
+ ```ts
270
+ const triage = await core.conversations.create({ title: 'Triage', model, target, browserProfile: 'support' })
271
+ const refunds = await core.conversations.create({ title: 'Refunds', model, target, browserProfile: 'support' })
272
+ // Back to a profile of its own, from its next browser command on:
273
+ await refunds.update({ browserProfile: null })
274
+ ```
275
+
276
+ An agent introduces itself as Jush unless its conversation names an
277
+ `identity`, the sentences that open its system prompt instead. Jush's rules
278
+ for running commands and replying still follow them. `plugins` lists which
279
+ of your program's plugins the conversation's agents have, by id; without it
280
+ they have all of them. Jush's own plugins follow the user's switches either
281
+ way. A change made with `update` reaches each agent from its next request.
282
+
283
+ ```ts
284
+ const desk = await core.conversations.create({
285
+ model,
286
+ target,
287
+ identity: "You are the help desk's assistant. You answer the team's questions about their accounts.",
288
+ plugins: ['tickets'],
289
+ })
290
+ // Try the next version of the commands in this conversation alone:
291
+ await desk.update({ plugins: ['tickets-next'] })
292
+ ```
293
+
294
+ `conversation.run(input)` sends a message and resolves once the turn it
295
+ starts ended, with that turn's blocks and outcome, also when your program's
296
+ connection to the process dropped while the turn ended. It fails when the
297
+ message leaves the queue without running, as an abort that clears the queue
298
+ or gives the message back makes it, or when the conversation closes first.
299
+ The other actions are the ones the app has:
300
+
301
+ | Method | What it does |
302
+ | --- | --- |
303
+ | `send(input, messageId?)` | Sends a message, queued behind a running turn; resolves once the conversation holds it |
304
+ | `steer(input, steerId?)` | Hands a message to the running turn; resolves once the turn took it |
305
+ | `abort()` | Stops the running turn |
306
+ | `retry()` | Runs the latest turn again from your message |
307
+ | `resume()` | Finishes a turn that did not finish |
308
+ | `compact()` | Summarizes the conversation so far, to free its context |
309
+
310
+ `send` and `steer` take an id after the input. Give one when you may send
311
+ the same message again, such as after a lost answer: while the conversation
312
+ holds input under an id, queued, waiting or in its history, anything sent
313
+ under it again, as a message or a steer, is acknowledged and not taken a
314
+ second time. Input that leaves it, such as a message taken out of the queue,
315
+ frees its id. Make each id your own, such as a ticket's number with a
316
+ prefix: a steer under the id of one of the conversation's blocks is refused.
317
+
318
+ ```ts
319
+ await conversation.steer('Use the staging database instead.', 'steer-ticket-42')
320
+ ```
321
+
322
+ A message is text, or content blocks, such as a file on one of the core's
323
+ devices:
324
+
325
+ ```ts
326
+ await conversation.run([
327
+ { type: 'text', text: 'Summarize this report' },
328
+ { type: 'remote_file', deviceId: device.id, path: '/srv/work/report.md' },
329
+ ])
330
+ ```
331
+
332
+ `conversation.blocks` is what the conversation holds, oldest first.
333
+ `conversation.events()` yields everything that happens in it, as the app
334
+ shows it live; a `transcript_patch` event says the blocks changed, such as
335
+ while the agent writes:
336
+
337
+ ```ts
338
+ for await (const event of conversation.events()) {
339
+ if (event.type === 'transcript_patch') {
340
+ render(conversation.blocks)
341
+ }
342
+ }
343
+ ```
344
+
345
+ The loop ends when you leave it or the conversation closes.
346
+ `conversation.close()` stops following the conversation; its agents go on in
347
+ the core, and the next action follows it again.
348
+
349
+ `conversation.agents` lists the conversation's agents: the root, whose id is
350
+ the conversation's, and each subagent, with its role, phase and queue. The
351
+ `agents` and `agent` events say they changed.
352
+
353
+ `conversation.sendToAgent(node, text)` sends a message to one subagent, named
354
+ by its id in `conversation.agents`. A subagent at work takes it as a steer, an
355
+ idle one starts a turn with it, and one that ended is resumed with it. Give
356
+ the message an id when you may send it again, such as after a lost answer:
357
+ the subagent takes a message once, however often it arrives.
358
+
359
+ ```ts
360
+ const tester = conversation.agents.find((agent) => agent.role.kind === 'subagent' && agent.role.profile === 'tester')
361
+ if (tester) {
362
+ await conversation.sendToAgent(tester.id, 'The build finished.', 'reminder-7')
363
+ }
364
+ ```
365
+
366
+ ## Permission requests
367
+
368
+ A command that acts on Jush itself, such as `jush credentials`, which hands
369
+ the agent a stored secret, or one of your plugin's commands that declares a
370
+ permission, waits for the user's permission in the conversation. `events()` yields a `permission`
371
+ event for each request, and `conversation.permissions` lists those waiting:
372
+
373
+ ```ts
374
+ for await (const event of conversation.events()) {
375
+ if (event.type === 'permission') {
376
+ await event.permission.allow()
377
+ }
378
+ }
379
+ ```
380
+
381
+ `deny()` refuses it. A request for a credential takes the values it asks
382
+ for: `allow({ values: { token: 'xoxb-example' } })`.
383
+
384
+ ## Plugins
385
+
386
+ A plugin gives the agents commands that your program runs. The following
387
+ plugin adds `jush chat send`, which posts to the chat a conversation answers
388
+ in:
389
+
390
+ ```ts
391
+ import { Jush, definePlugin, leaf } from '@jush-agent/sdk'
392
+ import { z } from 'zod'
393
+
394
+ const chat = definePlugin({
395
+ id: 'chat',
396
+ name: 'Chat Commands',
397
+ description: 'Gives the agent `jush chat send`, which posts to the chat.',
398
+ commands: {
399
+ chat: {
400
+ summary: 'The chat this conversation answers in',
401
+ index: 'Posts to the chat this conversation answers in.',
402
+ commands: {
403
+ send: leaf({
404
+ summary: 'Posts a message to the chat',
405
+ input: z.object({ text: z.string().describe('The message, in Markdown') }),
406
+ positionals: ['text'],
407
+ output: 'the id of the message posted',
408
+ async run({ text }, call) {
409
+ const id = await postToChat(call.invocation.context.conversation, text)
410
+ await call.stdout(`${id}\n`)
411
+ },
412
+ }),
413
+ },
414
+ },
415
+ },
416
+ })
417
+
418
+ const jush = await Jush.start({ plugins: [chat] })
419
+ ```
420
+
421
+ Every core of the process gives its agents the plugin's commands. The agent
422
+ learns them as it learns Jush's own: `index` is the group's entry in the
423
+ index of capabilities the agent reads, which says what the group is for, and
424
+ each command's `summary`, input and `output` are its `--help`.
425
+
426
+ - Each field of `input` is an option of the same name, such as `--text`, and
427
+ its `describe` text is the option's help; `positionals` lists the fields
428
+ given by their place, in order. Arguments that do not fit the schema fail
429
+ before `run` is called.
430
+ - `run(input, call)` writes the command's output with `call.stdout()` and
431
+ `call.stderr()`, and reads its standard input with `call.readStdin()` when
432
+ the leaf names a `stdin` field. What it returns is the exit status, 0 when
433
+ it returns nothing; a failure writes why to standard error and returns a
434
+ status other than 0, as a shell command does.
435
+ - `call.signal` aborts when the agent stops the command.
436
+ - `jsonOutput` declares what the command's `--json` writes.
437
+ - A group's `permissions` declares categories, and a leaf's `permission`
438
+ names the one it needs: the conversation then asks before the command
439
+ runs.
440
+
441
+ A plugin can also add a context block before each request (`context`),
442
+ search a conversation's project (`projectSearch`), and follow conversations
443
+ being deleted or forked.
444
+
445
+ A command your program runs outlives your program's restart. If your
446
+ program stops while `run` is under way, the command waits, and once your
447
+ program serves the plugin again, `run` is called again for the same call,
448
+ with `call.resent` true. `call.request` is the call's number, which no other
449
+ call ever takes: use it to do the work once, for example when the command
450
+ posts a message. What the command already wrote stays in its output, and
451
+ what `run` writes now follows it; input the earlier call read is not read
452
+ again. While no program serves the plugin, a new command waits 10 seconds
453
+ for one, and then fails, telling the agent that the plugin's program is
454
+ unreachable. A `context` call does not wait: when your program stops
455
+ during one, the agent goes on without its block.
456
+
457
+ ## Product state and notifications
458
+
459
+ `core.state` is the core's product state: its workspaces, projects, provider
460
+ entries and their models, devices, conversations and sign-ins, as the app
461
+ shows them. `core.on('state', listener)` calls the listener at each change,
462
+ and answers a function that stops it.
463
+
464
+ `core.on('notify', listener)` receives what the app would notify the user
465
+ of: a turn that finished or failed, a permission request, or a notification
466
+ the agent sent with `jush notify send`. A program has one such listener for
467
+ each core, and a new one replaces it; when several services listen to one
468
+ core, the one that listened last receives them. Answer how you delivered
469
+ it; the agent's `jush notify send` reports it:
470
+
471
+ ```ts
472
+ core.on('notify', async (message) => {
473
+ if (message.kind === 'agent') {
474
+ await postToChat(message.conversationId, `${message.title}\n${message.body}`)
475
+ return { type: 'sending', to: 1 }
476
+ }
477
+ return { type: 'nowhere' }
478
+ })
479
+ ```
480
+
481
+ `{ type: 'shown' }` says every place that would show it shows its
482
+ conversation already.
483
+
484
+ ## Showing conversations on your pages
485
+
486
+ [`@jush-agent/web-components`](../web-components/README.md) shows a
487
+ conversation on your own pages with the app's own views: its transcript,
488
+ its composer, and its work in windows with a taskbar.
489
+ Your server forwards the pages' requests with `core.fetch(request, base)`
490
+ and their connection with `core.accept(socket, url)`, which takes a
491
+ WebSocket of the standard interface, as Deno's `upgradeWebSocket` and the
492
+ `ws` package give.
493
+
494
+ Jush can reach your program from outside when you tell it where your server
495
+ forwards its routes: `Jush.start({ publicUrl: 'https://bot.example.com/jush' })`.
496
+ A schedule's URL is then `/hooks/{id}` below it, which your server answers
497
+ with `jush.fetch(request, '/jush')`, and a plugin's sign-in returns there.
498
+
499
+ ## Errors
500
+
501
+ A request the core refuses fails with a `JushError`: `status` is the HTTP
502
+ status, `code` the refusal's code, such as `core_open`, and `message` says
503
+ why in words. `requestId` names the request in the core's log.
504
+
505
+ Part of [Jush](../../README.md). The package is under the Apache License 2.0.