@neta-art/cohub-cli 10.21.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) {
@@ -67659,6 +67659,7 @@ function createScriptRuntime(module, initial, host) {
67659
67659
  invalidate(false);
67660
67660
  },
67661
67661
  async commit(patch) {
67662
+ if (input.capabilities && !input.capabilities.includes("board.commit")) throw new Error("This viewer cannot edit the Board.");
67662
67663
  return await host.call("board.commit", {
67663
67664
  patch,
67664
67665
  frame: stepping
@@ -44495,6 +44495,7 @@ function createScriptRuntime(module, initial, host) {
44495
44495
  invalidate(false);
44496
44496
  },
44497
44497
  async commit(patch) {
44498
+ if (input.capabilities && !input.capabilities.includes("board.commit")) throw new Error("This viewer cannot edit the Board.");
44498
44499
  return await host.call("board.commit", {
44499
44500
  patch,
44500
44501
  frame: stepping
@@ -47531,6 +47532,7 @@ function createNodeBoardScriptHost(renderer, options) {
47531
47532
  }
47532
47533
  function createNodeBoardScriptRuntime(renderer, options) {
47533
47534
  const { callbacks } = options;
47535
+ const capabilities = Object.keys(callbacks.capabilities);
47534
47536
  const lanes = createNodeScriptLanes(renderer, {
47535
47537
  ...options,
47536
47538
  call: (id, name, input) => {
@@ -47651,10 +47653,13 @@ function createNodeBoardScriptRuntime(renderer, options) {
47651
47653
  entries.set(id, entry);
47652
47654
  }
47653
47655
  if (entry.error || entry.busy) continue;
47654
- const input = scopedInput(document, attachment, item ? scene.layout.box(id) : {
47655
- width: 0,
47656
- height: 0
47657
- });
47656
+ const input = {
47657
+ ...scopedInput(document, attachment, item ? scene.layout.box(id) : {
47658
+ width: 0,
47659
+ height: 0
47660
+ }),
47661
+ capabilities
47662
+ };
47658
47663
  const inputKey = JSON.stringify(input);
47659
47664
  if (!(inputKey !== entry.inputKey || entry.dirty || entry.events.length > 0) && entry.output && (entry.time === time || !entry.output.animated && !entry.output.updating)) continue;
47660
47665
  entry.dirty = false;
@@ -50335,7 +50340,10 @@ function createInteractionModule(ctx) {
50335
50340
  });
50336
50341
  }
50337
50342
  function browsing() {
50338
- return options.readonly === true || ctx.frames.view()?.present === true;
50343
+ return options.readonly === true || state.tool === "play" || ctx.frames.view()?.present === true;
50344
+ }
50345
+ function movable(item) {
50346
+ return Boolean(item && !ctx.query.isLocked(item) && registry.capabilities(item).canMove);
50339
50347
  }
50340
50348
  function opensOnTap(item) {
50341
50349
  return registry.activation(item, browsing()) === "tap";
@@ -50549,7 +50557,7 @@ function createInteractionModule(ctx) {
50549
50557
  const dx = event.screen.x - gesture.start.x;
50550
50558
  const dy = event.screen.y - gesture.start.y;
50551
50559
  const item = state.scene.get(gesture.itemId);
50552
- if (!(!browsing() && state.tool === "select" && item && !ctx.query.isLocked(item) && registry.capabilities(item).canMove)) {
50560
+ if (!(!options.readonly && !ctx.frames.view()?.present && (state.tool === "select" || state.tool === "play") && movable(item))) {
50553
50561
  state.interaction = {
50554
50562
  type: "panning",
50555
50563
  start: gesture.start,
@@ -50585,7 +50593,7 @@ function createInteractionModule(ctx) {
50585
50593
  }
50586
50594
  const id = gesture.type === "pressing" ? gesture.itemId : gesture.type === "panning" && !gesture.moved ? gesture.tapSelection?.targetId : null;
50587
50595
  const item = id ? state.scene.get(id) : null;
50588
- if (!item || ctx.query.isLocked(item) || !registry.capabilities(item).canMove) return null;
50596
+ if (!movable(item)) return null;
50589
50597
  state.selection = [item.id];
50590
50598
  state.tool = "select";
50591
50599
  state.interaction = {
@@ -50624,6 +50632,23 @@ function createInteractionModule(ctx) {
50624
50632
  return item?.type === "frame" && registry.hitTest(item, point);
50625
50633
  });
50626
50634
  }
50635
+ function play(event) {
50636
+ if (!state.spaceHeld && pressCard(event)) return;
50637
+ const item = !state.spaceHeld && event.button === 0 ? ctx.query.pickAt(event.world, event.pointerType) : null;
50638
+ state.interaction = movable(item) ? {
50639
+ type: "translating",
50640
+ start: event.world,
50641
+ ...ctx.selection.grab([item.id]),
50642
+ moved: false,
50643
+ duplicate: false
50644
+ } : {
50645
+ type: "panning",
50646
+ start: event.screen,
50647
+ origin: { ...state.camera },
50648
+ moved: false,
50649
+ tapSelection: null
50650
+ };
50651
+ }
50627
50652
  function translateSelection(event, tap) {
50628
50653
  state.interaction = {
50629
50654
  type: "translating",
@@ -50678,6 +50703,7 @@ function createInteractionModule(ctx) {
50678
50703
  }
50679
50704
  browseByTouch(event);
50680
50705
  const { tool, spaceHeld } = state;
50706
+ if (tool === "play") return play(event);
50681
50707
  const additive = event.shiftKey || event.metaKey || event.ctrlKey;
50682
50708
  if (!spaceHeld && (tool === "hand" || options.readonly) && pressCard(event)) return;
50683
50709
  const fingerOnPenCanvas = tool === "draw" && event.pointerType === "touch" && penSeen;
@@ -50908,7 +50934,8 @@ function createInteractionModule(ctx) {
50908
50934
  };
50909
50935
  let tx = dx;
50910
50936
  let ty = dy;
50911
- if (!event.metaKey && !event.ctrlKey) {
50937
+ const playing = state.tool === "play";
50938
+ if (!playing && !event.metaKey && !event.ctrlKey) {
50912
50939
  const snap = computeTranslationSnap(shift(dx, dy), movingWith(current.origin));
50913
50940
  tx += snap.dx;
50914
50941
  ty += snap.dy;
@@ -50916,7 +50943,9 @@ function createInteractionModule(ctx) {
50916
50943
  } else state.snapGuides = [];
50917
50944
  ctx.document.writeDraft(ctx.selection.placed(shift(tx, ty), current.grabbed), false, current.grabbed);
50918
50945
  let dropTargetId = null;
50919
- for (const parent of dropParents(current.origin, true).values()) if (parent) dropTargetId = parent;
50946
+ if (!playing) {
50947
+ for (const parent of dropParents(current.origin, true).values()) if (parent) dropTargetId = parent;
50948
+ }
50920
50949
  if ((current.dropTargetId ?? null) !== dropTargetId) state.interaction = {
50921
50950
  ...current,
50922
50951
  dropTargetId
@@ -52118,6 +52147,7 @@ function createBoardEditor(options) {
52118
52147
  const registry = options.registry ?? defaultBoardRegistry;
52119
52148
  const channels = createChannels();
52120
52149
  const track = options.track ?? (() => {});
52150
+ let collecting = null;
52121
52151
  const preferences = options.preferences;
52122
52152
  const state = observable({
52123
52153
  base: options.document,
@@ -52227,11 +52257,16 @@ function createBoardEditor(options) {
52227
52257
  };
52228
52258
  ctx.preferencesChanged();
52229
52259
  }
52260
+ function note(channel) {
52261
+ track(channel);
52262
+ collecting?.add(channel);
52263
+ }
52230
52264
  function read(channel, value) {
52231
- if (typeof channel === "string") track(channel);
52232
- else for (const each of channel) track(each);
52265
+ if (typeof channel === "string") note(channel);
52266
+ else for (const each of channel) note(each);
52233
52267
  return value();
52234
52268
  }
52269
+ const visibleRect = memo(() => [state.camera, state.surfaceSize], (_camera, _surface) => camera.visibleRect());
52235
52270
  function tracked(channels, query) {
52236
52271
  return (...args) => read(channels, () => query(...args));
52237
52272
  }
@@ -52239,6 +52274,20 @@ function createBoardEditor(options) {
52239
52274
  registry,
52240
52275
  readonly: options.readonly === true,
52241
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
+ },
52242
52291
  get hasScripts() {
52243
52292
  return read("document", () => hasBoardScripts(state.base));
52244
52293
  },
@@ -52293,6 +52342,9 @@ function createBoardEditor(options) {
52293
52342
  get camera() {
52294
52343
  return read("camera", () => state.camera);
52295
52344
  },
52345
+ get visibleRect() {
52346
+ return read("camera", visibleRect);
52347
+ },
52296
52348
  get cameraPolicy() {
52297
52349
  return read("camera", () => state.cameraPolicy);
52298
52350
  },
@@ -52322,7 +52374,7 @@ function createBoardEditor(options) {
52322
52374
  ctx.chosenTool = value;
52323
52375
  state.tool = value;
52324
52376
  if (isCreationBoardTool(value)) state.hoverId = null;
52325
- if (value === "draw" || value === "arrow") {
52377
+ if (value === "draw" || value === "arrow" || value === "play") {
52326
52378
  state.selection = [];
52327
52379
  state.editingId = null;
52328
52380
  }
@@ -52940,7 +52992,7 @@ function boardScriptsMayTakeInput(event, editor) {
52940
52992
  return !editor.onHandle();
52941
52993
  }
52942
52994
  function boardScriptTakesTool(tools, tool, readonly) {
52943
- return readonly || (tools ?? DEFAULT_TOOLS).includes(tool);
52995
+ return readonly || tool === "play" || (tools ?? DEFAULT_TOOLS).includes(tool);
52944
52996
  }
52945
52997
  const DEFAULT_TOOLS = ["select", "hand"];
52946
52998
  //#endregion
@@ -53078,10 +53130,10 @@ function createBoardScriptController(options) {
53078
53130
  throw error;
53079
53131
  }
53080
53132
  },
53081
- "board.commit": (id, value) => {
53133
+ ...editor.readonly ? {} : { "board.commit": async (id, value) => {
53082
53134
  const { patch, frame } = value;
53083
53135
  return commits.commit(id, patch, !frame && activated(id));
53084
- },
53136
+ } },
53085
53137
  "board.layoutText": async (_id, value) => layoutBoardScriptText(value)
53086
53138
  },
53087
53139
  onOutput: (id, output) => {
@@ -1,7 +1,7 @@
1
1
  import type { BoardExportRegion, BoardThemeId } from "@neta-art/cohub/board";
2
2
  import type { BoardNodeExportFormat } from "@neta-art/cohub/board/export/node";
3
3
  import type { BoardScriptHarnessPointer, BoardScriptHarnessPress } from "@neta-art/cohub/board/testing";
4
- declare const TOOLS: readonly ["select", "hand", "text", "shape", "draw", "arrow", "frame"];
4
+ declare const TOOLS: readonly ["select", "hand", "play", "text", "shape", "draw", "arrow", "frame"];
5
5
  type Point = {
6
6
  x: number;
7
7
  y: number;
@@ -6,7 +6,7 @@ import { boardScriptAttachments, boardShaderParameters, buildBoardScene, checkBo
6
6
  import { settleBoardDocument } from "./board-media.js";
7
7
  import { parseBoardTime } from "./board-time.js";
8
8
  import { createClient } from "./client.js";
9
- const TOOLS = ["select", "hand", "text", "shape", "draw", "arrow", "frame"];
9
+ const TOOLS = ["select", "hand", "play", "text", "shape", "draw", "arrow", "frame"];
10
10
  const POINTER_TYPES = ["mouse", "pen", "touch"];
11
11
  const MAX_STEPS = 10_000;
12
12
  const MAX_TIME_MS = 600_000;
package/dist/build.json CHANGED
@@ -1 +1 @@
1
- {"commit":"b2e3ef6"}
1
+ {"commit":"a26ba39"}
@@ -350,6 +350,8 @@ function registerSimulateCommand(boards) {
350
350
  Steps are {"steps": [...]}, points in board coordinates, run on a virtual clock:
351
351
  {"wait": "500ms"} {"tool": "draw"} {"tap": [x, y]} {"drag": [[x, y], ...], "pointerType": "pen"}
352
352
  {"pointer": "down", "at": [x, y]} {"key": "Enter"} {"select": ["id"]}
353
+ {"tool": "play"} acts like an App visitor: drags move unlocked items, empty space pans,
354
+ and script regions take every press.
353
355
 
354
356
  Shaders are compiled with a local Chrome, Chromium or Edge when one is found, before
355
357
  the steps run; their errors join the scripts' errors and stop the run.
@@ -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();
@@ -3,7 +3,10 @@ import { type JsonRecord } from "../json-rpc.js";
3
3
  import type { ApprovalBroker, ApprovalRequest } from "../native/approvals.js";
4
4
  /** Cards answer Claude Code's permission prompts, so without `--permission-prompt-tool stdio` no mode is offered. */
5
5
  export declare function claudeApprovalModes(help: string): ApprovalMode[];
6
- /** The platform's read-only access always wins; `null` keeps `acceptEdits`. */
6
+ /**
7
+ * The platform's read-only access always wins. No mode follows local settings, as the picker shows;
8
+ * a CLI that cannot ask (no modes) keeps `acceptEdits` (`null`), since its prompts would be denied.
9
+ */
7
10
  export declare function claudeApprovalMode(input: RuntimeTurnInput, modes: readonly ApprovalMode[]): ApprovalMode | null;
8
11
  export declare const claudePermissionMode: (mode: Exclude<ApprovalMode, "read_only"> | null) => string | null;
9
12
  /**
@@ -10,15 +10,20 @@ export function claudeApprovalModes(help) {
10
10
  const choices = new Set([...(/\(choices:([^)]*)\)/.exec(option)?.[1] ?? "").matchAll(/"([^"]+)"/g)].map((match) => match[1]));
11
11
  return APPROVAL_MODES.filter((mode) => mode === "inherit" || choices.has(PERMISSION_MODES[mode] ?? ""));
12
12
  }
13
- /** The platform's read-only access always wins; `null` keeps `acceptEdits`. */
13
+ /**
14
+ * The platform's read-only access always wins. No mode follows local settings, as the picker shows;
15
+ * a CLI that cannot ask (no modes) keeps `acceptEdits` (`null`), since its prompts would be denied.
16
+ */
14
17
  export function claudeApprovalMode(input, modes) {
15
18
  if (input.accessMode === "read_only" && input.approvalMode && input.approvalMode !== "read_only") {
16
19
  throw new Error("The approval mode conflicts with read-only access");
17
20
  }
18
21
  if (input.accessMode === "read_only")
19
22
  return "read_only";
20
- if (!input.approvalMode || modes.includes(input.approvalMode))
21
- return input.approvalMode ?? null;
23
+ if (!input.approvalMode)
24
+ return modes.includes("inherit") ? "inherit" : null;
25
+ if (modes.includes(input.approvalMode))
26
+ return input.approvalMode;
22
27
  throw new Error(`This Claude Code does not support the ${input.approvalMode} approval mode; update Claude Code and restart the Runtime`);
23
28
  }
24
29
  export const claudePermissionMode = (mode) => mode ? PERMISSION_MODES[mode] : "acceptEdits";
@@ -122,14 +122,23 @@ async function claudeInitialize(executable, cwd, extra = []) {
122
122
  await host.close();
123
123
  }
124
124
  }
125
- /** Gateway models are served by `ANTHROPIC_BASE_URL`, so they carry its host as provider. */
126
- function claudeModelCatalog(entries, baseUrl) {
127
- let gateway = "gateway";
125
+ /**
126
+ * A gateway at `ANTHROPIC_BASE_URL` serves every model, built-in aliases included, so all carry its host.
127
+ * Discovered gateway models without a visible base URL (e.g. set in Claude settings) get a generic name.
128
+ */
129
+ function claudeProvider(baseUrl, discovered = false) {
130
+ let host = "";
128
131
  try {
129
132
  if (baseUrl)
130
- gateway = new URL(baseUrl).hostname.slice(0, 100) || gateway;
133
+ host = new URL(baseUrl).hostname.slice(0, 100);
131
134
  }
132
- catch { /* Keep the generic name. */ }
135
+ catch { /* Unparsable; use the generic name. */ }
136
+ if (host === "api.anthropic.com")
137
+ return profile.provider;
138
+ return host || (baseUrl || discovered ? "gateway" : profile.provider);
139
+ }
140
+ function claudeModelCatalog(entries, baseUrl) {
141
+ const provider = claudeProvider(baseUrl, entries.some((value) => text(record(value).description).startsWith("From gateway")));
133
142
  const seen = new Set();
134
143
  return entries.flatMap((value) => {
135
144
  const model = record(value);
@@ -139,8 +148,7 @@ function claudeModelCatalog(entries, baseUrl) {
139
148
  seen.add(id);
140
149
  const effortLevels = model.supportsEffort === true ? array(model.supportedEffortLevels).filter((level) => typeof level === "string") : [];
141
150
  return [streamJsonModel(profile, id, (text(model.displayName) || id).slice(0, 255), {
142
- reasoning: effortLevels.length > 0, effortLevels, isDefault: id === DEFAULT_MODEL,
143
- provider: text(model.description).startsWith("From gateway") ? gateway : profile.provider,
151
+ reasoning: effortLevels.length > 0, effortLevels, isDefault: id === DEFAULT_MODEL, provider,
144
152
  })];
145
153
  });
146
154
  }
@@ -162,11 +170,12 @@ export const claudeHarness = {
162
170
  throw error;
163
171
  }
164
172
  // Aliases follow the signed-in account; Haiku takes no effort level.
173
+ const provider = claudeProvider(process.env.ANTHROPIC_BASE_URL);
165
174
  return [
166
- streamJsonModel(profile, DEFAULT_MODEL, "Default", { reasoning: true, isDefault: true }),
167
- streamJsonModel(profile, "opus", "Claude Opus", { reasoning: true }),
168
- streamJsonModel(profile, "sonnet", "Claude Sonnet", { reasoning: true }),
169
- streamJsonModel(profile, "haiku", "Claude Haiku", { reasoning: false }),
175
+ streamJsonModel(profile, DEFAULT_MODEL, "Default", { reasoning: true, isDefault: true, provider }),
176
+ streamJsonModel(profile, "opus", "Claude Opus", { reasoning: true, provider }),
177
+ streamJsonModel(profile, "sonnet", "Claude Sonnet", { reasoning: true, provider }),
178
+ streamJsonModel(profile, "haiku", "Claude Haiku", { reasoning: false, provider }),
170
179
  ];
171
180
  },
172
181
  approvalModes: probeApprovalModes,
@@ -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.21.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.12.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",