@neta-art/cohub-cli 10.22.0 → 10.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/avatar.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { CohubHttpClient, PublicAssetPurpose } from "@neta-art/cohub";
1
+ import { type CohubHttpClient, type PublicAssetPurpose } from "@neta-art/cohub";
2
2
  type PreparedAvatar = {
3
3
  body: Buffer;
4
4
  mimeType: "image/webp" | "image/jpeg" | "image/png" | "image/gif";
@@ -18,6 +18,19 @@ export declare function uploadAvatarAsset(input: {
18
18
  uploadMethod: "PUT";
19
19
  uploadHeaders?: Record<string, string>;
20
20
  }>;
21
+ export declare function normalizeLikeStickerFile(path: string): Promise<PreparedAvatar>;
22
+ export declare function uploadLikeStickerAsset(input: {
23
+ client: CohubHttpClient;
24
+ spaceId: string;
25
+ path: string;
26
+ }): Promise<{
27
+ purpose: PublicAssetPurpose;
28
+ objectKey: string;
29
+ publicUrl: string;
30
+ uploadUrl: string;
31
+ uploadMethod: "PUT";
32
+ uploadHeaders?: Record<string, string>;
33
+ }>;
21
34
  export declare function normalizeChatImageFile(path: string): Promise<{
22
35
  body: Buffer<ArrayBuffer>;
23
36
  width: number;
package/dist/avatar.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { readFile } from "node:fs/promises";
2
+ import { LIKE_STICKER_MAX_EDGE, LIKE_STICKER_MAX_FILE_BYTES } from "@neta-art/cohub";
2
3
  const loadSharp = async () => (await import("sharp")).default;
3
4
  const AVATAR_SIZE = 1024;
4
5
  const AVATAR_QUALITY = 86;
@@ -47,6 +48,38 @@ export async function uploadAvatarAsset(input) {
47
48
  filename: `avatar.${avatar.extension}`,
48
49
  });
49
50
  }
51
+ export async function normalizeLikeStickerFile(path) {
52
+ const original = await readFile(path);
53
+ const format = detectAvatarFormat(original);
54
+ if (!format)
55
+ throw new Error("Like sticker must be a PNG, GIF, WebP, or JPEG image");
56
+ const sharp = await loadSharp().catch(() => null);
57
+ let prepared = { body: original, ...format };
58
+ if (sharp) {
59
+ const body = await sharp(original, { animated: true })
60
+ .resize(LIKE_STICKER_MAX_EDGE, LIKE_STICKER_MAX_EDGE, { fit: "inside", withoutEnlargement: true })
61
+ .webp({ quality: AVATAR_QUALITY, effort: 5 })
62
+ .toBuffer();
63
+ prepared = { body, mimeType: "image/webp", extension: "webp" };
64
+ }
65
+ else if (format.mimeType === "image/jpeg") {
66
+ throw new Error("Converting a JPEG like sticker needs sharp; use a PNG, GIF, or WebP image");
67
+ }
68
+ if (prepared.body.byteLength > LIKE_STICKER_MAX_FILE_BYTES) {
69
+ throw new Error(`Like sticker must be at most ${LIKE_STICKER_MAX_FILE_BYTES / 1024 / 1024} MiB after resizing`);
70
+ }
71
+ return prepared;
72
+ }
73
+ export async function uploadLikeStickerAsset(input) {
74
+ const sticker = await normalizeLikeStickerFile(input.path);
75
+ return input.client.publicAssets.upload({
76
+ purpose: "space_like_sticker",
77
+ spaceId: input.spaceId,
78
+ file: new Blob([new Uint8Array(sticker.body)], { type: sticker.mimeType }),
79
+ mimeType: sticker.mimeType,
80
+ filename: `like-sticker.${sticker.extension}`,
81
+ });
82
+ }
50
83
  const CHAT_IMAGE_MAX_EDGE = 1984;
51
84
  const CHAT_IMAGE_QUALITY = 86;
52
85
  export async function normalizeChatImageFile(path) {
@@ -52147,6 +52147,7 @@ function createBoardEditor(options) {
52147
52147
  const registry = options.registry ?? defaultBoardRegistry;
52148
52148
  const channels = createChannels();
52149
52149
  const track = options.track ?? (() => {});
52150
+ let collecting = null;
52150
52151
  const preferences = options.preferences;
52151
52152
  const state = observable({
52152
52153
  base: options.document,
@@ -52256,11 +52257,16 @@ function createBoardEditor(options) {
52256
52257
  };
52257
52258
  ctx.preferencesChanged();
52258
52259
  }
52260
+ function note(channel) {
52261
+ track(channel);
52262
+ collecting?.add(channel);
52263
+ }
52259
52264
  function read(channel, value) {
52260
- if (typeof channel === "string") track(channel);
52261
- else for (const each of channel) track(each);
52265
+ if (typeof channel === "string") note(channel);
52266
+ else for (const each of channel) note(each);
52262
52267
  return value();
52263
52268
  }
52269
+ const visibleRect = memo(() => [state.camera, state.surfaceSize], (_camera, _surface) => camera.visibleRect());
52264
52270
  function tracked(channels, query) {
52265
52271
  return (...args) => read(channels, () => query(...args));
52266
52272
  }
@@ -52268,6 +52274,20 @@ function createBoardEditor(options) {
52268
52274
  registry,
52269
52275
  readonly: options.readonly === true,
52270
52276
  subscribe: channels.subscribe,
52277
+ collect(read) {
52278
+ const outer = collecting;
52279
+ const seen = /* @__PURE__ */ new Set();
52280
+ collecting = seen;
52281
+ try {
52282
+ return {
52283
+ value: read(),
52284
+ channels: seen
52285
+ };
52286
+ } finally {
52287
+ collecting = outer;
52288
+ if (outer) for (const channel of seen) outer.add(channel);
52289
+ }
52290
+ },
52271
52291
  get hasScripts() {
52272
52292
  return read("document", () => hasBoardScripts(state.base));
52273
52293
  },
@@ -52322,6 +52342,9 @@ function createBoardEditor(options) {
52322
52342
  get camera() {
52323
52343
  return read("camera", () => state.camera);
52324
52344
  },
52345
+ get visibleRect() {
52346
+ return read("camera", visibleRect);
52347
+ },
52325
52348
  get cameraPolicy() {
52326
52349
  return read("camera", () => state.cameraPolicy);
52327
52350
  },
package/dist/build.json CHANGED
@@ -1 +1 @@
1
- {"commit":"7ce9bec"}
1
+ {"commit":"a26ba39"}
@@ -366,7 +366,8 @@ Examples:
366
366
  if (opts.async) {
367
367
  if (jsonRequested(opts))
368
368
  return outJson(created);
369
- return ok(`Generation queued — task ID: ${created.taskRunId}\n ${resumeHint(created.taskRunId)}`);
369
+ const reserved = created.reservation ? `\n reserved: ${created.reservation.amountUsd} USD` : "";
370
+ return ok(`Generation queued — task ID: ${created.taskRunId}${reserved}\n ${resumeHint(created.taskRunId)}`);
370
371
  }
371
372
  const spin = spinner();
372
373
  let pollCount = 0;
@@ -44,6 +44,36 @@ export function registerMe(program) {
44
44
  handleHttp(e);
45
45
  }
46
46
  });
47
+ meCmd
48
+ .command("billing-activity")
49
+ .description("List your personal wallet activity, including generation reserves and refunds")
50
+ .option("--page <n>", "Page number (default 1)")
51
+ .option("--json", "Output as JSON")
52
+ .action(async (opts) => {
53
+ const client = createClient();
54
+ try {
55
+ const { activities } = await client.billing.getBalanceActivities({
56
+ page: opts.page ? parseInteger(opts.page, "page", 1) : undefined,
57
+ });
58
+ if (jsonRequested(opts))
59
+ return outJson(activities);
60
+ if (activities.items.length === 0) {
61
+ console.log(" (empty)");
62
+ return;
63
+ }
64
+ table(activities.items, [
65
+ { key: "title", label: "Activity" },
66
+ { key: "amountUsd", label: "Amount (USD)" },
67
+ { key: "operationId", label: "Operation" },
68
+ { key: "createdAt", label: "Date" },
69
+ ]);
70
+ if (activities.pagination.hasMore)
71
+ console.log(` More: --page ${activities.page + 1}`);
72
+ }
73
+ catch (e) {
74
+ handleHttp(e);
75
+ }
76
+ });
47
77
  meCmd
48
78
  .command("activity")
49
79
  .description("Show your activity across all spaces")
@@ -1,5 +1,6 @@
1
1
  import { filterDiscoverableGenerationModels, filterGenerationDeclarationsByPolicy, getAllowedGenerationModelIds, parseGenerationPolicyFromEnv, } from "@neta-art/cohub";
2
2
  import { createClient } from "../client.js";
3
+ import { explicitSpace, failSpaceTarget, resolveSpaceRef } from "../space.js";
3
4
  import { table, json as outJson, jsonRequested, error, handleHttp } from "../output.js";
4
5
  export function toMultimodalModelSummary(model) {
5
6
  return {
@@ -154,6 +155,21 @@ function printMultimodalModel(model) {
154
155
  return `${index + 1}. ${title}${prompt ? `"${prompt}"` : example.request.model}`;
155
156
  }));
156
157
  }
158
+ function formatModelContext(model) {
159
+ const value = model.contextWindow;
160
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0)
161
+ return "";
162
+ const source = typeof model.contextWindowSource === "string" ? model.contextWindowSource : null;
163
+ const ref = typeof model.contextWindowSourceRef === "string" ? `:${model.contextWindowSourceRef}` : "";
164
+ return source ? `${formatTokenCount(value)} (${source}${ref})` : formatTokenCount(value);
165
+ }
166
+ function formatTokenCount(value) {
167
+ if (value >= 1_000_000)
168
+ return `${(value / 1_000_000).toFixed(1)}M`;
169
+ if (value >= 1_000)
170
+ return `${(value / 1_000).toFixed(1)}k`;
171
+ return String(value);
172
+ }
157
173
  export function registerModels(program) {
158
174
  const cmd = program
159
175
  .command("models")
@@ -162,6 +178,7 @@ export function registerModels(program) {
162
178
 
163
179
  Examples:
164
180
  cohub models ls
181
+ cohub models ls --space <spaceId>
165
182
  cohub models ls --model-type multimodal
166
183
  cohub models ls --model-type multimodal --json
167
184
  cohub models show <model>
@@ -173,7 +190,7 @@ Examples:
173
190
  .description("List available models")
174
191
  .option("--model-type <type>", "Model type: llm | multimodal", "llm")
175
192
  .option("--json", "Output as JSON")
176
- .action(async (opts) => {
193
+ .action(async (opts, command) => {
177
194
  const client = createClient();
178
195
  try {
179
196
  if (opts.modelType === "multimodal") {
@@ -201,7 +218,9 @@ Examples:
201
218
  if (opts.modelType && opts.modelType !== "llm") {
202
219
  return error("Invalid model type", "Use --model-type llm or --model-type multimodal");
203
220
  }
204
- const catalog = await client.models.list();
221
+ const spaceRef = explicitSpace(command);
222
+ const spaceId = spaceRef ? await resolveSpaceRef(spaceRef).catch(failSpaceTarget) : undefined;
223
+ const catalog = await client.models.list({ spaceId });
205
224
  const visibleCatalog = filterHiddenLlmModels(catalog);
206
225
  if (jsonRequested(opts))
207
226
  return outJson(visibleCatalog);
@@ -213,10 +232,12 @@ Examples:
213
232
  table(entries.map((entry) => ({
214
233
  id: entry.id,
215
234
  provider: entry.provider,
235
+ context: formatModelContext(entry.model),
216
236
  cost: formatLlmModelCost(entry.model),
217
237
  })), [
218
238
  { key: "id", label: "ID" },
219
239
  { key: "provider", label: "Provider" },
240
+ { key: "context", label: "Context" },
220
241
  { key: "cost", label: "Cost" },
221
242
  ]);
222
243
  }
@@ -33,7 +33,7 @@ export function registerSpaceWallet(spaces) {
33
33
  const value = await createClient().space(await resolveSpace(spaces)).wallet.activities(page);
34
34
  if (jsonRequested(opts))
35
35
  return outJson(value);
36
- table(value.items, [{ key: "kind", label: "Activity" }, { key: "amountUsd", label: "Amount (USD)" }, { key: "actorUserId", label: "User" }, { key: "createdAt", label: "Date" }]);
36
+ table(value.items, [{ key: "title", label: "Activity" }, { key: "amountUsd", label: "Amount (USD)" }, { key: "actorUserId", label: "User" }, { key: "createdAt", label: "Date" }]);
37
37
  }
38
38
  catch (cause) {
39
39
  handleHttp(cause);
@@ -1,7 +1,7 @@
1
1
  import { readdir, stat } from "node:fs/promises";
2
2
  import { basename, dirname, relative, resolve, sep } from "node:path";
3
3
  import { APPROVAL_MODES, harnessSchema, isApprovalMode, isModelThinkingLevel, MODEL_THINKING_LEVELS, readSentTurns, readSessionTurnOrigin, resolveCohubEnvironment } from "@neta-art/cohub";
4
- import { uploadAvatarAsset, uploadChatImageAsset } from "../avatar.js";
4
+ import { uploadAvatarAsset, uploadChatImageAsset, uploadLikeStickerAsset } from "../avatar.js";
5
5
  import { createClient } from "../client.js";
6
6
  import { collectOption, readPromptContent } from "../command-input.js";
7
7
  import { table, json as outJson, jsonRequested, ok, error, handleHttp, formatEpochMs, truncateText } from "../output.js";
@@ -202,15 +202,12 @@ async function sendPrompt(command, words, opts) {
202
202
  if (opts.note) {
203
203
  const agentOnly = Object.entries({
204
204
  "--delay-ms": opts.delayMs, "--at": opts.at, "--cron": opts.cron, "--model": opts.model, "--provider": opts.provider,
205
- "--thinking-level": opts.thinkingLevel, "--approval-mode": opts.approvalMode, "--service-tier": opts.serviceTier,
205
+ "--thinking-level": opts.thinkingLevel, "--context-window": opts.contextWindow, "--approval-mode": opts.approvalMode, "--service-tier": opts.serviceTier,
206
206
  "--read-only": opts.readOnly, "--steer": opts.steer, "--env": opts.env?.length,
207
207
  }).flatMap(([flag, value]) => value ? [flag] : []);
208
208
  if (agentOnly.length)
209
209
  return error("Conflicting options", `--note cannot be combined with ${agentOnly.join(", ")}`);
210
210
  }
211
- if (opts.reply && (opts.note || scheduleFlags.length)) {
212
- return error("Conflicting options", "--reply cannot be combined with --note or scheduling");
213
- }
214
211
  const requestedThinkingLevel = opts.thinkingLevel?.trim() || undefined;
215
212
  const thinkingLevel = isModelThinkingLevel(requestedThinkingLevel) ? requestedThinkingLevel : undefined;
216
213
  if (requestedThinkingLevel && !thinkingLevel) {
@@ -218,6 +215,7 @@ async function sendPrompt(command, words, opts) {
218
215
  }
219
216
  if (opts.approvalMode !== undefined && !isApprovalMode(opts.approvalMode))
220
217
  return error("Invalid approval mode", `Use ${APPROVAL_MODES.join("|")}`);
218
+ const contextWindow = opts.contextWindow !== undefined ? parseInteger(opts.contextWindow, "context-window", { min: 1 }) : undefined;
221
219
  const spaceId = await resolveSpace(command, { home: true });
222
220
  const client = createClient();
223
221
  try {
@@ -265,6 +263,7 @@ async function sendPrompt(command, words, opts) {
265
263
  provider: opts.provider,
266
264
  harness: opts.harness,
267
265
  thinkingLevel,
266
+ ...(contextWindow ? { contextWindow } : {}),
268
267
  ...(isApprovalMode(opts.approvalMode) ? { approvalMode: opts.approvalMode } : {}),
269
268
  ...(opts.serviceTier ? { serviceTier: opts.serviceTier } : {}),
270
269
  accessMode: opts.readOnly ? "read_only" : "full_access",
@@ -272,14 +271,11 @@ async function sendPrompt(command, words, opts) {
272
271
  env: parseEnvOptions(opts.env),
273
272
  schedule,
274
273
  labelRefs: opts.label?.length ? opts.label : undefined,
275
- ...(opts.reply ? { reply: "prompt" } : {}),
276
274
  });
277
275
  if (jsonRequested(opts))
278
276
  return outJson(result);
279
- if (result.mode === "immediate") {
280
- const label = opts.note ? "Note recorded" : opts.reply ? "Prompt sent; the reply will come back to this Chat" : "Prompt sent";
281
- return ok(`${label} — sessionId: ${result.session.id}, turnId: ${result.turn.id}`);
282
- }
277
+ if (result.mode === "immediate")
278
+ return ok(`${opts.note ? "Note recorded" : "Prompt sent"} — sessionId: ${result.session.id}, turnId: ${result.turn.id}`);
283
279
  if (result.mode === "repeat")
284
280
  return ok(`Prompt scheduled — cronJobId: ${result.cronJobId}, nextRunAt: ${result.nextRunAt}`);
285
281
  return ok(`Prompt scheduled — taskRunId: ${result.taskRunId}, scheduledAt: ${result.scheduledAt}`);
@@ -377,6 +373,7 @@ export function registerPrompt(program) {
377
373
  .option("-p, --provider <provider>", "Provider name")
378
374
  .option("--harness <harness>", `Harness: ${harnessSchema.options.join(", ")}`, "cohub")
379
375
  .option("--thinking-level <level>", `Thinking level: ${MODEL_THINKING_LEVELS.join("|")}`)
376
+ .option("--context-window <tokens>", "Context window for this session from this prompt on; capped at the platform value")
380
377
  .option("--approval-mode <mode>", `Local Harness approval mode: ${APPROVAL_MODES.join("|")}`)
381
378
  .option("--service-tier <tier>", "Local Harness service tier, e.g. priority for Codex Fast")
382
379
  .option("--read-only", "Use read-only tools")
@@ -389,7 +386,6 @@ export function registerPrompt(program) {
389
386
  .option("--env <key=value>", "Set an environment variable for this turn", collectOption, [])
390
387
  .option("--image <path>", "Attach an image", collectOption, [])
391
388
  .option("--note", "Record the message without an AI reply")
392
- .option("--reply", "Send the final reply back to the calling Chat and run its Agent")
393
389
  .option("--json", "Output as JSON")
394
390
  .action((words, opts) => sendPrompt(program, words, opts));
395
391
  program
@@ -611,7 +607,8 @@ export function registerSpaces(program) {
611
607
  return outJson(space);
612
608
  const usage = space.workspaceUsage;
613
609
  const storage = usage ? `${usage.bytes === null ? "-" : formatBytes(usage.bytes)} (${usage.status})` : undefined;
614
- table([{ ...space, storage }], [
610
+ const likeSticker = space.publicProfile?.likeSticker?.url;
611
+ table([{ ...space, storage, likeSticker }], [
615
612
  { key: "id", label: "ID" },
616
613
  { key: "name", label: "Name" },
617
614
  { key: "slug", label: "Slug" },
@@ -619,6 +616,7 @@ export function registerSpaces(program) {
619
616
  { key: "status", label: "Status" },
620
617
  { key: "createdAt", label: "Created" },
621
618
  ...(storage ? [{ key: "storage", label: "Storage" }] : []),
619
+ ...(likeSticker ? [{ key: "likeSticker", label: "Like sticker" }] : []),
622
620
  ]);
623
621
  }
624
622
  catch (e) {
@@ -691,6 +689,28 @@ export function registerSpaces(program) {
691
689
  handleHttp(e);
692
690
  }
693
691
  });
692
+ // ── spaces like-sticker ──
693
+ spacesCmd
694
+ .command("like-sticker [path]")
695
+ .description("Set the image that replaces the heart on the space's published Apps")
696
+ .option("--clear", "Restore the default heart")
697
+ .option("--json", "Output as JSON")
698
+ .action(async (path, opts) => {
699
+ if (Boolean(path) === Boolean(opts.clear))
700
+ return error("Pass an image path or --clear");
701
+ const spaceId = await resolveSpace(spacesCmd);
702
+ const client = createClient();
703
+ try {
704
+ const asset = path ? await uploadLikeStickerAsset({ client, spaceId, path }) : null;
705
+ const result = await client.space(spaceId).profile({ likeSticker: asset ? { url: asset.publicUrl } : null });
706
+ if (jsonRequested(opts))
707
+ return outJson({ ...result, ...(asset ? { asset } : {}) });
708
+ ok(asset ? "Like sticker updated" : "Like sticker cleared");
709
+ }
710
+ catch (e) {
711
+ handleHttp(e);
712
+ }
713
+ });
694
714
  registerSpaceSetup(spacesCmd);
695
715
  // ── spaces config ──
696
716
  spacesCmd
@@ -754,6 +774,7 @@ export function registerSpaces(program) {
754
774
  .option("-m, --model <model>", "Model name")
755
775
  .option("-p, --provider <provider>", "Provider name")
756
776
  .option("--thinking-level <level>", `Thinking level: ${MODEL_THINKING_LEVELS.join("|")}`)
777
+ .option("--context-window <tokens>", "Context window for this session from this prompt on; capped at the platform value")
757
778
  .option("--approval-mode <mode>", `Local Harness approval mode: ${APPROVAL_MODES.join("|")}`)
758
779
  .option("--service-tier <tier>", "Local Harness service tier, e.g. priority for Codex Fast")
759
780
  .option("--read-only", "Use read-only tools")
@@ -766,7 +787,6 @@ export function registerSpaces(program) {
766
787
  .option("--env <key=value>", "Set an environment variable for this turn", collectOption, [])
767
788
  .option("--image <path>", "Attach an image", collectOption, [])
768
789
  .option("--note", "Record the message without an AI reply")
769
- .option("--reply", "Send the final reply back to the calling Chat and run its Agent")
770
790
  .option("--json", "Output as JSON")
771
791
  .action((words, opts) => sendPrompt(spacesCmd, words, opts));
772
792
  // ── spaces completion ──
package/dist/host/auth.js CHANGED
@@ -3,6 +3,7 @@ import { basename, dirname } from "node:path";
3
3
  import { HOST_SERVICE_SHELL_EVENTS, hostAuthChangedSchema, hostShellOpenSchema } from "@neta-art/cohub/host-bridge";
4
4
  import { AuthRequiredError, authSessionPath, pollDeviceCode, readAuthSession, requestDeviceCode, resolveAccessToken, revokeAndClearAuthSession, } from "../auth.js";
5
5
  import { clearHomeSpaceCache, jwtClaim } from "../space.js";
6
+ const REOPEN_AFTER_MS = 10_000;
6
7
  function snapshot() {
7
8
  const session = readAuthSession();
8
9
  if (!session)
@@ -21,6 +22,8 @@ export class HostAuth {
21
22
  #debounce;
22
23
  #rewatch;
23
24
  #pending = null;
25
+ #requesting = null;
26
+ #redirectPath;
24
27
  constructor(emit, onAccountChanged) {
25
28
  this.emit = emit;
26
29
  this.onAccountChanged = onAccountChanged;
@@ -65,22 +68,31 @@ export class HostAuth {
65
68
  return { authenticated: subject !== null, userUuid: null, subject, email: null };
66
69
  }
67
70
  async signIn(redirectPath) {
68
- const destination = hostAuthChangedSchema.shape.redirectPath.safeParse(redirectPath).data;
69
- if (this.#pending && this.#pending.expiresAt > Date.now()) {
70
- this.#pending.redirectPath = destination;
71
- this.#open(this.#pending.url);
71
+ this.#redirectPath = hostAuthChangedSchema.shape.redirectPath.safeParse(redirectPath).data;
72
+ const pending = this.#pending;
73
+ if (pending && pending.expiresAt > Date.now()) {
74
+ if (Date.now() - pending.openedAt >= REOPEN_AFTER_MS)
75
+ this.#openPending(pending);
72
76
  return true;
73
77
  }
78
+ this.#requesting ??= this.#request().finally(() => { this.#requesting = null; });
79
+ await this.#requesting;
80
+ return true;
81
+ }
82
+ async #request() {
74
83
  const code = await requestDeviceCode();
75
- const pending = { url: code.verificationUriComplete, expiresAt: code.expiresAt, redirectPath: destination };
84
+ const pending = { url: code.verificationUriComplete, expiresAt: code.expiresAt, openedAt: 0 };
76
85
  this.#pending = pending;
77
- this.#open(pending.url);
86
+ this.#openPending(pending);
78
87
  void pollDeviceCode(code)
79
- .then(() => this.#sync({ redirectPath: pending.redirectPath, signedIn: true }))
88
+ .then(() => this.#sync({ redirectPath: this.#redirectPath, signedIn: true }))
80
89
  .catch((error) => process.stderr.write(`Sign-in did not complete: ${error instanceof Error ? error.message : String(error)}\n`))
81
90
  .finally(() => { if (this.#pending === pending)
82
91
  this.#pending = null; });
83
- return true;
92
+ }
93
+ #openPending(pending) {
94
+ pending.openedAt = Date.now();
95
+ this.#open(pending.url);
84
96
  }
85
97
  async signOut() {
86
98
  await revokeAndClearAuthSession();
@@ -50,6 +50,7 @@ export class NativeRuntime {
50
50
  if (link.sessionFile)
51
51
  this.ingest.touch(link.sessionFile);
52
52
  },
53
+ onDroppedLine: (nativeSessionId, bytes) => options.diagnostics.log("warn", "native.pi_line_dropped", { nativeSessionId, bytes }, { component: "native", harness: "pi" }),
53
54
  });
54
55
  this.codex = new CodexShared(options.executables.codex || "codex", options.root, Boolean(options.config?.codexShared) && options.harnesses.includes("codex"));
55
56
  this.codex.onConnect((channel) => this.observeCodex(channel));
@@ -31,5 +31,6 @@ type Pi = {
31
31
  };
32
32
  /** Runtime directory shared with the CLI; one socket per bound directory, hashed to stay short. */
33
33
  export declare function controlSocketPath(root: string): string;
34
+ export declare function forwardedEvent(name: string, event: unknown): Record<string, unknown>;
34
35
  export default function cohub(pi: Pi): void;
35
36
  export {};
@@ -43,8 +43,25 @@ function locateSocket(cwd) {
43
43
  }
44
44
  /** How often a missing or lost Runtime is looked for again. */
45
45
  const RECONNECT_MS = 3_000;
46
- /** Streamed events the daemon uses; everything else Pi emits stays local. */
47
- const FORWARDED = new Set(["agent_start", "agent_end", "agent_settled", "turn_start", "turn_end", "message_start", "message_update", "message_end", "tool_execution_start", "tool_execution_update", "tool_execution_end"]);
46
+ const MESSAGE_FIELDS = ["message", "assistantMessageEvent"];
47
+ const TOOL_FIELDS = ["toolCallId", "toolName", "args", "result", "partialResult", "isError"];
48
+ /**
49
+ * Streamed events the daemon uses, with the fields it reads; everything else Pi emits stays local.
50
+ * An allowlist, since Pi adds fields across versions, some with the whole context (`turn_end`).
51
+ */
52
+ const FORWARDED = {
53
+ agent_start: [], agent_end: ["willRetry"], agent_settled: [], turn_start: [], turn_end: ["message", "toolResults"],
54
+ message_start: MESSAGE_FIELDS, message_update: MESSAGE_FIELDS, message_end: MESSAGE_FIELDS,
55
+ tool_execution_start: TOOL_FIELDS, tool_execution_update: TOOL_FIELDS, tool_execution_end: TOOL_FIELDS,
56
+ };
57
+ export function forwardedEvent(name, event) {
58
+ const source = (event ?? {});
59
+ const forwarded = { type: name };
60
+ for (const field of FORWARDED[name] ?? [])
61
+ if (field in source)
62
+ forwarded[field] = source[field];
63
+ return forwarded;
64
+ }
48
65
  export default function cohub(pi) {
49
66
  // Cohub may load this file explicitly into a Pi it starts; never attach twice.
50
67
  const marker = Symbol.for("cohub.pi.control");
@@ -148,12 +165,12 @@ export default function cohub(pi) {
148
165
  });
149
166
  };
150
167
  pi.on("session_start", (_event, ctx) => attach(ctx));
151
- for (const name of FORWARDED) {
168
+ for (const name of Object.keys(FORWARDED)) {
152
169
  pi.on(name, (event, ctx) => {
153
170
  context = ctx;
154
171
  if (!socket)
155
172
  attach(ctx);
156
- send({ type: "event", sessionId: ctx.sessionManager.getSessionId(), event: { ...event, type: name } });
173
+ send({ type: "event", sessionId: ctx.sessionManager.getSessionId(), event: forwardedEvent(name, event) });
157
174
  });
158
175
  }
159
176
  // Pi replaces this instance on /new, /resume, /fork and /reload, and loads the next one only
@@ -33,6 +33,8 @@ export declare class PiLink {
33
33
  onEvent?: (session: PiSessionLink, event: Record<string, unknown>) => void;
34
34
  onConnect?: (session: PiSessionLink) => void;
35
35
  onDisconnect?: (session: PiSessionLink) => void;
36
+ /** A line over the limit was skipped; the connection stays up. */
37
+ onDroppedLine?: (sessionId: string | null, bytes: number) => void;
36
38
  });
37
39
  get socketPath(): string;
38
40
  subscribe(sessionId: string, listener: (event: Record<string, unknown>) => void): () => void;
@@ -149,9 +149,12 @@ export class PiLink {
149
149
  });
150
150
  }
151
151
  accept(socket) {
152
- let buffer = "";
152
+ /** The line being received; an oversized one is only counted, until its newline arrives. */
153
+ let parts = [];
154
+ let size = 0;
153
155
  /** This connection's link; a newer connection for the same session replaces it in the map. */
154
156
  let own = null;
157
+ const dropped = (bytes) => this.options.onDroppedLine?.(own?.sessionId ?? null, bytes);
155
158
  socket.setNoDelay?.(true);
156
159
  socket.on("error", () => socket.destroy());
157
160
  socket.on("close", () => {
@@ -172,14 +175,25 @@ export class PiLink {
172
175
  this.options.onDisconnect?.(link);
173
176
  });
174
177
  socket.on("data", (bytes) => {
175
- buffer += bytes.toString("utf8");
176
- if (buffer.length > MAX_LINE_BYTES) {
177
- socket.destroy();
178
- return;
179
- }
180
- for (let end = buffer.indexOf("\n"); end >= 0; end = buffer.indexOf("\n")) {
181
- const line = buffer.slice(0, end);
182
- buffer = buffer.slice(end + 1);
178
+ for (let start = 0;;) {
179
+ const end = bytes.indexOf(0x0a, start);
180
+ const piece = bytes.subarray(start, end < 0 ? bytes.length : end);
181
+ size += piece.length;
182
+ if (size <= MAX_LINE_BYTES)
183
+ parts.push(piece);
184
+ else
185
+ parts = [];
186
+ if (end < 0)
187
+ return;
188
+ start = end + 1;
189
+ const length = size, kept = parts;
190
+ parts = [];
191
+ size = 0;
192
+ if (length > MAX_LINE_BYTES) {
193
+ dropped(length);
194
+ continue;
195
+ }
196
+ const line = Buffer.concat(kept, length).toString("utf8");
183
197
  if (!line)
184
198
  continue;
185
199
  let message;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@neta-art/cohub-cli",
3
- "version": "10.22.0",
3
+ "version": "10.23.0",
4
4
  "description": "CLI for Cohub — spaces, sessions, and agent collaboration.",
5
5
  "type": "module",
6
6
  "engines": {
@@ -24,7 +24,7 @@
24
24
  "NOTICE"
25
25
  ],
26
26
  "dependencies": {
27
- "@neta-art/cohub": "13.13.0",
27
+ "@neta-art/cohub": "13.14.0",
28
28
  "@neta-art/generation": "0.2.15",
29
29
  "commander": "^15.0.0",
30
30
  "sharp": "^0.35.4",