@anycon/sdk 0.1.1 → 0.3.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.
Files changed (52) hide show
  1. package/README.md +52 -14
  2. package/README.zh-CN.md +50 -14
  3. package/dist/attachments.d.ts +62 -14
  4. package/dist/attachments.d.ts.map +1 -1
  5. package/dist/attachments.js +126 -15
  6. package/dist/attachments.js.map +1 -1
  7. package/dist/client.d.ts +53 -0
  8. package/dist/client.d.ts.map +1 -1
  9. package/dist/client.js +205 -3
  10. package/dist/client.js.map +1 -1
  11. package/dist/errors.d.ts +3 -3
  12. package/dist/errors.js +1 -1
  13. package/dist/hub.d.ts +10 -0
  14. package/dist/hub.d.ts.map +1 -1
  15. package/dist/hub.js +18 -1
  16. package/dist/hub.js.map +1 -1
  17. package/dist/index.d.ts +2 -2
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +2 -2
  20. package/dist/index.js.map +1 -1
  21. package/dist/node.d.ts +27 -7
  22. package/dist/node.d.ts.map +1 -1
  23. package/dist/node.js +41 -10
  24. package/dist/node.js.map +1 -1
  25. package/dist/pair.d.ts.map +1 -1
  26. package/dist/pair.js +6 -1
  27. package/dist/pair.js.map +1 -1
  28. package/dist/rotation.d.ts +33 -0
  29. package/dist/rotation.d.ts.map +1 -0
  30. package/dist/rotation.js +41 -0
  31. package/dist/rotation.js.map +1 -0
  32. package/dist/session.d.ts +5 -3
  33. package/dist/session.d.ts.map +1 -1
  34. package/dist/session.js.map +1 -1
  35. package/dist/storage.d.ts +11 -0
  36. package/dist/storage.d.ts.map +1 -1
  37. package/dist/storage.js +16 -2
  38. package/dist/storage.js.map +1 -1
  39. package/dist/version.d.ts +1 -1
  40. package/dist/version.js +1 -1
  41. package/package.json +6 -6
  42. package/src/attachments.ts +167 -22
  43. package/src/client.ts +292 -2
  44. package/src/errors.ts +3 -3
  45. package/src/hub.ts +23 -1
  46. package/src/index.ts +13 -1
  47. package/src/node.ts +49 -13
  48. package/src/pair.ts +9 -2
  49. package/src/rotation.ts +50 -0
  50. package/src/session.ts +5 -3
  51. package/src/storage.ts +24 -2
  52. package/src/version.ts +1 -1
package/README.md CHANGED
@@ -93,13 +93,16 @@ await node.worktrees.remove(id, { force: true, deleteBranch: false })
93
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
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
95
 
96
- ## Image attachments (ADR-35)
96
+ ## Attachments (ADR-35, ADR-44)
97
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`):
98
+ Images and files 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
99
 
100
100
  ```ts
101
101
  import { readFile } from 'node:fs/promises'
102
- import { AttachmentError } from '@anycon/sdk'
102
+ import { AttachmentError, acceptsAttachment } from '@anycon/sdk'
103
+
104
+ // any file: the daemon records the name and mime and doesn't look inside non-images
105
+ const doc = await node.uploadFile(await readFile('spec.pdf'), { name: 'spec.pdf' }) // mime defaults to the detected image type, else application/octet-stream
103
106
 
104
107
  const ref = await node.uploadImage(await readFile('shot.png'), {
105
108
  name: 'shot.png', // without mime, the type is detected from the file header (png / jpeg / gif / webp)
@@ -122,24 +125,36 @@ try {
122
125
  await node.sessions.create({ project: 'app', agent: 'claude-code', attachments: [ref2] })
123
126
  // uploaded but not sent; if you don't discard it, the daemon reclaims it after 24 hours
124
127
  await node.discardAttachment(ref3)
128
+
129
+ // any other file: same channel, same queue
130
+ const doc = await node.uploadFile(await readFile('spec.pdf'), {
131
+ name: 'spec.pdf', // without mime: image header, else the extension, else application/octet-stream
132
+ }) // → { blob_id, name, mime: 'application/pdf', bytes }
133
+ if (acceptsAttachment(agent, doc.mime)) {
134
+ // agent: an entry of node.agents.list()
135
+ for await (const ev of session.send('summarize this', { attachments: [doc] })) { /* … */ }
136
+ }
125
137
  ```
126
138
 
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`.
139
+ - **Images vs. other files.** `image/png`, `image/jpeg`, `image/gif` and `image/webp` are images: the daemon checks the file header and reads the size, and an agent that takes images natively gets them as images. Any other file is not read by the daemon at all. What the agent takes natively (`capabilities.attachments`, usually just the four image types) goes to it directly; everything else is copied by the daemon into the session's working directory (`.anycon/attachments/<session_id>/`), and the paths are listed at the end of the text the agent receives. So every agent can use every file type, as long as the node reports `file_attachments`.
140
+ - **`uploadFile(bytes, { name, mime? })`.** Without `mime`, the SDK uses the file header for the four image types, then a small table of common extensions (`pdf`, `txt`, `md`, `csv`, `json`, `html`, `xml`, `yaml`, `zip`, `gz`, `tar`, `js`, `ts`, `py`, `rs`, `go`, …; see `guessMime`), and falls back to `application/octet-stream`. A file whose name ends in `.png` but whose content isn't a PNG is not guessed as an image. A `mime` you pass must be a well-formed `type/subtype` without parameters; it is lowercased before sending, and a malformed one throws `AnyconError('invalid_mime')` with nothing sent. The daemon is the real validation point. `uploadImage` stays image-only: any other `mime`, or no `mime` and an unrecognized header, throws `AnyconError('unsupported_image')`.
141
+ - **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 file (`sessions.max_attachment_bytes`) and at most 20 attachments 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).
142
+ - Whether the node and agent take a file type: `acceptsAttachment(await node.info(), agent, ref.mime)` (true when the node reports `capabilities.file_attachments`, otherwise only for what the agent takes natively, `isNativeAttachment(agent, ref.mime)`; `agent` is an entry of `node.agents.list()`). Whether the node supports the blob channel: `(await node.info()).capabilities.blobs`; the limits are in `attachment_limits`.
143
+ - **Files and images the agent doesn't take natively are saved in the working directory.** Attachments in a mime type the agent accepts (`capabilities.attachments`) go to it directly. Everything else (every non-image file, and images in a format the agent doesn't take) the daemon copies to `.anycon/attachments/<session_id>/` in the session's working directory and lists, as relative paths, at the end of the text it hands to the agent. The `user_message` event keeps the original text and the attachment metadata. A single file is at most 10 MiB by default (`sessions.max_attachment_bytes`), a message carries at most 20 attachments, ≤ 20 MiB in total. If the copy fails (disk full, `.anycon/attachments` replaced by a symbolic link …), that turn ends with `error { code: 'attachment_failed' }`; fix the cause and resend. A daemon without `file_attachments` (older versions) takes images only, and answers other files with `unsupported`.
144
+ - Uploads on one `Node` (images and files alike) are **queued and go one at a time** (even a `Promise.all` batch has only one upload in progress, with 2 chunks in flight), so requests like "allow" or "stop" don't wait behind a multi-megabyte file. 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
145
  - Refusals throw `AttachmentError` (a subclass of `RpcError`; `.code` is unchanged and `.reason` is narrowed):
131
146
 
132
147
  | `reason` | `code` | When it happens / what to do |
133
148
  |---|---|---|
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()` |
149
+ | `too_large` | `invalid` | One file is over the node's limit, or one message totals more than 20 MiB: shrink it or split it across messages |
150
+ | `quota` | `busy` | Unreferenced uploads on the node total more than 1 GiB: send them first, or `discardAttachment()` |
136
151
  | `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) |
152
+ | `blob` | `not_found` | The referenced attachment was reclaimed (unused for 24 hours) or discarded: upload it again |
153
+ | `blob_in_use` | `invalid` | The attachment is already used in another session (an attachment belongs to one session only): upload it again |
154
+ | `in_use` | `invalid` | `discardAttachment` on an attachment that a message already references (it is deleted along with the session) |
155
+ | `finalizing` / `incomplete` / `hash_mismatch` / `mime_mismatch` | `invalid` | The upload failed finalization or verification (the file header doesn't match an image `mime`, or the content was corrupted in transit) |
141
156
 
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.
157
+ A node without `file_attachments` (older daemons) turns away anything but what the agent takes natively with `RpcError` (`unsupported`). More than 8 concurrent uploads from this device → `RpcError` (`busy`, no `reason`). `uploadImage` with a non-image `mime`, or with no `mime` and an unrecognized file header → `AnyconError('unsupported_image')`; `uploadFile` with a malformed `mime` → `AnyconError('invalid_mime')`. In both cases nothing is sent.
143
158
 
144
159
  ## API overview
145
160
 
@@ -152,7 +167,7 @@ await node.discardAttachment(ref3)
152
167
  - `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
168
  - `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
169
  - 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).
170
+ - `Node`: `info()`, `agents.list({ refresh? })` (cached by etag), `projects.list/create/clone/link/unlink/browse/branches/rename/trash/trashList/restore/purge` (`create` and `clone` take an optional `root`: one of the paths in `info().workspace_roots`, the primary root by default), `sessions.list/get/create/search` (`create` accepts `workspace`, `prompt`, `attachments`, `messageId`), `worktrees.list/remove`, `uploadImage(bytes, { name, mime?, signal?, onProgress?, requestTimeoutMs? })` / `uploadFile(bytes, { name, mime?, signal?, onProgress?, requestTimeoutMs? })` / `downloadAttachment(refOrBlobId)` / `discardAttachment(refOrBlobId)` (see [Attachments](#attachments-adr-35-adr-44) 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
171
  - `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
172
  - `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
173
  - 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).
@@ -197,6 +212,29 @@ The device identity and paired nodes are stored locally, behind a minimal key-va
197
212
 
198
213
  `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
214
 
215
+ ## Device token rotation
216
+
217
+ The hub signs a device token when you pair. To shorten how long a leaked token stays useful, the SDK rotates it (`rotate_token` → `token_rotated`; the hub keeps the previous token valid for another 60 s and accepts at most one rotation per device per minute).
218
+
219
+ - **Identity kept by the SDK** (written by `pair()`, or in the `storage` you pass): after authenticating, `connect()` / `Client.open()` rotates a token that is 30 days old or older. The new token and its issue time (`tokenIssuedAtMs`) are written back in **one** `storage.set` (`FileStorage`: temporary file + rename, mode 0600), and only then used for reconnects. Records without an issue time (and issue times in the future, after a clock change) count as old and are rotated once on the next connect. If the reply doesn't arrive, the request is sent again after 75 s (the first 3 sends of a connection are 75 s apart), then re-checked hourly, so a connection that stays up for weeks still rotates. Resending helps when the request was ignored as too soon, or when the reply was lost on a connection that stayed up. It does not help after a reconnect: the hub only lets a connection that authenticated with the current token rotate, so if a reply is lost and the client reconnects with the old token inside the 60 s grace, it cannot rotate again and has to pair again once the grace is over. `close()` waits up to 2 s for a reply that is still on its way so a script that exits right after connecting doesn't lose the new token. A failed storage write isn't fatal: the new token stays in memory for this process's reconnects, and the event says `persisted: false`.
220
+ - **Credentials from environment variables** (`ANYCON_DEVICE_KEY` / `ANYCON_DEVICE_TOKEN`) are **not rotated automatically**: the SDK has nowhere to save a new token, and rotating without saving locks the device out (the old token stops working after 60 s; you would have to pair again and revoke the old device). Call `client.rotateToken()` yourself and save the returned `deviceToken`.
221
+
222
+ ```ts
223
+ import { Client } from '@anycon/sdk'
224
+
225
+ const client = await Client.open(hubUrl, {
226
+ // Called on every successful rotation. With env credentials the SDK doesn't write
227
+ // anything, so this is where you store the new token.
228
+ onTokenRotated: ({ deviceToken, persisted }) => {
229
+ if (!persisted) secrets.put('ANYCON_DEVICE_TOKEN', deviceToken)
230
+ },
231
+ })
232
+ client.on('tokenRotated', (rotation) => {}) // same payload: { deviceToken, issuedAtMs, persisted, persistError? }
233
+ const rotation = await client.rotateToken() // rotate now; resolves with the same object
234
+ ```
235
+
236
+ `rotateToken({ timeoutMs })` waits up to 10 s by default. It rejects with `not_connected` before the hub connection is up, `rotate_timeout` if the hub doesn't answer (a second request within a minute of the previous rotation is ignored, so is a request on a connection that authenticated with an old token, and hubs without rotation never answer), and fails if the connection drops or the client closes while waiting. A reply that arrives after the timeout is still applied. `connect()` doesn't expose the `Client`; use `Client.open()` to rotate on demand. `ClientOptions.tokenRotation` has `auto: false` to turn off automatic rotation, and `maxAgeMs` / `retryAfterMs` / `recheckMs` / `closeWaitMs` to change the timings (mainly for tests).
237
+
200
238
  ## Large messages and transport desync
201
239
 
202
240
  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:
package/README.zh-CN.md CHANGED
@@ -71,13 +71,16 @@ await node.worktrees.remove(id, { force: true, deleteBranch: false }) // 会
71
71
  - `prompt` 时 `create()` 不替你收第一个 turn 的事件:创建后马上 `s.events({ fromSeq: 0 })`(补历史期间到的实时事件会扣住、补完再接上,seq 严格递增不重复)。权限策略也要等会话有进行中的 `events()` / `send()` 才会代答。`messageId` 可传自己的幂等键:`create()` 超时后重试传同一个,daemon 返回第一次创建的会话,不会再开第二个。
72
72
  - 创建被拒的原因看 `RpcError.code` / `.reason`:项目不是 `worktree_ready` → `invalid` / `not_worktree_ready`,分支已存在 → `exists`,`base` 解析不了 → `invalid` / `bad_base`。`syncBase` 的失败:turn 在跑 → `busy`;有未提交改动 → `invalid` / `uncommitted_changes`;上次合并停在冲突里 → `invalid` / `merge_in_progress`;fetch / merge 失败 → `internal` / `fetch_failed` / `git_failed`。`gitStatus` 在会话不在 git 仓库里时 → `invalid` / `not_git`。
73
73
 
74
- ## 图片附件(ADR-35)
74
+ ## 附件(ADR-35、ADR-44)
75
75
 
76
- 图片先经 blob 通道传到节点(`blob.put_begin` → 512 KiB 一块、最多 2 块在途的 `blob.put_chunk` → `blob.put_end`),消息只带 daemon 返回的引用(`AttachmentRef`):
76
+ 图片和文件先经 blob 通道传到节点(`blob.put_begin` → 512 KiB 一块、最多 2 块在途的 `blob.put_chunk` → `blob.put_end`),消息只带 daemon 返回的引用(`AttachmentRef`):
77
77
 
78
78
  ```ts
79
79
  import { readFile } from 'node:fs/promises'
80
- import { AttachmentError } from '@anycon/sdk'
80
+ import { AttachmentError, acceptsAttachment } from '@anycon/sdk'
81
+
82
+ // 任意文件:daemon 记下文件名和 mime,不看非图片的内容
83
+ const doc = await node.uploadFile(await readFile('spec.pdf'), { name: 'spec.pdf' }) // mime 缺省:认得出图片就用图片的,否则 application/octet-stream
81
84
 
82
85
  const ref = await node.uploadImage(await readFile('shot.png'), {
83
86
  name: 'shot.png', // mime 缺省按文件头判断(png / jpeg / gif / webp)
@@ -95,24 +98,35 @@ try {
95
98
  }
96
99
  await node.sessions.create({ project: 'app', agent: 'claude-code', attachments: [ref2] }) // 第一条消息只有图也行
97
100
  await node.discardAttachment(ref3) // 传了但不发;不丢的话 daemon 24 小时后回收
101
+
102
+ // 任意文件:同一个通道、同一个队列
103
+ const doc = await node.uploadFile(await readFile('spec.pdf'), {
104
+ name: 'spec.pdf', // mime 缺省:先认图片文件头,再看扩展名,都不行是 application/octet-stream
105
+ }) // → { blob_id, name, mime: 'application/pdf', bytes }
106
+ if (acceptsAttachment(agent, doc.mime)) { // agent:node.agents.list() 里的一项
107
+ for await (const ev of session.send('总结一下这个文件', { attachments: [doc] })) { /* … */ }
108
+ }
98
109
  ```
99
110
 
100
- - **SDK 不缩放、不重编码图片。** 调用方自己把图控制在**长边 ≤ 2000 px、单张 ≤ 约 1.5 MiB**(比如先用 `sharp` / ImageMagick 缩一下)。daemon 的硬上限是每张 10 MiB(`sessions.max_attachment_bytes`)、每条消息至多 20 张且合计 ≤ 20 MiB;而图一旦进了 Claude Code 的会话历史,之后每个 turn 都会带着它重发,大图会让会话很快超过 Claude 的请求体上限。同理,`node.uploadImage()` 原样上传字节:**不去掉 EXIF 元数据(包括 GPS 位置),也不按 EXIF 方向转正**,只有 Web UI 会在上传前重编码图片。在意隐私或方向的调用方,请在 `uploadImage` 之前自己处理(比如 `sharp(bytes).rotate().toBuffer()`:按 EXIF 转正,输出默认不带元数据)。
101
- - agent 收不收图看 `(await node.agents.list())[i].capabilities?.attachments`;节点支不支持 blob 通道看 `(await node.info()).capabilities.blobs`。
102
- - 同一个 `Node` 上的上传**排队、一次一张**(`Promise.all` 一批图也只有一张在传、2 块在途),免得「允许」「停止」之类的请求排在几 MB 的图后面。超时(每块默认 90 秒,`requestTimeoutMs`)/ 掉线的块各自重试 2 次,daemon 的明确拒绝不重试;失败或 `signal` 中止时 SDK 尽力 `blob.discard`。
111
+ - **图片和其它文件。** `image/png`、`image/jpeg`、`image/gif`、`image/webp` 是图片:daemon 核对文件头、读宽高,原生收图的 agent 把它们当图片看。其它文件 daemon 完全不读。agent 原生收的类型(`capabilities.attachments`,一般只是四种图片)直接交给它;其余的由 daemon 复制进会话的工作目录(`.anycon/attachments/<session_id>/`),路径列在发给 agent 的文字末尾。所以只要节点报了 `file_attachments`,每个 agent 都能用每种文件。
112
+ - **`uploadFile(bytes, { name, mime? })`。** `mime` 缺省时先按文件头认四种图片,再查一张常见扩展名的小表(`pdf`、`txt`、`md`、`csv`、`json`、`html`、`xml`、`yaml`、`zip`、`gz`、`tar`、`js`、`ts`、`py`、`rs`、`go`……,见 `guessMime`),都不行用 `application/octet-stream`;扩展名是 `.png` 但内容不是 PNG 的不会被猜成图片。显式给的 `mime` 必须是成形的 `type/subtype`(不带参数),发出去前转小写,不成形抛 `AnyconError('invalid_mime')`,什么都不发;真正的校验在 daemon。`uploadImage` 仍然只传图片:给了别的 `mime`,或者没给而文件头认不出,抛 `AnyconError('unsupported_image')`。
113
+ - **SDK 不缩放、不重编码图片。** 调用方自己把图控制在**长边 ≤ 2000 px、单张 ≤ 约 1.5 MiB**(比如先用 `sharp` / ImageMagick 缩一下)。daemon 的硬上限是每个文件 10 MiB(`sessions.max_attachment_bytes`)、每条消息至多 20 个附件且合计 ≤ 20 MiB;而图一旦进了 Claude Code 的会话历史,之后每个 turn 都会带着它重发,大图会让会话很快超过 Claude 的请求体上限。同理,`node.uploadImage()` 原样上传字节:**不去掉 EXIF 元数据(包括 GPS 位置),也不按 EXIF 方向转正**,只有 Web UI 会在上传前重编码图片。在意隐私或方向的调用方,请在 `uploadImage` 之前自己处理(比如 `sharp(bytes).rotate().toBuffer()`:按 EXIF 转正,输出默认不带元数据)。
114
+ - 节点和 agent 收不收某种文件看 `acceptsAttachment(await node.info(), agent, ref.mime)`(节点带 `capabilities.file_attachments` 时为 true,否则只对 agent 原生收的类型为 true,即 `isNativeAttachment(agent, ref.mime)`;`agent` 是 `node.agents.list()` 里的一项);节点支不支持 blob 通道看 `(await node.info()).capabilities.blobs`,上限在 `attachment_limits` 里。
115
+ - **文件和 agent 不原生收的图片会落到工作目录。** agent 收的 mime(`capabilities.attachments`)直接交给它;其余的(所有非图片文件、agent 不收的图片格式)daemon 复制到会话工作目录的 `.anycon/attachments/<session_id>/` 下,并在发给 agent 的文字末尾用相对路径列出;`user_message` 事件里仍是原文和附件元数据。单个文件默认 ≤ 10 MiB(`sessions.max_attachment_bytes`),每条消息至多 20 个、合计 ≤ 20 MiB。复制失败(磁盘满、`.anycon/attachments` 被换成符号链接…)时这一轮以 `error { code: 'attachment_failed' }` 结束,处理好原因后重发。没有 `file_attachments` 的 daemon(旧版本)只收图片,别的文件得到 `unsupported`。
116
+ - 同一个 `Node` 上的上传(图片和文件一样)**排队、一次一个**(`Promise.all` 一批也只有一个在传、2 块在途),免得「允许」「停止」之类的请求排在几 MB 的文件后面。超时(每块默认 90 秒,`requestTimeoutMs`)/ 掉线的块各自重试 2 次,daemon 的明确拒绝不重试;失败或 `signal` 中止时 SDK 尽力 `blob.discard`。
103
117
  - 被拒抛 `AttachmentError`(`RpcError` 的子类,`.code` 照旧,`.reason` 收窄):
104
118
 
105
119
  | `reason` | `code` | 什么时候 / 怎么办 |
106
120
  |---|---|---|
107
- | `too_large` | `invalid` | 单张超过节点上限,或一条消息合计超过 20 MiB:缩小 / 分几条发 |
108
- | `quota` | `busy` | 没被引用的图全节点超过 1 GiB:先发出去,或 `discardAttachment()` |
121
+ | `too_large` | `invalid` | 单个文件超过节点上限,或一条消息合计超过 20 MiB:缩小 / 分几条发 |
122
+ | `quota` | `busy` | 没被引用的附件全节点超过 1 GiB:先发出去,或 `discardAttachment()` |
109
123
  | `disk_full` | `busy` | 节点数据盘快满了 |
110
- | `blob` | `not_found` | 引用的图已被回收(24 小时没用)或丢掉了:重新上传 |
111
- | `blob_in_use` | `invalid` | 这张图已经用在别的会话里(一张图只属于一个会话):重新上传 |
112
- | `in_use` | `invalid` | `discardAttachment` 一张已被消息引用的图(它随会话删除) |
113
- | `finalizing` / `incomplete` / `hash_mismatch` / `mime_mismatch` | `invalid` | 上传的收尾和校验没过(文件头和 `mime` 对不上、内容在路上坏了) |
124
+ | `blob` | `not_found` | 引用的附件已被回收(24 小时没用)或丢掉了:重新上传 |
125
+ | `blob_in_use` | `invalid` | 这个附件已经用在别的会话里(一个附件只属于一个会话):重新上传 |
126
+ | `in_use` | `invalid` | `discardAttachment` 一个已被消息引用的附件(它随会话删除) |
127
+ | `finalizing` / `incomplete` / `hash_mismatch` / `mime_mismatch` | `invalid` | 上传的收尾和校验没过(声明为图片而文件头和 `mime` 对不上、内容在路上坏了) |
114
128
 
115
- `mime` 不在白名单 / agent 不收 → `RpcError`(`unsupported`);这台设备同时进行的上传超过 8 个 → `RpcError`(`busy`,没有 `reason`);`mime` 缺省而文件头认不出 → `AnyconError('unsupported_image')`,什么都不发。
129
+ 没有 `file_attachments` 的 daemon(旧版本)收到 agent 原生收的类型以外的文件 → `RpcError`(`unsupported`);这台设备同时进行的上传超过 8 个 → `RpcError`(`busy`,没有 `reason`);`uploadImage` 给了非图片 `mime`、或 `mime` 缺省而文件头认不出 → `AnyconError('unsupported_image')`;`uploadFile` 给了不成形的 `mime` → `AnyconError('invalid_mime')`。这两种情况什么都不发。
116
130
 
117
131
  ## API 速览
118
132
 
@@ -120,7 +134,7 @@ await node.discardAttachment(ref3) // 传了但不发;
120
134
  - `forgetNode(hubUrl, nodeNameOrIdPrefix, { storage?, profile? })` — 忘掉本地记录的某个节点;`NodeKeyChanged` 之后确认新公钥可信时用它,再 `pair()` 一次。
121
135
  - `connect(hubUrl, { node?, storage?, onPermission?, headers?, … })` → `Node`。每次 WS 连上、收到 `peer_online`(或 `auth_ok.peers_online` 含该节点)都重新做 IK 握手;掉线指数退避重连(1s → 30s,hub 重启 `4002` 用 1–3 s 抖动)。
122
136
  - 同时连多个节点:`const client = await Client.open(hubUrl)` + 多次 `client.node('name')`(hub 对单设备只允许一条连接,所以多节点共用一个 `Client`)。
123
- - `Node`:`info()`、`agents.list({ refresh? })`(带 etag 缓存)、`projects.list/create/clone/link/unlink/browse/branches/rename/trash/trashList/restore/purge`(`link(path, { name? })` 把 daemon 所在机器上的已有目录关联为项目——不移动、不复制,路径要在 daemon 的 `workspace.link_roots` 之内;`unlink(name)` 只解除关联、不动目录;`browse({ path?, showHidden? })` 列 `link_roots` 之内的子目录供选择;关联项目的 `kind` 为 `linked`,目录没了时 `missing` 为 true)、`sessions.list/get/create/search`(`create` 接受 `workspace`、`prompt`、`attachments`、`messageId`)、`worktrees.list/remove`、`uploadImage(bytes, { name, mime?, signal?, onProgress?, requestTimeoutMs? })` / `downloadAttachment(refOrBlobId)` / `discardAttachment(refOrBlobId)`(见上面「图片附件」)、`permissions.list`、`online` / `waitOnline()`、事件 `online` / `offline` / `permission` / `permission_error` / `error`(非致命的通道问题)/ `session_changed` …、`call(method, params)`(类型化)和 `rpc(method, params)`(原始)。
137
+ - `Node`:`info()`、`agents.list({ refresh? })`(带 etag 缓存)、`projects.list/create/clone/link/unlink/browse/branches/rename/trash/trashList/restore/purge`(`create` / `clone` 可带 `root`:`info().workspace_roots` 里的某个 `path`,缺省是主根;`link(path, { name? })` 把 daemon 所在机器上的已有目录关联为项目——不移动、不复制,路径要在 daemon 的 `workspace.link_roots` 之内;`unlink(name)` 只解除关联、不动目录;`browse({ path?, showHidden? })` 列 `link_roots` 之内的子目录供选择;关联项目的 `kind` 为 `linked`,目录没了时 `missing` 为 true)、`sessions.list/get/create/search`(`create` 接受 `workspace`、`prompt`、`attachments`、`messageId`)、`worktrees.list/remove`、`uploadImage(bytes, { name, mime?, signal?, onProgress?, requestTimeoutMs? })` / `uploadFile(bytes, { name, mime?, signal?, onProgress?, requestTimeoutMs? })` / `downloadAttachment(refOrBlobId)` / `discardAttachment(refOrBlobId)`(见上面「附件」)、`permissions.list`、`online` / `waitOnline()`、事件 `online` / `offline` / `permission` / `permission_error` / `error`(非致命的通道问题)/ `session_changed` …、`call(method, params)`(类型化)和 `rpc(method, params)`(原始)。
124
138
  - `Session`:`send(text, { attachments?, messageId?, signal? })` → 可迭代事件流(**立即发送**,迭代到本 turn 的 `turn_done` 或不可恢复的 `error`;中途 `break` 不取消 turn)、`run(text)`、`respond(requestId, optionId | { answers }, message?)`、`setSettings(settings, { clear? })`、`cancel`、`history`、`events()`、`rename/archive/delete/restart`(`archive({ worktree? })`、`delete({ worktree?, deleteBranch? })`)、`worktree`(getter)、`gitStatus({ includePr? })`、`diff({ against?, path? })`、`syncBase({ abort? })`。`watch` / `unwatch` 和掉线后的补事件(`session.history`)是内部的。
125
139
  - 权限:`permission` 事件上有 `allow()` / `allowSession()` / `deny(message?)` / `respond(optionId)` / `answer(answers)`;`onPermission` 策略返回 `'allow' | 'allow_session' | 'deny' | { option, message } | { answers } | undefined`。**只对 SDK 自己正在用的会话(有进行中的 `send()` / `events()`)代答**,不会替用户在 Web 上开的会话做决定;没人答复的请求 `permissionTimeoutMs`(默认 10 分钟)后由 SDK deny。
126
140
  - **不会悄悄升级成 `allow_always`**:`allow()` / `'allow'` 只选 `allow_once`;请求里没有 `allow_once` 时 `allow()` 报错 `no_matching_option`,策略的 `'allow'` 则发 `node.on('permission_error', (error, request) => …)` 并照常走超时 deny。要「本会话都允许」显式用 `allowSession()` / `'allow_session'`(没有 `allow_always` 选项时退回 `allow_once`,只会收窄)。
@@ -163,6 +177,28 @@ await pair(hub, { code: code2, name: 'ci-runner' })
163
177
 
164
178
  `profile` 默认 `default`,`ANYCON_PROFILE` 或 `{ profile }` 切换。profile 会变成目录名,所以只允许字母数字和 `. _ -`(以字母数字开头、最多 64 位、不含 `..`),路径分隔符 / `..` / 空串直接抛 `invalid_profile`;`ANYCON_HOME` 是空串时当作没设。CI 里可以不落盘直接注入:`ANYCON_DEVICE_KEY`(32 字节私钥 hex)+ `ANYCON_DEVICE_TOKEN`,以及要连的节点 `ANYCON_NODE_ID` + `ANYCON_NODE_KEY`(daemon 公钥 hex)。
165
179
 
180
+ ## 设备 token 轮换
181
+
182
+ 配对时 hub 签发一个设备 token。为了缩短泄露的 token 能用多久,SDK 会定期轮换它(`rotate_token` → `token_rotated`;hub 让旧 token 再有效 60 秒,同一设备 1 分钟内最多轮换一次)。
183
+
184
+ - **身份由 SDK 自己存着**(`pair()` 写的,或你传的 `storage`):`connect()` / `Client.open()` 认证成功后,token 满 30 天就轮换。新 token 和签发时间(`tokenIssuedAtMs`)在**一次** `storage.set` 里写回(`FileStorage`:临时文件 + rename、0600),写完才用于重连。没有签发时间的老记录(以及签发时间在未来、时钟被拨回过的)当作很旧,下次连上换一次。回复没等到就 75 秒后重发(一条连接上头 3 次发送各隔 75 秒),之后每小时复查一次,所以连上几周不断的长连接也会轮换。重发有用的情形:请求被当作「太频繁」忽略了,或者回复在同一条连接上丢了。重连之后不行:hub 只让用当前 token 认证的连接轮换,回复丢了、又在 60 秒宽限内用旧 token 重连的话,不能再请求,宽限一过要重新配对。`close()` 最多多等 2 秒,让还在路上的回复落盘,刚连上就退出的脚本不会丢新 token。写存储失败不致命:新 token 仍留在内存里供本进程重连,事件里 `persisted: false`。
185
+ - **凭据来自环境变量**(`ANYCON_DEVICE_KEY` / `ANYCON_DEVICE_TOKEN`)时**不自动轮换**:SDK 没有地方存新 token,换了没保存会把设备锁在外面(旧 token 60 秒后失效,只能重新配对并吊销旧设备)。要轮换就自己调 `client.rotateToken()`,并保存返回的 `deviceToken`。
186
+
187
+ ```ts
188
+ import { Client } from '@anycon/sdk'
189
+
190
+ const client = await Client.open(hubUrl, {
191
+ // 每次轮换成功都会调用。环境变量凭据时 SDK 不写任何存储,新 token 要在这里自己存。
192
+ onTokenRotated: ({ deviceToken, persisted }) => {
193
+ if (!persisted) secrets.put('ANYCON_DEVICE_TOKEN', deviceToken)
194
+ },
195
+ })
196
+ client.on('tokenRotated', (rotation) => {}) // 同样的参数:{ deviceToken, issuedAtMs, persisted, persistError? }
197
+ const rotation = await client.rotateToken() // 立刻轮换;resolve 同一个对象
198
+ ```
199
+
200
+ `rotateToken({ timeoutMs })` 默认最多等 10 秒:还没连上 hub 抛 `not_connected`;hub 不回复抛 `rotate_timeout`(同一设备 1 分钟内的第二次请求会被忽略,用旧 token 认证的连接上的请求也会,不支持轮换的 hub 也不会回复);等待期间断线或 client 关闭则失败。超时之后才到的回复仍会处理。`connect()` 不暴露 `Client`,要按需轮换请用 `Client.open()`。`ClientOptions.tokenRotation` 里 `auto: false` 关闭自动轮换,`maxAgeMs` / `retryAfterMs` / `recheckMs` / `closeWaitMs` 调整各项时间(主要给测试用)。
201
+
166
202
  ## 大消息与传输失步
167
203
 
168
204
  hub 对单个信封有大小上限(默认 256 KiB),而一页 `session.history` 或一条 `tool_result` 可能更大。所以 SDK 把每条 JSON-RPC 消息加密之后按 `frame`(`@anycon/protocol`,ADR-30)切成 ≤ 200 KiB 的 `data` 信封,对端重组后再解密;两个方向都是。Noise 的 nonce 是顺序的,**任何一片丢失都意味着传输失步**,所以:
@@ -1,27 +1,37 @@
1
1
  /**
2
- * 图片附件(ADR-35,docs/protocol.md § 5.6):经 blob 通道把图片传到 daemon,消息只带 `AttachmentRef`。
2
+ * 附件(ADR-35,docs/protocol.md § 5.6):经 blob 通道把文件传到 daemon,消息只带 `AttachmentRef`。
3
3
  *
4
+ * - 两个入口共用同一套分块上传:`uploadImage` 只传图片(`image/png|jpeg|gif|webp`,认不出抛 `unsupported_image`),
5
+ * `uploadFile` 传任意文件(mime 缺省时先按文件头认图片,再按扩展名猜,猜不出用 `application/octet-stream`)。
6
+ * 四种图片由 daemon 核对文件头、读宽高;其它文件 daemon 不看内容。agent 原生收的类型(`capabilities.attachments`,一般是图片)
7
+ * 交给 adapter,其余的由 daemon 复制进会话的工作目录、在发给 agent 的文字里附上路径(ADR-44);节点要有 `capabilities.file_attachments`
8
+ * 才收这些(`acceptsAttachment` 综合两者判断)。
4
9
  * - 上传:`blob.put_begin` → 每块 `chunk_size`(daemon 给,目前 512 KiB)的 `blob.put_chunk`,最多 2 块在途 →
5
- * `blob.put_end`,返回 daemon 记录的 `AttachmentRef`(含宽高)。每块都有答复:超时 / 掉线的块自己重试,不整张重传;
10
+ * `blob.put_end`,返回 daemon 记录的 `AttachmentRef`(图片含宽高)。每块都有答复:超时 / 掉线的块自己重试,不整个重传;
6
11
  * daemon 明确拒绝的不重试(块答 `finalizing` = `put_end` 已经接手,直接 `put_end` 拿结果)。失败或中止时尽力 `blob.discard`。
7
- * - 同一个 `Node` 上的上传排队、一张一张传(ADR-35「2026-10 修订」:每个节点 1 张在上传、2 块在途),
8
- * 免得「允许」「停止」之类的请求排在几 MB 的图后面。
9
- * - SDK 不缩放、不重编码图片,也不替 daemon 校验(daemon 是唯一的校验点):调用方自己把图控制在长边 ≤ 2000 px、
10
- * 单张 ≤ 约 1.5 MiB(硬上限:daemon 每张默认 10 MiB、每条消息合计 20 MiB;Claude 单张 base64 后约 5 MB)。
11
- * - 下载:`blob.get` 按偏移分页拉(每段 ≤ 512 KiB)。
12
+ * - 同一个 `Node` 上的上传排队、一个一个传(ADR-35「2026-10 修订」:每个节点 1 个在上传、2 块在途),
13
+ * 免得「允许」「停止」之类的请求排在几 MB 的文件后面。
14
+ * - SDK 不缩放、不重编码图片,也不替 daemon 校验(daemon 是唯一的校验点;SDK 只挡掉明显不成形的 mime):调用方自己把图控制在
15
+ * 长边 ≤ 2000 px、单张 ≤ 约 1.5 MiB(硬上限:daemon 每个文件默认 10 MiB、每条消息合计 20 MiB;Claude 单张 base64 后约 5 MB)。
16
+ * - 下载:`blob.get` 按偏移分页拉(每段 ≤ 512 KiB),图片和其它文件一样。
12
17
  */
13
- import { type AttachmentRef } from '@anycon/protocol';
18
+ import { type AgentCapabilities, type AttachmentRef, type NodeCapabilities } from '@anycon/protocol';
14
19
  import type { Node } from './node.js';
15
- /** daemon 的上传白名单(agent 收不收还要看它的 `capabilities.attachments`)。 */
20
+ /** daemon 当作图片处理(核对文件头、读宽高、作为图片交给模型)的四种类型。 */
16
21
  export declare const IMAGE_MIME_TYPES: readonly ["image/png", "image/jpeg", "image/gif", "image/webp"];
17
22
  export type ImageMime = (typeof IMAGE_MIME_TYPES)[number];
23
+ /** 不知道类型时用的 mime(daemon 也这么约定)。 */
24
+ export declare const DEFAULT_FILE_MIME = "application/octet-stream";
18
25
  /** 同一个节点同时在途的块数(一块 512 KiB,base64 后约 700 KB)。 */
19
26
  export declare const MAX_CHUNKS_IN_FLIGHT = 2;
20
- export interface UploadImageOptions {
27
+ export interface UploadFileOptions {
21
28
  /** 展示用的文件名(1–255 字节,不含 `/` `\` 和控制字符)。daemon 不用它拼路径;扩展名和 mime 对不上时 daemon 会补上。 */
22
29
  name: string;
23
- /** `image/png` / `image/jpeg` / `image/gif` / `image/webp`。缺省按文件头(magic bytes)判断,认不出抛 `unsupported_image`。 */
24
- mime?: ImageMime | (string & {});
30
+ /**
31
+ * `type/subtype`(不带参数,大小写不敏感,发出去前转小写)。缺省时:文件头是四种图片之一就用它,否则按 `name` 的扩展名猜,
32
+ * 猜不出用 `application/octet-stream`。不成形的抛 `AnyconError('invalid_mime')`,什么都不发。
33
+ */
34
+ mime?: string;
25
35
  /** 中止上传:不再发块、尽力 `blob.discard`,以 `signal.reason` 失败。 */
26
36
  signal?: AbortSignal;
27
37
  /** 已确认的字节数 / 总字节数。从 `(0, total)` 开始,成功时以 `(total, total)` 结束。 */
@@ -29,6 +39,13 @@ export interface UploadImageOptions {
29
39
  /** 每块(和 `put_end`)的请求超时,默认 90 秒。 */
30
40
  requestTimeoutMs?: number;
31
41
  }
42
+ export interface UploadImageOptions extends UploadFileOptions {
43
+ /**
44
+ * `image/png` / `image/jpeg` / `image/gif` / `image/webp`(大小写不敏感)。缺省按文件头(magic bytes)判断;
45
+ * 认不出、或者给的不是这四种之一,抛 `AnyconError('unsupported_image')`,什么都不发。
46
+ */
47
+ mime?: ImageMime | (string & {});
48
+ }
32
49
  export interface DownloadOptions {
33
50
  signal?: AbortSignal;
34
51
  }
@@ -39,6 +56,34 @@ export interface DownloadedAttachment {
39
56
  }
40
57
  /** 按文件头判断图片类型(和 daemon 一样只比前缀,不解码)。认不出返回 `undefined`。 */
41
58
  export declare function detectImageMime(bytes: Uint8Array): ImageMime | undefined;
59
+ /** 规范化一个 mime:成形(`type/subtype`、不带参数、≤ 127 字节)就返回小写形式,否则 `undefined`。 */
60
+ export declare function normalizeMime(mime: string): string | undefined;
61
+ /**
62
+ * `uploadFile` 缺省 mime 时的猜法:文件头是四种图片之一 → 那种图片;否则按 `name` 的扩展名查一张常见类型的小表;
63
+ * 都不行 → `application/octet-stream`。只是猜,daemon 只核对四种图片的文件头。
64
+ */
65
+ export declare function guessMime(bytes: Uint8Array, name: string): string;
66
+ /**
67
+ * agent **原生**收不收 `mime` 类型的附件(`capabilities.attachments` 点名了它,不分大小写)。原生收的由 daemon 交给 adapter
68
+ * (图片作为图片给模型);别的附件 daemon 落到工作目录,见 `acceptsAttachment`。没有 `capabilities` / 列表为空 = 一个都不原生收。
69
+ */
70
+ export declare function isNativeAttachment(agent: {
71
+ capabilities?: Pick<AgentCapabilities, 'attachments'> | null;
72
+ }, mime: string): boolean;
73
+ /**
74
+ * 这个节点上的这个 agent 能不能收 `mime` 类型的附件:节点带 `capabilities.file_attachments`(`node.info()`,ADR-44)时任何类型都行
75
+ * ——agent 原生收的交给它,其余落到会话工作目录;旧节点(没有这个字段)只收 agent 原生收的类型(`isNativeAttachment`),
76
+ * 别的得到 `unsupported`。和 daemon 在 `session.send` / `session.create` 的核对一致。
77
+ */
78
+ export declare function acceptsAttachment(node: {
79
+ capabilities?: Partial<Pick<NodeCapabilities, 'blobs' | 'file_attachments'>> | null;
80
+ }, agent: {
81
+ capabilities?: Pick<AgentCapabilities, 'attachments'> | null;
82
+ }, mime: string): boolean;
83
+ /** @internal `uploadImage` 的 mime:给了就必须是四种图片之一,没给按文件头认。 */
84
+ export declare function resolveImageMime(bytes: Uint8Array, options: UploadImageOptions): ImageMime;
85
+ /** @internal `uploadFile` 的 mime:给了就校验成形并转小写,没给按 `guessMime` 猜。 */
86
+ export declare function resolveFileMime(bytes: Uint8Array, options: UploadFileOptions): string;
42
87
  /** 标准 base64(带 padding)。 */
43
88
  export declare function bytesToBase64(bytes: Uint8Array): string;
44
89
  export declare function base64ToBytes(data: string): Uint8Array;
@@ -46,8 +91,11 @@ export declare function base64ToBytes(data: string): Uint8Array;
46
91
  export declare function sha256Hex(bytes: Uint8Array): Promise<string>;
47
92
  /** 等 `p`,但 `signal` 中止时立刻放弃(在途的请求还会跑完,结果不再有人要)。 */
48
93
  export declare function raceAbort<T>(p: Promise<T>, signal: AbortSignal | undefined): Promise<T>;
49
- /** @internal `Node.uploadImage` 的实现(排队由 `Node` 负责)。 */
50
- export declare function uploadImage(node: Node, bytes: Uint8Array, options: UploadImageOptions): Promise<AttachmentRef>;
94
+ /**
95
+ * @internal `Node.uploadImage` / `Node.uploadFile` 共用的分块上传(排队由 `Node` 负责)。
96
+ * `mime` 已经由 `resolveImageMime` / `resolveFileMime` 定好。
97
+ */
98
+ export declare function uploadBlob(node: Node, bytes: Uint8Array, mime: string, options: UploadFileOptions): Promise<AttachmentRef>;
51
99
  /** @internal `Node.downloadAttachment` 的实现。 */
52
100
  export declare function downloadAttachment(node: Node, blobId: string, options?: DownloadOptions): Promise<DownloadedAttachment>;
53
101
  //# sourceMappingURL=attachments.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"attachments.d.ts","sourceRoot":"","sources":["../src/attachments.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,EAAmB,KAAK,aAAa,EAA2B,MAAM,kBAAkB,CAAA;AAG/F,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAErC,gEAAgE;AAChE,eAAO,MAAM,gBAAgB,iEAAkE,CAAA;AAC/F,MAAM,MAAM,SAAS,GAAG,CAAC,OAAO,gBAAgB,CAAC,CAAC,MAAM,CAAC,CAAA;AAEzD,iDAAiD;AACjD,eAAO,MAAM,oBAAoB,IAAI,CAAA;AAarC,MAAM,WAAW,kBAAkB;IACjC,kFAAkF;IAClF,IAAI,EAAE,MAAM,CAAA;IACZ,8GAA8G;IAC9G,IAAI,CAAC,EAAE,SAAS,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC,CAAA;IAChC,wDAAwD;IACxD,MAAM,CAAC,EAAE,WAAW,CAAA;IACpB,iEAAiE;IACjE,UAAU,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,KAAK,IAAI,CAAA;IAClD,oCAAoC;IACpC,gBAAgB,CAAC,EAAE,MAAM,CAAA;CAC1B;AAED,MAAM,WAAW,eAAe;IAC9B,MAAM,CAAC,EAAE,WAAW,CAAA;CACrB;AAED,MAAM,WAAW,oBAAoB;IACnC,wDAAwD;IACxD,GAAG,EAAE,aAAa,CAAA;IAClB,KAAK,EAAE,UAAU,CAAA;CAClB;AAID,yDAAyD;AACzD,wBAAgB,eAAe,CAAC,KAAK,EAAE,UAAU,GAAG,SAAS,GAAG,SAAS,CAQxE;AAED,4BAA4B;AAC5B,wBAAgB,aAAa,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CAQvD;AAED,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,UAAU,CAOtD;AAOD,6EAA6E;AAC7E,wBAAsB,SAAS,CAAC,KAAK,EAAE,UAAU,GAAG,OAAO,CAAC,MAAM,CAAC,CAUlE;AAMD,mDAAmD;AACnD,wBAAgB,SAAS,CAAC,CAAC,EAAE,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,WAAW,GAAG,SAAS,GAAG,OAAO,CAAC,CAAC,CAAC,CAQvF;AAoCD,uDAAuD;AACvD,wBAAsB,WAAW,CAC/B,IAAI,EAAE,IAAI,EACV,KAAK,EAAE,UAAU,EACjB,OAAO,EAAE,kBAAkB,GAC1B,OAAO,CAAC,aAAa,CAAC,CA8FxB;AAED,+CAA+C;AAC/C,wBAAsB,kBAAkB,CACtC,IAAI,EAAE,IAAI,EACV,MAAM,EAAE,MAAM,EACd,OAAO,GAAE,eAAoB,GAC5B,OAAO,CAAC,oBAAoB,CAAC,CAoC/B"}
1
+ {"version":3,"file":"attachments.d.ts","sourceRoot":"","sources":["../src/attachments.ts"],"names":[],"mappings":"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"}
@@ -1,19 +1,73 @@
1
1
  /**
2
- * 图片附件(ADR-35,docs/protocol.md § 5.6):经 blob 通道把图片传到 daemon,消息只带 `AttachmentRef`。
2
+ * 附件(ADR-35,docs/protocol.md § 5.6):经 blob 通道把文件传到 daemon,消息只带 `AttachmentRef`。
3
3
  *
4
+ * - 两个入口共用同一套分块上传:`uploadImage` 只传图片(`image/png|jpeg|gif|webp`,认不出抛 `unsupported_image`),
5
+ * `uploadFile` 传任意文件(mime 缺省时先按文件头认图片,再按扩展名猜,猜不出用 `application/octet-stream`)。
6
+ * 四种图片由 daemon 核对文件头、读宽高;其它文件 daemon 不看内容。agent 原生收的类型(`capabilities.attachments`,一般是图片)
7
+ * 交给 adapter,其余的由 daemon 复制进会话的工作目录、在发给 agent 的文字里附上路径(ADR-44);节点要有 `capabilities.file_attachments`
8
+ * 才收这些(`acceptsAttachment` 综合两者判断)。
4
9
  * - 上传:`blob.put_begin` → 每块 `chunk_size`(daemon 给,目前 512 KiB)的 `blob.put_chunk`,最多 2 块在途 →
5
- * `blob.put_end`,返回 daemon 记录的 `AttachmentRef`(含宽高)。每块都有答复:超时 / 掉线的块自己重试,不整张重传;
10
+ * `blob.put_end`,返回 daemon 记录的 `AttachmentRef`(图片含宽高)。每块都有答复:超时 / 掉线的块自己重试,不整个重传;
6
11
  * daemon 明确拒绝的不重试(块答 `finalizing` = `put_end` 已经接手,直接 `put_end` 拿结果)。失败或中止时尽力 `blob.discard`。
7
- * - 同一个 `Node` 上的上传排队、一张一张传(ADR-35「2026-10 修订」:每个节点 1 张在上传、2 块在途),
8
- * 免得「允许」「停止」之类的请求排在几 MB 的图后面。
9
- * - SDK 不缩放、不重编码图片,也不替 daemon 校验(daemon 是唯一的校验点):调用方自己把图控制在长边 ≤ 2000 px、
10
- * 单张 ≤ 约 1.5 MiB(硬上限:daemon 每张默认 10 MiB、每条消息合计 20 MiB;Claude 单张 base64 后约 5 MB)。
11
- * - 下载:`blob.get` 按偏移分页拉(每段 ≤ 512 KiB)。
12
+ * - 同一个 `Node` 上的上传排队、一个一个传(ADR-35「2026-10 修订」:每个节点 1 个在上传、2 块在途),
13
+ * 免得「允许」「停止」之类的请求排在几 MB 的文件后面。
14
+ * - SDK 不缩放、不重编码图片,也不替 daemon 校验(daemon 是唯一的校验点;SDK 只挡掉明显不成形的 mime):调用方自己把图控制在
15
+ * 长边 ≤ 2000 px、单张 ≤ 约 1.5 MiB(硬上限:daemon 每个文件默认 10 MiB、每条消息合计 20 MiB;Claude 单张 base64 后约 5 MB)。
16
+ * - 下载:`blob.get` 按偏移分页拉(每段 ≤ 512 KiB),图片和其它文件一样。
12
17
  */
13
- import { RpcTimeoutError } from '@anycon/protocol';
18
+ import { RpcTimeoutError, } from '@anycon/protocol';
14
19
  import { AnyconError, AttachmentError, NodeOffline } from './errors.js';
15
- /** daemon 的上传白名单(agent 收不收还要看它的 `capabilities.attachments`)。 */
20
+ /** daemon 当作图片处理(核对文件头、读宽高、作为图片交给模型)的四种类型。 */
16
21
  export const IMAGE_MIME_TYPES = ['image/png', 'image/jpeg', 'image/gif', 'image/webp'];
22
+ /** 不知道类型时用的 mime(daemon 也这么约定)。 */
23
+ export const DEFAULT_FILE_MIME = 'application/octet-stream';
24
+ /**
25
+ * `uploadFile` 缺省 mime 时按扩展名(小写,不带点)猜的表。故意不含四种图片:它们只按文件头认,
26
+ * 扩展名是 `.png` 但内容不是 PNG 的文件按 `application/octet-stream` 传,免得在 `put_end` 撞上 `mime_mismatch`。
27
+ */
28
+ const MIME_BY_EXTENSION = {
29
+ pdf: 'application/pdf',
30
+ txt: 'text/plain',
31
+ log: 'text/plain',
32
+ md: 'text/markdown',
33
+ markdown: 'text/markdown',
34
+ csv: 'text/csv',
35
+ tsv: 'text/tab-separated-values',
36
+ json: 'application/json',
37
+ html: 'text/html',
38
+ htm: 'text/html',
39
+ css: 'text/css',
40
+ xml: 'application/xml',
41
+ yaml: 'application/yaml',
42
+ yml: 'application/yaml',
43
+ toml: 'application/toml',
44
+ svg: 'image/svg+xml',
45
+ zip: 'application/zip',
46
+ gz: 'application/gzip',
47
+ tgz: 'application/gzip',
48
+ tar: 'application/x-tar',
49
+ js: 'text/javascript',
50
+ mjs: 'text/javascript',
51
+ cjs: 'text/javascript',
52
+ ts: 'text/x-typescript',
53
+ tsx: 'text/x-typescript',
54
+ jsx: 'text/javascript',
55
+ py: 'text/x-python',
56
+ rs: 'text/x-rust',
57
+ go: 'text/x-go',
58
+ java: 'text/x-java',
59
+ c: 'text/x-c',
60
+ h: 'text/x-c',
61
+ cpp: 'text/x-c++',
62
+ hpp: 'text/x-c++',
63
+ sh: 'application/x-sh',
64
+ sql: 'application/sql',
65
+ diff: 'text/x-diff',
66
+ patch: 'text/x-diff',
67
+ };
68
+ /** 和 daemon 一样:`type/subtype`,不带参数,≤ 127 字节。字符按 RFC 6838 的 restricted-name。 */
69
+ const MIME_PATTERN = /^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/;
70
+ const MAX_MIME_BYTES = 127;
17
71
  /** 同一个节点同时在途的块数(一块 512 KiB,base64 后约 700 KB)。 */
18
72
  export const MAX_CHUNKS_IN_FLIGHT = 2;
19
73
  /** 超时 / 掉线的块(和 `put_end`)再试几次。 */
@@ -41,6 +95,64 @@ export function detectImageMime(bytes) {
41
95
  return 'image/webp';
42
96
  return undefined;
43
97
  }
98
+ /** 规范化一个 mime:成形(`type/subtype`、不带参数、≤ 127 字节)就返回小写形式,否则 `undefined`。 */
99
+ export function normalizeMime(mime) {
100
+ const lower = mime.toLowerCase();
101
+ return lower.length <= MAX_MIME_BYTES && MIME_PATTERN.test(lower) ? lower : undefined;
102
+ }
103
+ /**
104
+ * `uploadFile` 缺省 mime 时的猜法:文件头是四种图片之一 → 那种图片;否则按 `name` 的扩展名查一张常见类型的小表;
105
+ * 都不行 → `application/octet-stream`。只是猜,daemon 只核对四种图片的文件头。
106
+ */
107
+ export function guessMime(bytes, name) {
108
+ const image = detectImageMime(bytes);
109
+ if (image)
110
+ return image;
111
+ const dot = name.lastIndexOf('.');
112
+ const ext = dot > 0 ? name.slice(dot + 1).toLowerCase() : '';
113
+ return MIME_BY_EXTENSION[ext] ?? DEFAULT_FILE_MIME;
114
+ }
115
+ /**
116
+ * agent **原生**收不收 `mime` 类型的附件(`capabilities.attachments` 点名了它,不分大小写)。原生收的由 daemon 交给 adapter
117
+ * (图片作为图片给模型);别的附件 daemon 落到工作目录,见 `acceptsAttachment`。没有 `capabilities` / 列表为空 = 一个都不原生收。
118
+ */
119
+ export function isNativeAttachment(agent, mime) {
120
+ const want = mime.toLowerCase();
121
+ return (agent.capabilities?.attachments ?? []).some((m) => m.toLowerCase() === want);
122
+ }
123
+ /**
124
+ * 这个节点上的这个 agent 能不能收 `mime` 类型的附件:节点带 `capabilities.file_attachments`(`node.info()`,ADR-44)时任何类型都行
125
+ * ——agent 原生收的交给它,其余落到会话工作目录;旧节点(没有这个字段)只收 agent 原生收的类型(`isNativeAttachment`),
126
+ * 别的得到 `unsupported`。和 daemon 在 `session.send` / `session.create` 的核对一致。
127
+ */
128
+ export function acceptsAttachment(node, agent, mime) {
129
+ return node.capabilities?.file_attachments === true || isNativeAttachment(agent, mime);
130
+ }
131
+ /** @internal `uploadImage` 的 mime:给了就必须是四种图片之一,没给按文件头认。 */
132
+ export function resolveImageMime(bytes, options) {
133
+ const accepted = `only ${IMAGE_MIME_TYPES.join(', ')} are accepted; use uploadFile() for other files`;
134
+ if (options.mime === undefined) {
135
+ const detected = detectImageMime(bytes);
136
+ if (detected)
137
+ return detected;
138
+ throw new AnyconError('unsupported_image', `cannot tell the image type of ${options.name} from its first bytes; pass mime (${accepted})`);
139
+ }
140
+ const mime = options.mime.toLowerCase();
141
+ if (!IMAGE_MIME_TYPES.includes(mime)) {
142
+ throw new AnyconError('unsupported_image', `${options.mime} is not an image type (${accepted})`);
143
+ }
144
+ return mime;
145
+ }
146
+ /** @internal `uploadFile` 的 mime:给了就校验成形并转小写,没给按 `guessMime` 猜。 */
147
+ export function resolveFileMime(bytes, options) {
148
+ if (options.mime === undefined)
149
+ return guessMime(bytes, options.name);
150
+ const mime = normalizeMime(options.mime);
151
+ if (mime === undefined) {
152
+ throw new AnyconError('invalid_mime', `${JSON.stringify(options.mime)} is not a valid mime type: expected type/subtype without parameters, at most ${MAX_MIME_BYTES} bytes (application/octet-stream if unknown)`);
153
+ }
154
+ return mime;
155
+ }
44
156
  /** 标准 base64(带 padding)。 */
45
157
  export function bytesToBase64(bytes) {
46
158
  const B = globalThis.Buffer;
@@ -117,16 +229,15 @@ async function withRetry(node, fn, signal) {
117
229
  function discardQuietly(node, blobId) {
118
230
  node.call('blob.discard', { blob_id: blobId }).catch(() => undefined);
119
231
  }
120
- /** @internal `Node.uploadImage` 的实现(排队由 `Node` 负责)。 */
121
- export async function uploadImage(node, bytes, options) {
232
+ /**
233
+ * @internal `Node.uploadImage` / `Node.uploadFile` 共用的分块上传(排队由 `Node` 负责)。
234
+ * `mime` 已经由 `resolveImageMime` / `resolveFileMime` 定好。
235
+ */
236
+ export async function uploadBlob(node, bytes, mime, options) {
122
237
  const { signal, onProgress } = options;
123
238
  const timeoutMs = options.requestTimeoutMs ?? UPLOAD_REQUEST_TIMEOUT_MS;
124
239
  if (signal?.aborted)
125
240
  throw abortReason(signal);
126
- const mime = options.mime ?? detectImageMime(bytes);
127
- if (mime === undefined) {
128
- throw new AnyconError('unsupported_image', `cannot tell the image type of ${options.name} from its first bytes; pass mime (only ${IMAGE_MIME_TYPES.join(', ')} are accepted)`);
129
- }
130
241
  const size = bytes.length;
131
242
  const sha256 = await sha256Hex(bytes);
132
243
  if (signal?.aborted)