@0gfoundation/0g-agentdna 0.2.3 → 0.5.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 (255) hide show
  1. package/GUIDE.md +190 -40
  2. package/OPERATORS.md +164 -0
  3. package/OPERATORS.zh.md +141 -0
  4. package/PROVIDERS.md +6 -0
  5. package/PROVIDERS.zh.md +3 -1
  6. package/README.md +84 -11
  7. package/dist/AgentClient.d.ts +374 -26
  8. package/dist/AgentClient.d.ts.map +1 -1
  9. package/dist/AgentClient.js +323 -40
  10. package/dist/AgentClient.js.map +1 -1
  11. package/dist/AgenticID.d.ts +170 -80
  12. package/dist/AgenticID.d.ts.map +1 -1
  13. package/dist/AgenticID.js +300 -42
  14. package/dist/AgenticID.js.map +1 -1
  15. package/dist/AttestorClient.d.ts +115 -31
  16. package/dist/AttestorClient.d.ts.map +1 -1
  17. package/dist/AttestorClient.js +276 -56
  18. package/dist/AttestorClient.js.map +1 -1
  19. package/dist/Credentials.d.ts +574 -0
  20. package/dist/Credentials.d.ts.map +1 -0
  21. package/dist/Credentials.js +838 -0
  22. package/dist/Credentials.js.map +1 -0
  23. package/dist/Operators.d.ts +60 -0
  24. package/dist/Operators.d.ts.map +1 -0
  25. package/dist/Operators.js +38 -0
  26. package/dist/Operators.js.map +1 -0
  27. package/dist/Providers.d.ts +13 -0
  28. package/dist/Providers.d.ts.map +1 -1
  29. package/dist/Providers.js +20 -1
  30. package/dist/Providers.js.map +1 -1
  31. package/dist/Releases.d.ts +51 -0
  32. package/dist/Releases.d.ts.map +1 -0
  33. package/dist/Releases.js +72 -0
  34. package/dist/Releases.js.map +1 -0
  35. package/dist/ReputationClient.d.ts +47 -3
  36. package/dist/ReputationClient.d.ts.map +1 -1
  37. package/dist/ReputationClient.js +204 -78
  38. package/dist/ReputationClient.js.map +1 -1
  39. package/dist/ServeProof.d.ts +70 -23
  40. package/dist/ServeProof.d.ts.map +1 -1
  41. package/dist/ServeProof.js +94 -35
  42. package/dist/ServeProof.js.map +1 -1
  43. package/dist/ServeSession.d.ts +17 -2
  44. package/dist/ServeSession.d.ts.map +1 -1
  45. package/dist/ServeSession.js +77 -9
  46. package/dist/ServeSession.js.map +1 -1
  47. package/dist/Settings.d.ts +25 -1
  48. package/dist/Settings.d.ts.map +1 -1
  49. package/dist/Settings.js +53 -1
  50. package/dist/Settings.js.map +1 -1
  51. package/dist/TrustRegistry.d.ts +28 -0
  52. package/dist/TrustRegistry.d.ts.map +1 -0
  53. package/dist/TrustRegistry.js +67 -0
  54. package/dist/TrustRegistry.js.map +1 -0
  55. package/dist/abi.d.ts +346 -34
  56. package/dist/abi.d.ts.map +1 -1
  57. package/dist/abi.js +150 -30
  58. package/dist/abi.js.map +1 -1
  59. package/dist/cli/attach.d.ts +79 -0
  60. package/dist/cli/attach.d.ts.map +1 -0
  61. package/dist/cli/attach.js +253 -0
  62. package/dist/cli/attach.js.map +1 -0
  63. package/dist/cli/commands/cells.d.ts +45 -0
  64. package/dist/cli/commands/cells.d.ts.map +1 -1
  65. package/dist/cli/commands/cells.js +77 -0
  66. package/dist/cli/commands/cells.js.map +1 -1
  67. package/dist/cli/commands/cred.d.ts +12 -0
  68. package/dist/cli/commands/cred.d.ts.map +1 -0
  69. package/dist/cli/commands/cred.js +43 -0
  70. package/dist/cli/commands/cred.js.map +1 -0
  71. package/dist/cli/commands/doctor.d.ts.map +1 -1
  72. package/dist/cli/commands/doctor.js +44 -35
  73. package/dist/cli/commands/doctor.js.map +1 -1
  74. package/dist/cli/commands/interactive.d.ts +597 -21
  75. package/dist/cli/commands/interactive.d.ts.map +1 -1
  76. package/dist/cli/commands/interactive.js +5082 -1323
  77. package/dist/cli/commands/interactive.js.map +1 -1
  78. package/dist/cli/commands/list.d.ts +5 -5
  79. package/dist/cli/commands/list.d.ts.map +1 -1
  80. package/dist/cli/commands/list.js +21 -26
  81. package/dist/cli/commands/list.js.map +1 -1
  82. package/dist/cli/commands/providers.d.ts +4 -0
  83. package/dist/cli/commands/providers.d.ts.map +1 -1
  84. package/dist/cli/commands/providers.js +19 -5
  85. package/dist/cli/commands/providers.js.map +1 -1
  86. package/dist/cli/commands/releases.d.ts +13 -0
  87. package/dist/cli/commands/releases.d.ts.map +1 -0
  88. package/dist/cli/commands/releases.js +65 -0
  89. package/dist/cli/commands/releases.js.map +1 -0
  90. package/dist/cli/commands/settings.d.ts +5 -0
  91. package/dist/cli/commands/settings.d.ts.map +1 -1
  92. package/dist/cli/commands/settings.js +70 -24
  93. package/dist/cli/commands/settings.js.map +1 -1
  94. package/dist/cli/commands/status.d.ts +2 -1
  95. package/dist/cli/commands/status.d.ts.map +1 -1
  96. package/dist/cli/commands/status.js +22 -19
  97. package/dist/cli/commands/status.js.map +1 -1
  98. package/dist/cli/config.d.ts +48 -1
  99. package/dist/cli/config.d.ts.map +1 -1
  100. package/dist/cli/config.js +114 -5
  101. package/dist/cli/config.js.map +1 -1
  102. package/dist/cli/credentials.d.ts +179 -0
  103. package/dist/cli/credentials.d.ts.map +1 -0
  104. package/dist/cli/credentials.js +1443 -0
  105. package/dist/cli/credentials.js.map +1 -0
  106. package/dist/cli/download.d.ts +21 -0
  107. package/dist/cli/download.d.ts.map +1 -0
  108. package/dist/cli/download.js +89 -0
  109. package/dist/cli/download.js.map +1 -0
  110. package/dist/cli/env.d.ts +6 -0
  111. package/dist/cli/env.d.ts.map +1 -1
  112. package/dist/cli/env.js +18 -6
  113. package/dist/cli/env.js.map +1 -1
  114. package/dist/cli/envelope.d.ts +4 -2
  115. package/dist/cli/envelope.d.ts.map +1 -1
  116. package/dist/cli/envelope.js +10 -6
  117. package/dist/cli/envelope.js.map +1 -1
  118. package/dist/cli/errors.d.ts +45 -1
  119. package/dist/cli/errors.d.ts.map +1 -1
  120. package/dist/cli/errors.js +77 -0
  121. package/dist/cli/errors.js.map +1 -1
  122. package/dist/cli/inference.d.ts.map +1 -1
  123. package/dist/cli/inference.js +7 -0
  124. package/dist/cli/inference.js.map +1 -1
  125. package/dist/cli/inkView.d.ts +341 -0
  126. package/dist/cli/inkView.d.ts.map +1 -0
  127. package/dist/cli/inkView.js +1019 -0
  128. package/dist/cli/inkView.js.map +1 -0
  129. package/dist/cli/legacy/modelKey.d.ts +24 -0
  130. package/dist/cli/legacy/modelKey.d.ts.map +1 -0
  131. package/dist/cli/legacy/modelKey.js +32 -0
  132. package/dist/cli/legacy/modelKey.js.map +1 -0
  133. package/dist/cli/livePrompt.d.ts +212 -0
  134. package/dist/cli/livePrompt.d.ts.map +1 -0
  135. package/dist/cli/livePrompt.js +576 -0
  136. package/dist/cli/livePrompt.js.map +1 -0
  137. package/dist/cli/main.js +206 -72
  138. package/dist/cli/main.js.map +1 -1
  139. package/dist/cli/modelkey.d.ts +64 -0
  140. package/dist/cli/modelkey.d.ts.map +1 -0
  141. package/dist/cli/modelkey.js +113 -0
  142. package/dist/cli/modelkey.js.map +1 -0
  143. package/dist/cli/outboxSync.d.ts +51 -0
  144. package/dist/cli/outboxSync.d.ts.map +1 -0
  145. package/dist/cli/outboxSync.js +210 -0
  146. package/dist/cli/outboxSync.js.map +1 -0
  147. package/dist/cli/plain.d.ts +46 -0
  148. package/dist/cli/plain.d.ts.map +1 -0
  149. package/dist/cli/plain.js +260 -0
  150. package/dist/cli/plain.js.map +1 -0
  151. package/dist/cli/proofs.d.ts +5 -0
  152. package/dist/cli/proofs.d.ts.map +1 -1
  153. package/dist/cli/proofs.js +20 -0
  154. package/dist/cli/proofs.js.map +1 -1
  155. package/dist/cli/ref.d.ts.map +1 -1
  156. package/dist/cli/ref.js +3 -2
  157. package/dist/cli/ref.js.map +1 -1
  158. package/dist/cli/releaseNotice.d.ts +64 -0
  159. package/dist/cli/releaseNotice.d.ts.map +1 -0
  160. package/dist/cli/releaseNotice.js +194 -0
  161. package/dist/cli/releaseNotice.js.map +1 -0
  162. package/dist/cli/sdk.d.ts +18 -0
  163. package/dist/cli/sdk.d.ts.map +1 -1
  164. package/dist/cli/sdk.js +99 -1
  165. package/dist/cli/sdk.js.map +1 -1
  166. package/dist/cli/settings.d.ts +90 -9
  167. package/dist/cli/settings.d.ts.map +1 -1
  168. package/dist/cli/settings.js +273 -21
  169. package/dist/cli/settings.js.map +1 -1
  170. package/dist/cli/textfit.d.ts +28 -0
  171. package/dist/cli/textfit.d.ts.map +1 -0
  172. package/dist/cli/textfit.js +111 -0
  173. package/dist/cli/textfit.js.map +1 -0
  174. package/dist/constants.d.ts +1 -1
  175. package/dist/constants.js +1 -1
  176. package/dist/context.d.ts +26 -0
  177. package/dist/context.d.ts.map +1 -1
  178. package/dist/context.js +1 -0
  179. package/dist/context.js.map +1 -1
  180. package/dist/index.d.ts +19 -11
  181. package/dist/index.d.ts.map +1 -1
  182. package/dist/index.js +35 -2
  183. package/dist/index.js.map +1 -1
  184. package/dist/legacy/modelKey.d.ts +67 -0
  185. package/dist/legacy/modelKey.d.ts.map +1 -0
  186. package/dist/legacy/modelKey.js +80 -0
  187. package/dist/legacy/modelKey.js.map +1 -0
  188. package/dist/legacy/serveProofV1.d.ts +56 -0
  189. package/dist/legacy/serveProofV1.d.ts.map +1 -0
  190. package/dist/legacy/serveProofV1.js +91 -0
  191. package/dist/legacy/serveProofV1.js.map +1 -0
  192. package/dist/provider-catalog.json +3 -2
  193. package/dist/secretEnv.d.ts +18 -3
  194. package/dist/secretEnv.d.ts.map +1 -1
  195. package/dist/secretEnv.js +16 -2
  196. package/dist/secretEnv.js.map +1 -1
  197. package/dist/types.d.ts +63 -1
  198. package/dist/types.d.ts.map +1 -1
  199. package/dist/viemErrors.d.ts +30 -0
  200. package/dist/viemErrors.d.ts.map +1 -0
  201. package/dist/viemErrors.js +36 -0
  202. package/dist/viemErrors.js.map +1 -0
  203. package/package.json +5 -1
  204. package/src/AgentClient.ts +622 -68
  205. package/src/AgenticID.ts +345 -56
  206. package/src/AttestorClient.ts +330 -83
  207. package/src/Credentials.ts +1027 -0
  208. package/src/Operators.ts +71 -0
  209. package/src/Providers.ts +20 -0
  210. package/src/Releases.ts +95 -0
  211. package/src/ReputationClient.ts +231 -79
  212. package/src/ServeProof.ts +123 -39
  213. package/src/ServeSession.ts +91 -9
  214. package/src/Settings.ts +61 -1
  215. package/src/TrustRegistry.ts +75 -0
  216. package/src/abi.ts +153 -30
  217. package/src/cli/attach.ts +257 -0
  218. package/src/cli/commands/cells.ts +104 -0
  219. package/src/cli/commands/cred.ts +44 -0
  220. package/src/cli/commands/doctor.ts +45 -37
  221. package/src/cli/commands/interactive.ts +4120 -664
  222. package/src/cli/commands/list.ts +21 -30
  223. package/src/cli/commands/providers.ts +17 -4
  224. package/src/cli/commands/releases.ts +60 -0
  225. package/src/cli/commands/settings.ts +75 -28
  226. package/src/cli/commands/status.ts +24 -21
  227. package/src/cli/config.ts +119 -4
  228. package/src/cli/credentials.ts +1379 -0
  229. package/src/cli/download.ts +80 -0
  230. package/src/cli/env.ts +22 -7
  231. package/src/cli/envelope.ts +10 -6
  232. package/src/cli/errors.ts +92 -0
  233. package/src/cli/inference.ts +8 -1
  234. package/src/cli/inkView.ts +969 -0
  235. package/src/cli/legacy/modelKey.ts +35 -0
  236. package/src/cli/livePrompt.ts +615 -0
  237. package/src/cli/main.ts +206 -76
  238. package/src/cli/modelkey.ts +124 -0
  239. package/src/cli/outboxSync.ts +231 -0
  240. package/src/cli/plain.ts +260 -0
  241. package/src/cli/proofs.ts +27 -0
  242. package/src/cli/ref.ts +5 -4
  243. package/src/cli/releaseNotice.ts +200 -0
  244. package/src/cli/sdk.ts +87 -7
  245. package/src/cli/settings.ts +275 -25
  246. package/src/cli/textfit.ts +95 -0
  247. package/src/constants.ts +1 -1
  248. package/src/context.ts +28 -0
  249. package/src/index.ts +50 -7
  250. package/src/legacy/modelKey.ts +80 -0
  251. package/src/legacy/serveProofV1.ts +124 -0
  252. package/src/provider-catalog.json +3 -2
  253. package/src/secretEnv.ts +18 -3
  254. package/src/types.ts +60 -1
  255. package/src/viemErrors.ts +39 -0
@@ -19,6 +19,25 @@
19
19
  import { proofFromResponse, requestBytesOf, normalizedMethod, type TaskExchange } from './ServeSession';
20
20
  import type { ServeProof } from './types';
21
21
 
22
+ /** What a task id the agent returns must look like to be handed out. */
23
+ const TASK_ID = /^[A-Za-z0-9_.:-]{1,128}$/;
24
+
25
+ /**
26
+ * Text from the agent (an activity label, an error it sent) made one plain
27
+ * line for display: escape sequences, control characters and bidi controls
28
+ * removed, so a program that prints it cannot have its terminal restyled.
29
+ */
30
+ export function plainText(s: string): string {
31
+ return s
32
+ .replace(/\u001b\[[0-?]*[ -/]*[@-~]/g, '')
33
+ .replace(/\u009b[0-?]*[ -/]*[@-~]/g, '')
34
+ .replace(/\u001b\][^\u0007\u001b\u009c]*(?:\u0007|\u001b\\|\u009c)?/g, '')
35
+ .replace(/\u001b[PX^_][^\u001b\u009c]*(?:\u001b\\|\u009c)?/g, '')
36
+ // eslint-disable-next-line no-control-regex
37
+ .replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g, ' ')
38
+ .replace(/[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g, '');
39
+ }
40
+
22
41
  /**
23
42
  * One agent-registered service, as listed in `/hello`'s `services` array.
24
43
  * These are exact `/api/*` paths the agent's own code serves; they are not
@@ -120,6 +139,189 @@ export interface ChatMessage {
120
139
  content: string;
121
140
  }
122
141
 
142
+ /**
143
+ * An image sent with a message (`images` on {@link AgentClient.chat} /
144
+ * {@link AgentClient.chatStream}): PNG, JPEG, WebP or GIF, its bytes in
145
+ * base64. 0g-harness takes at most 8 per message, 10 MiB each and 32 MiB
146
+ * together; other frameworks may ignore or refuse them.
147
+ */
148
+ export interface ChatImage {
149
+ mediaType: 'image/png' | 'image/jpeg' | 'image/webp' | 'image/gif';
150
+ data: string;
151
+ /** Its file name on the owner's side (`flag test.png`). Sent as the part's
152
+ * `filename` only to an agent that says it reads one (0g-harness
153
+ * `GET /v1/harness` → `features.image_names`): a model that cannot view
154
+ * images gets the file under this name in `~/inbox`. */
155
+ name?: string;
156
+ }
157
+
158
+ /**
159
+ * What the agent's runtime says about a message it took (`onNotice`,
160
+ * 0g-harness): the owner's model cannot view images, so the images were saved
161
+ * as files in the agent's file inbox `~/inbox` instead; or the turn left files new or
162
+ * changed in the agent's `~/outbox`, for the owner to download
163
+ * ({@link AgentClient.downloadFile}).
164
+ */
165
+ export interface ChatNotice {
166
+ imagesSavedAsFiles?: string[];
167
+ /** Names of files in the outbox (`downloadFile('outbox', name)`). */
168
+ outboxFiles?: string[];
169
+ }
170
+
171
+ /** A file the owner can download ({@link AgentClient.listFiles}). */
172
+ export interface AgentFile {
173
+ name: string;
174
+ bytes: number;
175
+ /** ISO 8601. */
176
+ mtime: string;
177
+ /** Hex; given for files up to 4 MiB. */
178
+ sha256?: string;
179
+ }
180
+
181
+ /** Where a download comes from: what the agent handed over, or what the owner uploaded. */
182
+ export type AgentFileDir = 'outbox' | 'inbox';
183
+
184
+ /** A file the owner sent ({@link AgentClient.uploadFile}): where it landed. */
185
+ export interface UploadedFile {
186
+ /** Absolute path in the agent's container (in its file inbox, `~/inbox`). */
187
+ path: string;
188
+ bytes: number;
189
+ }
190
+
191
+ /** What {@link AgentClient.steer} did with the owner's text. */
192
+ export interface SteerResult {
193
+ /** true: read in the running owner turn `turn`, before its next model
194
+ * call. false: no owner turn was running, so it is an ordinary turn,
195
+ * `queued` (follow it like any response); `reason` says why. */
196
+ merged: boolean;
197
+ /** The steered message's id, for {@link AgentClient.steerState} (merged only). */
198
+ id?: string;
199
+ turn?: string;
200
+ queued?: string;
201
+ reason?: string;
202
+ }
203
+
204
+ /** One of the owner's sessions on 0g-harness (zgh-style; {@link AgentClient.sessions}). */
205
+ export interface AgentSession {
206
+ id: string;
207
+ object?: 'session';
208
+ /** owner: the default `owner-chat`; session: one the owner opened; task: a task's session. */
209
+ kind: 'owner' | 'session' | 'task';
210
+ title: string;
211
+ /** running: a turn is open. idle: loaded. stored: unloaded, resumes on its next prompt. */
212
+ state: 'running' | 'idle' | 'stored';
213
+ created_at: number;
214
+ updated_at: number;
215
+ forked_from?: string;
216
+ }
217
+
218
+ /** What {@link AgentClient.promptSession} did with a message. */
219
+ export interface SessionPromptResult {
220
+ /** false: the message is the session's next turn, record `id` (follow it
221
+ * with {@link AgentClient.followTask}). true (mode steer): read in the
222
+ * running turn `turn`, before its next model call; `id` is the steer's id. */
223
+ merged: boolean;
224
+ id: string;
225
+ session?: string;
226
+ turn?: string;
227
+ /** Why a steer was queued instead (no turn running). */
228
+ reason?: string;
229
+ }
230
+
231
+ /** A task's state on 0g-harness (zgh's task model; {@link AgentClient.getTask}). */
232
+ export type HarnessTaskState = 'queued' | 'working' | 'idle' | 'needs-input' | 'done' | 'failed' | 'archived';
233
+
234
+ /**
235
+ * One outcome record a task's agent made: `raise_question` and
236
+ * `request_action` end in `needs-input` and close when the owner answers;
237
+ * `report_complete` ends in `done` and closes when the next run starts.
238
+ * `arguments` is the agent's own text: clean it before printing it.
239
+ */
240
+ export interface HarnessTaskRecord {
241
+ id: number;
242
+ run: number;
243
+ tool: string;
244
+ ends_in: 'needs-input' | 'done';
245
+ closes_on: 'answer' | 'next-run';
246
+ arguments: Record<string, unknown>;
247
+ at: number;
248
+ state: 'open' | 'closed';
249
+ closed?: { how: string; at: number };
250
+ }
251
+
252
+ /** What the task feed carries of a task ({@link AgentClient.taskFeed}). */
253
+ export interface HarnessTaskSummary {
254
+ id: string;
255
+ state: HarnessTaskState;
256
+ /** For `failed`: `error` (the last turn failed, or the watchdog stopped the run) or `interrupted` (a restart). */
257
+ reason: string | null;
258
+ /** The latest run's records. */
259
+ outcome: HarnessTaskRecord[];
260
+ /** The done record that sealed a working run, else null. */
261
+ sealed: number | null;
262
+ /** The records still open. */
263
+ records: HarnessTaskRecord[];
264
+ runs: { count: number; last?: { started_at: number; ended_at?: number; end?: string; error?: string; records: number } };
265
+ updated_at: number;
266
+ /** In the feed: what changed (`created`, `run-started`, `recorded`, `input`, `run-ended`, `cancelled`, `archived`). */
267
+ change?: string;
268
+ }
269
+
270
+ /** A task on 0g-harness: a piece of work with its own session, workspace, state and outcome records. */
271
+ export interface HarnessTask extends HarnessTaskSummary {
272
+ object?: 'task';
273
+ title: string;
274
+ prompt: string;
275
+ workspace: { path: string };
276
+ session_id: string;
277
+ /** Inputs waiting for the next run. */
278
+ pending: number;
279
+ outcome_tools: string[];
280
+ metadata: Record<string, unknown>;
281
+ created_at: number;
282
+ queued_at?: number;
283
+ }
284
+
285
+ /** What {@link AgentClient.createTask} takes. */
286
+ export interface CreateTaskOptions {
287
+ prompt: string;
288
+ /** `task-` and 1 to 63 lowercase letters, digits or `-`: makes the create idempotent. */
289
+ id?: string;
290
+ title?: string;
291
+ /** An existing directory under the agent's home; default `~/tasks/<id>`. */
292
+ workspace?: { dir: string };
293
+ /** Added to the task agent's system prompt. */
294
+ instructions?: string;
295
+ /** true (all built-ins, the default), false (none), or built-in names. */
296
+ outcome_tools?: boolean | string[];
297
+ metadata?: Record<string, unknown>;
298
+ }
299
+
300
+ /** What {@link AgentClient.taskInput} did with the input. */
301
+ export interface TaskInputResult extends HarnessTask {
302
+ /** current-run: steered into the running turn (`steer` is its id), or the run's next turn.
303
+ * next-run: the run is sealed by a done record. queued: it starts or waits for a run. */
304
+ delivery: 'current-run' | 'next-run' | 'queued';
305
+ steer?: string;
306
+ }
307
+
308
+ /** One event of {@link AgentClient.taskFeed}: a task's state, or `ready` once every task was sent. */
309
+ export type HarnessTaskFeedEvent = { type: 'task'; task: HarnessTaskSummary } | { type: 'ready' };
310
+
311
+ /** What became of a steered text ({@link AgentClient.steerState}). */
312
+ export interface SteerState {
313
+ id: string;
314
+ /** pending: not read yet. merged: read in `turn`. turn: the turn it was
315
+ * meant for ended first, so it opened `turn`, an owner turn of its own.
316
+ * dropped: an interrupt, or a cancel of its turn, came first (a cancel
317
+ * drops them from 0g-harness #12 on; an older one leaves them pending and
318
+ * gives them to the next turn). */
319
+ state: 'pending' | 'merged' | 'turn' | 'dropped';
320
+ turn: string;
321
+ /** The text as sent (0g-harness #12 on). */
322
+ text?: string;
323
+ }
324
+
123
325
  /**
124
326
  * Snapshot of one long-running task (a "response" in OpenAI Responses API
125
327
  * terms) on the agent. Returned by {@link AgentClient.task} /
@@ -131,6 +333,8 @@ export interface AgentTask {
131
333
  /** Assistant text produced so far (full text once completed). */
132
334
  output_text: string;
133
335
  error?: { message: string };
336
+ /** Runtime notices about the message that opened it (0g-harness). */
337
+ harness?: { images_saved_as_files?: string[]; outbox_files?: string[] };
134
338
  }
135
339
 
136
340
  export interface ChatCompletion {
@@ -139,15 +343,16 @@ export interface ChatCompletion {
139
343
  }
140
344
 
141
345
  /**
142
- * One unit of work on the agent, as its task list shows it
143
- * ({@link AgentClient.tasks}): a turn of its conversation, a background
346
+ * One thing that runs or ran on the agent, as its activity list shows it
347
+ * ({@link AgentClient.activities}): a turn of its conversation, a background
144
348
  * command, or a subagent. `actor` says who does the work, `trigger` who asked
145
- * for it.
349
+ * for it. ("Task" is kept for zgh-style tasks: a unit of work with its own
350
+ * session, state and outcome.)
146
351
  */
147
- export interface AgentTaskInfo {
352
+ export interface AgentActivityInfo {
148
353
  /** A turn: `resp_…` (the id {@link AgentClient.task} and
149
- * {@link AgentClient.followTask} take). A command: `bash-N`. A subagent:
150
- * `subagent-N`. */
354
+ * {@link AgentClient.followTask} take). A command: `bash-<hex>`. A
355
+ * subagent: its session id (a UUID). */
151
356
  id: string;
152
357
  type: 'turn' | 'command' | 'subagent';
153
358
  status: AgentTask['status'];
@@ -156,7 +361,14 @@ export interface AgentTaskInfo {
156
361
  /** Who asked. A turn: `user` | `job` | `schedule` | `plugin`. A command or
157
362
  * a subagent: `agent` (the main agent started it). */
158
363
  trigger: string;
159
- /** What the task is: the prompt, the job notice, the reminder's text. */
364
+ /** A turn: the session it ran in (`owner-chat`, another of the owner's, a task's). */
365
+ session?: string;
366
+ /** A command or subagent (0g-harness #12 on): the turn that started it,
367
+ * who asked for that turn (`user` for an owner turn) and its session. */
368
+ parent_turn?: string;
369
+ parent_trigger?: string;
370
+ parent_session?: string;
371
+ /** What the activity is: the prompt, the job notice, the reminder's text. */
160
372
  label: string;
161
373
  /** Unix seconds. */
162
374
  created_at: number;
@@ -166,17 +378,23 @@ export interface AgentTaskInfo {
166
378
  detail?: string;
167
379
  /** Notices that reached the agent while this turn ran, merged into it. */
168
380
  merged_notices?: string[];
169
- /** {@link AgentClient.taskInfo} only: a turn's text, or a finished
381
+ /** {@link AgentClient.activity} only: a turn's text, or a finished
170
382
  * subagent's final answer. A command's output is never returned. */
171
383
  output_text?: string;
172
384
  }
173
385
 
174
- /** What stopping one task did ({@link AgentClient.stopTask}). */
175
- export interface AgentTaskStop {
386
+ /** @deprecated Renamed {@link AgentActivityInfo}. */
387
+ export type AgentTaskInfo = AgentActivityInfo;
388
+
389
+ /** What stopping one activity did ({@link AgentClient.stopActivity}). */
390
+ export interface AgentActivityStop {
176
391
  id: string;
177
392
  outcome: 'cancelled' | 'already-finished' | 'not-running';
178
393
  }
179
394
 
395
+ /** @deprecated Renamed {@link AgentActivityStop}. */
396
+ export type AgentTaskStop = AgentActivityStop;
397
+
180
398
  /**
181
399
  * The words of a turn the agent opened itself (a background job finished, a
182
400
  * reminder came due), kept in the agent's inbox until the owner reads them.
@@ -231,8 +449,8 @@ export interface AgentSchedule {
231
449
  *
232
450
  * | type | data |
233
451
  * |---|---|
234
- * | `turn.queued` / `turn.started` / `turn.completed` / `turn.failed` / `turn.cancelled` | an {@link AgentTaskInfo} (a turn) |
235
- * | `task.updated` | an {@link AgentTaskInfo} (a command or a subagent) |
452
+ * | `turn.queued` / `turn.started` / `turn.completed` / `turn.failed` / `turn.cancelled` | an {@link AgentActivityInfo} (a turn) |
453
+ * | `activity.updated` | an {@link AgentActivityInfo} (a command or a subagent); a runtime from before the rename sends it as `task.updated` |
236
454
  * | `inbox.message` | an {@link AgentInboxMessage} |
237
455
  * | `inbox.read` | `{ read_through }` |
238
456
  * | `schedule.changed` | `{ operation: "create" \| "delete" \| "dispatch", id }` |
@@ -240,7 +458,7 @@ export interface AgentSchedule {
240
458
  *
241
459
  * `reset` means the agent could not serve the position asked for (it is
242
460
  * older than the agent's in-memory window, or from before a `/clear`):
243
- * re-read the inbox, tasks and schedules; the feed carries on from `cursor`.
461
+ * re-read the inbox, activities and schedules; the feed carries on from `cursor`.
244
462
  * A type this list does not name is passed through as it came.
245
463
  */
246
464
  export interface AgentEvent {
@@ -301,7 +519,14 @@ export interface AgentClient {
301
519
  * the agent; the completion is reassembled before returning, so the shape is
302
520
  * a plain {@link ChatCompletion}.
303
521
  */
304
- chat?(messages: ChatMessage[], opts?: { model?: string; signal?: AbortSignal }): Promise<ChatCompletion>;
522
+ chat?(messages: ChatMessage[], opts?: {
523
+ model?: string;
524
+ signal?: AbortSignal;
525
+ /** Images sent with the last user message (see {@link ChatImage}). */
526
+ images?: ChatImage[];
527
+ /** The runtime's notices about this message (see {@link ChatNotice}). */
528
+ onNotice?: (notice: ChatNotice) => void;
529
+ }): Promise<ChatCompletion>;
305
530
  /**
306
531
  * Like {@link chat}, but yields each content delta as it is generated — for
307
532
  * a live-typing UI. Present under the same conditions as `chat`.
@@ -317,6 +542,10 @@ export interface AgentClient {
317
542
  chatStream?(messages: ChatMessage[], opts?: {
318
543
  model?: string;
319
544
  signal?: AbortSignal;
545
+ /** Images sent with the last user message (see {@link ChatImage}). */
546
+ images?: ChatImage[];
547
+ /** The runtime's notices about this message (see {@link ChatNotice}). */
548
+ onNotice?: (notice: ChatNotice) => void;
320
549
  /** Tool-activity progress, when the agent's bridge streams it (SSE
321
550
  * ": activity tool/call <name>" comments — 0g-harness does). Labels like
322
551
  * "tool/call bash", "tool/result", "turn/end". Advisory: absence just
@@ -406,29 +635,128 @@ export interface AgentClient {
406
635
  * Everything running or that has run on the agent, newest first: turns,
407
636
  * background commands and subagents, with who does each (`actor`) and who
408
637
  * asked (`trigger`). `status` filters: `"active"` (queued or running) or one
409
- * status name. Present only when the agent declares a `kind: "tasks"` route
410
- * and this handle holds the owner token.
638
+ * status name. Present only when the agent declares a `kind: "activities"`
639
+ * route (or, on a runtime from before the rename, `kind: "tasks"`) and this
640
+ * handle holds the owner token. Reads `/v1/activities`, and the deprecated
641
+ * `/v1/tasks` when an older harness answers 404 there.
411
642
  */
412
- tasks?(opts?: { status?: string; limit?: number }): Promise<AgentTaskInfo[]>;
413
- /** One task of {@link tasks}, by id, with its `output_text` where there
414
- * is one. Present under the same conditions as {@link tasks}. */
415
- taskInfo?(id: string): Promise<AgentTaskInfo>;
643
+ activities?(opts?: { status?: string; limit?: number }): Promise<AgentActivityInfo[]>;
644
+ /** One activity of {@link activities}, by id, with its `output_text` where
645
+ * there is one. Present under the same conditions as {@link activities}. */
646
+ activity?(id: string): Promise<AgentActivityInfo>;
416
647
  /**
417
- * Stop one task of {@link tasks}: a turn is cancelled (a queued one never
418
- * starts), a command or subagent is killed. Already-executed actions are
419
- * not rolled back. Present under the same conditions as {@link tasks}.
648
+ * Stop one activity of {@link activities}: a turn is cancelled (a queued
649
+ * one never starts), a command or subagent is killed. Already-executed
650
+ * actions are not rolled back. Present under the same conditions as
651
+ * {@link activities}.
420
652
  */
421
- stopTask?(id: string): Promise<AgentTaskStop>;
653
+ stopActivity?(id: string): Promise<AgentActivityStop>;
422
654
  /** Stop everything: queued turns first, then the running turn, then every
423
655
  * running command and subagent. Present under the same conditions as
424
- * {@link tasks}. */
425
- stopAllTasks?(): Promise<AgentTaskStop[]>;
656
+ * {@link activities}. */
657
+ stopAllActivities?(): Promise<AgentActivityStop[]>;
658
+ /** @deprecated Renamed {@link activities}. */
659
+ tasks?(opts?: { status?: string; limit?: number }): Promise<AgentActivityInfo[]>;
660
+ /** @deprecated Renamed {@link activity}. */
661
+ taskInfo?(id: string): Promise<AgentActivityInfo>;
662
+ /** @deprecated Renamed {@link stopActivity}. */
663
+ stopTask?(id: string): Promise<AgentActivityStop>;
664
+ /** @deprecated Renamed {@link stopAllActivities}. */
665
+ stopAllTasks?(): Promise<AgentActivityStop[]>;
426
666
  /**
427
667
  * The reminders the agent set for itself. `enabled: false` means the
428
668
  * agent's reminders are switched off. Present only when the agent declares
429
669
  * a `kind: "schedules"` route and this handle holds the owner token.
430
670
  */
431
671
  schedules?(): Promise<{ enabled: boolean; data: AgentSchedule[] }>;
672
+ /**
673
+ * Send the agent a file: it lands in the agent's file inbox `~/inbox` (a new
674
+ * name, never over an existing file; container-local, lost on a reset),
675
+ * and the agent reads it with its own tools — tell it the returned path.
676
+ * At most 25 MiB. Present only when the agent declares a `kind: "files"`
677
+ * route (0g-harness) and this handle holds the owner token.
678
+ */
679
+ uploadFile?(name: string, data: Uint8Array): Promise<UploadedFile>;
680
+ /**
681
+ * The owner's word for the turn already running: the agent reads it before
682
+ * that turn's next model call — when the current model answer or tool call
683
+ * finishes, not in the middle of a long command. With no owner turn
684
+ * running it is queued as an ordinary turn (`merged: false`). Present only
685
+ * when the agent declares a `kind: "steer"` route (0g-harness) and this
686
+ * handle holds the owner token.
687
+ */
688
+ steer?(text: string): Promise<SteerResult>;
689
+ /**
690
+ * The owner's sessions, most recently used first (0g-harness, kind
691
+ * `sessions`): `owner-chat` (the default, behind chat/Responses) and the
692
+ * ones the owner opened. Each is its own conversation; all share the
693
+ * agent's persona, skills, memory and credentials.
694
+ */
695
+ sessions?(): Promise<AgentSession[]>;
696
+ /** One session. Present with {@link sessions}. */
697
+ session?(id: string): Promise<AgentSession>;
698
+ /**
699
+ * Open a session: fresh, or a `fork` of another session's history (its
700
+ * first `at` events when given). `resume` loads an existing one instead.
701
+ * Present with {@link sessions}.
702
+ */
703
+ createSession?(opts?: { title?: string; fork?: string; at?: number; resume?: string }): Promise<AgentSession>;
704
+ /**
705
+ * Send a session a message: its next turn (`mode: 'next'`, the default),
706
+ * or a steer into its running turn (`'steer'`). Present with {@link sessions}.
707
+ */
708
+ promptSession?(id: string, text: string, opts?: { mode?: 'next' | 'steer' }): Promise<SessionPromptResult>;
709
+ /** Stop a session's running turn. Present with {@link sessions}. */
710
+ cancelSession?(id: string): Promise<{ cancelled: string | null; session: string }>;
711
+ /**
712
+ * Hand the agent a task (0g-harness, zgh's task model): it runs in a
713
+ * session and workspace of its own and ends each run with an outcome
714
+ * record. With an `id` already taken, the existing task comes back with
715
+ * `created: false`. Present only when the agent declares the `tasks` and
716
+ * `task-feed` kinds and this handle holds the owner token.
717
+ */
718
+ createTask?(opts: CreateTaskOptions): Promise<{ task: HarnessTask; created: boolean }>;
719
+ /** Tasks, newest first; `state` and `metadata` filter. Present with {@link createTask}. */
720
+ listTasks?(opts?: { state?: HarnessTaskState | HarnessTaskState[]; metadata?: Record<string, string>; limit?: number }): Promise<HarnessTask[]>;
721
+ /** One task. Present with {@link createTask}. */
722
+ getTask?(id: string): Promise<HarnessTask>;
723
+ /**
724
+ * Input for a task: to a resting task it starts a run; to a working one
725
+ * `mode: 'steer'` (the default) reaches the running turn and `'next'` is
726
+ * the run's next turn (the next run's once a done record sealed it). It
727
+ * answers the task's open questions. Present with {@link createTask}.
728
+ */
729
+ taskInput?(id: string, text: string, opts?: { mode?: 'steer' | 'next' }): Promise<TaskInputResult>;
730
+ /** Stop a task's run (or take it out of the queue); input waiting is dropped. Present with {@link createTask}. */
731
+ cancelTaskRun?(id: string): Promise<HarnessTask>;
732
+ /** Archive a task: stopped, records closed, agent disposed; its workspace stays. Present with {@link createTask}. */
733
+ archiveTask?(id: string): Promise<HarnessTask>;
734
+ /**
735
+ * Every task's changes: one `task` event per task not archived, then
736
+ * `ready`, then one per change. One connection: it ends when the stream
737
+ * does (reconnect and re-read on `ready`). Present with {@link createTask}.
738
+ */
739
+ taskFeed?(opts?: { signal?: AbortSignal }): AsyncGenerator<HarnessTaskFeedEvent>;
740
+ /** What became of a text {@link steer} merged. Present with {@link steer}. */
741
+ steerState?(id: string): Promise<SteerState>;
742
+ /**
743
+ * The files the owner can download, newest first: what the agent put in its
744
+ * `~/outbox` (the default) or what the owner sent (`'inbox'`, the file inbox
745
+ * `~/inbox` — not the message inbox, {@link AgentClient.inbox}). Both are
746
+ * container-local and lost on a reset. Present only when the agent declares
747
+ * a `kind: "files"` route (0g-harness) and this handle holds the owner token;
748
+ * an agent whose runtime predates downloads answers with an error saying so.
749
+ */
750
+ listFiles?(dir?: AgentFileDir): Promise<AgentFile[]>;
751
+ /** One file's bytes (at most 50 MiB). See {@link AgentClient.listFiles}. */
752
+ downloadFile?(dir: AgentFileDir, name: string): Promise<Uint8Array>;
753
+ /**
754
+ * Remove one file from the agent's outbox or file inbox (0g-harness
755
+ * `DELETE /v1/files/{dir}/{name}`). `deleted`: it is gone; `missing`: there
756
+ * was no such file; `unsupported`: this agent's runtime has no delete
757
+ * route (an older image).
758
+ */
759
+ deleteFile?(dir: AgentFileDir, name: string): Promise<'deleted' | 'missing' | 'unsupported'>;
432
760
  }
433
761
 
434
762
  /** Longest-prefix match over declared routes, or undefined if none match. */
@@ -522,11 +850,11 @@ function chunkDelta(chunk: Record<string, unknown>): { role?: string; content: s
522
850
  }
523
851
 
524
852
  /** Fold an SSE chat stream into a single reassembled {@link ChatCompletion}. */
525
- async function collectChatStream(body: ReadableStream<Uint8Array>): Promise<ChatCompletion> {
853
+ async function collectChatStream(body: ReadableStream<Uint8Array>, onComment?: (c: string) => void): Promise<ChatCompletion> {
526
854
  let content = '';
527
855
  let role = 'assistant';
528
856
  let last: Record<string, unknown> = {};
529
- for await (const chunk of iterSseChunks(body)) {
857
+ for await (const chunk of iterSseChunks(body, onComment)) {
530
858
  last = chunk;
531
859
  const d = chunkDelta(chunk);
532
860
  if (d.role) role = d.role;
@@ -535,6 +863,62 @@ async function collectChatStream(body: ReadableStream<Uint8Array>): Promise<Chat
535
863
  return { ...last, choices: [{ message: { role, content } }] } as ChatCompletion;
536
864
  }
537
865
 
866
+ // Base64 without Node's Buffer, so the module runs in browsers too.
867
+ function bytesToBase64(bytes: Uint8Array): string {
868
+ let bin = '';
869
+ for (let i = 0; i < bytes.length; i += 0x8000) bin += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
870
+ return btoa(bin);
871
+ }
872
+
873
+ const imageUrl = (im: ChatImage): string => `data:${im.mediaType};base64,${im.data}`;
874
+
875
+ /**
876
+ * The messages with `images` on the last user message, in the request's own
877
+ * shape: chat/completions `image_url` parts, or Responses `input_text` /
878
+ * `input_image` parts. No images: the messages as they are.
879
+ */
880
+ export function withImages(messages: ChatMessage[], images: ChatImage[] | undefined, shape: 'chat' | 'responses', names = false): unknown[] {
881
+ if (!images?.length) return messages;
882
+ let i = messages.length - 1;
883
+ while (i >= 0 && messages[i].role !== 'user') i--;
884
+ const text = i >= 0 ? messages[i].content : '';
885
+ // `filename` only where the agent reads it (`names`): another runtime may refuse a field it does not know.
886
+ const named = (im: ChatImage): { filename?: string } => (names && im.name ? { filename: im.name } : {});
887
+ const content = shape === 'chat'
888
+ ? [{ type: 'text', text }, ...images.map((im) => ({ type: 'image_url', image_url: { url: imageUrl(im) }, ...named(im) }))]
889
+ : [{ type: 'input_text', text }, ...images.map((im) => ({ type: 'input_image', image_url: imageUrl(im), ...named(im) }))];
890
+ const out: unknown[] = messages.slice();
891
+ if (i >= 0) out[i] = { role: 'user', content };
892
+ else out.push({ role: 'user', content });
893
+ return out;
894
+ }
895
+
896
+ /** The notice an SSE comment carries (`: notice images_saved_as_files [...]`, `: notice outbox_files [...]`), if any. */
897
+ function noticeOf(comment: string): ChatNotice | undefined {
898
+ const m = /^notice (images_saved_as_files|outbox_files) (\[.*\])$/.exec(comment);
899
+ if (!m) return undefined;
900
+ try {
901
+ const items = JSON.parse(m[2]) as unknown;
902
+ if (!Array.isArray(items) || !items.every((p) => typeof p === 'string')) return undefined;
903
+ const clean = items.map((p) => plainText(p));
904
+ return m[1] === 'outbox_files' ? { outboxFiles: clean } : { imagesSavedAsFiles: clean };
905
+ } catch { /* not a notice */ }
906
+ return undefined;
907
+ }
908
+
909
+ /** The notice a buffered reply or a Responses record carries in `harness`, if any. */
910
+ function harnessNotice(harness: AgentTask['harness'] | undefined): ChatNotice | undefined {
911
+ if (!harness) return undefined;
912
+ const n: ChatNotice = {};
913
+ const strings = (v: unknown): string[] | undefined =>
914
+ Array.isArray(v) && v.length && v.every((p) => typeof p === 'string') ? v.map((p) => plainText(p)) : undefined;
915
+ const images = strings(harness.images_saved_as_files);
916
+ const outbox = strings(harness.outbox_files);
917
+ if (images) n.imagesSavedAsFiles = images;
918
+ if (outbox) n.outboxFiles = outbox;
919
+ return images || outbox ? n : undefined;
920
+ }
921
+
538
922
  /**
539
923
  * Build an {@link AgentClient} from a base URL, the agent's declared surface,
540
924
  * and (optionally) a way to authenticate:
@@ -659,8 +1043,31 @@ export function makeAgentClient(params: {
659
1043
  // deploy. There's no framework-agnostic default (/hello doesn't declare it),
660
1044
  // so omit the field when the caller doesn't set one rather than sending a
661
1045
  // bogus value the framework rejects.
662
- const chatBody = (messages: ChatMessage[], opts?: { model?: string; signal?: AbortSignal }) =>
663
- JSON.stringify(opts?.model ? { model: opts.model, messages, stream: true } : { messages, stream: true });
1046
+ const chatBody = async (messages: ChatMessage[], opts?: { model?: string; images?: ChatImage[] }) => {
1047
+ const sent = withImages(messages, opts?.images, 'chat', await imageNames(opts?.images));
1048
+ return JSON.stringify(opts?.model ? { model: opts.model, messages: sent, stream: true } : { messages: sent, stream: true });
1049
+ };
1050
+
1051
+ // What the agent's runtime says it reads (0g-harness `GET /v1/harness`,
1052
+ // `features`), asked once; null where there is no such route.
1053
+ let featuresAsked: Promise<Record<string, unknown> | null> | null = null;
1054
+ const harnessFeatures = (): Promise<Record<string, unknown> | null> => {
1055
+ const r = routes.find((x) => x.kind === 'chat') ?? routes.find((x) => x.kind === 'responses');
1056
+ if (!r || !canAuth) return Promise.resolve(null);
1057
+ const path = r.kind === 'chat' ? `${r.prefix.replace(/\/?$/, '/')}harness` : r.prefix.replace(/responses\/?$/, 'harness');
1058
+ featuresAsked ??= doFetch(path, { signal: AbortSignal.timeout(5000) })
1059
+ .then(async (res) => {
1060
+ if (res.status === 404) return null; // not a harness: it never will be
1061
+ if (!res.ok) throw new Error(`harness: HTTP ${res.status}`);
1062
+ const f = ((await res.json()) as { features?: unknown }).features;
1063
+ return f && typeof f === 'object' ? f as Record<string, unknown> : null;
1064
+ })
1065
+ .catch(() => { featuresAsked = null; return null; }); // asked again next time
1066
+ return featuresAsked;
1067
+ };
1068
+ /** Whether image parts carry their file name: only where the agent says it reads it. */
1069
+ const imageNames = async (images?: ChatImage[]): Promise<boolean> =>
1070
+ !!images?.some((im) => im.name) && (await harnessFeatures())?.image_names === true;
664
1071
 
665
1072
  const chat = routes.find((r) => r.kind === 'chat');
666
1073
  if (chat && canAuth) {
@@ -683,7 +1090,7 @@ export function makeAgentClient(params: {
683
1090
  return { aborted: !!j.aborted, note: j.note };
684
1091
  }
685
1092
  if (r.status === 404) return { aborted: false, note: 'no bridge endpoint — this framework stops its turn when the stream disconnects' };
686
- throw new Error(`interrupt: HTTP ${r.status}: ${await r.text()}`);
1093
+ throw new Error(`interrupt: HTTP ${r.status}: ${plainText(await r.text())}`);
687
1094
  } catch (e) {
688
1095
  if ((e as Error).message.startsWith('interrupt:')) throw e;
689
1096
  return { aborted: false, note: 'interrupt transport failed — this framework stops its turn when the stream disconnects' };
@@ -694,25 +1101,28 @@ export function makeAgentClient(params: {
694
1101
  const r = await doFetch(path, {
695
1102
  method: 'POST',
696
1103
  headers: { 'content-type': 'application/json' },
697
- body: chatBody(messages, opts),
1104
+ body: await chatBody(messages, opts),
698
1105
  signal: opts?.signal,
699
1106
  });
700
- if (!r.ok) throw new Error(`chat: HTTP ${r.status}: ${await r.text()}`);
1107
+ if (!r.ok) throw new Error(`chat: HTTP ${r.status}: ${plainText(await r.text())}`);
701
1108
  const ct = r.headers.get('content-type') ?? '';
702
1109
  if (!r.body || !ct.toLowerCase().includes('text/event-stream')) {
703
- return (await r.json()) as ChatCompletion; // server didn't stream → plain JSON
1110
+ const full = (await r.json()) as ChatCompletion & { harness?: AgentTask['harness'] };
1111
+ const n = harnessNotice(full.harness);
1112
+ if (n) opts?.onNotice?.(n);
1113
+ return full; // server didn't stream → plain JSON
704
1114
  }
705
- return collectChatStream(r.body);
1115
+ return collectChatStream(r.body, opts?.onNotice ? (c) => { const n = noticeOf(c); if (n) opts.onNotice!(n); } : undefined);
706
1116
  };
707
1117
 
708
1118
  client.chatStream = async function* (messages, opts) {
709
1119
  const r = await doFetch(path, {
710
1120
  method: 'POST',
711
1121
  headers: { 'content-type': 'application/json' },
712
- body: chatBody(messages, opts),
1122
+ body: await chatBody(messages, opts),
713
1123
  signal: opts?.signal,
714
1124
  });
715
- if (!r.ok) throw new Error(`chat: HTTP ${r.status}: ${await r.text()}`);
1125
+ if (!r.ok) throw new Error(`chat: HTTP ${r.status}: ${plainText(await r.text())}`);
716
1126
  const ct = r.headers.get('content-type') ?? '';
717
1127
  if (!r.body || !ct.toLowerCase().includes('text/event-stream')) {
718
1128
  // Server didn't stream — yield the whole reply as one delta. An EMPTY
@@ -731,8 +1141,12 @@ export function makeAgentClient(params: {
731
1141
  // (feedback.md F15)
732
1142
  let sawContent = false;
733
1143
  let streamErr: string | null = null;
734
- const onComment = opts?.onActivity
735
- ? (c: string): void => { if (c.startsWith('activity ')) opts.onActivity!(c.slice(9)); }
1144
+ const onComment = opts?.onActivity || opts?.onNotice
1145
+ ? (c: string): void => {
1146
+ if (c.startsWith('activity ')) opts.onActivity?.(plainText(c.slice(9)));
1147
+ const n = noticeOf(c);
1148
+ if (n) opts.onNotice?.(n);
1149
+ }
736
1150
  : undefined;
737
1151
  let lastThinkingAt = 0;
738
1152
  const thinking = (): void => {
@@ -749,8 +1163,8 @@ export function makeAgentClient(params: {
749
1163
  if (opts?.onActivity) {
750
1164
  const tool = (chunk as { tool_name?: string }).tool_name ?? '';
751
1165
  if (tool === '_thinking') thinking();
752
- else if (ev === 'hermes.tool.progress') { if (tool) opts.onActivity(`tool/call ${tool}`); }
753
- else opts.onActivity(tool ? `${ev.replace(/^hermes\./, '')} ${tool}` : ev.replace(/^hermes\./, ''));
1166
+ else if (ev === 'hermes.tool.progress') { if (tool) opts.onActivity(plainText(`tool/call ${tool}`)); }
1167
+ else opts.onActivity(plainText(tool ? `${ev.replace(/^hermes\./, '')} ${tool}` : ev.replace(/^hermes\./, '')));
754
1168
  }
755
1169
  continue;
756
1170
  }
@@ -763,7 +1177,7 @@ export function makeAgentClient(params: {
763
1177
  const delta = choice?.delta as { tool_calls?: Array<{ function?: { name?: string } }> } | undefined;
764
1178
  for (const tc of delta?.tool_calls ?? []) {
765
1179
  const fn = tc?.function?.name;
766
- if (fn) opts.onActivity(`tool/call ${fn}`);
1180
+ if (fn) opts.onActivity(plainText(`tool/call ${fn}`));
767
1181
  }
768
1182
  }
769
1183
  const d = chunkDelta(chunk);
@@ -772,7 +1186,7 @@ export function makeAgentClient(params: {
772
1186
  if (!sawContent) {
773
1187
  throw new Error(
774
1188
  streamErr
775
- ? `chat: upstream error: ${streamErr}`
1189
+ ? `chat: upstream error: ${plainText(String(streamErr))}`
776
1190
  : 'chat: the stream ended without any output — the agent-side model call likely failed (see /agentlog)',
777
1191
  );
778
1192
  }
@@ -795,7 +1209,7 @@ export function makeAgentClient(params: {
795
1209
 
796
1210
  const taskSnapshot = async (id: string): Promise<AgentTask> => {
797
1211
  const r = await doFetch(`${rPrefix}/${id}`);
798
- if (!r.ok) throw new Error(`task: HTTP ${r.status}: ${await r.text()}`);
1212
+ if (!r.ok) throw new Error(`task: HTTP ${r.status}: ${plainText(await r.text())}`);
799
1213
  return (await r.json()) as AgentTask;
800
1214
  };
801
1215
 
@@ -846,8 +1260,8 @@ export function makeAgentClient(params: {
846
1260
 
847
1261
  const lostAgent = (id: string | undefined, why: string): Error =>
848
1262
  new Error(
849
- `task ${id}: lost the agent while following (${why}) — ` +
850
- `the task may still be running; re-attach with followTask("${id}")`,
1263
+ `task ${plainText(String(id))}: lost the agent while following (${plainText(why)}) — ` +
1264
+ `the task may still be running; re-attach with followTask("${plainText(String(id))}")`,
851
1265
  );
852
1266
 
853
1267
  async function* followResponse(args: {
@@ -855,6 +1269,7 @@ export function makeAgentClient(params: {
855
1269
  startingAfter?: number;
856
1270
  signal?: AbortSignal;
857
1271
  onActivity?: (label: string) => void;
1272
+ onNotice?: (notice: ChatNotice) => void;
858
1273
  }): AsyncGenerator<string> {
859
1274
  const id = args.id;
860
1275
  let seq = args.startingAfter ?? 0;
@@ -894,7 +1309,7 @@ export function makeAgentClient(params: {
894
1309
  let res: Response;
895
1310
  try {
896
1311
  const r = await doFetch(`${rPrefix}/${id}?stream=true&starting_after=${seq}`, { signal: attempt.signal });
897
- if (!r.ok) throw new Error(`HTTP ${r.status}: ${await r.text()}`);
1312
+ if (!r.ok) throw new Error(`HTTP ${r.status}: ${plainText(await r.text())}`);
898
1313
  res = r;
899
1314
  lastByteAt = Date.now();
900
1315
  } catch (e) {
@@ -935,7 +1350,7 @@ export function makeAgentClient(params: {
935
1350
  }
936
1351
  case 'response.activity': {
937
1352
  const label = (chunk as { label?: string }).label;
938
- if (args.onActivity && typeof label === 'string') args.onActivity(label);
1353
+ if (args.onActivity && typeof label === 'string') args.onActivity(plainText(label));
939
1354
  break;
940
1355
  }
941
1356
  case 'response.completed':
@@ -976,8 +1391,13 @@ export function makeAgentClient(params: {
976
1391
  }
977
1392
  }
978
1393
 
1394
+ // Notices known only when the turn ends (files it left in the outbox).
1395
+ {
1396
+ const n = harnessNotice(terminal.harness);
1397
+ if (n?.outboxFiles) args.onNotice?.({ outboxFiles: n.outboxFiles });
1398
+ }
979
1399
  if (terminal.status === 'failed') {
980
- throw new Error(`chat: ${terminal.error?.message ?? 'task failed'}`);
1400
+ throw new Error(`chat: ${plainText(terminal.error?.message ?? 'task failed')}`);
981
1401
  }
982
1402
  if (terminal.status === 'cancelled') return; // owner stopped it — partial text already yielded
983
1403
  if (!sawText) {
@@ -996,7 +1416,7 @@ export function makeAgentClient(params: {
996
1416
  // returns the id in milliseconds, so every long-lived byte after that
997
1417
  // travels on a GET we can always resume by id. One extra round trip
998
1418
  // buys the guarantee that a task is never lost to a dropped connection.
999
- const payload: Record<string, unknown> = { input: messages };
1419
+ const payload: Record<string, unknown> = { input: withImages(messages, opts?.images, 'responses', await imageNames(opts?.images)) };
1000
1420
  if (opts?.model) payload.model = opts.model;
1001
1421
  if (opts?.thinking) payload.reasoning = { effort: opts.thinking };
1002
1422
  const r = await doFetch(rPrefix, {
@@ -1005,15 +1425,20 @@ export function makeAgentClient(params: {
1005
1425
  body: JSON.stringify(payload),
1006
1426
  signal: opts?.signal,
1007
1427
  });
1008
- if (!r.ok) throw new Error(`chat: HTTP ${r.status}: ${await r.text()}`);
1428
+ if (!r.ok) throw new Error(`chat: HTTP ${r.status}: ${plainText(await r.text())}`);
1009
1429
  const submitted = (await r.json()) as AgentTask;
1010
1430
  if (!submitted?.id) throw new Error('chat: the agent accepted the task but returned no id');
1011
- opts?.onTask?.(submitted.id);
1431
+ const saved = harnessNotice(submitted.harness)?.imagesSavedAsFiles;
1432
+ if (saved) opts?.onNotice?.({ imagesSavedAsFiles: saved });
1433
+ // A task id is a name to re-attach with: one that is not a plain
1434
+ // identifier is not handed out to be printed.
1435
+ if (TASK_ID.test(submitted.id)) opts?.onTask?.(submitted.id);
1012
1436
  yield* followResponse({
1013
1437
  id: submitted.id,
1014
1438
  startingAfter: 0,
1015
1439
  signal: opts?.signal,
1016
1440
  onActivity: wrapActivity(opts?.onActivity),
1441
+ onNotice: opts?.onNotice,
1017
1442
  });
1018
1443
  };
1019
1444
 
@@ -1032,12 +1457,12 @@ export function makeAgentClient(params: {
1032
1457
  });
1033
1458
  client.cancelTask = async (id) => {
1034
1459
  const r = await doFetch(`${rPrefix}/${id}/cancel`, { method: 'POST' });
1035
- if (!r.ok) throw new Error(`cancelTask: HTTP ${r.status}: ${await r.text()}`);
1460
+ if (!r.ok) throw new Error(`cancelTask: HTTP ${r.status}: ${plainText(await r.text())}`);
1036
1461
  return (await r.json()) as AgentTask;
1037
1462
  };
1038
1463
  }
1039
1464
 
1040
- // ── The agent's own work: inbox, live feed, tasks, reminders ─────────────
1465
+ // ── The agent's own work: inbox, live feed, activities, reminders ────────
1041
1466
  //
1042
1467
  // An agent that works in the background (commands, subagents, reminders)
1043
1468
  // also opens turns by itself, and their words belong to no chat request.
@@ -1056,7 +1481,7 @@ export function makeAgentClient(params: {
1056
1481
  };
1057
1482
  const getJSON = async <T>(what: string, path: string): Promise<T> => {
1058
1483
  const r = await doFetch(path);
1059
- if (!r.ok) throw new Error(`${what}: HTTP ${r.status}: ${await r.text()}`);
1484
+ if (!r.ok) throw new Error(`${what}: HTTP ${r.status}: ${plainText(await r.text())}`);
1060
1485
  return (await r.json()) as T;
1061
1486
  };
1062
1487
  const postJSON = async <T>(what: string, path: string, body?: unknown): Promise<T> => {
@@ -1064,7 +1489,7 @@ export function makeAgentClient(params: {
1064
1489
  method: 'POST',
1065
1490
  ...(body === undefined ? {} : { headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }),
1066
1491
  });
1067
- if (!r.ok) throw new Error(`${what}: HTTP ${r.status}: ${await r.text()}`);
1492
+ if (!r.ok) throw new Error(`${what}: HTTP ${r.status}: ${plainText(await r.text())}`);
1068
1493
  return (await r.json()) as T;
1069
1494
  };
1070
1495
 
@@ -1074,18 +1499,40 @@ export function makeAgentClient(params: {
1074
1499
  client.ackInbox = (through) => postJSON('ackInbox', `${inboxBase}/ack`, { through });
1075
1500
  }
1076
1501
 
1077
- const tasksBase = ownerBase('tasks');
1078
- if (tasksBase) {
1079
- client.tasks = async (opts) =>
1080
- (await getJSON<{ data: AgentTaskInfo[] }>('tasks', `${tasksBase}${query({ status: opts?.status, limit: opts?.limit })}`)).data;
1081
- client.taskInfo = (id) => getJSON<AgentTaskInfo>('taskInfo', `${tasksBase}/${encodeURIComponent(id)}`);
1082
- client.stopTask = async (id) => {
1502
+ // The activity list: /v1/activities, or /v1/tasks, its old name, on a
1503
+ // runtime from before the rename. A newer sealed can run an older harness
1504
+ // package, which answers 404 on /v1/activities: then the old name. A
1505
+ // runtime that declares `task-feed` serves zgh-style tasks on /v1/tasks
1506
+ // instead (below), so there is no old name to fall back to.
1507
+ const taskFeedBase = ownerBase('task-feed');
1508
+ const activitiesBase = ownerBase('activities');
1509
+ const legacyTasksBase = taskFeedBase ? undefined : ownerBase('tasks');
1510
+ if (activitiesBase || legacyTasksBase) {
1511
+ let base = (activitiesBase ?? legacyTasksBase) as string;
1512
+ const activityCall = async <T>(what: string, rest: string, post = false): Promise<T> => {
1513
+ const send = (b: string) => doFetch(`${b}${rest}`, post ? { method: 'POST' } : undefined);
1514
+ let r = await send(base);
1515
+ if (r.status === 404 && base === activitiesBase && legacyTasksBase) {
1516
+ const old = await send(legacyTasksBase);
1517
+ if (old.status !== 404) { base = legacyTasksBase; r = old; }
1518
+ }
1519
+ if (!r.ok) throw new Error(`${what}: HTTP ${r.status}: ${plainText(await r.text())}`);
1520
+ return (await r.json()) as T;
1521
+ };
1522
+ client.activities = async (opts) =>
1523
+ (await activityCall<{ data: AgentActivityInfo[] }>('activities', query({ status: opts?.status, limit: opts?.limit }))).data;
1524
+ client.activity = (id) => activityCall<AgentActivityInfo>('activity', `/${encodeURIComponent(id)}`);
1525
+ client.stopActivity = async (id) => {
1083
1526
  // `all` is a different request with a different answer.
1084
- if (id === 'all') throw new Error('stopTask: "all" is stopAllTasks()');
1085
- return postJSON<AgentTaskStop>('stopTask', `${tasksBase}/${encodeURIComponent(id)}/cancel`);
1527
+ if (id === 'all') throw new Error('stopActivity: "all" is stopAllActivities()');
1528
+ return activityCall<AgentActivityStop>('stopActivity', `/${encodeURIComponent(id)}/cancel`, true);
1086
1529
  };
1087
- client.stopAllTasks = async () =>
1088
- (await postJSON<{ data: AgentTaskStop[] }>('stopAllTasks', `${tasksBase}/all/cancel`)).data;
1530
+ client.stopAllActivities = async () =>
1531
+ (await activityCall<{ data: AgentActivityStop[] }>('stopAllActivities', '/all/cancel', true)).data;
1532
+ client.tasks = client.activities;
1533
+ client.taskInfo = client.activity;
1534
+ client.stopTask = client.stopActivity;
1535
+ client.stopAllTasks = client.stopAllActivities;
1089
1536
  }
1090
1537
 
1091
1538
  const schedulesBase = ownerBase('schedules');
@@ -1096,6 +1543,113 @@ export function makeAgentClient(params: {
1096
1543
  };
1097
1544
  }
1098
1545
 
1546
+ const filesBase = ownerBase('files');
1547
+ if (filesBase) {
1548
+ client.uploadFile = (name, data) => postJSON<UploadedFile>('uploadFile', filesBase, { name, content_base64: bytesToBase64(data) });
1549
+ // Downloads share the files route; an agent whose runtime predates them
1550
+ // does not list the GET endpoints, and the proxy answers 404.
1551
+ const noDownloads = (what: string, status: number, text: string): Error =>
1552
+ status === 404 && /no route|not found|404/i.test(text) && !/no file /.test(text)
1553
+ ? new Error(`${what}: this agent's runtime does not serve downloads (update the agent)`)
1554
+ : new Error(`${what}: HTTP ${status}: ${plainText(text)}`);
1555
+ client.listFiles = async (dir = 'outbox') => {
1556
+ const r = await doFetch(`${filesBase}${query({ dir })}`);
1557
+ if (!r.ok) throw noDownloads('listFiles', r.status, await r.text());
1558
+ const j = (await r.json()) as { data?: AgentFile[] };
1559
+ return (j.data ?? []).map((f) => ({ ...f, name: plainText(String(f.name)) }));
1560
+ };
1561
+ client.downloadFile = async (dir, name) => {
1562
+ if (dir !== 'outbox' && dir !== 'inbox') throw new Error('downloadFile: dir is outbox or inbox');
1563
+ if (!name || name.includes('/') || name.includes('\\') || name.startsWith('.')) throw new Error('downloadFile: a file name is one path segment, without a leading dot');
1564
+ const r = await doFetch(`${filesBase}/${dir}/${encodeURIComponent(name)}`);
1565
+ if (!r.ok) throw noDownloads('downloadFile', r.status, await r.text());
1566
+ return new Uint8Array(await r.arrayBuffer());
1567
+ };
1568
+ client.deleteFile = async (dir, name) => {
1569
+ if (dir !== 'outbox' && dir !== 'inbox') throw new Error('deleteFile: dir is outbox or inbox');
1570
+ if (!name || name.includes('/') || name.includes('\\') || name.startsWith('.')) throw new Error('deleteFile: a file name is one path segment, without a leading dot');
1571
+ const r = await doFetch(`${filesBase}/${dir}/${encodeURIComponent(name)}`, { method: 'DELETE' });
1572
+ if (r.ok) return 'deleted';
1573
+ const text = await r.text();
1574
+ // The harness answers a missing file with "no file …"; anything else
1575
+ // that is not found (or a method the route does not take) is a runtime
1576
+ // without the delete route.
1577
+ if (r.status === 404 && /no file /i.test(text)) return 'missing';
1578
+ if (r.status === 404 || r.status === 405) return 'unsupported';
1579
+ throw new Error(`deleteFile: HTTP ${r.status}: ${plainText(text)}`);
1580
+ };
1581
+ }
1582
+
1583
+ const steerBase = ownerBase('steer');
1584
+ if (steerBase) {
1585
+ client.steer = (text) => postJSON<SteerResult>('steer', steerBase, { text });
1586
+ client.steerState = (id) => getJSON<SteerState>('steerState', `${steerBase}/${encodeURIComponent(id)}`);
1587
+ }
1588
+
1589
+ const sessionsBase = ownerBase('sessions');
1590
+ if (sessionsBase) {
1591
+ const sid = (id: string): string => {
1592
+ // owner-chat, an owner session, a task, or a session a schedule opened (DSH's `session-…` ids).
1593
+ if (!/^(owner-chat|(sess|task)-[a-z0-9][a-z0-9-]{0,62}|session-[a-z0-9][a-z0-9-]{0,90})$/.test(id)) throw new Error(`not a session id: ${plainText(id)}`);
1594
+ return `${sessionsBase}/${id}`;
1595
+ };
1596
+ const clean = (s: AgentSession): AgentSession => ({ ...s, title: plainText(String(s.title ?? '')) });
1597
+ client.sessions = async () => ((await getJSON<{ data?: AgentSession[] }>('sessions', sessionsBase)).data ?? []).map(clean);
1598
+ client.session = async (id) => clean(await getJSON<AgentSession>('session', sid(id)));
1599
+ client.createSession = async (opts = {}) => clean(await postJSON<AgentSession>('createSession', sessionsBase, opts));
1600
+ client.promptSession = (id, text, opts = {}) => postJSON<SessionPromptResult>('promptSession', `${sid(id)}/prompt`, { text, ...(opts.mode ? { mode: opts.mode } : {}) });
1601
+ client.cancelSession = (id) => postJSON<{ cancelled: string | null; session: string }>('cancelSession', `${sid(id)}/cancel`);
1602
+ }
1603
+
1604
+ // zgh-style tasks: /v1/tasks with the `task-feed` kind beside it (an older
1605
+ // runtime's `tasks` kind alone is the activity list's old name).
1606
+ const tasksBase = taskFeedBase ? ownerBase('tasks') : undefined;
1607
+ if (tasksBase && taskFeedBase) {
1608
+ const tid = (id: string): string => {
1609
+ // A task's id, or a scheduled task's (the session id a schedule gave it).
1610
+ if (!/^(task-[a-z0-9][a-z0-9-]{0,62}|session-[a-z0-9][a-z0-9-]{0,90})$/.test(id)) throw new Error(`not a task id: ${plainText(id)}`);
1611
+ return `${tasksBase}/${id}`;
1612
+ };
1613
+ const clean = <T extends { title?: string }>(t: T): T => (t && typeof t.title === 'string' ? { ...t, title: plainText(t.title) } : t);
1614
+ client.createTask = async (opts) => {
1615
+ const r = await doFetch(tasksBase, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(opts) });
1616
+ const text = await r.text();
1617
+ let body: { error?: { code?: string }; task?: HarnessTask } | HarnessTask | undefined;
1618
+ try { body = JSON.parse(text); } catch { body = undefined; }
1619
+ if (r.status === 201 && body) return { task: clean(body as HarnessTask), created: true };
1620
+ const taken = body as { error?: { code?: string }; task?: HarnessTask } | undefined;
1621
+ if (r.status === 409 && taken?.error?.code === 'id-taken' && taken.task) return { task: clean(taken.task), created: false };
1622
+ throw new Error(`createTask: HTTP ${r.status}: ${plainText(text)}`);
1623
+ };
1624
+ client.listTasks = async (opts = {}) => {
1625
+ const q = new URLSearchParams();
1626
+ for (const st of opts.state === undefined ? [] : Array.isArray(opts.state) ? opts.state : [opts.state]) q.append('state', st);
1627
+ for (const [k, v] of Object.entries(opts.metadata ?? {})) q.set(`metadata.${k}`, v);
1628
+ if (opts.limit !== undefined) q.set('limit', String(opts.limit));
1629
+ const qs = q.toString();
1630
+ return ((await getJSON<{ data?: HarnessTask[] }>('listTasks', `${tasksBase}${qs ? `?${qs}` : ''}`)).data ?? []).map(clean);
1631
+ };
1632
+ client.getTask = async (id) => clean(await getJSON<HarnessTask>('getTask', tid(id)));
1633
+ client.taskInput = async (id, text, opts = {}) => clean(await postJSON<TaskInputResult>('taskInput', `${tid(id)}/input`, { text, ...(opts.mode ? { mode: opts.mode } : {}) }));
1634
+ client.cancelTaskRun = async (id) => clean(await postJSON<HarnessTask>('cancelTaskRun', `${tid(id)}/cancel`));
1635
+ client.archiveTask = async (id) => clean(await postJSON<HarnessTask>('archiveTask', `${tid(id)}/archive`));
1636
+ client.taskFeed = async function* (opts) {
1637
+ const res = await doFetch(taskFeedBase, opts?.signal ? { signal: opts.signal } : undefined);
1638
+ if (!res.ok) throw new Error(`taskFeed: HTTP ${res.status}: ${plainText(await res.text())}`);
1639
+ if (!res.body) throw new Error('taskFeed: expected an SSE stream from the task-feed route');
1640
+ try {
1641
+ for await (const chunk of iterSseChunks(res.body)) {
1642
+ const { __sseEvent, ...data } = chunk as Record<string, unknown> & { __sseEvent?: string };
1643
+ if (__sseEvent === 'ready') yield { type: 'ready' };
1644
+ else if (__sseEvent === 'task' && typeof data.id === 'string') yield { type: 'task', task: data as unknown as HarnessTaskSummary };
1645
+ }
1646
+ } catch (err) {
1647
+ if (opts?.signal?.aborted) return;
1648
+ throw err;
1649
+ }
1650
+ };
1651
+ }
1652
+
1099
1653
  const eventsBase = ownerBase('events');
1100
1654
  if (eventsBase) {
1101
1655
  // The agent sends a keepalive every 10s, so this much silence means the
@@ -1142,7 +1696,7 @@ export function makeAgentClient(params: {
1142
1696
  // A 4xx is an answer (the route is gone, the handle is refused),
1143
1697
  // and asking again gets the same one.
1144
1698
  if (res.status < 500 && res.status !== 408 && res.status !== 429) {
1145
- throw new Error(`events: HTTP ${res.status}: ${text}`);
1699
+ throw new Error(`events: HTTP ${res.status}: ${plainText(text)}`);
1146
1700
  }
1147
1701
  res = undefined;
1148
1702
  }
@@ -1201,7 +1755,7 @@ export function makeAgentClient(params: {
1201
1755
  headers: { 'X-Auth-Message': message, 'X-Auth-Signature': signature },
1202
1756
  signal: AbortSignal.timeout(30_000),
1203
1757
  });
1204
- if (!r.ok) throw new Error(`logs: HTTP ${r.status}: ${await r.text()}`);
1758
+ if (!r.ok) throw new Error(`logs: HTTP ${r.status}: ${plainText(await r.text())}`);
1205
1759
  const text = await r.text();
1206
1760
  if (opts?.tail && opts.tail > 0) {
1207
1761
  return text.split('\n').slice(-opts.tail).join('\n');