@anycon/sdk 0.1.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/LICENSE +176 -0
- package/README.md +240 -0
- package/README.zh-CN.md +188 -0
- package/dist/async-queue.d.ts +20 -0
- package/dist/async-queue.d.ts.map +1 -0
- package/dist/async-queue.js +95 -0
- package/dist/async-queue.js.map +1 -0
- package/dist/attachments.d.ts +53 -0
- package/dist/attachments.d.ts.map +1 -0
- package/dist/attachments.js +228 -0
- package/dist/attachments.js.map +1 -0
- package/dist/client.d.ts +90 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +280 -0
- package/dist/client.js.map +1 -0
- package/dist/connect.d.ts +16 -0
- package/dist/connect.d.ts.map +1 -0
- package/dist/connect.js +24 -0
- package/dist/connect.js.map +1 -0
- package/dist/default-storage.d.ts +4 -0
- package/dist/default-storage.d.ts.map +1 -0
- package/dist/default-storage.js +15 -0
- package/dist/default-storage.js.map +1 -0
- package/dist/emitter.d.ts +10 -0
- package/dist/emitter.d.ts.map +1 -0
- package/dist/emitter.js +38 -0
- package/dist/emitter.js.map +1 -0
- package/dist/errors.d.ts +112 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +155 -0
- package/dist/errors.js.map +1 -0
- package/dist/hub.d.ts +85 -0
- package/dist/hub.d.ts.map +1 -0
- package/dist/hub.js +362 -0
- package/dist/hub.js.map +1 -0
- package/dist/index.d.ts +34 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +32 -0
- package/dist/index.js.map +1 -0
- package/dist/link.d.ts +87 -0
- package/dist/link.d.ts.map +1 -0
- package/dist/link.js +628 -0
- package/dist/link.js.map +1 -0
- package/dist/node.d.ts +213 -0
- package/dist/node.d.ts.map +1 -0
- package/dist/node.js +474 -0
- package/dist/node.js.map +1 -0
- package/dist/pair.d.ts +75 -0
- package/dist/pair.d.ts.map +1 -0
- package/dist/pair.js +390 -0
- package/dist/pair.js.map +1 -0
- package/dist/permissions.d.ts +65 -0
- package/dist/permissions.d.ts.map +1 -0
- package/dist/permissions.js +74 -0
- package/dist/permissions.js.map +1 -0
- package/dist/runtime.d.ts +5 -0
- package/dist/runtime.d.ts.map +1 -0
- package/dist/runtime.js +15 -0
- package/dist/runtime.js.map +1 -0
- package/dist/session.d.ts +208 -0
- package/dist/session.d.ts.map +1 -0
- package/dist/session.js +504 -0
- package/dist/session.js.map +1 -0
- package/dist/storage-file.d.ts +21 -0
- package/dist/storage-file.d.ts.map +1 -0
- package/dist/storage-file.js +62 -0
- package/dist/storage-file.js.map +1 -0
- package/dist/storage-idb.d.ts +19 -0
- package/dist/storage-idb.d.ts.map +1 -0
- package/dist/storage-idb.js +64 -0
- package/dist/storage-idb.js.map +1 -0
- package/dist/storage.d.ts +78 -0
- package/dist/storage.d.ts.map +1 -0
- package/dist/storage.js +163 -0
- package/dist/storage.js.map +1 -0
- package/dist/version.d.ts +3 -0
- package/dist/version.d.ts.map +1 -0
- package/dist/version.js +3 -0
- package/dist/version.js.map +1 -0
- package/dist/ws.d.ts +41 -0
- package/dist/ws.d.ts.map +1 -0
- package/dist/ws.js +66 -0
- package/dist/ws.js.map +1 -0
- package/package.json +65 -0
- package/src/async-queue.ts +100 -0
- package/src/attachments.ts +301 -0
- package/src/client.ts +351 -0
- package/src/connect.ts +29 -0
- package/src/default-storage.ts +14 -0
- package/src/emitter.ts +40 -0
- package/src/errors.ts +218 -0
- package/src/hub.ts +456 -0
- package/src/index.ts +143 -0
- package/src/link.ts +699 -0
- package/src/node.ts +652 -0
- package/src/pair.ts +527 -0
- package/src/permissions.ts +134 -0
- package/src/runtime.ts +14 -0
- package/src/session.ts +697 -0
- package/src/storage-file.ts +78 -0
- package/src/storage-idb.ts +74 -0
- package/src/storage.ts +231 -0
- package/src/version.ts +2 -0
- package/src/ws.ts +94 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
package/README.md
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
# @anycon/sdk
|
|
2
|
+
|
|
3
|
+
[简体中文](https://github.com/anycon-ai/anycon/blob/main/packages/sdk/README.zh-CN.md)
|
|
4
|
+
|
|
5
|
+
The TypeScript SDK for [Anycon](https://github.com/anycon-ai/anycon), **client side**: pair once, then connect to a node (daemon), manage projects and sessions, stream events, and handle permission requests.
|
|
6
|
+
The same code runs on Node ≥ 20 and in browsers (Node uses `ws`, browsers use the native WebSocket). ESM only. The full spec is [docs/spec/sdk.md](https://github.com/anycon-ai/anycon/blob/main/docs/spec/sdk.md) (the design docs are in Chinese for now).
|
|
7
|
+
|
|
8
|
+
```bash
|
|
9
|
+
npm install @anycon/sdk
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
```ts
|
|
13
|
+
import { pair, connect, policies } from '@anycon/sdk'
|
|
14
|
+
|
|
15
|
+
const hub = 'https://hub.example.com'
|
|
16
|
+
|
|
17
|
+
// Once: run `anycon pair` on the node to get a pairing code (16 characters by default; `--short`
|
|
18
|
+
// gives 8, which is only suitable for a self-hosted hub). You can also pass the pairing link.
|
|
19
|
+
await pair(hub, { code: '7K3P-Q2MX-W4NH-8CRD', name: 'ci-runner' })
|
|
20
|
+
// await pair(hub, { code: 'https://hub.example.com/pair#code=7K3P-Q2MX-W4NH-8CRD', name: 'ci-runner' })
|
|
21
|
+
|
|
22
|
+
const node = await connect(hub, { node: 'mac-mini' }) // `node` can be left out when only one node is paired
|
|
23
|
+
const agents = await node.agents.list() // the valid model / thinking / permission-mode values come from here
|
|
24
|
+
const session = await node.sessions.create({
|
|
25
|
+
project: 'app',
|
|
26
|
+
agent: 'claude-code',
|
|
27
|
+
settings: { model: 'opus', thinking: 'high', mode: 'acceptEdits' },
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
for await (const ev of session.send('run the tests and fix whatever fails')) {
|
|
31
|
+
if (ev.type === 'text_delta') process.stdout.write(ev.text)
|
|
32
|
+
if (ev.type === 'permission') await ev.allow() // or ev.deny("don't delete files") / ev.allowSession()
|
|
33
|
+
if (ev.type === 'turn_done') console.log(ev.usage)
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// Rather not answer permission requests by hand? Pass a policy (it applies to sessions the SDK itself is using)
|
|
37
|
+
const node2 = await connect(hub, { onPermission: policies.allowReadsDenyRest })
|
|
38
|
+
const result = await session.run('translate the README into English') // { text, turnId, reason, usage, events }
|
|
39
|
+
|
|
40
|
+
await session.setSettings({ model: 'sonnet' }) // applies from the next turn; fields left out stay as they are
|
|
41
|
+
await session.setSettings({}, { clear: ['thinking', 'max_turns'] }) // resetting a field to unset needs clear
|
|
42
|
+
await session.cancel()
|
|
43
|
+
const { events } = await session.history({ afterSeq: 0 })
|
|
44
|
+
await node.close()
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## Per-session worktrees and git (ADR-34)
|
|
48
|
+
|
|
49
|
+
A session can work in a git worktree (and branch) that the daemon creates for it, leaving the project's main directory alone. `sessions.create` without `workspace` works in the project directory itself. The SDK **does not read the node's `worktree.default` for you**. If you want a worktree, pass one explicitly:
|
|
50
|
+
|
|
51
|
+
```ts
|
|
52
|
+
const branches = await node.projects.branches('app') // { current, default_base, local, remote, truncated? }
|
|
53
|
+
const s = await node.sessions.create({
|
|
54
|
+
project: 'app',
|
|
55
|
+
agent: 'claude-code',
|
|
56
|
+
// also accepts branch: 'feature/login'; if left out, the daemon picks a name
|
|
57
|
+
workspace: { mode: 'worktree', base: branches.default_base },
|
|
58
|
+
// optional: send the first message right after creating (the SDK generates a uuid v4 message_id)
|
|
59
|
+
prompt: 'fix the login redirect',
|
|
60
|
+
})
|
|
61
|
+
// { id, branch, base, base_sha, path, state }: state starts as 'creating', becomes 'active'
|
|
62
|
+
// once the worktree is ready, and follows session.changed
|
|
63
|
+
s.worktree
|
|
64
|
+
// watch the first turn from the start (including the { type: 'git', action: 'worktree_created', … } event)
|
|
65
|
+
for await (const ev of s.events({ fromSeq: 0 })) {
|
|
66
|
+
if (ev.type === 'git') console.log(ev.action, ev.branch)
|
|
67
|
+
if (ev.type === 'turn_done') break
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// branch / HEAD / ahead / behind / uncommitted / conflicts / merging / upstream; with includePr, also pr or pr_error
|
|
71
|
+
const st = await s.gitStatus({ includePr: true })
|
|
72
|
+
// { from_sha, files: [{ path, status, additions, deletions, untracked? }], truncated? }
|
|
73
|
+
const list = await s.diff()
|
|
74
|
+
// against: 'base' (the default, worktree sessions only) | 'uncommitted'; the patch is included only with path
|
|
75
|
+
const one = await s.diff({ against: 'uncommitted', path: 'src/a.ts' })
|
|
76
|
+
// { outcome: 'up_to_date' | 'merged' | 'conflicts' | 'aborted', commits, conflicts? }
|
|
77
|
+
const sync = await s.syncBase()
|
|
78
|
+
if (sync.outcome === 'conflicts') await s.syncBase({ abort: true })
|
|
79
|
+
|
|
80
|
+
// 'auto' (the default: remove if clean, keep if there are uncommitted changes) | 'keep' | 'remove' (discards uncommitted changes)
|
|
81
|
+
await s.archive({ worktree: 'auto' })
|
|
82
|
+
// deleteBranch: also runs git branch -D (unmerged commits are lost); only takes effect when the worktree is removed too
|
|
83
|
+
await s.delete({ worktree: 'remove', deleteBranch: true })
|
|
84
|
+
|
|
85
|
+
// WorktreeInfo[], including kept worktrees and those whose session was deleted
|
|
86
|
+
await node.worktrees.list({ project: 'app' })
|
|
87
|
+
// session not archived → busy; uncommitted changes without force → invalid (error.reason === 'uncommitted_changes')
|
|
88
|
+
await node.worktrees.remove(id, { force: true, deleteBranch: false })
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
- On an archived session, `send()` / `syncBase()` throw `RpcError` (`invalid`, `reason === 'archived'`). Call `unarchive()` first. While a session is running or waiting for approval, `archive()` throws `busy` (`cancel()` first, or answer the permission request).
|
|
92
|
+
- `archive()` / `delete()` without arguments send only `session_id`. Sessions without a worktree ignore these options.
|
|
93
|
+
- With `prompt`, `create()` doesn't collect the first turn's events for you. Call `s.events({ fromSeq: 0 })` right after creating the session (live events that arrive while history is being backfilled are held and appended afterwards, so seqs are strictly increasing with no duplicates). Permission policies also only answer once the session has an active `events()` / `send()`. You can pass your own idempotency key as `messageId`: if `create()` times out and you retry with the same key, the daemon returns the session it created the first time instead of opening a second one.
|
|
94
|
+
- When creation is refused, check `RpcError.code` / `.reason`: the project isn't `worktree_ready` → `invalid` / `not_worktree_ready`; the branch already exists → `exists`; `base` can't be resolved → `invalid` / `bad_base`. `syncBase` failures: a turn is running → `busy`; there are uncommitted changes → `invalid` / `uncommitted_changes`; the previous merge stopped in conflicts → `invalid` / `merge_in_progress`; fetch / merge failed → `internal` / `fetch_failed` / `git_failed`. `gitStatus` on a session that isn't in a git repository → `invalid` / `not_git`.
|
|
95
|
+
|
|
96
|
+
## Image attachments (ADR-35)
|
|
97
|
+
|
|
98
|
+
Images are first sent to the node over the blob channel (`blob.put_begin` → `blob.put_chunk` in 512 KiB chunks with at most 2 in flight → `blob.put_end`). The message carries only the reference the daemon returns (`AttachmentRef`):
|
|
99
|
+
|
|
100
|
+
```ts
|
|
101
|
+
import { readFile } from 'node:fs/promises'
|
|
102
|
+
import { AttachmentError } from '@anycon/sdk'
|
|
103
|
+
|
|
104
|
+
const ref = await node.uploadImage(await readFile('shot.png'), {
|
|
105
|
+
name: 'shot.png', // without mime, the type is detected from the file header (png / jpeg / gif / webp)
|
|
106
|
+
onProgress: (sent, total) => console.log(`${sent}/${total}`),
|
|
107
|
+
}) // → { blob_id, name, mime, bytes, width?, height? }
|
|
108
|
+
try {
|
|
109
|
+
// the text can be an empty string
|
|
110
|
+
for await (const ev of session.send("what's in this image?", { attachments: [ref] })) {
|
|
111
|
+
if (ev.type === 'user_message' && ev.attachments) {
|
|
112
|
+
// images from history (fetched page by page with blob.get)
|
|
113
|
+
const { bytes } = await node.downloadAttachment(ev.attachments[0]!)
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
} catch (err) {
|
|
117
|
+
if (err instanceof AttachmentError && err.reason === 'blob') {
|
|
118
|
+
/* the image was reclaimed: uploadImage again, then resend */
|
|
119
|
+
} else throw err
|
|
120
|
+
}
|
|
121
|
+
// a first message with only images works too
|
|
122
|
+
await node.sessions.create({ project: 'app', agent: 'claude-code', attachments: [ref2] })
|
|
123
|
+
// uploaded but not sent; if you don't discard it, the daemon reclaims it after 24 hours
|
|
124
|
+
await node.discardAttachment(ref3)
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
- **The SDK doesn't resize or re-encode images.** Keep each image to **≤ 2000 px on the long edge and about ≤ 1.5 MiB** yourself (for example, shrink it with `sharp` / ImageMagick first). The daemon's hard limits are 10 MiB per image (`sessions.max_attachment_bytes`) and at most 20 images per message, ≤ 20 MiB in total. Once an image is in a Claude Code session's history, it is resent with every later turn, so large images quickly push the session past Claude's request size limit. In the same way, `node.uploadImage()` uploads the bytes as they are: it **doesn't strip EXIF metadata (including GPS location) and doesn't apply the EXIF orientation**. Only the Web UI re-encodes images before upload. If privacy or orientation matters to you, handle it before `uploadImage` (for example, `sharp(bytes).rotate().toBuffer()` rotates according to EXIF, and its output has no metadata by default).
|
|
128
|
+
- Whether an agent accepts images: `(await node.agents.list())[i].capabilities?.attachments`. Whether the node supports the blob channel: `(await node.info()).capabilities.blobs`.
|
|
129
|
+
- Uploads on one `Node` are **queued and go one image at a time** (even a `Promise.all` batch has only one image uploading, with 2 chunks in flight), so requests like "allow" or "stop" don't wait behind a multi-megabyte image. A chunk that times out (90 seconds per chunk by default, `requestTimeoutMs`) or is lost to a disconnect is retried up to 2 times. Explicit refusals from the daemon are not retried. On failure or `signal` abort, the SDK makes a best-effort `blob.discard`.
|
|
130
|
+
- Refusals throw `AttachmentError` (a subclass of `RpcError`; `.code` is unchanged and `.reason` is narrowed):
|
|
131
|
+
|
|
132
|
+
| `reason` | `code` | When it happens / what to do |
|
|
133
|
+
|---|---|---|
|
|
134
|
+
| `too_large` | `invalid` | One image is over the node's limit, or one message totals more than 20 MiB: shrink it or split it across messages |
|
|
135
|
+
| `quota` | `busy` | Unreferenced images on the node total more than 1 GiB: send them first, or `discardAttachment()` |
|
|
136
|
+
| `disk_full` | `busy` | The node's data disk is nearly full |
|
|
137
|
+
| `blob` | `not_found` | The referenced image was reclaimed (unused for 24 hours) or discarded: upload it again |
|
|
138
|
+
| `blob_in_use` | `invalid` | The image is already used in another session (an image belongs to one session only): upload it again |
|
|
139
|
+
| `in_use` | `invalid` | `discardAttachment` on an image that a message already references (it is deleted along with the session) |
|
|
140
|
+
| `finalizing` / `incomplete` / `hash_mismatch` / `mime_mismatch` | `invalid` | The upload failed finalization or verification (the file header doesn't match `mime`, or the content was corrupted in transit) |
|
|
141
|
+
|
|
142
|
+
A `mime` that isn't on the allowlist, or an agent that doesn't accept images → `RpcError` (`unsupported`). More than 8 concurrent uploads from this device → `RpcError` (`busy`, no `reason`). No `mime` and an unrecognized file header → `AnyconError('unsupported_image')`, and nothing is sent.
|
|
143
|
+
|
|
144
|
+
## API overview
|
|
145
|
+
|
|
146
|
+
- `pair(hubUrl, { code, name, storage?, profile?, headers?, ackTimeoutMs? })`: the joiner. `code` can be a 16-character (default) or 8-character (`anycon pair --short`) pairing code (case and hyphens don't matter), or a pairing link `https://hub/pair#code=…` / just `#code=…` (the code is in the URL fragment, which is not sent to the hub). The flow:
|
|
147
|
+
1. Run `derivePairSecrets(code)` locally, **once** (Argon2id, 64 MiB × 3 passes; about 0.1–0.3 s in Node and 0.1–1 s with browser wasm, blocking the thread). `match_id` and the PSK come out of the same computation, and the PSK is zeroed after use. This adds that much time to every `pair()` in a pairing test, so don't set timeouts below 1 s.
|
|
148
|
+
2. Connect to the hub → `PairJoin { match_id }` (**the pairing code is never sent to the hub**) → Noise XXpsk3 (as initiator, with the PSK from step 1) → `PairConfirm` → `PairDone`.
|
|
149
|
+
3. **Wait for the daemon to send `pair.ack` over the newly established Noise transport** (up to `ackTimeoutMs`, 30 seconds by default). Check that `peer_id` is this device's permanent id, that `node_id == PairDone.peer`, and that `fingerprint` matches the fingerprint of the node public key from the handshake. **Only when every check passes is anything saved** (device identity + node public key). A timeout or mismatch → `PairingFailed`, and nothing is kept.
|
|
150
|
+
|
|
151
|
+
The node name comes from `pair.ack` (authenticated, with control characters removed). The payload of the third handshake message carries this device's `{ name, kind, platform, version }`, which the daemon uses to display the device. Nodes are keyed by `PairDone.peer` (the permanent device id). If a node with the same id but a different public key is already stored → `NodeKeyChanged` is thrown and nothing is overwritten (see `forgetNode`). If the hub has invalidated the local identity (`auth_fail invalid | revoked` / close 4004), `pair()` clears it and retries with a fresh identity. For `headers`, see [Account ownership](#account-ownership-the-first-pairing-needs-a-cookie) below.
|
|
152
|
+
- `forgetNode(hubUrl, nodeNameOrIdPrefix, { storage?, profile? })`: forgets a locally stored node. Use it after `NodeKeyChanged`, once you've confirmed the new public key can be trusted, then `pair()` again.
|
|
153
|
+
- `connect(hubUrl, { node?, storage?, onPermission?, headers?, … })` → `Node`. Every time the WebSocket connects, or `peer_online` arrives (or `auth_ok.peers_online` includes the node), it does a new IK handshake. After a disconnect it reconnects with exponential backoff (1 s → 30 s; a hub restart, close code `4002`, uses 1–3 s with jitter).
|
|
154
|
+
- Several nodes at once: `const client = await Client.open(hubUrl)` plus `client.node('name')` for each node (the hub allows only one connection per device, so the nodes share one `Client`).
|
|
155
|
+
- `Node`: `info()`, `agents.list({ refresh? })` (cached by etag), `projects.list/create/clone/link/unlink/browse/branches/rename/trash/trashList/restore/purge`, `sessions.list/get/create/search` (`create` accepts `workspace`, `prompt`, `attachments`, `messageId`), `worktrees.list/remove`, `uploadImage(bytes, { name, mime?, signal?, onProgress?, requestTimeoutMs? })` / `downloadAttachment(refOrBlobId)` / `discardAttachment(refOrBlobId)` (see [Image attachments](#image-attachments-adr-35) above), `permissions.list`, `online` / `waitOnline()`, the events `online` / `offline` / `permission` / `permission_error` / `error` (non-fatal channel problems) / `session_changed` …, `call(method, params)` (typed), and `rpc(method, params)` (raw).
|
|
156
|
+
- `projects.link(path, { name? })` registers an existing directory on the daemon's machine as a project, without moving or copying it. The path must be inside the daemon's `workspace.link_roots`. `unlink(name)` only removes the link and leaves the directory alone. `browse({ path?, showHidden? })` lists the subdirectories inside `link_roots` to choose from. Linked projects have `kind` `linked`, and `missing` is true when the directory is gone.
|
|
157
|
+
- `Session`: `send(text, { attachments?, messageId?, signal? })` → an iterable event stream (**sent immediately**; iteration runs until this turn's `turn_done` or an unrecoverable `error`; a `break` midway doesn't cancel the turn), `run(text)`, `respond(requestId, optionId | { answers }, message?)`, `setSettings(settings, { clear? })`, `cancel`, `history`, `events()`, `rename/archive/unarchive/delete/restart` (`archive({ worktree? })`, `delete({ worktree?, deleteBranch? })`), `worktree` (getter), `gitStatus({ includePr? })`, `diff({ against?, path? })`, `syncBase({ abort? })`. `watch` / `unwatch` and catching up on events after a disconnect (`session.history`) are handled internally.
|
|
158
|
+
- Permissions: the `permission` event has `allow()` / `allowSession()` / `deny(message?)` / `respond(optionId)` / `answer(answers)`. An `onPermission` policy returns `'allow' | 'allow_session' | 'deny' | { option, message? } | { deny } | { answers } | undefined`. **Policies answer only for sessions the SDK itself is using (with an active `send()` / `events()`)**, and never decide for sessions the user opened in the Web UI. The SDK denies requests that nobody answers after `permissionTimeoutMs` (10 minutes by default).
|
|
159
|
+
- **No silent escalation to `allow_always`.** `allow()` / `'allow'` only pick `allow_once`. If the request has no `allow_once` option, `allow()` fails with `no_matching_option`, and a policy's `'allow'` emits `node.on('permission_error', (error, request) => …)` and falls through to the timeout deny. To allow for the whole session, use `allowSession()` / `'allow_session'` explicitly (when there is no `allow_always` option it falls back to `allow_once`, which can only narrow the grant).
|
|
160
|
+
- `policies.allowAll` **doesn't approve `mode_change` or `plan`** (switching the permission mode or approving a plan is an escalation), and doesn't handle `question`. Those are left to the caller or the timeout deny. To approve them as well, opt in explicitly: `policies.allowAllWith({ modeChange: true, plan: true })`. A policy callback that throws also emits `permission_error` instead of being swallowed.
|
|
161
|
+
- Errors: `PairingRequired`, `PairingFailed(reason)`, `NodeKeyChanged`, `NodeOffline`, `NodeRejected`, `AgentUnavailable(reason)`, `SettingsInvalid(field, reason)`, `NodeBusy`, `ProtocolMismatch(ours, theirs)`, `AttachmentError(code, reason)` (attachment refused; a subclass of `RpcError`), `RpcError(code)` (other protocol errors; `.code` is a stable snake_case string such as `already_resolved`), `ConnectionError`, `AnyconError` (the base class).
|
|
162
|
+
|
|
163
|
+
## Account ownership: the first pairing needs a cookie
|
|
164
|
+
|
|
165
|
+
Every device on the hub belongs to an account. Pairing decides the account like this (the rules are in [docs/spec/hub.md](https://github.com/anycon-ai/anycon/blob/main/docs/spec/hub.md) § 4, under "cross-account" and "daemon's first identity"):
|
|
166
|
+
|
|
167
|
+
- Whichever side already has an account, the host (daemon) or the joiner (SDK), decides. If the two sides have different accounts → `PairingFailed('forbidden')`.
|
|
168
|
+
- The SDK is the joiner and, like the CLI, has **no browser cookie**. So when the **daemon has paired before** (it is a registered device on the hub, with an account), `pair()` just works, and the new device is added to the daemon's account.
|
|
169
|
+
- A **brand-new daemon** (its first pairing after `anycon init`, with no account on the hub yet) plus an SDK without a cookie means neither side has an account → the hub replies `PairFailed { reason: 'forbidden' }` and stores nothing.
|
|
170
|
+
|
|
171
|
+
The most common approach is to do the first pairing in a browser (the Web UI's sign-in cookie puts the daemon into your account). For scripts or CI with no browser, use `headers` to send a sign-in cookie and pair the daemon into the account first. Get the cookie from `/auth/token`:
|
|
172
|
+
|
|
173
|
+
```bash
|
|
174
|
+
curl -si -X POST "$HUB/auth/token" -H 'X-Anycon: 1' -H 'Content-Type: application/json' \
|
|
175
|
+
-d "{\"token\":\"$ANYCON_ADMIN_TOKEN\"}" | grep -i '^set-cookie: anycon_session='
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
```ts
|
|
179
|
+
// 1) The first time: with the cookie (run `anycon pair --json` on the node to get the code).
|
|
180
|
+
// This SDK device also becomes the first paired device.
|
|
181
|
+
await pair(hub, { code, name: 'bootstrap', storage, headers: { Cookie: 'anycon_session=…' } })
|
|
182
|
+
// 2) Any new device after that (run `anycon pair` on the node again): no cookie needed
|
|
183
|
+
await pair(hub, { code: code2, name: 'ci-runner' })
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
`headers` (accepted by `pair()`, `connect()` and `Client.open()`) are HTTP headers for the WebSocket upgrade request, and they **only take effect in Node / Bun**. The browser's native WebSocket can't set headers (the browser sends same-origin cookies itself), so they are ignored there. You can also use them for headers that a reverse proxy in front of the hub requires (such as Cloudflare Access's `CF-Access-Client-Id`). Paired devices authenticate with a device token, so `connect()` doesn't need a cookie.
|
|
187
|
+
|
|
188
|
+
## Storage
|
|
189
|
+
|
|
190
|
+
The device identity and paired nodes are stored locally, behind a minimal key-value interface, `SdkStorage { get, set, delete }`:
|
|
191
|
+
|
|
192
|
+
| Backend | Used for | Location |
|
|
193
|
+
|---|---|---|
|
|
194
|
+
| `FileStorage(dir)` | Default in Node / Bun | `$ANYCON_HOME/sdk/<hub-host>/<profile>/` (`ANYCON_HOME` defaults to `~/.anycon`); directory mode 0700, file mode 0600, atomic writes |
|
|
195
|
+
| `IndexedDBStorage(scope)` | Default in browsers | Database `anycon-sdk:<hub-host>/<profile>` |
|
|
196
|
+
| `MemoryStorage` | Tests / one-off scripts | In process |
|
|
197
|
+
|
|
198
|
+
`profile` defaults to `default`. Switch it with `ANYCON_PROFILE` or `{ profile }`. The profile becomes a directory name, so only letters, digits and `. _ -` are allowed (it must start with a letter or digit, be at most 64 characters, and not contain `..`). Path separators, `..` or an empty string throw `invalid_profile`. An empty `ANYCON_HOME` is treated as unset. In CI you can inject credentials without writing to disk: `ANYCON_DEVICE_KEY` (the 32-byte private key, hex) + `ANYCON_DEVICE_TOKEN`, plus the node to connect to, `ANYCON_NODE_ID` + `ANYCON_NODE_KEY` (the daemon's public key, hex).
|
|
199
|
+
|
|
200
|
+
## Large messages and transport desync
|
|
201
|
+
|
|
202
|
+
The hub limits the size of a single envelope (256 KiB by default), and a page of `session.history` or a single `tool_result` can be larger. So the SDK encrypts each JSON-RPC message and then uses `frame` (`@anycon/protocol`, ADR-30) to split it into `data` envelopes of ≤ 200 KiB, which the peer reassembles and then decrypts. This works the same in both directions. Noise nonces are sequential, so **losing any fragment desynchronizes the transport**. Therefore:
|
|
203
|
+
|
|
204
|
+
- For a paired `(from, to)`, the hub only forwards an envelope or bounces it back with `backpressure { to, seq }`. It **never drops one silently**, and bounces are "sticky": once a seq is bounced, the hub lets through only the smallest bounced seq (moving on only after it is resent successfully) and bounces everything else ([docs/protocol.md](https://github.com/anycon-ai/anycon/blob/main/docs/protocol.md) § 3.1). So the SDK keeps the **raw bytes** of recently sent envelopes (capped by size: 16 MiB by default, with a protocol minimum of 8 MiB; adjust it with `connect({ resendBufferBytes })`).
|
|
205
|
+
- Envelopes sent less than 10 s ago, and bounced envelopes waiting to be resent, are **never evicted**. When the retained bytes go over the cap, the SDK **pauses sending new envelopes** instead of evicting (it treats the cap as an in-flight window and continues once the oldest batch is older than 10 s).
|
|
206
|
+
- On `backpressure`, the SDK **pauses** sending anything new to that node, collects the bounced seqs, and waits `retry_after_ms` (from the latest `rate_limited`, capped at 30 s; otherwise 100–300 ms plus jitter, doubling on consecutive bounces up to about 2.4 s). It then resends every bounced seq **in ascending order, byte for byte** (without re-encrypting), and then sends the queued new requests. If envelopes are bounced again during the resend, it runs another round.
|
|
207
|
+
- If the hub reports a seq the SDK didn't keep (never sent, or not from the current transport), the order can't be guaranteed: the SDK drops the Transport and does a new IK handshake (in-flight requests fail with `NodeOffline`).
|
|
208
|
+
- When a `handshake` envelope is bounced, the SDK waits `retry_after_ms` (otherwise 300–1000 ms plus jitter, doubling on consecutive bounces, capped at 30 s) and then handshakes again, without resending right away or resetting.
|
|
209
|
+
|
|
210
|
+
This is how 5 MiB and 9 MiB `fs.read` replies, and sustained traffic of tens of MiB, still arrive in order.
|
|
211
|
+
- On a decryption failure, an out-of-order / oversized / malformed fragment, or a `RESET` frame from the daemon, the SDK drops the Transport (in-flight requests fail with `NodeOffline`) and does a new IK handshake right away. Later requests work as usual.
|
|
212
|
+
- The hub's `dropped { seq, reason }` arrives at most once per connection per second. It signals that something wrong was sent and is not a per-envelope receipt, so the SDK **doesn't resend on it**: `node.on('error', …)` receives an `AnyconError` (`envelope_too_large` means still over the limit after fragmenting, i.e. the hub's `ANYCON_MAX_ENVELOPE_BYTES` is smaller than one fragment; `not_paired` becomes `NodeRejected`), in-flight requests fail, and the channel handshakes again.
|
|
213
|
+
- The hub's `rate_limited { retry_after_ms }` is a "how long to pause" hint for the **whole hub connection** (all nodes, resends included). It comes with `backpressure`, is capped at 30 s, resets on reconnect, and **doesn't mean an envelope was dropped**. Until it expires, new envelopes for every node are queued, and bounced seqs also wait until then to be resent. It doesn't fail requests, start a new handshake, or emit an `error` event, and the SDK doesn't treat the transport as desynchronized just because data was sent within the last second.
|
|
214
|
+
|
|
215
|
+
## Development
|
|
216
|
+
|
|
217
|
+
```bash
|
|
218
|
+
bun run --cwd packages/sdk test # bun test
|
|
219
|
+
bun run --cwd packages/sdk test:node # the same tests on Node: node --import tsx --conditions source --test
|
|
220
|
+
bun run --cwd packages/sdk typecheck
|
|
221
|
+
bun run --cwd packages/sdk build # builds @anycon/protocol first, then tsc → dist/
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
`just test-sdk-real` runs end-to-end tests against a **real** `anycon-hub` + `anycon daemon` (mock agent). It builds them with `cargo build -p anycon-hub -p anycon-cli` and then runs `ANYCON_SDK_REAL=1 bun test tests/real.e2e.test.ts`; run `just gen-wasm` first. The tests use a temporary directory, random ports, and a fixed `ANYCON_ADMIN_TOKEN`:
|
|
225
|
+
|
|
226
|
+
- First, a `pair()` with the admin cookie pairs the daemon into the account. Then a regular `pair()` → `connect()` → `info` / `agents.list` / `projects.create` / `sessions.create` → `send('run permission')` (permissions, `tool_call`, usage) → `history()` cross-check → `setSettings` → `cancel()`.
|
|
227
|
+
- The last three cases cover large messages and heavy traffic: a 5 MiB `fs.read` reply arrives byte for byte; after 10 × 3 MiB in a row (30 MiB in total), the node is still online with no 30-second timeout; and the SDK, as the sender, sends 13 × 900 KiB `session.send` calls back to back, goes over the client budget of 10 MiB per minute, then pauses, waits, and resends until all of them complete without disconnecting. These rely on the hub's sticky rule and per-connection-kind rate budgets, and on the daemon resending in ascending order. On failure, the error includes the tail of the hub / daemon logs.
|
|
228
|
+
|
|
229
|
+
The real-stack tests are skipped by default. They run on Node too: `ANYCON_SDK_REAL=1 node --import tsx --conditions source --test tests/real.e2e.test.ts`. Override the binary directory with `ANYCON_BIN_DIR` (default `target/debug`).
|
|
230
|
+
|
|
231
|
+
The other, fast tests use two fakes:
|
|
232
|
+
|
|
233
|
+
- `tests/fake-hub.ts`: a real WebSocket server that only forwards. It implements Auth / `PairBegin { match_id }` / `PairJoin { match_id }` / forwarding / undeliverable / sticky backpressure per `(from, to)` (an `interceptor` returning `'backpressure'` / `'rate_limited'` bounces an envelope, and every later envelope is bounced until the bounced seq is resent successfully; `arrivals` / `bounced` record the order of arrivals and bounces) / `dropped`, following the real hub's wire conventions: permanent ids are assigned only at `PairDone`, temporary connections can only send `PairJoin` / `PairConfirm`, and envelopes over `maxEnvelopeBytes` get `dropped { too_large }`. It can also misbehave (`forgePairDoneOnConfirm`, `tamperPairDonePeer`) to test that pairing can't be fooled by a man in the middle.
|
|
234
|
+
- `tests/fake-daemon.ts`: a Noise responder written in TS. It generates the pairing code locally and handles `pair.ack`, `frame` fragmentation / reassembly / RESET, scripted `node.info` / `agent.list` / `workspace.*` / `session.*` / `permission.*` / `test.echo`, and `blob.*` following the real daemon's rules, with `blobChunkSize`, `maxAttachmentBytes`, `blobRefusal` (`quota` / `disk_full`), `chunkHook` (delays a chunk or makes it fail), and `chunksPeak` (the number of chunks being processed at once) for the attachment tests.
|
|
235
|
+
|
|
236
|
+
Every scenario runs once against each of two Noise implementations: `tests/mock-crypto.ts` (a toy implementation shaped like real Noise, always available) and the real wasm (present in `packages/protocol/wasm/` after `just gen-wasm`; if it's missing, a notice is printed and only the mock runs).
|
|
237
|
+
|
|
238
|
+
## License
|
|
239
|
+
|
|
240
|
+
[Apache-2.0](https://github.com/anycon-ai/anycon/blob/main/LICENSE)
|