gipity 1.1.11 → 1.1.13

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/README.md CHANGED
@@ -23,7 +23,7 @@ irm https://gipity.ai/install.ps1 | iex
23
23
  | You want to... | Run |
24
24
  |----------------|-----|
25
25
  | Start building right now, from anywhere | `gipity build` |
26
- | Use your own workflow in your own directory | `gipity init`, then `claude` / `codex` / `grok` |
26
+ | Use your own workflow in your own directory | `gipity init`, then `claude` / `codex` / `grok` / `opencode` |
27
27
  | Drive this computer from gipity.ai (phone, browser) | `gipity connect` |
28
28
 
29
29
  ### `gipity build` - start from anywhere
@@ -40,7 +40,7 @@ Prefer launching your agent yourself? From any project directory:
40
40
 
41
41
  ```bash
42
42
  gipity init
43
- claude # or codex, or grok - whatever you use
43
+ claude # or codex, grok, or opencode - whatever you use
44
44
  ```
45
45
 
46
46
  `init` links the directory to a Gipity project, writes CLAUDE.md/AGENTS.md primers so your agent understands Gipity, and installs the Gipity skills + file-sync hooks into the agent CLIs found on your machine (Claude Code, Codex, Grok; Cursor and Gemini get primer files too).
@@ -126,7 +126,7 @@ gipity login --email you@example.com
126
126
  gipity login --code 123456
127
127
  cd my-project
128
128
  gipity init
129
- claude # or codex, or grok
129
+ claude # or codex, grok, or opencode
130
130
  ```
131
131
 
132
132
  ## Coding Agent Integration
package/dist/adopt-cwd.js CHANGED
@@ -17,7 +17,6 @@ import { get, post, ApiError } from './api.js';
17
17
  import { isSyncIgnored } from './setup.js';
18
18
  import { finalizeLocalProject } from './project-setup.js';
19
19
  import { getProjectsRoot } from './relay/paths.js';
20
- import * as relayState from './relay/state.js';
21
20
  const EASY_FILES = 200;
22
21
  const EASY_BYTES = 100 * 1024 * 1024; // 100 MB
23
22
  const REFUSE_FILES = 2000;
@@ -210,15 +209,15 @@ export async function adoptCurrentDir(opts) {
210
209
  }
211
210
  let isNew = false;
212
211
  if (!project) {
213
- const device = relayState.getDevice();
212
+ // No autoChat: which agent will run here isn't known (init wires them
213
+ // all up; build's picker runs later), so a pre-created chat would guess
214
+ // `claude_code` and sit empty forever when another agent is used. The
215
+ // first captured session creates/reuses a conversation with the right
216
+ // source via the launch path or the capture runner's self-arm resolve.
214
217
  const body = {
215
218
  name: opts.projectName,
216
219
  slug: opts.projectSlug,
217
220
  };
218
- if (device) {
219
- body.autoChat = 'claude_code';
220
- body.deviceGuid = device.guid;
221
- }
222
221
  try {
223
222
  const res = await post('/projects', body);
224
223
  project = res.data;
@@ -2,12 +2,14 @@ import { claudeCodeAdapter } from './claude-code.js';
2
2
  import { codexAdapter } from './codex.js';
3
3
  import { grokAdapter } from './grok.js';
4
4
  import { agyAdapter } from './agy.js';
5
+ import { opencodeAdapter } from './opencode.js';
5
6
  /** Picker/help order: Claude first (the default), then the others. */
6
7
  export const AGENT_ADAPTERS = [
7
8
  claudeCodeAdapter,
8
9
  codexAdapter,
9
10
  grokAdapter,
10
11
  agyAdapter,
12
+ opencodeAdapter,
11
13
  ];
12
14
  export const AGENT_KEYS = AGENT_ADAPTERS.map(a => a.key);
13
15
  export function getAdapter(key) {
@@ -0,0 +1,143 @@
1
+ /**
2
+ * opencode adapter (opencode.ai, Anomaly - vanilla opencode, never a fork).
3
+ * Flag surface per the opencode 1.18.x CLI docs: `opencode run [message..]`
4
+ * for headless one-shots with `--model provider/model`, `--session <id>` to
5
+ * continue, `--auto` to auto-approve permissions, `--format json`.
6
+ *
7
+ * Models: the Gipity opencode plugin registers a "gipity" provider - the
8
+ * curated open coding models (DeepSeek / Qwen / Kimi / GLM families) billed
9
+ * via the user's Gipity credits through the platform's serving path. A
10
+ * `--model` value with no provider prefix (a Gipity id or family alias like
11
+ * `deepseek`) is therefore namespaced to `gipity/…` here; opencode-native
12
+ * refs (`anthropic/…`, `openrouter/…`) pass through for BYO-key users.
13
+ *
14
+ * Capture: opencode fires no Claude-format hooks, but it loads plugins in
15
+ * every mode (TUI, `run`, serve). The Gipity plugin mirrors sessions itself -
16
+ * on session.idle it writes a normalized transcript to
17
+ * ~/.gipity/opencode/transcripts/<session_id>.jsonl and invokes the capture
18
+ * runner (`capture.cjs opencode stop`), riding the same ingest spine as every
19
+ * other agent. No launcher-driven replay hack needed (that path exists for
20
+ * Grok because grok -p fires nothing; opencode's plugin bus fires everywhere).
21
+ */
22
+ import { homedir } from 'os';
23
+ import { join } from 'path';
24
+ import { hasEnvPrefix } from './types.js';
25
+ import { planForInstall, whichFirst } from './self-update.js';
26
+ import { parseTranscript as parseOpencodeTranscript } from '../capture/sources/opencode.js';
27
+ import { OPENCODE_PACKAGE, ensureOpencodeInstalled, ensureOpencodePluginInstalled, ensureOpencodeModelToken, opencodePluginState, removeOpencodePlugin, } from '../opencode-setup.js';
28
+ import { ensureOpencodeSkillsInstalled, removeAgentSkills } from '../setup.js';
29
+ /** opencode's own built-in provider namespaces. A --model whose first segment
30
+ * is one of these is an opencode-native ref (BYO key) and passes through;
31
+ * anything else is treated as a Gipity model id/alias and namespaced to the
32
+ * plugin's "gipity" provider. */
33
+ const OPENCODE_NATIVE_PROVIDERS = new Set([
34
+ 'gipity', 'anthropic', 'openai', 'google', 'openrouter', 'xai', 'groq',
35
+ 'mistral', 'azure', 'amazon-bedrock', 'github-copilot', 'opencode',
36
+ ]);
37
+ function toOpencodeModel(model) {
38
+ const head = model.split('/', 1)[0];
39
+ return OPENCODE_NATIVE_PROVIDERS.has(head) ? model : `gipity/${model}`;
40
+ }
41
+ export const opencodeAdapter = {
42
+ key: 'opencode',
43
+ source: 'opencode',
44
+ harness: 'opencode',
45
+ displayName: 'opencode',
46
+ providerName: 'Anomaly',
47
+ binary: 'opencode',
48
+ buildInteractiveArgs({ resume, model }) {
49
+ const args = [];
50
+ if (model)
51
+ args.push('--model', toOpencodeModel(model));
52
+ if (resume)
53
+ args.push('--session', resume);
54
+ return args;
55
+ },
56
+ buildHeadlessArgs({ message, resume, model, bypassApprovals, jsonStream }) {
57
+ const args = ['run', message];
58
+ if (model)
59
+ args.push('--model', toOpencodeModel(model));
60
+ if (resume)
61
+ args.push('--session', resume);
62
+ if (bypassApprovals)
63
+ args.push('--auto');
64
+ if (jsonStream)
65
+ args.push('--format', 'json');
66
+ return args;
67
+ },
68
+ sessionIdFromStreamEvent(event) {
69
+ // `opencode run --format json` emits bus events; session ids ride
70
+ // properties.sessionID (message/part events) or properties.info.id
71
+ // (session.created/updated).
72
+ const fromProps = event?.properties?.sessionID;
73
+ if (typeof fromProps === 'string' && fromProps)
74
+ return fromProps;
75
+ const fromInfo = event?.properties?.info?.id;
76
+ if (typeof fromInfo === 'string' && fromInfo.startsWith('ses'))
77
+ return fromInfo;
78
+ return null;
79
+ },
80
+ hooksSupportedOnPlatform() {
81
+ return true; // plugin-based capture; no OS-specific hook files
82
+ },
83
+ daemonStreamCapture: false,
84
+ ensureInstalled() {
85
+ return ensureOpencodeInstalled();
86
+ },
87
+ // Plain literal, not `npm install -g ${OPENCODE_PACKAGE}`: this module sits
88
+ // in an import cycle (opencode.ts -> opencode-setup.ts -> setup.ts -> ...
89
+ // -> agents/index.ts -> opencode.ts), so a module-eval read of an imported
90
+ // binding hits the TDZ when the cycle is entered from setup.ts's side.
91
+ // Function bodies (updatePlan below) read the live binding safely.
92
+ installHint: 'npm install -g opencode-ai (or: curl -fsSL https://opencode.ai/install | bash)',
93
+ updatePlan() {
94
+ // Same-channel rule: npm-global installs update via npm; anything else
95
+ // (the curl installer) gets opencode's own `opencode upgrade`.
96
+ return planForInstall(whichFirst('opencode'), OPENCODE_PACKAGE, ['opencode', 'upgrade']);
97
+ },
98
+ async prepareLaunch() {
99
+ // The model slot needs a long-lived token before opencode starts (the
100
+ // plugin reads it at provider-auth time). Mint/refresh is a no-op when
101
+ // one is already valid.
102
+ await ensureOpencodeModelToken();
103
+ },
104
+ detectEnv() {
105
+ // The Gipity plugin injects OPENCODE_SESSION_ID into every shell opencode
106
+ // spawns (shell.env hook); opencode itself may leak other OPENCODE_* vars.
107
+ if (!hasEnvPrefix('OPENCODE'))
108
+ return null;
109
+ return { harness: 'opencode', harnessSession: process.env.OPENCODE_SESSION_ID };
110
+ },
111
+ capture: {
112
+ hookKey: 'opencode',
113
+ parse: (content, afterUuid) => parseOpencodeTranscript(content, afterUuid),
114
+ // The plugin writes the transcript at a derivable path, so a hook payload
115
+ // without transcript_path still resolves.
116
+ resolveTranscriptPath: (hook) => {
117
+ if (!hook.session_id)
118
+ return null;
119
+ const gipityDir = process.env.GIPITY_DIR || join(homedir(), '.gipity');
120
+ return join(gipityDir, 'opencode', 'transcripts', `${hook.session_id}.jsonl`);
121
+ },
122
+ },
123
+ setup: {
124
+ state: () => opencodePluginState(),
125
+ install: () => {
126
+ ensureOpencodeSkillsInstalled();
127
+ ensureOpencodePluginInstalled();
128
+ },
129
+ uninstall: () => {
130
+ const removedPlugin = removeOpencodePlugin();
131
+ const n = removeAgentSkills();
132
+ if (!removedPlugin && !n)
133
+ return null;
134
+ const parts = [];
135
+ if (removedPlugin)
136
+ parts.push('Gipity plugin removed from opencode.');
137
+ if (n)
138
+ parts.push(`Removed ${n} Gipity skills from ~/.agents/skills.`);
139
+ return parts.join(' ');
140
+ },
141
+ },
142
+ };
143
+ //# sourceMappingURL=opencode.js.map
package/dist/api.js CHANGED
@@ -25,6 +25,15 @@ export class ApiError extends Error {
25
25
  // the time-to-first-byte here and an idle watchdog in sync.ts guards the body.
26
26
  const REQUEST_TIMEOUT_MS = 60_000;
27
27
  const DOWNLOAD_HEADER_TIMEOUT_MS = 30_000;
28
+ // Media generation (music/video/image/speech, `service call` POSTs) can
29
+ // legitimately run minutes in ONE request/response: a GPU-backed music model
30
+ // waking from scale-to-zero spends 1-3 min booting + loading weights before it
31
+ // renders a note, and Veo video runs 30-120s. The server bounds all of these at
32
+ // 300s (its provider fetch budget and the ALB idle timeout are both 300s), so
33
+ // the long-call cap sits just above that ceiling - the server's clearer error
34
+ // always arrives before the CLI gives up. Callers opt in per request; plain
35
+ // JSON calls keep the tight default so a wedged connection still fails fast.
36
+ export const LONG_REQUEST_TIMEOUT_MS = 310_000;
28
37
  /** fetch() that rejects with a clean 408 ApiError if the whole exchange (headers
29
38
  * + body) doesn't complete within timeoutMs, instead of hanging forever. For
30
39
  * request/response JSON calls only - never wrap a long streaming body in this. */
@@ -111,16 +120,16 @@ export async function getAuthHeader() {
111
120
  const headers = await getHeaders();
112
121
  return headers.Authorization;
113
122
  }
114
- async function request(method, path, body, retrying = false) {
123
+ async function request(method, path, body, retrying = false, timeoutMs = REQUEST_TIMEOUT_MS) {
115
124
  const headers = await getHeaders();
116
125
  const url = `${baseUrl()}${path}`;
117
126
  const res = await fetchWithTimeout(url, {
118
127
  method,
119
128
  headers,
120
129
  body: body ? JSON.stringify(body) : undefined,
121
- }, REQUEST_TIMEOUT_MS, `${method} ${path}`);
130
+ }, timeoutMs, `${method} ${path}`);
122
131
  if (await shouldRetryAfter401(res.status, retrying)) {
123
- return request(method, path, body, true);
132
+ return request(method, path, body, true, timeoutMs);
124
133
  }
125
134
  if (!res.ok) {
126
135
  const json = await res.json().catch(() => ({ error: { code: 'UNKNOWN', message: res.statusText } }));
@@ -132,8 +141,8 @@ async function request(method, path, body, retrying = false) {
132
141
  export function get(path) {
133
142
  return request('GET', path);
134
143
  }
135
- export function post(path, body) {
136
- return request('POST', path, body);
144
+ export function post(path, body, opts) {
145
+ return request('POST', path, body, false, opts?.timeoutMs);
137
146
  }
138
147
  /** POST JSON and consume the response as a tar stream, returning each entry as
139
148
  * { name, buffer } in arrival order. Non-2xx responses are parsed as JSON errors. */
@@ -176,6 +176,16 @@ export function parseTranscript(content, afterUuid) {
176
176
  // whole file (including pre-watermark lines) so a result whose tool_use
177
177
  // was forwarded in an earlier sweep still resolves its name.
178
178
  const toolNames = new Map();
179
+ // Token totals for the newly parsed range. Claude Code splits one API
180
+ // response across several transcript lines (one per content block), each
181
+ // repeating the same `message.usage`, so count each `message.id` once.
182
+ // tokens_in is the full input side (fresh + cache-read + cache-creation)
183
+ // to match the relay result footer's semantics; the per-entry input_tokens
184
+ // stays fresh-input-only, which is why summing entries can't replace this.
185
+ const countedUsage = new Set();
186
+ let tokensIn = 0;
187
+ let tokensOut = 0;
188
+ const num = (v) => (typeof v === 'number' && v > 0 ? v : 0);
179
189
  for (const raw of content.split('\n')) {
180
190
  const line = raw.trim();
181
191
  if (!line)
@@ -201,6 +211,18 @@ export function parseTranscript(content, afterUuid) {
201
211
  seenWatermark = true;
202
212
  continue;
203
213
  }
214
+ // Usage is counted independently of entry emission: an assistant line
215
+ // whose content produced no entries still carries real token usage.
216
+ if (parsed?.type === 'assistant' && parsed?.isSidechain !== true) {
217
+ const m = parsed.message;
218
+ const u = m?.usage;
219
+ const key = typeof m?.id === 'string' && m.id ? m.id : parsed.uuid;
220
+ if (u && typeof key === 'string' && !countedUsage.has(key)) {
221
+ countedUsage.add(key);
222
+ tokensIn += num(u.input_tokens) + num(u.cache_read_input_tokens) + num(u.cache_creation_input_tokens);
223
+ tokensOut += num(u.output_tokens);
224
+ }
225
+ }
204
226
  const entries = transcriptLineToEntries(parsed, toolNames);
205
227
  if (entries.length) {
206
228
  for (const e of entries)
@@ -218,6 +240,7 @@ export function parseTranscript(content, afterUuid) {
218
240
  entries: out,
219
241
  lastUuid,
220
242
  foundWatermark: seenWatermark,
243
+ usage: { tokensIn, tokensOut },
221
244
  };
222
245
  }
223
246
  //# sourceMappingURL=claude-code.js.map
@@ -149,6 +149,19 @@ function lineToEntries(parsed, sessionId, idx, toolNames) {
149
149
  * *after* the positional watermark `afterUuid`. Same contract as the
150
150
  * claude-code parser: returns entries in order, the new watermark, and
151
151
  * whether the old watermark was still valid for this file. */
152
+ /** Cumulative token totals from a `token_count` event_msg, or null. The
153
+ * rollout's `info.total_token_usage` is the session running total and its
154
+ * `input_tokens` already includes cached input (verified against real
155
+ * rollouts: total_tokens = input_tokens + output_tokens), so range usage is
156
+ * a plain delta of totals - never a sum over events, which would re-count
157
+ * the whole session on every event. */
158
+ function tokenTotals(payload) {
159
+ const t = payload?.info?.total_token_usage;
160
+ if (!t || typeof t !== 'object')
161
+ return null;
162
+ const num = (v) => (typeof v === 'number' && v > 0 ? v : 0);
163
+ return { input: num(t.input_tokens), output: num(t.output_tokens) };
164
+ }
152
165
  export function parseTranscript(content, afterUuid) {
153
166
  const lines = content.split('\n');
154
167
  // The session id lives in the first session_meta line. Without it we can
@@ -180,6 +193,10 @@ export function parseTranscript(content, afterUuid) {
180
193
  const out = [];
181
194
  const toolNames = new Map();
182
195
  let lastIdx = startAfter;
196
+ // Cumulative token totals at the watermark (baseline) and at the end of
197
+ // the parsed range - their delta is this range's usage.
198
+ let baseUsage = null;
199
+ let lastUsage = null;
183
200
  for (let i = 0; i < lines.length; i++) {
184
201
  const line = lines[i].trim();
185
202
  if (!line)
@@ -191,17 +208,23 @@ export function parseTranscript(content, afterUuid) {
191
208
  catch {
192
209
  continue;
193
210
  }
211
+ const isTokenCount = parsed?.type === 'event_msg' && parsed?.payload?.type === 'token_count';
194
212
  if (startAfter !== null && i <= startAfter) {
195
213
  // Pre-watermark: record tool names only, so a post-watermark
196
- // tool_result still resolves the name of an already-forwarded call.
214
+ // tool_result still resolves the name of an already-forwarded call
215
+ // (and the running token total, so the range delta starts right).
197
216
  const p = parsed?.payload;
198
217
  if (parsed?.type === 'response_item' && p &&
199
218
  (p.type === 'custom_tool_call' || p.type === 'function_call') &&
200
219
  typeof p.call_id === 'string') {
201
220
  toolNames.set(p.call_id, typeof p.name === 'string' && p.name ? p.name : 'tool');
202
221
  }
222
+ if (isTokenCount)
223
+ baseUsage = tokenTotals(parsed.payload) ?? baseUsage;
203
224
  continue;
204
225
  }
226
+ if (isTokenCount)
227
+ lastUsage = tokenTotals(parsed.payload) ?? lastUsage;
205
228
  const entries = lineToEntries(parsed, sessionId, i, toolNames);
206
229
  for (const e of entries)
207
230
  out.push(e);
@@ -211,6 +234,12 @@ export function parseTranscript(content, afterUuid) {
211
234
  entries: out,
212
235
  lastUuid: lastIdx === null ? afterUuid : positional(sessionId, lastIdx),
213
236
  foundWatermark,
237
+ usage: lastUsage === null
238
+ ? { tokensIn: 0, tokensOut: 0 }
239
+ : {
240
+ tokensIn: Math.max(0, lastUsage.input - (baseUsage?.input ?? 0)),
241
+ tokensOut: Math.max(0, lastUsage.output - (baseUsage?.output ?? 0)),
242
+ },
214
243
  };
215
244
  }
216
245
  //# sourceMappingURL=codex.js.map
@@ -0,0 +1,156 @@
1
+ /**
2
+ * opencode transcript JSONL → ingest entries.
3
+ *
4
+ * opencode does not write a single transcript file itself - it persists
5
+ * sessions as per-message JSON blobs in its own storage dir. The Gipity
6
+ * opencode plugin (installed to ~/.config/opencode/plugins/gipity.js by
7
+ * `gipity` setup, shipped in the GipityAI/skills repo) bridges that gap: on
8
+ * every `session.idle` it fetches the full message list over the opencode
9
+ * server SDK and rewrites
10
+ * ~/.gipity/opencode/transcripts/<session_id>.jsonl
11
+ * with one line per message, then invokes the capture runner (`capture.cjs
12
+ * opencode stop`). Line shape (SDK types, opencode 1.18.x):
13
+ *
14
+ * { info: UserMessage | AssistantMessage, parts: Part[] }
15
+ *
16
+ * info.role 'user' → prompt entry (joined text parts; synthetic parts
17
+ * are plugin/system injections and are skipped)
18
+ * info.role 'assistant' → assistant entry (text, tokens, modelID, finish)
19
+ * + tool_use per tool part (stable `callID`)
20
+ * + tool_result per completed/errored tool part
21
+ * reasoning / step-start / step-finish / file / snapshot parts → SKIP
22
+ *
23
+ * Dedup/watermark: message ids (`msg_…`) are stable and ordered, so the
24
+ * watermark is the last message id emitted. The file is fully rewritten each
25
+ * idle; a watermark that no longer appears (deleted/forked session) makes the
26
+ * caller replay from the top, and the server's source_uuid unique index
27
+ * collapses anything already forwarded. tool_use/tool_result key off the
28
+ * stable `callID`, which survives rewrites.
29
+ */
30
+ function toIso(ms) {
31
+ return typeof ms === 'number' && ms > 0 ? new Date(ms).toISOString() : undefined;
32
+ }
33
+ function joinTextParts(parts) {
34
+ const out = [];
35
+ for (const p of parts) {
36
+ if (p?.type === 'text' && typeof p.text === 'string' && !p.synthetic && !p.ignored) {
37
+ out.push(p.text);
38
+ }
39
+ }
40
+ return out.join('\n');
41
+ }
42
+ function messageToEntries(info, parts) {
43
+ if (!info || typeof info.id !== 'string')
44
+ return [];
45
+ const ts = toIso(info?.time?.created);
46
+ if (info.role === 'user') {
47
+ const prompt = joinTextParts(parts);
48
+ if (!prompt)
49
+ return [];
50
+ return [{ kind: 'prompt', prompt, source_uuid: info.id, ...(ts ? { ts } : {}) }];
51
+ }
52
+ if (info.role === 'assistant') {
53
+ const out = [];
54
+ const text = joinTextParts(parts);
55
+ const toolParts = parts.filter((p) => p?.type === 'tool' && typeof p.callID === 'string' && p.callID);
56
+ if (text || toolParts.length) {
57
+ out.push({
58
+ kind: 'assistant',
59
+ text,
60
+ blocks: text ? [{ type: 'text', text }] : [],
61
+ ...(typeof info?.tokens?.input === 'number' ? { input_tokens: info.tokens.input } : {}),
62
+ ...(typeof info?.tokens?.output === 'number' ? { output_tokens: info.tokens.output } : {}),
63
+ ...(typeof info.modelID === 'string' ? { model: info.modelID } : {}),
64
+ ...(typeof info.finish === 'string' ? { stop_reason: info.finish } : {}),
65
+ source_uuid: info.id,
66
+ ...(ts ? { ts } : {}),
67
+ });
68
+ }
69
+ for (const p of toolParts) {
70
+ const toolName = typeof p.tool === 'string' && p.tool ? p.tool : 'tool';
71
+ out.push({
72
+ kind: 'tool_use',
73
+ tool_use_id: p.callID,
74
+ tool_name: toolName,
75
+ tool_input: p?.state?.input ?? null,
76
+ source_uuid: p.callID,
77
+ });
78
+ const status = p?.state?.status;
79
+ if (status === 'completed' || status === 'error') {
80
+ out.push({
81
+ kind: 'tool_result',
82
+ tool_use_id: p.callID,
83
+ tool_name: toolName,
84
+ content: status === 'error' ? (p.state.error ?? '') : (p.state.output ?? ''),
85
+ ...(status === 'error' ? { is_error: true } : {}),
86
+ source_uuid: `${p.callID}#out`,
87
+ });
88
+ }
89
+ }
90
+ return out;
91
+ }
92
+ return [];
93
+ }
94
+ /** Parse the plugin-written transcript JSONL and emit every ingest entry that
95
+ * comes *after* the message-id watermark `afterUuid`. Same contract as the
96
+ * claude-code parser. */
97
+ export function parseTranscript(content, afterUuid) {
98
+ const lines = content.split('\n');
99
+ // First pass: locate the watermark message so a rewind/fork (id gone)
100
+ // replays from the top instead of wedging capture.
101
+ let watermarkLine = -1;
102
+ if (afterUuid) {
103
+ for (let i = 0; i < lines.length; i++) {
104
+ const line = lines[i].trim();
105
+ if (!line)
106
+ continue;
107
+ try {
108
+ if (JSON.parse(line)?.info?.id === afterUuid) {
109
+ watermarkLine = i;
110
+ break;
111
+ }
112
+ }
113
+ catch { /* skip unparseable */ }
114
+ }
115
+ }
116
+ const foundWatermark = afterUuid === null || watermarkLine !== -1;
117
+ const out = [];
118
+ let lastUuid = foundWatermark ? afterUuid : null;
119
+ // Token totals for the newly parsed range. tokens_in is the full input side
120
+ // (fresh input + cache read/write) to match the relay result footer's
121
+ // semantics; the per-entry input_tokens stays `tokens.input` only.
122
+ let tokensIn = 0;
123
+ let tokensOut = 0;
124
+ const num = (v) => (typeof v === 'number' && v > 0 ? v : 0);
125
+ for (let i = 0; i < lines.length; i++) {
126
+ if (watermarkLine !== -1 && i <= watermarkLine)
127
+ continue;
128
+ const line = lines[i].trim();
129
+ if (!line)
130
+ continue;
131
+ let parsed;
132
+ try {
133
+ parsed = JSON.parse(line);
134
+ }
135
+ catch {
136
+ continue;
137
+ }
138
+ const info = parsed?.info;
139
+ const entries = messageToEntries(info, Array.isArray(parsed?.parts) ? parsed.parts : []);
140
+ if (!entries.length)
141
+ continue;
142
+ // Count usage only for lines that emit entries: entry-less lines don't
143
+ // advance the watermark, so counting them would re-add their tokens on
144
+ // every subsequent flush.
145
+ if (info?.role === 'assistant' && info?.tokens) {
146
+ tokensIn += num(info.tokens.input) + num(info.tokens.cache?.read) + num(info.tokens.cache?.write);
147
+ tokensOut += num(info.tokens.output);
148
+ }
149
+ for (const e of entries)
150
+ out.push(e);
151
+ if (typeof info?.id === 'string')
152
+ lastUuid = info.id;
153
+ }
154
+ return { entries: out, lastUuid, foundWatermark, usage: { tokensIn, tokensOut } };
155
+ }
156
+ //# sourceMappingURL=opencode.js.map
@@ -34,12 +34,12 @@ export const agentCommand = new Command('agent')
34
34
  }));
35
35
  agentCommand
36
36
  .command('models')
37
- .description('List the LLM models an agent can use (ids for `agent create --model` and `agent set model`)')
37
+ .description('List the LLM models an agent can use (ids and tier aliases for `agent create --model` and `agent set model`)')
38
38
  .option('--json', 'Output as JSON')
39
39
  .action((opts) => run('Models', async () => {
40
40
  const res = await get('/agents/models');
41
41
  if (opts.json) {
42
- console.log(JSON.stringify(res.data));
42
+ console.log(JSON.stringify({ models: res.data, aliases: res.aliases ?? {} }));
43
43
  return;
44
44
  }
45
45
  const width = res.data.reduce((m, x) => Math.max(m, x.id.length), 0);
@@ -56,11 +56,21 @@ agentCommand
56
56
  notes.push('default');
57
57
  console.log(`${m.id.padEnd(width)} ${muted(notes.join(' · '))}`);
58
58
  }
59
+ // Tier aliases (older servers don't send them): an id pins that exact
60
+ // model; an alias follows the platform's rotation as new models ship.
61
+ if (res.aliases && Object.keys(res.aliases).length > 0) {
62
+ console.log('');
63
+ console.log('Tier aliases (an agent set to one follows the platform model rotations):');
64
+ const aw = Object.keys(res.aliases).reduce((m, k) => Math.max(m, k.length), 0);
65
+ for (const [alias, id] of Object.entries(res.aliases)) {
66
+ console.log(`${alias.padEnd(aw)} ${muted(`-> ${id}`)}`);
67
+ }
68
+ }
59
69
  }));
60
70
  agentCommand
61
71
  .command('create <name>')
62
72
  .description('Create an agent')
63
- .option('--model <model>', 'Model preference (an id from `gipity agent models`; default: platform default)')
73
+ .option('--model <model>', 'Model id (pins that model) or tier alias like gipity-default/opus (follows rotations) - see `gipity agent models`. Default: gipity-default')
64
74
  .option('--switch', 'Switch to new agent after creation')
65
75
  .option('--json', 'Output as JSON')
66
76
  .action((name, opts) => run('Create', async () => {
@@ -83,7 +93,7 @@ agentCommand
83
93
  }));
84
94
  agentCommand
85
95
  .command('set <field> <value>')
86
- .description('Set a field (model, temp). Model ids: `gipity agent models`')
96
+ .description('Set a field (model, temp). Model ids + tier aliases: `gipity agent models`')
87
97
  .option('--json', 'Output as JSON')
88
98
  .action((field, value, opts) => run('Set', async () => {
89
99
  const config = requireConfig();
@@ -1127,6 +1127,14 @@ async function launchNonClaudeAgent(adapter, ctx) {
1127
1127
  console.log('');
1128
1128
  }
1129
1129
  // ── Spawn ───────────────────────────────────────────────────────────────
1130
+ // Async pre-spawn setup (e.g. opencode's model-slot token mint). Best-effort:
1131
+ // the agent must still launch when offline or logged out.
1132
+ if (adapter.prepareLaunch) {
1133
+ try {
1134
+ await adapter.prepareLaunch();
1135
+ }
1136
+ catch { /* never block the launch */ }
1137
+ }
1130
1138
  const childEnv = { ...process.env };
1131
1139
  if (convGuid)
1132
1140
  childEnv.GIPITY_CONVERSATION_GUID = convGuid;
@@ -1387,12 +1395,12 @@ async function createNewProject(existingSlugs, preset) {
1387
1395
  continue;
1388
1396
  }
1389
1397
  try {
1390
- const device = relayState.getDevice();
1398
+ // No autoChat here: the agent isn't chosen yet (the picker runs after
1399
+ // project setup), so a pre-created chat would guess `claude_code` and
1400
+ // sit empty forever whenever the user picks another agent. The launch
1401
+ // path creates (or the placeholder-reuse logic finds) the conversation
1402
+ // with the RIGHT source moments later.
1391
1403
  const body = { name: projectName, slug: projectSlug };
1392
- if (device) {
1393
- body.autoChat = 'claude_code';
1394
- body.deviceGuid = device.guid;
1395
- }
1396
1404
  const res = await post('/projects', body);
1397
1405
  // Single console.log keeps the line on the headless stderr stream -
1398
1406
  // process.stdout.write would leak the message onto the child's stdout.